MDL-35984 grade: Add behat tests for grade aggregations
[moodle.git] / grade / report / lib.php
CommitLineData
e060e33d 1<?php
e060e33d 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/>.
8ad36f4c 16
38b9e8a8 17/**
a153c9f2
AD
18 * File containing the grade_report class
19 *
20 * @package core_grades
21 * @copyright 2007 Moodle Pty Ltd (http://moodle.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38b9e8a8 23 */
eea6690a 24
25require_once($CFG->libdir.'/gradelib.php');
26
27/**
28 * An abstract class containing variables and methods used by all or most reports.
02d1a0a5
MA
29 * @copyright 2007 Moodle Pty Ltd (http://moodle.com)
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
eea6690a 31 */
d24832f9 32abstract class grade_report {
eea6690a 33 /**
34 * The courseid.
35 * @var int $courseid
36 */
d24832f9 37 public $courseid;
eea6690a 38
b2bc96d1 39 /**
40 * The course.
41 * @var object $course
42 */
d24832f9 43 public $course;
b2bc96d1 44
d30c4481 45 /** Grade plugin return tracking object.
4889285b 46 * @var object $gpr
47 */
48 public $gpr;
d30c4481 49
eea6690a 50 /**
51 * The context.
52 * @var int $context
53 */
d24832f9 54 public $context;
eea6690a 55
56 /**
57 * The grade_tree object.
58 * @var object $gtree
59 */
d24832f9 60 public $gtree;
eea6690a 61
62 /**
63 * User preferences related to this report.
e50ce569 64 * @var array $prefs
eea6690a 65 */
d24832f9 66 public $prefs = array();
eea6690a 67
68 /**
69 * The roles for this report.
70 * @var string $gradebookroles
71 */
d24832f9 72 public $gradebookroles;
eea6690a 73
74 /**
75 * base url for sorting by first/last name.
76 * @var string $baseurl
77 */
d24832f9 78 public $baseurl;
eea6690a 79
80 /**
81 * base url for paging.
82 * @var string $pbarurl
83 */
d24832f9 84 public $pbarurl;
eea6690a 85
86 /**
87 * Current page (for paging).
88 * @var int $page
89 */
d24832f9 90 public $page;
eea6690a 91
388234f4 92 /**
93 * Array of cached language strings (using get_string() all the time takes a long time!).
94 * @var array $lang_strings
95 */
d24832f9 96 public $lang_strings = array();
388234f4 97
02d1a0a5 98 // GROUP VARIABLES (including SQL)
90d3960c 99
100 /**
101 * The current group being displayed.
102 * @var int $currentgroup
103 */
d24832f9 104 public $currentgroup;
90d3960c 105
cbe8e5b3
MA
106 /**
107 * The current groupname being displayed.
108 * @var string $currentgroupname
109 */
110 public $currentgroupname;
111
35079f53 112 /**
113 * Current course group mode
114 * @var int $groupmode
115 */
02d1a0a5 116 public $groupmode;
35079f53 117
90d3960c 118 /**
119 * A HTML select element used to select the current group.
120 * @var string $group_selector
121 */
d24832f9 122 public $group_selector;
90d3960c 123
124 /**
125 * An SQL fragment used to add linking information to the group tables.
126 * @var string $groupsql
127 */
d24832f9 128 protected $groupsql;
90d3960c 129
130 /**
131 * An SQL constraint to append to the queries used by this object to build the report.
132 * @var string $groupwheresql
133 */
d24832f9 134 protected $groupwheresql;
135
136 /**
137 * The ordered params for $groupwheresql
138 * @var array $groupwheresql_params
139 */
140 protected $groupwheresql_params = array();
90d3960c 141
41877849 142 // USER VARIABLES (including SQL).
8e4bf6cc
MA
143
144 /**
145 * An SQL constraint to append to the queries used by this object to build the report.
146 * @var string $userwheresql
147 */
148 protected $userwheresql;
149
150 /**
151 * The ordered params for $userwheresql
152 * @var array $userwheresql_params
153 */
154 protected $userwheresql_params = array();
90d3960c 155
eea6690a 156 /**
157 * Constructor. Sets local copies of user preferences and initialises grade_tree.
158 * @param int $courseid
d30c4481 159 * @param object $gpr grade plugin return tracking object
eea6690a 160 * @param string $context
161 * @param int $page The current page being viewed (when report is paged)
162 */
d24832f9 163 public function __construct($courseid, $gpr, $context, $page=null) {
5c75a0a3 164 global $CFG, $COURSE, $DB;
eea6690a 165
dde8e548 166 if (empty($CFG->gradebookroles)) {
771dc7b2 167 print_error('norolesdefined', 'grades');
0893aa30 168 }
284abb09 169
4faf5f99 170 $this->courseid = $courseid;
b2bc96d1 171 if ($this->courseid == $COURSE->id) {
172 $this->course = $COURSE;
173 } else {
5c75a0a3 174 $this->course = $DB->get_record('course', array('id' => $this->courseid));
b2bc96d1 175 }
41f22daa 176
4faf5f99 177 $this->gpr = $gpr;
178 $this->context = $context;
179 $this->page = $page;
eea6690a 180
181 // roles to be displayed in the gradebook
182 $this->gradebookroles = $CFG->gradebookroles;
183
dc482cfa 184 // Set up link to preferences page
185 $this->preferences_page = $CFG->wwwroot.'/grade/report/grader/preferences.php?id='.$courseid;
186
4faf5f99 187 // init gtree in child class
38b9e8a8 188 }
189
eea6690a 190 /**
191 * Given the name of a user preference (without grade_report_ prefix), locally saves then returns
192 * the value of that preference. If the preference has already been fetched before,
193 * the saved value is returned. If the preference is not set at the User level, the $CFG equivalent
194 * is given (site default).
02d1a0a5 195 * Can be called statically, but then doesn't benefit from caching
eea6690a 196 * @param string $pref The name of the preference (do not include the grade_report_ prefix)
8c5a416e 197 * @param int $objectid An optional itemid or categoryid to check for a more fine-grained preference
eea6690a 198 * @return mixed The value of the preference
199 */
d24832f9 200 public function get_pref($pref, $objectid=null) {
eea6690a 201 global $CFG;
501e0e34 202 $fullprefname = 'grade_report_' . $pref;
54294d3b 203 $shortprefname = 'grade_' . $pref;
38b9e8a8 204
e50ce569 205 $retval = null;
206
438a5aa9 207 if (!isset($this) OR get_class($this) != 'grade_report') {
8c5a416e 208 if (!empty($objectid)) {
02d1a0a5
MA
209 $retval = get_user_preferences($fullprefname . $objectid, self::get_pref($pref));
210 } else if (isset($CFG->$fullprefname)) {
e50ce569 211 $retval = get_user_preferences($fullprefname, $CFG->$fullprefname);
02d1a0a5 212 } else if (isset($CFG->$shortprefname)) {
d24832f9 213 $retval = get_user_preferences($fullprefname, $CFG->$shortprefname);
54294d3b 214 } else {
215 $retval = null;
bb384a8e 216 }
501e0e34 217 } else {
8c5a416e 218 if (empty($this->prefs[$pref.$objectid])) {
e50ce569 219
8c5a416e 220 if (!empty($objectid)) {
221 $retval = get_user_preferences($fullprefname . $objectid);
e50ce569 222 if (empty($retval)) {
223 // No item pref found, we are returning the global preference
224 $retval = $this->get_pref($pref);
8c5a416e 225 $objectid = null;
e50ce569 226 }
501e0e34 227 } else {
e50ce569 228 $retval = get_user_preferences($fullprefname, $CFG->$fullprefname);
501e0e34 229 }
8c5a416e 230 $this->prefs[$pref.$objectid] = $retval;
e50ce569 231 } else {
8c5a416e 232 $retval = $this->prefs[$pref.$objectid];
501e0e34 233 }
eea6690a 234 }
e50ce569 235
236 return $retval;
eea6690a 237 }
bb384a8e 238
eea6690a 239 /**
501e0e34 240 * Uses set_user_preferences() to update the value of a user preference. If 'default' is given as the value,
241 * the preference will be removed in favour of a higher-level preference.
02d1a0a5 242 * @param string $pref The name of the preference.
eea6690a 243 * @param mixed $pref_value The value of the preference.
bb384a8e 244 * @param int $itemid An optional itemid to which the preference will be assigned
eea6690a 245 * @return bool Success or failure.
eea6690a 246 */
d24832f9 247 public function set_pref($pref, $pref_value='default', $itemid=null) {
bb384a8e 248 $fullprefname = 'grade_report_' . $pref;
501e0e34 249 if ($pref_value == 'default') {
250 return unset_user_preference($fullprefname.$itemid);
251 } else {
252 return set_user_preference($fullprefname.$itemid, $pref_value);
eea6690a 253 }
38b9e8a8 254 }
38b9e8a8 255
eea6690a 256 /**
257 * Handles form data sent by this report for this report. Abstract method to implement in all children.
258 * @abstract
259 * @param array $data
260 * @return mixed True or array of errors
261 */
02d1a0a5 262 abstract public function process_data($data);
38b9e8a8 263
eea6690a 264 /**
265 * Processes a single action against a category, grade_item or grade.
266 * @param string $target Sortorder
267 * @param string $action Which action to take (edit, delete etc...)
268 * @return
eea6690a 269 */
02d1a0a5 270 abstract public function process_action($target, $action);
eea6690a 271
388234f4 272 /**
273 * First checks the cached language strings, then returns match if found, or uses get_string()
274 * to get it from the DB, caches it then returns it.
275 * @param string $strcode
276 * @param string $section Optional language section
277 * @return string
278 */
d24832f9 279 public function get_lang_string($strcode, $section=null) {
388234f4 280 if (empty($this->lang_strings[$strcode])) {
281 $this->lang_strings[$strcode] = get_string($strcode, $section);
282 }
283 return $this->lang_strings[$strcode];
284 }
285
90d3960c 286 /**
287 * Fetches and returns a count of all the users that will be shown on this page.
28bcbc38 288 * @param boolean $groups include groups limit
8e4bf6cc 289 * @param boolean $users include users limit - default false, used for searching purposes
90d3960c 290 * @return int Count of users
291 */
8e4bf6cc
MA
292 public function get_numusers($groups = true, $users = false) {
293 global $CFG, $DB;
294 $userwheresql = "";
28bcbc38 295 $groupsql = "";
296 $groupwheresql = "";
387815db 297
4e829d48 298 // Limit to users with a gradeable role.
387815db 299 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
300
4e829d48 301 // Limit to users with an active enrollment.
387815db 302 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
303
4e829d48
MN
304 // We want to query both the current context and parent contexts.
305 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
306
307 $params = array_merge($gradebookrolesparams, $enrolledparams, $relatedctxparams);
d24832f9 308
8e4bf6cc
MA
309 if ($users) {
310 $userwheresql = $this->userwheresql;
311 $params = array_merge($params, $this->userwheresql_params);
312 }
313
28bcbc38 314 if ($groups) {
315 $groupsql = $this->groupsql;
bbadce53 316 $groupwheresql = $this->groupwheresql;
d24832f9 317 $params = array_merge($params, $this->groupwheresql_params);
28bcbc38 318 }
319
d5f6d9eb 320 $sql = "SELECT DISTINCT u.id
b50371da 321 FROM {user} u
25081b95
SH
322 JOIN ($enrolledsql) je
323 ON je.id = u.id
324 JOIN {role_assignments} ra
325 ON u.id = ra.userid
326 $groupsql
327 WHERE ra.roleid $gradebookrolessql
328 AND u.deleted = 0
8e4bf6cc 329 $userwheresql
b50371da 330 $groupwheresql
4e829d48 331 AND ra.contextid $relatedctxsql";
d5f6d9eb
MA
332 $selectedusers = $DB->get_records_sql($sql, $params);
333
334 $count = 0;
02d1a0a5 335 // Check if user's enrolment is active and should be displayed.
d5f6d9eb 336 if (!empty($selectedusers)) {
d5f6d9eb 337 $coursecontext = $this->context->get_course_context(true);
02d1a0a5
MA
338
339 $useractiveenrolments = get_enrolled_users($coursecontext, '', 0, 'u.*', null, 0, 0, true);
d5f6d9eb
MA
340
341 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
342 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
343 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
344
345 foreach ($selectedusers as $id => $value) {
346 if (!$showonlyactiveenrol || ($showonlyactiveenrol && array_key_exists($id, $useractiveenrolments))) {
347 $count++;
348 }
349 }
02d1a0a5 350 }
d5f6d9eb 351 return $count;
90d3960c 352 }
353
354 /**
355 * Sets up this object's group variables, mainly to restrict the selection of users to display.
356 */
0fd8bc00 357 protected function setup_groups() {
02d1a0a5 358 // find out current groups mode
35079f53 359 if ($this->groupmode = groups_get_course_groupmode($this->course)) {
7a9ba4b4 360 $this->currentgroup = groups_get_course_group($this->course, true);
35079f53 361 $this->group_selector = groups_print_course_menu($this->course, $this->pbarurl, true);
7a9ba4b4 362
363 if ($this->groupmode == SEPARATEGROUPS and !$this->currentgroup and !has_capability('moodle/site:accessallgroups', $this->context)) {
6ef4878b 364 $this->currentgroup = -2; // means can not access any groups at all
7a9ba4b4 365 }
35079f53 366
367 if ($this->currentgroup) {
cbe8e5b3 368 $group = groups_get_group($this->currentgroup);
02d1a0a5 369 $this->currentgroupname = $group->name;
35079f53 370 $this->groupsql = " JOIN {groups_members} gm ON gm.userid = u.id ";
371 $this->groupwheresql = " AND gm.groupid = :gr_grpid ";
372 $this->groupwheresql_params = array('gr_grpid'=>$this->currentgroup);
373 }
90d3960c 374 }
375 }
2e3987a9 376
02d1a0a5
MA
377 /**
378 * Sets up this report's user criteria to restrict the selection of users to display.
379 */
8e4bf6cc 380 public function setup_users() {
d1a4346f 381 global $SESSION, $DB;
02d1a0a5 382
8e4bf6cc
MA
383 $this->userwheresql = "";
384 $this->userwheresql_params = array();
02d1a0a5 385 if (isset($SESSION->gradereport['filterfirstname']) && !empty($SESSION->gradereport['filterfirstname'])) {
d1a4346f 386 $this->userwheresql .= ' AND '.$DB->sql_like('u.firstname', ':firstname', false, false);
02d1a0a5 387 $this->userwheresql_params['firstname'] = $SESSION->gradereport['filterfirstname'].'%';
8e4bf6cc 388 }
02d1a0a5 389 if (isset($SESSION->gradereport['filtersurname']) && !empty($SESSION->gradereport['filtersurname'])) {
d1a4346f 390 $this->userwheresql .= ' AND '.$DB->sql_like('u.lastname', ':lastname', false, false);
02d1a0a5 391 $this->userwheresql_params['lastname'] = $SESSION->gradereport['filtersurname'].'%';
8e4bf6cc
MA
392 }
393 }
394
2e3987a9 395 /**
396 * Returns an arrow icon inside an <a> tag, for the purpose of sorting a column.
397 * @param string $direction
02d1a0a5 398 * @param moodle_url $sortlink
2e3987a9 399 */
319770d7 400 protected function get_sort_arrow($direction='move', $sortlink=null) {
401 global $OUTPUT;
0cddd851 402 $pix = array('up' => 't/sort_desc', 'down' => 't/sort_asc', 'move' => 't/sort');
dc482cfa 403 $matrix = array('up' => 'desc', 'down' => 'asc', 'move' => 'desc');
2e3987a9 404 $strsort = $this->get_lang_string('sort' . $matrix[$direction]);
dc482cfa 405
0cddd851 406 $arrow = $OUTPUT->pix_icon($pix[$direction], $strsort, '', array('class' => 'sorticon'));
75015e5f 407 return html_writer::link($sortlink, $arrow, array('title'=>$strsort));
2e3987a9 408 }
61541a5a
AD
409
410 /**
411 * Optionally blank out course/category totals if they contain any hidden items
412 * @param string $courseid the course id
413 * @param string $course_item an instance of grade_item
414 * @param string $finalgrade the grade for the course_item
415 * @return string The new final grade
416 */
417 protected function blank_hidden_total($courseid, $course_item, $finalgrade) {
418 global $CFG, $DB;
419 static $hiding_affected = null;//array of items in this course affected by hiding
420
30dd9930 421 // If we're dealing with multiple users we need to know when we've moved on to a new user.
8eabc1d8
AD
422 static $previous_userid = null;
423
30dd9930
AD
424 // If we're dealing with multiple courses we need to know when we've moved on to a new course.
425 static $previous_courseid = null;
426
5df9bc39
AD
427 if (!is_array($this->showtotalsifcontainhidden)) {
428 debugging('showtotalsifcontainhidden should be an array', DEBUG_DEVELOPER);
429 $this->showtotalsifcontainhidden = array($courseid => $this->showtotalsifcontainhidden);
430 }
431
432 if ($this->showtotalsifcontainhidden[$courseid] == GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN) {
61541a5a
AD
433 return $finalgrade;
434 }
435
30dd9930
AD
436 // If we've moved on to another course or user, reload the grades.
437 if ($previous_userid != $this->user->id || $previous_courseid != $courseid) {
8eabc1d8
AD
438 $hiding_affected = null;
439 $previous_userid = $this->user->id;
30dd9930 440 $previous_courseid = $courseid;
8eabc1d8
AD
441 }
442
02d1a0a5 443 if (!$hiding_affected) {
61541a5a
AD
444 $items = grade_item::fetch_all(array('courseid'=>$courseid));
445 $grades = array();
446 $sql = "SELECT g.*
ffe50258
EL
447 FROM {grade_grades} g
448 JOIN {grade_items} gi ON gi.id = g.itemid
61541a5a
AD
449 WHERE g.userid = {$this->user->id} AND gi.courseid = {$courseid}";
450 if ($gradesrecords = $DB->get_records_sql($sql)) {
451 foreach ($gradesrecords as $grade) {
452 $grades[$grade->itemid] = new grade_grade($grade, false);
453 }
454 unset($gradesrecords);
455 }
02d1a0a5 456 foreach ($items as $itemid => $unused) {
61541a5a
AD
457 if (!isset($grades[$itemid])) {
458 $grade_grade = new grade_grade();
459 $grade_grade->userid = $this->user->id;
460 $grade_grade->itemid = $items[$itemid]->id;
461 $grades[$itemid] = $grade_grade;
462 }
463 $grades[$itemid]->grade_item =& $items[$itemid];
464 }
465 $hiding_affected = grade_grade::get_hiding_affected($grades, $items);
466 }
467
468 //if the item definitely depends on a hidden item
469 if (array_key_exists($course_item->id, $hiding_affected['altered'])) {
02d1a0a5 470 if (!$this->showtotalsifcontainhidden[$courseid]) {
61541a5a
AD
471 //hide the grade
472 $finalgrade = null;
02d1a0a5 473 } else {
61541a5a
AD
474 //use reprocessed marks that exclude hidden items
475 $finalgrade = $hiding_affected['altered'][$course_item->id];
476 }
477 } else if (!empty($hiding_affected['unknown'][$course_item->id])) {
478 //not sure whether or not this item depends on a hidden item
02d1a0a5 479 if (!$this->showtotalsifcontainhidden[$courseid]) {
61541a5a
AD
480 //hide the grade
481 $finalgrade = null;
02d1a0a5 482 } else {
61541a5a
AD
483 //use reprocessed marks that exclude hidden items
484 $finalgrade = $hiding_affected['unknown'][$course_item->id];
485 }
486 }
487
488 return $finalgrade;
489 }
38b9e8a8 490}
6c3ef410 491