Merge branch 'MDL-37563-23' of git://github.com/damyon/moodle into MOODLE_23_STABLE
[moodle.git] / grade / report / grader / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Definition of the grader report class
19  *
20  * @package   gradereport_grader
21  * @copyright 2007 Nicolas Connault
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 require_once($CFG->dirroot . '/grade/report/lib.php');
26 require_once($CFG->libdir.'/tablelib.php');
28 /**
29  * Class providing an API for the grader report building and displaying.
30  * @uses grade_report
31  * @package gradereport_grader
32  */
33 class grade_report_grader extends grade_report {
34     /**
35      * The final grades.
36      * @var array $grades
37      */
38     public $grades;
40     /**
41      * Array of errors for bulk grades updating.
42      * @var array $gradeserror
43      */
44     public $gradeserror = array();
46 //// SQL-RELATED
48     /**
49      * The id of the grade_item by which this report will be sorted.
50      * @var int $sortitemid
51      */
52     public $sortitemid;
54     /**
55      * Sortorder used in the SQL selections.
56      * @var int $sortorder
57      */
58     public $sortorder;
60     /**
61      * An SQL fragment affecting the search for users.
62      * @var string $userselect
63      */
64     public $userselect;
66     /**
67      * The bound params for $userselect
68      * @var array $userselectparams
69      */
70     public $userselectparams = array();
72     /**
73      * List of collapsed categories from user preference
74      * @var array $collapsed
75      */
76     public $collapsed;
78     /**
79      * A count of the rows, used for css classes.
80      * @var int $rowcount
81      */
82     public $rowcount = 0;
84     /**
85      * Capability check caching
86      * */
87     public $canviewhidden;
89     var $preferencespage=false;
91     /**
92      * Length at which feedback will be truncated (to the nearest word) and an ellipsis be added.
93      * TODO replace this by a report preference
94      * @var int $feedback_trunc_length
95      */
96     protected $feedback_trunc_length = 50;
98     /**
99      * Constructor. Sets local copies of user preferences and initialises grade_tree.
100      * @param int $courseid
101      * @param object $gpr grade plugin return tracking object
102      * @param string $context
103      * @param int $page The current page being viewed (when report is paged)
104      * @param int $sortitemid The id of the grade_item by which to sort the table
105      */
106     public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) {
107         global $CFG;
108         parent::__construct($courseid, $gpr, $context, $page);
110         $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->course->id));
112         // load collapsed settings for this report
113         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
114             $this->collapsed = unserialize($collapsed);
115         } else {
116             $this->collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
117         }
119         if (empty($CFG->enableoutcomes)) {
120             $nooutcomes = false;
121         } else {
122             $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
123         }
125         // if user report preference set or site report setting set use it, otherwise use course or site setting
126         $switch = $this->get_pref('aggregationposition');
127         if ($switch == '') {
128             $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
129         }
131         // Grab the grade_tree for this course
132         $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
134         $this->sortitemid = $sortitemid;
136         // base url for sorting by first/last name
138         $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
140         $studentsperpage = $this->get_students_per_page();
141         if (!empty($this->page) && !empty($studentsperpage)) {
142             $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
143         }
145         $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid));
147         $this->setup_groups();
149         $this->setup_sortitemid();
150     }
152     /**
153      * Processes the data sent by the form (grades and feedbacks).
154      * Caller is responsible for all access control checks
155      * @param array $data form submission (with magic quotes)
156      * @return array empty array if success, array of warnings if something fails.
157      */
158     public function process_data($data) {
159         global $DB;
160         $warnings = array();
162         $separategroups = false;
163         $mygroups       = array();
164         if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
165             $separategroups = true;
166             $mygroups = groups_get_user_groups($this->course->id);
167             $mygroups = $mygroups[0]; // ignore groupings
168             // reorder the groups fro better perf below
169             $current = array_search($this->currentgroup, $mygroups);
170             if ($current !== false) {
171                 unset($mygroups[$current]);
172                 array_unshift($mygroups, $this->currentgroup);
173             }
174         }
176         // always initialize all arrays
177         $queue = array();
178         $this->load_users();
179         $this->load_final_grades();
181         // Were any changes made?
182         $changedgrades = false;
184         foreach ($data as $varname => $students) {
186             $needsupdate = false;
188             // skip, not a grade nor feedback
189             if (strpos($varname, 'grade') === 0) {
190                 $datatype = 'grade';
191             } else if (strpos($varname, 'feedback') === 0) {
192                 $datatype = 'feedback';
193             } else {
194                 continue;
195             }
197             foreach ($students as $userid => $items) {
198                 $userid = clean_param($userid, PARAM_INT);
199                 foreach ($items as $itemid => $postedvalue) {
200                     $itemid = clean_param($itemid, PARAM_INT);
202                     // Was change requested?
203                     $oldvalue = $this->grades[$userid][$itemid];
204                     if ($datatype === 'grade') {
205                         // If there was no grade and there still isn't
206                         if (is_null($oldvalue->finalgrade) && $postedvalue == -1) {
207                             // -1 means no grade
208                             continue;
209                         }
211                         // If the grade item uses a custom scale
212                         if (!empty($oldvalue->grade_item->scaleid)) {
214                             if ((int)$oldvalue->finalgrade === (int)$postedvalue) {
215                                 continue;
216                             }
217                         } else {
218                             // The grade item uses a numeric scale
220                             // Format the finalgrade from the DB so that it matches the grade from the client
221                             if ($postedvalue === format_float($oldvalue->finalgrade, $oldvalue->grade_item->get_decimals())) {
222                                 continue;
223                             }
224                         }
226                         $changedgrades = true;
228                     } else if ($datatype === 'feedback') {
229                         if (($oldvalue->feedback === $postedvalue) or ($oldvalue->feedback === NULL and empty($postedvalue))) {
230                             continue;
231                         }
232                     }
234                     if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) {
235                         print_error('invalidgradeitemid');
236                     }
238                     // Pre-process grade
239                     if ($datatype == 'grade') {
240                         $feedback = false;
241                         $feedbackformat = false;
242                         if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
243                             if ($postedvalue == -1) { // -1 means no grade
244                                 $finalgrade = null;
245                             } else {
246                                 $finalgrade = $postedvalue;
247                             }
248                         } else {
249                             $finalgrade = unformat_float($postedvalue);
250                         }
252                         $errorstr = '';
253                         // Warn if the grade is out of bounds.
254                         if (is_null($finalgrade)) {
255                             // ok
256                         } else {
257                             $bounded = $gradeitem->bounded_grade($finalgrade);
258                             if ($bounded > $finalgrade) {
259                             $errorstr = 'lessthanmin';
260                             } else if ($bounded < $finalgrade) {
261                                 $errorstr = 'morethanmax';
262                             }
263                         }
264                         if ($errorstr) {
265                             $user = $DB->get_record('user', array('id' => $userid), 'id, firstname, lastname');
266                             $gradestr = new stdClass();
267                             $gradestr->username = fullname($user);
268                             $gradestr->itemname = $gradeitem->get_name();
269                             $warnings[] = get_string($errorstr, 'grades', $gradestr);
270                         }
272                     } else if ($datatype == 'feedback') {
273                         $finalgrade = false;
274                         $trimmed = trim($postedvalue);
275                         if (empty($trimmed)) {
276                              $feedback = NULL;
277                         } else {
278                              $feedback = $postedvalue;
279                         }
280                     }
282                     // group access control
283                     if ($separategroups) {
284                         // note: we can not use $this->currentgroup because it would fail badly
285                         //       when having two browser windows each with different group
286                         $sharinggroup = false;
287                         foreach($mygroups as $groupid) {
288                             if (groups_is_member($groupid, $userid)) {
289                                 $sharinggroup = true;
290                                 break;
291                             }
292                         }
293                         if (!$sharinggroup) {
294                             // either group membership changed or somebody is hacking grades of other group
295                             $warnings[] = get_string('errorsavegrade', 'grades');
296                             continue;
297                         }
298                     }
300                     $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
302                     // We can update feedback without reloading the grade item as it doesn't affect grade calculations
303                     if ($datatype === 'feedback') {
304                         $this->grades[$userid][$itemid]->feedback = $feedback;
305                     }
306                 }
307             }
308         }
310         if ($changedgrades) {
311             // If a final grade was overriden reload grades so dependent grades like course total will be correct
312             $this->grades = null;
313         }
315         return $warnings;
316     }
319     /**
320      * Setting the sort order, this depends on last state
321      * all this should be in the new table class that we might need to use
322      * for displaying grades.
323      */
324     private function setup_sortitemid() {
326         global $SESSION;
328         if (!isset($SESSION->gradeuserreport)) {
329             $SESSION->gradeuserreport = new stdClass();
330         }
332         if ($this->sortitemid) {
333             if (!isset($SESSION->gradeuserreport->sort)) {
334                 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
335                     $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
336                 } else {
337                     $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
338                 }
339             } else {
340                 // this is the first sort, i.e. by last name
341                 if (!isset($SESSION->gradeuserreport->sortitemid)) {
342                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
343                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
344                     } else {
345                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
346                     }
347                 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
348                     // same as last sort
349                     if ($SESSION->gradeuserreport->sort == 'ASC') {
350                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
351                     } else {
352                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
353                     }
354                 } else {
355                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
356                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
357                     } else {
358                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
359                     }
360                 }
361             }
362             $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
363         } else {
364             // not requesting sort, use last setting (for paging)
366             if (isset($SESSION->gradeuserreport->sortitemid)) {
367                 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
368             }else{
369                 $this->sortitemid = 'lastname';
370             }
372             if (isset($SESSION->gradeuserreport->sort)) {
373                 $this->sortorder = $SESSION->gradeuserreport->sort;
374             } else {
375                 $this->sortorder = 'ASC';
376             }
377         }
378     }
380     /**
381      * pulls out the userids of the users to be display, and sorts them
382      */
383     public function load_users() {
384         global $CFG, $DB;
386         if (!empty($this->users)) {
387             return;
388         }
390         //limit to users with a gradeable role
391         list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
393         //limit to users with an active enrollment
394         list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
396         //fields we need from the user table
397         $userfields = user_picture::fields('u', get_extra_user_fields($this->context));
399         $sortjoin = $sort = $params = null;
401         //if the user has clicked one of the sort asc/desc arrows
402         if (is_numeric($this->sortitemid)) {
403             $params = array_merge(array('gitemid'=>$this->sortitemid), $gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
405             $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
406             $sort = "g.finalgrade $this->sortorder";
408         } else {
409             $sortjoin = '';
410             switch($this->sortitemid) {
411                 case 'lastname':
412                     $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder";
413                     break;
414                 case 'firstname':
415                     $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder";
416                     break;
417                 case 'email':
418                     $sort = "u.email $this->sortorder";
419                     break;
420                 case 'idnumber':
421                 default:
422                     $sort = "u.idnumber $this->sortorder";
423                     break;
424             }
426             $params = array_merge($gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
427         }
429         $sql = "SELECT $userfields
430                   FROM {user} u
431                   JOIN ($enrolledsql) je ON je.id = u.id
432                        $this->groupsql
433                        $sortjoin
434                   JOIN (
435                            SELECT DISTINCT ra.userid
436                              FROM {role_assignments} ra
437                             WHERE ra.roleid IN ($this->gradebookroles)
438                               AND ra.contextid " . get_related_contexts_string($this->context) . "
439                        ) rainner ON rainner.userid = u.id
440                    AND u.deleted = 0
441                    $this->groupwheresql
442               ORDER BY $sort";
444         $studentsperpage = $this->get_students_per_page();
445         $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage);
447         if (empty($this->users)) {
448             $this->userselect = '';
449             $this->users = array();
450             $this->userselect_params = array();
451         } else {
452             list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
453             $this->userselect = "AND g.userid $usql";
454             $this->userselect_params = $uparams;
456             //add a flag to each user indicating whether their enrolment is active
457             $sql = "SELECT ue.userid
458                       FROM {user_enrolments} ue
459                       JOIN {enrol} e ON e.id = ue.enrolid
460                      WHERE ue.userid $usql
461                            AND ue.status = :uestatus
462                            AND e.status = :estatus
463                            AND e.courseid = :courseid
464                   GROUP BY ue.userid";
465             $coursecontext = get_course_context($this->context);
466             $params = array_merge($uparams, array('estatus'=>ENROL_INSTANCE_ENABLED, 'uestatus'=>ENROL_USER_ACTIVE, 'courseid'=>$coursecontext->instanceid));
467             $useractiveenrolments = $DB->get_records_sql($sql, $params);
469             foreach ($this->users as $user) {
470                 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
471             }
472         }
474         return $this->users;
475     }
477     /**
478      * we supply the userids in this query, and get all the grades
479      * pulls out all the grades, this does not need to worry about paging
480      */
481     public function load_final_grades() {
482         global $CFG, $DB;
484         if (!empty($this->grades)) {
485             return;
486         }
488         // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
489         $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
490         $sql = "SELECT g.*
491                   FROM {grade_items} gi,
492                        {grade_grades} g
493                  WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
495         $userids = array_keys($this->users);
498         if ($grades = $DB->get_records_sql($sql, $params)) {
499             foreach ($grades as $graderec) {
500                 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
501                     $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
502                     $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching
503                 }
504             }
505         }
507         // prefil grades that do not exist yet
508         foreach ($userids as $userid) {
509             foreach ($this->gtree->get_items() as $itemid=>$unused) {
510                 if (!isset($this->grades[$userid][$itemid])) {
511                     $this->grades[$userid][$itemid] = new grade_grade();
512                     $this->grades[$userid][$itemid]->itemid = $itemid;
513                     $this->grades[$userid][$itemid]->userid = $userid;
514                     $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching
515                 }
516             }
517         }
518     }
520     /**
521      * Builds and returns a div with on/off toggles.
522      * @return string HTML code
523      */
524     public function get_toggles_html() {
525         global $CFG, $USER, $COURSE, $OUTPUT;
527         $html = '';
528         if ($USER->gradeediting[$this->courseid]) {
529             if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
530                 $html .= $this->print_toggle('eyecons');
531             }
532             if (has_capability('moodle/grade:manage', $this->context)
533              or has_capability('moodle/grade:lock', $this->context)
534              or has_capability('moodle/grade:unlock', $this->context)) {
535                 $html .= $this->print_toggle('locks');
536             }
537             if (has_capability('moodle/grade:manage', $this->context)) {
538                 $html .= $this->print_toggle('quickfeedback');
539             }
541             if (has_capability('moodle/grade:manage', $this->context)) {
542                 $html .= $this->print_toggle('calculations');
543             }
544         }
546         if ($this->canviewhidden) {
547             $html .= $this->print_toggle('averages');
548         }
550         $html .= $this->print_toggle('ranges');
551         if (!empty($CFG->enableoutcomes)) {
552             $html .= $this->print_toggle('nooutcomes');
553         }
555         return $OUTPUT->container($html, 'grade-report-toggles');
556     }
558     /**
559     * Shortcut function for printing the grader report toggles.
560     * @param string $type The type of toggle
561     * @param bool $return Whether to return the HTML string rather than printing it
562     * @return void
563     */
564     public function print_toggle($type) {
565         global $CFG, $OUTPUT;
567         $icons = array('eyecons' => 't/hide',
568                        'calculations' => 't/calc',
569                        'locks' => 't/lock',
570                        'averages' => 't/mean',
571                        'quickfeedback' => 't/feedback',
572                        'nooutcomes' => 't/outcomes');
574         $prefname = 'grade_report_show' . $type;
576         if (array_key_exists($prefname, $CFG)) {
577             $showpref = get_user_preferences($prefname, $CFG->$prefname);
578         } else {
579             $showpref = get_user_preferences($prefname);
580         }
582         $strshow = $this->get_lang_string('show' . $type, 'grades');
583         $strhide = $this->get_lang_string('hide' . $type, 'grades');
585         $showhide = 'show';
586         $toggleaction = 1;
588         if ($showpref) {
589             $showhide = 'hide';
590             $toggleaction = 0;
591         }
593         if (array_key_exists($type, $icons)) {
594             $imagename = $icons[$type];
595         } else {
596             $imagename = "t/$type";
597         }
599         $string = ${'str' . $showhide};
601         $url = new moodle_url($this->baseurl, array('toggle' => $toggleaction, 'toggle_type' => $type));
603         $retval = $OUTPUT->container($OUTPUT->action_icon($url, new pix_icon($imagename, $string))); // TODO: this container looks wrong here
605         return $retval;
606     }
608     /**
609      * Builds and returns the rows that will make up the left part of the grader report
610      * This consists of student names and icons, links to user reports and id numbers, as well
611      * as header cells for these columns. It also includes the fillers required for the
612      * categories displayed on the right side of the report.
613      * @return array Array of html_table_row objects
614      */
615     public function get_left_rows() {
616         global $CFG, $USER, $OUTPUT;
618         $rows = array();
620         $showuserimage = $this->get_pref('showuserimage');
621         $fixedstudents = $this->is_fixed_students();
623         $strfeedback  = $this->get_lang_string("feedback");
624         $strgrade     = $this->get_lang_string('grade');
626         $extrafields = get_extra_user_fields($this->context);
628         $arrows = $this->get_sort_arrows($extrafields);
630         $colspan = 1;
631         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
632             $colspan++;
633         }
634         $colspan += count($extrafields);
636         $levels = count($this->gtree->levels) - 1;
638         for ($i = 0; $i < $levels; $i++) {
639             $fillercell = new html_table_cell();
640             $fillercell->attributes['class'] = 'fixedcolumn cell topleft';
641             $fillercell->text = ' ';
642             $fillercell->colspan = $colspan;
643             $row = new html_table_row(array($fillercell));
644             $rows[] = $row;
645         }
647         $headerrow = new html_table_row();
648         $headerrow->attributes['class'] = 'heading';
650         $studentheader = new html_table_cell();
651         $studentheader->attributes['class'] = 'header';
652         $studentheader->scope = 'col';
653         $studentheader->header = true;
654         $studentheader->id = 'studentheader';
655         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
656             $studentheader->colspan = 2;
657         }
658         $studentheader->text = $arrows['studentname'];
660         $headerrow->cells[] = $studentheader;
662         foreach ($extrafields as $field) {
663             $fieldheader = new html_table_cell();
664             $fieldheader->attributes['class'] = 'header userfield user' . $field;
665             $fieldheader->scope = 'col';
666             $fieldheader->header = true;
667             $fieldheader->text = $arrows[$field];
669             $headerrow->cells[] = $fieldheader;
670         }
672         $rows[] = $headerrow;
674         $rows = $this->get_left_icons_row($rows, $colspan);
676         $rowclasses = array('even', 'odd');
678         $suspendedstring = null;
679         foreach ($this->users as $userid => $user) {
680             $userrow = new html_table_row();
681             $userrow->id = 'fixed_user_'.$userid;
682             $userrow->attributes['class'] = 'r'.$this->rowcount++.' '.$rowclasses[$this->rowcount % 2];
684             $usercell = new html_table_cell();
685             $usercell->attributes['class'] = 'user';
687             $usercell->header = true;
688             $usercell->scope = 'row';
690             if ($showuserimage) {
691                 $usercell->text = $OUTPUT->user_picture($user);
692             }
694             $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
696             if (!empty($user->suspendedenrolment)) {
697                 $usercell->attributes['class'] .= ' usersuspended';
699                 //may be lots of suspended users so only get the string once
700                 if (empty($suspendedstring)) {
701                     $suspendedstring = get_string('userenrolmentsuspended', 'grades');
702                 }
703                 $usercell->text .= html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('i/enrolmentsuspended'), 'title'=>$suspendedstring, 'alt'=>$suspendedstring, 'class'=>'usersuspendedicon'));
704             }
706             $userrow->cells[] = $usercell;
708             if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
709                 $userreportcell = new html_table_cell();
710                 $userreportcell->attributes['class'] = 'userreport';
711                 $userreportcell->header = true;
712                 $a = new stdClass();
713                 $a->user = fullname($user);
714                 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
715                 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
716                 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
717                 $userrow->cells[] = $userreportcell;
718             }
720             foreach ($extrafields as $field) {
721                 $fieldcell = new html_table_cell();
722                 $fieldcell->attributes['class'] = 'header userfield user' . $field;
723                 $fieldcell->header = true;
724                 $fieldcell->scope = 'row';
725                 $fieldcell->text = $user->{$field};
726                 $userrow->cells[] = $fieldcell;
727             }
729             $rows[] = $userrow;
730         }
732         $rows = $this->get_left_range_row($rows, $colspan);
733         $rows = $this->get_left_avg_row($rows, $colspan, true);
734         $rows = $this->get_left_avg_row($rows, $colspan);
736         return $rows;
737     }
739     /**
740      * Builds and returns the rows that will make up the right part of the grader report
741      * @return array Array of html_table_row objects
742      */
743     public function get_right_rows() {
744         global $CFG, $USER, $OUTPUT, $DB, $PAGE;
746         $rows = array();
747         $this->rowcount = 0;
748         $numrows = count($this->gtree->get_levels());
749         $numusers = count($this->users);
750         $gradetabindex = 1;
751         $columnstounset = array();
752         $strgrade = $this->get_lang_string('grade');
753         $strfeedback  = $this->get_lang_string("feedback");
754         $arrows = $this->get_sort_arrows();
756         $jsarguments = array(
757             'id'        => '#fixed_column',
758             'cfg'       => array('ajaxenabled'=>false),
759             'items'     => array(),
760             'users'     => array(),
761             'feedback'  => array()
762         );
763         $jsscales = array();
765         foreach ($this->gtree->get_levels() as $key=>$row) {
766             if ($key == 0) {
767                 // do not display course grade category
768                 // continue;
769             }
771             $headingrow = new html_table_row();
772             $headingrow->attributes['class'] = 'heading_name_row';
774             foreach ($row as $columnkey => $element) {
775                 $sortlink = clone($this->baseurl);
776                 if (isset($element['object']->id)) {
777                     $sortlink->param('sortitemid', $element['object']->id);
778                 }
780                 $eid    = $element['eid'];
781                 $object = $element['object'];
782                 $type   = $element['type'];
783                 $categorystate = @$element['categorystate'];
785                 if (!empty($element['colspan'])) {
786                     $colspan = $element['colspan'];
787                 } else {
788                     $colspan = 1;
789                 }
791                 if (!empty($element['depth'])) {
792                     $catlevel = 'catlevel'.$element['depth'];
793                 } else {
794                     $catlevel = '';
795                 }
797 // Element is a filler
798                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
799                     $fillercell = new html_table_cell();
800                     $fillercell->attributes['class'] = $type . ' ' . $catlevel;
801                     $fillercell->colspan = $colspan;
802                     $fillercell->text = '&nbsp;';
803                     $fillercell->header = true;
804                     $fillercell->scope = 'col';
805                     $headingrow->cells[] = $fillercell;
806                 }
807 // Element is a category
808                 else if ($type == 'category') {
809                     $categorycell = new html_table_cell();
810                     $categorycell->attributes['class'] = 'category ' . $catlevel;
811                     $categorycell->colspan = $colspan;
812                     $categorycell->text = shorten_text($element['object']->get_name());
813                     $categorycell->text .= $this->get_collapsing_icon($element);
814                     $categorycell->header = true;
815                     $categorycell->scope = 'col';
817                     // Print icons
818                     if ($USER->gradeediting[$this->courseid]) {
819                         $categorycell->text .= $this->get_icons($element);
820                     }
822                     $headingrow->cells[] = $categorycell;
823                 }
824 // Element is a grade_item
825                 else {
826                     //$itemmodule = $element['object']->itemmodule;
827                     //$iteminstance = $element['object']->iteminstance;
829                     if ($element['object']->id == $this->sortitemid) {
830                         if ($this->sortorder == 'ASC') {
831                             $arrow = $this->get_sort_arrow('up', $sortlink);
832                         } else {
833                             $arrow = $this->get_sort_arrow('down', $sortlink);
834                         }
835                     } else {
836                         $arrow = $this->get_sort_arrow('move', $sortlink);
837                     }
839                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
841                     $itemcell = new html_table_cell();
842                     $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable';
844                     if ($element['object']->is_hidden()) {
845                         $itemcell->attributes['class'] .= ' hidden';
846                     }
848                     $itemcell->colspan = $colspan;
849                     $itemcell->text = shorten_text($headerlink) . $arrow;
850                     $itemcell->header = true;
851                     $itemcell->scope = 'col';
853                     $headingrow->cells[] = $itemcell;
854                 }
855             }
856             $rows[] = $headingrow;
857         }
859         $rows = $this->get_right_icons_row($rows);
861         // Preload scale objects for items with a scaleid and initialize tab indices
862         $scaleslist = array();
863         $tabindices = array();
865         foreach ($this->gtree->get_items() as $itemid=>$item) {
866             $scale = null;
867             if (!empty($item->scaleid)) {
868                 $scaleslist[] = $item->scaleid;
869                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
870             } else {
871                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
872             }
873             $tabindices[$item->id]['grade'] = $gradetabindex;
874             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
875             $gradetabindex += $numusers * 2;
876         }
877         $scalesarray = array();
879         if (!empty($scaleslist)) {
880             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
881         }
882         $jsscales = $scalesarray;
884         $rowclasses = array('even', 'odd');
886         foreach ($this->users as $userid => $user) {
888             if ($this->canviewhidden) {
889                 $altered = array();
890                 $unknown = array();
891             } else {
892                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
893                 $altered = $hidingaffected['altered'];
894                 $unknown = $hidingaffected['unknown'];
895                 unset($hidingaffected);
896             }
899             $itemrow = new html_table_row();
900             $itemrow->id = 'user_'.$userid;
901             $itemrow->attributes['class'] = $rowclasses[$this->rowcount % 2];
903             $jsarguments['users'][$userid] = fullname($user);
905             foreach ($this->gtree->items as $itemid=>$unused) {
906                 $item =& $this->gtree->items[$itemid];
907                 $grade = $this->grades[$userid][$item->id];
909                 $itemcell = new html_table_cell();
911                 $itemcell->id = 'u'.$userid.'i'.$itemid;
913                 // Get the decimal points preference for this item
914                 $decimalpoints = $item->get_decimals();
916                 if (in_array($itemid, $unknown)) {
917                     $gradeval = null;
918                 } else if (array_key_exists($itemid, $altered)) {
919                     $gradeval = $altered[$itemid];
920                 } else {
921                     $gradeval = $grade->finalgrade;
922                 }
923                 if (!empty($grade->finalgrade)) {
924                     $gradevalforJS = null;
925                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
926                         $gradevalforJS = (int)$gradeval;
927                     } else {
928                         $gradevalforJS = format_float($gradeval, $decimalpoints);
929                     }
930                     $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforJS);
931                 }
933                 // MDL-11274
934                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
935                 if (!$this->canviewhidden and $grade->is_hidden()) {
936                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
937                         // 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
938                         $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
939                     } else {
940                         $itemcell->text = '-';
941                     }
942                     $itemrow->cells[] = $itemcell;
943                     continue;
944                 }
946                 // emulate grade element
947                 $eid = $this->gtree->get_grade_eid($grade);
948                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
950                 $itemcell->attributes['class'] .= ' grade';
951                 if ($item->is_category_item()) {
952                     $itemcell->attributes['class'] .= ' cat';
953                 }
954                 if ($item->is_course_item()) {
955                     $itemcell->attributes['class'] .= ' course';
956                 }
957                 if ($grade->is_overridden()) {
958                     $itemcell->attributes['class'] .= ' overridden';
959                 }
961                 if ($grade->is_excluded()) {
962                     // $itemcell->attributes['class'] .= ' excluded';
963                 }
965                 if (!empty($grade->feedback)) {
966                     //should we be truncating feedback? ie $short_feedback = shorten_text($feedback, $this->feedback_trunc_length);
967                     $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
968                 }
970                 if ($grade->is_excluded()) {
971                     $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
972                 }
974                 // Do not show any icons if no grade (no record in DB to match)
975                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
976                     $itemcell->text .= $this->get_icons($element);
977                 }
979                 $hidden = '';
980                 if ($grade->is_hidden()) {
981                     $hidden = ' hidden ';
982                 }
984                 $gradepass = ' gradefail ';
985                 if ($grade->is_passed($item)) {
986                     $gradepass = ' gradepass ';
987                 } elseif (is_null($grade->is_passed($item))) {
988                     $gradepass = '';
989                 }
991                 // if in editing mode, we need to print either a text box
992                 // or a drop down (for scales)
993                 // grades in item of type grade category or course are not directly editable
994                 if ($item->needsupdate) {
995                     $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
997                 } else if ($USER->gradeediting[$this->courseid]) {
999                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1000                         $scale = $scalesarray[$item->scaleid];
1001                         $gradeval = (int)$gradeval; // scales use only integers
1002                         $scales = explode(",", $scale->scale);
1003                         // reindex because scale is off 1
1005                         // MDL-12104 some previous scales might have taken up part of the array
1006                         // so this needs to be reset
1007                         $scaleopt = array();
1008                         $i = 0;
1009                         foreach ($scales as $scaleoption) {
1010                             $i++;
1011                             $scaleopt[$i] = $scaleoption;
1012                         }
1014                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
1015                             $oldval = empty($gradeval) ? -1 : $gradeval;
1016                             if (empty($item->outcomeid)) {
1017                                 $nogradestr = $this->get_lang_string('nograde');
1018                             } else {
1019                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
1020                             }
1021                             $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
1022                             $itemcell->text .= html_writer::label(get_string('typescale', 'grades'), $attributes['id'], false, array('class' => 'accesshide'));
1023                             $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes);
1024                         } elseif(!empty($scale)) {
1025                             $scales = explode(",", $scale->scale);
1027                             // invalid grade if gradeval < 1
1028                             if ($gradeval < 1) {
1029                                 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
1030                             } else {
1031                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
1032                                 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
1033                             }
1034                         } else {
1035                             // no such scale, throw error?
1036                         }
1038                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
1039                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
1040                             $value = format_float($gradeval, $decimalpoints);
1041                             $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
1042                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade['
1043                                           .$userid.'][' .$item->id.']" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
1044                         } else {
1045                             $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
1046                         }
1047                     }
1050                     // If quickfeedback is on, print an input element
1051                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
1053                         $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
1054                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />';
1055                     }
1057                 } else { // Not editing
1058                     $gradedisplaytype = $item->get_displaytype();
1060                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1061                         $itemcell->attributes['class'] .= ' grade_type_scale';
1062                     } else if ($item->gradetype != GRADE_TYPE_TEXT) {
1063                         $itemcell->attributes['class'] .= ' grade_type_text';
1064                     }
1066                     if ($this->get_pref('enableajax')) {
1067                         $itemcell->attributes['class'] .= ' clickable';
1068                     }
1070                     if ($item->needsupdate) {
1071                         $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
1072                     } else {
1073                         $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
1074                         if ($this->get_pref('showanalysisicon')) {
1075                             $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
1076                         }
1077                     }
1078                 }
1080                 if (!empty($this->gradeserror[$item->id][$userid])) {
1081                     $itemcell->text .= $this->gradeserror[$item->id][$userid];
1082                 }
1084                 $itemrow->cells[] = $itemcell;
1085             }
1086             $rows[] = $itemrow;
1087         }
1089         if ($this->get_pref('enableajax')) {
1090             $jsarguments['cfg']['ajaxenabled'] = true;
1091             $jsarguments['cfg']['scales'] = array();
1092             foreach ($jsscales as $scale) {
1093                 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
1094             }
1095             $jsarguments['cfg']['feedbacktrunclength'] =  $this->feedback_trunc_length;
1097             // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
1098         }
1099         $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
1100         $jsarguments['cfg']['courseid'] =  $this->courseid;
1101         $jsarguments['cfg']['studentsperpage'] =  $this->get_students_per_page();
1102         $jsarguments['cfg']['showquickfeedback'] =  (bool)$this->get_pref('showquickfeedback');
1104         $module = array(
1105             'name'      => 'gradereport_grader',
1106             'fullpath'  => '/grade/report/grader/module.js',
1107             'requires'  => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
1108         );
1109         $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1110         $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
1111         $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1113         $rows = $this->get_right_range_row($rows);
1114         $rows = $this->get_right_avg_row($rows, true);
1115         $rows = $this->get_right_avg_row($rows);
1117         return $rows;
1118     }
1120     /**
1121      * Depending on the style of report (fixedstudents vs traditional one-table),
1122      * arranges the rows of data in one or two tables, and returns the output of
1123      * these tables in HTML
1124      * @return string HTML
1125      */
1126     public function get_grade_table() {
1127         global $OUTPUT;
1128         $fixedstudents = $this->is_fixed_students();
1130         $leftrows = $this->get_left_rows();
1131         $rightrows = $this->get_right_rows();
1133         $html = '';
1136         if ($fixedstudents) {
1137             $fixedcolumntable = new html_table();
1138             $fixedcolumntable->id = 'fixed_column';
1139             $fixedcolumntable->data = $leftrows;
1140             $html .= $OUTPUT->container(html_writer::table($fixedcolumntable), 'left_scroller');
1142             $righttable = new html_table();
1143             $righttable->id = 'user-grades';
1144             $righttable->data = $rightrows;
1146             $html .= $OUTPUT->container(html_writer::table($righttable), 'right_scroller');
1147         } else {
1148             $fulltable = new html_table();
1149             $fulltable->attributes['class'] = 'gradestable flexible boxaligncenter generaltable';
1150             $fulltable->id = 'user-grades';
1152             // Extract rows from each side (left and right) and collate them into one row each
1153             foreach ($leftrows as $key => $row) {
1154                 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1155                 $fulltable->data[] = $row;
1156             }
1157             $html .= html_writer::table($fulltable);
1158         }
1159         return $OUTPUT->container($html, 'gradeparent');
1160     }
1162     /**
1163      * Builds and return the row of icons for the left side of the report.
1164      * It only has one cell that says "Controls"
1165      * @param array $rows The Array of rows for the left part of the report
1166      * @param int $colspan The number of columns this cell has to span
1167      * @return array Array of rows for the left part of the report
1168      */
1169     public function get_left_icons_row($rows=array(), $colspan=1) {
1170         global $USER;
1172         if ($USER->gradeediting[$this->courseid]) {
1173             $controlsrow = new html_table_row();
1174             $controlsrow->attributes['class'] = 'controls';
1175             $controlscell = new html_table_cell();
1176             $controlscell->attributes['class'] = 'header controls';
1177             $controlscell->colspan = $colspan;
1178             $controlscell->text = $this->get_lang_string('controls','grades');
1180             $controlsrow->cells[] = $controlscell;
1181             $rows[] = $controlsrow;
1182         }
1183         return $rows;
1184     }
1186     /**
1187      * Builds and return the header for the row of ranges, for the left part of the grader report.
1188      * @param array $rows The Array of rows for the left part of the report
1189      * @param int $colspan The number of columns this cell has to span
1190      * @return array Array of rows for the left part of the report
1191      */
1192     public function get_left_range_row($rows=array(), $colspan=1) {
1193         global $CFG, $USER;
1195         if ($this->get_pref('showranges')) {
1196             $rangerow = new html_table_row();
1197             $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1198             $rangecell = new html_table_cell();
1199             $rangecell->attributes['class'] = 'header range';
1200             $rangecell->colspan = $colspan;
1201             $rangecell->header = true;
1202             $rangecell->scope = 'row';
1203             $rangecell->text = $this->get_lang_string('range','grades');
1204             $rangerow->cells[] = $rangecell;
1205             $rows[] = $rangerow;
1206         }
1208         return $rows;
1209     }
1211     /**
1212      * Builds and return the headers for the rows of averages, for the left part of the grader report.
1213      * @param array $rows The Array of rows for the left part of the report
1214      * @param int $colspan The number of columns this cell has to span
1215      * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1216      * @return array Array of rows for the left part of the report
1217      */
1218     public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1219         if (!$this->canviewhidden) {
1220             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1221             // better not show them at all if user can not see all hideen grades
1222             return $rows;
1223         }
1225         $showaverages = $this->get_pref('showaverages');
1226         $showaveragesgroup = $this->currentgroup && $showaverages;
1227         $straveragegroup = get_string('groupavg', 'grades');
1229         if ($groupavg) {
1230             if ($showaveragesgroup) {
1231                 $groupavgrow = new html_table_row();
1232                 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1233                 $groupavgcell = new html_table_cell();
1234                 $groupavgcell->attributes['class'] = 'header range';
1235                 $groupavgcell->colspan = $colspan;
1236                 $groupavgcell->header = true;
1237                 $groupavgcell->scope = 'row';
1238                 $groupavgcell->text = $straveragegroup;
1239                 $groupavgrow->cells[] = $groupavgcell;
1240                 $rows[] = $groupavgrow;
1241             }
1242         } else {
1243             $straverage = get_string('overallaverage', 'grades');
1245             if ($showaverages) {
1246                 $avgrow = new html_table_row();
1247                 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1248                 $avgcell = new html_table_cell();
1249                 $avgcell->attributes['class'] = 'header range';
1250                 $avgcell->colspan = $colspan;
1251                 $avgcell->header = true;
1252                 $avgcell->scope = 'row';
1253                 $avgcell->text = $straverage;
1254                 $avgrow->cells[] = $avgcell;
1255                 $rows[] = $avgrow;
1256             }
1257         }
1259         return $rows;
1260     }
1262     /**
1263      * Builds and return the row of icons when editing is on, for the right part of the grader report.
1264      * @param array $rows The Array of rows for the right part of the report
1265      * @return array Array of rows for the right part of the report
1266      */
1267     public function get_right_icons_row($rows=array()) {
1268         global $USER;
1269         if ($USER->gradeediting[$this->courseid]) {
1270             $iconsrow = new html_table_row();
1271             $iconsrow->attributes['class'] = 'controls';
1273             foreach ($this->gtree->items as $itemid=>$unused) {
1274                 // emulate grade element
1275                 $item = $this->gtree->get_item($itemid);
1277                 $eid = $this->gtree->get_item_eid($item);
1278                 $element = $this->gtree->locate_element($eid);
1279                 $itemcell = new html_table_cell();
1280                 $itemcell->attributes['class'] = 'controls icons';
1281                 $itemcell->text = $this->get_icons($element);
1282                 $iconsrow->cells[] = $itemcell;
1283             }
1284             $rows[] = $iconsrow;
1285         }
1286         return $rows;
1287     }
1289     /**
1290      * Builds and return the row of ranges for the right part of the grader report.
1291      * @param array $rows The Array of rows for the right part of the report
1292      * @return array Array of rows for the right part of the report
1293      */
1294     public function get_right_range_row($rows=array()) {
1295         global $OUTPUT;
1297         if ($this->get_pref('showranges')) {
1298             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1299             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1300             $rangerow = new html_table_row();
1301             $rangerow->attributes['class'] = 'heading range';
1303             foreach ($this->gtree->items as $itemid=>$unused) {
1304                 $item =& $this->gtree->items[$itemid];
1305                 $itemcell = new html_table_cell();
1306                 $itemcell->header = true;
1307                 $itemcell->attributes['class'] .= ' header range';
1309                 $hidden = '';
1310                 if ($item->is_hidden()) {
1311                     $hidden = ' hidden ';
1312                 }
1314                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1316                 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1317                 $rangerow->cells[] = $itemcell;
1318             }
1319             $rows[] = $rangerow;
1320         }
1321         return $rows;
1322     }
1324     /**
1325      * Builds and return the row of averages for the right part of the grader report.
1326      * @param array $rows Whether to return only group averages or all averages.
1327      * @param bool $grouponly Whether to return only group averages or all averages.
1328      * @return array Array of rows for the right part of the report
1329      */
1330     public function get_right_avg_row($rows=array(), $grouponly=false) {
1331         global $CFG, $USER, $DB, $OUTPUT;
1333         if (!$this->canviewhidden) {
1334             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1335             // better not show them at all if user can not see all hidden grades
1336             return $rows;
1337         }
1339         $showaverages = $this->get_pref('showaverages');
1340         $showaveragesgroup = $this->currentgroup && $showaverages;
1342         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1343         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1344         $meanselection         = $this->get_pref('meanselection');
1345         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1347         $avghtml = '';
1348         $avgcssclass = 'avg';
1350         if ($grouponly) {
1351             $straverage = get_string('groupavg', 'grades');
1352             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1353             $groupsql = $this->groupsql;
1354             $groupwheresql = $this->groupwheresql;
1355             $groupwheresqlparams = $this->groupwheresql_params;
1356             $avgcssclass = 'groupavg';
1357         } else {
1358             $straverage = get_string('overallaverage', 'grades');
1359             $showaverages = $this->get_pref('showaverages');
1360             $groupsql = "";
1361             $groupwheresql = "";
1362             $groupwheresqlparams = array();
1363         }
1365         if ($shownumberofgrades) {
1366             $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1367         }
1369         $totalcount = $this->get_numusers($grouponly);
1371         //limit to users with a gradeable role
1372         list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1374         //limit to users with an active enrollment
1375         list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
1377         if ($showaverages) {
1378             $params = array_merge(array('courseid'=>$this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams);
1380             // find sums of all grade items in course
1381             $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1382                       FROM {grade_items} gi
1383                       JOIN {grade_grades} g ON g.itemid = gi.id
1384                       JOIN {user} u ON u.id = g.userid
1385                       JOIN ($enrolledsql) je ON je.id = u.id
1386                       JOIN (
1387                                SELECT DISTINCT ra.userid
1388                                  FROM {role_assignments} ra
1389                                 WHERE ra.roleid $gradebookrolessql
1390                                   AND ra.contextid " . get_related_contexts_string($this->context) . "
1391                            ) rainner ON rainner.userid = u.id
1392                       $groupsql
1393                      WHERE gi.courseid = :courseid
1394                        AND u.deleted = 0
1395                        AND g.finalgrade IS NOT NULL
1396                        $groupwheresql
1397                      GROUP BY g.itemid";
1398             $sumarray = array();
1399             if ($sums = $DB->get_records_sql($sql, $params)) {
1400                 foreach ($sums as $itemid => $csum) {
1401                     $sumarray[$itemid] = $csum->sum;
1402                 }
1403             }
1405             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1406             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1407             $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1408                       FROM {grade_items} gi
1409                       CROSS JOIN {user} u
1410                       JOIN ($enrolledsql) je
1411                            ON je.id = u.id
1412                       JOIN {role_assignments} ra
1413                            ON ra.userid = u.id
1414                       LEFT OUTER JOIN {grade_grades} g
1415                            ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1416                       $groupsql
1417                      WHERE gi.courseid = :courseid
1418                            AND ra.roleid $gradebookrolessql
1419                            AND ra.contextid ".get_related_contexts_string($this->context)."
1420                            AND u.deleted = 0
1421                            AND g.id IS NULL
1422                            $groupwheresql
1423                   GROUP BY gi.id";
1425             $ungradedcounts = $DB->get_records_sql($sql, $params);
1427             $avgrow = new html_table_row();
1428             $avgrow->attributes['class'] = 'avg';
1430             foreach ($this->gtree->items as $itemid=>$unused) {
1431                 $item =& $this->gtree->items[$itemid];
1433                 if ($item->needsupdate) {
1434                     $avgcell = new html_table_cell();
1435                     $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1436                     $avgrow->cells[] = $avgcell;
1437                     continue;
1438                 }
1440                 if (!isset($sumarray[$item->id])) {
1441                     $sumarray[$item->id] = 0;
1442                 }
1444                 if (empty($ungradedcounts[$itemid])) {
1445                     $ungradedcount = 0;
1446                 } else {
1447                     $ungradedcount = $ungradedcounts[$itemid]->count;
1448                 }
1450                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1451                     $meancount = $totalcount - $ungradedcount;
1452                 } else { // Bump up the sum by the number of ungraded items * grademin
1453                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1454                     $meancount = $totalcount;
1455                 }
1457                 $decimalpoints = $item->get_decimals();
1459                 // Determine which display type to use for this average
1460                 if ($USER->gradeediting[$this->courseid]) {
1461                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1463                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1464                     $displaytype = $item->get_displaytype();
1466                 } else {
1467                     $displaytype = $averagesdisplaytype;
1468                 }
1470                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1471                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1472                     $decimalpoints = $item->get_decimals();
1474                 } else {
1475                     $decimalpoints = $averagesdecimalpoints;
1476                 }
1478                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1479                     $avgcell = new html_table_cell();
1480                     $avgcell->text = '-';
1481                     $avgrow->cells[] = $avgcell;
1483                 } else {
1484                     $sum = $sumarray[$item->id];
1485                     $avgradeval = $sum/$meancount;
1486                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1488                     $numberofgrades = '';
1489                     if ($shownumberofgrades) {
1490                         $numberofgrades = " ($meancount)";
1491                     }
1493                     $avgcell = new html_table_cell();
1494                     $avgcell->text = $gradehtml.$numberofgrades;
1495                     $avgrow->cells[] = $avgcell;
1496                 }
1497             }
1498             $rows[] = $avgrow;
1499         }
1500         return $rows;
1501     }
1503     /**
1504      * Given a grade_category, grade_item or grade_grade, this function
1505      * figures out the state of the object and builds then returns a div
1506      * with the icons needed for the grader report.
1507      *
1508      * @param array $object
1509      * @return string HTML
1510      */
1511     protected function get_icons($element) {
1512         global $CFG, $USER, $OUTPUT;
1514         if (!$USER->gradeediting[$this->courseid]) {
1515             return '<div class="grade_icons" />';
1516         }
1518         // Init all icons
1519         $editicon = '';
1521         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1522             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1523         }
1525         $editcalculationicon = '';
1526         $showhideicon        = '';
1527         $lockunlockicon      = '';
1529         if (has_capability('moodle/grade:manage', $this->context)) {
1530             if ($this->get_pref('showcalculations')) {
1531                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1532             }
1534             if ($this->get_pref('showeyecons')) {
1535                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1536             }
1538             if ($this->get_pref('showlocks')) {
1539                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1540             }
1542         }
1544         $gradeanalysisicon   = '';
1545         if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1546             $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1547         }
1549         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1550     }
1552     /**
1553      * Given a category element returns collapsing +/- icon if available
1554      * @param object $object
1555      * @return string HTML
1556      */
1557     protected function get_collapsing_icon($element) {
1558         global $OUTPUT;
1560         $icon = '';
1561         // If object is a category, display expand/contract icon
1562         if ($element['type'] == 'category') {
1563             // Load language strings
1564             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1565             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1566             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1568             $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
1570             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1571                 $url->param('action', 'switch_plus');
1572                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
1574             } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1575                 $url->param('action', 'switch_whole');
1576                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
1578             } else {
1579                 $url->param('action', 'switch_minus');
1580                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
1581             }
1582         }
1583         return $icon;
1584     }
1586     public function process_action($target, $action) {
1587         return self::do_process_action($target, $action);
1588     }
1590     /**
1591      * Processes a single action against a category, grade_item or grade.
1592      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1593      * @param string $action Which action to take (edit, delete etc...)
1594      * @return
1595      */
1596     public static function do_process_action($target, $action) {
1597         // TODO: this code should be in some grade_tree static method
1598         $targettype = substr($target, 0, 1);
1599         $targetid = substr($target, 1);
1600         // TODO: end
1602         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1603             $collapsed = unserialize($collapsed);
1604         } else {
1605             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1606         }
1608         switch ($action) {
1609             case 'switch_minus': // Add category to array of aggregatesonly
1610                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1611                     $collapsed['aggregatesonly'][] = $targetid;
1612                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1613                 }
1614                 break;
1616             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1617                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1618                 if ($key !== false) {
1619                     unset($collapsed['aggregatesonly'][$key]);
1620                 }
1621                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1622                     $collapsed['gradesonly'][] = $targetid;
1623                 }
1624                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1625                 break;
1626             case 'switch_whole': // Remove the category from the array of collapsed cats
1627                 $key = array_search($targetid, $collapsed['gradesonly']);
1628                 if ($key !== false) {
1629                     unset($collapsed['gradesonly'][$key]);
1630                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1631                 }
1633                 break;
1634             default:
1635                 break;
1636         }
1638         return true;
1639     }
1641     /**
1642      * Returns whether or not to display fixed students column.
1643      * Includes a browser check, because IE6 doesn't support the scrollbar.
1644      *
1645      * @return bool
1646      */
1647     public function is_fixed_students() {
1648         global $USER, $CFG;
1649         return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1650             (check_browser_version('MSIE', '7.0') ||
1651              check_browser_version('Firefox', '2.0') ||
1652              check_browser_version('Gecko', '2006010100') ||
1653              check_browser_version('Camino', '1.0') ||
1654              check_browser_version('Opera', '6.0') ||
1655              check_browser_version('Chrome', '6') ||
1656              check_browser_version('Safari', '300'));
1657     }
1659     /**
1660      * Refactored function for generating HTML of sorting links with matching arrows.
1661      * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1662      * to inject into a table header cell.
1663      * @param array $extrafields Array of extra fields being displayed, such as
1664      *   user idnumber
1665      * @return array An associative array of HTML sorting links+arrows
1666      */
1667     public function get_sort_arrows(array $extrafields = array()) {
1668         global $OUTPUT;
1669         $arrows = array();
1671         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
1672         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
1673         $strfirstname = $this->get_lang_string('firstname');
1674         $strlastname  = $this->get_lang_string('lastname');
1676         $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1677         $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
1679         $arrows['studentname'] = $lastlink;
1681         if ($this->sortitemid === 'lastname') {
1682             if ($this->sortorder == 'ASC') {
1683                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1684             } else {
1685                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1686             }
1687         }
1689         $arrows['studentname'] .= ' ' . $firstlink;
1691         if ($this->sortitemid === 'firstname') {
1692             if ($this->sortorder == 'ASC') {
1693                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1694             } else {
1695                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1696             }
1697         }
1699         foreach ($extrafields as $field) {
1700             $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1701                     array('sortitemid'=>$field)), get_user_field_name($field));
1702             $arrows[$field] = $fieldlink;
1704             if ($field == $this->sortitemid) {
1705                 if ($this->sortorder == 'ASC') {
1706                     $arrows[$field] .= print_arrow('up', $strsortasc, true);
1707                 } else {
1708                     $arrows[$field] .= print_arrow('down', $strsortdesc, true);
1709                 }
1710             }
1711         }
1713         return $arrows;
1714     }
1716     /**
1717      * Returns the maximum number of students to be displayed on each page
1718      *
1719      * Takes into account the 'studentsperpage' user preference and the 'max_input_vars'
1720      * PHP setting. Too many fields is only a problem when submitting grades but
1721      * we respect 'max_input_vars' even when viewing grades to prevent students disappearing
1722      * when toggling editing on and off.
1723      *
1724      * @return int The maximum number of students to display per page
1725      */
1726     public function get_students_per_page() {
1727         global $USER;
1728         static $studentsperpage = null;
1730         if ($studentsperpage === null) {
1731             $originalstudentsperpage = $studentsperpage = $this->get_pref('studentsperpage');
1733             // Will this number of students result in more fields that we are allowed?
1734             $maxinputvars = ini_get('max_input_vars');
1735             if ($maxinputvars !== false) {
1736                 // We can't do anything about there being more grade items than max_input_vars,
1737                 // but we can decrease number of students per page if there are >= max_input_vars
1738                 $fieldsperstudent = 0; // The number of fields output per student
1740                 if ($this->get_pref('quickgrading') || $this->get_pref('showquickfeedback')) {
1741                     // Each array (grade, feedback) will gain one element
1742                     $fieldsperstudent ++;
1743                 }
1745                 $fieldsrequired = $studentsperpage * $fieldsperstudent;
1746                 if ($fieldsrequired >= $maxinputvars) {
1747                     $studentsperpage = $maxinputvars - 1; // Subtract one to be on the safe side
1748                     if ($studentsperpage<1) {
1749                         // Make sure students per page doesn't fall below 1, though if your
1750                         // max_input_vars is only 1 you've got bigger problems!
1751                         $studentsperpage = 1;
1752                     }
1754                     $a = new stdClass();
1755                     $a->originalstudentsperpage = $originalstudentsperpage;
1756                     $a->studentsperpage = $studentsperpage;
1757                     $a->maxinputvars = $maxinputvars;
1758                     debugging(get_string('studentsperpagereduced', 'grades', $a));
1759                 }
1760             }
1761         }
1763         return $studentsperpage;
1764     }