Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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/>.
16
 
17
/**
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
23
 */
24
 
25
use core_user\fields;
26
 
27
require_once($CFG->libdir.'/gradelib.php');
28
 
29
/**
30
 * An abstract class containing variables and methods used by all or most reports.
31
 * @copyright 2007 Moodle Pty Ltd (http://moodle.com)
32
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33
 */
34
abstract class grade_report {
35
    /**
36
     * The courseid.
37
     * @var int $courseid
38
     */
39
    public $courseid;
40
 
41
    /**
42
     * The course.
43
     * @var object $course
44
     */
45
    public $course;
46
 
47
    /** Grade plugin return tracking object.
48
     * @var object $gpr
49
     */
50
    public $gpr;
51
 
52
    /**
53
     * The context.
54
     *
55
     * @var context $context
56
     */
57
    public $context;
58
 
59
    /**
60
     * The grade_tree object.
61
     * @var grade_tree $gtree
62
     */
63
    public $gtree;
64
 
65
    /**
66
     * User preferences related to this report.
67
     * @var array $prefs
68
     */
69
    public $prefs = array();
70
 
71
    /**
72
     * The roles for this report.
73
     * @var string $gradebookroles
74
     */
75
    public $gradebookroles;
76
 
77
    /**
78
     * base url for sorting by first/last name.
79
     * @var string $baseurl
80
     */
81
    public $baseurl;
82
 
83
    /**
84
     * base url for paging.
85
     * @var string $pbarurl
86
     */
87
    public $pbarurl;
88
 
89
    /**
90
     * Current page (for paging).
91
     * @var int $page
92
     */
93
    public $page;
94
 
95
    // GROUP VARIABLES (including SQL)
96
 
97
    /**
98
     * The current group being displayed.
99
     * @var int $currentgroup
100
     */
101
    public $currentgroup;
102
 
103
    /**
104
     * The current groupname being displayed.
105
     * @var string $currentgroupname
106
     */
107
    public $currentgroupname;
108
 
109
    /**
110
     * Current course group mode
111
     * @var int $groupmode
112
     */
113
    public $groupmode;
114
 
115
    /**
116
     * A HTML select element used to select the current group.
117
     * @var string $group_selector
118
     */
119
    public $group_selector;
120
 
121
    /**
122
     * An SQL fragment used to add linking information to the group tables.
123
     * @var string $groupsql
124
     */
125
    protected $groupsql;
126
 
127
    /**
128
     * An SQL constraint to append to the queries used by this object to build the report.
129
     * @var string $groupwheresql
130
     */
131
    protected $groupwheresql;
132
 
133
    /**
134
     * The ordered params for $groupwheresql
135
     * @var array $groupwheresql_params
136
     */
137
    protected $groupwheresql_params = array();
138
 
139
    // USER VARIABLES (including SQL).
140
 
141
    /**
142
     * An SQL constraint to append to the queries used by this object to build the report.
143
     * @var string $userwheresql
144
     */
145
    protected $userwheresql;
146
 
147
    /**
148
     * The ordered params for $userwheresql
149
     * @var array $userwheresql_params
150
     */
151
    protected $userwheresql_params = array();
152
 
153
    /**
154
     * To store user data
155
     * @var stdClass $user
156
     */
157
    public $user;
158
 
159
    /**
160
     * show course/category totals if they contain hidden items
161
     * @var array $showtotalsifcontainhidden
162
     */
163
    public $showtotalsifcontainhidden = [];
164
 
165
    /**
166
     * To store a link to preferences page
167
     * @var string $preferences_page
168
     */
169
    protected $preferences_page;
170
 
171
    /**
172
     * If the user is wanting to search for a particular user within searchable fields their needle will be placed here.
173
     * @var string $usersearch
174
     */
175
    protected string $usersearch = '';
176
 
177
    /**
178
     * If the user is wanting to show only one particular user their id will be placed here.
179
     * @var int $userid
180
     */
181
    protected int $userid = -1;
182
 
183
    /**
184
     * Constructor. Sets local copies of user preferences and initialises grade_tree.
185
     * @param int $courseid
186
     * @param object $gpr grade plugin return tracking object
187
     * @param string $context
188
     * @param int $page The current page being viewed (when report is paged)
189
     */
190
    public function __construct($courseid, $gpr, $context, $page=null) {
191
        global $CFG, $COURSE, $DB;
192
 
193
        if (empty($CFG->gradebookroles)) {
194
            throw new \moodle_exception('norolesdefined', 'grades');
195
        }
196
 
197
        $this->courseid  = $courseid;
198
        if ($this->courseid == $COURSE->id) {
199
            $this->course = $COURSE;
200
        } else {
201
            $this->course = $DB->get_record('course', array('id' => $this->courseid));
202
        }
203
 
204
        $this->gpr       = $gpr;
205
        $this->context   = $context;
206
        $this->page      = $page;
207
 
208
        // roles to be displayed in the gradebook
209
        $this->gradebookroles = $CFG->gradebookroles;
210
 
211
        // Set up link to preferences page
212
        $this->preferences_page = $CFG->wwwroot.'/grade/report/grader/preferences.php?id='.$courseid;
213
 
214
        // init gtree in child class
215
 
216
        // Set any url params.
217
        $this->usersearch = optional_param('gpr_search', '', PARAM_NOTAGS);
218
        $this->userid = optional_param('gpr_userid', -1, PARAM_INT);
219
    }
220
 
221
    /**
222
     * Given the name of a user preference (without grade_report_ prefix), locally saves then returns
223
     * the value of that preference. If the preference has already been fetched before,
224
     * the saved value is returned. If the preference is not set at the User level, the $CFG equivalent
225
     * is given (site default).
226
     * Can be called statically, but then doesn't benefit from caching
227
     * @param string $pref The name of the preference (do not include the grade_report_ prefix)
228
     * @param int $objectid An optional itemid or categoryid to check for a more fine-grained preference
229
     * @return mixed The value of the preference
230
     */
231
    public function get_pref($pref, $objectid=null) {
232
        global $CFG;
233
        $fullprefname = 'grade_report_' . $pref;
234
        $shortprefname = 'grade_' . $pref;
235
 
236
        $retval = null;
237
 
238
        if (!isset($this) OR get_class($this) != 'grade_report') {
239
            if (!empty($objectid)) {
240
                $retval = get_user_preferences($fullprefname . $objectid, self::get_pref($pref));
241
            } else if (isset($CFG->$fullprefname)) {
242
                $retval = get_user_preferences($fullprefname, $CFG->$fullprefname);
243
            } else if (isset($CFG->$shortprefname)) {
244
                $retval = get_user_preferences($fullprefname, $CFG->$shortprefname);
245
            } else {
246
                $retval = null;
247
            }
248
        } else {
249
            if (empty($this->prefs[$pref.$objectid])) {
250
 
251
                if (!empty($objectid)) {
252
                    $retval = get_user_preferences($fullprefname . $objectid);
253
                    if (empty($retval)) {
254
                        // No item pref found, we are returning the global preference
255
                        $retval = $this->get_pref($pref);
256
                        $objectid = null;
257
                    }
258
                } else {
259
                    $retval = get_user_preferences($fullprefname, $CFG->$fullprefname);
260
                }
261
                $this->prefs[$pref.$objectid] = $retval;
262
            } else {
263
                $retval = $this->prefs[$pref.$objectid];
264
            }
265
        }
266
 
267
        return $retval;
268
    }
269
 
270
    /**
271
     * Uses set_user_preferences() to update the value of a user preference. If 'default' is given as the value,
272
     * the preference will be removed in favour of a higher-level preference.
273
     * @param string $pref The name of the preference.
274
     * @param mixed $pref_value The value of the preference.
275
     * @param int $itemid An optional itemid to which the preference will be assigned
276
     * @return bool Success or failure.
277
     */
278
    public function set_pref($pref, $pref_value='default', $itemid=null) {
279
        $fullprefname = 'grade_report_' . $pref;
280
        if ($pref_value == 'default') {
281
            return unset_user_preference($fullprefname.$itemid);
282
        } else {
283
            return set_user_preference($fullprefname.$itemid, $pref_value);
284
        }
285
    }
286
 
287
    /**
288
     * Handles form data sent by this report for this report. Abstract method to implement in all children.
289
     * @abstract
290
     * @param array $data
291
     * @return mixed True or array of errors
292
     */
293
    abstract public function process_data($data);
294
 
295
    /**
296
     * Processes a single action against a category, grade_item or grade.
297
     * @param string $target Sortorder
298
     * @param string $action Which action to take (edit, delete etc...)
299
     * @return
300
     */
301
    abstract public function process_action($target, $action);
302
 
303
    /**
304
     * Add additional links specific to plugin
305
     * @param context_course $context Course context
306
     * @param int $courseid Course ID
307
     * @param array  $element An array representing an element in the grade_tree
308
     * @param grade_plugin_return $gpr A grade_plugin_return object
309
     * @param string $mode Mode (user or grade item)
310
     * @param stdClass $templatecontext Template context
311
     * @param bool $otherplugins If we need to insert links to other plugins
312
     * @return ?stdClass Updated template context
313
     */
314
    public static function get_additional_context(context_course $context, int $courseid, array $element,
315
            grade_plugin_return $gpr, string $mode, stdClass $templatecontext, bool $otherplugins = false): ?stdClass {
316
 
317
        if (!$otherplugins) {
318
            $component = 'gradereport_' . $gpr->plugin;
319
            $params = [$context, $courseid, $element, $gpr, $mode, $templatecontext];
320
            return component_callback($component, 'get_report_link', $params);
321
        } else {
322
            // Loop through all installed grade reports.
323
            foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
324
                $params = [$context, $courseid, $element, $gpr, $mode, $templatecontext];
325
                $component = 'gradereport_' . $plugin;
326
                $templatecontextupdated = component_callback($component, 'get_report_link', $params);
327
                if ($templatecontextupdated) {
328
                    $templatecontext = $templatecontextupdated;
329
                }
330
            }
331
            return $templatecontext;
332
        }
333
    }
