Proyectos de Subversion Moodle

Rev

| 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
namespace mod_quiz;
18
 
19
use coding_exception;
20
use core\di;
21
use core\hook;
22
use core_component;
23
use mod_quiz\event\quiz_grade_updated;
24
use mod_quiz\hook\structure_modified;
25
use mod_quiz\output\grades\grade_out_of;
26
use qubaid_condition;
27
use qubaid_list;
28
use question_engine_data_mapper;
29
use question_usage_by_activity;
30
use stdClass;
31
 
32
/**
33
 * This class contains all the logic for computing the grade of a quiz.
34
 *
35
 * There are two sorts of calculation which need to be done. For a single
36
 * attempt, we need to compute the total attempt score from score for each question.
37
 * And for a quiz user, we need to compute the final grade from all the separate attempt grades.
38
 *
39
 * @package   mod_quiz
40
 * @copyright 2023 The Open University
41
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
class grade_calculator {
44
 
45
    /** @var float a number that is effectively zero. Used to avoid division-by-zero or underflow problems. */
46
    const ALMOST_ZERO = 0.000005;
47
 
48
    /** @var quiz_settings the quiz for which this instance computes grades. */
49
    protected $quizobj;
50
 
51
    /**
52
     * @var stdClass[]|null quiz_grade_items for this quiz indexed by id, sorted by sortorder, with a maxmark field added.
53
     *
54
     * Lazy-loaded when needed. See {@see ensure_grade_items_loaded()}.
55
     */
56
    protected ?array $gradeitems = null;
57
 
58
    /**
59
     * @var ?stdClass[]|null quiz_slot for this quiz. Only ->slot and ->quizgradeitemid fields are used.
60
     *
61
     * This is either set by another class that already has the data, using {@see set_slots()}
62
     * or it is lazy-loaded when needed. See {@see ensure_slots_loaded()}.
63
     */
64
    protected ?array $slots = null;
65
 
66
    /**
67
     * Constructor. Recommended way to get an instance is $quizobj->get_grade_calculator();
68
     *
69
     * @param quiz_settings $quizobj
70
     */
71
    protected function __construct(quiz_settings $quizobj) {
72
        $this->quizobj = $quizobj;
73
    }
74
 
75
    /**
76
     * Factory. The recommended way to get an instance is $quizobj->get_grade_calculator();
77
     *
78
     * @param quiz_settings $quizobj settings of a quiz.
79
     * @return grade_calculator instance of this class for the given quiz.
80
     */
81
    public static function create(quiz_settings $quizobj): grade_calculator {
82
        return new self($quizobj);
83
    }
84
 
85
    /**
86
     * Update the sumgrades field of the quiz.
87
     *
88
     * This needs to be called whenever the grading structure of the quiz is changed.
89
     * For example if a question is added or removed, or a question weight is changed.
90
     *
91
     * You should call {@see quiz_delete_previews()} before you call this function.
92
     */
93
    public function recompute_quiz_sumgrades(): void {
94
        global $DB;
95
        $quiz = $this->quizobj->get_quiz();
96
 
97
        // Update sumgrades in the database.
98
        $DB->execute("
99
                UPDATE {quiz}
100
                   SET sumgrades = COALESCE((
101
                        SELECT SUM(maxmark)
102
                          FROM {quiz_slots}
103
                         WHERE quizid = {quiz}.id
104
                       ), 0)
105
                 WHERE id = ?
106
             ", [$quiz->id]);
107
 
108
        // Update the value in memory.
109
        $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', ['id' => $quiz->id]);
110
 
111
        if ($quiz->sumgrades < self::ALMOST_ZERO && quiz_has_attempts($quiz->id)) {
112
            // If the quiz has been attempted, and the sumgrades has been
113
            // set to 0, then we must also set the maximum possible grade to 0, or
114
            // we will get a divide by zero error.
115
            self::update_quiz_maximum_grade(0);
116
        }
117
 
118
        // This class callback is deprecated, and will be removed in Moodle 4.8 (MDL-80327).
119
        // Use the structure_modified hook instead.
120
        $callbackclasses = core_component::get_plugin_list_with_class('quiz', 'quiz_structure_modified');
121
        foreach ($callbackclasses as $callbackclass) {
122
            component_class_callback($callbackclass, 'callback', [$quiz->id], null, true);
123
        }
124
 
125
        di::get(hook\manager::class)->dispatch(new structure_modified($this->quizobj->get_structure()));
126
    }
127
 
128
    /**
129
     * Update the sumgrades field of attempts at this quiz.
130
     */
131
    public function recompute_all_attempt_sumgrades(): void {
132
        global $DB;
133
        $dm = new question_engine_data_mapper();
134
        $timenow = time();
135
 
136
        $DB->execute("
137
                UPDATE {quiz_attempts}
138
                   SET timemodified = :timenow,
139
                       sumgrades = (
140
                           {$dm->sum_usage_marks_subquery('uniqueid')}
141
                       )
142
                 WHERE quiz = :quizid AND state = :finishedstate
143
            ", [
144
                'timenow' => $timenow,
145
                'quizid' => $this->quizobj->get_quizid(),
146
                'finishedstate' => quiz_attempt::FINISHED
147
            ]);
148
    }
