MDL Shield

Quiz archive report

quiz_archive

Print Report
Plugin Information

Quiz report subplugin (quiz_archive) that renders the full review page (summary table, every question with responses, feedback, correct answers and optional response history) for every non-preview attempt in a quiz on a single page, so teachers can print or save all attempts as PDF for archiving.

Version:2026120100
Release:v5.3-r3
Reviewed for:5.3
Privacy API
Unit Tests
Behat Tests
Reviewed:2026-12-01
11 files·1,294 lines
Grade Justification

No security vulnerabilities were found. Access to the report is gated by the core dispatcher (require_login() plus mod/quiz:viewreports via quiz_report_list()) and then by an explicit require_capability('mod/quiz:grade') before any attempt data is rendered. The student list comes from core's get_enrolled_with_capabilities_join() and the separate-groups logic in report_base::get_current_group(), so teachers in separate-groups mode only see their own groups. The only SQL query is parameterised. The settings form is a moodleform and changes nothing but display toggles. All output goes through core quiz and question renderers.

All findings are low or info:

  • A missing DISTINCT that causes developer debugging noise when a student has more than one enrolment.
  • The new 5.3 report navigation bar is not rendered.
  • The report's required capability is not registered with the quiz report framework.
  • $plugin->requires does not match the declared supported range.
  • The whole archive is rendered in one request without raising time limits.
  • One unit test makes no assertions.

None of these can be exploited by any role. Together they amount to minor compatibility and code-quality debt in an otherwise small, well-structured plugin with PHPUnit and Behat coverage.

AI Summary

quiz_archive is a small quiz report subplugin of about 700 lines of PHP. One report class, a settings form, an options class and an install/upgrade script render every student's attempt review on one printable page. There is no JavaScript, no templates, no bundled third-party code and no data storage, and the null privacy provider correctly reflects that.

The security posture is good. The page can only be reached through mod/quiz/report.php (require_login() and mod/quiz:viewreports), and the report itself enforces mod/quiz:grade before rendering anything. Student selection uses core's enrolment/capability joins and the standard separate-groups handling. The one SQL query uses placeholders, and all HTML is produced by core quiz and question renderers. I found no XSS, CSRF, SQL injection or access-control issues.

The findings worth acting on concern Moodle 5.3 compatibility, which the plugin claims in $plugin->supported. The page never calls the new print_action_bar(), and 5.3's report.php disables the old overflow menu, so the archive page has no report switcher. The report's mod/quiz:grade requirement is also not registered in quiz_reports.capability or has_permission(). As a result, users with mod/quiz:viewreports but without mod/quiz:grade see an Archive entry that fails when they open it. The remaining findings are small code-quality items: a missing DISTINCT, an outdated requires value, no time-limit raise for a potentially very large page, and a test without assertions.

Findings

code qualityLow
Attempt query lacks DISTINCT, duplicating rows for multi-enrolled users

quizreportgetstudentandattempts() joins the core enrolment fragment from get_enrolled_with_capabilities_join() without DISTINCT. That fragment joins {user_enrolments} and {enrol} directly, so a student enrolled in the course through two methods (e.g. manual plus cohort sync or meta link) produces one row per enrolment for each attempt. get_records_sql() keys results on the first column (attemptid), so the duplicates collapse. With developer debugging on, though, each one triggers a "Did you remember to make the first column something unique…" notice on the report page, and the database returns redundant rows. Core's attempts_report_table::base_sql() uses DISTINCT with this same join for exactly this reason.

Risk Assessment

Low risk. Rendering is not functionally affected because duplicate keys overwrite each other in PHP's result array. The impact is debugging noise and wasted rows on sites where students hold more than one enrolment.

Context

display_archive() iterates the returned list and renders each attempt. get_enrolled_join() in lib/enrollib.php emits JOIN {user_enrolments} ... JOIN {enrol} ... without deduplication.

Identified Code
        $sql = "SELECT quiza.id AS attemptid, u.id AS userid, u.firstname, u.lastname
                  FROM {user} u
                  JOIN {quiz_attempts} quiza ON quiza.userid = u.id
                  {$joins->joins}
                 WHERE quiza.quiz = :quizid AND quiza.preview = 0
                   AND {$joins->wheres}
              ORDER BY u.lastname, u.firstname";
Suggested Fix
        $sql = "SELECT DISTINCT quiza.id AS attemptid, u.id AS userid, u.firstname, u.lastname
                  FROM {user} u
                  JOIN {quiz_attempts} quiza ON quiza.userid = u.id
                  {$joins->joins}
                 WHERE quiza.quiz = :quizid AND quiza.preview = 0
                   AND {$joins->wheres}
              ORDER BY u.lastname, u.firstname";

The ORDER BY columns are already in the select list, so this is portable to PostgreSQL.

