Merge branch 'MDL-62310-master' of git://github.com/cescobedo/moodle
authorJake Dallimore <jake@moodle.com>
Thu, 3 May 2018 09:59:48 +0000 (17:59 +0800)
committerJake Dallimore <jake@moodle.com>
Thu, 3 May 2018 10:00:40 +0000 (18:00 +0800)
191 files changed:
admin/classes/privacy/provider.php
admin/registration/index.php
admin/registration/renderer.php [deleted file]
admin/renderer.php
admin/settings/development.php
admin/settings/privacy.php [deleted file]
admin/settings/top.php
admin/settings/users.php
admin/tool/dataprivacy/classes/api.php
admin/tool/log/classes/local/privacy/helper.php [new file with mode: 0644]
admin/tool/log/classes/local/privacy/logstore_provider.php [new file with mode: 0644]
admin/tool/log/classes/local/privacy/moodle_database_export_and_delete.php [new file with mode: 0644]
admin/tool/log/classes/privacy/provider.php [new file with mode: 0644]
admin/tool/log/lang/en/tool_log.php
admin/tool/log/store/database/classes/privacy/provider.php [new file with mode: 0644]
admin/tool/log/store/database/lang/en/logstore_database.php
admin/tool/log/store/database/tests/privacy_test.php [new file with mode: 0644]
admin/tool/log/store/legacy/classes/privacy/provider.php [new file with mode: 0644]
admin/tool/log/store/legacy/lang/en/logstore_legacy.php
admin/tool/log/store/legacy/tests/privacy_test.php [new file with mode: 0644]
admin/tool/log/store/standard/classes/privacy/provider.php [new file with mode: 0644]
admin/tool/log/store/standard/lang/en/logstore_standard.php
admin/tool/log/store/standard/tests/privacy_test.php [new file with mode: 0644]
admin/tool/log/tests/privacy_test.php [new file with mode: 0644]
admin/tool/messageinbound/classes/manager.php
admin/tool/messageinbound/classes/privacy/provider.php [new file with mode: 0644]
admin/tool/messageinbound/classes/task/cleanup_task.php
admin/tool/messageinbound/lang/en/tool_messageinbound.php
admin/tool/messageinbound/tests/manager_test.php [new file with mode: 0644]
admin/tool/messageinbound/tests/privacy_test.php [new file with mode: 0644]
admin/tool/profiling/settings.php
auth/classes/privacy/provider.php [new file with mode: 0644]
auth/tests/privacy_test.php [new file with mode: 0644]
availability/classes/privacy/provider.php [new file with mode: 0644]
badges/classes/privacy/provider.php [new file with mode: 0644]
badges/tests/privacy_test.php [new file with mode: 0644]
blocks/classes/privacy/provider.php [new file with mode: 0644]
blocks/comments/classes/privacy/provider.php [new file with mode: 0644]
blocks/comments/lang/en/block_comments.php
blocks/comments/tests/privacy_provider_test.php [new file with mode: 0644]
blocks/recent_activity/classes/privacy/provider.php [new file with mode: 0644]
blocks/recent_activity/lang/en/block_recent_activity.php
blocks/tests/privacy_test.php [new file with mode: 0644]
cache/classes/privacy/provider.php [new file with mode: 0644]
cache/locks/file/classes/privacy/provider.php [new file with mode: 0644]
cache/locks/file/lang/en/cachelock_file.php
cache/stores/apcu/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/apcu/lang/en/cachestore_apcu.php
cache/stores/file/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/file/lang/en/cachestore_file.php
cache/stores/memcache/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/memcache/lang/en/cachestore_memcache.php
cache/stores/memcached/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/memcached/lang/en/cachestore_memcached.php
cache/stores/mongodb/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/mongodb/lang/en/cachestore_mongodb.php
cache/stores/redis/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/redis/lang/en/cachestore_redis.php
cache/stores/session/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/session/lang/en/cachestore_session.php
cache/stores/static/classes/privacy/provider.php [new file with mode: 0644]
cache/stores/static/lang/en/cachestore_static.php
calendar/classes/privacy/provider.php [new file with mode: 0644]
calendar/lib.php
calendar/tests/privacy_test.php [new file with mode: 0644]
course/moodleform_mod.php
course/publish/backup.php
course/publish/index.php
course/publish/metadata.php
course/publish/renderer.php [deleted file]
course/renderer.php
files/classes/conversion.php
files/classes/privacy/provider.php [new file with mode: 0644]
files/classes/task/conversion_cleanup_task.php
files/converter/classes/privacy/provider.php [new file with mode: 0644]
files/tests/conversion_test.php
grade/classes/privacy/provider.php [new file with mode: 0644]
grade/tests/privacy_test.php [new file with mode: 0644]
install/lang/el/error.php
install/lang/te/moodle.php
install/lang/tl/moodle.php
lang/en/auth.php
lang/en/availability.php
lang/en/badges.php
lang/en/block.php
lang/en/cache.php
lang/en/calendar.php
lang/en/fileconverter.php [moved from lang/en/register.php with 68% similarity]
lang/en/files.php [new file with mode: 0644]
lang/en/grades.php
lang/en/mnet.php
lang/en/webservice.php
lib/classes/component.php
lib/tests/component_test.php
lib/upgrade.txt
lib/xhprof/xhprof_moodle.php
message/templates/message_area_message.mustache
mnet/classes/privacy/provider.php [moved from admin/registration/classes/privacy/provider.php with 87% similarity]
mod/assign/classes/privacy/assign_plugin_request_data.php [new file with mode: 0644]
mod/assign/classes/privacy/assignfeedback_provider.php [new file with mode: 0644]
mod/assign/classes/privacy/assignsubmission_provider.php [new file with mode: 0644]
mod/assign/classes/privacy/feedback_legacy_polyfill.php [new file with mode: 0644]
mod/assign/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/classes/privacy/submission_legacy_polyfill.php [new file with mode: 0644]
mod/assign/classes/privacy/useridlist.php [new file with mode: 0644]
mod/assign/feedback/comments/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/feedback/comments/lang/en/assignfeedback_comments.php
mod/assign/feedback/comments/tests/privacy_test.php [new file with mode: 0644]
mod/assign/feedback/editpdf/classes/document_services.php
mod/assign/feedback/editpdf/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/feedback/editpdf/lang/en/assignfeedback_editpdf.php
mod/assign/feedback/editpdf/tests/privacy_test.php [new file with mode: 0644]
mod/assign/feedback/file/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/feedback/file/lang/en/assignfeedback_file.php
mod/assign/feedback/file/tests/privacy_test.php [new file with mode: 0644]
mod/assign/feedback/offline/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/feedback/offline/lang/en/assignfeedback_offline.php
mod/assign/lang/en/assign.php
mod/assign/locallib.php
mod/assign/submission/comments/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/submission/comments/lang/en/assignsubmission_comments.php
mod/assign/submission/comments/tests/privacy_test.php [new file with mode: 0644]
mod/assign/submission/file/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/submission/file/lang/en/assignsubmission_file.php
mod/assign/submission/file/tests/privacy_test.php [new file with mode: 0644]
mod/assign/submission/onlinetext/classes/privacy/provider.php [new file with mode: 0644]
mod/assign/submission/onlinetext/lang/en/assignsubmission_onlinetext.php
mod/assign/submission/onlinetext/tests/privacy_test.php [new file with mode: 0644]
mod/assign/tests/privacy_feedback_legacy_polyfill_test.php [new file with mode: 0644]
mod/assign/tests/privacy_submission_legacy_polyfill_test.php [new file with mode: 0644]
mod/assign/tests/privacy_test.php [new file with mode: 0644]
mod/book/classes/privacy/provider.php [new file with mode: 0644]
mod/book/lang/en/book.php
mod/lti/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/lang/en/lti.php
mod/lti/service/gradebookservices/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/service/gradebookservices/lang/en/ltiservice_gradebookservices.php
mod/lti/service/gradebookservices/tests/privacy_provider_test.php [new file with mode: 0644]
mod/lti/service/memberships/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/service/memberships/lang/en/ltiservice_memberships.php
mod/lti/service/memberships/tests/privacy_provider_test.php [new file with mode: 0644]
mod/lti/service/profile/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/service/profile/lang/en/ltiservice_profile.php
mod/lti/service/toolproxy/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/service/toolproxy/lang/en/ltiservice_toolproxy.php
mod/lti/service/toolsettings/classes/privacy/provider.php [new file with mode: 0644]
mod/lti/service/toolsettings/lang/en/ltiservice_toolsettings.php
mod/lti/tests/privacy_provider_test.php [new file with mode: 0644]
mod/quiz/classes/output/edit_renderer.php
mod/quiz/classes/structure.php
mod/quiz/locallib.php
mod/quiz/tests/locallib_test.php
mod/quiz/tests/structure_test.php
mod/scorm/classes/privacy/provider.php [new file with mode: 0644]
mod/scorm/lang/en/scorm.php
mod/scorm/report/basic/classes/privacy/provider.php [new file with mode: 0644]
mod/scorm/report/basic/lang/en/scormreport_basic.php
mod/scorm/report/basic/tests/privacy_test.php [new file with mode: 0644]
mod/scorm/report/graphs/classes/privacy/provider.php [new file with mode: 0644]
mod/scorm/report/graphs/lang/en/scormreport_graphs.php
mod/scorm/report/interactions/classes/privacy/provider.php [new file with mode: 0644]
mod/scorm/report/interactions/lang/en/scormreport_interactions.php
mod/scorm/report/interactions/tests/privacy_test.php [new file with mode: 0644]
mod/scorm/report/objectives/classes/privacy/provider.php [new file with mode: 0644]
mod/scorm/report/objectives/lang/en/scormreport_objectives.php
mod/scorm/report/objectives/tests/privacy_test.php [new file with mode: 0644]
mod/scorm/tests/privacy_test.php [new file with mode: 0644]
privacy/classes/local/request/moodle_content_writer.php
privacy/classes/tests/request/content_writer.php
privacy/tests/manager_test.php
privacy/tests/moodle_content_writer_test.php
privacy/tests/tests_content_writer_test.php
theme/boost/amd/build/drawer.min.js
theme/boost/amd/src/drawer.js
theme/boost/scss/moodle/blocks.scss
theme/boost/scss/moodle/bs4alphacompat.scss
theme/boost/scss/moodle/calendar.scss
theme/boost/scss/moodle/core.scss
theme/boost/scss/moodle/forms.scss
theme/boost/scss/moodle/icons.scss
theme/boost/scss/moodle/message.scss
theme/boost/scss/moodle/modules.scss
theme/boost/scss/moodle/undo.scss
theme/boost/templates/core/custom_menu_item.mustache
theme/boost/templates/core/filemanager_modal_generallayout.mustache
theme/boost/tests/behat/behat_theme_boost_behat_repository_upload.php
theme/bootstrapbase/less/moodle/backup-restore.less
theme/bootstrapbase/style/moodle.css
version.php
webservice/classes/privacy/provider.php [new file with mode: 0644]
webservice/tests/privacy_test.php [new file with mode: 0644]

index b8f795e..118308d 100644 (file)
@@ -38,4 +38,4 @@ class provider implements \core_privacy\local\metadata\null_provider {
     public static function get_reason() : string {
         return 'privacy:metadata';
     }
-}
\ No newline at end of file
+}
index dee1ba0..57d65a3 100644 (file)
@@ -110,7 +110,7 @@ if (\core\hub\registration::is_registered()) {
     echo $OUTPUT->heading(get_string('registerwithmoodleorg', 'admin'));
 }
 
-$renderer = $PAGE->get_renderer('core', 'register');
+$renderer = $PAGE->get_renderer('core', 'admin');
 echo $renderer->moodleorg_registration_message();
 
 $siteregistrationform->display();
diff --git a/admin/registration/renderer.php b/admin/registration/renderer.php
deleted file mode 100644 (file)
index b7414b4..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-<?php
-
-///////////////////////////////////////////////////////////////////////////
-//                                                                       //
-// This file is part of Moodle - http://moodle.org/                      //
-// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
-//                                                                       //
-// Moodle is free software: you can redistribute it and/or modify        //
-// it under the terms of the GNU General Public License as published by  //
-// the Free Software Foundation, either version 3 of the License, or     //
-// (at your option) any later version.                                   //
-//                                                                       //
-// Moodle is distributed in the hope that it will be useful,             //
-// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
-// GNU General Public License for more details.                          //
-//                                                                       //
-// You should have received a copy of the GNU General Public License     //
-// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.       //
-//                                                                       //
-///////////////////////////////////////////////////////////////////////////
-
-/**
- * Registration renderer.
- * @package   moodle
- * @subpackage registration
- * @copyright 2010 Moodle Pty Ltd (http://moodle.com)
- * @author    Jerome Mouneyrac
- * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-class core_register_renderer extends plugin_renderer_base {
-
-    /**
-     * Display message about the benefits of registering on Moodle.org
-     *
-     * @return string
-     */
-    public function moodleorg_registration_message() {
-        return format_text(get_string('registermoodlenet', 'admin'), FORMAT_HTML, ['noclean' => true]);
-    }
-}
index dbd77f6..f22c6a2 100644 (file)
@@ -2084,4 +2084,13 @@ class core_admin_renderer extends plugin_renderer_base {
             return $this->warning(get_string('legacylogginginuse'));
         }
     }
+
+    /**
+     * Display message about the benefits of registering on Moodle.org
+     *
+     * @return string
+     */
+    public function moodleorg_registration_message() {
+        return format_text(get_string('registermoodlenet', 'admin'), FORMAT_HTML, ['noclean' => true]);
+    }
 }
index 41d779f..0d42707 100644 (file)
@@ -30,7 +30,9 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
     $ADMIN->add('development', $temp);
 
     // "Profiling" settingpage (conditionally if the 'xhprof' extension is available only).
-    $xhprofenabled = extension_loaded('xhprof') || extension_loaded('tideways');
+    $xhprofenabled = extension_loaded('tideways_xhprof');
+    $xhprofenabled = $xhprofenabled || extension_loaded('tideways');
+    $xhprofenabled = $xhprofenabled || extension_loaded('xhprof');
     $temp = new admin_settingpage('profiling', new lang_string('profiling', 'admin'), 'moodle/site:config', !$xhprofenabled);
     // Main profiling switch.
     $temp->add(new admin_setting_configcheckbox('profilingenabled', new lang_string('profilingenabled', 'admin'), new lang_string('profilingenabled_help', 'admin'), false));
