Proyectos de Subversion Moodle

Rev

Rev 11 | | 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
 * This file defines the quiz overview report class.
19
 *
20
 * @package   quiz_overview
21
 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
use mod_quiz\local\reports\attempts_report;
26
use mod_quiz\question\bank\qbank_helper;
27
use mod_quiz\quiz_attempt;
28
 
29
defined('MOODLE_INTERNAL') || die();
30
 
31
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_options.php');
32
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_form.php');
33
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_table.php');
34
 
35
 
36
/**
37
 * Quiz report subclass for the overview (grades) report.
38
 *
39
 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
40
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
class quiz_overview_report extends attempts_report {
43
 
44
    public function display($quiz, $cm, $course) {
1441 ariadna 45
        global $DB, $PAGE, $OUTPUT;
1 efrain 46
 
47
        list($currentgroup, $studentsjoins, $groupstudentsjoins, $allowedjoins) = $this->init(
48
                'overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
49
 
50
        $options = new quiz_overview_options('overview', $quiz, $cm, $course);
51
 
52
        if ($fromform = $this->form->get_data()) {
53
            $options->process_settings_from_form($fromform);
54
 
55
        } else {
56
            $options->process_settings_from_params();
57
        }
58
 
59
        $this->form->set_data($options->get_initial_form_data());
60
 
61
        // Load the required questions.
62
        $questions = quiz_report_get_significant_questions($quiz);
63
        // Prepare for downloading, if applicable.
64
        $courseshortname = format_string($course->shortname, true,
65
                ['context' => context_course::instance($course->id)]);
66
        $table = new quiz_overview_table($quiz, $this->context, $this->qmsubselect,
67
                $options, $groupstudentsjoins, $studentsjoins, $questions, $options->get_url());
68
        $filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'),
69
                $courseshortname, $quiz->name);
70
        $table->is_downloading($options->download, $filename,
71
                $courseshortname . ' ' . format_string($quiz->name, true));
72
        if ($table->is_downloading()) {
73
            raise_memory_limit(MEMORY_EXTRA);
74
        }
75
 
76
        $this->hasgroupstudents = false;
77
        if (!empty($groupstudentsjoins->joins)) {
78
            $sql = "SELECT DISTINCT u.id
79
                      FROM {user} u
80
                    $groupstudentsjoins->joins
81
                     WHERE $groupstudentsjoins->wheres";
82
            $this->hasgroupstudents = $DB->record_exists_sql($sql, $groupstudentsjoins->params);
83
        }
84
        $hasstudents = false;
85
        if (!empty($studentsjoins->joins)) {
86
            $sql = "SELECT DISTINCT u.id
87
                    FROM {user} u
88
                    $studentsjoins->joins
89
                    WHERE $studentsjoins->wheres";
90
            $hasstudents = $DB->record_exists_sql($sql, $studentsjoins->params);
91
        }
92
        if ($options->attempts == self::ALL_WITH) {
93
            // This option is only available to users who can access all groups in
94
            // groups mode, so setting allowed to empty (which means all quiz attempts
1441 ariadna 95
            // are accessible, is not a security problem.
1 efrain 96
            $allowedjoins = new \core\dml\sql_join();
97
        }
98
 
99
        $this->process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $options->get_url());
100
 
101
        $hasquestions = quiz_has_questions($quiz->id);
102
 
103
        // Start output.
104
        if (!$table->is_downloading()) {
105
            // Only print headers if not asked to download data.
106
            $this->print_standard_header_and_messages($cm, $course, $quiz,
107
                    $options, $currentgroup, $hasquestions, $hasstudents);
108
 
109
            // Print the display options.
110
            $this->form->display();
111
        }
112
 
113
        $hasstudents = $hasstudents && (!$currentgroup || $this->hasgroupstudents);
114
        if ($hasquestions && ($hasstudents || $options->attempts == self::ALL_WITH)) {
115
            // Construct the SQL.
116
            $table->setup_sql_queries($allowedjoins);
117
            if (!$table->is_downloading()) {
118
                // Print information on the grading method.
119
                if ($strattempthighlight = quiz_report_highlighting_grading_method(
120
                        $quiz, $this->qmsubselect, $options->onlygraded)) {
121
                    echo '<div class="quizattemptcounts mt-3">' . $strattempthighlight . '</div>';
122
                }
123
            }
124
 
125
            // Define table columns.
126
            $columns = [];
127
            $headers = [];
128
 
129
            if (!$table->is_downloading() && $options->checkboxcolumn) {
130
                $columnname = 'checkbox';
131
                $columns[] = $columnname;
132
                $headers[] = $table->checkbox_col_header($columnname);
133
            }
134
 
135
            $this->add_user_columns($table, $columns, $headers);
136
            $this->add_state_column($columns, $headers);
137
            $this->add_time_columns($columns, $headers);
138
 
139
            $this->add_grade_columns($quiz, $options->usercanseegrades, $columns, $headers, false);
140
            $this->add_grade_item_columns($options->usercanseegrades, $columns, $headers);
141
 
1441 ariadna 142
            $canregrade = has_capability('mod/quiz:regrade', $this->context);
143
            if (!$table->is_downloading() && $canregrade &&
1 efrain 144
                    $this->has_regraded_questions($table->sql->from, $table->sql->where, $table->sql->params)) {
145
                $columns[] = 'regraded';
146
                $headers[] = get_string('regrade', 'quiz_overview');
147
            }
148
 
149
            if ($options->slotmarks) {
150
                foreach ($questions as $slot => $question) {
151
                    $columns[] = 'qsgrade' . $slot;
11 efrain 152
                    $header = get_string('qbrief', 'quiz', $question->displaynumber);
1 efrain 153
                    if (!$table->is_downloading()) {
154
                        $header .= '<br />';
155
                    } else {
156
                        $header .= ' ';
157
                    }
158
                    $header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question');
159
                    $headers[] = $header;
160
                }
161
            }
162
 
163
            $this->set_up_table_columns($table, $columns, $headers, $this->get_base_url(), $options, false);
164
            $table->set_attribute('class', 'generaltable generalbox grades');
165
 
166
            $table->out($options->pagesize, true);
1441 ariadna 167
 
168
            if ($canregrade && !$table->is_downloading()) {
169
                $this->display_commit_regrade_if_required($quiz, $groupstudentsjoins, $options);
170
            }
1 efrain 171
        }
172
 
173
        if (!$table->is_downloading() && $options->usercanseegrades) {
174
            $output = $PAGE->get_renderer('mod_quiz');
175
            list($bands, $bandwidth) = self::get_bands_count_and_width($quiz);
176
            $labels = self::get_bands_labels($bands, $bandwidth, $quiz);
177
 
178
            if ($currentgroup && $this->hasgroupstudents) {
179
                $sql = "SELECT qg.id
180
                          FROM {quiz_grades} qg
181
                          JOIN {user} u on u.id = qg.userid
182
                        {$groupstudentsjoins->joins}
183
                          WHERE qg.quiz = $quiz->id AND {$groupstudentsjoins->wheres}";
184
                if ($DB->record_exists_sql($sql, $groupstudentsjoins->params)) {
185
                    $data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, $groupstudentsjoins);
186
                    $chart = self::get_chart($labels, $data);
187
                    $groupname = format_string(groups_get_group_name($currentgroup), true, [
188
                        'context' => $this->context,
189
                    ]);
190
                    $graphname = get_string('overviewreportgraphgroup', 'quiz_overview', $groupname);
191
                    // Numerical range data should display in LTR even for RTL languages.
192
                    echo $output->chart($chart, $graphname, ['dir' => 'ltr']);
193
                }
194
            }
195
 
196
            if ($DB->record_exists('quiz_grades', ['quiz' => $quiz->id])) {
197
                $data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, new \core\dml\sql_join());
198
                $chart = self::get_chart($labels, $data);
199
                $graphname = get_string('overviewreportgraph', 'quiz_overview');
200
                // Numerical range data should display in LTR even for RTL languages.
201
                echo $output->chart($chart, $graphname, ['dir' => 'ltr']);
202
            }
203
        }
1441 ariadna 204
 
1 efrain 205
        return true;
206
    }
207
 
208
    /**
1441 ariadna 209
     * If a previous dry run regrade had been done, display a message to commit the changes.
210
     *
211
     * @param stdClass $quiz quiz settings.
212
     * @param \core\dml\sql_join $groupstudentsjoins which users' attempts should be considered.
213
     * @param quiz_overview_options $options report options.
214
     */