334
 
335
    /**
336
     * @deprecated since 4.2
337
     */
1441 ariadna 338
    #[\core\attribute\deprecated('get_string', since: '4.2', mdl: 'MDL-77033', final: true)]
339
    public function get_lang_string(): void {
340
        \core\deprecation::emit_deprecation([self::class, __FUNCTION__]);
1 efrain 341
    }
342
 
343
    /**
344
     * Fetches and returns a count of all the users that will be shown on this page.
345
     * @param boolean $groups include groups limit
346
     * @param boolean $users include users limit - default false, used for searching purposes
347
     * @return int Count of users
348
     */
349
    public function get_numusers($groups = true, $users = false) {
350
        global $CFG, $DB;
351
        $userwheresql = "";
352
        $groupsql      = "";
353
        $groupwheresql = "";
354
 
355
        // Limit to users with a gradeable role.
356
        list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
357
 
358
        // Limit to users with an active enrollment.
359
        list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
360
 
361
        // We want to query both the current context and parent contexts.
362
        list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
363
 
364
        $params = array_merge($gradebookrolesparams, $enrolledparams, $relatedctxparams);
365
 
366
        if ($users) {
367
            $userwheresql = $this->userwheresql;
368
            $params       = array_merge($params, $this->userwheresql_params);
369
        }
370
 
371
        if ($groups) {
372
            $groupsql      = $this->groupsql;
373
            $groupwheresql = $this->groupwheresql;
374
            $params        = array_merge($params, $this->groupwheresql_params);
375
        }
376
 
377
        $sql = "SELECT DISTINCT u.id
378
                       FROM {user} u
379
                       JOIN ($enrolledsql) je
380
                            ON je.id = u.id
381
                       JOIN {role_assignments} ra
382
                            ON u.id = ra.userid
383
                       $groupsql
384
                      WHERE ra.roleid $gradebookrolessql
385
                            AND u.deleted = 0
386
                            $userwheresql
387
                            $groupwheresql
388
                            AND ra.contextid $relatedctxsql";
389
        $selectedusers = $DB->get_records_sql($sql, $params);
390
 
391
        $count = 0;
392
        // Check if user's enrolment is active and should be displayed.
393
        if (!empty($selectedusers)) {
394
            $coursecontext = $this->context->get_course_context(true);
395
 
396
            $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
397
            $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
398
            $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
399
 
400
            if ($showonlyactiveenrol) {
401
                $useractiveenrolments = get_enrolled_users($coursecontext, '', 0, 'u.id',  null, 0, 0, true);
402
            }
403
 
404
            foreach ($selectedusers as $id => $value) {
405
                if (!$showonlyactiveenrol || ($showonlyactiveenrol && array_key_exists($id, $useractiveenrolments))) {
406
                    $count++;
407
                }
408
            }
409
        }
410
        return $count;
411
    }