code qualityLow
Moodle 5.3 report navigation bar not rendered on the archive page

In Moodle 5.3, mod/quiz/report.php calls $PAGE->set_navigation_overflow_state(false). This disables the tertiary overflow menu that used to list the quiz reports, and expects each report to call the new report_base::print_action_bar() instead. The archive report only calls print_header_and_tabs(), so on 5.3 the page has no report selector for switching to Grades, Responses, Statistics or Manual grading. The plugin declares $plugin->supported = [400, 503], and mod/quiz/UPGRADING.md (5.3, Changed) explicitly asks custom reports to adopt print_action_bar(). The plugin's own groups_print_activity_menu() call keeps the group selector working, but it would duplicate the selector the action bar renders once that bar is added.

Risk Assessment

Low risk. This is a functional regression in navigation on 5.3 only. Users must go back through the quiz's Results link to reach other reports. No data or access-control impact.

Context

quiz_report_navigation_bar (rendered only by print_action_bar()) contains the quiz_report_action_selector report switcher. In 5.3, secondary::get_overflow_menu_data() returns null when overflow is disabled, so no other page element provides that switcher.

Identified Code
        $this->print_header_and_tabs($cm, $course, $quiz, 'archive');

        $this->form->display();
Suggested Fix
        $this->print_header_and_tabs($cm, $course, $quiz, 'archive');
        $hasactionbar = method_exists($this, 'print_action_bar');
        if ($hasactionbar) {
            // Moodle 5.3+: report selector and group selector.
            $this->print_action_bar('archive', null, $cm, $this->get_base_url());
        }

        $this->form->display();
Identified Code
            if (groups_get_activity_groupmode($cm)) {
                groups_print_activity_menu($cm, $this->get_base_url());
            }
Suggested Fix

Only print the legacy group menu when the action bar is not available:

            if (!$hasactionbar && groups_get_activity_groupmode($cm)) {
                groups_print_activity_menu($cm, $this->get_base_url());
            }
best practiceLow
Report capability not registered with the quiz report framework

The report requires mod/quiz:grade, but db/install.php inserts the quiz_reports row without a capability value. quiz_report_list() therefore falls back to mod/quiz:viewreports when deciding who sees the Archive entry. On sites where a role has mod/quiz:viewreports but not mod/quiz:grade, users are offered the report and then get a required capability exception. The check also sits in display() rather than in an override of report_base::has_permission(). The 5.3 mod/quiz/UPGRADING.md recommends overriding that method, because the mod_quiz_get_users_in_report web service calls it. The web service currently returns nothing for this report because setup_report_data() is not implemented, so this is a robustness gap rather than an exposure. Core's quiz_grading report, which has the same requirement, registers capability = 'mod/quiz:grade' and overrides has_permission().

Risk Assessment

Low risk. No data is exposed: the stricter check still runs before anything is rendered. The impact is a broken navigation entry for customised roles and reliance on display() alone for the permission check.

Context

quiz_report_list() in mod/quiz/report/reportlib.php reads name, capability from {quiz_reports} and uses mod/quiz:viewreports when capability is empty. The dispatcher only lets users open reports in that list, and display() then applies the stricter mod/quiz:grade check.

Identified Code
    $record = new stdClass();
    $record->name         = 'archive';
    $record->displayorder = '2000';

    $DB->insert_record('quiz_reports', $record);
Suggested Fix
    $record = new stdClass();
    $record->name         = 'archive';
    $record->displayorder = '2000';
    $record->capability   = 'mod/quiz:grade';

    $DB->insert_record('quiz_reports', $record);

Add a matching db/upgrade.php step ($DB->set_field('quiz_reports', 'capability', 'mod/quiz:grade', ['name' => 'archive'])) for existing installs.

Identified Code
        $this->context = context_module::instance($cm->id);
        require_capability('mod/quiz:grade', $this->context);
Suggested Fix

Move the check into an override that both display() and core's web service use:

    public function has_permission(context $context): void {
        require_capability('mod/quiz:grade', $context);
    }

Then call $this->has_permission($this->context); in display(). On pre-5.3 the base method does not exist, but defining it in the subclass is harmless.

code qualityLow
`$plugin->requires` allows installation on versions the code doesn't support

version.php sets $plugin->requires = 2017110800 (Moodle 3.4). The same file declares $plugin->supported = [400, 503], and the README states the plugin requires Moodle 4.0. Core uses requires as the hard installation gate, while supported is only advisory, so the plugin can be installed on 3.4–3.11 sites it is not tested against. For example, the code relies on PHP 7.1 short-list destructuring ([$currentgroup, ...] = $this->init(...)), which does not parse on the PHP 7.0 runtime that Moodle 3.4 allows.

Risk Assessment