215
    protected function display_commit_regrade_if_required(
216
        stdClass $quiz,
217
        \core\dml\sql_join $groupstudentsjoins,
218
        quiz_overview_options $options,
219
    ) {
220
        global $OUTPUT;
221
 
222
        [$attemptcount, $slotcount] = $this->count_attempts_and_questions_needing_regrade($quiz, $groupstudentsjoins);
223
        if (!$attemptcount) {
224
            return;
225
        }
226
 
227
        $commitregradeurl = new moodle_url($options->get_url(), ['sesskey' => sesskey(), 'regradealldrydo' => 1]);
228
 
229
        // We can't use $OUTPUT->notification because is aggressively cleans the message, which strips the button.
230
        echo html_writer::div(get_string('regrade_regradeneedednotificationmessage', 'quiz_overview',
231
                ['attempts' => $attemptcount, 'questions' => $slotcount]) . ' ' .
232
            $OUTPUT->single_button($commitregradeurl, get_string('regrade_commitregrade', 'quiz_overview')),
233
            'alert alert-info alert-block fade in');
234
    }
235
 
236
    #[\Override]
237
    protected function process_actions($quiz, $cm, $currentgroup, \core\dml\sql_join $groupstudentsjoins,
238
            \core\dml\sql_join $allowedjoins, $redirecturl) {
239
        parent::process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $redirecturl);