diff --git a/admin/settings/privacy.php b/admin/settings/privacy.php
deleted file mode 100644 (file)
index 87f8c52..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-<?php
-// This file is part of Moodle - http://moodle.org/
-//
-// Moodle is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// Moodle is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
-
-/**
- * Adds privacy and policies links to admin tree.
- *
- * @package   core_privacy
- * @copyright 2018 Marina Glancy
- * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-defined('MOODLE_INTERNAL') || die();
-
-if ($hassiteconfig) {
-    // Privacy settings.
-    $temp = new admin_settingpage('privacysettings', new lang_string('privacysettings', 'admin'));
-
-    $options = array(
-        0 => get_string('no'),
-        1 => get_string('yes')
-    );
-    $url = new moodle_url('/admin/settings.php?section=supportcontact');
-    $url = $url->out();
-    $setting = new admin_setting_configselect('agedigitalconsentverification',
-        new lang_string('agedigitalconsentverification', 'admin'),
-        new lang_string('agedigitalconsentverification_desc', 'admin', $url), 0, $options);
-    $setting->set_force_ltr(true);
-    $temp->add($setting);
-
-    $setting = new admin_setting_agedigitalconsentmap('agedigitalconsentmap',
-        new lang_string('ageofdigitalconsentmap', 'admin'),
-        new lang_string('ageofdigitalconsentmap_desc', 'admin'),
-        // See {@link https://gdpr-info.eu/art-8-gdpr/}.
-        implode(PHP_EOL, [
-            '*, 16',
-            'AT, 14',
-            'CZ, 13',
-            'DE, 14',
-            'DK, 13',
-            'ES, 13',
-            'FI, 15',
-            'GB, 13',
-            'HU, 14',
-            'IE, 13',
-            'LT, 16',
-            'LU, 16',
-            'NL, 16',
-            'PL, 13',
-            'SE, 13',
-        ]),
-        PARAM_RAW
-    );
-    $temp->add($setting);
-
-    $ADMIN->add('privacy', $temp);
-
-    // Policy settings.
-    $temp = new admin_settingpage('policysettings', new lang_string('policysettings', 'admin'));
-    $temp->add(new admin_settings_sitepolicy_handler_select('sitepolicyhandler', new lang_string('sitepolicyhandler', 'core_admin'),
-        new lang_string('sitepolicyhandler_desc', 'core_admin')));
-    $temp->add(new admin_setting_configtext('sitepolicy', new lang_string('sitepolicy', 'core_admin'),
-        new lang_string('sitepolicy_help', 'core_admin'), '', PARAM_RAW));
-    $temp->add(new admin_setting_configtext('sitepolicyguest', new lang_string('sitepolicyguest', 'core_admin'),
-        new lang_string('sitepolicyguest_help', 'core_admin'), (isset($CFG->sitepolicy) ? $CFG->sitepolicy : ''), PARAM_RAW));
-
-    $ADMIN->add('privacy', $temp);
-}
index a049ce9..17621cb 100644 (file)
@@ -29,7 +29,6 @@ $ADMIN->add('root', new admin_category('badges', new lang_string('badges'), empt
 $ADMIN->add('root', new admin_category('location', new lang_string('location','admin')));
 $ADMIN->add('root', new admin_category('language', new lang_string('language')));
 $ADMIN->add('root', new admin_category('modules', new lang_string('plugins', 'admin')));
-$ADMIN->add('root', new admin_category('privacy', new lang_string('privacyandpolicies', 'admin')));
 $ADMIN->add('root', new admin_category('security', new lang_string('security','admin')));
 $ADMIN->add('root', new admin_category('appearance', new lang_string('appearance','admin')));
 $ADMIN->add('root', new admin_category('frontpage', new lang_string('frontpage','admin')));
index d444961..465a9d7 100644 (file)
@@ -4,6 +4,7 @@
 
 $ADMIN->add('users', new admin_category('accounts', new lang_string('accounts', 'admin')));
 $ADMIN->add('users', new admin_category('roles', new lang_string('permissions', 'role')));
+$ADMIN->add('users', new admin_category('privacy', new lang_string('privacyandpolicies', 'admin')));
 
 if ($hassiteconfig
  or has_capability('moodle/user:create', $systemcontext)
@@ -210,3 +211,58 @@ if ($hassiteconfig
     $ADMIN->add('roles', new admin_externalpage('checkpermissions', new lang_string('checkglobalpermissions', 'role'), "$CFG->wwwroot/$CFG->admin/roles/check.php?contextid=".$systemcontext->id, array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage')));
 
 } // end of speedup
+
+// Privacy settings.
+if ($hassiteconfig) {
+    $temp = new admin_settingpage('privacysettings', new lang_string('privacysettings', 'admin'));
+
+    $options = array(
+        0 => get_string('no'),
+        1 => get_string('yes')
+    );
+    $url = new moodle_url('/admin/settings.php?section=supportcontact');
+    $url = $url->out();
+    $setting = new admin_setting_configselect('agedigitalconsentverification',
+        new lang_string('agedigitalconsentverification', 'admin'),
+        new lang_string('agedigitalconsentverification_desc', 'admin', $url), 0, $options);
+    $setting->set_force_ltr(true);
+    $temp->add($setting);
+
+    $setting = new admin_setting_agedigitalconsentmap('agedigitalconsentmap',
+        new lang_string('ageofdigitalconsentmap', 'admin'),
+        new lang_string('ageofdigitalconsentmap_desc', 'admin'),
+        // See {@link https://gdpr-info.eu/art-8-gdpr/}.
+        implode(PHP_EOL, [
+            '*, 16',
+            'AT, 14',
+            'CZ, 13',
+            'DE, 14',
+            'DK, 13',
+            'ES, 13',
+            'FI, 15',
+            'GB, 13',
+            'HU, 14',
+            'IE, 13',
+            'LT, 16',
+            'LU, 16',
+            'NL, 16',
+            'PL, 13',
+            'SE, 13',
+        ]),
+        PARAM_RAW
+    );
+    $temp->add($setting);
+
+    $ADMIN->add('privacy', $temp);
+
+    // Policy settings.
+    $temp = new admin_settingpage('policysettings', new lang_string('policysettings', 'admin'));
+    $temp->add(new admin_settings_sitepolicy_handler_select('sitepolicyhandler', new lang_string('sitepolicyhandler', 'core_admin'),
+        new lang_string('sitepolicyhandler_desc', 'core_admin')));
+    $temp->add(new admin_setting_configtext('sitepolicy', new lang_string('sitepolicy', 'core_admin'),
+        new lang_string('sitepolicy_help', 'core_admin'), '', PARAM_RAW));
+    $temp->add(new admin_setting_configtext('sitepolicyguest', new lang_string('sitepolicyguest', 'core_admin'),
+        new lang_string('sitepolicyguest_help', 'core_admin'), (isset($CFG->sitepolicy) ? $CFG->sitepolicy : ''), PARAM_RAW));
+
+    $ADMIN->add('privacy', $temp);
+}
\ No newline at end of file
index 9ec5f45..09583b2 100644 (file)
@@ -220,6 +220,7 @@ class api {
     public static function get_data_requests($userid = 0) {
         global $USER;
         $results = [];
+        $sort = 'status ASC, timemodified ASC';
         if ($userid) {
             // Get the data requests for the user or data requests made by the user.
             $select = "userid = :userid OR requestedby = :requestedby";
@@ -227,11 +228,11 @@ class api {
                 'userid' => $userid,
                 'requestedby' => $userid
             ];
-            $results = data_request::get_records_select($select, $params, 'status DESC, timemodified DESC');
+            $results = data_request::get_records_select($select, $params, $sort);
         } else {
             // If the current user is one of the site's Data Protection Officers, then fetch all data requests.
             if (self::is_site_dpo($USER->id)) {
-                $results = data_request::get_records(null, 'status DESC, timemodified DESC', '');
+                $results = data_request::get_records(null, $sort, '');
             }
         }
 
diff --git a/admin/tool/log/classes/local/privacy/helper.php b/admin/tool/log/classes/local/privacy/helper.php
new file mode 100644 (file)
index 0000000..4aa17d1
--- /dev/null
@@ -0,0 +1,148 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy helper.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_log\local\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use core_privacy\local\request\transform;
+
+/**
+ * Privacy helper class.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class helper {
+
+    /**
+     * Returns an event from a standard record.
+     *
+     * @see \logstore_standard\log\store::get_log_event()
+     * @param object $data Log data.
+     * @return \core\event\base
+     */
+    protected static function restore_event_from_standard_record($data) {
+        $extra = ['origin' => $data->origin, 'ip' => $data->ip, 'realuserid' => $data->realuserid];
+        $data = (array) $data;
+        $id = $data['id'];
+        $data['other'] = unserialize($data['other']);
+        if ($data['other'] === false) {
+            $data['other'] = [];
+        }
+        unset($data['origin']);
+        unset($data['ip']);
+        unset($data['realuserid']);
+        unset($data['id']);
+
+        if (!$event = \core\event\base::restore($data, $extra)) {
+            return null;
+        }
+
+        return $event;
+    }
+
+    /**
+     * Transform a standard log record for a user.
+     *
+     * @param object $record The record.
+     * @param int $userid The user ID.
+     * @return array
+     */
+    public static function transform_standard_log_record_for_userid($record, $userid) {
+
+        // Restore the event to try to get the name, description and other field.
+        $restoredevent = static::restore_event_from_standard_record($record);
+        if ($restoredevent) {
+            $name = $restoredevent->get_name();
+            $description = $restoredevent->get_description();
+            $other = $restoredevent->other;
+
+        } else {
+            $name = $record->eventname;
+            $description = "Unknown event ({$name})";
+            $other = unserialize($record->other);
+        }
+
+        $realuserid = $record->realuserid;
+        $isauthor = $record->userid == $userid;
+        $isrelated = $record->relateduserid == $userid;
+        $isrealuser = $realuserid == $userid;
+        $ismasqueraded = $realuserid !== null && $record->userid != $realuserid;
+        $ismasquerading = $isrealuser && !$isauthor;
+        $isanonymous = $record->anonymous;
+
+        $data = [
+            'name' => $name,
+            'description' => $description,
+            'timecreated' => transform::datetime($record->timecreated),
+            'ip' => $record->ip,
+            'origin' => static::transform_origin($record->origin),
+            'other' => $other ? $other : []
+        ];
+
+        if ($isanonymous) {
+            $data['action_was_done_anonymously'] = transform::yesno($isanonymous);
+        }
+        if ($isauthor || !$isanonymous) {
+            $data['authorid'] = transform::user($record->userid);
+            $data['author_of_the_action_was_you'] = transform::yesno($isauthor);
+        }
+
+        if ($record->relateduserid) {
+            $data['relateduserid'] = transform::user($record->relateduserid);
+            $data['related_user_was_you'] = transform::yesno($isrelated);
+        }
+
+        if ($ismasqueraded) {
+            $data['author_of_the_action_was_masqueraded'] = transform::yesno(true);
+            if ($ismasquerading || !$isanonymous) {
+                $data['masqueradinguserid'] = transform::user($realuserid);
+                $data['masquerading_user_was_you'] = transform::yesno($ismasquerading);
+            }
+        }
+
+        return $data;
+    }
+
+    /**
+     * Transform origin.
+     *
+     * @param string $origin The page request origin.
+     * @return string
+     */
+    public static function transform_origin($origin) {
+        switch ($origin) {
+            case 'cli':
+            case 'restore':
+            case 'web':
+            case 'ws':
+                return get_string('privacy:request:origin:' . $origin, 'tool_log');
+                break;
+        }
+        return $origin;
+    }
+}
diff --git a/admin/tool/log/classes/local/privacy/logstore_provider.php b/admin/tool/log/classes/local/privacy/logstore_provider.php
new file mode 100644 (file)
index 0000000..cecc130
--- /dev/null
@@ -0,0 +1,78 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Logstore provider interface.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_log\local\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+/**
+ * Logstore provider interface.
+ *
+ * Logstore subplugins providers must implement this interface.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+interface logstore_provider extends \core_privacy\local\request\plugin\subplugin_provider {
+
+    /**
+     * Add contexts that contain user information for the specified user.
+     *
+     * @param contextlist $contextlist The contextlist to add the contexts to.
+     * @param int $userid The user to find the contexts for.
+     * @return void
+     */
+    public static function add_contexts_for_userid(contextlist $contextlist, $userid);
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     * @return void
+     */
+    public static function export_user_data(approved_contextlist $contextlist);
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     * @return void
+     */
+    public static function delete_data_for_all_users_in_context(context $context);
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     * @return void
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist);
+
+}
diff --git a/admin/tool/log/classes/local/privacy/moodle_database_export_and_delete.php b/admin/tool/log/classes/local/privacy/moodle_database_export_and_delete.php
new file mode 100644 (file)
index 0000000..da973ea
--- /dev/null
@@ -0,0 +1,123 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Moodle database: export and delete.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_log\local\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\writer;
+
+/**
+ * Moodle database: export and delete trait.
+ *
+ * This is to be used with logstores which use a database and table with the same columns
+ * as the core plugin 'logstore_standard'.
+ *
+ * This trait expects the following methods to be present in the object:
+ *
+ * - public static function get_database_and_table(): [moodle_database|null, string|null]
+ * - public static function get_export_subcontext(): []
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+trait moodle_database_export_and_delete {
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        list($db, $table) = static::get_database_and_table();
+        if (!$db || !$table) {
+            return;
+        }
+
+        $userid = $contextlist->get_user()->id;
+        list($insql, $inparams) = $db->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
+
+        $sql = "(userid = :userid1 OR relateduserid = :userid2 OR realuserid = :userid3) AND contextid $insql";
+        $params = array_merge($inparams, [
+            'userid1' => $userid,
+            'userid2' => $userid,
+            'userid3' => $userid,
+        ]);
+
+        $path = static::get_export_subcontext();
+        $flush = function($lastcontextid, $data) use ($path) {
+            $context = context::instance_by_id($lastcontextid);
+            writer::with_context($context)->export_data($path, (object) ['logs' => $data]);
+        };
+
+        $lastcontextid = null;
+        $data = [];
+        $recordset = $db->get_recordset_select($table, $sql, $params, 'contextid, timecreated, id');
+        foreach ($recordset as $record) {
+            if ($lastcontextid && $lastcontextid != $record->contextid) {
+                $flush($lastcontextid, $data);
+                $data = [];
+            }
+            $data[] = helper::transform_standard_log_record_for_userid($record, $userid);
+            $lastcontextid = $record->contextid;
+        }
+        if ($lastcontextid) {
+            $flush($lastcontextid, $data);
+        }
+        $recordset->close();
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        list($db, $table) = static::get_database_and_table();
+        if (!$db || !$table) {
+            return;
+        }
+        $db->delete_records($table, ['contextid' => $context->id]);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        list($db, $table) = static::get_database_and_table();
+        if (!$db || !$table) {
+            return;
+        }
+        list($insql, $inparams) = $db->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
+        $params = array_merge($inparams, ['userid' => $contextlist->get_user()->id]);
+        $db->delete_records_select($table, "userid = :userid AND contextid $insql", $params);
+    }
+
+}
diff --git a/admin/tool/log/classes/privacy/provider.php b/admin/tool/log/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..af91b8b
--- /dev/null
@@ -0,0 +1,110 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_log\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use tool_log\log\manager;
+
+/**
+ * Data provider class.
+ *
+ * @package    tool_log
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\subsystem\provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_plugintype_link('logstore', [], 'privacy:metadata:logstore');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param int $userid The user to search.
+     * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
+        $contextlist = new \core_privacy\local\request\contextlist();
+        static::call_subplugins_method_with_args('add_contexts_for_userid', [$contextlist, $userid]);
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        static::call_subplugins_method_with_args('export_user_data', [$contextlist]);
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        static::call_subplugins_method_with_args('delete_data_for_all_users_in_context', [$context]);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        static::call_subplugins_method_with_args('delete_data_for_user', [$contextlist]);
+    }
+
+    /**
+     * Invoke the subplugins method with arguments.
+     *
+     * @param string $method The method name.
+     * @param array $args The arguments.
+     * @return void
+     */
+    protected static function call_subplugins_method_with_args($method, array $args = []) {
+        $interface = \tool_log\local\privacy\logstore_provider::class;
+        \core_privacy\manager::plugintype_class_callback('logstore', $interface, $method, $args);
+    }
+
+}
index c57c424..bfda300 100644 (file)
@@ -26,7 +26,13 @@ $string['actlogshdr'] = 'Available log stores';
 $string['configlogplugins'] = 'Please enable all required plugins and arrange them in appropriate order.';
 $string['logging'] = 'Logging';
 $string['managelogging'] = 'Manage log stores';
-$string['reportssupported'] = 'Reports supported';
 $string['pluginname'] = 'Log store manager';
+$string['privacy:metadata:logstore'] = 'The log stores';
+$string['privacy:path:logs'] = 'Logs';
+$string['privacy:request:origin:cli'] = 'Command line tool';
+$string['privacy:request:origin:restore'] = 'Backup being restored';
+$string['privacy:request:origin:web'] = 'Standard web request';
+$string['privacy:request:origin:ws'] = 'Mobile app or web service';
+$string['reportssupported'] = 'Reports supported';
 $string['subplugintype_logstore'] = 'Log store';
 $string['subplugintype_logstore_plural'] = 'Log stores';
diff --git a/admin/tool/log/store/database/classes/privacy/provider.php b/admin/tool/log/store/database/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..b5e8eac
--- /dev/null
@@ -0,0 +1,114 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    logstore_database
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace logstore_database\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+
+/**
+ * Data provider class.
+ *
+ * @package    logstore_database
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \tool_log\local\privacy\logstore_provider {
+
+    use \tool_log\local\privacy\moodle_database_export_and_delete;
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('log', [
+            'eventname' => 'privacy:metadata:log:eventname',
+            'userid' => 'privacy:metadata:log:userid',
+            'relateduserid' => 'privacy:metadata:log:relateduserid',
+            'anonymous' => 'privacy:metadata:log:anonymous',
+            'other' => 'privacy:metadata:log:other',
+            'timecreated' => 'privacy:metadata:log:timecreated',
+            'origin' => 'privacy:metadata:log:origin',
+            'ip' => 'privacy:metadata:log:ip',
+            'realuserid' => 'privacy:metadata:log:realuserid',
+        ], 'privacy:metadata:log');
+        return $collection;
+    }
+
+    /**
+     * Add contexts that contain user information for the specified user.
+     *
+     * @param contextlist $contextlist The contextlist to add the contexts to.
+     * @param int $userid The user to find the contexts for.
+     * @return void
+     */
+    public static function add_contexts_for_userid(contextlist $contextlist, $userid) {
+        list($db, $table) = static::get_database_and_table();
+        if (!$db || !$table) {
+            return;
+        }
+
+        $sql = 'userid = :userid1 OR relateduserid = :userid2 OR realuserid = :userid3';
+        $params = ['userid1' => $userid, 'userid2' => $userid, 'userid3' => $userid];
+        $contextids = $db->get_fieldset_select($table, 'DISTINCT contextid', $sql, $params);
+        if (empty($contextids)) {
+            return;
+        }
+
+        $sql = implode(' UNION ', array_map(function($id) use ($db) {
+            return 'SELECT ' . $id . $db->sql_null_from_clause();
+        }, $contextids));
+        $contextlist->add_from_sql($sql, []);
+    }
+
+    /**
+     * Get the database object.
+     *
+     * @return array Containing moodle_database, string, or null values.
+     */
+    protected static function get_database_and_table() {
+        $manager = get_log_manager();
+        $store = new \logstore_database\log\store($manager);
+        $db = $store->get_extdb();
+        return $db ? [$db, $store->get_config_value('dbtable')] : [null, null];
+    }
+
+    /**
+     * Get the path to export the logs to.
+     *
+     * @return array
+     */
+    protected static function get_export_subcontext() {
+        return [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_database')];
+    }
+}
index 0873229..8f49696 100644 (file)
@@ -44,6 +44,16 @@ $string['other'] = 'Other';
 $string['participating'] = 'Participating';
 $string['pluginname'] = 'External database log';
 $string['pluginname_desc'] = 'A log plugin that stores log entries in an external database table.';
+$string['privacy:metadata:log'] = 'A collection of past events';
+$string['privacy:metadata:log:anonymous'] = 'Whether the event was flagged as anonymous';
+$string['privacy:metadata:log:eventname'] = 'The event name';
+$string['privacy:metadata:log:ip'] = 'The IP address used at the time of the event';
+$string['privacy:metadata:log:origin'] = 'The origin of the event';
+$string['privacy:metadata:log:other'] = 'Additional information about the event';
+$string['privacy:metadata:log:realuserid'] = 'The ID of the real user behind the event, when masquerading a user.';
+$string['privacy:metadata:log:relateduserid'] = 'The ID of a user related to this event';
+$string['privacy:metadata:log:timecreated'] = 'The time at which the event occurred';
+$string['privacy:metadata:log:userid'] = 'The ID of the user who triggered this event';
 $string['read'] = 'Read';
 $string['tablenotfound'] = 'Specified table was not found';
 $string['teaching'] = 'Teaching';
diff --git a/admin/tool/log/store/database/tests/privacy_test.php b/admin/tool/log/store/database/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..4a1e37e
--- /dev/null
@@ -0,0 +1,416 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    logstore_database
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use logstore_database\privacy\provider;
+
+require_once(__DIR__ . '/fixtures/event.php');
+
+/**
+ * Data provider testcase class.
+ *
+ * This testcase is almost identical to the logstore_standard testcase, aside from the
+ * initialisation of the relevant logstore obviously.
+ *
+ * @package    logstore_database
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class logstore_database_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        global $CFG;
+        $this->resetAfterTest();
+        $this->preventResetByRollback(); // Logging waits till the transaction gets committed.
+
+        // Fake the settings, we will abuse the standard plugin table here...
+        set_config('dbdriver', $CFG->dblibrary . '/' . $CFG->dbtype, 'logstore_database');
+        set_config('dbhost', $CFG->dbhost, 'logstore_database');
+        set_config('dbuser', $CFG->dbuser, 'logstore_database');
+        set_config('dbpass', $CFG->dbpass, 'logstore_database');
+        set_config('dbname', $CFG->dbname, 'logstore_database');
+        set_config('dbtable', $CFG->prefix . 'logstore_standard_log', 'logstore_database');
+        if (!empty($CFG->dboptions['dbpersist'])) {
+            set_config('dbpersist', 1, 'logstore_database');
+        } else {
+            set_config('dbpersist', 0, 'logstore_database');
+        }
+        if (!empty($CFG->dboptions['dbsocket'])) {
+            set_config('dbsocket', $CFG->dboptions['dbsocket'], 'logstore_database');
+        } else {
+            set_config('dbsocket', '', 'logstore_database');
+        }
+        if (!empty($CFG->dboptions['dbport'])) {
+            set_config('dbport', $CFG->dboptions['dbport'], 'logstore_database');
+        } else {
+            set_config('dbport', '', 'logstore_database');
+        }
+        if (!empty($CFG->dboptions['dbschema'])) {
+            set_config('dbschema', $CFG->dboptions['dbschema'], 'logstore_database');
+        } else {
+            set_config('dbschema', '', 'logstore_database');
+        }
+        if (!empty($CFG->dboptions['dbcollation'])) {
+            set_config('dbcollation', $CFG->dboptions['dbcollation'], 'logstore_database');
+        } else {
+            set_config('dbcollation', '', 'logstore_database');
+        }
+        if (!empty($CFG->dboptions['dbhandlesoptions'])) {
+            set_config('dbhandlesoptions', $CFG->dboptions['dbhandlesoptions'], 'logstore_database');
+        } else {
+            set_config('dbhandlesoptions', false, 'logstore_database');
+        }
+    }
+
+    public function test_get_contexts_for_userid() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+
+        $c1 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm2 = $this->getDataGenerator()->create_module('url', ['course' => $c2]);
+
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+        $cm2ctx = context_module::instance($cm2->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), []);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $cm1ctx]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$cm1ctx]);
+
+        // User 2 is the related user.
+        $this->setUser(0);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), []);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $cm2ctx, 'relateduserid' => $u2->id]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), [$cm2ctx]);
+
+        // Admin user is the real user.
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), []);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), []);
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx]);
+
+        // By admin user masquerading u1 related to u3.
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$cm1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx]);
+        $this->setAdminUser();
+        \core\session\manager::loginas($u1->id, context_system::instance());
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u3->id]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$sysctx, $cm1ctx, $c2ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx, $c2ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx, $c2ctx]);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(3, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_database', [$c1ctx->id]));
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(3, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $u4 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm2 = $this->getDataGenerator()->create_module('url', ['course' => $c2]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+        $cm2ctx = context_module::instance($cm2->cmid);
+
+        $path = [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_database')];
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx, 'other' => ['i' => 0]]);
+        $e->trigger();
+
+        // User 2 is related.
+        $this->setUser(0);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx, 'relateduserid' => $u2->id,
+            'other' => ['i' => 1]]);
+        $e->trigger();
+
+        // Admin user masquerades u3, which is related to u4.
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c1ctx, 'relateduserid' => $u4->id,
+            'other' => ['i' => 2]]);
+        $e->trigger();
+
+        // Confirm data present for u1.
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_database', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertSame(0, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u2.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u2, 'logstore_database', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertSame(1, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u3.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u3, 'logstore_database', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['masquerading_user_was_you']);
+        $this->assertSame(2, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u4.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u4, 'logstore_database', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['masquerading_user_was_you']);
+        $this->assertSame(2, $data->logs[0]['other']['i']);
+
+        // Add anonymous events.
+        $this->setUser($u1);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u2->id,
+            'anonymous' => true]);
+        $e->trigger();
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_database\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u4->id,
+            'anonymous' => true]);
+        $e->trigger();
+
+        // Confirm data present for u1.
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_database', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+
+        // Confirm data present for u2.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u2, 'logstore_database', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertArrayNotHasKey('author_of_the_action_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('authorid', $data->logs[0]);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+
+        // Confirm data present for u3.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u3, 'logstore_database', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertArrayNotHasKey('masquerading_user_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('masqueradinguserid', $data->logs[0]);
+
+        // Confirm data present for u4.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u4, 'logstore_database', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertArrayNotHasKey('author_of_the_action_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('authorid', $data->logs[0]);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertArrayNotHasKey('masquerading_user_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('masqueradinguserid', $data->logs[0]);
+    }
+
+    /**
+     * Assert the content of a context list.
+     *
+     * @param contextlist $contextlist The collection.
+     * @param array $expected List of expected contexts or IDs.
+     * @return void
+     */
+    protected function assert_contextlist_equals($contextlist, array $expected) {
+        $expectedids = array_map(function($context) {
+            if (is_object($context)) {
+                return $context->id;
+            }
+            return $context;
+        }, $expected);
+        $contextids = array_map('intval', $contextlist->get_contextids());
+        sort($contextids);
+        sort($expectedids);
+        $this->assertEquals($expectedids, $contextids);
+    }
+
+    /**
+     * Enable logging.
+     *
+     * @return void
+     */
+    protected function enable_logging() {
+        set_config('enabled_stores', 'logstore_database', 'tool_log');
+        set_config('buffersize', 0, 'logstore_database');
+        set_config('logguests', 1, 'logstore_database');
+        get_log_manager(true);
+    }
+
+    /**
+     * Get the contextlist for a user.
+     *
+     * @param object $user The user.
+     * @return contextlist
+     */
+    protected function get_contextlist_for_user($user) {
+        $contextlist = new contextlist();
+        provider::add_contexts_for_userid($contextlist, $user->id);
+        return $contextlist;
+    }
+}
diff --git a/admin/tool/log/store/legacy/classes/privacy/provider.php b/admin/tool/log/store/legacy/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..298d821
--- /dev/null
@@ -0,0 +1,220 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    logstore_legacy
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace logstore_legacy\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use tool_log\local\privacy\helper;
+
+/**
+ * Data provider class.
+ *
+ * @package    logstore_legacy
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \tool_log\local\privacy\logstore_provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('log', [
+            'time' => 'privacy:metadata:log:time',
+            'userid' => 'privacy:metadata:log:userid',
+            'ip' => 'privacy:metadata:log:ip',
+            'action' => 'privacy:metadata:log:action',
+            'url' => 'privacy:metadata:log:url',
+            'info' => 'privacy:metadata:log:info',
+        ], 'privacy:metadata:log');
+        return $collection;
+    }
+
+    /**
+     * Add contexts that contain user information for the specified user.
+     *
+     * @param contextlist $contextlist The contextlist to add the contexts to.
+     * @param int $userid The user to find the contexts for.
+     * @return void
+     */
+    public static function add_contexts_for_userid(contextlist $contextlist, $userid) {
+        $sql = "
+            SELECT ctx.id
+              FROM {context} ctx
+              JOIN {log} l
+                ON (l.cmid = 0 AND l.course = ctx.instanceid AND ctx.contextlevel = :courselevel)
+                OR (l.cmid > 0 AND l.cmid = ctx.instanceid AND ctx.contextlevel = :modulelevel)
+                OR (l.course <= 0 AND ctx.id = :syscontextid)
+             WHERE l.userid = :userid";
+        $params = [
+            'courselevel' => CONTEXT_COURSE,
+            'modulelevel' => CONTEXT_MODULE,
+            'syscontextid' => SYSCONTEXTID,
+            'userid' => $userid,
+        ];
+        $contextlist->add_from_sql($sql, $params);
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        global $DB;
+
+        $userid = $contextlist->get_user()->id;
+        list($insql, $inparams) = static::get_sql_where_from_contexts($contextlist->get_contexts());
+        if (empty($insql)) {
+            return;
+        }
+        $sql = "userid = :userid AND $insql";
+        $params = array_merge($inparams, ['userid' => $userid]);
+
+        $path = [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_legacy')];
+        $flush = function($lastcontextid, $data) use ($path) {
+            $context = context::instance_by_id($lastcontextid);
+            writer::with_context($context)->export_data($path, (object) ['logs' => $data]);
+        };
+
+        $lastcontextid = null;
+        $data = [];
+        $recordset = $DB->get_recordset_select('log', $sql, $params, 'course, cmid, time, id');
+        foreach ($recordset as $record) {
+            $event = \logstore_legacy\event\legacy_logged::restore_legacy($record);
+            $context = $event->get_context();
+            if ($lastcontextid && $lastcontextid != $context->id) {
+                $flush($lastcontextid, $data);
+                $data = [];
+            }
+
+            $extra = $event->get_logextra();
+            $data[] = [
+                'name' => $event->get_name(),
+                'description' => $event->get_description(),
+                'timecreated' => transform::datetime($event->timecreated),
+                'ip' => $extra['ip'],
+                'origin' => helper::transform_origin($extra['origin']),
+            ];
+
+            $lastcontextid = $context->id;
+        }
+        if ($lastcontextid) {
+            $flush($lastcontextid, $data);
+        }
+        $recordset->close();
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        global $DB;
+        list($sql, $params) = static::get_sql_where_from_contexts([$context]);
+        if (empty($sql)) {
+            return;
+        }
+        $DB->delete_records_select('log', $sql, $params);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        global $DB;
+        list($sql, $params) = static::get_sql_where_from_contexts($contextlist->get_contexts());
+        if (empty($sql)) {
+            return;
+        }
+        $userid = $contextlist->get_user()->id;
+        $DB->delete_records_select('log', "$sql AND userid = :userid", array_merge($params, ['userid' => $userid]));
+    }
+
+    /**
+     * Get an SQL where statement from a list of contexts.
+     *
+     * @param array $contexts The contexts.
+     * @return array [$sql, $params]
+     */
+    protected static function get_sql_where_from_contexts(array $contexts) {
+        global $DB;
+
+        $sorted = array_reduce($contexts, function ($carry, $context) {
+            $level = $context->contextlevel;
+            if ($level == CONTEXT_MODULE || $level == CONTEXT_COURSE) {
+                $carry[$level][] = $context->instanceid;
+            } else if ($level == CONTEXT_SYSTEM) {
+                $carry[$level] = $context->id;
+            }
+            return $carry;
+        }, [
+            CONTEXT_COURSE => [],
+            CONTEXT_MODULE => [],
+            CONTEXT_SYSTEM => null,
+        ]);
+
+        $sqls = [];
+        $params = [];
+
+        if (!empty($sorted[CONTEXT_MODULE])) {
+            list($insql, $inparams) = $DB->get_in_or_equal($sorted[CONTEXT_MODULE], SQL_PARAMS_NAMED);
+            $sqls[] = "cmid $insql";
+            $params = array_merge($params, $inparams);
+        }
+
+        if (!empty($sorted[CONTEXT_COURSE])) {
+            list($insql, $inparams) = $DB->get_in_or_equal($sorted[CONTEXT_COURSE], SQL_PARAMS_NAMED);
+
+            $sqls[] = "cmid = 0 AND course $insql";
+            $params = array_merge($params, $inparams);
+        }
+
+        if (!empty($sorted[CONTEXT_SYSTEM])) {
+            $sqls[] = "course <= 0";
+        }
+
+        if (empty($sqls)) {
+            return [null, null];
+        }
+
+        return ['((' . implode(') OR (', $sqls) . '))', $params];
+    }
+}
index 1086cc6..5f35555 100644 (file)
@@ -27,4 +27,11 @@ $string['loglegacy'] = 'Log legacy data';
 $string['loglegacy_help'] = 'This plugin records log data to the legacy log table (mdl_log). This functionality has been replaced by newer, richer and more efficient logging plugins, so you should only run this plugin if you have old custom reports that directly query the old log table. Writing to the legacy logs will increase load, so it is recommended that you disable this plugin for performance reasons when it is not needed.';
 $string['pluginname'] = 'Legacy log';
 $string['pluginname_desc'] = 'A log plugin that stores log entries in the legacy log table.';
