MDL-63626 mod_quiz: Fixed a bug when there was no attempt on the quiz
[moodle.git] / mod / quiz / classes / privacy / provider.php
CommitLineData
4c729982
AN
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 * Privacy Subsystem implementation for mod_quiz.
19 *
20 * @package mod_quiz
21 * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace mod_quiz\privacy;
26
27use \core_privacy\local\request\writer;
28use \core_privacy\local\request\transform;
29use \core_privacy\local\request\contextlist;
30use \core_privacy\local\request\approved_contextlist;
31use \core_privacy\local\request\deletion_criteria;
32use \core_privacy\local\metadata\collection;
33use \core_privacy\manager;
34
35defined('MOODLE_INTERNAL') || die();
36
37require_once($CFG->dirroot . '/mod/quiz/lib.php');
38require_once($CFG->dirroot . '/mod/quiz/locallib.php');
39
40/**
41 * Privacy Subsystem implementation for mod_quiz.
42 *
43 * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 */
46class provider implements
47 // This plugin has data.
48 \core_privacy\local\metadata\provider,
49
50 // This plugin currently implements the original plugin_provider interface.
51 \core_privacy\local\request\plugin\provider {
52
53 /**
54 * Get the list of contexts that contain user information for the specified user.
55 *
56 * @param collection $items The collection to add metadata to.
57 * @return collection The array of metadata
58 */
59 public static function get_metadata(collection $items) : collection {
60 // The table 'quiz' stores a record for each quiz.
61 // It does not contain user personal data, but data is returned from it for contextual requirements.
62
63 // The table 'quiz_attempts' stores a record of each quiz attempt.
64 // It contains a userid which links to the user making the attempt and contains information about that attempt.
65 $items->add_database_table('quiz_attempts', [
66 'attempt' => 'privacy:metadata:quiz_attempts:attempt',
67 'currentpage' => 'privacy:metadata:quiz_attempts:currentpage',
68 'preview' => 'privacy:metadata:quiz_attempts:preview',
69 'state' => 'privacy:metadata:quiz_attempts:state',
70 'timestart' => 'privacy:metadata:quiz_attempts:timestart',
71 'timefinish' => 'privacy:metadata:quiz_attempts:timefinish',
72 'timemodified' => 'privacy:metadata:quiz_attempts:timemodified',
73 'timemodifiedoffline' => 'privacy:metadata:quiz_attempts:timemodifiedoffline',
74 'timecheckstate' => 'privacy:metadata:quiz_attempts:timecheckstate',
75 'sumgrades' => 'privacy:metadata:quiz_attempts:sumgrades',
76 ], 'privacy:metadata:quiz_attempts');
77
78 // The table 'quiz_feedback' contains the feedback responses which will be shown to users depending upon the
79 // grade they achieve in the quiz.
80 // It does not identify the user who wrote the feedback item so cannot be returned directly and is not
81 // described, but relevant feedback items will be included with the quiz export for a user who has a grade.
82
83 // The table 'quiz_grades' contains the current grade for each quiz/user combination.
84 $items->add_database_table('quiz_grades', [
85 'quiz' => 'privacy:metadata:quiz_grades:quiz',
86 'userid' => 'privacy:metadata:quiz_grades:userid',
87 'grade' => 'privacy:metadata:quiz_grades:grade',
88 'timemodified' => 'privacy:metadata:quiz_grades:timemodified',
89 ], 'privacy:metadata:quiz_grades');
90
91 // The table 'quiz_overrides' contains any user or group overrides for users.
92 // It should be included where data exists for a user.
93 $items->add_database_table('quiz_overrides', [
94 'quiz' => 'privacy:metadata:quiz_overrides:quiz',
95 'userid' => 'privacy:metadata:quiz_overrides:userid',
96 'timeopen' => 'privacy:metadata:quiz_overrides:timeopen',
97 'timeclose' => 'privacy:metadata:quiz_overrides:timeclose',
98 'timelimit' => 'privacy:metadata:quiz_overrides:timelimit',
99 ], 'privacy:metadata:quiz_overrides');
100
101 // These define the structure of the quiz.
102
103 // The table 'quiz_sections' contains data about the structure of a quiz.
104 // It does not contain any user identifying data and does not need a mapping.
105
106 // The table 'quiz_slots' contains data about the structure of a quiz.
107 // It does not contain any user identifying data and does not need a mapping.
108
109 // The table 'quiz_reports' does not contain any user identifying data and does not need a mapping.
110
111 // The table 'quiz_statistics' contains abstract statistics about question usage and cannot be mapped to any
112 // specific user.
113 // It does not contain any user identifying data and does not need a mapping.
114
115 // The quiz links to the 'core_question' subsystem for all question functionality.
116 $items->add_subsystem_link('core_question', [], 'privacy:metadata:core_question');
117
118 // The quiz has two subplugins..
119 $items->add_plugintype_link('quiz', [], 'privacy:metadata:quiz');
120 $items->add_plugintype_link('quizaccess', [], 'privacy:metadata:quizaccess');
121
122 // Although the quiz supports the core_completion API and defines custom completion items, these will be
123 // noted by the manager as all activity modules are capable of supporting this functionality.
124
125 return $items;
126 }
127
128 /**
129 * Get the list of contexts where the specified user has attempted a quiz, or been involved with manual marking
130 * and/or grading of a quiz.
131 *
132 * @param int $userid The user to search.
133 * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
134 */
135 public static function get_contexts_for_userid(int $userid) : contextlist {
44b30f9c
SR
136 $resultset = new contextlist();
137
138 // Users who attempted the quiz.
139 $sql = "SELECT c.id
140 FROM {context} c
141 JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel
142 JOIN {modules} m ON m.id = cm.module AND m.name = :modname
143 JOIN {quiz} q ON q.id = cm.instance
144 JOIN {quiz_attempts} qa ON qa.quiz = q.id
145 WHERE qa.userid = :userid AND qa.preview = 0";
146 $params = ['contextlevel' => CONTEXT_MODULE, 'modname' => 'quiz', 'userid' => $userid];
147 $resultset->add_from_sql($sql, $params);
148
149 // Users with quiz overrides.
150 $sql = "SELECT c.id
151 FROM {context} c
152 JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel
153 JOIN {modules} m ON m.id = cm.module AND m.name = :modname
154 JOIN {quiz} q ON q.id = cm.instance
155 JOIN {quiz_overrides} qo ON qo.quiz = q.id
156 WHERE qo.userid = :userid";
157 $params = ['contextlevel' => CONTEXT_MODULE, 'modname' => 'quiz', 'userid' => $userid];
158 $resultset->add_from_sql($sql, $params);
159
4c729982
AN
160 // Get the SQL used to link indirect question usages for the user.
161 // This includes where a user is the manual marker on a question attempt.
162 $qubaid = \core_question\privacy\provider::get_related_question_usages_for_user('rel', 'mod_quiz', 'qa.uniqueid', $userid);
163
164 // Select the context of any quiz attempt where a user has an attempt, plus the related usages.
165 $sql = "SELECT c.id
166 FROM {context} c
167 JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel
168 JOIN {modules} m ON m.id = cm.module AND m.name = :modname
169 JOIN {quiz} q ON q.id = cm.instance
170 JOIN {quiz_attempts} qa ON qa.quiz = q.id
4c729982 171 " . $qubaid->from . "
44b30f9c
SR
172 WHERE " . $qubaid->where() . " AND qa.preview = 0";
173 $params = ['contextlevel' => CONTEXT_MODULE, 'modname' => 'quiz'] + $qubaid->from_where_params();
4c729982
AN
174 $resultset->add_from_sql($sql, $params);
175
176 return $resultset;
177 }
178
179 /**
44b30f9c 180 * Export all user data for the specified user, in the specified contexts.
4c729982
AN
181 *
182 * @param approved_contextlist $contextlist The approved contexts to export information for.
183 */
184 public static function export_user_data(approved_contextlist $contextlist) {
185 global $DB;
186
187 if (!count($contextlist)) {
188 return;
189 }
190
191 $user = $contextlist->get_user();
192 $userid = $user->id;
193 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
194
195 $sql = "SELECT
196 q.*,
197 qg.id AS hasgrade,
198 qg.grade AS bestgrade,
199 qg.timemodified AS grademodified,
200 qo.id AS hasoverride,
201 qo.timeopen AS override_timeopen,
202 qo.timeclose AS override_timeclose,
203 qo.timelimit AS override_timelimit,
204 c.id AS contextid,
205 cm.id AS cmid
206 FROM {context} c
207 INNER JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel
208 INNER JOIN {modules} m ON m.id = cm.module AND m.name = :modname
209 INNER JOIN {quiz} q ON q.id = cm.instance
210 LEFT JOIN {quiz_overrides} qo ON qo.quiz = q.id AND qo.userid = :qouserid
211 LEFT JOIN {quiz_grades} qg ON qg.quiz = q.id AND qg.userid = :qguserid
212 WHERE c.id {$contextsql}";
213
214 $params = [
215 'contextlevel' => CONTEXT_MODULE,
216 'modname' => 'quiz',
217 'qguserid' => $userid,
218 'qouserid' => $userid,
219 ];
220 $params += $contextparams;
221
222 // Fetch the individual quizzes.
223 $quizzes = $DB->get_recordset_sql($sql, $params);
224 foreach ($quizzes as $quiz) {
225 list($course, $cm) = get_course_and_cm_from_cmid($quiz->cmid, 'quiz');
226 $quizobj = new \quiz($quiz, $cm, $course);
227 $context = $quizobj->get_context();
228
229 $quizdata = \core_privacy\local\request\helper::get_context_data($context, $contextlist->get_user());
230 \core_privacy\local\request\helper::export_context_files($context, $contextlist->get_user());
231
232 if (!empty($quizdata->timeopen)) {
233 $quizdata->timeopen = transform::datetime($quiz->timeopen);
234 }
235 if (!empty($quizdata->timeclose)) {
236 $quizdata->timeclose = transform::datetime($quiz->timeclose);
237 }
238 if (!empty($quizdata->timelimit)) {
239 $quizdata->timelimit = $quiz->timelimit;
240 }
241
242 if (!empty($quiz->hasoverride)) {
243 $quizdata->override = (object) [];
244
245 if (!empty($quizdata->override_override_timeopen)) {
246 $quizdata->override->timeopen = transform::datetime($quiz->override_timeopen);
247 }
248 if (!empty($quizdata->override_timeclose)) {
249 $quizdata->override->timeclose = transform::datetime($quiz->override_timeclose);
250 }
251 if (!empty($quizdata->override_timelimit)) {
252 $quizdata->override->timelimit = $quiz->override_timelimit;
253 }
254 }
255
256 $quizdata->accessdata = (object) [];
257
258 $components = \core_component::get_plugin_list('quizaccess');
259 $exportparams = [
260 $quizobj,
261 $user,
262 ];
263 foreach (array_keys($components) as $component) {
264 $classname = manager::get_provider_classname_for_component("quizaccess_$component");
265 if (class_exists($classname) && is_subclass_of($classname, quizaccess_provider::class)) {
266 $result = component_class_callback($classname, 'export_quizaccess_user_data', $exportparams);
267 if (count((array) $result)) {
268 $quizdata->accessdata->$component = $result;
269 }
270 }
271 }
272
273 if (empty((array) $quizdata->accessdata)) {
274 unset($quizdata->accessdata);
275 }
276
277 writer::with_context($context)
278 ->export_data([], $quizdata);
279 }
280 $quizzes->close();
281
282 // Store all quiz attempt data.
283 static::export_quiz_attempts($contextlist);
284 }
285
286 /**
287 * Delete all data for all users in the specified context.
288 *
289 * @param context $context The specific context to delete data for.
290 */
291 public static function delete_data_for_all_users_in_context(\context $context) {
63b0f627
AN
292 if ($context->contextlevel != CONTEXT_MODULE) {
293 // Only quiz module will be handled.
294 return;
295 }
296
4c729982
AN
297 $cm = get_coursemodule_from_id('quiz', $context->instanceid);
298 if (!$cm) {
299 // Only quiz module will be handled.
300 return;
301 }
63b0f627
AN
302
303 $quizobj = \quiz::create($cm->instance);
304 $quiz = $quizobj->get_quiz();
4c729982
AN
305
306 // Handle the 'quizaccess' subplugin.
307 manager::plugintype_class_callback(
308 'quizaccess',
309 quizaccess_provider::class,
310 'delete_subplugin_data_for_all_users_in_context',
63b0f627 311 [$quizobj]
4c729982
AN
312 );
313
314 // Delete all overrides - do not log.
315 quiz_delete_all_overrides($quiz, false);
316
317 // This will delete all question attempts, quiz attempts, and quiz grades for this quiz.
318 quiz_delete_all_attempts($quiz);
319 }
320
321 /**
322 * Delete all user data for the specified user, in the specified contexts.
323 *
324 * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
325 */
326 public static function delete_data_for_user(approved_contextlist $contextlist) {
327 global $DB;
328
329 foreach ($contextlist as $context) {
63b0f627
AN
330 if ($context->contextlevel != CONTEXT_MODULE) {
331 // Only quiz module will be handled.
332 continue;
333 }
334
4c729982 335 $cm = get_coursemodule_from_id('quiz', $context->instanceid);
63b0f627
AN
336 if (!$cm) {
337 // Only quiz module will be handled.
338 continue;
339 }
340
341 // Fetch the details of the data to be removed.
342 $quizobj = \quiz::create($cm->instance);
343 $quiz = $quizobj->get_quiz();
4c729982
AN
344 $user = $contextlist->get_user();
345
346 // Handle the 'quizaccess' quizaccess.
347 manager::plugintype_class_callback(
348 'quizaccess',
349 quizaccess_provider::class,
350 'delete_quizaccess_data_for_user',
63b0f627 351 [$quizobj, $user]
4c729982
AN
352 );
353
63b0f627 354 // Remove overrides for this user.
4c729982 355 $overrides = $DB->get_records('quiz_overrides' , [
63b0f627
AN
356 'quiz' => $quizobj->get_quizid(),
357 'userid' => $user->id,
358 ]);
4c729982
AN
359
360 foreach ($overrides as $override) {
361 quiz_delete_override($quiz, $override->id, false);
362 }
363
364 // This will delete all question attempts, quiz attempts, and quiz grades for this quiz.
63b0f627 365 quiz_delete_user_attempts($quizobj, $user);
4c729982
AN
366 }
367 }
368
369 /**
370 * Store all quiz attempts for the contextlist.
371 *
372 * @param approved_contextlist $contextlist
373 */
374 protected static function export_quiz_attempts(approved_contextlist $contextlist) {
375 global $DB;
376
377 $userid = $contextlist->get_user()->id;
378 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
379 $qubaid = \core_question\privacy\provider::get_related_question_usages_for_user('rel', 'mod_quiz', 'qa.uniqueid', $userid);
380
381 $sql = "SELECT
382 c.id AS contextid,
383 cm.id AS cmid,
384 qa.*
385 FROM {context} c
386 JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel
387 JOIN {modules} m ON m.id = cm.module AND m.name = 'quiz'
388 JOIN {quiz} q ON q.id = cm.instance
389 JOIN {quiz_attempts} qa ON qa.quiz = q.id
390 " . $qubaid->from. "
391 WHERE (
392 qa.userid = :qauserid OR
393 " . $qubaid->where() . "
394 ) AND qa.preview = 0
395 ";
396
397 $params = array_merge(
398 [
399 'contextlevel' => CONTEXT_MODULE,
400 'qauserid' => $userid,
401 ],
402 $qubaid->from_where_params()
403 );
404
405 $attempts = $DB->get_recordset_sql($sql, $params);
406 foreach ($attempts as $attempt) {
407 $quiz = $DB->get_record('quiz', ['id' => $attempt->quiz]);
408 $context = \context_module::instance($attempt->cmid);
409 $attemptsubcontext = helper::get_quiz_attempt_subcontext($attempt, $contextlist->get_user());
410 $options = quiz_get_review_options($quiz, $attempt, $context);
411
412 if ($attempt->userid == $userid) {
413 // This attempt was made by the user.
414 // They 'own' all data on it.
415 // Store the question usage data.
416 \core_question\privacy\provider::export_question_usage($userid,
417 $context,
418 $attemptsubcontext,
419 $attempt->uniqueid,
420 $options,
421 true
422 );
423
424 // Store the quiz attempt data.
425 $data = (object) [
426 'state' => \quiz_attempt::state_name($attempt->state),
427 ];
428
429 if (!empty($attempt->timestart)) {
430 $data->timestart = transform::datetime($attempt->timestart);
431 }
432 if (!empty($attempt->timefinish)) {
433 $data->timefinish = transform::datetime($attempt->timefinish);
434 }
435 if (!empty($attempt->timemodified)) {
436 $data->timemodified = transform::datetime($attempt->timemodified);
437 }
438 if (!empty($attempt->timemodifiedoffline)) {
439 $data->timemodifiedoffline = transform::datetime($attempt->timemodifiedoffline);
440 }
441 if (!empty($attempt->timecheckstate)) {
442 $data->timecheckstate = transform::datetime($attempt->timecheckstate);
443 }
444
445 if ($options->marks == \question_display_options::MARK_AND_MAX) {
446 $grade = quiz_rescale_grade($attempt->sumgrades, $quiz, false);
447 $data->grade = (object) [
448 'grade' => quiz_format_grade($quiz, $grade),
449 'feedback' => quiz_feedback_for_grade($grade, $quiz, $context),
450 ];
451 }
452
453 writer::with_context($context)
454 ->export_data($attemptsubcontext, $data);
455 } else {
456 // This attempt was made by another user.
457 // The current user may have marked part of the quiz attempt.
458 \core_question\privacy\provider::export_question_usage(
459 $userid,
460 $context,
461 $attemptsubcontext,
462 $attempt->uniqueid,
463 $options,
464 false
465 );
466 }
467 }
468 $attempts->close();
469 }
470}