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