This formats and then exports the event monitor subscriptions.

@param  array $subscriptions Subscriptions
@param  \context_user $context The user context
345520
protected static function export_monitor_subscriptions(array $subscriptions, \context_user $context) {
        foreach ($subscriptions as $subscription) {
            $subscriptiondata = new \stdClass();
            $subscriptiondata->instancename = $subscription->get_instance_name();
            $subscriptiondata->eventname = $subscription->get_event_name();
            $subscriptiondata->frequency = $subscription->get_filters_description();
            $subscriptiondata->name = $subscription->get_name($context);
            $subscriptiondata->description = $subscription->get_description($context);
            $subscriptiondata->pluginname = $subscription->get_plugin_name();
            $subscriptiondata->course = $subscription->get_course_name($context);
            $subscriptiondata->timecreated = transform::datetime($subscription->timecreated);
            $subscriptiondata->lastnotificationsent = transform::datetime($subscription->lastnotificationsent);
            writer::with_context($context)->export_data([get_string('privacy:subscriptions', 'tool_monitor'),
                    $subscriptiondata->name . '_' . $subscription->id, $subscriptiondata->course, $subscriptiondata->instancename],
                    $subscriptiondata);
        }
    }
1189915
protected function _authorizeSubscribe($context)
    {
        $entity = $this->_entity;

        if (is_guest($this->_viewer)) {
            return false;
        }

        if (! $entity->isSubscribable()) {
            return false;
        }

        return $this->_viewer->following($entity);
    }
77175
protected static function export_user_data_user_evidence(context_user $context) {
        global $DB;

        $userid = $context->instanceid;
        $path = [get_string('competencies', 'core_competency'), get_string('privacy:path:userevidence', 'core_competency')];
        $uefields = user_evidence::get_sql_fields('ue', 'ue_');
        $cfields = competency::get_sql_fields('c', 'c_');

        $sql = "
            SELECT $uefields, $cfields
              FROM {" . user_evidence::TABLE . "} ue
         LEFT JOIN {" . user_evidence_competency::TABLE . "} uec
                ON uec.userevidenceid = ue.id
         LEFT JOIN {" . competency::TABLE . "} c
                ON c.id = uec.competencyid
             WHERE ue.userid = :userid
          ORDER BY ue.id";
        $params = ['userid' => $userid];

        $recordset = $DB->get_recordset_sql($sql, $params);
        static::recordset_loop_and_export($recordset, 'ue_id', null, function($carry, $record) use ($userid, $context){
            if ($carry === null) {
                $ue = new user_evidence(null, user_evidence::extract_record($record, 'ue_'));
                $carry = static::transform_user_evidence($userid, $ue);
            }

            if (!empty($record->c_id)) {
                $competency = new competency(null, competency::extract_record($record, 'c_'));
                $carry['competencies'][] = static::transform_competency_brief($competency);
            }

            return $carry;
        }, function($ueid, $data) use ($context, $path) {
            $finalpath = array_merge($path, [$data['name'] . ' (' . $ueid . ')']);
            writer::with_context($context)->export_area_files($finalpath, 'core_competency', 'userevidence', $ueid);
            writer::with_context($context)->export_data($finalpath, (object) $data);
        });
    }
