Merge branch 'MDL-36316-master' of git://github.com/danpoltawski/moodle
[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', context_course::instance($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 quick grading is on, feedback needs to be compared without line breaks.
230                         if ($this->get_pref('quickgrading')) {
231                             $oldvalue->feedback = preg_replace("/\r\n|\r|\n/", "", $oldvalue->feedback);
232                         }
233                         if (($oldvalue->feedback === $postedvalue) or ($oldvalue->feedback === NULL and empty($postedvalue))) {
234                             continue;
235                         }
236                     }
238                     if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) {
239                         print_error('invalidgradeitemid');
240                     }
242                     // Pre-process grade
243                     if ($datatype == 'grade') {
244                         $feedback = false;
245                         $feedbackformat = false;
246                         if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
247                             if ($postedvalue == -1) { // -1 means no grade
248                                 $finalgrade = null;
249                             } else {
250                                 $finalgrade = $postedvalue;
251                             }
252                         } else {
253                             $finalgrade = unformat_float($postedvalue);
254                         }
256                         $errorstr = '';
257                         // Warn if the grade is out of bounds.
258                         if (is_null($finalgrade)) {
259                             // ok
260                         } else {
261                             $bounded = $gradeitem->bounded_grade($finalgrade);
262                             if ($bounded > $finalgrade) {
263                                 $errorstr = 'lessthanmin';
264                             } else if ($bounded < $finalgrade) {
265                                 $errorstr = 'morethanmax';
266                             }
267                         }
268                         if ($errorstr) {
269                             $userfields = 'id, ' . get_all_user_name_fields(true);
270                             $user = $DB->get_record('user', array('id' => $userid), $userfields);
271                             $gradestr = new stdClass();
272                             $gradestr->username = fullname($user);
273                             $gradestr->itemname = $gradeitem->get_name();
274                             $warnings[] = get_string($errorstr, 'grades', $gradestr);
275                         }
277                     } else if ($datatype == 'feedback') {
278                         $finalgrade = false;
279                         $trimmed = trim($postedvalue);
280                         if (empty($trimmed)) {
281                              $feedback = NULL;
282                         } else {
283                              $feedback = $postedvalue;
284                         }
285                     }
287                     // group access control
288                     if ($separategroups) {
289                         // note: we can not use $this->currentgroup because it would fail badly
290                         //       when having two browser windows each with different group
291                         $sharinggroup = false;
292                         foreach($mygroups as $groupid) {
293                             if (groups_is_member($groupid, $userid)) {
294                                 $sharinggroup = true;
295                                 break;
296                             }
297                         }
298                         if (!$sharinggroup) {
299                             // either group membership changed or somebody is hacking grades of other group
300                             $warnings[] = get_string('errorsavegrade', 'grades');
301                             continue;
302                         }
303                     }
305                     $url = '/report/grader/index.php?id=' . $this->course->id;
306                     $fullname = fullname($this->users[$userid]);
308                     $info = "{$gradeitem->itemname}: $fullname";
309                     add_to_log($this->course->id, 'grade', 'update', $url, $info);
311                     $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
313                     // We can update feedback without reloading the grade item as it doesn't affect grade calculations
314                     if ($datatype === 'feedback') {
315                         $this->grades[$userid][$itemid]->feedback = $feedback;
316                     }
317                 }
318             }
319         }
321         if ($changedgrades) {
322             // If a final grade was overriden reload grades so dependent grades like course total will be correct
323             $this->grades = null;
324         }
326         return $warnings;
327     }
330     /**
331      * Setting the sort order, this depends on last state
332      * all this should be in the new table class that we might need to use
333      * for displaying grades.
334      */
335     private function setup_sortitemid() {
337         global $SESSION;
339         if (!isset($SESSION->gradeuserreport)) {
340             $SESSION->gradeuserreport = new stdClass();
341         }
343         if ($this->sortitemid) {
344             if (!isset($SESSION->gradeuserreport->sort)) {
345                 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
346                     $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
347                 } else {
348                     $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
349                 }
350             } else {
351                 // this is the first sort, i.e. by last name
352                 if (!isset($SESSION->gradeuserreport->sortitemid)) {
353                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
354                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
355                     } else {
356                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
357                     }
358                 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
359                     // same as last sort
360                     if ($SESSION->gradeuserreport->sort == 'ASC') {
361                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
362                     } else {
363                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
364                     }
365                 } else {
366                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
367                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
368                     } else {
369                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
370                     }
371                 }
372             }
373             $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
374         } else {
375             // not requesting sort, use last setting (for paging)
377             if (isset($SESSION->gradeuserreport->sortitemid)) {
378                 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
379             }else{
380                 $this->sortitemid = 'lastname';
381             }
383             if (isset($SESSION->gradeuserreport->sort)) {
384                 $this->sortorder = $SESSION->gradeuserreport->sort;
385             } else {
386                 $this->sortorder = 'ASC';
387             }
388         }
389     }
391     /**
392      * pulls out the userids of the users to be display, and sorts them
393      */
394     public function load_users() {
395         global $CFG, $DB;
397         if (!empty($this->users)) {
398             return;
399         }
401         // Limit to users with a gradeable role.
402         list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
404         // Limit to users with an active enrollment.
405         list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
407         // Fields we need from the user table.
408         $userfields = user_picture::fields('u', get_extra_user_fields($this->context));
410         // We want to query both the current context and parent contexts.
411         list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
413         // If the user has clicked one of the sort asc/desc arrows.
414         if (is_numeric($this->sortitemid)) {
415             $params = array_merge(array('gitemid' => $this->sortitemid), $gradebookrolesparams, $this->groupwheresql_params, $enrolledparams,
416                 $relatedctxparams);
418             $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
419             $sort = "g.finalgrade $this->sortorder";
420         } else {
421             $sortjoin = '';
422             switch($this->sortitemid) {
423                 case 'lastname':
424                     $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder";
425                     break;
426                 case 'firstname':
427                     $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder";
428                     break;
429                 case 'email':
430                     $sort = "u.email $this->sortorder";
431                     break;
432                 case 'idnumber':
433                 default:
434                     $sort = "u.idnumber $this->sortorder";
435                     break;
436             }
438             $params = array_merge($gradebookrolesparams, $this->groupwheresql_params, $enrolledparams, $relatedctxparams);
439         }
441         $sql = "SELECT $userfields
442                   FROM {user} u
443                   JOIN ($enrolledsql) je ON je.id = u.id
444                        $this->groupsql
445                        $sortjoin
446                   JOIN (
447                            SELECT DISTINCT ra.userid
448                              FROM {role_assignments} ra
449                             WHERE ra.roleid IN ($this->gradebookroles)
450                               AND ra.contextid $relatedctxsql
451                        ) rainner ON rainner.userid = u.id
452                    AND u.deleted = 0
453                    $this->groupwheresql
454               ORDER BY $sort";
455         $studentsperpage = $this->get_students_per_page();
456         $this->users = $DB->get_records_sql($sql, $params, $studentsperpage * $this->page, $studentsperpage);
458         if (empty($this->users)) {
459             $this->userselect = '';
460             $this->users = array();
461             $this->userselect_params = array();
462         } else {
463             list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
464             $this->userselect = "AND g.userid $usql";
465             $this->userselect_params = $uparams;
467             // Add a flag to each user indicating whether their enrolment is active.
468             $sql = "SELECT ue.userid
469                       FROM {user_enrolments} ue
470                       JOIN {enrol} e ON e.id = ue.enrolid
471                      WHERE ue.userid $usql
472                            AND ue.status = :uestatus
473                            AND e.status = :estatus
474                            AND e.courseid = :courseid
475                   GROUP BY ue.userid";
476             $coursecontext = $this->context->get_course_context(true);
477             $params = array_merge($uparams, array('estatus'=>ENROL_INSTANCE_ENABLED, 'uestatus'=>ENROL_USER_ACTIVE, 'courseid'=>$coursecontext->instanceid));
478             $useractiveenrolments = $DB->get_records_sql($sql, $params);
480             $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
481             $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
482             $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
483             foreach ($this->users as $user) {
484                 // If we are showing only active enrolments, then remove suspended users from list.
485                 if ($showonlyactiveenrol && !array_key_exists($user->id, $useractiveenrolments)) {
486                     unset($this->users[$user->id]);
487                 } else {
488                     $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
489                 }
490             }
491         }
493         return $this->users;
494     }
496     /**
497      * we supply the userids in this query, and get all the grades
498      * pulls out all the grades, this does not need to worry about paging
499      */
500     public function load_final_grades() {
501         global $CFG, $DB;
503         if (!empty($this->grades)) {
504             return;
505         }
507         // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
508         $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
509         $sql = "SELECT g.*
510                   FROM {grade_items} gi,
511                        {grade_grades} g
512                  WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
514         $userids = array_keys($this->users);
517         if ($grades = $DB->get_records_sql($sql, $params)) {
518             foreach ($grades as $graderec) {
519                 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
520                     $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
521                     $this->grades[$graderec->userid][$graderec->itemid]->grade_item = $this->gtree->get_item($graderec->itemid); // db caching
522                 }
523             }
524         }
526         // prefil grades that do not exist yet
527         foreach ($userids as $userid) {
528             foreach ($this->gtree->get_items() as $itemid=>$unused) {
529                 if (!isset($this->grades[$userid][$itemid])) {
530                     $this->grades[$userid][$itemid] = new grade_grade();
531                     $this->grades[$userid][$itemid]->itemid = $itemid;
532                     $this->grades[$userid][$itemid]->userid = $userid;
533                     $this->grades[$userid][$itemid]->grade_item = $this->gtree->get_item($itemid); // db caching
534                 }
535             }
536         }
537     }
539     /**
540      * @deprecated since Moodle 2.4 as it appears not to be used any more.
541      */
542     public function get_toggles_html() {
543         throw new coding_exception('get_toggles_html() can not be used any more');
544     }
546     /**
547      * @deprecated since 2.4 as it appears not to be used any more.
548      */
549     public function print_toggle($type) {
550         throw new coding_exception('print_toggle() can not be used any more');
551     }
553     /**
554      * Builds and returns the rows that will make up the left part of the grader report
555      * This consists of student names and icons, links to user reports and id numbers, as well
556      * as header cells for these columns. It also includes the fillers required for the
557      * categories displayed on the right side of the report.
558      * @return array Array of html_table_row objects
559      */
560     public function get_left_rows() {
561         global $CFG, $USER, $OUTPUT;
563         $rows = array();
565         $showuserimage = $this->get_pref('showuserimage');
567         $strfeedback  = $this->get_lang_string("feedback");
568         $strgrade     = $this->get_lang_string('grade');
570         $extrafields = get_extra_user_fields($this->context);
572         $arrows = $this->get_sort_arrows($extrafields);
574         $colspan = 1;
575         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
576             $colspan++;
577         }
578         $colspan += count($extrafields);
580         $levels = count($this->gtree->levels) - 1;
582         for ($i = 0; $i < $levels; $i++) {
583             $fillercell = new html_table_cell();
584             $fillercell->attributes['class'] = 'fixedcolumn cell topleft';
585             $fillercell->text = ' ';
586             $fillercell->colspan = $colspan;
587             $row = new html_table_row(array($fillercell));
588             $rows[] = $row;
589         }
591         $headerrow = new html_table_row();
592         $headerrow->attributes['class'] = 'heading';
594         $studentheader = new html_table_cell();
595         $studentheader->attributes['class'] = 'header';
596         $studentheader->scope = 'col';
597         $studentheader->header = true;
598         $studentheader->id = 'studentheader';
599         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
600             $studentheader->colspan = 2;
601         }
602         $studentheader->text = $arrows['studentname'];
604         $headerrow->cells[] = $studentheader;
606         foreach ($extrafields as $field) {
607             $fieldheader = new html_table_cell();
608             $fieldheader->attributes['class'] = 'header userfield user' . $field;
609             $fieldheader->scope = 'col';
610             $fieldheader->header = true;
611             $fieldheader->text = $arrows[$field];
613             $headerrow->cells[] = $fieldheader;
614         }
616         $rows[] = $headerrow;
618         $rows = $this->get_left_icons_row($rows, $colspan);
620         $rowclasses = array('even', 'odd');
622         $suspendedstring = null;
623         foreach ($this->users as $userid => $user) {
624             $userrow = new html_table_row();
625             $userrow->id = 'fixed_user_'.$userid;
626             $userrow->attributes['class'] = 'r'.$this->rowcount++.' '.$rowclasses[$this->rowcount % 2];
628             $usercell = new html_table_cell();
629             $usercell->attributes['class'] = 'user';
631             $usercell->header = true;
632             $usercell->scope = 'row';
634             if ($showuserimage) {
635                 $usercell->text = $OUTPUT->user_picture($user);
636             }
638             $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
640             if (!empty($user->suspendedenrolment)) {
641                 $usercell->attributes['class'] .= ' usersuspended';
643                 //may be lots of suspended users so only get the string once
644                 if (empty($suspendedstring)) {
645                     $suspendedstring = get_string('userenrolmentsuspended', 'grades');
646                 }
647                 $usercell->text .= html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('i/enrolmentsuspended'), 'title'=>$suspendedstring, 'alt'=>$suspendedstring, 'class'=>'usersuspendedicon'));
648             }
650             $userrow->cells[] = $usercell;
652             if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
653                 $userreportcell = new html_table_cell();
654                 $userreportcell->attributes['class'] = 'userreport';
655                 $userreportcell->header = true;
656                 $a = new stdClass();
657                 $a->user = fullname($user);
658                 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
659                 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
660                 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
661                 $userrow->cells[] = $userreportcell;
662             }
664             foreach ($extrafields as $field) {
665                 $fieldcell = new html_table_cell();
666                 $fieldcell->attributes['class'] = 'header userfield user' . $field;
667                 $fieldcell->header = true;
668                 $fieldcell->scope = 'row';
669                 $fieldcell->text = $user->{$field};
670                 $userrow->cells[] = $fieldcell;
671             }
673             $rows[] = $userrow;
674         }
676         $rows = $this->get_left_range_row($rows, $colspan);
677         $rows = $this->get_left_avg_row($rows, $colspan, true);
678         $rows = $this->get_left_avg_row($rows, $colspan);
680         return $rows;
681     }
683     /**
684      * Builds and returns the rows that will make up the right part of the grader report
685      * @return array Array of html_table_row objects
686      */
687     public function get_right_rows() {
688         global $CFG, $USER, $OUTPUT, $DB, $PAGE;
690         $rows = array();
691         $this->rowcount = 0;
692         $numrows = count($this->gtree->get_levels());
693         $numusers = count($this->users);
694         $gradetabindex = 1;
695         $columnstounset = array();
696         $strgrade = $this->get_lang_string('grade');
697         $strfeedback  = $this->get_lang_string("feedback");
698         $arrows = $this->get_sort_arrows();
700         $jsarguments = array(
701             'id'        => '#fixed_column',
702             'cfg'       => array('ajaxenabled'=>false),
703             'items'     => array(),
704             'users'     => array(),
705             'feedback'  => array()
706         );
707         $jsscales = array();
709         foreach ($this->gtree->get_levels() as $key=>$row) {
710             if ($key == 0) {
711                 // do not display course grade category
712                 // continue;
713             }
715             $headingrow = new html_table_row();
716             $headingrow->attributes['class'] = 'heading_name_row';
718             foreach ($row as $columnkey => $element) {
719                 $sortlink = clone($this->baseurl);
720                 if (isset($element['object']->id)) {
721                     $sortlink->param('sortitemid', $element['object']->id);
722                 }
724                 $eid    = $element['eid'];
725                 $object = $element['object'];
726                 $type   = $element['type'];
727                 $categorystate = @$element['categorystate'];
729                 if (!empty($element['colspan'])) {
730                     $colspan = $element['colspan'];
731                 } else {
732                     $colspan = 1;
733                 }
735                 if (!empty($element['depth'])) {
736                     $catlevel = 'catlevel'.$element['depth'];
737                 } else {
738                     $catlevel = '';
739                 }
741 // Element is a filler
742                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
743                     $fillercell = new html_table_cell();
744                     $fillercell->attributes['class'] = $type . ' ' . $catlevel;
745                     $fillercell->colspan = $colspan;
746                     $fillercell->text = '&nbsp;';
747                     $fillercell->header = true;
748                     $fillercell->scope = 'col';
749                     $headingrow->cells[] = $fillercell;
750                 }
751 // Element is a category
752                 else if ($type == 'category') {
753                     $categorycell = new html_table_cell();
754                     $categorycell->attributes['class'] = 'category ' . $catlevel;
755                     $categorycell->colspan = $colspan;
756                     $categorycell->text = shorten_text($element['object']->get_name());
757                     $categorycell->text .= $this->get_collapsing_icon($element);
758                     $categorycell->header = true;
759                     $categorycell->scope = 'col';
761                     // Print icons
762                     if ($USER->gradeediting[$this->courseid]) {
763                         $categorycell->text .= $this->get_icons($element);
764                     }
766                     $headingrow->cells[] = $categorycell;
767                 }
768 // Element is a grade_item
769                 else {
770                     //$itemmodule = $element['object']->itemmodule;
771                     //$iteminstance = $element['object']->iteminstance;
773                     if ($element['object']->id == $this->sortitemid) {
774                         if ($this->sortorder == 'ASC') {
775                             $arrow = $this->get_sort_arrow('up', $sortlink);
776                         } else {
777                             $arrow = $this->get_sort_arrow('down', $sortlink);
778                         }
779                     } else {
780                         $arrow = $this->get_sort_arrow('move', $sortlink);
781                     }
783                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
785                     $itemcell = new html_table_cell();
786                     $itemcell->attributes['class'] = $type . ' ' . $catlevel . ' highlightable'. ' i'. $element['object']->id;
788                     if ($element['object']->is_hidden()) {
789                         $itemcell->attributes['class'] .= ' dimmed_text';
790                     }
792                     $itemcell->colspan = $colspan;
793                     $itemcell->text = shorten_text($headerlink) . $arrow;
794                     $itemcell->header = true;
795                     $itemcell->scope = 'col';
797                     $headingrow->cells[] = $itemcell;
798                 }
799             }
800             $rows[] = $headingrow;
801         }
803         $rows = $this->get_right_icons_row($rows);
805         // Preload scale objects for items with a scaleid and initialize tab indices
806         $scaleslist = array();
807         $tabindices = array();
809         foreach ($this->gtree->get_items() as $itemid=>$item) {
810             $scale = null;
811             if (!empty($item->scaleid)) {
812                 $scaleslist[] = $item->scaleid;
813                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
814             } else {
815                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
816             }
817             $tabindices[$item->id]['grade'] = $gradetabindex;
818             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
819             $gradetabindex += $numusers * 2;
820         }
821         $scalesarray = array();
823         if (!empty($scaleslist)) {
824             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
825         }
826         $jsscales = $scalesarray;
828         $rowclasses = array('even', 'odd');
830         foreach ($this->users as $userid => $user) {
832             if ($this->canviewhidden) {
833                 $altered = array();
834                 $unknown = array();
835             } else {
836                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
837                 $altered = $hidingaffected['altered'];
838                 $unknown = $hidingaffected['unknown'];
839                 unset($hidingaffected);
840             }
843             $itemrow = new html_table_row();
844             $itemrow->id = 'user_'.$userid;
845             $itemrow->attributes['class'] = $rowclasses[$this->rowcount % 2];
847             $jsarguments['users'][$userid] = fullname($user);
849             foreach ($this->gtree->items as $itemid=>$unused) {
850                 $item =& $this->gtree->items[$itemid];
851                 $grade = $this->grades[$userid][$item->id];
853                 $itemcell = new html_table_cell();
855                 $itemcell->id = 'u'.$userid.'i'.$itemid;
857                 // Get the decimal points preference for this item
858                 $decimalpoints = $item->get_decimals();
860                 if (in_array($itemid, $unknown)) {
861                     $gradeval = null;
862                 } else if (array_key_exists($itemid, $altered)) {
863                     $gradeval = $altered[$itemid];
864                 } else {
865                     $gradeval = $grade->finalgrade;
866                 }
867                 if (!empty($grade->finalgrade)) {
868                     $gradevalforJS = null;
869                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
870                         $gradevalforJS = (int)$gradeval;
871                     } else {
872                         $gradevalforJS = format_float($gradeval, $decimalpoints);
873                     }
874                     $jsarguments['grades'][] = array('user'=>$userid, 'item'=>$itemid, 'grade'=>$gradevalforJS);
875                 }
877                 // MDL-11274
878                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
879                 if (!$this->canviewhidden and $grade->is_hidden()) {
880                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
881                         // 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
882                         $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
883                     } else {
884                         $itemcell->text = '-';
885                     }
886                     $itemrow->cells[] = $itemcell;
887                     continue;
888                 }
890                 // emulate grade element
891                 $eid = $this->gtree->get_grade_eid($grade);
892                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
894                 $itemcell->attributes['class'] .= ' grade i'.$itemid;
895                 if ($item->is_category_item()) {
896                     $itemcell->attributes['class'] .= ' cat';
897                 }
898                 if ($item->is_course_item()) {
899                     $itemcell->attributes['class'] .= ' course';
900                 }
901                 if ($grade->is_overridden()) {
902                     $itemcell->attributes['class'] .= ' overridden';
903                 }
905                 if ($grade->is_excluded()) {
906                     // $itemcell->attributes['class'] .= ' excluded';
907                 }
909                 if (!empty($grade->feedback)) {
910                     //should we be truncating feedback? ie $short_feedback = shorten_text($feedback, $this->feedback_trunc_length);
911                     $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
912                 }
914                 if ($grade->is_excluded()) {
915                     $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
916                 }
918                 // Do not show any icons if no grade (no record in DB to match)
919                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
920                     $itemcell->text .= $this->get_icons($element);
921                 }
923                 $hidden = '';
924                 if ($grade->is_hidden()) {
925                     $hidden = ' hidden ';
926                 }
928                 $gradepass = ' gradefail ';
929                 if ($grade->is_passed($item)) {
930                     $gradepass = ' gradepass ';
931                 } elseif (is_null($grade->is_passed($item))) {
932                     $gradepass = '';
933                 }
935                 // if in editing mode, we need to print either a text box
936                 // or a drop down (for scales)
937                 // grades in item of type grade category or course are not directly editable
938                 if ($item->needsupdate) {
939                     $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
941                 } else if ($USER->gradeediting[$this->courseid]) {
943                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
944                         $scale = $scalesarray[$item->scaleid];
945                         $gradeval = (int)$gradeval; // scales use only integers
946                         $scales = explode(",", $scale->scale);
947                         // reindex because scale is off 1
949                         // MDL-12104 some previous scales might have taken up part of the array
950                         // so this needs to be reset
951                         $scaleopt = array();
952                         $i = 0;
953                         foreach ($scales as $scaleoption) {
954                             $i++;
955                             $scaleopt[$i] = $scaleoption;
956                         }
958                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
959                             $oldval = empty($gradeval) ? -1 : $gradeval;
960                             if (empty($item->outcomeid)) {
961                                 $nogradestr = $this->get_lang_string('nograde');
962                             } else {
963                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
964                             }
965                             $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
966                             $itemcell->text .= html_writer::label(get_string('typescale', 'grades'), $attributes['id'], false, array('class' => 'accesshide'));
967                             $itemcell->text .= html_writer::select($scaleopt, 'grade['.$userid.']['.$item->id.']', $gradeval, array(-1=>$nogradestr), $attributes);
968                         } elseif(!empty($scale)) {
969                             $scales = explode(",", $scale->scale);
971                             // invalid grade if gradeval < 1
972                             if ($gradeval < 1) {
973                                 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
974                             } else {
975                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
976                                 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
977                             }
978                         } else {
979                             // no such scale, throw error?
980                         }
982                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
983                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
984                             $value = format_float($gradeval, $decimalpoints);
985                             $gradelabel = fullname($user) . ' ' . $item->itemname;
986                             $itemcell->text .= '<label class="accesshide" for="grade_'.$userid.'_'.$item->id.'">'
987                                           .get_string('useractivitygrade', 'gradereport_grader', $gradelabel).'</label>';
988                             $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
989                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade['
990                                           .$userid.'][' .$item->id.']" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
991                         } else {
992                             $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
993                         }
994                     }
997                     // If quickfeedback is on, print an input element
998                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
999                         $feedbacklabel = fullname($user) . ' ' . $item->itemname;
1000                         $itemcell->text .= '<label class="accesshide" for="feedback_'.$userid.'_'.$item->id.'">'
1001                                       .get_string('useractivityfeedback', 'gradereport_grader', $feedbacklabel).'</label>';
1002                         $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
1003                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback['.$userid.']['.$item->id.']" value="' . s($grade->feedback) . '" />';
1004                     }
1006                 } else { // Not editing
1007                     $gradedisplaytype = $item->get_displaytype();
1009                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
1010                         $itemcell->attributes['class'] .= ' grade_type_scale';
1011                     } else if ($item->gradetype != GRADE_TYPE_TEXT) {
1012                         $itemcell->attributes['class'] .= ' grade_type_text';
1013                     }
1015                     if ($this->get_pref('enableajax')) {
1016                         $itemcell->attributes['class'] .= ' clickable';
1017                     }
1019                     if ($item->needsupdate) {
1020                         $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
1021                     } else {
1022                         $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
1023                         if ($this->get_pref('showanalysisicon')) {
1024                             $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
1025                         }
1026                     }
1027                 }
1029                 if (!empty($this->gradeserror[$item->id][$userid])) {
1030                     $itemcell->text .= $this->gradeserror[$item->id][$userid];
1031                 }
1033                 $itemrow->cells[] = $itemcell;
1034             }
1035             $rows[] = $itemrow;
1036         }
1038         if ($this->get_pref('enableajax')) {
1039             $jsarguments['cfg']['ajaxenabled'] = true;
1040             $jsarguments['cfg']['scales'] = array();
1041             foreach ($jsscales as $scale) {
1042                 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
1043             }
1044             $jsarguments['cfg']['feedbacktrunclength'] =  $this->feedback_trunc_length;
1046             // Student grades and feedback are already at $jsarguments['feedback'] and $jsarguments['grades']
1047         }
1048         $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
1049         $jsarguments['cfg']['courseid'] =  $this->courseid;
1050         $jsarguments['cfg']['studentsperpage'] =  $this->get_students_per_page();
1051         $jsarguments['cfg']['showquickfeedback'] =  (bool)$this->get_pref('showquickfeedback');
1053         $module = array(
1054             'name'      => 'gradereport_grader',
1055             'fullpath'  => '/grade/report/grader/module.js',
1056             'requires'  => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
1057         );
1058         $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1059         $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
1060         $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1062         $rows = $this->get_right_range_row($rows);
1063         $rows = $this->get_right_avg_row($rows, true);
1064         $rows = $this->get_right_avg_row($rows);
1066         return $rows;
1067     }
1069     /**
1070      * Depending on the style of report (fixedstudents vs traditional one-table),
1071      * arranges the rows of data in one or two tables, and returns the output of
1072      * these tables in HTML
1073      * @return string HTML
1074      */
1075     public function get_grade_table() {
1076         global $OUTPUT;
1077         $fixedstudents = $this->is_fixed_students();
1079         $leftrows = $this->get_left_rows();
1080         $rightrows = $this->get_right_rows();
1082         $html = '';
1085         if ($fixedstudents) {
1086             $fixedcolumntable = new html_table();
1087             $fixedcolumntable->id = 'fixed_column';
1088             $fixedcolumntable->data = $leftrows;
1089             $html .= $OUTPUT->container(html_writer::table($fixedcolumntable), 'left_scroller');
1091             $righttable = new html_table();
1092             $righttable->id = 'user-grades';
1093             $righttable->data = $rightrows;
1095             $html .= $OUTPUT->container(html_writer::table($righttable), 'right_scroller');
1096         } else {
1097             $fulltable = new html_table();
1098             $fulltable->attributes['class'] = 'gradestable flexible boxaligncenter generaltable';
1099             $fulltable->id = 'user-grades';
1101             // Extract rows from each side (left and right) and collate them into one row each
1102             foreach ($leftrows as $key => $row) {
1103                 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1104                 $fulltable->data[] = $row;
1105             }
1106             $html .= html_writer::table($fulltable);
1107         }
1108         return $OUTPUT->container($html, 'gradeparent');
1109     }
1111     /**
1112      * Builds and return the row of icons for the left side of the report.
1113      * It only has one cell that says "Controls"
1114      * @param array $rows The Array of rows for the left part of the report
1115      * @param int $colspan The number of columns this cell has to span
1116      * @return array Array of rows for the left part of the report
1117      */
1118     public function get_left_icons_row($rows=array(), $colspan=1) {
1119         global $USER;
1121         if ($USER->gradeediting[$this->courseid]) {
1122             $controlsrow = new html_table_row();
1123             $controlsrow->attributes['class'] = 'controls';
1124             $controlscell = new html_table_cell();
1125             $controlscell->attributes['class'] = 'header controls';
1126             $controlscell->colspan = $colspan;
1127             $controlscell->text = $this->get_lang_string('controls','grades');
1129             $controlsrow->cells[] = $controlscell;
1130             $rows[] = $controlsrow;
1131         }
1132         return $rows;
1133     }
1135     /**
1136      * Builds and return the header for the row of ranges, for the left part of the grader report.
1137      * @param array $rows The Array of rows for the left part of the report
1138      * @param int $colspan The number of columns this cell has to span
1139      * @return array Array of rows for the left part of the report
1140      */
1141     public function get_left_range_row($rows=array(), $colspan=1) {
1142         global $CFG, $USER;
1144         if ($this->get_pref('showranges')) {
1145             $rangerow = new html_table_row();
1146             $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1147             $rangecell = new html_table_cell();
1148             $rangecell->attributes['class'] = 'header range';
1149             $rangecell->colspan = $colspan;
1150             $rangecell->header = true;
1151             $rangecell->scope = 'row';
1152             $rangecell->text = $this->get_lang_string('range','grades');
1153             $rangerow->cells[] = $rangecell;
1154             $rows[] = $rangerow;
1155         }
1157         return $rows;
1158     }
1160     /**
1161      * Builds and return the headers for the rows of averages, for the left part of the grader report.
1162      * @param array $rows The Array of rows for the left part of the report
1163      * @param int $colspan The number of columns this cell has to span
1164      * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1165      * @return array Array of rows for the left part of the report
1166      */
1167     public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1168         if (!$this->canviewhidden) {
1169             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1170             // better not show them at all if user can not see all hideen grades
1171             return $rows;
1172         }
1174         $showaverages = $this->get_pref('showaverages');
1175         $showaveragesgroup = $this->currentgroup && $showaverages;
1176         $straveragegroup = get_string('groupavg', 'grades');
1178         if ($groupavg) {
1179             if ($showaveragesgroup) {
1180                 $groupavgrow = new html_table_row();
1181                 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1182                 $groupavgcell = new html_table_cell();
1183                 $groupavgcell->attributes['class'] = 'header range';
1184                 $groupavgcell->colspan = $colspan;
1185                 $groupavgcell->header = true;
1186                 $groupavgcell->scope = 'row';
1187                 $groupavgcell->text = $straveragegroup;
1188                 $groupavgrow->cells[] = $groupavgcell;
1189                 $rows[] = $groupavgrow;
1190             }
1191         } else {
1192             $straverage = get_string('overallaverage', 'grades');
1194             if ($showaverages) {
1195                 $avgrow = new html_table_row();
1196                 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1197                 $avgcell = new html_table_cell();
1198                 $avgcell->attributes['class'] = 'header range';
1199                 $avgcell->colspan = $colspan;
1200                 $avgcell->header = true;
1201                 $avgcell->scope = 'row';
1202                 $avgcell->text = $straverage;
1203                 $avgrow->cells[] = $avgcell;
1204                 $rows[] = $avgrow;
1205             }
1206         }
1208         return $rows;
1209     }
1211     /**
1212      * Builds and return the row of icons when editing is on, for the right part of the grader report.
1213      * @param array $rows The Array of rows for the right part of the report
1214      * @return array Array of rows for the right part of the report
1215      */
1216     public function get_right_icons_row($rows=array()) {
1217         global $USER;
1218         if ($USER->gradeediting[$this->courseid]) {
1219             $iconsrow = new html_table_row();
1220             $iconsrow->attributes['class'] = 'controls';
1222             foreach ($this->gtree->items as $itemid=>$unused) {
1223                 // emulate grade element
1224                 $item = $this->gtree->get_item($itemid);
1226                 $eid = $this->gtree->get_item_eid($item);
1227                 $element = $this->gtree->locate_element($eid);
1228                 $itemcell = new html_table_cell();
1229                 $itemcell->attributes['class'] = 'controls icons i'.$itemid;
1230                 $itemcell->text = $this->get_icons($element);
1231                 $iconsrow->cells[] = $itemcell;
1232             }
1233             $rows[] = $iconsrow;
1234         }
1235         return $rows;
1236     }
1238     /**
1239      * Builds and return the row of ranges for the right part of the grader report.
1240      * @param array $rows The Array of rows for the right part of the report
1241      * @return array Array of rows for the right part of the report
1242      */
1243     public function get_right_range_row($rows=array()) {
1244         global $OUTPUT;
1246         if ($this->get_pref('showranges')) {
1247             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1248             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1249             $rangerow = new html_table_row();
1250             $rangerow->attributes['class'] = 'heading range';
1252             foreach ($this->gtree->items as $itemid=>$unused) {
1253                 $item =& $this->gtree->items[$itemid];
1254                 $itemcell = new html_table_cell();
1255                 $itemcell->attributes['class'] .= ' range i'. $itemid;
1257                 $hidden = '';
1258                 if ($item->is_hidden()) {
1259                     $hidden = ' hidden ';
1260                 }
1262                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1264                 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1265                 $rangerow->cells[] = $itemcell;
1266             }
1267             $rows[] = $rangerow;
1268         }
1269         return $rows;
1270     }
1272     /**
1273      * Builds and return the row of averages for the right part of the grader report.
1274      * @param array $rows Whether to return only group averages or all averages.
1275      * @param bool $grouponly Whether to return only group averages or all averages.
1276      * @return array Array of rows for the right part of the report
1277      */
1278     public function get_right_avg_row($rows=array(), $grouponly=false) {
1279         global $USER, $DB, $OUTPUT;
1281         if (!$this->canviewhidden) {
1282             // Totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1283             // better not show them at all if user can not see all hidden grades.
1284             return $rows;
1285         }
1287         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1288         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1289         $meanselection         = $this->get_pref('meanselection');
1290         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1292         if ($grouponly) {
1293             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1294             $groupsql = $this->groupsql;
1295             $groupwheresql = $this->groupwheresql;
1296             $groupwheresqlparams = $this->groupwheresql_params;
1297         } else {
1298             $showaverages = $this->get_pref('showaverages');
1299             $groupsql = "";
1300             $groupwheresql = "";
1301             $groupwheresqlparams = array();
1302         }
1304         if ($showaverages) {
1305             $totalcount = $this->get_numusers($grouponly);
1307             // Limit to users with a gradeable role.
1308             list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1310             // Limit to users with an active enrollment.
1311             list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
1313             // We want to query both the current context and parent contexts.
1314             list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
1316             $params = array_merge(array('courseid' => $this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams, $relatedctxparams);
1318             // Find sums of all grade items in course.
1319             $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1320                       FROM {grade_items} gi
1321                       JOIN {grade_grades} g ON g.itemid = gi.id
1322                       JOIN {user} u ON u.id = g.userid
1323                       JOIN ($enrolledsql) je ON je.id = u.id
1324                       JOIN (
1325                                SELECT DISTINCT ra.userid
1326                                  FROM {role_assignments} ra
1327                                 WHERE ra.roleid $gradebookrolessql
1328                                   AND ra.contextid $relatedctxsql
1329                            ) rainner ON rainner.userid = u.id
1330                       $groupsql
1331                      WHERE gi.courseid = :courseid
1332                        AND u.deleted = 0
1333                        AND g.finalgrade IS NOT NULL
1334                        $groupwheresql
1335                      GROUP BY g.itemid";
1336             $sumarray = array();
1337             if ($sums = $DB->get_records_sql($sql, $params)) {
1338                 foreach ($sums as $itemid => $csum) {
1339                     $sumarray[$itemid] = $csum->sum;
1340                 }
1341             }
1343             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1344             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1345             $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1346                       FROM {grade_items} gi
1347                       CROSS JOIN {user} u
1348                       JOIN ($enrolledsql) je
1349                            ON je.id = u.id
1350                       JOIN {role_assignments} ra
1351                            ON ra.userid = u.id
1352                       LEFT OUTER JOIN {grade_grades} g
1353                            ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1354                       $groupsql
1355                      WHERE gi.courseid = :courseid
1356                            AND ra.roleid $gradebookrolessql
1357                            AND ra.contextid $relatedctxsql
1358                            AND u.deleted = 0
1359                            AND g.id IS NULL
1360                            $groupwheresql
1361                   GROUP BY gi.id";
1363             $ungradedcounts = $DB->get_records_sql($sql, $params);
1365             $avgrow = new html_table_row();
1366             $avgrow->attributes['class'] = 'avg';
1368             foreach ($this->gtree->items as $itemid=>$unused) {
1369                 $item =& $this->gtree->items[$itemid];
1371                 if ($item->needsupdate) {
1372                     $avgcell = new html_table_cell();
1373                     $avgcell->attributes['class'] = 'i'. $itemid;
1374                     $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1375                     $avgrow->cells[] = $avgcell;
1376                     continue;
1377                 }
1379                 if (!isset($sumarray[$item->id])) {
1380                     $sumarray[$item->id] = 0;
1381                 }
1383                 if (empty($ungradedcounts[$itemid])) {
1384                     $ungradedcount = 0;
1385                 } else {
1386                     $ungradedcount = $ungradedcounts[$itemid]->count;
1387                 }
1389                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1390                     $meancount = $totalcount - $ungradedcount;
1391                 } else { // Bump up the sum by the number of ungraded items * grademin
1392                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1393                     $meancount = $totalcount;
1394                 }
1396                 // Determine which display type to use for this average
1397                 if ($USER->gradeediting[$this->courseid]) {
1398                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1400                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1401                     $displaytype = $item->get_displaytype();
1403                 } else {
1404                     $displaytype = $averagesdisplaytype;
1405                 }
1407                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1408                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1409                     $decimalpoints = $item->get_decimals();
1411                 } else {
1412                     $decimalpoints = $averagesdecimalpoints;
1413                 }
1415                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1416                     $avgcell = new html_table_cell();
1417                     $avgcell->attributes['class'] = 'i'. $itemid;
1418                     $avgcell->text = '-';
1419                     $avgrow->cells[] = $avgcell;
1421                 } else {
1422                     $sum = $sumarray[$item->id];
1423                     $avgradeval = $sum/$meancount;
1424                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1426                     $numberofgrades = '';
1427                     if ($shownumberofgrades) {
1428                         $numberofgrades = " ($meancount)";
1429                     }
1431                     $avgcell = new html_table_cell();
1432                     $avgcell->attributes['class'] = 'i'. $itemid;
1433                     $avgcell->text = $gradehtml.$numberofgrades;
1434                     $avgrow->cells[] = $avgcell;
1435                 }
1436             }
1437             $rows[] = $avgrow;
1438         }
1439         return $rows;
1440     }
1442     /**
1443      * Given a grade_category, grade_item or grade_grade, this function
1444      * figures out the state of the object and builds then returns a div
1445      * with the icons needed for the grader report.
1446      *
1447      * @param array $object
1448      * @return string HTML
1449      */
1450     protected function get_icons($element) {
1451         global $CFG, $USER, $OUTPUT;
1453         if (!$USER->gradeediting[$this->courseid]) {
1454             return '<div class="grade_icons" />';
1455         }
1457         // Init all icons
1458         $editicon = '';
1460         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1461             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1462         }
1464         $editcalculationicon = '';
1465         $showhideicon        = '';
1466         $lockunlockicon      = '';
1468         if (has_capability('moodle/grade:manage', $this->context)) {
1469             if ($this->get_pref('showcalculations')) {
1470                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1471             }
1473             if ($this->get_pref('showeyecons')) {
1474                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1475             }
1477             if ($this->get_pref('showlocks')) {
1478                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1479             }
1481         }
1483         $gradeanalysisicon   = '';
1484         if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1485             $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1486         }
1488         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1489     }
1491     /**
1492      * Given a category element returns collapsing +/- icon if available
1493      * @param object $object
1494      * @return string HTML
1495      */
1496     protected function get_collapsing_icon($element) {
1497         global $OUTPUT;
1499         $icon = '';
1500         // If object is a category, display expand/contract icon
1501         if ($element['type'] == 'category') {
1502             // Load language strings
1503             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1504             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1505             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1507             $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
1509             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1510                 $url->param('action', 'switch_plus');
1511                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
1513             } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1514                 $url->param('action', 'switch_whole');
1515                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
1517             } else {
1518                 $url->param('action', 'switch_minus');
1519                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
1520             }
1521         }
1522         return $icon;
1523     }
1525     public function process_action($target, $action) {
1526         return self::do_process_action($target, $action);
1527     }
1529     /**
1530      * Processes a single action against a category, grade_item or grade.
1531      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1532      * @param string $action Which action to take (edit, delete etc...)
1533      * @return
1534      */
1535     public static function do_process_action($target, $action) {
1536         // TODO: this code should be in some grade_tree static method
1537         $targettype = substr($target, 0, 1);
1538         $targetid = substr($target, 1);
1539         // TODO: end
1541         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1542             $collapsed = unserialize($collapsed);
1543         } else {
1544             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1545         }
1547         switch ($action) {
1548             case 'switch_minus': // Add category to array of aggregatesonly
1549                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1550                     $collapsed['aggregatesonly'][] = $targetid;
1551                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1552                 }
1553                 break;
1555             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1556                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1557                 if ($key !== false) {
1558                     unset($collapsed['aggregatesonly'][$key]);
1559                 }
1560                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1561                     $collapsed['gradesonly'][] = $targetid;
1562                 }
1563                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1564                 break;
1565             case 'switch_whole': // Remove the category from the array of collapsed cats
1566                 $key = array_search($targetid, $collapsed['gradesonly']);
1567                 if ($key !== false) {
1568                     unset($collapsed['gradesonly'][$key]);
1569                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1570                 }
1572                 break;
1573             default:
1574                 break;
1575         }
1577         return true;
1578     }
1580     /**
1581      * Returns whether or not to display fixed students column.
1582      * Includes a browser check, because IE6 doesn't support the scrollbar.
1583      *
1584      * @return bool
1585      */
1586     public function is_fixed_students() {
1587         global $CFG;
1589         return $CFG->grade_report_fixedstudents;
1590     }
1592     /**
1593      * Refactored function for generating HTML of sorting links with matching arrows.
1594      * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1595      * to inject into a table header cell.
1596      * @param array $extrafields Array of extra fields being displayed, such as
1597      *   user idnumber
1598      * @return array An associative array of HTML sorting links+arrows
1599      */
1600     public function get_sort_arrows(array $extrafields = array()) {
1601         global $OUTPUT;
1602         $arrows = array();
1604         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
1605         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
1606         $strfirstname = $this->get_lang_string('firstname');
1607         $strlastname  = $this->get_lang_string('lastname');
1608         $iconasc = $OUTPUT->pix_icon('t/sort_asc', $strsortasc, '', array('class' => 'iconsmall sorticon'));
1609         $icondesc = $OUTPUT->pix_icon('t/sort_desc', $strsortdesc, '', array('class' => 'iconsmall sorticon'));
1611         $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1612         $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
1614         $arrows['studentname'] = $lastlink;
1616         if ($this->sortitemid === 'lastname') {
1617             if ($this->sortorder == 'ASC') {
1618                 $arrows['studentname'] .= $iconasc;
1619             } else {
1620                 $arrows['studentname'] .= $icondesc;
1621             }
1622         }
1624         $arrows['studentname'] .= ' ' . $firstlink;
1626         if ($this->sortitemid === 'firstname') {
1627             if ($this->sortorder == 'ASC') {
1628                 $arrows['studentname'] .= $iconasc;
1629             } else {
1630                 $arrows['studentname'] .= $icondesc;
1631             }
1632         }
1634         foreach ($extrafields as $field) {
1635             $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1636                     array('sortitemid'=>$field)), get_user_field_name($field));
1637             $arrows[$field] = $fieldlink;
1639             if ($field == $this->sortitemid) {
1640                 if ($this->sortorder == 'ASC') {
1641                     $arrows[$field] .= $iconasc;
1642                 } else {
1643                     $arrows[$field] .= $icondesc;
1644                 }
1645             }
1646         }
1648         return $arrows;
1649     }
1651     /**
1652      * Returns the maximum number of students to be displayed on each page
1653      *
1654      * Takes into account the 'studentsperpage' user preference and the 'max_input_vars'
1655      * PHP setting. Too many fields is only a problem when submitting grades but
1656      * we respect 'max_input_vars' even when viewing grades to prevent students disappearing
1657      * when toggling editing on and off.
1658      *
1659      * @return int The maximum number of students to display per page
1660      */
1661     public function get_students_per_page() {
1662         global $USER;
1663         static $studentsperpage = null;
1665         if ($studentsperpage === null) {
1666             $originalstudentsperpage = $studentsperpage = $this->get_pref('studentsperpage');
1668             // Will this number of students result in more fields that we are allowed?
1669             $maxinputvars = ini_get('max_input_vars');
1670             if ($maxinputvars !== false) {
1671                 // We can't do anything about there being more grade items than max_input_vars,
1672                 // but we can decrease number of students per page if there are >= max_input_vars
1673                 $fieldsperstudent = 0; // The number of fields output per student
1675                 if ($this->get_pref('quickgrading') || $this->get_pref('showquickfeedback')) {
1676                     // Each array (grade, feedback) will gain one element
1677                     $fieldsperstudent ++;
1678                 }
1680                 $fieldsrequired = $studentsperpage * $fieldsperstudent;
1681                 if ($fieldsrequired >= $maxinputvars) {
1682                     $studentsperpage = $maxinputvars - 1; // Subtract one to be on the safe side
1683                     if ($studentsperpage<1) {
1684                         // Make sure students per page doesn't fall below 1, though if your
1685                         // max_input_vars is only 1 you've got bigger problems!
1686                         $studentsperpage = 1;
1687                     }
1689                     $a = new stdClass();
1690                     $a->originalstudentsperpage = $originalstudentsperpage;
1691                     $a->studentsperpage = $studentsperpage;
1692                     $a->maxinputvars = $maxinputvars;
1693                     debugging(get_string('studentsperpagereduced', 'grades', $a));
1694                 }
1695             }
1696         }
1698         return $studentsperpage;
1699     }