From dfd0dc28e8c7c37b5ad5ddb2ea4ef56aa296bf61 Mon Sep 17 00:00:00 2001 From: Mark Johnson Date: Wed, 21 May 2025 16:31:48 +0100 Subject: [PATCH] MDL-85556 backup: Only update question refs in restored course The previous query updated all question references matching the original question bank entry, regardless of whether they were part of the restore or not. When we are dealing with duplicated questions, this means we could accidentally change question references in the backed-up course as well as the restored one. This change filters the references to ensure they exist in a context within the restored course, before updating them. --- backup/moodle2/restore_stepslib.php | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/backup/moodle2/restore_stepslib.php b/backup/moodle2/restore_stepslib.php index 83e7ea8fcd1..3a65aaf2724 100644 --- a/backup/moodle2/restore_stepslib.php +++ b/backup/moodle2/restore_stepslib.php @@ -5487,18 +5487,39 @@ class restore_move_module_questions_categories extends restore_execution_step { $originalcontext = context::instance_by_id($contextid, IGNORE_MISSING); if ($originalcontext && has_capability('mod/qbank:view', $originalcontext)) { $originalquestions = get_questions_category(question_get_top_category($contextid), false); + $targetcoursecontext = context_course::instance($this->get_courseid()); foreach ($originalquestions as $originalquestion) { $backupids = restore_dbops::get_backup_ids_record( $this->get_restoreid(), 'question', $originalquestion->id, ); + // Restored question references will point to the restored copy of the question. Select question references + // that point to that restored copy, only if they are within the target course's context, so we can update + // them to point to the original question. + $conpathlike = $DB->sql_like('con.path', '?'); + $references = $DB->get_records_sql( + "SELECT qr.id, qr.questionbankentryid + FROM {question_references} qr + JOIN {context} con ON qr.usingcontextid = con.id + JOIN {question_versions} qv ON qv.questionbankentryid = qr.questionbankentryid + WHERE qv.questionid = ? + AND {$conpathlike}", + [ + $backupids->newitemid, + $targetcoursecontext->path . '/%', + ], + ); + if (empty($references)) { + continue; + } + [$refin, $refparams] = $DB->get_in_or_equal(array_keys($references)); $DB->set_field_select( 'question_references', 'questionbankentryid', $DB->get_field('question_versions', 'questionbankentryid', ['questionid' => $backupids->itemid]), - 'questionbankentryid = (SELECT questionbankentryid FROM {question_versions} WHERE questionid = ?)', - [$backupids->newitemid], + 'id ' . $refin, + $refparams, ); } continue;