412
 
413
    /**
414
     * Shows support for being used as a 'Grades' report.
415
     */
416
    public static function supports_mygrades() {
417
        return false;
418
    }
419
 
420
    /**
421
     * Sets up this object's group variables, mainly to restrict the selection of users to display.
422
     */
423
    protected function setup_groups() {
424
        // find out current groups mode
425
        if ($this->groupmode = groups_get_course_groupmode($this->course)) {
426
            if (empty($this->gpr->groupid)) {
427
                $this->currentgroup = groups_get_course_group($this->course, true);
428
            } else {
429
                $this->currentgroup = $this->gpr->groupid;
430
            }
431
            $this->group_selector = groups_print_course_menu($this->course, $this->pbarurl, true);
432
 
433
            if ($this->groupmode == SEPARATEGROUPS and !$this->currentgroup and !has_capability('moodle/site:accessallgroups', $this->context)) {
434
                $this->currentgroup = -2; // means can not access any groups at all
435
            }
436
            if ($this->currentgroup) {
437
                if ($group = groups_get_group($this->currentgroup)) {
438
                    $this->currentgroupname = $group->name;
439
                }
440
                $this->groupsql             = " JOIN {groups_members} gm ON gm.userid = u.id ";
441
                $this->groupwheresql        = " AND gm.groupid = :gr_grpid ";
442
                $this->groupwheresql_params = array('gr_grpid'=>$this->currentgroup);
443
            }
444
        }
445
    }