240
 
241
        // Process regrade actions.
242
        $this->process_regrade_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $redirecturl);
243
    }
244
 
245
    /**
1 efrain 246
     * Extends parent function processing any submitted actions.
247
     *
248
     * @param stdClass $quiz
249
     * @param stdClass $cm
250
     * @param int $currentgroup
251
     * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params)
252
     * @param moodle_url $redirecturl
253
     */
1441 ariadna 254
    protected function process_regrade_actions($quiz, $cm, $currentgroup,
255
            \core\dml\sql_join $groupstudentsjoins, moodle_url $redirecturl) {
1 efrain 256
 
1441 ariadna 257
        if ($currentgroup && !$this->hasgroupstudents) {
258
            return;
1 efrain 259
        }
1441 ariadna 260
        if (!has_capability('mod/quiz:regrade', $this->context)) {
261
            return;
262
        }
1 efrain 263
 
1441 ariadna 264
        $dryrun = optional_param('dryrunregrade', 0, PARAM_BOOL);
265
        if ($dryrun || optional_param('regrade', 0, PARAM_BOOL)) {
1 efrain 266
 
1441 ariadna 267
            $attemptids = [];
268
            if (optional_param('regradeselectedattempts', 0, PARAM_BOOL)) {
269
                $attemptids = optional_param_array('attemptid', [], PARAM_INT);
270
            }
271
 
272
            $slots = null;
273
            if (optional_param('regradeselectedquestions', 0, PARAM_BOOL)) {
274
                $slots = optional_param_array('regradeslot', [], PARAM_INT);
275
            }
276
 
1 efrain 277
            $this->start_regrade($quiz, $cm);
1441 ariadna 278
            $this->regrade_attempts($quiz, $dryrun, $groupstudentsjoins, $attemptids, $slots);
1 efrain 279
            $this->finish_regrade($redirecturl);
1441 ariadna 280
        }
1 efrain 281
 
1441 ariadna 282
        // Process commit of a previous dry run.
283
        if (optional_param('regradealldrydo', 0, PARAM_BOOL) && confirm_sesskey()) {
1 efrain 284
            $this->start_regrade($quiz, $cm);
285
            $this->regrade_attempts_needing_it($quiz, $groupstudentsjoins);
286
            $this->finish_regrade($redirecturl);
287
        }
288
    }
289
 
290
    /**
291
     * Check necessary capabilities, and start the display of the regrade progress page.
292
     * @param stdClass $quiz the quiz settings.
293
     * @param stdClass $cm the cm object for the quiz.
294
     */
295
    protected function start_regrade($quiz, $cm) {
296
        require_capability('mod/quiz:regrade', $this->context);
297
        $this->print_header_and_tabs(
298
            $cm,
299
            get_course($cm->course),
300
            $quiz,
301
            $this->mode
302
        );
303
    }
304
 
305
    /**
306
     * Finish displaying the regrade progress page.
307
     * @param moodle_url $nexturl where to send the user after the regrade.
308
     * @uses exit. This method never returns.
309
     */
310
    protected function finish_regrade($nexturl) {
311
        global $OUTPUT;
312
        \core\notification::success(get_string('regradecomplete', 'quiz_overview'));
313
        echo $OUTPUT->continue_button($nexturl);
314
        echo $OUTPUT->footer();
315
        die();
316
    }