1230209
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) use ($userid) {
            if ($context->contextlevel == CONTEXT_USER) {
                if ($context->instanceid == $userid) {
                    $carry['has_mine'] = true;
                } else {
                    $carry['others'][] = $context->instanceid;
                }
            }
            return $carry;
        }, [
            'has_mine' => false,
            'others' => []
        ]);

        $path = [get_string('webservices', 'core_webservice')];

        // Exporting my stuff.
        if ($contexts['has_mine']) {

            $data = [];

            // Exporting my tokens.
            $sql = "
                SELECT t.*, s.name as externalservicename
                  FROM {external_tokens} t
                  JOIN {external_services} s
                    ON s.id = t.externalserviceid
                 WHERE t.userid = :userid
              ORDER BY t.id";
            $recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
            foreach ($recordset as $record) {
                if (!isset($data['tokens'])) {
                    $data['tokens'] = [];
                }
                $data['tokens'][] = static::transform_token($record);
            }
            $recordset->close();

            // Exporting the services I have access to.
            $sql = "
                SELECT su.*, s.name as externalservicename
                  FROM {external_services_users} su
                  JOIN {external_services} s
                    ON s.id = su.externalserviceid
                 WHERE su.userid = :userid
              ORDER BY su.id";
            $recordset = $DB->get_recordset_sql($sql, ['userid' => $userid]);
            foreach ($recordset as $record) {
                if (!isset($data['services_user'])) {
                    $data['services_user'] = [];
                }
                $data['services_user'][] = [
                    'external_service' => $record->externalservicename,
                    'ip_restriction' => $record->iprestriction,
                    'valid_until' => $record->validuntil ? transform::datetime($record->validuntil) : null,
                    'created_on' => transform::datetime($record->timecreated),
                ];
            }
            $recordset->close();

            if (!empty($data)) {
                writer::with_context(context_user::instance($userid))->export_data($path, (object) $data);
            };
        }

        // Exporting the tokens I created.
        if (!empty($contexts['others'])) {
            list($insql, $inparams) = $DB->get_in_or_equal($contexts['others'], SQL_PARAMS_NAMED);
            $sql = "
                SELECT t.*, s.name as externalservicename
                  FROM {external_tokens} t
                  JOIN {external_services} s
                    ON s.id = t.externalserviceid
                 WHERE t.userid $insql
                   AND t.creatorid = :userid1
                   AND t.userid <> :userid2
              ORDER BY t.userid, t.id";
            $params = array_merge($inparams, ['userid1' => $userid, 'userid2' => $userid]);
            $recordset = $DB->get_recordset_sql($sql, $params);
            static::recordset_loop_and_export($recordset, 'userid', [], function($carry, $record) {
                $carry[] = static::transform_token($record);
                return $carry;
            }, function($userid, $data) use ($path) {
                writer::with_context(context_user::instance($userid))->export_related_data($path, 'created_by_you', (object) [
                    'tokens' => $data
                ]);
            });
        }
    }
1277020
public function addObservableEvents($observables)
    {
        $observables = is_array($observables) ? $observables : func_get_args();

        $this->observables = array_unique(array_merge($this->observables, $observables));
    }
867259
protected static function export_user(\stdClass $user, \context $context) {
        $data = (object) [
            'auth' => $user->auth,
            'confirmed' => transform::yesno($user->confirmed),
            'policyagreed' => transform::yesno($user->policyagreed),
            'deleted' => transform::yesno($user->deleted),
            'suspended' => transform::yesno($user->suspended),
            'username' => $user->username,
            'idnumber' => $user->idnumber,
            'firstname' => format_string($user->firstname, true, ['context' => $context]),
            'lastname' => format_string($user->lastname, true, ['context' => $context]),
            'email' => $user->email,
            'emailstop' => transform::yesno($user->emailstop),
            'icq' => format_string($user->icq, true, ['context' => $context]),
            'skype' => format_string($user->skype, true, ['context' => $context]),
            'yahoo' => format_string($user->yahoo, true, ['context' => $context]),
            'aim' => format_string($user->aim, true, ['context' => $context]),
            'msn' => format_string($user->msn, true, ['context' => $context]),
            'phone1' => format_string($user->phone1, true, ['context' => $context]),
            'phone2' => format_string($user->phone2, true, ['context' => $context]),
            'institution' => format_string($user->institution, true, ['context' => $context]),
            'department' => format_string($user->department, true, ['context' => $context]),
            'address' => format_string($user->address, true, ['context' => $context]),
            'city' => format_string($user->city, true, ['context' => $context]),
            'country' => format_string($user->country, true, ['context' => $context]),
            'lang' => $user->lang,
            'calendartype' => $user->calendartype,
            'theme' => $user->theme,
            'timezone' => $user->timezone,
            'firstaccess' => transform::datetime($user->firstaccess),
            'lastaccess' => transform::datetime($user->lastaccess),
            'lastlogin' => transform::datetime($user->lastlogin),
            'currentlogin' => $user->currentlogin,
            'lastip' => $user->lastip,
            'secret' => $user->secret,
            'picture' => $user->picture,
            'url' => $user->url,
            'description' => format_text($user->description, $user->descriptionformat, ['context' => $context]),
            'maildigest' => transform::yesno($user->maildigest),
            'maildisplay' => $user->maildisplay,
            'autosubscribe' => transform::yesno($user->autosubscribe),
            'trackforums' => transform::yesno($user->trackforums),
            'timecreated' => transform::datetime($user->timecreated),
            'timemodified' => transform::datetime($user->timemodified),
            'imagealt' => format_string($user->imagealt, true, ['context' => $context]),
            'lastnamephonetic' => format_string($user->lastnamephonetic, true, ['context' => $context]),
            'firstnamephonetic' => format_string($user->firstnamephonetic, true, ['context' => $context]),
            'middlename' => format_string($user->middlename, true, ['context' => $context]),
            'alternatename'  => format_string($user->alternatename, true, ['context' => $context])
        ];
        if (isset($data->description)) {
            $data->description = writer::with_context($context)->rewrite_pluginfile_urls(
                    [get_string('privacy:descriptionpath', 'user')], 'user', 'profile', '', $data->description);
        }
        writer::with_context($context)->export_area_files([], 'user', 'profile', 0)
                ->export_data([], $data);
        // Export profile images.
        writer::with_context($context)->export_area_files([get_string('privacy:profileimagespath', 'user')], 'user', 'icon', 0);
        // Export private files.
        writer::with_context($context)->export_area_files([get_string('privacy:privatefilespath', 'user')], 'user', 'private', 0);
        // Export draft files.
        writer::with_context($context)->export_area_files([get_string('privacy:draftfilespath', 'user')], 'user', 'draft', false);
    }