+$string['privacy:metadata:log'] = 'A collection of past events';
+$string['privacy:metadata:log:action'] = 'A description of the action';
+$string['privacy:metadata:log:info'] = 'Additional information';
+$string['privacy:metadata:log:ip'] = 'The IP address used at the time of the event';
+$string['privacy:metadata:log:time'] = 'The date at wich the action took place';
+$string['privacy:metadata:log:url'] = 'The URL related to the event';
+$string['privacy:metadata:log:userid'] = 'The ID of the user who performed the action';
 $string['taskcleanup'] = 'Legacy log table cleanup';
diff --git a/admin/tool/log/store/legacy/tests/privacy_test.php b/admin/tool/log/store/legacy/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..a60960a
--- /dev/null
@@ -0,0 +1,344 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    logstore_legacy
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use logstore_legacy\privacy\provider;
+use logstore_legacy\event\unittest_executed;
+
+require_once(__DIR__ . '/fixtures/event.php');
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    logstore_legacy
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class logstore_legacy_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+    }
+
+    public function test_get_contexts_for_userid() {
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), []);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 1]]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$cm1ctx]);
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), []);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 2]]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), [$cm1ctx]);
+
+        // User 3 is the author.
+        $this->setUser($u3);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), []);
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 3]]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx]);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 1]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 2]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 3]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 4]]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 5]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 6]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 7]]);
+        $e->trigger();
+
+        // Assert what we have.
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => 0]));
+        $this->assertEquals(4, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete other context.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_legacy', [$c2ctx->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => 0]));
+        $this->assertEquals(4, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete system.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_legacy', [$sysctx->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => 0]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete course.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_legacy', [$c1ctx->id]));
+        $this->assertTrue($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => 0]));
+        $this->assertEquals(2, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete course.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_legacy', [$cm1ctx->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['userid' => $u1->id, 'cmid' => 0, 'course' => 0]));
+        $this->assertEquals(0, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 1]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 2]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 3]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 4]]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 5]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 6]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 7]]);
+        $e->trigger();
+
+        // Assert what we have.
+        $this->assertTrue($DB->record_exists('log', ['cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['cmid' => 0, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['cmid' => 0, 'course' => 0]));
+        $this->assertEquals(4, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete other context.
+        provider::delete_data_for_all_users_in_context($c2ctx);
+        $this->assertTrue($DB->record_exists('log', ['cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['cmid' => 0, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['cmid' => 0, 'course' => 0]));
+        $this->assertEquals(4, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete system.
+        provider::delete_data_for_all_users_in_context($sysctx);
+        $this->assertTrue($DB->record_exists('log', ['cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertTrue($DB->record_exists('log', ['cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['cmid' => 0, 'course' => 0]));
+        $this->assertEquals(3, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete course.
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $this->assertTrue($DB->record_exists('log', ['cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['cmid' => 0, 'course' => 0]));
+        $this->assertEquals(2, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('log', ['userid' => $u2->id]));
+
+        // Delete course.
+        provider::delete_data_for_all_users_in_context($cm1ctx);
+        $this->assertFalse($DB->record_exists('log', ['cmid' => $cm1->cmid, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['cmid' => 0, 'course' => $c1->id]));
+        $this->assertFalse($DB->record_exists('log', ['cmid' => 0, 'course' => 0]));
+        $this->assertEquals(0, $DB->count_records('log', ['userid' => $u1->id]));
+        $this->assertEquals(0, $DB->count_records('log', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        global $DB;
+
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+        $path = [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_legacy')];
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 1]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 2]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 3]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 4]]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = unittest_executed::create(['context' => $cm1ctx, 'other' => ['sample' => 5]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $c1ctx, 'other' => ['sample' => 6]]);
+        $e->trigger();
+        $e = unittest_executed::create(['context' => $sysctx, 'other' => ['sample' => 7]]);
+        $e->trigger();
+
+        // Test export.
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_legacy', [$cm1ctx->id]));
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($cm1ctx)->get_data($path);
+        $this->assertCount(2, $data->logs);
+
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_legacy', [$c1ctx->id]));
+        $data = writer::with_context($cm1ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_legacy', [$sysctx->id]));
+        $data = writer::with_context($sysctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+    }
+
+    /**
+     * Assert the content of a context list.
+     *
+     * @param contextlist $contextlist The collection.
+     * @param array $expected List of expected contexts or IDs.
+     * @return void
+     */
+    protected function assert_contextlist_equals($contextlist, array $expected) {
+        $expectedids = array_map(function($context) {
+            if (is_object($context)) {
+                return $context->id;
+            }
+            return $context;
+        }, $expected);
+        $contextids = array_map('intval', $contextlist->get_contextids());
+        sort($contextids);
+        sort($expectedids);
+        $this->assertEquals($expectedids, $contextids);
+    }
+
+    /**
+     * Enable logging.
+     *
+     * @return void
+     */
+    protected function enable_logging() {
+        set_config('enabled_stores', 'logstore_legacy', 'tool_log');
+        set_config('loglegacy', 1, 'logstore_legacy');
+        get_log_manager(true);
+    }
+
+    /**
+     * Get the contextlist for a user.
+     *
+     * @param object $user The user.
+     * @return contextlist
+     */
+    protected function get_contextlist_for_user($user) {
+        $contextlist = new contextlist();
+        provider::add_contexts_for_userid($contextlist, $user->id);
+        return $contextlist;
+    }
+}
diff --git a/admin/tool/log/store/standard/classes/privacy/provider.php b/admin/tool/log/store/standard/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..1994e29
--- /dev/null
@@ -0,0 +1,109 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    logstore_standard
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace logstore_standard\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+
+/**
+ * Data provider class.
+ *
+ * @package    logstore_standard
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \tool_log\local\privacy\logstore_provider {
+
+    use \tool_log\local\privacy\moodle_database_export_and_delete;
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_database_table('log', [
+            'eventname' => 'privacy:metadata:log:eventname',
+            'userid' => 'privacy:metadata:log:userid',
+            'relateduserid' => 'privacy:metadata:log:relateduserid',
+            'anonymous' => 'privacy:metadata:log:anonymous',
+            'other' => 'privacy:metadata:log:other',
+            'timecreated' => 'privacy:metadata:log:timecreated',
+            'origin' => 'privacy:metadata:log:origin',
+            'ip' => 'privacy:metadata:log:ip',
+            'realuserid' => 'privacy:metadata:log:realuserid',
+        ], 'privacy:metadata:log');
+        return $collection;
+    }
+
+    /**
+     * Add contexts that contain user information for the specified user.
+     *
+     * @param contextlist $contextlist The contextlist to add the contexts to.
+     * @param int $userid The user to find the contexts for.
+     * @return void
+     */
+    public static function add_contexts_for_userid(contextlist $contextlist, $userid) {
+        $sql = "
+            SELECT ctx.id
+              FROM {context} ctx
+              JOIN {logstore_standard_log} l
+                ON l.contextid = ctx.id
+             WHERE l.userid = :userid1
+                OR l.relateduserid = :userid2
+                OR l.realuserid = :userid3";
+        $contextlist->add_from_sql($sql, [
+            'userid1' => $userid,
+            'userid2' => $userid,
+            'userid3' => $userid,
+        ]);
+    }
+
+    /**
+     * Get the database object.
+     *
+     * @return array Containing moodle_database, string, or null values.
+     */
+    protected static function get_database_and_table() {
+        global $DB;
+        return [$DB, 'logstore_standard_log'];
+    }
+
+    /**
+     * Get the path to export the logs to.
+     *
+     * @return array
+     */
+    protected static function get_export_subcontext() {
+        return [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_standard')];
+    }
+}
index 2e2c2a7..33c229f 100644 (file)
 $string['buffersize'] = 'Write buffer size';
 $string['pluginname'] = 'Standard log';
 $string['pluginname_desc'] = 'A log plugin stores log entries in a Moodle database table.';
+$string['privacy:metadata:log'] = 'A collection of past events';
+$string['privacy:metadata:log:anonymous'] = 'Whether the event was flagged as anonymous';
+$string['privacy:metadata:log:eventname'] = 'The event name';
+$string['privacy:metadata:log:ip'] = 'The IP address used at the time of the event';
+$string['privacy:metadata:log:origin'] = 'The origin of the event';
+$string['privacy:metadata:log:other'] = 'Additional information about the event';
+$string['privacy:metadata:log:realuserid'] = 'The ID of the real user behind the event, when masquerading a user.';
+$string['privacy:metadata:log:relateduserid'] = 'The ID of a user related to this event';
+$string['privacy:metadata:log:timecreated'] = 'The time at which the event occurred';
+$string['privacy:metadata:log:userid'] = 'The ID of the user who triggered this event';
 $string['taskcleanup'] = 'Log table cleanup';
diff --git a/admin/tool/log/store/standard/tests/privacy_test.php b/admin/tool/log/store/standard/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..5103b3a
--- /dev/null
@@ -0,0 +1,373 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    logstore_standard
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use logstore_standard\privacy\provider;
+
+require_once(__DIR__ . '/fixtures/event.php');
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    logstore_standard
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class logstore_standard_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+        $this->preventResetByRollback(); // Logging waits till the transaction gets committed.
+    }
+
+    public function test_get_contexts_for_userid() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+
+        $c1 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm2 = $this->getDataGenerator()->create_module('url', ['course' => $c2]);
+
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+        $cm2ctx = context_module::instance($cm2->cmid);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), []);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $cm1ctx]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$cm1ctx]);
+
+        // User 2 is the related user.
+        $this->setUser(0);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), []);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $cm2ctx, 'relateduserid' => $u2->id]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u2), [$cm2ctx]);
+
+        // Admin user is the real user.
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), []);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), []);
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx]);
+
+        // By admin user masquerading u1 related to u3.
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$cm1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx]);
+        $this->setAdminUser();
+        \core\session\manager::loginas($u1->id, context_system::instance());
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u3->id]);
+        $e->trigger();
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u1), [$sysctx, $cm1ctx, $c2ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($u3), [$sysctx, $c1ctx, $c2ctx]);
+        $this->assert_contextlist_equals($this->get_contextlist_for_user($admin), [$sysctx, $c1ctx, $c2ctx]);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(3, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_standard', [$c1ctx->id]));
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c2 = $this->getDataGenerator()->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(3, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $u3 = $this->getDataGenerator()->create_user();
+        $u4 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $cm1 = $this->getDataGenerator()->create_module('url', ['course' => $c1]);
+        $c2 = $this->getDataGenerator()->create_course();
+        $cm2 = $this->getDataGenerator()->create_module('url', ['course' => $c2]);
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $cm1ctx = context_module::instance($cm1->cmid);
+        $cm2ctx = context_module::instance($cm2->cmid);
+
+        $path = [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_standard')];
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx, 'other' => ['i' => 0]]);
+        $e->trigger();
+
+        // User 2 is related.
+        $this->setUser(0);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx, 'relateduserid' => $u2->id,
+            'other' => ['i' => 1]]);
+        $e->trigger();
+
+        // Admin user masquerades u3, which is related to u4.
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx, 'relateduserid' => $u4->id,
+            'other' => ['i' => 2]]);
+        $e->trigger();
+
+        // Confirm data present for u1.
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_standard', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertSame(0, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u2.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u2, 'logstore_standard', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertSame(1, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u3.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u3, 'logstore_standard', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['masquerading_user_was_you']);
+        $this->assertSame(2, $data->logs[0]['other']['i']);
+
+        // Confirm data present for u4.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u4, 'logstore_standard', [$c2ctx->id, $c1ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertEquals(transform::yesno(false), $data->logs[0]['masquerading_user_was_you']);
+        $this->assertSame(2, $data->logs[0]['other']['i']);
+
+        // Add anonymous events.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u2->id,
+            'anonymous' => true]);
+        $e->trigger();
+        $this->setAdminUser();
+        \core\session\manager::loginas($u3->id, $sysctx);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c2ctx, 'relateduserid' => $u4->id,
+            'anonymous' => true]);
+        $e->trigger();
+
+        // Confirm data present for u1.
+        provider::export_user_data(new approved_contextlist($u1, 'logstore_standard', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+
+        // Confirm data present for u2.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u2, 'logstore_standard', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertArrayNotHasKey('author_of_the_action_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('authorid', $data->logs[0]);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+
+        // Confirm data present for u3.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u3, 'logstore_standard', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertArrayNotHasKey('masquerading_user_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('masqueradinguserid', $data->logs[0]);
+
+        // Confirm data present for u4.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u4, 'logstore_standard', [$c2ctx->id]));
+        $data = writer::with_context($c2ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['action_was_done_anonymously']);
+        $this->assertArrayNotHasKey('author_of_the_action_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('authorid', $data->logs[0]);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['related_user_was_you']);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_masqueraded']);
+        $this->assertArrayNotHasKey('masquerading_user_was_you', $data->logs[0]);
+        $this->assertArrayNotHasKey('masqueradinguserid', $data->logs[0]);
+    }
+
+    /**
+     * Assert the content of a context list.
+     *
+     * @param contextlist $contextlist The collection.
+     * @param array $expected List of expected contexts or IDs.
+     * @return void
+     */
+    protected function assert_contextlist_equals($contextlist, array $expected) {
+        $expectedids = array_map(function($context) {
+            if (is_object($context)) {
+                return $context->id;
+            }
+            return $context;
+        }, $expected);
+        $contextids = array_map('intval', $contextlist->get_contextids());
+        sort($contextids);
+        sort($expectedids);
+        $this->assertEquals($expectedids, $contextids);
+    }
+
+    /**
+     * Enable logging.
+     *
+     * @return void
+     */
+    protected function enable_logging() {
+        set_config('enabled_stores', 'logstore_standard', 'tool_log');
+        set_config('buffersize', 0, 'logstore_standard');
+        set_config('logguests', 1, 'logstore_standard');
+    }
+
+    /**
+     * Get the contextlist for a user.
+     *
+     * @param object $user The user.
+     * @return contextlist
+     */
+    protected function get_contextlist_for_user($user) {
+        $contextlist = new contextlist();
+        provider::add_contexts_for_userid($contextlist, $user->id);
+        return $contextlist;
+    }
+}
diff --git a/admin/tool/log/tests/privacy_test.php b/admin/tool/log/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..9e5be71
--- /dev/null
@@ -0,0 +1,176 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    tool_log
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use tool_log\privacy\provider;
+
+require_once($CFG->dirroot . '/admin/tool/log/store/standard/tests/fixtures/event.php');
+
+/**
+ * Data provider testcase class.
+ *
+ * We're not testing the full functionality, just that the provider passes the requests
+ * down to at least one of its subplugin. Each subplugin should have tests to cover the
+ * different provider methods in depth.
+ *
+ * @package    tool_log
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_log_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+        $this->preventResetByRollback(); // Logging waits till the transaction gets committed.
+    }
+
+    public function test_get_contexts_for_userid() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c1ctx = context_course::instance($c1->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        $this->setUser($u1);
+        $this->assertEmpty(provider::get_contexts_for_userid($u1->id)->get_contextids(), []);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $this->assertEquals($c1ctx->id, provider::get_contexts_for_userid($u1->id)->get_contextids()[0]);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c1ctx = context_course::instance($c1->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_user(new approved_contextlist($u1, 'logstore_standard', [$c1ctx->id]));
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['userid' => $u1->id, 'contextid' => $c1ctx->id]));
+        $this->assertEquals(0, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+        $u1 = $this->getDataGenerator()->create_user();
+        $u2 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c1ctx = context_course::instance($c1->id);
+
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+
+        // User 2 is the author.
+        $this->setUser($u2);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx]);
+        $e->trigger();
+
+        // Confirm data present.
+        $this->assertTrue($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(2, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(1, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+
+        // Delete all the things!
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $this->assertFalse($DB->record_exists('logstore_standard_log', ['contextid' => $c1ctx->id]));
+        $this->assertEquals(0, $DB->count_records('logstore_standard_log', ['userid' => $u1->id]));
+        $this->assertEquals(0, $DB->count_records('logstore_standard_log', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        $admin = \core_user::get_user(2);
+        $u1 = $this->getDataGenerator()->create_user();
+        $c1 = $this->getDataGenerator()->create_course();
+        $c1ctx = context_course::instance($c1->id);
+
+        $path = [get_string('privacy:path:logs', 'tool_log'), get_string('pluginname', 'logstore_standard')];
+        $this->enable_logging();
+        $manager = get_log_manager(true);
+
+        // User 1 is the author.
+        $this->setUser($u1);
+        $e = \logstore_standard\event\unittest_executed::create(['context' => $c1ctx, 'other' => ['i' => 123]]);
+        $e->trigger();
+
+        // Confirm data present for u1.
+        provider::export_user_data(new approved_contextlist($u1, 'tool_log', [$c1ctx->id]));
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->logs);
+        $this->assertEquals(transform::yesno(true), $data->logs[0]['author_of_the_action_was_you']);
+        $this->assertSame(123, $data->logs[0]['other']['i']);
+    }
+
+    /**
+     * Enable logging.
+     *
+     * @return void
+     */
+    protected function enable_logging() {
+        set_config('enabled_stores', 'logstore_standard', 'tool_log');
+        set_config('buffersize', 0, 'logstore_standard');
+        set_config('logguests', 1, 'logstore_standard');
+    }
+}
index c8ef59f..6596aad 100644 (file)
@@ -310,6 +310,16 @@ class manager {
         return true;
     }
 