317
 
318
    /**
319
     * Unlock the session and allow the regrading process to run in the background.
320
     */
321
    protected function unlock_session() {
322
        \core\session\manager::write_close();
323
        ignore_user_abort(true);
324
    }
325
 
326
    /**
327
     * Regrade a particular quiz attempt. Either for real ($dryrun = false), or
328
     * as a pretend regrade to see which fractions would change. The outcome is
329
     * stored in the quiz_overview_regrades table.
330
     *
331
     * Note, $attempt is not upgraded in the database. The caller needs to do that.
332
     * However, $attempt->sumgrades is updated, if this is not a dry run.
333
     *
334
     * @param stdClass $attempt the quiz attempt to regrade.
335
     * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
1441 ariadna 336
     * @param array|null $slots if null, regrade all questions, otherwise, just regrade
1 efrain 337
     *      the questions with those slots.
338
     * @return array messages array with keys slot number, and values reasons why that slot cannot be regraded.
339
     */
340
    public function regrade_attempt($attempt, $dryrun = false, $slots = null): array {
341
        global $DB;
342
        // Need more time for a quiz with many questions.
343
        core_php_time_limit::raise(300);
344
 
345
        $transaction = $DB->start_delegated_transaction();
346
 
347
        $quba = question_engine::load_questions_usage_by_activity($attempt->uniqueid);
348
        $versioninformation = qbank_helper::get_version_information_for_questions_in_attempt(
349
            $attempt, $this->context);
350
 
351
        if (is_null($slots)) {
352
            $slots = $quba->get_slots();
353
        }
354
 
355
        $messages = [];
356
        $finished = $attempt->state == quiz_attempt::FINISHED;
357
        foreach ($slots as $slot) {
358
            $qqr = new stdClass();
359
            $qqr->oldfraction = $quba->get_question_fraction($slot);
360
            $otherquestionversion = question_bank::load_question($versioninformation[$slot]->newquestionid);
361
 
362
            $message = $quba->validate_can_regrade_with_other_version($slot, $otherquestionversion);
363
            if ($message) {
364
                $messages[$slot] = $message;
365
                continue;
366
            }
367
 
368
            $quba->regrade_question($slot, $finished, null, $otherquestionversion);
369
 
370
            $qqr->newfraction = $quba->get_question_fraction($slot);
371
 
372
            if (abs($qqr->oldfraction - $qqr->newfraction) > 1e-7) {
373
                $qqr->questionusageid = $quba->get_id();
374
                $qqr->slot = $slot;
375
                $qqr->regraded = empty($dryrun);
376
                $qqr->timemodified = time();
377
                $DB->insert_record('quiz_overview_regrades', $qqr, false);
378
            }
379
        }
380
 
381
        if (!$dryrun) {
382
            question_engine::save_questions_usage_by_activity($quba);
383
 
384
            $params = [
385
              'objectid' => $attempt->id,
386
              'relateduserid' => $attempt->userid,
387
              'context' => $this->context,
388
              'other' => [
389
                'quizid' => $attempt->quiz
390
              ]
391
            ];
392
            $event = \mod_quiz\event\attempt_regraded::create($params);
393
            $event->trigger();
394
        }
395
 
396
        $transaction->allow_commit();
397
 
398
        // Really, PHP should not need this hint, but without this, we just run out of memory.
399
        $quba = null;
400
        $transaction = null;
401
        gc_collect_cycles();
402
        return $messages;
403
    }
404
 
405
    /**
406
     * Regrade attempts for this quiz, exactly which attempts are regraded is
407
     * controlled by the parameters.
408
     *
409
     * @param stdClass $quiz the quiz settings.
410
     * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
411
     * @param \core\dml\sql_join|null $groupstudentsjoins empty for all attempts, otherwise regrade attempts
412
     * for these users.
413
     * @param array $attemptids blank for all attempts, otherwise only regrade
414
     * attempts whose id is in this list.
1441 ariadna 415
     * @param array|null $slots if null, regrade all questions, otherwise, just regrade
416
     *      the questions with those slots.
1 efrain 417
     */