1232797
protected function _actionEditsubscription(AnCommandContext $context)
    {
        if ($subscription = $this->_subscriber->changeSubscriptionTo($this->getItem())) {
            $subscription->endDate = $context->data->endDate;
        }
    }
813435
public static function export_user_data(approved_contextlist $contextlist) {
        $context = $contextlist->current();
        $user = \core_user::get_user($contextlist->get_user()->id);
        static::export_recentitems($user->id, $context);
    }
606202
public function subscribe($events)
    {
        $events->listen(
            Added::class,
            'Laranix\Auth\User\Groups\Events\Subscriber@onAdded'
        );

        $events->listen(
            Updated::class,
            'Laranix\Auth\User\Groups\Events\Subscriber@onUpdated'
        );

        $events->listen(
            Removed::class,
            'Laranix\Auth\User\Groups\Events\Subscriber@onRemoved'
        );
    }
920042
protected function _actionProcess($context)
    {
        try {
            $identifier = 'com:subscriptions.controller.subscription';
            $subscription = $this->getService($identifier)->setOrder($this->order->cloneEntity())->add();
        } catch (ComSubscriptionsDomainPaymentException $exception) {
            $this->setMessage('COM-SUBSCRIPTIONS-TRANSACTION-ERROR', 'error');
            throw new RuntimeException('Payment process error');
        }

        if ($subscription->persisted()) {

            AnRequest::set('session.signup', null);
            AnRequest::set('session.subscriber_id', $subscription->person->id);
            $url = route('option=com_subscriptions&view=signup&layout=processed&id='.$this->getItem()->id);

            if (get_viewer()->guest()) {
                $return = base64UrlEncode($url);
                $token = $subscription->person->activationCode;
                $url = route('option=com_people&view=session&token='.$token.'&return='.$return);
            }

            $context->response->setRedirect($url);

        } else {
            throw new RuntimeException("Couldn't subscribe");
        }

        return true;
    }
689805
private function addSubscribers(array $eventSubscribers)
    {
        foreach ($eventSubscribers as $eventSubscriber) {
            if (is_string($eventSubscriber)) {
                $eventSubscriber = new $eventSubscriber();
            } elseif (is_callable($eventSubscriber)) {
                $eventSubscriber = call_user_func($eventSubscriber, $this->dispatcher);
            }

            $this->dispatcher->addSubscriber($eventSubscriber);
        }

        return $this;
    }
1309650
public function has_subscriber($subscriptions)
    {
        $enabled_components = $this->wrappedObject->enabled_components()->orderBy('order')->pluck('id')->toArray();
        $intersected = array_intersect($enabled_components, $subscriptions);

        return count($intersected) != 0;
    }