+    /**
+     * Remove older verification failures.
+     *
+     * @return void
+     */
+    public function tidy_old_verification_failures() {
+        global $DB;
+        $DB->delete_records_select('messageinbound_messagelist', 'timecreated < :time', ['time' => time() - DAYSECS]);
+    }
+
     /**
      * Process a message and pass it through the Inbound Message handling systems.
      *
diff --git a/admin/tool/messageinbound/classes/privacy/provider.php b/admin/tool/messageinbound/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..53be916
--- /dev/null
@@ -0,0 +1,173 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    tool_messageinbound
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_messageinbound\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use context_user;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+
+/**
+ * Data provider class.
+ *
+ * @package    tool_messageinbound
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+
+        $collection->add_database_table('messageinbound_messagelist', [
+            'messageid' => 'privacy:metadata:messagelist:messageid',
+            'userid' => 'privacy:metadata:messagelist:userid',
+            'address' => 'privacy:metadata:messagelist:address',
+            'timecreated' => 'privacy:metadata:messagelist:timecreated',
+        ], 'privacy:metadata:messagelist');
+
+        // Arguably the keys are handled by \core\message\inbound\address_manager and thus could/should be handled by core.
+        $collection->add_subsystem_link('core_userkey', [], 'privacy:metadata:coreuserkey');
+
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param int $userid The user to search.
+     * @return \contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
+        $contextlist = new \core_privacy\local\request\contextlist();
+
+        // Always add the user context so we're sure we're not dodging user keys, besides it's not costly to do so.
+        $contextlist->add_user_context($userid);
+
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        global $DB;
+        if (!static::approved_contextlist_contains_my_context($contextlist)) {
+            // We only care about the user's user context.
+            return;
+        }
+
+        $userid = $contextlist->get_user()->id;
+        $context = context_user::instance($userid);
+        $path = [get_string('messageinbound', 'tool_messageinbound')];
+
+        // Export user keys.
+        \core_userkey\privacy\provider::export_userkeys($context, $path, 'messageinbound_handler');
+
+        // Export the message list.
+        $data = [];
+        $recordset = $DB->get_recordset('messageinbound_messagelist', ['userid' => $userid], 'timecreated, id');
+        foreach ($recordset as $record) {
+            $data[] = [
+                'received_at' => $record->address,
+                'timecreated' => transform::datetime($record->timecreated),
+            ];
+        }
+        $recordset->close();
+        writer::with_context($context)->export_data($path, (object) ['messages_pending_validation' => $data]);
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        global $DB;
+        if ($context->contextlevel != CONTEXT_USER) {
+            return;
+        }
+
+        static::delete_user_data($context->instanceid);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        global $DB;
+        if (!static::approved_contextlist_contains_my_context($contextlist)) {
+            // We only care about the user's user context.
+            return;
+        }
+
+        static::delete_user_data($contextlist->get_user()->id);
+    }
+
+    /**
+     * Delete a user's data.
+     *
+     * @param int $userid The user ID.
+     * @return void
+     */
+    protected static function delete_user_data($userid) {
+        global $DB;
+        $DB->delete_records_select('messageinbound_messagelist', 'userid = :userid', ['userid' => $userid]);
+        \core_userkey\privacy\provider::delete_userkeys('messageinbound_handler', $userid);
+    }
+
+    /**
+     * Return whether the contextlist contains our own context.
+     *
+     * @param approved_contextlist $contextlist The contextlist
+     * @return bool
+     */
+    protected static function approved_contextlist_contains_my_context(approved_contextlist $contextlist) {
+        $userid = $contextlist->get_user()->id;
+        foreach ($contextlist->get_contexts() as $context) {
+            if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $userid) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+}
index e8b1c7a..fc2c01d 100644 (file)
@@ -49,6 +49,7 @@ class cleanup_task extends \core\task\scheduled_task {
      */
     public function execute() {
         $manager = new \tool_messageinbound\manager();
-        return $manager->tidy_old_messages();
+        $manager->tidy_old_messages();
+        $manager->tidy_old_verification_failures();
     }
 }
index b074060..c847b03 100644 (file)
@@ -94,6 +94,12 @@ $string['onehour'] = 'One hour';
 $string['oneweek'] = 'One week';
 $string['oneyear'] = 'One year';
 $string['pluginname'] = 'Inbound message configuration';
+$string['privacy:metadata:coreuserkey'] = 'User\'s keys to validate the email received';
+$string['privacy:metadata:messagelist'] = 'A list of message identifiers which failed validation and requires further authorisation';
+$string['privacy:metadata:messagelist:address'] = 'The address at which the email was sent';
+$string['privacy:metadata:messagelist:messageid'] = 'The message ID';
+$string['privacy:metadata:messagelist:timecreated'] = 'The time at which the record was made';
+$string['privacy:metadata:messagelist:userid'] = 'The ID of user who need to approve the message';
 $string['replysubjectprefix'] = 'Re:';
 $string['requirevalidation'] = 'Validate sender address';
 $string['name'] = 'Name';