446
 
447
    /**
448
     * Sets up this report's user criteria to restrict the selection of users to display.
449
     */
450
    public function setup_users() {
451
        global $SESSION, $DB;
452
 
453
        $filterfirstnamekey = "filterfirstname-{$this->context->id}";
454
        $filtersurnamekey = "filtersurname-{$this->context->id}";
455
 
456
        $this->userwheresql = "";
457
        $this->userwheresql_params = array();
458
        if (!empty($SESSION->gradereport[$filterfirstnamekey])) {
459
            $this->userwheresql .= ' AND '.$DB->sql_like('u.firstname', ':firstname', false, false);
460
            $this->userwheresql_params['firstname'] = $SESSION->gradereport[$filterfirstnamekey] . '%';
461
        }
462
        if (!empty($SESSION->gradereport[$filtersurnamekey])) {
463
            $this->userwheresql .= ' AND '.$DB->sql_like('u.lastname', ':lastname', false, false);
464
            $this->userwheresql_params['lastname'] = $SESSION->gradereport[$filtersurnamekey] . '%';
465
        }
466
 
467
        // When a user wants to view a particular user rather than a set of users.
468
        // By omission when selecting one user, also allow passing the search value around.
469
        if ($this->userid !== -1) {
470
            $this->userwheresql .= " AND u.id = :uid";
471
            $this->userwheresql_params['uid'] = $this->userid;
472
        }
473
 
474
        // A user wants to return a subset of learners that match their search criteria.
475
        if ($this->usersearch !== '' && $this->userid === -1) {
476
            [
477
                'where' => $keywordswhere,
478
                'params' => $keywordsparams,
1441 ariadna 479
            ] = \core_user::get_users_search_sql($this->context, $this->usersearch);
1 efrain 480
            $this->userwheresql .= " AND $keywordswhere";
481
            $this->userwheresql_params = array_merge($this->userwheresql_params, $keywordsparams);
482
        }
483
    }
484
 
485
    /**
486
     * Returns an arrow icon inside an <a> tag, for the purpose of sorting a column.
487
     * @param string $direction
488
     * @param moodle_url|null $sortlink
489
     */
490
    protected function get_sort_arrow(string $direction = 'down', ?moodle_url $sortlink = null) {
491
        global $OUTPUT;
492
        $pix = ['up' => 't/sort_desc', 'down' => 't/sort_asc'];
493
        $matrix = ['up' => 'desc', 'down' => 'asc'];
494
        $strsort = get_string($matrix[$direction], 'moodle');
495
        $arrow = $OUTPUT->pix_icon($pix[$direction], '', '', ['class' => 'sorticon']);
496
 
497
        if (!empty($sortlink)) {
498
            $sortlink->param('sort', ($direction == 'up' ? 'asc' : 'desc'));
499
        }
500
 
501
        return html_writer::link($sortlink, $arrow, ['title' => $strsort, 'aria-label' => $strsort, 'data-collapse' => 'sort',
502
            'class' => 'arrow_link py-1']);
503
    }
504
 
505
    /**
506
     * Optionally blank out course/category totals if they contain any hidden items
507
     * @param string $courseid the course id
508
     * @param string $course_item an instance of grade_item
509
     * @param string $finalgrade the grade for the course_item
510
     * @return array[] containing values for 'grade', 'grademax', 'grademin', 'aggregationstatus' and 'aggregationweight'
511
     */