149
 
150
    /**
151
     * Update the final grade at this quiz for a particular student.
152
     *
153
     * That is, given the quiz settings, and all the attempts this user has made,
154
     * compute their final grade for the quiz, as shown in the gradebook.
155
     *
156
     * The $attempts parameter is for efficiency. If you already have the data for
157
     * all this user's attempts loaded (for example from {@see quiz_get_user_attempts()}
158
     * or because you are looping through a large recordset fetched in one efficient query,
159
     * then you can pass that data here to save DB queries.
160
     *
161
     * @param int|null $userid The userid to calculate the grade for. Defaults to the current user.
162
     * @param array $attempts if you already have this user's attempt records loaded, pass them here to save queries.
163
     */
164
    public function recompute_final_grade(?int $userid = null, array $attempts = []): void {
165
        global $DB, $USER;
166
        $quiz = $this->quizobj->get_quiz();
167
 
168
        if (empty($userid)) {
169
            $userid = $USER->id;
170
        }
171
 
172
        if (!$attempts) {
173
            // Get all the attempts made by the user.
174
            $attempts = quiz_get_user_attempts($quiz->id, $userid);
175
        }
176
 
177
        // Calculate the best grade.
178
        $bestgrade = $this->compute_final_grade_from_attempts($attempts);
179
        $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
180
 
181
        // Save the best grade in the database.
182
        if (is_null($bestgrade)) {
183
            $DB->delete_records('quiz_grades', ['quiz' => $quiz->id, 'userid' => $userid]);
184
 
185
        } else if ($grade = $DB->get_record('quiz_grades',
186
                ['quiz' => $quiz->id, 'userid' => $userid])) {
187
            $grade->grade = $bestgrade;
188
            $grade->timemodified = time();
189
            $DB->update_record('quiz_grades', $grade);
190
 
191
        } else {
192
            $grade = new stdClass();
193
            $grade->quiz = $quiz->id;
194
            $grade->userid = $userid;
195
            $grade->grade = $bestgrade;
196
            $grade->timemodified = time();
197
            $DB->insert_record('quiz_grades', $grade);
198
        }
199
 
200
        quiz_update_grades($quiz, $userid);
201
    }
202
 
203
    /**
204
     * Calculate the overall grade for a quiz given a number of attempts by a particular user.
205
     *
206
     * @param array $attempts an array of all the user's attempts at this quiz in order.
207
     * @return float|null the overall grade, or null if the user does not have a grade.
208
     */