diff --git a/admin/tool/messageinbound/tests/manager_test.php b/admin/tool/messageinbound/tests/manager_test.php
new file mode 100644 (file)
index 0000000..b88a742
--- /dev/null
@@ -0,0 +1,97 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Manager tests.
+ *
+ * @package    tool_messageinbound
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use tool_messageinbound\privacy\provider;
+
+/**
+ * Manager testcase class.
+ *
+ * @package    tool_messageinbound
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_messageinbound_manager_testcase extends provider_testcase {
+
+    public function setUp() {
+        global $CFG;
+        $this->resetAfterTest();
+
+        // Pretend the system is enabled.
+        $CFG->messageinbound_enabled = true;
+        $CFG->messageinbound_mailbox = 'mailbox';
+        $CFG->messageinbound_domain = 'example.com';
+    }
+
+    public function test_tidy_old_verification_failures() {
+        global $DB;
+
+        $now = time();
+        $stale = $now - DAYSECS - 1;    // Make a second older because PHP Unit is too damn fast!!
+
+        $this->create_messagelist(['timecreated' => $now]);
+        $this->create_messagelist(['timecreated' => $now - HOURSECS]);
+        $this->create_messagelist(['timecreated' => $stale]);
+        $this->create_messagelist(['timecreated' => $stale - HOURSECS]);
+        $this->create_messagelist(['timecreated' => $stale - YEARSECS]);
+
+        $this->assertEquals(5, $DB->count_records('messageinbound_messagelist', []));
+        $this->assertEquals(3, $DB->count_records_select('messageinbound_messagelist', 'timecreated < :t', ['t' => $stale + 1]));
+
+        $manager = new \tool_messageinbound\manager();
+        $manager->tidy_old_verification_failures();
+
+        $this->assertEquals(2, $DB->count_records('messageinbound_messagelist', []));
+        $this->assertEquals(0, $DB->count_records_select('messageinbound_messagelist', 'timecreated < :t', ['t' => $stale + 1]));
+    }
+
+    /**
+     * Create a message to validate.
+     *
+     * @param array $params The params.
+     * @return stdClass
+     */
+    protected function create_messagelist(array $params) {
+        global $DB, $USER;
+        $record = (object) array_merge([
+            'messageid' => 'abc',
+            'userid' => $USER->id,
+            'address' => 'text@example.com',
+            'timecreated' => time(),
+        ], $params);
+        $record->id = $DB->insert_record('messageinbound_messagelist', $record);
+        return $record;
+    }
+
+}
diff --git a/admin/tool/messageinbound/tests/privacy_test.php b/admin/tool/messageinbound/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..5be172c
--- /dev/null
@@ -0,0 +1,201 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    tool_messageinbound
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use tool_messageinbound\privacy\provider;
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    tool_messageinbound
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_messageinbound_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        global $CFG;
+        $this->resetAfterTest();
+
+        // Pretend the system is enabled.
+        $CFG->messageinbound_enabled = true;
+        $CFG->messageinbound_mailbox = 'mailbox';
+        $CFG->messageinbound_domain = 'example.com';
+    }
+
+    public function test_get_contexts_for_userid() {
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $contexts = provider::get_contexts_for_userid($u1->id)->get_contexts();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u1ctx->id, $contexts[0]->id);
+
+        $contexts = provider::get_contexts_for_userid($u2->id)->get_contexts();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u2ctx->id, $contexts[0]->id);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $addressmanager = new \core\message\inbound\address_manager();
+        $addressmanager->set_handler('\tool_messageinbound\message\inbound\invalid_recipient_handler');
+        $addressmanager->set_data(123);
+
+        // Create a user key for both users.
+        $addressmanager->generate($u1->id);
+        $addressmanager->generate($u2->id);
+
+        // Create a messagelist for both users.
+        $this->create_messagelist(['userid' => $u1->id]);
+        $this->create_messagelist(['userid' => $u2->id]);
+
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u1->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u2->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u2->id]));
+
+        // Passing another user's context does not do anything.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'tool_messageinbound', [$u2ctx->id]));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u1->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u2->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u2->id]));
+
+        // Deleting user 1.
+        provider::delete_data_for_user(new approved_contextlist($u1, 'tool_messageinbound', [$u1ctx->id]));
+        $this->assertFalse($DB->record_exists('user_private_key', ['userid' => $u1->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u2->id, 'script' => 'messageinbound_handler']));
+        $this->assertFalse($DB->record_exists('messageinbound_messagelist', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $addressmanager = new \core\message\inbound\address_manager();
+        $addressmanager->set_handler('\tool_messageinbound\message\inbound\invalid_recipient_handler');
+        $addressmanager->set_data(123);
+
+        // Create a user key for both users.
+        $addressmanager->generate($u1->id);
+        $addressmanager->generate($u2->id);
+
+        // Create a messagelist for both users.
+        $this->create_messagelist(['userid' => $u1->id]);
+        $this->create_messagelist(['userid' => $u2->id]);
+
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u1->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u2->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u2->id]));
+
+        // Deleting user 1.
+        provider::delete_data_for_all_users_in_context($u1ctx);
+        $this->assertFalse($DB->record_exists('user_private_key', ['userid' => $u1->id, 'script' => 'messageinbound_handler']));
+        $this->assertTrue($DB->record_exists('user_private_key', ['userid' => $u2->id, 'script' => 'messageinbound_handler']));
+        $this->assertFalse($DB->record_exists('messageinbound_messagelist', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('messageinbound_messagelist', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $addressmanager = new \core\message\inbound\address_manager();
+        $addressmanager->set_handler('\tool_messageinbound\message\inbound\invalid_recipient_handler');
+        $addressmanager->set_data(123);
+
+        // Create a user key for both users.
+        $addressmanager->generate($u1->id);
+        $addressmanager->generate($u2->id);
+
+        // Create a messagelist for both users.
+        $this->create_messagelist(['userid' => $u1->id, 'address' => 'u1@example1.com']);
+        $this->create_messagelist(['userid' => $u1->id, 'address' => 'u1@example2.com']);
+        $this->create_messagelist(['userid' => $u2->id, 'address' => 'u2@example1.com']);
+
+        // Export for user.
+        $this->setUser($u1);
+        provider::export_user_data(new approved_contextlist($u1, 'tool_messageinbound', [$u1ctx->id, $u2ctx->id]));
+        $data = writer::with_context($u2ctx)->get_data([get_string('messageinbound', 'tool_messageinbound')]);
+        $this->assertEmpty($data);
+        $data = writer::with_context($u1ctx)->get_data([get_string('messageinbound', 'tool_messageinbound')]);
+        $this->assertCount(2, $data->messages_pending_validation);
+        $this->assertEquals('u1@example1.com', $data->messages_pending_validation[0]['received_at']);
+        $this->assertEquals('u1@example2.com', $data->messages_pending_validation[1]['received_at']);
+
+        $data = writer::with_context($u2ctx)->get_related_data([get_string('messageinbound', 'tool_messageinbound')], 'userkeys');
+        $this->assertEmpty($data);
+        $data = writer::with_context($u1ctx)->get_related_data([get_string('messageinbound', 'tool_messageinbound')], 'userkeys');
+        $this->assertCount(1, $data->keys);
+        $this->assertEquals('messageinbound_handler', $data->keys[0]->script);
+    }
+
+    /**
+     * Create a message to validate.
+     *
+     * @param array $params The params.
+     * @return stdClass
+     */
+    protected function create_messagelist(array $params) {
+        global $DB, $USER;
+        $record = (object) array_merge([
+            'messageid' => 'abc',
+            'userid' => $USER->id,
+            'address' => 'text@example.com',
+            'timecreated' => time(),
+        ], $params);
+        $record->id = $DB->insert_record('messageinbound_messagelist', $record);
+        return $record;
+    }
+
+}
index c04d32b..2c9840b 100644 (file)
 
 defined('MOODLE_INTERNAL') || die;
 
-// profiling tool, added to development
-if ((extension_loaded('xhprof') || extension_loaded('tideways')) && (!empty($CFG->profilingenabled) || !empty($CFG->earlyprofilingenabled))) {
+// Profiling tool, added to development.
+$hasextension = extension_loaded('tideways_xhprof');
+$hasextension = $hasextension || extension_loaded('tideways');
+$hasextension = $hasextension || extension_loaded('xhprof');
+$isenabled = !empty($CFG->profilingenabled) || !empty($CFG->earlyprofilingenabled);
+if ($hasextension && $isenabled) {
     $ADMIN->add('development', new admin_externalpage('toolprofiling', get_string('pluginname', 'tool_profiling'),
             "$CFG->wwwroot/$CFG->admin/tool/profiling/index.php", 'moodle/site:config'));
 }
diff --git a/auth/classes/privacy/provider.php b/auth/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..1c61c57
--- /dev/null
@@ -0,0 +1,103 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    core_auth
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_auth\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+
+/**
+ * Data provider class.
+ *
+ * @package    core_auth
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\user_preference_provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+
+        $collection->add_user_preference('auth_forcepasswordchange', 'privacy:metadata:userpref:forcepasswordchange');
+        $collection->add_user_preference('create_password', 'privacy:metadata:userpref:createpassword');
+        $collection->add_user_preference('login_failed_count', 'privacy:metadata:userpref:loginfailedcount');
+        $collection->add_user_preference('login_failed_count_since_success',
+            'privacy:metadata:userpref:loginfailedcountsincesuccess');
+        $collection->add_user_preference('login_failed_last', 'privacy:metadata:userpref:loginfailedlast');
+        $collection->add_user_preference('login_lockout', 'privacy:metadata:userpref:loginlockout');
+        $collection->add_user_preference('login_lockout_ignored', 'privacy:metadata:userpref:loginlockoutignored');
+        $collection->add_user_preference('login_lockout_secret', 'privacy:metadata:userpref:loginlockoutsecret');
+
+        return $collection;
+    }
+
+    /**
+     * Export all user preferences for the plugin.
+     *
+     * @param int $userid The userid of the user whose data is to be exported.
+     */
+    public static function export_user_preferences(int $userid) {
+
+        $yesno = function($v) {
+            return transform::yesno($v);
+        };
+        $datetime = function($v) {
+            return $v ? transform::datetime($v) : null;
+        };
+
+        $prefs = [
+            ['auth_forcepasswordchange', 'forcepasswordchange', $yesno],
+            ['create_password', 'createpassword', $yesno],
+            ['login_failed_count', 'loginfailedcount', null],
+            ['login_failed_count_since_success', 'loginfailedcountsincesuccess', null],
+            ['login_failed_last', 'loginfailedlast', $datetime],
+            ['login_lockout', 'loginlockout', $datetime],
+            ['login_lockout_ignored', 'loginlockoutignored', $yesno],
+            ['login_lockout_secret', 'loginlockoutsecret', null],
+        ];
+
+        foreach ($prefs as $prefdata) {
+            list($prefname, $langkey, $transformer) = $prefdata;
+            $value = get_user_preferences($prefname, null, $userid);
+            if ($value === null) {
+                continue;
+            }
+            writer::export_user_preference('core_auth', $prefname, $transformer ? $transformer($value) : $value,
+                get_string("privacy:metadata:userpref:{$langkey}", 'core_auth'));
+        }
+    }
+
+}
diff --git a/auth/tests/privacy_test.php b/auth/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..16701f2
--- /dev/null
@@ -0,0 +1,103 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    core_auth
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use core_auth\privacy\provider;
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    core_auth
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class core_auth_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+    }
+
+    public function test_export_user_preferences() {
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $sysctx = context_system::instance();
+        $now = time();
+
+        // Check nothing is there.
+        writer::reset();
+        provider::export_user_preferences($u1->id);
+        $prefs = writer::with_context($sysctx)->get_user_preferences('core_auth');
+        $this->assertEmpty((array) $prefs);
+
+        // Set some preferences.
+        set_user_preference('auth_forcepasswordchange', 1, $u1);
+        set_user_preference('create_password', 1, $u1);
+        set_user_preference('login_failed_count', 18, $u1);
+        set_user_preference('login_failed_count_since_success', 7, $u1);
+        set_user_preference('login_failed_last', $now - DAYSECS, $u1);
+        set_user_preference('login_lockout', $now - HOURSECS, $u1);
+        set_user_preference('login_lockout_ignored', 0, $u1);
+        set_user_preference('login_lockout_secret', 'Hello world!', $u1);
+
+        set_user_preference('auth_forcepasswordchange', 0, $u2);
+        set_user_preference('create_password', 0, $u2);
+        set_user_preference('login_lockout_ignored', 1, $u2);
+
+        // Check user 1.
+        writer::reset();
+        provider::export_user_preferences($u1->id);
+        $prefs = writer::with_context($sysctx)->get_user_preferences('core_auth');
+        $this->assertEquals(transform::yesno(true), $prefs->auth_forcepasswordchange->value);
+        $this->assertEquals(transform::yesno(true), $prefs->create_password->value);
+        $this->assertEquals(18, $prefs->login_failed_count->value);
+        $this->assertEquals(7, $prefs->login_failed_count_since_success->value);
+        $this->assertEquals(transform::datetime($now - DAYSECS), $prefs->login_failed_last->value);
+        $this->assertEquals(transform::datetime($now - HOURSECS), $prefs->login_lockout->value);
+        $this->assertEquals(transform::yesno(false), $prefs->login_lockout_ignored->value);
+        $this->assertEquals('Hello world!', $prefs->login_lockout_secret->value);
+
+        // Check user 2.
+        writer::reset();
+        provider::export_user_preferences($u2->id);
+        $prefs = writer::with_context($sysctx)->get_user_preferences('core_auth');
+        $this->assertEquals(transform::yesno(false), $prefs->auth_forcepasswordchange->value);
+        $this->assertEquals(transform::yesno(false), $prefs->create_password->value);
+        $this->assertObjectNotHasAttribute('login_failed_count', $prefs);
+        $this->assertObjectNotHasAttribute('login_failed_count_since_success', $prefs);
+        $this->assertObjectNotHasAttribute('login_failed_last', $prefs);
+        $this->assertObjectNotHasAttribute('login_lockout', $prefs);
+        $this->assertEquals(transform::yesno(true), $prefs->login_lockout_ignored->value);
+        $this->assertObjectNotHasAttribute('login_lockout_secret', $prefs);
+    }
+}
diff --git a/availability/classes/privacy/provider.php b/availability/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..bb8a3a7
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for core_availability.
+ *
+ * @package    core_availability
+ * @copyright  2018 Sara Arjona <sara@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_availability\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for core_availability implementing null_provider.
+ *
+ * @copyright  2018 Sara Arjona <sara@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return  string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
\ No newline at end of file
diff --git a/badges/classes/privacy/provider.php b/badges/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..1b198cb
--- /dev/null
@@ -0,0 +1,511 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    core_badges
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_badges\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use badge;
+use context;
+use context_course;
+use context_helper;
+use context_system;
+use context_user;
+use core_text;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+
+require_once($CFG->libdir . '/badgeslib.php');
+
+/**
+ * Data provider class.
+ *
+ * @package    core_badges
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\subsystem\provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+
+        $collection->add_database_table('badge', [
+            'usercreated' => 'privacy:metadata:badge:usercreated',
+            'usermodified' => 'privacy:metadata:badge:usermodified',
+            'timecreated' => 'privacy:metadata:badge:timecreated',
+            'timemodified' => 'privacy:metadata:badge:timemodified',
+        ], 'privacy:metadata:badge');
+
+        $collection->add_database_table('badge_issued', [
+            'userid' => 'privacy:metadata:issued:userid',
+            'dateissued' => 'privacy:metadata:issued:dateissued',
+            'dateexpire' => 'privacy:metadata:issued:dateexpire',
+        ], 'privacy:metadata:issued');
+
+        $collection->add_database_table('badge_criteria_met', [
+            'userid' => 'privacy:metadata:criteriamet:userid',
+            'datemet' => 'privacy:metadata:criteriamet:datemet',
+        ], 'privacy:metadata:criteriamet');
+
+        $collection->add_database_table('badge_manual_award', [
+            'recipientid' => 'privacy:metadata:manualaward:recipientid',
+            'issuerid' => 'privacy:metadata:manualaward:issuerid',
+            'issuerrole' => 'privacy:metadata:manualaward:issuerrole',
+            'datemet' => 'privacy:metadata:manualaward:datemet',
+        ], 'privacy:metadata:manualaward');
+
+        $collection->add_database_table('badge_backpack', [
+            'userid' => 'privacy:metadata:backpack:userid',
+            'email' => 'privacy:metadata:backpack:email',
+            'backpackurl' => 'privacy:metadata:backpack:backpackurl',
+            'backpackuid' => 'privacy:metadata:backpack:backpackuid',
+            // The columns autosync and password are not used.
+        ], 'privacy:metadata:backpack');
+
+        $collection->add_external_location_link('backpacks', [
+            'name' => 'privacy:metadata:external:backpacks:badge',
+            'description' => 'privacy:metadata:external:backpacks:description',
+            'image' => 'privacy:metadata:external:backpacks:image',
+            'url' => 'privacy:metadata:external:backpacks:url',
+            'issuer' => 'privacy:metadata:external:backpacks:issuer',
+        ], 'privacy:metadata:external:backpacks');
+
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param int $userid The user to search.
+     * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
+        $contextlist = new \core_privacy\local\request\contextlist();
+
+        // Find the modifications we made on badges (course & system).
+        $sql = "
+            SELECT ctx.id
+              FROM {badge} b
+              JOIN {context} ctx
+                ON (b.type = :typecourse AND b.courseid = ctx.instanceid AND ctx.contextlevel = :courselevel)
+                OR (b.type = :typesite AND ctx.id = :syscontextid)
+             WHERE b.usermodified = :userid1
+                OR b.usercreated = :userid2";
+        $params = [
+            'courselevel' => CONTEXT_COURSE,
+            'syscontextid' => SYSCONTEXTID,
+            'typecourse' => BADGE_TYPE_COURSE,
+            'typesite' => BADGE_TYPE_SITE,
+            'userid1' => $userid,
+            'userid2' => $userid,
+        ];
+        $contextlist->add_from_sql($sql, $params);
+
+        // Find where we've manually awarded a badge (recipient user context).
+        $sql = "
+            SELECT ctx.id
+              FROM {badge_manual_award} bma
+              JOIN {context} ctx
+                ON ctx.instanceid = bma.recipientid
+               AND ctx.contextlevel = :userlevel
+             WHERE bma.issuerid = :userid";
+        $params = [
+            'userlevel' => CONTEXT_USER,
+            'userid' => $userid,
+        ];
+        $contextlist->add_from_sql($sql, $params);
+
+        // Now find where there is real user data (user context).
+        $sql = "
+            SELECT ctx.id
+              FROM {context} ctx
+         LEFT JOIN {badge_manual_award} bma
+                ON bma.recipientid = ctx.instanceid
+         LEFT JOIN {badge_issued} bi
+                ON bi.userid = ctx.instanceid
+         LEFT JOIN {badge_criteria_met} bcm
+                ON bcm.userid = ctx.instanceid
+         LEFT JOIN {badge_backpack} bb
+                ON bb.userid = ctx.instanceid
+             WHERE ctx.contextlevel = :userlevel
+               AND ctx.instanceid = :userid
+               AND (bma.id IS NOT NULL
+                OR bi.id IS NOT NULL
+                OR bcm.id IS NOT NULL
+                OR bb.id IS NOT NULL)";
+        $params = [
+            'userlevel' => CONTEXT_USER,
+            'userid' => $userid,
+        ];
+        $contextlist->add_from_sql($sql, $params);
+
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        global $DB;
+
+        $userid = $contextlist->get_user()->id;
+        $contexts = array_reduce($contextlist->get_contexts(), function($carry, $context) {
+            $level = $context->contextlevel;
+            if ($level == CONTEXT_USER || $level == CONTEXT_COURSE) {
+                $carry[$level][] = $context->instanceid;
+            } else if ($level == CONTEXT_SYSTEM) {
+                $carry[$level] = SYSCONTEXTID;
+            }
+            return $carry;
+        }, [
+            CONTEXT_COURSE => [],
+            CONTEXT_USER => [],
+            CONTEXT_SYSTEM => null,
+        ]);
+
+        $path = [get_string('badges', 'core_badges')];
+        $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
+
+        // Export the badges we've created or modified.
+        if (!empty($contexts[CONTEXT_SYSTEM]) || !empty($contexts[CONTEXT_COURSE])) {
+            $sqls = [];
+            $params = [];
+
+            if (!empty($contexts[CONTEXT_SYSTEM])) {
+                $sqls[] = "b.type = :typesite";
+                $params['typesite'] = BADGE_TYPE_SITE;
+            }
+
+            if (!empty($contexts[CONTEXT_COURSE])) {
+                list($insql, $inparams) = $DB->get_in_or_equal($contexts[CONTEXT_COURSE], SQL_PARAMS_NAMED);
+                $sqls[] = "(b.type = :typecourse AND b.courseid $insql)";
+                $params = array_merge($params, ['typecourse' => BADGE_TYPE_COURSE], $inparams);
+            }
+
+            $sqlwhere = '(' . implode(' OR ', $sqls) . ')';
+            $sql = "
+                SELECT b.*, COALESCE(b.courseid, 0) AS normalisedcourseid
+                  FROM {badge} b
+                 WHERE (b.usermodified = :userid1 OR b.usercreated = :userid2)
+                   AND $sqlwhere
+              ORDER BY b.courseid, b.id";
+            $params = array_merge($params, ['userid1' => $userid, 'userid2' => $userid]);
+            $recordset = $DB->get_recordset_sql($sql, $params);
+            static::recordset_loop_and_export($recordset, 'normalisedcourseid', [], function($carry, $record) use ($userid) {
+                $carry[] = [
+                    'name' => $record->name,
+                    'created_on' => transform::datetime($record->timecreated),
+                    'created_by_you' => transform::yesno($record->usercreated == $userid),
+                    'modified_on' => transform::datetime($record->timemodified),
+                    'modified_by_you' => transform::yesno($record->usermodified == $userid),
+                ];
+                return $carry;
+            }, function($courseid, $data) use ($path) {
+                $context = $courseid ? context_course::instance($courseid) : context_system::instance();
+                writer::with_context($context)->export_data($path, (object) ['badges' => $data]);
+            });
+        }
+
+        // Export the badges we've manually awarded.
+        if (!empty($contexts[CONTEXT_USER])) {
+            list($insql, $inparams) = $DB->get_in_or_equal($contexts[CONTEXT_USER], SQL_PARAMS_NAMED);
+            $sql = "
+                SELECT bma.id, bma.recipientid, bma.datemet, b.name, b.courseid,
+                       r.id AS roleid,
+                       r.name AS rolename,
+                       r.shortname AS roleshortname,
+                       r.archetype AS rolearchetype,
+                       $ctxfields
+                  FROM {badge_manual_award} bma
+                  JOIN {badge} b
+                    ON b.id = bma.badgeid
+                  JOIN {role} r
+                    ON r.id = bma.issuerrole
+                  JOIN {context} ctx
+                    ON (COALESCE(b.courseid, 0) > 0 AND ctx.instanceid = b.courseid AND ctx.contextlevel = :courselevel)
+                    OR (COALESCE(b.courseid, 0) = 0 AND ctx.id = :syscontextid)
+                 WHERE bma.recipientid $insql
+                   AND bma.issuerid = :userid
+              ORDER BY bma.recipientid, bma.id";
+            $params = array_merge($inparams, [
+                'courselevel' => CONTEXT_COURSE,
+                'syscontextid' => SYSCONTEXTID,
+                'userid' => $userid
+            ]);
+            $recordset = $DB->get_recordset_sql($sql, $params);
+            static::recordset_loop_and_export($recordset, 'recipientid', [], function($carry, $record) use ($userid) {
+
+                // The only reason we fetch the context and role is to format the name of the role, which could be
+                // different to the standard name if the badge was created in a course.
+                context_helper::preload_from_record($record);
+                $context = $record->courseid ? context_course::instance($record->courseid) : context_system::instance();
+                $role = (object) [
+                    'id' => $record->roleid,
+                    'name' => $record->rolename,
+                    'shortname' => $record->roleshortname,
+                    'archetype' => $record->rolearchetype,
+                    // Mock those two fields as they do not matter.
+                    'sortorder' => 0,
+                    'description' => ''
+                ];
+
+                $carry[] = [
+                    'name' => $record->name,
+                    'issued_by_you' => transform::yesno(true),
+                    'issued_on' => transform::datetime($record->datemet),
+                    'issuer_role' => role_get_name($role, $context),
+                ];
+                return $carry;
+            }, function($userid, $data) use ($path) {
+                $context = context_user::instance($userid);
+                writer::with_context($context)->export_related_data($path, 'manual_awards', (object) ['badges' => $data]);
+            });
+        }
+
+        // Export our data.
+        if (in_array($userid, $contexts[CONTEXT_USER])) {
+
+            // Export the badges.
+            $uniqueid = $DB->sql_concat_join("'-'", ['b.id', 'COALESCE(bc.id, 0)', 'COALESCE(bi.id, 0)',
+                'COALESCE(bma.id, 0)', 'COALESCE(bcm.id, 0)']);
+            $sql = "
+                SELECT $uniqueid AS uniqueid, b.id,
+                       bi.id AS biid, bi.dateissued, bi.dateexpire, bi.uniquehash,
+                       bma.id AS bmaid, bma.datemet, bma.issuerid,
+                       bcm.id AS bcmid,
+                       c.fullname AS coursename,
+                       $ctxfields
+                  FROM {badge} b
+             LEFT JOIN {badge_issued} bi
+                    ON bi.badgeid = b.id
+                   AND bi.userid = :userid1
+             LEFT JOIN {badge_manual_award} bma
+                    ON bma.badgeid = b.id
+                   AND bma.recipientid = :userid2
+             LEFT JOIN {badge_criteria} bc
+                    ON bc.badgeid = b.id
+             LEFT JOIN {badge_criteria_met} bcm
+                    ON bcm.critid = bc.id
+                   AND bcm.userid = :userid3
+             LEFT JOIN {course} c
+                    ON c.id = b.courseid
+                   AND b.type = :typecourse
+             LEFT JOIN {context} ctx
+                    ON ctx.instanceid = c.id
+                   AND ctx.contextlevel = :courselevel
+                 WHERE bi.id IS NOT NULL
+                    OR bma.id IS NOT NULL
+                    OR bcm.id IS NOT NULL
+              ORDER BY b.id";
+            $params = [
+                'userid1' => $userid,
+                'userid2' => $userid,
+                'userid3' => $userid,
+                'courselevel' => CONTEXT_COURSE,
+                'typecourse' => BADGE_TYPE_COURSE,
+            ];
+            $recordset = $DB->get_recordset_sql($sql, $params);
+            static::recordset_loop_and_export($recordset, 'id', null, function($carry, $record) use ($userid) {
+                $badge = new badge($record->id);
+
+                // Export details of the badge.
+                if ($carry === null) {
+                    $carry = [
+                        'name' => $badge->name,
+                        'issued' => null,
+                        'manual_award' => null,
+                        'criteria_met' => []
+                    ];
+
+                    if ($badge->type == BADGE_TYPE_COURSE) {
+                        context_helper::preload_from_record($record);
+                        $carry['course'] = format_string($record->coursename, true, ['context' => $badge->get_context()]);
+                    }
+
+                    if (!empty($record->biid)) {
+                        $carry['issued'] = [
+                            'issued_on' => transform::datetime($record->dateissued),
+                            'expires_on' => $record->dateexpire ? transform::datetime($record->dateexpire) : null,
+                            'unique_hash' => $record->uniquehash,
+                        ];
+                    }
+
+                    if (!empty($record->bmaid)) {
+                        $carry['manual_award'] = [
+                            'awarded_on' => transform::datetime($record->datemet),
+                            'issuer' => transform::user($record->issuerid)
+                        ];
+                    }
+                }
+
+                // Export the details of the criteria met.
+                // We only do that once, when we find that a least one criteria was met.
+                // This is heavily based on the logic present in core_badges_renderer::render_issued_badge.
+                if (!empty($record->bcmid) && empty($carry['criteria_met'])) {
+
+                    $agg = $badge->get_aggregation_methods();
+                    $evidenceids = array_map(function($record) {
+                        return $record->critid;
+                    }, $badge->get_criteria_completions($userid));
+
+                    $criteria = $badge->criteria;
+                    unset($criteria[BADGE_CRITERIA_TYPE_OVERALL]);
+
+                    $items = [];
+                    foreach ($criteria as $type => $c) {
+                        if (in_array($c->id, $evidenceids)) {
+                            $details = $c->get_details(true);
+                            if (count($c->params) == 1) {
+                                $items[] = get_string('criteria_descr_single_' . $type , 'core_badges') . ' ' . $details;
+                            } else {
+                                $items[] = get_string('criteria_descr_' . $type , 'core_badges',
+                                    core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . ' ' . $details;
+                            }
+                        }
+                    }
+                    $carry['criteria_met'] = $items;
+                }
+                return $carry;
+            }, function($badgeid, $data) use ($path, $userid) {
+                $path = array_merge($path, ["{$data['name']} ({$badgeid})"]);
+                $writer = writer::with_context(context_user::instance($userid));
+                $writer->export_data($path, (object) $data);
+                $writer->export_area_files($path, 'badges', 'userbadge', $badgeid);
+            });
+
+            // Export the backpacks.
+            $data = [];
+            $recordset = $DB->get_recordset_select('badge_backpack', 'userid = :userid', ['userid' => $userid]);
+            foreach ($recordset as $record) {
+                $data[] = [
+                    'email' => $record->email,
+                    'url' => $record->backpackurl,
+                    'uid' => $record->backpackuid
+                ];
+            }
+            $recordset->close();
+            if (!empty($data)) {
+                writer::with_context(context_user::instance($userid))->export_related_data($path, 'backpacks',
+                    (object) ['backpacks' => $data]);
+            }
+        }
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        // We cannot delete the course or system data as it is needed by the system.
+        if ($context->contextlevel != CONTEXT_USER) {
+            return;
+        }
+
+        // Delete all the user data.
+        static::delete_user_data($context->instanceid);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        $userid = $contextlist->get_user()->id;
+        foreach ($contextlist->get_contexts() as $context) {
+            if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $userid) {
+                // We can only delete our own data in the user context, nothing in course or system.
+                static::delete_user_data($userid);
+                break;
+            }
+        }
+    }
+
+    /**
+     * Delete all the data for a user.
+     *
+     * @param int $userid The user ID.
+     * @return void
+     */
+    protected static function delete_user_data($userid) {
+        global $DB;
+
+        // Delete the stuff.
+        $DB->delete_records('badge_manual_award', ['recipientid' => $userid]);
+        $DB->delete_records('badge_criteria_met', ['userid' => $userid]);
+        $DB->delete_records('badge_issued', ['userid' => $userid]);
+
+        // Delete the backpacks and related stuff.
+        $backpackids = $DB->get_fieldset_select('badge_backpack', 'id', 'userid = :userid', ['userid' => $userid]);
+        if (!empty($backpackids)) {
+            list($insql, $inparams) = $DB->get_in_or_equal($backpackids, SQL_PARAMS_NAMED);
+            $DB->delete_records_select('badge_external', "backpackid $insql", $inparams);
+            $DB->delete_records_select('badge_backpack', "id $insql", $inparams);
+        }
+    }
+
+    /**
+     * Loop and export from a recordset.
+     *
+     * @param \moodle_recordset $recordset The recordset.
+     * @param string $splitkey The record key to determine when to export.
+     * @param mixed $initial The initial data to reduce from.
+     * @param callable $reducer The function to return the dataset, receives current dataset, and the current record.
+     * @param callable $export The function to export the dataset, receives the last value from $splitkey and the dataset.
+     * @return void
+     */
+    protected static function recordset_loop_and_export(\moodle_recordset $recordset, $splitkey, $initial,
+            callable $reducer, callable $export) {
+
+        $data = $initial;
+        $lastid = null;
+
+        foreach ($recordset as $record) {
+            if ($lastid !== null && $record->{$splitkey} != $lastid) {
+                $export($lastid, $data);
+                $data = $initial;
+            }
+            $data = $reducer($data, $record);
+            $lastid = $record->{$splitkey};
+        }
+        $recordset->close();
+
+        if ($lastid !== null) {
+            $export($lastid, $data);
+        }
+    }
+}
diff --git a/badges/tests/privacy_test.php b/badges/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..bf3b084
--- /dev/null
@@ -0,0 +1,557 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    core_badges
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use core_badges\privacy\provider;
+
+require_once($CFG->libdir . '/badgeslib.php');
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    core_badges
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class core_badges_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+    }
+
+    public function test_get_contexts_for_userid_for_badge_editing() {
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u3 = $dg->create_user();
+        $u4 = $dg->create_user();
+        $u5 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $c2 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+
+        // Assert that we find contexts where we created/modified a badge.
+        $this->create_badge(['usercreated' => $u1->id, 'usermodified' => $u5->id]);
+        $this->create_badge(['usercreated' => $u2->id, 'type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id]);
+        $this->create_badge(['usermodified' => $u3->id]);
+        $this->create_badge(['usermodified' => $u4->id, 'type' => BADGE_TYPE_COURSE, 'courseid' => $c2->id,
+            'usercreated' => $u5->id]);
+
+        $contexts = provider::get_contexts_for_userid($u1->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($sysctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u2->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($c1ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u3->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($sysctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u4->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($c2ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u5->id)->get_contextids();
+        $this->assertCount(2, $contexts);
+        $this->assertTrue(in_array($sysctx->id, $contexts));
+        $this->assertTrue(in_array($c2ctx->id, $contexts));
+    }
+
+    public function test_get_contexts_for_userid_for_manual_award() {
+        global $DB;
+
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u3 = $dg->create_user();
+        $u4 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+        $u3ctx = context_user::instance($u3->id);
+        $u4ctx = context_user::instance($u4->id);
+        $b1 = $this->create_badge();
+        $b2 = $this->create_badge(['type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id]);
+
+        $this->create_manual_award(['recipientid' => $u4->id, 'issuerid' => $u1->id, 'badgeid' => $b1->id]);
+        $this->create_manual_award(['recipientid' => $u3->id, 'issuerid' => $u2->id, 'badgeid' => $b1->id]);
+        $this->create_manual_award(['recipientid' => $u3->id, 'issuerid' => $u2->id, 'badgeid' => $b2->id]);
+
+        $contexts = provider::get_contexts_for_userid($u1->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u4ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u2->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u3ctx->id, $contexts[0]);
+    }
+
+    public function test_get_contexts_for_userid_for_my_stuff() {
+        global $DB;
+
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u3 = $dg->create_user();
+        $u4 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+        $u3ctx = context_user::instance($u3->id);
+        $u4ctx = context_user::instance($u4->id);
+        $b1 = $this->create_badge();
+        $b2 = $this->create_badge(['type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id]);
+
+        $this->create_backpack(['userid' => $u1->id]);
+        $this->create_manual_award(['recipientid' => $u2->id, 'badgeid' => $b1->id]);
+        $this->create_issued(['badgeid' => $b2->id, 'userid' => $u3->id]);
+
+        $crit = $this->create_criteria_manual($b1->id);
+        $crit->mark_complete($u4->id);
+
+        $contexts = provider::get_contexts_for_userid($u1->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u1ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u2->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u2ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u3->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u3ctx->id, $contexts[0]);
+
+        $contexts = provider::get_contexts_for_userid($u4->id)->get_contextids();
+        $this->assertCount(1, $contexts);
+        $this->assertEquals($u4ctx->id, $contexts[0]);
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $b1 = $this->create_badge(['usercreated' => $u1->id, 'usermodified' => $u2->id]);
+        $b2 = $this->create_badge(['usercreated' => $u2->id, 'usermodified' => $u1->id,
+            'type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id]);
+
+        $this->create_backpack(['userid' => $u1->id]);
+        $this->create_backpack(['userid' => $u2->id]);
+        $this->create_manual_award(['recipientid' => $u1->id, 'badgeid' => $b1->id]);
+        $this->create_manual_award(['recipientid' => $u2->id, 'badgeid' => $b1->id, 'issuerid' => $u1->id]);
+        $this->create_issued(['badgeid' => $b2->id, 'userid' => $u1->id]);
+        $this->create_issued(['badgeid' => $b2->id, 'userid' => $u2->id]);
+
+        $crit = $this->create_criteria_manual($b1->id);
+        $crit->mark_complete($u2->id);
+        $crit = $this->create_criteria_manual($b2->id);
+        $crit->mark_complete($u1->id);
+
+        $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u2->id]));
+
+        provider::delete_data_for_user(new approved_contextlist($u1, 'core_badges', [$sysctx->id, $c1ctx->id,
+            $u1ctx->id, $u2ctx->id]));
+
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_backpack', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_manual_award', ['recipientid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_issued', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_criteria_met', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u2->id]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $b1 = $this->create_badge(['usercreated' => $u1->id, 'usermodified' => $u2->id]);
+        $b2 = $this->create_badge(['usercreated' => $u2->id, 'usermodified' => $u1->id,
+            'type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id]);
+
+        $this->create_backpack(['userid' => $u1->id]);
+        $this->create_backpack(['userid' => $u2->id]);
+        $this->create_manual_award(['recipientid' => $u1->id, 'badgeid' => $b1->id]);
+        $this->create_manual_award(['recipientid' => $u2->id, 'badgeid' => $b1->id, 'issuerid' => $u1->id]);
+        $this->create_issued(['badgeid' => $b2->id, 'userid' => $u1->id]);
+        $this->create_issued(['badgeid' => $b2->id, 'userid' => $u2->id]);
+
+        $crit = $this->create_criteria_manual($b1->id);
+        $crit->mark_complete($u2->id);
+        $crit = $this->create_criteria_manual($b2->id);
+        $crit->mark_complete($u1->id);
+
+        $assertnochange = function() use ($DB, $u1, $u2) {
+            $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u2->id]));
+            $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u2->id]));
+            $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u2->id]));
+            $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u2->id]));
+            $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u2->id]));
+            $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u1->id]));
+            $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u2->id]));
+        };
+        $assertnochange();
+
+        provider::delete_data_for_all_users_in_context($sysctx);
+        $assertnochange();
+
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $assertnochange();
+
+        provider::delete_data_for_all_users_in_context($u1ctx);
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usercreated' => $u2->id]));
+        $this->assertTrue($DB->record_exists('badge', ['usermodified' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_backpack', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_backpack', ['userid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_manual_award', ['recipientid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_manual_award', ['recipientid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_issued', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_issued', ['userid' => $u2->id]));
+        $this->assertFalse($DB->record_exists('badge_criteria_met', ['userid' => $u1->id]));
+        $this->assertTrue($DB->record_exists('badge_criteria_met', ['userid' => $u2->id]));
+    }
+
+    public function test_export_data_for_user() {
+        global $DB;
+
+        $yes = transform::yesno(true);
+        $no = transform::yesno(false);
+
+        $dg = $this->getDataGenerator();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $u3 = $dg->create_user();
+        $c1 = $dg->create_course();
+        $sysctx = context_system::instance();
+        $c1ctx = context_course::instance($c1->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $b1 = $this->create_badge(['usercreated' => $u3->id]);
+        $b2 = $this->create_badge(['type' => BADGE_TYPE_COURSE, 'courseid' => $c1->id, 'usermodified' => $u3->id]);
+        $b3 = $this->create_badge();
+        $b3crit = $this->create_criteria_manual($b3->id);
+        $b4 = $this->create_badge();
+
+        // Create things for user 2, to check it's not exported it.
+        $this->create_issued(['badgeid' => $b4->id, 'userid' => $u2->id]);
+        $this->create_backpack(['userid' => $u2->id, 'email' => $u2->email]);
+        $this->create_manual_award(['badgeid' => $b1->id, 'recipientid' => $u2->id, 'issuerid' => $u3->id]);
+
+        // Create a set of stuff for u1.
+        $this->create_issued(['badgeid' => $b1->id, 'userid' => $u1->id, 'uniquehash' => 'yoohoo']);
+        $this->create_manual_award(['badgeid' => $b2->id, 'recipientid' => $u1->id, 'issuerid' => $u3->id]);
+        $b3crit->mark_complete($u1->id);
+        $this->create_backpack(['userid' => $u1->id, 'email' => $u1->email]);
+
+        // Check u1.
+        writer::reset();
+        provider::export_user_data(new approved_contextlist($u1, 'core_badges', [$u1ctx->id, $u2ctx->id,
+            $sysctx->id, $c1ctx->id]));
+        $this->assertFalse(writer::with_context($u2ctx)->has_any_data());
+        $this->assertFalse(writer::with_context($sysctx)->has_any_data());
+        $this->assertFalse(writer::with_context($c1ctx)->has_any_data());
+
+        $path = [get_string('badges', 'core_badges'), "{$b1->name} ({$b1->id})"];
+        $data = writer::with_context($u1ctx)->get_data($path);
+        $this->assertEquals($b1->name, $data->name);
+        $this->assertNotEmpty($data->issued);
+        $this->assertEmpty($data->manual_award);
+        $this->assertEmpty($data->criteria_met);
+        $this->assertFalse(isset($data->course));
+        $this->assertEquals('yoohoo', $data->issued['unique_hash']);
+        $this->assertNull($data->issued['expires_on']);
+
+        $path = [get_string('badges', 'core_badges'), "{$b2->name} ({$b2->id})"];
+        $data = writer::with_context($u1ctx)->get_data($path);
+        $this->assertEquals($b2->name, $data->name);
+        $this->assertEmpty($data->issued);
+        $this->assertNotEmpty($data->manual_award);
+        $this->assertEmpty($data->criteria_met);
+        $this->assertEquals($c1->fullname, $data->course);
+        $this->assertEquals($u3->id, $data->manual_award['issuer']);
+
+        $path = [get_string('badges', 'core_badges'), "{$b3->name} ({$b3->id})"];
+        $data = writer::with_context($u1ctx)->get_data($path);
+        $this->assertEquals($b3->name, $data->name);
+        $this->assertEmpty($data->issued);
+        $this->assertEmpty($data->manual_award);
+        $this->assertNotEmpty($data->criteria_met);
+        $this->assertNotFalse(strpos($data->criteria_met[0], get_string('criteria_descr_2', 'core_badges', 'ALL')));
+
+        $path = [get_string('badges', 'core_badges')];
+        $data = writer::with_context($u1ctx)->get_related_data($path, 'backpacks');
+        $this->assertCount(1, $data->backpacks);
+        $this->assertEquals($u1->email, $data->backpacks[0]['email']);
+
+        // Confirm we do not have u2.
+        $path = [get_string('badges', 'core_badges'), "{$b4->name} ({$b4->id})"];
+        $data = writer::with_context($u1ctx)->get_data($path);
+        $this->assertEmpty($data);
+        $data = writer::with_context($u2ctx)->get_data($path);
+        $this->assertEmpty($data);
+
+        // Export for u3.
+        writer::reset();
+        $path = [get_string('badges', 'core_badges')];
+        provider::export_user_data(new approved_contextlist($u3, 'core_badges', [$u1ctx->id, $u2ctx->id,
+            $sysctx->id, $c1ctx->id]));
+
+        $data = writer::with_context($u2ctx)->get_related_data($path, 'manual_awards');
+        $this->assertCount(1, $data->badges);
+        $this->assertEquals($b1->name, $data->badges[0]['name']);
+        $this->assertEquals($yes, $data->badges[0]['issued_by_you']);
+        $this->assertEquals('Manager', $data->badges[0]['issuer_role']);
+
+        $data = writer::with_context($sysctx)->get_data($path);
+        $this->assertCount(1, $data->badges);
+        $this->assertEquals($b1->name, $data->badges[0]['name']);
+        $this->assertEquals($yes, $data->badges[0]['created_by_you']);
+        $this->assertEquals($no, $data->badges[0]['modified_by_you']);
+
+        $data = writer::with_context($c1ctx)->get_data($path);
+        $this->assertCount(1, $data->badges);
+        $this->assertEquals($b2->name, $data->badges[0]['name']);
+        $this->assertEquals($no, $data->badges[0]['created_by_you']);
+        $this->assertEquals($yes, $data->badges[0]['modified_by_you']);
+
+        $data = writer::with_context($u1ctx)->get_related_data($path, 'manual_awards');
+        $this->assertCount(1, $data->badges);
+        $this->assertEquals($b3->name, $data->badges[0]['name']);
+        $this->assertEquals($yes, $data->badges[0]['issued_by_you']);
+        $this->assertEquals('Manager', $data->badges[0]['issuer_role']);
+    }
+
+    /**
+     * Create a badge.
+     *
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_badge(array $params = []) {
+        global $DB, $USER;
+        $record = (object) array_merge([
+            'name' => "Test badge with 'apostrophe' and other friends (<>&@#)",
+            'description' => "Testing badges",
+            'timecreated' => time(),
+            'timemodified' => time(),
+            'usercreated' => $USER->id,
+            'usermodified' => $USER->id,
+            'issuername' => "Test issuer",
+            'issuerurl' => "http://issuer-url.domain.co.nz",
+            'issuercontact' => "issuer@example.com",
+            'expiredate' => null,
+            'expireperiod' => null,
+            'type' => BADGE_TYPE_SITE,
+            'courseid' => null,
+            'messagesubject' => "Test message subject",
+            'message' => "Test message body",
+            'attachment' => 1,
+            'notification' => 0,
+            'status' => BADGE_STATUS_ACTIVE,
+        ], $params);
+        $record->id = $DB->insert_record('badge', $record);
+
+        return $record;
+    }
+
+    /**
+     * Create a backpack.
+     *
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_backpack(array $params = []) {
+        global $DB;
+        $record = (object) array_merge([
+            'userid' => null,
+            'email' => 'test@example.com',
+            'backpackurl' => "http://here.there.com",
+            'backpackuid' => "12345",
+            'autosync' => 0,
+            'password' => '',
+        ], $params);
+        $record->id = $DB->insert_record('badge_backpack', $record);
+        return $record;
+    }
+
+    /**
+     * Create a criteria of type badge.
+     *
+     * @param int $badgeid The badge ID.
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_criteria_badge($badgeid, array $params = []) {
+        $badge = new badge($badgeid);
+        if (empty($badge->criteria)) {
+            $overall = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id]);
+            $overall->save(['agg' => BADGE_CRITERIA_AGGREGATION_ALL]);
+        }
+
+        $criteria = award_criteria::build([
+            'badgeid' => $badge->id,
+            'criteriatype' => BADGE_CRITERIA_TYPE_BADGE,
+        ]);
+
+        if (isset($params['badgeid'])) {
+            $params['badge_' . $params['badgeid']] = $params['badgeid'];
+            unset($params['badgeid']);
+        }
+
+        $criteria->save($params);
+        $badge = new badge($badgeid);
+        return $badge->criteria[BADGE_CRITERIA_TYPE_BADGE];
+    }
+
+    /**
+     * Create a criteria of type manual.
+     *
+     * @param int $badgeid The badge ID.
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_criteria_manual($badgeid, array $params = []) {
+        global $DB;
+
+        $badge = new badge($badgeid);
+        if (empty($badge->criteria)) {
+            $overall = award_criteria::build(['criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id]);
+            $overall->save(['agg' => BADGE_CRITERIA_AGGREGATION_ALL]);
+        }
+
+        $criteria = award_criteria::build([
+            'badgeid' => $badge->id,
+            'criteriatype' => BADGE_CRITERIA_TYPE_MANUAL,
+        ]);
+
+        $managerroleid = $DB->get_field_select('role', 'id', 'shortname = ?', ['manager'], IGNORE_MULTIPLE);
+        if (empty($params)) {
+            $params = [
+                'role_' . $managerroleid = $managerroleid
+            ];
+        }
+
+        $criteria->save($params);
+        $badge = new badge($badgeid);
+        return $badge->criteria[BADGE_CRITERIA_TYPE_MANUAL];
+    }
+
+    /**
+     * Create a badge issued.
+     *
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_issued(array $params = []) {
+        global $DB, $USER;
+        $record = (object) array_merge([
+            'badgeid' => null,
+            'userid' => null,
+            'uniquehash' => random_string(40),
+            'dateissued' => time(),
+            'dateexpire' => null,
+            'visible' => 1,
+            'issuernotified' => null,
+        ], $params);
+        $record->id = $DB->insert_record('badge_issued', $record);
+        return $record;
+    }
+
+    /**
+     * Create a manual award.
+     *
+     * @param array $params Parameters.
+     * @return object
+     */
+    protected function create_manual_award(array $params = []) {
+        global $DB, $USER;
+        $record = (object) array_merge([
+            'badgeid' => null,
+            'recipientid' => null,
+            'issuerid' => $USER->id,
+            'issuerrole' => $DB->get_field_select('role', 'id', 'shortname = ?', ['manager'], IGNORE_MULTIPLE),
+            'datemet' => time()
+        ], $params);
+        $record->id = $DB->insert_record('badge_manual_award', $record);
+        return $record;
+    }
+
+}
diff --git a/blocks/classes/privacy/provider.php b/blocks/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..cbee644
--- /dev/null
@@ -0,0 +1,227 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider.
+ *
+ * @package    core_block
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_block\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use context;
+use context_block;
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+
+/**
+ * Data provider class.
+ *
+ * @package    core_block
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\subsystem\provider,
+    \core_privacy\local\request\user_preference_provider {
+
+    /**
+     * Returns metadata.
+     *
+     * @param collection $collection The initialised collection to add items to.
+     * @return collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_user_preference('blockIDhidden', 'privacy:metadata:userpref:hiddenblock');
+        $collection->add_user_preference('docked_block_instance_ID', 'privacy:metadata:userpref:dockedinstance');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param int $userid The user to search.
+     * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
+        global $DB;
+        $contextlist = new \core_privacy\local\request\contextlist();
+
+        // Fetch the block instance IDs.
+        $likehidden = $DB->sql_like('name', ':hidden', false, false);
+        $likedocked = $DB->sql_like('name', ':docked', false, false);
+        $sql = "userid = :userid AND ($likehidden OR $likedocked)";
+        $params = [
+            'userid' => $userid,
+            'hidden' => 'block%hidden',
+            'docked' => 'docked_block_instance_%',
+        ];
+        $prefs = $DB->get_fieldset_select('user_preferences', 'name', $sql, $params);
+
+        $instanceids = array_unique(array_map(function($prefname) {
+            if (preg_match('/^block(\d+)hidden$/', $prefname, $matches)) {
+                return $matches[1];
+            } else if (preg_match('/^docked_block_instance_(\d+)$/', $prefname, $matches)) {
+                return $matches[1];
+            }
+            return 0;
+        }, $prefs));
+
+        // Find the context of the instances.
+        if (!empty($instanceids)) {
+            list($insql, $inparams) = $DB->get_in_or_equal($instanceids, SQL_PARAMS_NAMED);
+            $sql = "
+                SELECT ctx.id
+                  FROM {context} ctx
+                 WHERE ctx.instanceid $insql
+                   AND ctx.contextlevel = :blocklevel";
+            $params = array_merge($inparams, ['blocklevel' => CONTEXT_BLOCK]);
+            $contextlist->add_from_sql($sql, $params);
+        }
+
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        global $DB;
+        $userid = $contextlist->get_user()->id;
+
+        // Extract the block instance IDs.
+        $instanceids = array_reduce($contextlist->get_contexts(), function($carry, $context) {
+            if ($context->contextlevel == CONTEXT_BLOCK) {
+                $carry[] = $context->instanceid;
+            }
+            return $carry;
+        }, []);
+        if (empty($instanceids)) {
+            return;
+        }
+
+        // Query the blocks and their preferences.
+        list($insql, $inparams) = $DB->get_in_or_equal($instanceids, SQL_PARAMS_NAMED);
+        $hiddenkey = $DB->sql_concat("'block'", 'bi.id', "'hidden'");
+        $dockedkey = $DB->sql_concat("'docked_block_instance_'", 'bi.id');
+        $sql = "
+            SELECT bi.id, h.value AS prefhidden, d.value AS prefdocked
+              FROM {block_instances} bi
+         LEFT JOIN {user_preferences} h
+                ON h.userid = :userid1
+               AND h.name = $hiddenkey
+         LEFT JOIN {user_preferences} d
+                ON d.userid = :userid2
+               AND d.name = $dockedkey
+             WHERE bi.id $insql
+               AND (h.id IS NOT NULL
+                OR d.id IS NOT NULL)";
+        $params = array_merge($inparams, [
+            'userid1' => $userid,
+            'userid2' => $userid,
+        ]);
+
+        // Export all the things.
+        $dockedstr = get_string('privacy:request:blockisdocked', 'core_block');
+        $hiddenstr = get_string('privacy:request:blockishidden', 'core_block');
+        $recordset = $DB->get_recordset_sql($sql, $params);
+        foreach ($recordset as $record) {
+            $context = context_block::instance($record->id);
+            if ($record->prefdocked !== null) {
+                writer::with_context($context)->export_user_preference(
+                    'core_block',
+                    'block_is_docked',
+                    transform::yesno($record->prefdocked),
+                    $dockedstr
+                );
+            }
+            if ($record->prefhidden !== null) {
+                writer::with_context($context)->export_user_preference(
+                    'core_block',
+                    'block_is_hidden',
+                    transform::yesno($record->prefhidden),
+                    $hiddenstr
+                );
+            }
+        }
+        $recordset->close();
+    }
+
+    /**
+     * Export all user preferences for the plugin.
+     *
+     * @param int $userid The userid of the user whose data is to be exported.
+     */
+    public static function export_user_preferences(int $userid) {
+      // Our preferences aren't site-wide so they are exported in export_user_data.
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param context $context The specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(context $context) {
+        global $DB;
+        if ($context->contextlevel != CONTEXT_BLOCK) {
+            return;
+        }
+
+        // Delete the user preferences.
+        $instanceid = $context->instanceid;
+        $DB->delete_records_list('user_preferences', 'name', [
+            "block{$instanceid}hidden",
+            "docked_block_instance_{$instanceid}"
+        ]);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        global $DB;
+        $userid = $contextlist->get_user()->id;
+        $prefnames = array_reduce($contextlist->get_contexts(), function($carry, $context) {
+            if ($context->contextlevel == CONTEXT_BLOCK) {
+                $carry[] = "block{$context->instanceid}hidden";
+                $carry[] = "docked_block_instance_{$context->instanceid}";
+            }
+            return $carry;
+        }, []);
+
+        if (empty($prefnames)) {
+            return;
+        }
+
+        list($insql, $inparams) = $DB->get_in_or_equal($prefnames, SQL_PARAMS_NAMED);
+        $sql = "userid = :userid AND name $insql";
+        $params = array_merge($inparams, ['userid' => $userid]);
+        $DB->delete_records_select('user_preferences', $sql, $params);
+    }
+
+}
diff --git a/blocks/comments/classes/privacy/provider.php b/blocks/comments/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..d758293
--- /dev/null
@@ -0,0 +1,115 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for block_comments.
+ *
+ * @package    block_comments
+ * @category   privacy
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace block_comments\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\contextlist;
+
+/**
+ * Privacy Subsystem implementation for block_comments.
+ *
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+        // The block_comments block stores user provided data.
+        \core_privacy\local\metadata\provider,
+
+        // The block_comments block provides data directly to core.
+        \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param collection $collection
+     * @return collection
+     */
+    public static function get_metadata(collection $collection) : collection {
+        return $collection->add_subsystem_link('core_comment', [], 'privacy:metadata:core_comment');
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param int $userid
+     * @return contextlist
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        $contextlist = new contextlist();
+
+        $sql = "SELECT contextid
+                  FROM {comments}
+                 WHERE component = :component
+                   AND userid = :userid";
+        $params = [
+            'component' => 'block_comments',
+            'userid' => $userid
+        ];
+
+        $contextlist->add_from_sql($sql, $params);
+
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        $contexts = $contextlist->get_contexts();
+        foreach ($contexts as $context) {
+            \core_comment\privacy\provider::export_comments(
+                    $context,
+                    'block_comments',
+                    'page_comments',
+                    0,
+                    []
+            );
+        }
+    }
+
+    /**
+     * Delete all data for all users in the specified context.
+     *
+     * @param \context $context
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+        \core_comment\privacy\provider::delete_comments_for_all_users($context, 'block_comments');
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        \core_comment\privacy\provider::delete_comments_for_user($contextlist, 'block_comments');
+    }
+}
index f64e5f6..116f10e 100644 (file)
@@ -26,3 +26,4 @@
 $string['comments:myaddinstance'] = 'Add a new comments block to Dashboard';
 $string['comments:addinstance'] = 'Add a new comments block';
 $string['pluginname'] = 'Comments';
+$string['privacy:metadata:core_comment'] = 'A record of comments added.';
diff --git a/blocks/comments/tests/privacy_provider_test.php b/blocks/comments/tests/privacy_provider_test.php
new file mode 100644 (file)
index 0000000..9cc028b
--- /dev/null
@@ -0,0 +1,468 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy provider tests.
+ *
+ * @package    block_comments
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use core_privacy\local\metadata\collection;
+use block_comments\privacy\provider;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Class block_comments_privacy_provider_testcase.
+ *
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class block_comments_privacy_provider_testcase extends \core_privacy\tests\provider_testcase {
+
+    /** @var stdClass A student who is only enrolled in course1. */
+    protected $student1;
+
+    /** @var stdClass A student who is only enrolled in course2. */
+    protected $student2;
+
+    /** @var stdClass A student who is enrolled in both course1 and course2. */
+    protected $student12;
+
+    /** @var stdClass A test course. */
+    protected $course1;
+
+    /** @var stdClass A test course. */
+    protected $course2;
+
+    protected function setUp() {
+        global $DB;
+
+        $this->resetAfterTest();
+        $this->setAdminUser();
+
+        // Create courses.
+        $generator = $this->getDataGenerator();
+        $this->course1 = $generator->create_course();
+        $this->course2 = $generator->create_course();
+
+        // Create and enrol students.
+        $this->student1 = $generator->create_user();
+        $this->student2 = $generator->create_user();
+        $this->student12 = $generator->create_user();
+
+        $studentrole = $DB->get_record('role', ['shortname' => 'student']);
+        $generator->enrol_user($this->student1->id,  $this->course1->id, $studentrole->id);
+        $generator->enrol_user($this->student2->id,  $this->course2->id, $studentrole->id);
+        $generator->enrol_user($this->student12->id,  $this->course1->id, $studentrole->id);
+        $generator->enrol_user($this->student12->id,  $this->course2->id, $studentrole->id);
+
+        // Comment block on course pages.
+        $block = $this->add_comments_block_in_context(context_course::instance($this->course1->id));
+        $block = $this->add_comments_block_in_context(context_course::instance($this->course2->id));
+    }
+
+    /**
+     * Posts a comment on a given context.
+     *
+     * @param string $text The comment's text.
+     * @param context $context The context on which we want to put the comment.
+     */
+    protected function add_comment($text, context $context) {
+        $args = new stdClass;
+        $args->context = $context;
+        $args->area = 'page_comments';
+        $args->itemid = 0;
+        $args->component = 'block_comments';
+        $args->linktext = get_string('showcomments');
+        $args->notoggle = true;
+        $args->autostart = true;
+        $args->displaycancel = false;
+        $comment = new comment($args);
+
+        $comment->add($text);
+    }
+
+    /**
+     * Creates a comments block on a context.
+     *
+     * @param context $context The context on which we want to put the block.
+     * @return block_base The created block instance.
+     * @throws coding_exception
+     */
+    protected function add_comments_block_in_context(context $context) {
+        global $DB;
+
+        $course = null;
+
+        $page = new \moodle_page();
+        $page->set_context($context);
+
+        switch ($context->contextlevel) {
+            case CONTEXT_SYSTEM:
+                $page->set_pagelayout('frontpage');
+                $page->set_pagetype('site-index');
+                break;
+            case CONTEXT_COURSE:
+                $page->set_pagelayout('standard');
+                $page->set_pagetype('course-view');
+                $course = $DB->get_record('course', ['id' => $context->instanceid]);
+                $page->set_course($course);
+                break;
+            case CONTEXT_MODULE:
+                $page->set_pagelayout('standard');
+                $mod = $DB->get_field_sql("SELECT m.name
+                                             FROM {modules} m
+                                             JOIN {course_modules} cm on cm.module = m.id
+                                            WHERE cm.id = ?", [$context->instanceid]);
+                $page->set_pagetype("mod-$mod-view");
+                break;
+            case CONTEXT_USER:
+                $page->set_pagelayout('mydashboard');
+                $page->set_pagetype('my-index');
+                break;
+            default:
+                throw new coding_exception('Unsupported context for test');
+        }
+
+        $page->blocks->load_blocks();
+
+        $page->blocks->add_block_at_end_of_default_region('comments');
+
+        // We need to use another page object as load_blocks() only loads the blocks once.
+        $page2 = new \moodle_page();
+        $page2->set_context($page->context);
+        $page2->set_pagelayout($page->pagelayout);
+        $page2->set_pagetype($page->pagetype);
+        if ($course) {
+            $page2->set_course($course);
+        }
+
+        $page->blocks->load_blocks();
+        $page2->blocks->load_blocks();
+        $blocks = $page2->blocks->get_blocks_for_region($page2->blocks->get_default_region());
+        $block = end($blocks);
+
+        $block = block_instance('comments', $block->instance);
+
+        return $block;
+    }
+
+    /**
+     * Test for provider::get_metadata().
+     */
+    public function test_get_metadata() {
+        $collection = new collection('block_comments');
+        $newcollection = provider::get_metadata($collection);
+        $itemcollection = $newcollection->get_collection();
+        $this->assertCount(1, $itemcollection);
+
+        $link = reset($itemcollection);
+
+        $this->assertEquals('core_comment', $link->get_name());
+        $this->assertEmpty($link->get_privacy_fields());
+        $this->assertEquals('privacy:metadata:core_comment', $link->get_summary());
+    }
+
+    /**
+     * Test for provider::get_contexts_for_userid() when user had not posted any comments..
+     */
+    public function test_get_contexts_for_userid_no_comment() {
+        $this->setUser($this->student1);
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $this->add_comment('New comment', $coursecontext1);
+
+        $this->setUser($this->student2);
+        $contextlist = provider::get_contexts_for_userid($this->student2->id);
+        $this->assertCount(0, $contextlist);
+    }
+
+    /**
+     * Test for provider::get_contexts_for_userid().
+     */
+    public function test_get_contexts_for_userid() {
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $coursecontext2 = context_course::instance($this->course2->id);
+
+        $this->setUser($this->student12);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext2);
+
+        $contextlist = provider::get_contexts_for_userid($this->student12->id);
+        $this->assertCount(2, $contextlist);
+
+        $contextids = $contextlist->get_contextids();
+        $this->assertEquals([$coursecontext1->id, $coursecontext2->id], $contextids, '', 0.0, 10, true);
+    }
+
+    /**
+     * Test for provider::export_user_data() when the user has not posted any comments.
+     */
+    public function test_export_for_context_no_comment() {
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $coursecontext2 = context_course::instance($this->course2->id);
+
+        $this->setUser($this->student1);
+        $this->add_comment('New comment', $coursecontext1);
+
+        $this->setUser($this->student2);
+
+        $this->setUser($this->student2);
+        $this->export_context_data_for_user($this->student2->id, $coursecontext2, 'block_comments');
+        $writer = \core_privacy\local\request\writer::with_context($coursecontext2);
+        $this->assertFalse($writer->has_any_data());
+
+    }
+
+    /**
+     * Test for provider::export_user_data().
+     */
+    public function test_export_for_context() {
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $coursecontext2 = context_course::instance($this->course2->id);
+
+        $this->setUser($this->student12);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext2);
+
+        // Export all of the data for the context.
+        $this->export_context_data_for_user($this->student12->id, $coursecontext1, 'block_comments');
+        $writer = \core_privacy\local\request\writer::with_context($coursecontext1);
+        $this->assertTrue($writer->has_any_data());
+    }
+
+    /**
+     * Test for provider::delete_data_for_all_users_in_context().
+     */
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $coursecontext2 = context_course::instance($this->course2->id);
+
+        $this->setUser($this->student1);
+        $this->add_comment('New comment', $coursecontext1);
+
+        $this->setUser($this->student2);
+        $this->add_comment('New comment', $coursecontext2);
+
+        $this->setUser($this->student12);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext2);
+
+        // Before deletion, we should have 3 comments in $coursecontext1 and 2 comments in $coursecontext2.
+        $this->assertEquals(
+                3,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext1->id])
+        );
+        $this->assertEquals(
+                2,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext2->id])
+        );
+
+        // Delete data based on context.
+        provider::delete_data_for_all_users_in_context($coursecontext1);
+
+        // After deletion, the comments for $coursecontext1 should have been deleted.
+        $this->assertEquals(
+                0,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext1->id])
+        );
+        $this->assertEquals(
+                2,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext2->id])
+        );
+    }
+
+    /**
+     * Test for provider::delete_data_for_all_users_in_context() when there are also comments from other plugins.
+     */
+    public function test_delete_data_for_all_users_in_context_with_comments_from_other_plugins() {
+        global $DB;
+
+        $assigngenerator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
+        $instance = $assigngenerator->create_instance(['course' => $this->course1]);
+        $cm = get_coursemodule_from_instance('assign', $instance->id);
+        $assigncontext = \context_module::instance($cm->id);
+        $assign = new \assign($assigncontext, $cm, $this->course1);
+
+        // Add a comments block in the assignment page.
+        $this->add_comments_block_in_context($assigncontext);
+
+        $submission = $assign->get_user_submission($this->student1->id, true);
+
+        $options = new stdClass();
+        $options->area = 'submission_comments';
+        $options->course = $assign->get_course();
+        $options->context = $assigncontext;
+        $options->itemid = $submission->id;
+        $options->component = 'assignsubmission_comments';
+        $options->showcount = true;
+        $options->displaycancel = true;
+
+        $comment = new comment($options);
+        $comment->set_post_permission(true);
+
+        $this->setUser($this->student1);
+        $comment->add('Comment from student 1');
+
+        $this->add_comment('New comment', $assigncontext);
+
+        $this->setUser($this->student2);
+        $this->add_comment('New comment', $assigncontext);
+
+        // Before deletion, we should have 3 comments in $assigncontext.
+        // One comment is for the assignment submission and 2 are for the comments block.
+        $this->assertEquals(
+                3,
+                $DB->count_records('comments', ['contextid' => $assigncontext->id])
+        );
+        $this->assertEquals(
+                2,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $assigncontext->id])
+        );
+
+        provider::delete_data_for_all_users_in_context($assigncontext);
+
+        // After deletion, the comments for $assigncontext in the comment block should have been deleted,
+        // but the assignment submission comment should be left.
+        $this->assertEquals(
+                1,
+                $DB->count_records('comments', ['contextid' => $assigncontext->id])
+        );
+        $this->assertEquals(
+                0,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $assigncontext->id])
+        );
+    }
+
+    /**
+     * Test for provider::delete_data_for_user().
+     */
+    public function test_delete_data_for_user() {
+        global $DB;
+
+        $coursecontext1 = context_course::instance($this->course1->id);
+        $coursecontext2 = context_course::instance($this->course2->id);
+
+        $this->setUser($this->student1);
+        $this->add_comment('New comment', $coursecontext1);
+
+        $this->setUser($this->student2);
+        $this->add_comment('New comment', $coursecontext2);
+
+        $this->setUser($this->student12);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext1);
+        $this->add_comment('New comment', $coursecontext2);
+
+        // Before deletion, we should have 3 comments in $coursecontext1 and 2 comments in $coursecontext2,
+        // and 3 comments by student12 in $coursecontext1 and $coursecontext2 combined.
+        $this->assertEquals(
+                3,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext1->id])
+        );
+        $this->assertEquals(
+                2,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext2->id])
+        );
+        $this->assertEquals(
+                3,
+                $DB->count_records('comments', ['component' => 'block_comments', 'userid' => $this->student12->id])
+        );
+
+        $contextlist = new \core_privacy\local\request\approved_contextlist($this->student12, 'block_comments',
+                [$coursecontext1->id, $coursecontext2->id]);
+        provider::delete_data_for_user($contextlist);
+
+        // After deletion, the comments for the student12 should have been deleted.
+        $this->assertEquals(
+                1,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext1->id])
+        );
+        $this->assertEquals(
+                1,
+                $DB->count_records('comments', ['component' => 'block_comments', 'contextid' => $coursecontext2->id])
+        );
+        $this->assertEquals(
+                0,
+                $DB->count_records('comments', ['component' => 'block_comments', 'userid' => $this->student12->id])
+        );
+    }
+
+    /**
+     * Test for provider::delete_data_for_user() when there are also comments from other plugins.
+     */
+    public function test_delete_data_for_user_with_comments_from_other_plugins() {
+        global $DB;
+
+        $assigngenerator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
+        $instance = $assigngenerator->create_instance(['course' => $this->course1]);
+        $cm = get_coursemodule_from_instance('assign', $instance->id);
+        $assigncontext = \context_module::instance($cm->id);
+        $assign = new \assign($assigncontext, $cm, $this->course1);
+
+        // Add a comments block in the assignment page.
+        $this->add_comments_block_in_context($assigncontext);
+
+        $submission = $assign->get_user_submission($this->student1->id, true);
+
+        $options = new stdClass();
+        $options->area = 'submission_comments';
+        $options->course = $assign->get_course();
+        $options->context = $assigncontext;
+        $options->itemid = $submission->id;
+        $options->component = 'assignsubmission_comments';
+        $options->showcount = true;
+        $options->displaycancel = true;
+
+        $comment = new comment($options);
+        $comment->set_post_permission(true);
+
+        $this->setUser($this->student1);
+        $comment->add('Comment from student 1');
+
+        $this->add_comment('New comment', $assigncontext);
+        $this->add_comment('New comment', $assigncontext);
+
+        // Before deletion, we should have 3 comments in $assigncontext.
+        // one comment is for the assignment submission and 2 are for the comments block.
+        $this->assertEquals(
+                3,
+                $DB->count_records('comments', ['contextid' => $assigncontext->id])
+        );
+
+        $contextlist = new \core_privacy\local\request\approved_contextlist($this->student1, 'block_comments',
+                [$assigncontext->id]);
+        provider::delete_data_for_user($contextlist);
+
+        // After deletion, the comments for the student1 in the comment block should have been deleted,
+        // but the assignment submission comment should be left.
+        $this->assertEquals(
+                1,
+                $DB->count_records('comments', ['contextid' => $assigncontext->id])
+        );
+        $this->assertEquals(
+                0,
+                $DB->count_records('comments', ['component' => 'block_comments', 'userid' => $this->student1->id])
+        );
+    }
+}
diff --git a/blocks/recent_activity/classes/privacy/provider.php b/blocks/recent_activity/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..8e998d5
--- /dev/null
@@ -0,0 +1,47 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy subsystem implementation for block_recent_activity.
+ *
+ * @package    block_recent_activity
+ * @category   privacy
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace block_recent_activity\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * The block_recent_activity does not keep any data for more than COURSE_MAX_RECENT_PERIOD.
+ *
+ * @copyright  2018 Shamim Rezaie <shamim@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
index f7d1333..3f6eadb 100644 (file)
@@ -24,6 +24,7 @@
  */
 
 $string['pluginname'] = 'Recent activity';