512
    protected function blank_hidden_total_and_adjust_bounds($courseid, $course_item, $finalgrade) {
513
        global $CFG, $DB;
514
        static $hiding_affected = null;//array of items in this course affected by hiding
515
 
516
        // If we're dealing with multiple users we need to know when we've moved on to a new user.
517
        static $previous_userid = null;
518
 
519
        // If we're dealing with multiple courses we need to know when we've moved on to a new course.
520
        static $previous_courseid = null;
521
 
522
        $coursegradegrade = grade_grade::fetch(array('userid'=>$this->user->id, 'itemid'=>$course_item->id));
523
        $grademin = $course_item->grademin;
524
        $grademax = $course_item->grademax;
525
        if ($coursegradegrade) {
526
            $grademin = $coursegradegrade->get_grade_min();
527
            $grademax = $coursegradegrade->get_grade_max();
528
        } else {
529
            $coursegradegrade = new grade_grade(array('userid'=>$this->user->id, 'itemid'=>$course_item->id), false);
530
        }
531
        $hint = $coursegradegrade->get_aggregation_hint();
532
        $aggregationstatus = $hint['status'];
533
        $aggregationweight = $hint['weight'];
534
 
535
        if (!is_array($this->showtotalsifcontainhidden)) {
536
            debugging('showtotalsifcontainhidden should be an array', DEBUG_DEVELOPER);
537
            $this->showtotalsifcontainhidden = array($courseid => $this->showtotalsifcontainhidden);
538
        }
539
 
540
        if ($this->showtotalsifcontainhidden[$courseid] == GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN) {
541
            return array('grade' => $finalgrade,
542
                         'grademin' => $grademin,
543
                         'grademax' => $grademax,
544
                         'aggregationstatus' => $aggregationstatus,
545
                         'aggregationweight' => $aggregationweight);
546
        }
547
 
548
        // If we've moved on to another course or user, reload the grades.
549
        if ($previous_userid != $this->user->id || $previous_courseid != $courseid) {
550
            $hiding_affected = null;
551
            $previous_userid = $this->user->id;
552
            $previous_courseid = $courseid;
553
        }
554
 
555
        if (!$hiding_affected) {
556
            $items = grade_item::fetch_all(array('courseid'=>$courseid));
557
            $grades = array();
558
            $sql = "SELECT g.*
559
                      FROM {grade_grades} g
560
                      JOIN {grade_items} gi ON gi.id = g.itemid
561
                     WHERE g.userid = {$this->user->id} AND gi.courseid = {$courseid}";
562
            if ($gradesrecords = $DB->get_records_sql($sql)) {
563
                foreach ($gradesrecords as $grade) {
564
                    $grades[$grade->itemid] = new grade_grade($grade, false);
565
                }
566
                unset($gradesrecords);
567
            }
568
            foreach ($items as $itemid => $unused) {
569
                if (!isset($grades[$itemid])) {
570
                    $grade_grade = new grade_grade();
571
                    $grade_grade->userid = $this->user->id;
572
                    $grade_grade->itemid = $items[$itemid]->id;
573
                    $grades[$itemid] = $grade_grade;
574
                }
575
                $grades[$itemid]->grade_item =& $items[$itemid];
576
            }
577
            $hiding_affected = grade_grade::get_hiding_affected($grades, $items);
578
        }
579
 
580
        //if the item definitely depends on a hidden item
581
        if (array_key_exists($course_item->id, $hiding_affected['altered']) ||
582
                array_key_exists($course_item->id, $hiding_affected['alteredgrademin']) ||
583
                array_key_exists($course_item->id, $hiding_affected['alteredgrademax']) ||
584
                array_key_exists($course_item->id, $hiding_affected['alteredaggregationstatus']) ||
585
                array_key_exists($course_item->id, $hiding_affected['alteredaggregationweight'])) {
586
            if (!$this->showtotalsifcontainhidden[$courseid] && array_key_exists($course_item->id, $hiding_affected['altered'])) {
587
                // Hide the grade, but only when it has changed.
588
                $finalgrade = null;
589
            } else {
590
                //use reprocessed marks that exclude hidden items
591
                if (array_key_exists($course_item->id, $hiding_affected['altered'])) {
592
                    $finalgrade = $hiding_affected['altered'][$course_item->id];
593
                }
594
                if (array_key_exists($course_item->id, $hiding_affected['alteredgrademin'])) {
595
                    $grademin = $hiding_affected['alteredgrademin'][$course_item->id];
596
                }
597
                if (array_key_exists($course_item->id, $hiding_affected['alteredgrademax'])) {
598
                    $grademax = $hiding_affected['alteredgrademax'][$course_item->id];
599
                }
600
                if (array_key_exists($course_item->id, $hiding_affected['alteredaggregationstatus'])) {
601
                    $aggregationstatus = $hiding_affected['alteredaggregationstatus'][$course_item->id];
602
                }
603
                if (array_key_exists($course_item->id, $hiding_affected['alteredaggregationweight'])) {
604
                    $aggregationweight = $hiding_affected['alteredaggregationweight'][$course_item->id];
605
                }
606
 
607
                if (!$this->showtotalsifcontainhidden[$courseid]) {
608
                    // If the course total is hidden we must hide the weight otherwise
609
                    // it can be used to compute the course total.
610
                    $aggregationstatus = 'unknown';
611
                    $aggregationweight = null;
612
                }
613
            }
614
        } else if (array_key_exists($course_item->id, $hiding_affected['unknowngrades'])) {
615
            //not sure whether or not this item depends on a hidden item
616
            if (!$this->showtotalsifcontainhidden[$courseid]) {
617
                //hide the grade
618
                $finalgrade = null;
619
            } else {
620
                //use reprocessed marks that exclude hidden items
621
                $finalgrade = $hiding_affected['unknowngrades'][$course_item->id];
622
 
623
                if (array_key_exists($course_item->id, $hiding_affected['alteredgrademin'])) {
624
                    $grademin = $hiding_affected['alteredgrademin'][$course_item->id];
625
                }
626
                if (array_key_exists($course_item->id, $hiding_affected['alteredgrademax'])) {
627
                    $grademax = $hiding_affected['alteredgrademax'][$course_item->id];
628
                }
629
                if (array_key_exists($course_item->id, $hiding_affected['alteredaggregationstatus'])) {
630
                    $aggregationstatus = $hiding_affected['alteredaggregationstatus'][$course_item->id];
631
                }
632
                if (array_key_exists($course_item->id, $hiding_affected['alteredaggregationweight'])) {
633
                    $aggregationweight = $hiding_affected['alteredaggregationweight'][$course_item->id];
634
                }
635
            }
636
        }
637
 
638
        return array('grade' => $finalgrade, 'grademin' => $grademin, 'grademax' => $grademax, 'aggregationstatus'=>$aggregationstatus, 'aggregationweight'=>$aggregationweight);
639
    }