209
    protected function compute_final_grade_from_attempts(array $attempts): ?float {
210
 
211
        $grademethod = $this->quizobj->get_quiz()->grademethod;
212
        switch ($grademethod) {
213
 
214
            case QUIZ_ATTEMPTFIRST:
215
                $firstattempt = reset($attempts);
216
                return $firstattempt->sumgrades;
217
 
218
            case QUIZ_ATTEMPTLAST:
219
                $lastattempt = end($attempts);
220
                return $lastattempt->sumgrades;
221
 
222
            case QUIZ_GRADEAVERAGE:
223
                $sum = 0;
224
                $count = 0;
225
                foreach ($attempts as $attempt) {
226
                    if (!is_null($attempt->sumgrades)) {
227
                        $sum += $attempt->sumgrades;
228
                        $count++;
229
                    }
230
                }
231
                if ($count == 0) {
232
                    return null;
233
                }
234
                return $sum / $count;
235
 
236
            case QUIZ_GRADEHIGHEST:
237
                $max = null;
238
                foreach ($attempts as $attempt) {
239
                    if ($attempt->sumgrades > $max) {
240
                        $max = $attempt->sumgrades;
241
                    }
242
                }
243
                return $max;
244
 
245
            default:
246
                throw new coding_exception('Unrecognised grading method ' . $grademethod);
247
        }
248
    }
249
 
250
    /**
251
     * Update the final grade at this quiz for all students.
252
     *
253
     * This function is equivalent to calling {@see recompute_final_grade()} for all
254
     * users who have attempted the quiz, but is much more efficient.
255
     */