418
    protected function regrade_attempts($quiz, $dryrun = false,
1441 ariadna 419
            ?\core\dml\sql_join $groupstudentsjoins = null, $attemptids = [], ?array $slots = null) {
1 efrain 420
        global $DB;
421
        $this->unlock_session();
422
 
1441 ariadna 423
        // Get the attempts to regrade.
1 efrain 424
        $userfieldsapi = \core_user\fields::for_name();
425
        $sql = "SELECT quiza.*, " . $userfieldsapi->get_sql('u', false, '', '', false)->selects . "
426
                  FROM {quiz_attempts} quiza
427
                  JOIN {user} u ON u.id = quiza.userid";
428
        $where = "quiz = :qid AND preview = 0";
429
        $params = ['qid' => $quiz->id];
430
 
431
        if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
432
            $sql .= "\n{$groupstudentsjoins->joins}";
433
            $where .= " AND {$groupstudentsjoins->wheres}";
434
            $params += $groupstudentsjoins->params;
435
        }
436
 
437
        if ($attemptids) {
438
            list($attemptidcondition, $attemptidparams) = $DB->get_in_or_equal($attemptids, SQL_PARAMS_NAMED);
439
            $where .= " AND quiza.id $attemptidcondition";
440
            $params += $attemptidparams;
441
        }
442
 
443
        $sql .= "\nWHERE {$where}";
444
        $attempts = $DB->get_records_sql($sql, $params);
445
        if (!$attempts) {
446
            return;
447
        }
448
 
1441 ariadna 449
        // If only regrading some slots, put that information where regrade_batch_of_attempts expects.
450
        if ($slots) {
451
            foreach ($attempts as $attempt) {
452
                $attempt->regradeonlyslots = $slots;
453
            }
454
        }
455
 
456
        $this->regrade_batch_of_attempts($quiz, $attempts, $dryrun, $groupstudentsjoins, $slots);
1 efrain 457
    }
458
 
459
    /**
1441 ariadna 460
     * Regrade the questions in the attempts that are marked as needing it in quiz_overview_regrades.
461
     *
1 efrain 462
     * @param stdClass $quiz the quiz settings.
463
     * @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
1441 ariadna 464
     *      for these users.
1 efrain 465
     */
466
    protected function regrade_attempts_needing_it($quiz, \core\dml\sql_join $groupstudentsjoins) {
467
        global $DB;
468
        $this->unlock_session();
469
 
470
        $join = '{quiz_overview_regrades} qqr ON qqr.questionusageid = quiza.uniqueid';
471
        $where = "quiza.quiz = :qid AND quiza.preview = 0 AND qqr.regraded = 0";
472
        $params = ['qid' => $quiz->id];
473
 
474
        // Fetch all attempts that need regrading.
475
        if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
476
            $join .= "\nJOIN {user} u ON u.id = quiza.userid
477
                    {$groupstudentsjoins->joins}";
478
            $where .= " AND {$groupstudentsjoins->wheres}";
479
            $params += $groupstudentsjoins->params;
480
        }
481
 