640
 
641
    /**
642
     * Optionally blank out course/category totals if they contain any hidden items
643
     * @deprecated since Moodle 2.8 - Call blank_hidden_total_and_adjust_bounds instead.
644
     * @param string $courseid the course id
645
     * @param string $course_item an instance of grade_item
646
     * @param string $finalgrade the grade for the course_item
647
     * @return string The new final grade
648
     */
649
    protected function blank_hidden_total($courseid, $course_item, $finalgrade) {
650
        // Note it is flawed to call this function directly because
651
        // the aggregated grade does not make sense without the updated min and max information.
652
 
653
        debugging('grade_report::blank_hidden_total() is deprecated.
654
                   Call grade_report::blank_hidden_total_and_adjust_bounds instead.', DEBUG_DEVELOPER);
655
        $result = $this->blank_hidden_total_and_adjust_bounds($courseid, $course_item, $finalgrade);
656
        return $result['grade'];
657
    }
658
 
659
    /**
660
     * Calculate average grade for a given grade item.
661
     *
662
     * @param grade_item $gradeitem Grade item
663
     * @param array $info Ungraded grade items counts and report preferences.
664
     * @return array Average grade and meancount.
665
     */
666
    public static function calculate_average(grade_item $gradeitem, array $info): array {
667
 
668
        $meanselection = $info['report']['meanselection'];
669
        $totalcount = $info['report']['totalcount'];
670
        $ungradedcounts = $info['ungradedcounts'];
671
        $sumarray = $info['sumarray'];
672
 
673
        if (empty($sumarray[$gradeitem->id])) {
674
            $sumarray[$gradeitem->id] = 0;
675
        }
676
 
677
        if (empty($ungradedcounts[$gradeitem->id])) {
678
            $ungradedcounts = 0;
679
        } else {
680
            $ungradedcounts = $ungradedcounts[$gradeitem->id]->count;
681
        }
682
 
683
        // If they want the averages to include all grade items.
684
        if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
685
            $meancount = $totalcount - $ungradedcounts;
686
        } else {
687
            // Bump up the sum by the number of ungraded items * grademin.
688
            $sumarray[$gradeitem->id] += ($ungradedcounts * $gradeitem->grademin);
689
            $meancount = $totalcount;
690
        }
691
 
692
        $aggr['meancount'] = $meancount;
693
 
694
        if (empty($sumarray[$gradeitem->id]) || $meancount == 0) {
695
            $aggr['average'] = null;
696
        } else {
697
            $sum = $sumarray[$gradeitem->id];
698
            $aggr['average'] = $sum / $meancount;
699
        }
700
        return $aggr;
701
    }
702
 
703
    /**
704
     * To check if we only need to include active enrolments.
705
     *
706
     * @return bool
707
     */
708
    public function show_only_active(): bool {
709
        global $CFG;
710
 
711
        // Limit to users with an active enrolment.
712
        $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
713
        $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
714
        return $showonlyactiveenrol ||
715
            !has_capability('moodle/course:viewsuspendedusers', $this->context);
716
    }