Low risk. On an unsupported older site an admin could install the plugin and get fatal errors on the report page. There is no impact on supported versions.

Context

core\plugininfo\base loads supported into pluginsupported, which plugin_manager::check_explicitly_supported() only reports on; dependency resolution blocks installation based on requires.

Identified Code
$plugin->requires = 2017110800;
Suggested Fix
$plugin->requires = 2022041900; // Moodle 4.0.
best practiceLow
Entire archive rendered in one request without raising time/memory limits

display_archive() loads and fully renders every attempt of every student (summary table plus each question, including response history and step users) in a single HTTP request. There is no core_php_time_limit::raise() or raise_memory_limit() and no pagination. On large courses (hundreds of attempts × dozens of questions, random questions with many distinct definitions) the page can exceed the web server's max_execution_time and stop part-way, leaving an incomplete archive. Core's comparable heavy reports (quiz_overview, quiz_responses, quiz_statistics) explicitly raise these limits.

Risk Assessment

Low risk. This is a reliability problem for large quizzes, and only teachers who can view the report can trigger it.

Context

Each iteration calls quiz_create_attempt_handling_errors() and question_engine::load_questions_usage_by_activity(), then renders every slot. mod/quiz/report.php defines NO_OUTPUT_BUFFERING, so output streams, but PHP's execution-time limit still applies.

Identified Code
    protected function display_archive() {
        global $OUTPUT;
        $studentattempts = $this->quizreportgetstudentandattempts($this->quiz);
        if (count($studentattempts) === 0) {
            echo $OUTPUT->notification(get_string('nothingfound', 'quiz_grading'));
        }
        foreach ($studentattempts as $studentattempt) {
            echo $this->quiz_report_get_student_attempt($studentattempt['attemptid'], $studentattempt['userid']);
        }
    }
Suggested Fix
        $studentattempts = $this->quizreportgetstudentandattempts($this->quiz);
        \core_php_time_limit::raise();
        raise_memory_limit(MEMORY_EXTRA);

For very large quizzes, consider paging (e.g. by group or N attempts per page).

code qualityInfo
Unit test for the showuserpicture case makes no assertions

The docblock of test_get_student_attempt_output_with_showuserpicture() says the student's name must appear in the summary when showuserpicture is enabled, the regression fixed for MDL-84560. The test captures $output but never asserts anything about it. Moodle's phpunit.xml.dist sets beStrictAboutTestsThatDoNotTestAnything="false", so the test always passes silently. The Behat scenario in basic.feature does cover this behaviour, so the gap is in the PHPUnit suite only.

Risk Assessment

No runtime risk. A future regression in the showuserpicture override would not be caught by PHPUnit.

Context

The sibling test test_get_student_attempt_output() makes the same call and does assert the name; this variant only changes the quiz's showuserpicture setting.

Identified Code
        $output = $this->call_protected(
            $report,
            'quiz_report_get_student_attempt',
            [$attemptobj1->get_attemptid(), $student1->id]
        );
    }
Suggested Fix
        $output = $this->call_protected(
            $report,
            'quiz_report_get_student_attempt',
            [$attemptobj1->get_attemptid(), $student1->id]
        );

        $this->assertStringContainsString('Archibald', $output);
        $this->assertStringContainsString('Testington', $output);
    }
Additional AI Notes

Unscoped print CSS. styles.css is loaded on every page of the site, and several of its @media print rules are not tied to the archive report:

  • header[role=banner], #region-main.has-blocks and div.history.clearfix, div.que .info apply wherever they match.
  • .row-fluid .span9 / [class*="span"] target the Bootstrap 2 grid of the long-removed bootstrapbase theme.

The impact is cosmetic and print-only. Still, adding a body class from the report (e.g. $PAGE->add_body_class('quiz-report-archive')) and prefixing the rules with it would stop them affecting printouts of other pages, such as the core quiz review page.

Unused work in display(). $this->questions = quiz_report_get_significant_questions($quiz); builds a full quiz_settings/structure object on every request, but $this->questions is never read. Similarly, the $userid parameter of quiz_report_get_student_attempt() is unused. Removing both would save a few queries per page load.

Single failure aborts the whole archive. quiz_create_attempt_handling_errors() throws moodle_exception when an attempt cannot be loaded (for example after a question it used was deleted). Because all attempts are rendered in one loop, one broken attempt stops the entire archive page. Catching the exception per attempt and printing a notification would make the report more robust for its archiving purpose.

Privacy. The null_provider is appropriate: the plugin only reads and renders existing quiz attempt data and stores nothing of its own. The quiz_reports row created in db/install.php is removed by core's mod_quiz\plugininfo\quiz::uninstall_cleanup(), so no db/uninstall.php is needed.

This review was generated by an AI system and may contain inaccuracies. Findings should be verified by a human reviewer before acting on them.