256
    public function recompute_all_final_grades(): void {
257
        global $DB;
258
        $quiz = $this->quizobj->get_quiz();
259
 
260
        // If the quiz does not contain any graded questions, then there is nothing to do.
261
        if (!$quiz->sumgrades) {
262
            return;
263
        }
264
 
265
        $param = ['iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED];
266
        $firstlastattemptjoin = "JOIN (
267
                SELECT
268
                    iquiza.userid,
269
                    MIN(attempt) AS firstattempt,
270
                    MAX(attempt) AS lastattempt
271
 
272
                FROM {quiz_attempts} iquiza
273
 
274
                WHERE
275
                    iquiza.state = :istatefinished AND
276
                    iquiza.preview = 0 AND
277
                    iquiza.quiz = :iquizid
278
 
279
                GROUP BY iquiza.userid
280
            ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
281
 
282
        switch ($quiz->grademethod) {
283
            case QUIZ_ATTEMPTFIRST:
284
                // Because of the where clause, there will only be one row, but we
285
                // must still use an aggregate function.
286
                $select = 'MAX(quiza.sumgrades)';
287
                $join = $firstlastattemptjoin;
288
                $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
289
                break;
290
 
291
            case QUIZ_ATTEMPTLAST:
292
                // Because of the where clause, there will only be one row, but we
293
                // must still use an aggregate function.
294
                $select = 'MAX(quiza.sumgrades)';
295
                $join = $firstlastattemptjoin;
296
                $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
297
                break;
298
 
299
            case QUIZ_GRADEAVERAGE:
300
                $select = 'AVG(quiza.sumgrades)';
301
                $join = '';
302
                $where = '';
303
                break;
304
 
305
            default:
306
            case QUIZ_GRADEHIGHEST:
307
                $select = 'MAX(quiza.sumgrades)';
308
                $join = '';
309
                $where = '';
310
                break;
311
        }
312
 
313
        if ($quiz->sumgrades >= self::ALMOST_ZERO) {
314
            $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
315
        } else {
316
            $finalgrade = '0';
317
        }
318
        $param['quizid'] = $quiz->id;
319
        $param['quizid2'] = $quiz->id;
320
        $param['quizid3'] = $quiz->id;
321
        $param['quizid4'] = $quiz->id;
322
        $param['statefinished'] = quiz_attempt::FINISHED;
323
        $param['statefinished2'] = quiz_attempt::FINISHED;
324
        $param['almostzero'] = self::ALMOST_ZERO;
325
        $finalgradesubquery = "
326
                SELECT quiza.userid, $finalgrade AS newgrade
327
                FROM {quiz_attempts} quiza
328
                $join
329
                WHERE
330
                    $where
331
                    quiza.state = :statefinished AND
332
                    quiza.preview = 0 AND
333
                    quiza.quiz = :quizid3
334
                GROUP BY quiza.userid";
335
 
336
        $changedgrades = $DB->get_records_sql("
337
                SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
338
 
339
                FROM (
340
                    SELECT userid
341
                    FROM {quiz_grades} qg
342
                    WHERE quiz = :quizid
343
                UNION
344
                    SELECT DISTINCT userid
345
                    FROM {quiz_attempts} quiza2
346
                    WHERE
347
                        quiza2.state = :statefinished2 AND
348
                        quiza2.preview = 0 AND
349
                        quiza2.quiz = :quizid2
350
                ) users
351
 
352
                LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
353
 
354
                LEFT JOIN (
355
                    $finalgradesubquery
356
                ) newgrades ON newgrades.userid = users.userid
357
 
358
                WHERE
359
                    ABS(newgrades.newgrade - qg.grade) > :almostzero OR
360
                    ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
361
                              (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
362
                    // The mess on the previous line is detecting where the value is
363
                    // NULL in one column, and NOT NULL in the other, but SQL does
364
                    // not have an XOR operator, and MS SQL server can't cope with
365
                    // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
366
                $param);
367
 
368
        $timenow = time();
369
        $todelete = [];
370
        foreach ($changedgrades as $changedgrade) {
371
 
372
            if (is_null($changedgrade->newgrade)) {
373
                $todelete[] = $changedgrade->userid;
374
 
375
            } else if (is_null($changedgrade->grade)) {
376
                $toinsert = new stdClass();
377
                $toinsert->quiz = $quiz->id;
378
                $toinsert->userid = $changedgrade->userid;
379
                $toinsert->timemodified = $timenow;
380
                $toinsert->grade = $changedgrade->newgrade;
381
                $DB->insert_record('quiz_grades', $toinsert);
382
 
383
            } else {
384
                $toupdate = new stdClass();
385
                $toupdate->id = $changedgrade->id;
386
                $toupdate->grade = $changedgrade->newgrade;
387
                $toupdate->timemodified = $timenow;
388
                $DB->update_record('quiz_grades', $toupdate);
389
            }
390
        }
391
 
392
        if (!empty($todelete)) {
393
            list($test, $params) = $DB->get_in_or_equal($todelete);
394
            $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
395
                    array_merge([$quiz->id], $params));
396
        }
397
    }
398
 
399
    /**
400
     * Update the quiz setting for the grade the quiz is out of.
401
     *
402
     * This function will update the data in quiz_grades and quiz_feedback, and
403
     * pass the new grades on to the gradebook.
404
     *
405
     * @param float $newgrade the new maximum grade for the quiz.
406
     */
407
    public function update_quiz_maximum_grade(float $newgrade): void {
408
        global $DB;
409
        $quiz = $this->quizobj->get_quiz();
410
 
411
        // This is potentially expensive, so only do it if necessary.
412
        if (abs($quiz->grade - $newgrade) < self::ALMOST_ZERO) {
413
            // Nothing to do.
414
            return;
415
        }
416
 
417
        // Use a transaction.
418
        $transaction = $DB->start_delegated_transaction();
419
 
420
        // Update the quiz table.
421
        $oldgrade = $quiz->grade;
422
        $quiz->grade = $newgrade;
423
        $timemodified = time();
424
        $DB->update_record('quiz', (object) [
425
            'id' => $quiz->id,
426
            'grade' => $newgrade,
427
            'timemodified' => $timemodified,
428
        ]);
429
 
430
        // Rescale the grade of all quiz attempts.
431
        if ($oldgrade < $newgrade) {
432
            // The new total is bigger, so we need to recompute fully to avoid underflow problems.
433
            $this->recompute_all_final_grades();
434
 
435
        } else {
436
            // New total smaller, so we can rescale the grades efficiently.
437
            $DB->execute("
438
                    UPDATE {quiz_grades}
439
                       SET grade = ? * grade, timemodified = ?
440
                     WHERE quiz = ?
441
            ", [$newgrade / $oldgrade, $timemodified, $quiz->id]);
442
        }
443
 
444
        // Rescale the overall feedback boundaries.
445
        if ($oldgrade > self::ALMOST_ZERO) {
446
            // Update the quiz_feedback table.
447
            $factor = $newgrade / $oldgrade;
448
            $DB->execute("
449
                    UPDATE {quiz_feedback}
450
                    SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
451
                    WHERE quizid = ?
452
            ", [$factor, $factor, $quiz->id]);
453
        }
454
 
455
        // Update grade item and send all grades to gradebook.
456
        quiz_grade_item_update($quiz);
457
        quiz_update_grades($quiz);
458
 
459
        // Log quiz grade updated event.
460
        quiz_grade_updated::create([
461
            'context' => $this->quizobj->get_context(),
462
            'objectid' => $quiz->id,
463
            'other' => [
464
                'oldgrade' => $oldgrade + 0, // Remove trailing 0s.
465
                'newgrade' => $newgrade,
466
            ]
467
        ])->trigger();
468
 
469
        $transaction->allow_commit();
470
    }
471
 
472
    /**
473
     * Ensure the {@see grade_calculator::$gradeitems} field is ready to use.
474
     */
475
    protected function ensure_grade_items_loaded(): void {
476
        global $DB;
477
 
478
        if ($this->gradeitems !== null) {
479
            return; // Already done.
480
        }
481
 
482
        $this->gradeitems = $DB->get_records_sql("
483
            SELECT gi.id,
484
                   gi.quizid,
485
                   gi.sortorder,
486
                   gi.name,
487
                   COALESCE(SUM(slot.maxmark), 0) AS maxmark
488
 
489
              FROM {quiz_grade_items} gi
490
         LEFT JOIN {quiz_slots} slot ON slot.quizgradeitemid = gi.id
491
 
492
             WHERE gi.quizid = ? AND slot.quizid = ?
493
 
494
          GROUP BY gi.id, gi.quizid, gi.sortorder, gi.name
495
 
496
          ORDER BY gi.sortorder
497
            ", [$this->quizobj->get_quizid(), $this->quizobj->get_quizid()]);
498
    }
499
 
500
    /**
501
     * Get the extra grade items for this quiz.
502
     *
503
     * Returned objects have fields ->id, ->quizid, ->sortorder, ->name and maxmark.
504
     * @return stdClass[] the grade items for this quiz.
505
     */
506
    public function get_grade_items(): array {
507
        $this->ensure_grade_items_loaded();
508
        return $this->gradeitems;
509
    }
510
 
511
    /**
512
     * Lets other code pass in the slot information, so it does note have to be re-loaded from the DB.
513
     *
514
     * @param stdClass[] $slots the data from quiz_slots. The only required fields are ->slot and ->quizgradeitemid.
515
     */
516
    public function set_slots(array $slots): void {
517
        global $CFG;
518
        $this->slots = $slots;
519
 
520
        if ($CFG->debugdeveloper) {
521
            foreach ($slots as $slot) {
522
                if (!property_exists($slot, 'slot') || !property_exists($slot, 'quizgradeitemid')) {
523
                    debugging('Slot data passed to grade_calculator::set_slots ' .
524
                        'must have at least ->slot and ->quizgradeitemid set.', DEBUG_DEVELOPER);
525
                    break; // Only necessary to say this once.
526
                }
527
            }
528
        }
529
    }
530
 
531
    /**
532
     * Ensure the {@see $gradeitems} field is ready to use.
533
     */
534
    protected function ensure_slots_loaded(): void {
535
        global $DB;
536
 
537
        if ($this->slots !== null) {
538
            return; // Already done.
539
        }
540
 
541
        $this->slots = $DB->get_records('quiz_slots', ['quizid' => $this->quizobj->get_quizid()],
542
            'slot', 'slot, id, quizgradeitemid');
543
    }
544
 
545
    /**
546
     * Compute the grade and maximum for each item, for an attempt where the question_usage_by_activity is available.
547
     *
548
     * @param question_usage_by_activity $quba usage for the quiz attempt we want to calculate the grades of.
549
     * @return grade_out_of[] the grade for each item where the total grade is not zero.
550
     *      ->name will be set to the grade item name. Must be output through {@see format_string()}.
551
     */
552
    public function compute_grade_item_totals(question_usage_by_activity $quba): array {
553
        $this->ensure_grade_items_loaded();
554
        if (empty($this->gradeitems)) {
555
            // No extra grade items.
556
            return [];
557
        }
558
 
559
        $this->ensure_slots_loaded();
560
 
561
        // Prepare a place to store the results for each grade-item.
562
        $grades = [];
563
        foreach ($this->gradeitems as $gradeitem) {
564
            $grades[$gradeitem->id] = new grade_out_of(
565
                $this->quizobj->get_quiz(), 0, $gradeitem->maxmark, name: $gradeitem->name);
566
        }
567
 
568
        // Add up the scores.
569
        foreach ($this->slots as $slot) {
570
            if (!$slot->quizgradeitemid) {
571
                continue;
572
            }
573
            $grades[$slot->quizgradeitemid]->grade += $quba->get_question_mark($slot->slot);
574
        }
575
 
576
        // Remove any grade items where the total is 0.
577
        foreach ($grades as $gradeitemid => $grade) {
578
            if ($grade->maxgrade < self::ALMOST_ZERO) {
579
                unset($grades[$gradeitemid]);
580
            }
581
        }
582
 
583
        return $grades;
584
    }
585
 
586
    /**
587
     * Compute the grade and maximum for each item, for some attempts where we only have the usage ids.
588
     *
589
     * @param int[] $qubaids array of usage ids.
590
     * @return grade_out_of[][] question_usage.id => array of grade_out_of.
591
     *      ->name will be set to the grade item name. Must be output through {@see format_string()}..
592
     */
593
    public function compute_grade_item_totals_for_attempts(array $qubaids): array {
594
        $this->ensure_grade_items_loaded();
595
        $grades = [];
596
        foreach ($qubaids as $qubaid) {
597
            $grades[$qubaid] = [];
598
        }
599
 
600
        if (empty($this->gradeitems || empty($qubaids))) {
601
            // Nothing to do.
602
            return $grades;
603
        }
604
 
605
        $gradesdata = $this->load_grade_item_totals(new qubaid_list($qubaids));
606
        foreach ($qubaids as $qubaid) {
607
            foreach ($this->gradeitems as $gradeitem) {
608
                if ($gradeitem->maxmark < self::ALMOST_ZERO) {
609
                    continue;
610
                }
611
                $grades[$qubaid][$gradeitem->id] = new grade_out_of(
612
                    $this->quizobj->get_quiz(),
613
                    $gradesdata[$qubaid][$gradeitem->id] ?? 0,
614
                    $gradeitem->maxmark,
615
                    name: $gradeitem->name,
616
                );
617
            }
618
        }
619
 
620
        return $grades;
621
    }
622
 
623
    /**
624
     * Query the database return the total mark for each grade item for a set of attempts.
625
     *
626
     * @param qubaid_condition $qubaids which question_usages to computer the total marks for.
627
     * @return float[][] Array question_usage.id => quiz_grade_item.id => mark.
628
     */
629
    public function load_grade_item_totals(qubaid_condition $qubaids): array {
630
        global $DB;
631
        $dm = new question_engine_data_mapper();
632
 
633
        [$qalatestview, $viewparams] = $dm->question_attempt_latest_state_view('qalatest', $qubaids);
634
 
635
        $totals = $DB->get_records_sql("
636
            SELECT " . $DB->sql_concat('qalatest.questionusageid', "'#'", 'slot.quizgradeitemid') . " AS uniquefirstcolumn,
637
                   qalatest.questionusageid,
638
                   slot.quizgradeitemid,
639
                   SUM(qalatest.fraction * qalatest.maxmark) AS summarks
640
 
641
              FROM $qalatestview
642
 
643
              JOIN {quiz_slots} slot ON slot.slot = qalatest.slot
644
              JOIN {quiz_grade_items} qgi ON qgi.id = slot.quizgradeitemid
645
 
646
          GROUP BY qalatest.questionusageid, slot.quizgradeitemid
647
 
648
            ", $viewparams);
649
 
650
        $marks = [];
651
        foreach ($totals as $total) {
652
            $marks[$total->questionusageid][$total->quizgradeitemid] = $total->summarks + 0; // Convert to float with + 0.
653
        }
654
 
655
        return $marks;
656
    }
657
}