717
 
718
    /**
719
     * Get ungraded grade items info and sum of all grade items in a course.
720
     *
721
     * @param bool $grouponly If we want to compute group average only.
722
     * @param bool $includehiddengrades Include hidden grades.
723
     * @param bool $showonlyactiveenrol Whether to only include active enrolments.
724
     * @return array Ungraded grade items counts with report preferences.
725
     */
726
    public function ungraded_counts(bool $grouponly = false, bool $includehiddengrades = false, $showonlyactiveenrol = true): array {
727
        global $DB;
728
 
729
        $groupid = null;
730
        if ($grouponly && isset($this->gpr->groupid)) {
731
            $groupid = $this->gpr->groupid;
732
        }
733
 
734
        $info = [];
735
        $info['report'] = [
736
            'averagesdisplaytype' => $this->get_pref('averagesdisplaytype'),
737
            'averagesdecimalpoints' => $this->get_pref('averagesdecimalpoints'),
738
            'meanselection' => $this->get_pref('meanselection'),
739
            'shownumberofgrades' => $this->get_pref('shownumberofgrades'),
740
            'totalcount' => $this->get_numusers(!is_null($groupid)),
741
        ];
742
 
743
        // We want to query both the current context and parent contexts.
744
        list($relatedctxsql, $relatedctxparams) =
745
            $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
746
 
747
        // Limit to users with a gradeable role ie students.
748
        list($gradebookrolessql, $gradebookrolesparams) =
749
            $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
750
 
751
        list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
752
 
753
        $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
754
        $params['courseid'] = $this->courseid;
755
 
756
        if (empty($groupid)) {
757
            // Aggregate on whole course only.
758
            $this->groupsql = null;
759
            $this->groupwheresql = null;
760
        }
761
 
762
        $includesql = '';
763
        if (!$includehiddengrades) {
764
            $includesql = 'AND gg.hidden = 0';
765
        }
766
 
767
        // Empty grades must be evaluated as grademin, NOT always 0.
768
        // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table).
769
        // No join condition when joining grade_items and user to get a grade item row for every user.
770
        // Then left join with grade_grades and look for rows with null final grade
771
        // (which includes grade items with no grade_grade).
772
        $sql = "SELECT gi.id, COUNT(u.id) AS count
773
                      FROM {grade_items} gi
774
                      JOIN {user} u ON u.deleted = 0
775
                      JOIN ($enrolledsql) je ON je.id = u.id
776
                      JOIN (
777
                               SELECT DISTINCT ra.userid
778
                                 FROM {role_assignments} ra
779
                                WHERE ra.roleid $gradebookrolessql
780
                                  AND ra.contextid $relatedctxsql
781
                           ) rainner ON rainner.userid = u.id
782
                      LEFT JOIN {grade_grades} gg
783
                             ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL $includesql)
784
                      $this->groupsql
785
                     WHERE gi.courseid = :courseid
786
                           AND gg.finalgrade IS NULL
787
                           $this->groupwheresql
788
                  GROUP BY gi.id";
789
        $info['ungradedcounts'] = $DB->get_records_sql($sql, $params);
790
 
791
        // Find sums of all grade items in course.
792
        $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
793
                      FROM {grade_items} gi
794
                      JOIN {grade_grades} gg ON gg.itemid = gi.id
795
                      JOIN {user} u ON u.id = gg.userid
796
                      JOIN ($enrolledsql) je ON je.id = gg.userid
797
                      JOIN (
798
                                   SELECT DISTINCT ra.userid
799
                                     FROM {role_assignments} ra
800
                                    WHERE ra.roleid $gradebookrolessql
801
                                      AND ra.contextid $relatedctxsql
802
                           ) rainner ON rainner.userid = u.id
803
                      $this->groupsql
804
                     WHERE gi.courseid = :courseid
805
                       AND u.deleted = 0
806
                       AND gg.finalgrade IS NOT NULL
807
                       $includesql
808
                       $this->groupwheresql
809
                  GROUP BY gg.itemid";
810
 
811
        $sumarray = [];
812
        $sums = $DB->get_recordset_sql($sql, $params);
813
        foreach ($sums as $itemid => $csum) {
814
            $sumarray[$itemid] = grade_floatval($csum->sum);
815
        }
816
        $sums->close();
817
        $info['sumarray'] = $sumarray;
818
 
819
        return $info;
820
    }
821
 
822
    /**
823
     * Get grade item type names in a course to use in filter dropdown.
824
     *
825
     * @return array Item types.
826
     */