482
        $toregrade = $DB->get_recordset_sql("
483
                SELECT quiza.uniqueid, qqr.slot
484
                  FROM {quiz_attempts} quiza
485
                  JOIN $join
486
                 WHERE $where", $params);
487
 
488
        $attemptquestions = [];
489
        foreach ($toregrade as $row) {
490
            $attemptquestions[$row->uniqueid][] = $row->slot;
491
        }
492
        $toregrade->close();
493
 
494
        if (!$attemptquestions) {
495
            return;
496
        }
497
 
498
        list($uniqueidcondition, $params) = $DB->get_in_or_equal(array_keys($attemptquestions));
499
        $userfieldsapi = \core_user\fields::for_name();
500
        $attempts = $DB->get_records_sql("
501
                SELECT quiza.*, " . $userfieldsapi->get_sql('u', false, '', '', false)->selects . "
502
                  FROM {quiz_attempts} quiza
503
                  JOIN {user} u ON u.id = quiza.userid
504
                 WHERE quiza.uniqueid $uniqueidcondition
505
                ", $params);
506
 
507
        foreach ($attempts as $attempt) {
508
            $attempt->regradeonlyslots = $attemptquestions[$attempt->uniqueid];
509
        }
510
 
511
        $this->regrade_batch_of_attempts($quiz, $attempts, false, $groupstudentsjoins);
512
    }
513
 
514
    /**
515
     * This is a helper used by {@link regrade_attempts()} and
516
     * {@link regrade_attempts_needing_it()}.
517
     *
518
     * Given an array of attempts, it regrades them all, or does a dry run.
519
     * Each object in the attempts array must be a row from the quiz_attempts
520
     * table, with the \core_user\fields::for_name() fields from the user table joined in.
521
     * In addition, if $attempt->regradeonlyslots is set, then only those slots
522
     * are regraded, otherwise all slots are regraded.
523
     *
524
     * @param stdClass $quiz the quiz settings.
525
     * @param array $attempts of data from the quiz_attempts table, with extra data as above.
526
     * @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
527
     * @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
528
     */
529
    protected function regrade_batch_of_attempts($quiz, array $attempts,
530
            bool $dryrun, \core\dml\sql_join $groupstudentsjoins) {
531
        global $OUTPUT;
532
        $this->clear_regrade_table($quiz, $groupstudentsjoins);
533
 
534
        $progressbar = new progress_bar('quiz_overview_regrade', 500, true);
535
        $a = [
536
            'count' => count($attempts),
537
            'done'  => 0,
538
        ];
539
        foreach ($attempts as $attempt) {
540
            $a['done']++;
541
            $a['attemptnum'] = $attempt->attempt;
542
            $a['name'] = fullname($attempt);
543
            $a['attemptid'] = $attempt->id;
544
            $progressbar->update($a['done'], $a['count'],
545
                    get_string('regradingattemptxofywithdetails', 'quiz_overview', $a));
1441 ariadna 546
            $messages = $this->regrade_attempt($attempt, $dryrun, $attempt->regradeonlyslots ?? null);
1 efrain 547
            if ($messages) {
548
                $items = [];
549
                foreach ($messages as $slot => $message) {
550
                    $items[] = get_string('regradingattemptissue', 'quiz_overview',
551
                            ['slot' => $slot, 'reason' => $message]);
552
                }
553
                echo $OUTPUT->notification(
554
                        html_writer::tag('p', get_string('regradingattemptxofyproblem', 'quiz_overview', $a)) .
555
                        html_writer::alist($items), \core\output\notification::NOTIFY_WARNING);
556
            }
557
        }
558
        $progressbar->update($a['done'], $a['count'],
559
                get_string('regradedsuccessfullyxofy', 'quiz_overview', $a));
560
 
561
        if (!$dryrun) {
562
            $this->update_overall_grades($quiz);
563
        }
564
    }
565
 
566
    /**
1441 ariadna 567
     * Count the number of attempts and questions in need of regrading after the last dry run.
1 efrain 568
     *
569
     * @param stdClass $quiz the quiz settings.
1441 ariadna 570
     * @param \core\dml\sql_join $groupstudentsjoins which users' attempts should be considered.
571
     * @return array of two elements: the number of different attempts and questions needed to be regraded.
1 efrain 572
     */
1441 ariadna 573
    protected function count_attempts_and_questions_needing_regrade($quiz,
574
            \core\dml\sql_join $groupstudentsjoins): array {
1 efrain 575
        global $DB;
576
 
577
        $userjoin = '';
578
        $usertest = '';
579
        $params = [];
580
        if ($this->hasgroupstudents) {
581
            $userjoin = "JOIN {user} u ON u.id = quiza.userid
582
                    {$groupstudentsjoins->joins}";
583
            $usertest = "{$groupstudentsjoins->wheres} AND u.id = quiza.userid AND ";
584
            $params = $groupstudentsjoins->params;
585
        }
586
 
587
        $params['cquiz'] = $quiz->id;
1441 ariadna 588
        $sql = "SELECT COUNT(DISTINCT quiza.id) AS attemptcount,
589
                       COUNT(DISTINCT qqr.slot) AS slotcount
1 efrain 590
                  FROM {quiz_attempts} quiza
591
                  JOIN {quiz_overview_regrades} qqr ON quiza.uniqueid = qqr.questionusageid
592
                $userjoin
593
                 WHERE
594
                      $usertest
595
                      quiza.quiz = :cquiz AND
596
                      quiza.preview = 0 AND
597
                      qqr.regraded = 0";
1441 ariadna 598
        $counts = $DB->get_record_sql($sql, $params);
599
        return [$counts->attemptcount, $counts->slotcount];
1 efrain 600
    }
601
 
602
    /**
603
     * Are there any pending regrades in the table we are going to show?
604
     * @param string $from tables used by the main query.
605
     * @param string $where where clause used by the main query.
606
     * @param array $params required by the SQL.
607
     * @return bool whether there are pending regrades.
608
     */
609
    protected function has_regraded_questions($from, $where, $params) {
610
        global $DB;
611
        return $DB->record_exists_sql("
612
                SELECT 1
613
                  FROM {$from}
614
                  JOIN {quiz_overview_regrades} qor ON qor.questionusageid = quiza.uniqueid
615
                 WHERE {$where}", $params);
616
    }
617
 
618
    /**
619
     * Remove all information about pending/complete regrades from the database.
620
     * @param stdClass $quiz the quiz settings.
621
     * @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params). If this is given, only data relating
622
     * to these users is cleared.
623
     */
624
    protected function clear_regrade_table($quiz, \core\dml\sql_join $groupstudentsjoins) {
625
        global $DB;
626
 
627
        // Fetch all attempts that need regrading.
628
        $select = "questionusageid IN (
629
                    SELECT uniqueid
630
                      FROM {quiz_attempts} quiza";
631
        $where = "WHERE quiza.quiz = :qid";
632
        $params = ['qid' => $quiz->id];
633
        if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
634
            $select .= "\nJOIN {user} u ON u.id = quiza.userid
635
                    {$groupstudentsjoins->joins}";
636
            $where .= " AND {$groupstudentsjoins->wheres}";
637
            $params += $groupstudentsjoins->params;
638
        }
639
        $select .= "\n$where)";
640
 
641
        $DB->delete_records_select('quiz_overview_regrades', $select, $params);
642
    }
643
 
644
    /**
645
     * Update the final grades for all attempts. This method is used following a regrade.
646
     *
647
     * @param stdClass $quiz the quiz settings.
648
     */
649
    protected function update_overall_grades($quiz) {
650
        $gradecalculator = $this->quizobj->get_grade_calculator();
651
        $gradecalculator->recompute_all_attempt_sumgrades();
652
        $gradecalculator->recompute_all_final_grades();
653
        quiz_update_grades($quiz);
654
    }
655
 
656
    /**
657
     * Get the bands configuration for the quiz.
658
     *
659
     * This returns the configuration for having between 11 and 20 bars in
660
     * a chart based on the maximum grade to be given on a quiz. The width of
661
     * a band is the number of grade points it encapsulates.
662
     *
663
     * @param stdClass $quiz The quiz object.
664
     * @return array Contains the number of bands, and their width.
665
     */
666
    public static function get_bands_count_and_width($quiz) {
667
        $bands = $quiz->grade;
668
        while ($bands > 20 || $bands <= 10) {
669
            if ($bands > 50) {
670
                $bands /= 5;
671
            } else if ($bands > 20) {
672
                $bands /= 2;
673
            }
674
            if ($bands < 4) {
675
                $bands *= 5;
676
            } else if ($bands <= 10) {
677
                $bands *= 2;
678
            }
679
        }
680
        // See MDL-34589. Using doubles as array keys causes problems in PHP 5.4, hence the explicit cast to int.
681
        $bands = (int) ceil($bands);
682
        return [$bands, $quiz->grade / $bands];
683
    }
684
 
685
    /**
686
     * Get the bands labels.
687
     *
688
     * @param int $bands The number of bands.
689
     * @param int $bandwidth The band width.
690
     * @param stdClass $quiz The quiz object.
691
     * @return string[] The labels.
692
     */
693
    public static function get_bands_labels($bands, $bandwidth, $quiz) {
694
        $bandlabels = [];
695
        for ($i = 1; $i <= $bands; $i++) {
696
            $bandlabels[] = quiz_format_grade($quiz, ($i - 1) * $bandwidth) . ' - ' . quiz_format_grade($quiz, $i * $bandwidth);
697
        }
698
        return $bandlabels;
699
    }
700
 
701
    /**
702
     * Get a chart.
703
     *
704
     * @param string[] $labels Chart labels.
705
     * @param int[] $data The data.
706
     * @return \core\chart_base
707
     */
708
    protected static function get_chart($labels, $data) {
709
        $chart = new \core\chart_bar();
710
        $chart->set_labels($labels);
711
        $chart->get_xaxis(0, true)->set_label(get_string('gradenoun'));
712
 
713
        $yaxis = $chart->get_yaxis(0, true);
714
        $yaxis->set_label(get_string('participants'));
715
        $yaxis->set_stepsize(max(1, round(max($data) / 10)));
716
 
717
        $series = new \core\chart_series(get_string('participants'), $data);
718
        $chart->add_series($series);
719
        return $chart;
720
    }
721
}