247683
public static function delete_data_for_all_users_in_context(\context $context) {
        // Delete all Calendar Events in the specified context in batches.
        if ($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.
        if ($subscriptionids = array_keys(self::get_calendar_subscription_ids_by_context($context))) {
            self::delete_batch_records('event_subscriptions', 'id', $subscriptionids);
        }
    }
741890
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        if (empty($contextlist)) {
            return;
        }

        $user = $contextlist->get_user();
        $userid = $user->id;

        list($contextsql, $contextparams) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
        $params = $contextparams;

        // Digested forums.
        $sql = "SELECT
                    c.id AS contextid,
                    dig.maildigest AS maildigest
                  FROM {context} c
                  JOIN {course_modules} cm ON cm.id = c.instanceid
                  JOIN {forum} f ON f.id = cm.instance
                  JOIN {forum_digests} dig ON dig.forum = f.id
                 WHERE (
                    dig.userid = :userid AND
                    c.id {$contextsql}
                )
        ";
        $params['userid'] = $userid;
        $digests = $DB->get_records_sql_menu($sql, $params);

        // Forum subscriptions.
        $sql = "SELECT
                    c.id AS contextid,
                    sub.userid AS subscribed
                  FROM {context} c
                  JOIN {course_modules} cm ON cm.id = c.instanceid
                  JOIN {forum} f ON f.id = cm.instance
                  JOIN {forum_subscriptions} sub ON sub.forum = f.id
                 WHERE (
                    sub.userid = :userid AND
                    c.id {$contextsql}
                )
        ";
        $params['userid'] = $userid;
        $subscriptions = $DB->get_records_sql_menu($sql, $params);

        // Tracked forums.
        $sql = "SELECT
                    c.id AS contextid,
                    pref.userid AS tracked
                  FROM {context} c
                  JOIN {course_modules} cm ON cm.id = c.instanceid
                  JOIN {forum} f ON f.id = cm.instance
                  JOIN {forum_track_prefs} pref ON pref.forumid = f.id
                 WHERE (
                    pref.userid = :userid AND
                    c.id {$contextsql}
                )
        ";
        $params['userid'] = $userid;
        $tracked = $DB->get_records_sql_menu($sql, $params);

        $sql = "SELECT
                    c.id AS contextid,
                    f.*,
                    cm.id AS cmid
                  FROM {context} c
                  JOIN {course_modules} cm ON cm.id = c.instanceid
                  JOIN {forum} f ON f.id = cm.instance
                 WHERE (
                    c.id {$contextsql}
                )
        ";

        $params += $contextparams;

        // Keep a mapping of forumid to contextid.
        $mappings = [];

        $forums = $DB->get_recordset_sql($sql, $params);
        foreach ($forums as $forum) {
            $mappings[$forum->id] = $forum->contextid;

            $context = \context::instance_by_id($mappings[$forum->id]);

            // Store the main forum data.
            $data = request_helper::get_context_data($context, $user);
            writer::with_context($context)
                ->export_data([], $data);
            request_helper::export_context_files($context, $user);

            // Store relevant metadata about this forum instance.
            if (isset($digests[$forum->contextid])) {
                static::export_digest_data($userid, $forum, $digests[$forum->contextid]);
            }
            if (isset($subscriptions[$forum->contextid])) {
                static::export_subscription_data($userid, $forum, $subscriptions[$forum->contextid]);
            }
            if (isset($tracked[$forum->contextid])) {
                static::export_tracking_data($userid, $forum, $tracked[$forum->contextid]);
            }
        }
        $forums->close();

        if (!empty($mappings)) {
            // Store all discussion data for this forum.
            static::export_discussion_data($userid, $mappings);

            // Store all post data for this forum.
            static::export_all_posts($userid, $mappings);
        }
    }
157211
protected function _actionAdd($context)
    {
        $entity = parent::_actionAdd($context);

        if ($entity->owner->isSubscribable()) {
            $notification = $this->createNotification(array(
                'name' => 'topic_add',
                'object' => $entity,
                'subscribers' => $entity->owner->subscriberIds->toArray(),
            ))->setType('post', array('new_post' => true));
        }

        return $entity;
    }
404381
public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        if (empty($contextlist->count())) {
            return;
        }

        $user = $contextlist->get_user();

        list($contextsql, $contextparams) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);

        $sql = "SELECT ltiusers.lastgrade, ltiusers.lastaccess, ltiusers.timecreated, ltitools.contextid
                  FROM {enrol_lti_users} ltiusers
                  JOIN {enrol_lti_tools} ltitools
                    ON ltiusers.toolid = ltitools.id
                  JOIN {context} ctx
                    ON ctx.id = ltitools.contextid
                 WHERE ctx.id {$contextsql}
                   AND ltiusers.userid = :userid";
        $params = $contextparams + ['userid' => $user->id];
        $ltiusers = $DB->get_recordset_sql($sql, $params);
        self::recordset_loop_and_export($ltiusers, 'contextid', [], function($carry, $record) {
            $carry[] = [
                'lastgrade' => $record->lastgrade,
                'timecreated' => transform::datetime($record->lastaccess),
                'timemodified' => transform::datetime($record->timecreated)
            ];
            return $carry;
        }, function($contextid, $data) {
            $context = \context::instance_by_id($contextid);
            $finaldata = (object) $data;
            writer::with_context($context)->export_data(['enrol_lti_users'], $finaldata);
        });
    }
1335008
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();
    }