MDL-62167 core_badges: Remove usage of a reserved keyword of Oracle
[moodle.git] / badges / classes / privacy / provider.php
blob1b198cb1be11e955dfb6cf2fe407458aefadf38a
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.
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/>.
17 /**
18 * Data provider.
20 * @package core_badges
21 * @copyright 2018 Frédéric Massart
22 * @author Frédéric Massart <fred@branchup.tech>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 namespace core_badges\privacy;
27 defined('MOODLE_INTERNAL') || die();
29 use badge;
30 use context;
31 use context_course;
32 use context_helper;
33 use context_system;
34 use context_user;
35 use core_text;
36 use core_privacy\local\metadata\collection;
37 use core_privacy\local\request\approved_contextlist;
38 use core_privacy\local\request\transform;
39 use core_privacy\local\request\writer;
41 require_once($CFG->libdir . '/badgeslib.php');
43 /**
44 * Data provider class.
46 * @package core_badges
47 * @copyright 2018 Frédéric Massart
48 * @author Frédéric Massart <fred@branchup.tech>
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class provider implements
52 \core_privacy\local\metadata\provider,
53 \core_privacy\local\request\subsystem\provider {
55 /**
56 * Returns metadata.
58 * @param collection $collection The initialised collection to add items to.
59 * @return collection A listing of user data stored through this system.
61 public static function get_metadata(collection $collection) : collection {
63 $collection->add_database_table('badge', [
64 'usercreated' => 'privacy:metadata:badge:usercreated',
65 'usermodified' => 'privacy:metadata:badge:usermodified',
66 'timecreated' => 'privacy:metadata:badge:timecreated',
67 'timemodified' => 'privacy:metadata:badge:timemodified',
68 ], 'privacy:metadata:badge');
70 $collection->add_database_table('badge_issued', [
71 'userid' => 'privacy:metadata:issued:userid',
72 'dateissued' => 'privacy:metadata:issued:dateissued',
73 'dateexpire' => 'privacy:metadata:issued:dateexpire',
74 ], 'privacy:metadata:issued');
76 $collection->add_database_table('badge_criteria_met', [
77 'userid' => 'privacy:metadata:criteriamet:userid',
78 'datemet' => 'privacy:metadata:criteriamet:datemet',
79 ], 'privacy:metadata:criteriamet');
81 $collection->add_database_table('badge_manual_award', [
82 'recipientid' => 'privacy:metadata:manualaward:recipientid',
83 'issuerid' => 'privacy:metadata:manualaward:issuerid',
84 'issuerrole' => 'privacy:metadata:manualaward:issuerrole',
85 'datemet' => 'privacy:metadata:manualaward:datemet',
86 ], 'privacy:metadata:manualaward');
88 $collection->add_database_table('badge_backpack', [
89 'userid' => 'privacy:metadata:backpack:userid',
90 'email' => 'privacy:metadata:backpack:email',
91 'backpackurl' => 'privacy:metadata:backpack:backpackurl',
92 'backpackuid' => 'privacy:metadata:backpack:backpackuid',
93 // The columns autosync and password are not used.
94 ], 'privacy:metadata:backpack');
96 $collection->add_external_location_link('backpacks', [
97 'name' => 'privacy:metadata:external:backpacks:badge',
98 'description' => 'privacy:metadata:external:backpacks:description',
99 'image' => 'privacy:metadata:external:backpacks:image',
100 'url' => 'privacy:metadata:external:backpacks:url',
101 'issuer' => 'privacy:metadata:external:backpacks:issuer',
102 ], 'privacy:metadata:external:backpacks');
104 return $collection;
108 * Get the list of contexts that contain user information for the specified user.
110 * @param int $userid The user to search.
111 * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
113 public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
114 $contextlist = new \core_privacy\local\request\contextlist();
116 // Find the modifications we made on badges (course & system).
117 $sql = "
118 SELECT ctx.id
119 FROM {badge} b
120 JOIN {context} ctx
121 ON (b.type = :typecourse AND b.courseid = ctx.instanceid AND ctx.contextlevel = :courselevel)
122 OR (b.type = :typesite AND ctx.id = :syscontextid)
123 WHERE b.usermodified = :userid1
124 OR b.usercreated = :userid2";
125 $params = [
126 'courselevel' => CONTEXT_COURSE,
127 'syscontextid' => SYSCONTEXTID,
128 'typecourse' => BADGE_TYPE_COURSE,
129 'typesite' => BADGE_TYPE_SITE,
130 'userid1' => $userid,
131 'userid2' => $userid,
133 $contextlist->add_from_sql($sql, $params);
135 // Find where we've manually awarded a badge (recipient user context).
136 $sql = "
137 SELECT ctx.id
138 FROM {badge_manual_award} bma
139 JOIN {context} ctx
140 ON ctx.instanceid = bma.recipientid
141 AND ctx.contextlevel = :userlevel
142 WHERE bma.issuerid = :userid";
143 $params = [
144 'userlevel' => CONTEXT_USER,
145 'userid' => $userid,
147 $contextlist->add_from_sql($sql, $params);
149 // Now find where there is real user data (user context).
150 $sql = "
151 SELECT ctx.id
152 FROM {context} ctx
153 LEFT JOIN {badge_manual_award} bma
154 ON bma.recipientid = ctx.instanceid
155 LEFT JOIN {badge_issued} bi
156 ON bi.userid = ctx.instanceid
157 LEFT JOIN {badge_criteria_met} bcm
158 ON bcm.userid = ctx.instanceid
159 LEFT JOIN {badge_backpack} bb
160 ON bb.userid = ctx.instanceid
161 WHERE ctx.contextlevel = :userlevel
162 AND ctx.instanceid = :userid
163 AND (bma.id IS NOT NULL
164 OR bi.id IS NOT NULL
165 OR bcm.id IS NOT NULL
166 OR bb.id IS NOT NULL)";
167 $params = [
168 'userlevel' => CONTEXT_USER,
169 'userid' => $userid,
171 $contextlist->add_from_sql($sql, $params);
173 return $contextlist;
177 * Export all user data for the specified user, in the specified contexts.
179 * @param approved_contextlist $contextlist The approved contexts to export information for.
181 public static function export_user_data(approved_contextlist $contextlist) {
182 global $DB;
184 $userid = $contextlist->get_user()->id;
185 $contexts = array_reduce($contextlist->get_contexts(), function($carry, $context) {
186 $level = $context->contextlevel;
187 if ($level == CONTEXT_USER || $level == CONTEXT_COURSE) {
188 $carry[$level][] = $context->instanceid;
189 } else if ($level == CONTEXT_SYSTEM) {
190 $carry[$level] = SYSCONTEXTID;
192 return $carry;
193 }, [
194 CONTEXT_COURSE => [],
195 CONTEXT_USER => [],
196 CONTEXT_SYSTEM => null,
199 $path = [get_string('badges', 'core_badges')];
200 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
202 // Export the badges we've created or modified.
203 if (!empty($contexts[CONTEXT_SYSTEM]) || !empty($contexts[CONTEXT_COURSE])) {
204 $sqls = [];
205 $params = [];
207 if (!empty($contexts[CONTEXT_SYSTEM])) {
208 $sqls[] = "b.type = :typesite";
209 $params['typesite'] = BADGE_TYPE_SITE;
212 if (!empty($contexts[CONTEXT_COURSE])) {
213 list($insql, $inparams) = $DB->get_in_or_equal($contexts[CONTEXT_COURSE], SQL_PARAMS_NAMED);
214 $sqls[] = "(b.type = :typecourse AND b.courseid $insql)";
215 $params = array_merge($params, ['typecourse' => BADGE_TYPE_COURSE], $inparams);
218 $sqlwhere = '(' . implode(' OR ', $sqls) . ')';
219 $sql = "
220 SELECT b.*, COALESCE(b.courseid, 0) AS normalisedcourseid
221 FROM {badge} b
222 WHERE (b.usermodified = :userid1 OR b.usercreated = :userid2)
223 AND $sqlwhere
224 ORDER BY b.courseid, b.id";
225 $params = array_merge($params, ['userid1' => $userid, 'userid2' => $userid]);
226 $recordset = $DB->get_recordset_sql($sql, $params);
227 static::recordset_loop_and_export($recordset, 'normalisedcourseid', [], function($carry, $record) use ($userid) {
228 $carry[] = [
229 'name' => $record->name,
230 'created_on' => transform::datetime($record->timecreated),
231 'created_by_you' => transform::yesno($record->usercreated == $userid),
232 'modified_on' => transform::datetime($record->timemodified),
233 'modified_by_you' => transform::yesno($record->usermodified == $userid),
235 return $carry;
236 }, function($courseid, $data) use ($path) {
237 $context = $courseid ? context_course::instance($courseid) : context_system::instance();
238 writer::with_context($context)->export_data($path, (object) ['badges' => $data]);
242 // Export the badges we've manually awarded.
243 if (!empty($contexts[CONTEXT_USER])) {
244 list($insql, $inparams) = $DB->get_in_or_equal($contexts[CONTEXT_USER], SQL_PARAMS_NAMED);
245 $sql = "
246 SELECT bma.id, bma.recipientid, bma.datemet, b.name, b.courseid,
247 r.id AS roleid,
248 r.name AS rolename,
249 r.shortname AS roleshortname,
250 r.archetype AS rolearchetype,
251 $ctxfields
252 FROM {badge_manual_award} bma
253 JOIN {badge} b
254 ON b.id = bma.badgeid
255 JOIN {role} r
256 ON r.id = bma.issuerrole
257 JOIN {context} ctx
258 ON (COALESCE(b.courseid, 0) > 0 AND ctx.instanceid = b.courseid AND ctx.contextlevel = :courselevel)
259 OR (COALESCE(b.courseid, 0) = 0 AND ctx.id = :syscontextid)
260 WHERE bma.recipientid $insql
261 AND bma.issuerid = :userid
262 ORDER BY bma.recipientid, bma.id";
263 $params = array_merge($inparams, [
264 'courselevel' => CONTEXT_COURSE,
265 'syscontextid' => SYSCONTEXTID,
266 'userid' => $userid
268 $recordset = $DB->get_recordset_sql($sql, $params);
269 static::recordset_loop_and_export($recordset, 'recipientid', [], function($carry, $record) use ($userid) {
271 // The only reason we fetch the context and role is to format the name of the role, which could be
272 // different to the standard name if the badge was created in a course.
273 context_helper::preload_from_record($record);
274 $context = $record->courseid ? context_course::instance($record->courseid) : context_system::instance();
275 $role = (object) [
276 'id' => $record->roleid,
277 'name' => $record->rolename,
278 'shortname' => $record->roleshortname,
279 'archetype' => $record->rolearchetype,
280 // Mock those two fields as they do not matter.
281 'sortorder' => 0,
282 'description' => ''
285 $carry[] = [
286 'name' => $record->name,
287 'issued_by_you' => transform::yesno(true),
288 'issued_on' => transform::datetime($record->datemet),
289 'issuer_role' => role_get_name($role, $context),
291 return $carry;
292 }, function($userid, $data) use ($path) {
293 $context = context_user::instance($userid);
294 writer::with_context($context)->export_related_data($path, 'manual_awards', (object) ['badges' => $data]);
298 // Export our data.
299 if (in_array($userid, $contexts[CONTEXT_USER])) {
301 // Export the badges.
302 $uniqueid = $DB->sql_concat_join("'-'", ['b.id', 'COALESCE(bc.id, 0)', 'COALESCE(bi.id, 0)',
303 'COALESCE(bma.id, 0)', 'COALESCE(bcm.id, 0)']);
304 $sql = "
305 SELECT $uniqueid AS uniqueid, b.id,
306 bi.id AS biid, bi.dateissued, bi.dateexpire, bi.uniquehash,
307 bma.id AS bmaid, bma.datemet, bma.issuerid,
308 bcm.id AS bcmid,
309 c.fullname AS coursename,
310 $ctxfields
311 FROM {badge} b
312 LEFT JOIN {badge_issued} bi
313 ON bi.badgeid = b.id
314 AND bi.userid = :userid1
315 LEFT JOIN {badge_manual_award} bma
316 ON bma.badgeid = b.id
317 AND bma.recipientid = :userid2
318 LEFT JOIN {badge_criteria} bc
319 ON bc.badgeid = b.id
320 LEFT JOIN {badge_criteria_met} bcm
321 ON bcm.critid = bc.id
322 AND bcm.userid = :userid3
323 LEFT JOIN {course} c
324 ON c.id = b.courseid
325 AND b.type = :typecourse
326 LEFT JOIN {context} ctx
327 ON ctx.instanceid = c.id
328 AND ctx.contextlevel = :courselevel
329 WHERE bi.id IS NOT NULL
330 OR bma.id IS NOT NULL
331 OR bcm.id IS NOT NULL
332 ORDER BY b.id";
333 $params = [
334 'userid1' => $userid,
335 'userid2' => $userid,
336 'userid3' => $userid,
337 'courselevel' => CONTEXT_COURSE,
338 'typecourse' => BADGE_TYPE_COURSE,
340 $recordset = $DB->get_recordset_sql($sql, $params);
341 static::recordset_loop_and_export($recordset, 'id', null, function($carry, $record) use ($userid) {
342 $badge = new badge($record->id);
344 // Export details of the badge.
345 if ($carry === null) {
346 $carry = [
347 'name' => $badge->name,
348 'issued' => null,
349 'manual_award' => null,
350 'criteria_met' => []
353 if ($badge->type == BADGE_TYPE_COURSE) {
354 context_helper::preload_from_record($record);
355 $carry['course'] = format_string($record->coursename, true, ['context' => $badge->get_context()]);
358 if (!empty($record->biid)) {
359 $carry['issued'] = [
360 'issued_on' => transform::datetime($record->dateissued),
361 'expires_on' => $record->dateexpire ? transform::datetime($record->dateexpire) : null,
362 'unique_hash' => $record->uniquehash,
366 if (!empty($record->bmaid)) {
367 $carry['manual_award'] = [
368 'awarded_on' => transform::datetime($record->datemet),
369 'issuer' => transform::user($record->issuerid)
374 // Export the details of the criteria met.
375 // We only do that once, when we find that a least one criteria was met.
376 // This is heavily based on the logic present in core_badges_renderer::render_issued_badge.
377 if (!empty($record->bcmid) && empty($carry['criteria_met'])) {
379 $agg = $badge->get_aggregation_methods();
380 $evidenceids = array_map(function($record) {
381 return $record->critid;
382 }, $badge->get_criteria_completions($userid));
384 $criteria = $badge->criteria;
385 unset($criteria[BADGE_CRITERIA_TYPE_OVERALL]);
387 $items = [];
388 foreach ($criteria as $type => $c) {
389 if (in_array($c->id, $evidenceids)) {
390 $details = $c->get_details(true);
391 if (count($c->params) == 1) {
392 $items[] = get_string('criteria_descr_single_' . $type , 'core_badges') . ' ' . $details;
393 } else {
394 $items[] = get_string('criteria_descr_' . $type , 'core_badges',
395 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . ' ' . $details;
399 $carry['criteria_met'] = $items;
401 return $carry;
402 }, function($badgeid, $data) use ($path, $userid) {
403 $path = array_merge($path, ["{$data['name']} ({$badgeid})"]);
404 $writer = writer::with_context(context_user::instance($userid));
405 $writer->export_data($path, (object) $data);
406 $writer->export_area_files($path, 'badges', 'userbadge', $badgeid);
409 // Export the backpacks.
410 $data = [];
411 $recordset = $DB->get_recordset_select('badge_backpack', 'userid = :userid', ['userid' => $userid]);
412 foreach ($recordset as $record) {
413 $data[] = [
414 'email' => $record->email,
415 'url' => $record->backpackurl,
416 'uid' => $record->backpackuid
419 $recordset->close();
420 if (!empty($data)) {
421 writer::with_context(context_user::instance($userid))->export_related_data($path, 'backpacks',
422 (object) ['backpacks' => $data]);
428 * Delete all data for all users in the specified context.
430 * @param context $context The specific context to delete data for.
432 public static function delete_data_for_all_users_in_context(context $context) {
433 // We cannot delete the course or system data as it is needed by the system.
434 if ($context->contextlevel != CONTEXT_USER) {
435 return;
438 // Delete all the user data.
439 static::delete_user_data($context->instanceid);
443 * Delete all user data for the specified user, in the specified contexts.
445 * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
447 public static function delete_data_for_user(approved_contextlist $contextlist) {
448 $userid = $contextlist->get_user()->id;
449 foreach ($contextlist->get_contexts() as $context) {
450 if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $userid) {
451 // We can only delete our own data in the user context, nothing in course or system.
452 static::delete_user_data($userid);
453 break;
459 * Delete all the data for a user.
461 * @param int $userid The user ID.
462 * @return void
464 protected static function delete_user_data($userid) {
465 global $DB;
467 // Delete the stuff.
468 $DB->delete_records('badge_manual_award', ['recipientid' => $userid]);
469 $DB->delete_records('badge_criteria_met', ['userid' => $userid]);
470 $DB->delete_records('badge_issued', ['userid' => $userid]);
472 // Delete the backpacks and related stuff.
473 $backpackids = $DB->get_fieldset_select('badge_backpack', 'id', 'userid = :userid', ['userid' => $userid]);
474 if (!empty($backpackids)) {
475 list($insql, $inparams) = $DB->get_in_or_equal($backpackids, SQL_PARAMS_NAMED);
476 $DB->delete_records_select('badge_external', "backpackid $insql", $inparams);
477 $DB->delete_records_select('badge_backpack', "id $insql", $inparams);
482 * Loop and export from a recordset.
484 * @param \moodle_recordset $recordset The recordset.
485 * @param string $splitkey The record key to determine when to export.
486 * @param mixed $initial The initial data to reduce from.
487 * @param callable $reducer The function to return the dataset, receives current dataset, and the current record.
488 * @param callable $export The function to export the dataset, receives the last value from $splitkey and the dataset.
489 * @return void
491 protected static function recordset_loop_and_export(\moodle_recordset $recordset, $splitkey, $initial,
492 callable $reducer, callable $export) {
494 $data = $initial;
495 $lastid = null;
497 foreach ($recordset as $record) {
498 if ($lastid !== null && $record->{$splitkey} != $lastid) {
499 $export($lastid, $data);
500 $data = $initial;
502 $data = $reducer($data, $record);
503 $lastid = $record->{$splitkey};
505 $recordset->close();
507 if ($lastid !== null) {
508 $export($lastid, $data);