827
    public function item_types(): array {
828
        global $DB, $CFG;
829
 
830
        $modnames = [];
831
        $sql = "(SELECT gi.itemmodule
832
                   FROM {grade_items} gi
833
                  WHERE gi.courseid = :courseid1
834
                    AND gi.itemmodule IS NOT NULL)
835
                 UNION
836
                (SELECT gi1.itemtype
837
                   FROM {grade_items} gi1
838
                  WHERE gi1.courseid = :courseid2
839
                    AND gi1.itemtype = 'manual')";
840
 
841
        $itemtypes = $DB->get_records_sql($sql, ['courseid1' => $this->courseid, 'courseid2' => $this->courseid]);
842
        foreach ($itemtypes as $itemtype => $value) {
843
            if (file_exists("$CFG->dirroot/mod/$itemtype/lib.php")) {
844
                $modnames[$itemtype] = get_string("modulename", $itemtype, null, true);
845
            } else if ($itemtype == 'manual') {
846
                $modnames[$itemtype] = get_string('manualitem', 'grades', null, true);
847
            }
848
        }
849
 
850
        return $modnames;
851
    }
852
 
853
    /**
854
     * Load a valid list of gradable users in a course.
855
     *
856
     * @param int $courseid The course ID.
857
     * @param int|null $groupid The group ID (optional).
858
     * @return array A list of enrolled gradable users.
859
     */
860
    public static function get_gradable_users(int $courseid, ?int $groupid = null): array {
861
        global $CFG;
862
        require_once($CFG->dirroot . '/grade/lib.php');
863
 
864
        $context = context_course::instance($courseid);
865
        $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
866
        $onlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol) ||
867
            !has_capability('moodle/course:viewsuspendedusers', $context);
868
 
869
        return get_gradable_users($courseid, $groupid, $onlyactiveenrol);
870
    }
871
 
872
    /**
873
     * Returns a row of grade items averages
874
     *
875
     * @param array $ungradedcounts Ungraded grade items counts with report preferences.
876
     * @return html_table_row Row with averages
877
     */
878
    protected function format_averages(array $ungradedcounts): html_table_row {
879
 
880
        $avgrow = new html_table_row();
881
        $avgrow->attributes['class'] = 'avg';
882
 
883
        $averagesdisplaytype = $ungradedcounts['report']['averagesdisplaytype'];
884
        $averagesdecimalpoints = $ungradedcounts['report']['averagesdecimalpoints'];
885
        $shownumberofgrades = $ungradedcounts['report']['shownumberofgrades'];
886
 
887
        foreach ($this->gtree->items as $gradeitem) {
888
            if ($gradeitem->needsupdate) {
889
                $avgrow->cells[$gradeitem->id] = $this->format_average_cell($gradeitem);
890
            } else {
891
                $aggr = $this->calculate_average($gradeitem, $ungradedcounts);
892
 
893
                if (empty($aggr['average'])) {
894
                    $avgrow->cells[$gradeitem->id] =
895
                        $this->format_average_cell($gradeitem, $aggr, $ungradedcounts['report']['shownumberofgrades']);
896
                } else {
897
                    // Determine which display type to use for this average.
898
                    if (isset($USER->editing) && $USER->editing) {
899
                        $displaytype = GRADE_DISPLAY_TYPE_REAL;
900
                    } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) {
901
                        // No ==0 here, please resave the report and user preferences.
902
                        $displaytype = $gradeitem->get_displaytype();
903
                    } else {
904
                        $displaytype = $averagesdisplaytype;
905
                    }
906
 
907
                    // Override grade_item setting if a display preference (not inherit) was set for the averages.
908
                    if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
909
                        $decimalpoints = $gradeitem->get_decimals();
910
                    } else {
911
                        $decimalpoints = $averagesdecimalpoints;
912
                    }
913
 
914
                    $aggr['average'] = grade_format_gradevalue($aggr['average'],
915
                        $gradeitem, true, $displaytype, $decimalpoints);
916
 
917
                    $avgrow->cells[$gradeitem->id] = $this->format_average_cell($gradeitem, $aggr, $shownumberofgrades);
918
                }
919
            }
920
        }
921
        return $avgrow;
922
    }
923
 
924
    /**
925
     * Returns a row of grade items averages. Override this method to change the format of the average cell.
926
     *
927
     * @param grade_item $gradeitem Grade item.
928
     * @param array|null $aggr Average value and meancount information.
929
     * @param bool|null $shownumberofgrades Whether to show number of grades.
930
     * @return html_table_cell table cell.
931
     */
932
    protected function format_average_cell(grade_item $gradeitem, ?array $aggr = null, ?bool $shownumberofgrades = null): html_table_cell {
933
        return new html_table_cell();
934
    }
935
 
936
}