+$string['privacy:metadata'] = 'The recent activity block contains a cache of data stored elsewhere in Moodle.';
 $string['recent_activity:addinstance'] = 'Add a new recent activity block';
 $string['recent_activity:viewaddupdatemodule'] = 'View added and updated modules in recent activity block';
 $string['recent_activity:viewdeletemodule'] = 'View deleted modules in recent activity block';
diff --git a/blocks/tests/privacy_test.php b/blocks/tests/privacy_test.php
new file mode 100644 (file)
index 0000000..8c6327e
--- /dev/null
@@ -0,0 +1,364 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Data provider tests.
+ *
+ * @package    core_block
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+
+use core_privacy\tests\provider_testcase;
+use core_privacy\local\request\approved_contextlist;
+use core_privacy\local\request\transform;
+use core_privacy\local\request\writer;
+use core_block\privacy\provider;
+
+/**
+ * Data provider testcase class.
+ *
+ * @package    core_block
+ * @category   test
+ * @copyright  2018 Frédéric Massart
+ * @author     Frédéric Massart <fred@branchup.tech>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class core_block_privacy_testcase extends provider_testcase {
+
+    public function setUp() {
+        $this->resetAfterTest();
+    }
+
+    public function test_get_contexts_for_userid() {
+        $dg = $this->getDataGenerator();
+        $c1 = $dg->create_course();
+        $c2 = $dg->create_course();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $manager = $this->get_block_manager(['region-a'], $c1ctx);
+        $manager->add_block('myprofile', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockmyprofile = $manager->get_blocks_for_region('region-a')[0];
+
+        $manager = $this->get_block_manager(['region-a'], $c2ctx);
+        $manager->add_block('login', 'region-a', 0, false);
+        $manager->add_block('mentees', 'region-a', 1, false);
+        $manager->load_blocks();
+        list($blocklogin, $blockmentees) = $manager->get_blocks_for_region('region-a');
+
+        $manager = $this->get_block_manager(['region-a'], $u1ctx);
+        $manager->add_block('private_files', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockprivatefiles = $manager->get_blocks_for_region('region-a')[0];
+
+        $this->set_hidden_pref($blocklogin, true, $u1->id);
+        $this->set_hidden_pref($blockprivatefiles, true, $u1->id);
+        $this->set_docked_pref($blockmyprofile, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u2->id);
+
+        $contextids = provider::get_contexts_for_userid($u1->id)->get_contextids();
+        $this->assertCount(4, $contextids);
+        $this->assertTrue(in_array($blocklogin->context->id, $contextids));
+        $this->assertTrue(in_array($blockprivatefiles->context->id, $contextids));
+        $this->assertTrue(in_array($blockmyprofile->context->id, $contextids));
+        $this->assertTrue(in_array($blockmentees->context->id, $contextids));
+
+        $contextids = provider::get_contexts_for_userid($u2->id)->get_contextids();
+        $this->assertCount(1, $contextids);
+        $this->assertTrue(in_array($blockmentees->context->id, $contextids));
+    }
+
+    public function test_delete_data_for_user() {
+        global $DB;
+        $dg = $this->getDataGenerator();
+        $c1 = $dg->create_course();
+        $c2 = $dg->create_course();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $manager = $this->get_block_manager(['region-a'], $c1ctx);
+        $manager->add_block('myprofile', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockmyprofile = $manager->get_blocks_for_region('region-a')[0];
+
+        $manager = $this->get_block_manager(['region-a'], $c2ctx);
+        $manager->add_block('login', 'region-a', 0, false);
+        $manager->add_block('mentees', 'region-a', 1, false);
+        $manager->load_blocks();
+        list($blocklogin, $blockmentees) = $manager->get_blocks_for_region('region-a');
+
+        $manager = $this->get_block_manager(['region-a'], $u1ctx);
+        $manager->add_block('private_files', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockprivatefiles = $manager->get_blocks_for_region('region-a')[0];
+
+        $this->set_hidden_pref($blocklogin, true, $u1->id);
+        $this->set_hidden_pref($blocklogin, true, $u2->id);
+        $this->set_hidden_pref($blockprivatefiles, true, $u1->id);
+        $this->set_hidden_pref($blockmyprofile, true, $u1->id);
+        $this->set_docked_pref($blockmyprofile, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u2->id);
+
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+
+        provider::delete_data_for_user(new approved_contextlist($u1, 'core_block', [$blocklogin->context->id,
+            $blockmyprofile->context->id, $blockmentees->context->id]));
+
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+    }
+
+    public function test_delete_data_for_all_users_in_context() {
+        global $DB;
+        $dg = $this->getDataGenerator();
+        $c1 = $dg->create_course();
+        $c2 = $dg->create_course();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+
+        $manager = $this->get_block_manager(['region-a'], $c1ctx);
+        $manager->add_block('myprofile', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockmyprofile = $manager->get_blocks_for_region('region-a')[0];
+
+        $manager = $this->get_block_manager(['region-a'], $c2ctx);
+        $manager->add_block('login', 'region-a', 0, false);
+        $manager->add_block('mentees', 'region-a', 1, false);
+        $manager->load_blocks();
+        list($blocklogin, $blockmentees) = $manager->get_blocks_for_region('region-a');
+
+        $manager = $this->get_block_manager(['region-a'], $u1ctx);
+        $manager->add_block('private_files', 'region-a', 0, false);
+        $manager->load_blocks();
+        $blockprivatefiles = $manager->get_blocks_for_region('region-a')[0];
+
+        $this->set_hidden_pref($blocklogin, true, $u1->id);
+        $this->set_hidden_pref($blocklogin, true, $u2->id);
+        $this->set_hidden_pref($blockprivatefiles, true, $u1->id);
+        $this->set_hidden_pref($blockmyprofile, true, $u1->id);
+        $this->set_docked_pref($blockmyprofile, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u1->id);
+        $this->set_docked_pref($blockmentees, true, $u2->id);
+
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+
+        // Nothing happens.
+        provider::delete_data_for_all_users_in_context($c1ctx);
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+
+        // Delete one block.
+        provider::delete_data_for_all_users_in_context($blocklogin->context);
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+
+        // Delete another block.
+        provider::delete_data_for_all_users_in_context($blockmyprofile->context);
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "block{$blocklogin->instance->id}hidden"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockprivatefiles->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "block{$blockmyprofile->instance->id}hidden"]));
+        $this->assertFalse($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmyprofile->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u1->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+        $this->assertTrue($DB->record_exists('user_preferences', ['userid' => $u2->id,
+            'name' => "docked_block_instance_{$blockmentees->instance->id}"]));
+    }
+
+    public function test_export_data_for_user() {
+        global $DB;
+        $dg = $this->getDataGenerator();
+        $c1 = $dg->create_course();
+        $c2 = $dg->create_course();
+        $u1 = $dg->create_user();
+        $u2 = $dg->create_user();
+        $c1ctx = context_course::instance($c1->id);
+        $c2ctx = context_course::instance($c2->id);
+        $u1ctx = context_user::instance($u1->id);
+        $u2ctx = context_user::instance($u2->id);
+        $yes = transform::yesno(true);
+        $no = transform::yesno(false);
+
+        $manager = $this->get_block_manager(['region-a'], $c1ctx);
+        $manager->add_block('myprofile', 'region-a', 0, false);
+        $manager->add_block('login', 'region-a', 1, false);
+        $manager->add_block('mentees', 'region-a', 2, false);
+        $manager->add_block('private_files', 'region-a', 3, false);
+        $manager->load_blocks();
+        list($bmyprofile, $blogin, $bmentees, $bprivatefiles) = $manager->get_blocks_for_region('region-a');
+
+        // Set some user preferences.
+        $this->set_hidden_pref($blogin, true, $u1->id);
+        $this->set_docked_pref($blogin, false, $u1->id);
+        $this->set_docked_pref($blogin, true, $u2->id);
+        $this->set_hidden_pref($bprivatefiles, false, $u1->id);
+        $this->set_docked_pref($bprivatefiles, true, $u2->id);
+        $this->set_docked_pref($bmyprofile, true, $u1->id);
+        $this->set_docked_pref($bmentees, true, $u2->id);
+
+        // Export data.
+        provider::export_user_data(new approved_contextlist($u1, 'core_block', [$bmyprofile->context->id, $blogin->context->id,
+            $bmentees->context->id, $bprivatefiles->context->id]));
+        $prefs = writer::with_context($bmentees->context)->get_user_context_preferences('core_block');
+        $this->assertEmpty((array) $prefs);
+
+        $prefs = writer::with_context($blogin->context)->get_user_context_preferences('core_block');
+        $this->assertEquals($no, $prefs->block_is_docked->value);
+        $this->assertEquals($yes, $prefs->block_is_hidden->value);
+
+        $prefs = writer::with_context($bprivatefiles->context)->get_user_context_preferences('core_block');
+        $this->assertObjectNotHasAttribute('block_is_docked', $prefs);
+        $this->assertEquals($no, $prefs->block_is_hidden->value);
+
+        $prefs = writer::with_context($bmyprofile->context)->get_user_context_preferences('core_block');
+        $this->assertEquals($yes, $prefs->block_is_docked->value);
+        $this->assertObjectNotHasAttribute('block_is_hidden', $prefs);
+    }
+
+    /**
+     * Get the block manager.
+     *
+     * @param array $regions The regions.
+     * @param context $context The context.
+     * @param string $pagetype The page type.
+     * @param string $subpage The sub page.
+     * @return block_manager
+     */
+    protected function get_block_manager($regions, $context, $pagetype = 'page-type', $subpage = '') {
+        $page = new moodle_page();
+        $page->set_context($context);
+        $page->set_pagetype($pagetype);
+        $page->set_subpage($subpage);
+        $page->set_url(new moodle_url('/'));
+
+        $blockmanager = new block_manager($page);
+        $blockmanager->add_regions($regions, false);
+        $blockmanager->set_default_region($regions[0]);
+
+        return $blockmanager;
+    }
+
+    /**
+     * Set a docked preference.
+     *
+     * @param block_base $block The block.
+     * @param bool $value The value.
+     * @param int $userid The user ID.
+     */
+    protected function set_docked_pref($block, $value, $userid) {
+        set_user_preference("docked_block_instance_{$block->instance->id}", $value, $userid);
+    }
+
+    /**
+     * Set a hidden preference.
+     *
+     * @param block_base $block The block.
+     * @param bool $value The value.
+     * @param int $userid The user ID.
+     */
+    protected function set_hidden_pref($block, $value, $userid) {
+        set_user_preference("block{$block->instance->id}hidden", $value, $userid);
+    }
+
+}
diff --git a/cache/classes/privacy/provider.php b/cache/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..20cc83f
--- /dev/null
@@ -0,0 +1,66 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for core_cache.
+ *
+ * @package    core_cache
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_cache\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+use \core_privacy\local\metadata\collection;
+
+/**
+ * Privacy Subsystem implementation for core_cache.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+        // Caches store data.
+        \core_privacy\local\metadata\provider,
+
+        // The cache subsystem stores data on behalf of other components.
+        \core_privacy\local\request\subsystem\plugin_provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * Note, although this plugin does store user data, it is not able to
+     * identify it, and that user data is typically very short lived.
+     *
+     * Therefore it is not realistically possible to export any of this
+     * data as it is only identifiable by the plugin storing it, and that
+     * plugin should already be exporting the data as part of it's own
+     * implementation.
+     *
+     * @param   collection     $collection The initialised collection to add items to.
+     * @return  collection     A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        // Data is stored in cache stores.
+        $collection->add_plugintype_link('cachestore', [], 'privacy:metadata:cachestore');
+
+        // Cache locks do not store any personal user data.
+
+        return $collection;
+    }
+}
diff --git a/cache/locks/file/classes/privacy/provider.php b/cache/locks/file/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..a125cc5
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachelock_file.
+ *
+ * @package    cachelock_file
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachelock_file\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachelock_file implementing null_provider.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return  string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
index b57188c..fa5c6df 100644 (file)
@@ -23,4 +23,5 @@
  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
-$string['pluginname'] = 'File locking';
\ No newline at end of file
+$string['pluginname'] = 'File locking';
+$string['privacy:metadata'] = 'The File locking plugin does not store any personal data.';
diff --git a/cache/stores/apcu/classes/privacy/provider.php b/cache/stores/apcu/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..ce0998f
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_apcu.
+ *
+ * @package    cachestore_apcu
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_apcu\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_apcu implementing null_provider.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return  string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
index 9bdf82d..b9ee000 100644 (file)
@@ -30,5 +30,6 @@ $string['prefix'] = 'Prefix';
 $string['prefix_help'] = 'The above prefix gets used for all keys being stored in this APC store instance. By default the database prefix is used.';
 $string['prefixinvalid'] = 'The prefix you have selected is invalid. You can only use a-z A-Z 0-9-_.';
 $string['prefixnotunique'] = 'The prefix you have selected is not unique. Please choose a unique prefix.';
+$string['privacy:metadata'] = 'The APC user cache (APCu) plugin stores data briefly as part of its caching functionality but this data is regularly cleared and is not sent externally in any way.';
 $string['testperformance'] = 'Test performance';
 $string['testperformance_desc'] = 'If enabled, APCu performance will be included when viewing the Test performance page. Enabling this on a production site is not recommended.';
diff --git a/cache/stores/file/classes/privacy/provider.php b/cache/stores/file/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..ab08c8e
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_file.
+ *
+ * @package    cachestore_file
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_file\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_file implementing null_provider.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return  string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
index f0097c2..2759410 100644 (file)
@@ -33,6 +33,7 @@ $string['autocreate_help'] = 'If enabled the directory specified in path will be
 $string['path'] = 'Cache path';
 $string['path_help'] = 'The directory that should be used to store files for this cache store. If left blank (default) a directory will be automatically created in the moodledata directory. This can be used to point a file store towards a directory on a better performing drive (such as one in memory).';
 $string['pluginname'] = 'File cache';
+$string['privacy:metadata'] = 'The File cache cachestore plugin stores data briefly as part of its caching functionality but this data is regularly cleared.';
 $string['prescan'] = 'Prescan directory';
 $string['prescan_help'] = 'If enabled the directory is scanned when the cache is first used and requests for files are first checked against the scan data. This can help if you have a slow file system and are finding that file operations are causing you a bottle neck.';
 $string['singledirectory'] = 'Single directory store';
@@ -49,4 +50,4 @@ It is advisable to only turn this on if the following is true:<br />
  *     directory structure is inadvisable.
  *   - the things we are caching are more expensive to calculate, so the extra
  *     time to computer a better hash is a worthwhile trade-off.
- */
\ No newline at end of file
+ */
diff --git a/cache/stores/memcache/classes/privacy/provider.php b/cache/stores/memcache/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..e7e3779
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_memcache.
+ *
+ * @package    cachestore_memcache
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_memcache\privacy;
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_memcache.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\provider, \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param   collection $collection The initialised collection to add items to.
+     * @return  collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('memcache', [
+                'data' => 'privacy:metadata:memcache:data',
+            ], 'privacy:metadata:memcache');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param   int         $userid     The user to search.
+     * @return  contextlist $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        return new contextlist();
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+    }
+
+    /**
+     * Delete all use data which matches the specified deletion_criteria.
+     *
+     * @param \context $context A user context.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+    }
+}
index 62ef3fe..9095825 100644 (file)
@@ -39,6 +39,8 @@ $string['prefix_help'] = 'This prefix is used for all key names on the memcache
 * If you only have one Moodle instance using this server, you can leave this value default.
 * Due to key length restrictions, a maximum of 5 characters is permitted.';
 $string['prefixinvalid'] = 'Invalid prefix. You can only use a-z A-Z 0-9-_.';
+$string['privacy:metadata:memcache'] = 'The Memcache cachestore plugin stores data briefly as part of its caching functionality. This data is stored on an Memcache server where data is regularly removed.';
+$string['privacy:metadata:memcache:data'] = 'The various data stored in the cache';
 $string['servers'] = 'Servers';
 $string['servers_help'] = 'This sets the servers that should be utilised by this memcache adapter.
 Servers should be defined one per line and consist of a server address and optionally a port and weight.
diff --git a/cache/stores/memcached/classes/privacy/provider.php b/cache/stores/memcached/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..932e2ca
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_memcached.
+ *
+ * @package    cachestore_memcached
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_memcached\privacy;
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_memcached.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\provider, \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param   collection $collection The initialised collection to add items to.
+     * @return  collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('memcached', [
+                'data' => 'privacy:metadata:memcached:data',
+            ], 'privacy:metadata:memcached');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param   int         $userid     The user to search.
+     * @return  contextlist $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        return new contextlist();
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+    }
+
+    /**
+     * Delete all use data which matches the specified deletion_criteria.
+     *
+     * @param \context $context A user context.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+    }
+}
index fcfb2dc..e697808 100644 (file)
@@ -54,6 +54,8 @@ If the cache is shared by other applications then each key will be deleted indiv
 If you are running a dedicated cache for this application then the entire cache can safely be flushed without any risk of destroying another application's cache data. This should result in increased performance when purging the cache.
 ";
 $string['pluginname'] = 'Memcached';
+$string['privacy:metadata:memcached'] = 'The Memcached cachestore plugin stores data briefly as part of its caching functionality. This data is stored on an Memcache server where data is regularly removed.';
+$string['privacy:metadata:memcached:data'] = 'The various data stored in the cache';
 $string['prefix'] = 'Prefix key';
 $string['prefix_help'] = 'This can be used to create a "domain" for your item keys allowing you to create multiple memcached stores on a single memcached installation. It cannot be longer than 16 characters in order to ensure key length issues are not encountered.';
 $string['prefixinvalid'] = 'Invalid prefix. You can only use a-z A-Z 0-9-_.';
diff --git a/cache/stores/mongodb/classes/privacy/provider.php b/cache/stores/mongodb/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..c16d200
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_mongodb.
+ *
+ * @package    cachestore_mongodb
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_mongodb\privacy;
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_mongodb.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\provider, \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param   collection $collection The initialised collection to add items to.
+     * @return  collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('mongodb', [
+                'data' => 'privacy:metadata:mongodb:data',
+            ], 'privacy:metadata:mongodb');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param   int         $userid     The user to search.
+     * @return  contextlist $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        return new contextlist();
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+    }
+
+    /**
+     * Delete all use data which matches the specified deletion_criteria.
+     *
+     * @param \context $context A user context.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+    }
+}
index 90f9912..d0ca148 100644 (file)
@@ -30,6 +30,8 @@ $string['password'] = 'Password';
 $string['password_help'] = 'The password of the user being used for the connection.';
 $string['pleaseupgrademongo'] = 'You are using an old version of the PHP Mongo extension (< 1.3). Support for old versions of the Mongo extension will be dropped in the future. Please consider upgrading.';
 $string['pluginname'] = 'MongoDB';
+$string['privacy:metadata:mongodb'] = 'The MongoDB cachestore plugin stores data briefly as part of its caching functionality. This data is stored on an MongoDB server where data is regularly removed.';
+$string['privacy:metadata:mongodb:data'] = 'The various data stored in the cache';
 $string['replicaset'] = 'Replica set';
 $string['replicaset_help'] = 'The name of the replica set to connect to. If this is given the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed.';
 $string['server'] = 'Server';
diff --git a/cache/stores/redis/classes/privacy/provider.php b/cache/stores/redis/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..20defff
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_redis.
+ *
+ * @package    cachestore_redis
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_redis\privacy;
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_redis.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\provider, \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param   collection $collection The initialised collection to add items to.
+     * @return  collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_external_location_link('redis', [
+                'data' => 'privacy:metadata:redis:data',
+            ], 'privacy:metadata:redis');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param   int         $userid     The user to search.
+     * @return  contextlist $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        return new contextlist();
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+    }
+
+    /**
+     * Delete all use data which matches the specified deletion_criteria.
+     *
+     * @param \context $context A user context.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+    }
+}
index 26aad4e..0d155be 100644 (file)
@@ -30,6 +30,8 @@ $string['prefix_help'] = 'This prefix is used for all key names on the Redis ser
 * If you only have one Moodle instance using this server, you can leave this value default.
 * Due to key length restrictions, a maximum of 5 characters is permitted.';
 $string['prefixinvalid'] = 'Invalid prefix. You can only use a-z A-Z 0-9-_.';
+$string['privacy:metadata:redis'] = 'The Redis cachestore plugin stores data briefly as part of its caching functionality. This data is stored on an Redis server where data is regularly removed.';
+$string['privacy:metadata:redis:data'] = 'The various data stored in the cache';
 $string['serializer_igbinary'] = 'The igbinary serializer.';
 $string['serializer_php'] = 'The default PHP serializer.';
 $string['server'] = 'Server';
diff --git a/cache/stores/session/classes/privacy/provider.php b/cache/stores/session/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..e7e1644
--- /dev/null
@@ -0,0 +1,85 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_session.
+ *
+ * @package    cachestore_session
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_session\privacy;
+
+use core_privacy\local\metadata\collection;
+use core_privacy\local\request\contextlist;
+use core_privacy\local\request\approved_contextlist;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_session.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\provider, \core_privacy\local\request\plugin\provider {
+
+    /**
+     * Returns meta data about this system.
+     *
+     * @param   collection $collection The initialised collection to add items to.
+     * @return  collection A listing of user data stored through this system.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        $collection->add_subsystem_link('core_user', [], 'privacy:metadata:core_user');
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain user information for the specified user.
+     *
+     * @param   int         $userid     The user to search.
+     * @return  contextlist $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        return new contextlist();
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+    }
+
+    /**
+     * Delete all use data which matches the specified deletion_criteria.
+     *
+     * @param \context $context A user context.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+    }
+}
index 80b9c81..c6416b2 100644 (file)
@@ -28,4 +28,5 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$string['pluginname'] = 'Session cache';
\ No newline at end of file
+$string['pluginname'] = 'Session cache';
+$string['privacy:metadata:core_user'] = 'The Session cachestore plugin stores data briefly as part of its caching functionality. This data is stored in the short-lived user session.';
diff --git a/cache/stores/static/classes/privacy/provider.php b/cache/stores/static/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..3e994ee
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Privacy Subsystem implementation for cachestore_static.
+ *
+ * @package    cachestore_static
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace cachestore_static\privacy;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Privacy Subsystem for cachestore_static implementing null_provider.
+ *
+ * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements \core_privacy\local\metadata\null_provider {
+
+    /**
+     * Get the language string identifier with the component's language
+     * file to explain why this plugin stores no data.
+     *
+     * @return  string
+     */
+    public static function get_reason() : string {
+        return 'privacy:metadata';
+    }
+}
index b433999..ec687b9 100644 (file)
@@ -28,4 +28,5 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$string['pluginname'] = 'Static request cache';
\ No newline at end of file
+$string['pluginname'] = 'Static request cache';
+$string['privacy:metadata'] = 'The Static request cachestore plugin stores some data, but this is only present for the lifetime of a single HTTP request.';
diff --git a/calendar/classes/privacy/provider.php b/calendar/classes/privacy/provider.php
new file mode 100644 (file)
index 0000000..0065137
--- /dev/null
@@ -0,0 +1,555 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+/**
+ * Privacy class for requesting user data.
+ *
+ * @package    core_calendar
+ * @copyright  2018 Zig Tan <zig@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace core_calendar\privacy;
+defined('MOODLE_INTERNAL') || die();
+
+use \core_privacy\local\metadata\collection;
+use \core_privacy\local\request\approved_contextlist;
+use \core_privacy\local\request\context;
+use \core_privacy\local\request\contextlist;
+use \core_privacy\local\request\transform;
+use \core_privacy\local\request\writer;
+
+/**
+ * Privacy Subsystem for core_calendar implementing metadata, plugin, and user_preference providers.
+ *
+ * @package    core_calendar
+ * @copyright  2018 Zig Tan <zig@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class provider implements
+    \core_privacy\local\metadata\provider,
+    \core_privacy\local\request\plugin\provider,
+    \core_privacy\local\request\user_preference_provider
+{
+
+    /**
+     * Provides meta data that is stored about a user with core_calendar.
+     *
+     * @param  collection $collection A collection of meta data items to be added to.
+     * @return  collection Returns the collection of metadata.
+     */
+    public static function get_metadata(collection $collection) : collection {
+        // The calendar 'event' table contains user data.
+        $collection->add_database_table(
+            'event',
+            [
+                'name' => 'privacy:metadata:calendar:event:name',
+                'description' => 'privacy:metadata:calendar:event:description',
+                'eventtype' => 'privacy:metadata:calendar:event:eventtype',
+                'timestart' => 'privacy:metadata:calendar:event:timestart',
+                'timeduration' => 'privacy:metadata:calendar:event:timeduration',
+            ],
+            'privacy:metadata:calendar:event'
+        );
+
+        // The calendar 'event_subscriptions' table contains user data.
+        $collection->add_database_table(
+            'event_subscriptions',
+            [
+                'name' => 'privacy:metadata:calendar:event_subscriptions:name',
+                'url' => 'privacy:metadata:calendar:event_subscriptions:url',
+                'eventtype' => 'privacy:metadata:calendar:event_subscriptions:eventtype',
+            ],
+            'privacy:metadata:calendar:event_subscriptions'
+        );
+
+        // The calendar user preference setting 'calendar_savedflt'.
+        $collection->add_user_preference(
+            'calendar_savedflt',
+            'privacy:metadata:calendar:preferences:calendar_savedflt'
+        );
+
+        return $collection;
+    }
+
+    /**
+     * Get the list of contexts that contain calendar user information for the specified user.
+     *
+     * @param   int $userid The user to search.
+     * @return  contextlist   $contextlist  The contextlist containing the list of contexts used in this plugin.
+     */
+    public static function get_contexts_for_userid(int $userid) : contextlist {
+        $contextlist = new contextlist();
+
+        // Calendar Events can exist at Site, Course Category, Course, Course Group, User, or Course Modules contexts.
+        $params = [
+            'sitecontext'        => CONTEXT_SYSTEM,
+            'categorycontext'    => CONTEXT_COURSECAT,
+            'coursecontext'      => CONTEXT_COURSE,
+            'groupcontext'       => CONTEXT_COURSE,
+            'usercontext'        => CONTEXT_USER,
+            'cuserid'            => $userid,
+            'modulecontext'      => CONTEXT_MODULE,
+            'muserid'            => $userid
+        ];
+
+        // Get contexts of Calendar Events for the owner.
+        $sql = "SELECT ctx.id
+                  FROM {context} ctx
+                  JOIN {event} e ON
+                       (e.eventtype = 'site' AND ctx.contextlevel = :sitecontext) OR
+                       (e.categoryid = ctx.instanceid AND e.eventtype = 'category' AND ctx.contextlevel = :categorycontext) OR
+                       (e.courseid = ctx.instanceid AND e.eventtype = 'course' AND ctx.contextlevel = :coursecontext) OR
+                       (e.courseid = ctx.instanceid AND e.eventtype = 'group' AND ctx.contextlevel = :groupcontext) OR
+                       (e.userid = ctx.instanceid AND e.eventtype = 'user' AND ctx.contextlevel = :usercontext)
+                 WHERE e.userid = :cuserid
+                 UNION
+                SELECT ctx.id
+                  FROM {context} ctx
+                  JOIN {course_modules} cm ON cm.id = ctx.instanceid AND ctx.contextlevel = :modulecontext
+                  JOIN {modules} m ON m.id = cm.module
+                  JOIN {event} e ON e.modulename = m.name AND e.courseid = cm.course AND e.instance = cm.instance
+                 WHERE e.userid = :muserid";
+        $contextlist->add_from_sql($sql, $params);
+
+        // Calendar Subscriptions can exist at Site, Course Category, Course, Course Group, or User contexts.
+        $params = [
+            'sitecontext'       => CONTEXT_SYSTEM,
+            'categorycontext'   => CONTEXT_COURSECAT,
+            'coursecontext'     => CONTEXT_COURSE,
+            'groupcontext'      => CONTEXT_COURSE,
+            'usercontext'       => CONTEXT_USER,
+            'userid'            => $userid
+        ];
+
+        // Get contexts for Calendar Subscriptions for the owner.
+        $sql = "SELECT ctx.id
+                  FROM {context} ctx
+                  JOIN {event_subscriptions} s ON
+                       (s.eventtype = 'site' AND ctx.contextlevel = :sitecontext) OR
+                       (s.categoryid = ctx.instanceid AND s.eventtype = 'category' AND ctx.contextlevel = :categorycontext) OR
+                       (s.courseid = ctx.instanceid AND s.eventtype = 'course' AND ctx.contextlevel = :coursecontext) OR
+                       (s.courseid = ctx.instanceid AND s.eventtype = 'group' AND ctx.contextlevel = :groupcontext) OR
+                       (s.userid = ctx.instanceid AND s.eventtype = 'user' AND ctx.contextlevel = :usercontext)
+                 WHERE s.userid = :userid";
+        $contextlist->add_from_sql($sql, $params);
+
+        // Return combined contextlist for Calendar Events & Calendar Subscriptions.
+        return $contextlist;
+    }
+
+    /**
+     * Export all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist $contextlist The approved contexts to export information for.
+     */
+    public static function export_user_data(approved_contextlist $contextlist) {
+        if (empty($contextlist)) {
+            return;
+        }
+
+        self::export_user_calendar_event_data($contextlist);
+        self::export_user_calendar_subscription_data($contextlist);
+    }
+
+    /**
+     * Export all user preferences for the plugin.
+     *
+     * @param   int $userid The userid of the user whose data is to be exported.
+     */
+    public static function export_user_preferences(int $userid) {
+        $calendarsavedflt = get_user_preferences('calendar_savedflt', null, $userid);
+
+        if (null !== $calendarsavedflt) {
+            writer::export_user_preference(
+                'core_calendar',
+                'calendarsavedflt',
+                $calendarsavedflt,
+                get_string('privacy:metadata:calendar:preferences:calendar_savedflt', 'core_calendar')
+            );
+        }
+    }
+
+    /**
+     * Delete all Calendar Event and Calendar Subscription data for all users in the specified context.
+     *
+     * @param   context $context Transform the specific context to delete data for.
+     */
+    public static function delete_data_for_all_users_in_context(\context $context) {
+        if (empty($context)) {
+            return;
+        }
+
+        // Delete all Calendar Events in the specified context in batches.
+        $eventids = array_keys(self::get_calendar_event_ids_by_context($context));
+        self::delete_batch_records('event', 'id', $eventids);
+
+        // Delete all Calendar Subscriptions in the specified context in batches.
+        $subscriptionids = array_keys(self::get_calendar_subscription_ids_by_context($context));
+        self::delete_batch_records('event_subscriptions', 'id', $subscriptionids);
+    }
+
+    /**
+     * Delete all user data for the specified user, in the specified contexts.
+     *
+     * @param   approved_contextlist $contextlist The approved contexts and user information to delete information for.
+     */
+    public static function delete_data_for_user(approved_contextlist $contextlist) {
+        if (empty($contextlist)) {
+            return;
+        }
+
+        // Delete all Calendar Events for the owner and specified contexts in batches.
+        $eventdetails = self::get_calendar_event_details_by_contextlist($contextlist);
+        $eventids = [];
+        foreach ($eventdetails as $eventdetail) {
+            $eventids[] = $eventdetail->eventid;
+        }
+        $eventdetails->close();
+        self::delete_batch_records('event', 'id', $eventids);
+
+        // Delete all Calendar Subscriptions for the owner and specified contexts in batches.
+        $subscriptiondetails = self::get_calendar_subscription_details_by_contextlist($contextlist);
+        $subscriptionids = [];
+        foreach ($subscriptiondetails as $subscriptiondetail) {
+            $subscriptionids[] = $subscriptiondetail->subscriptionid;
+        }
+        $subscriptiondetails->close();
+        self::delete_batch_records('event_subscriptions', 'id', $subscriptionids);
+    }
+
+    /**
+     * Helper function to export Calendar Events data by a User's contextlist.
+     *
+     * @param approved_contextlist $contextlist
+     * @throws \coding_exception
+     */
+    protected static function export_user_calendar_event_data(approved_contextlist $contextlist) {
+        // Calendar Events can exist at Site, Course Category, Course, Course Group, User, or Course Modules contexts.
+        $eventdetails = self::get_calendar_event_details_by_contextlist($contextlist);
+
+        // Multiple Calendar Events of the same eventtype and time can exist for a context, so collate them for export.
+        $eventrecords = [];
+        foreach ($eventdetails as $eventdetail) {
+            // Create an array key based on the contextid, eventtype, and time.
+            $key = $eventdetail->contextid . $eventdetail->eventtype . $eventdetail->timestart;
+
+            if (array_key_exists($key, $eventrecords) === false) {
+                $eventrecords[$key] = [ $eventdetail ];
+&