Helper function to return all Calendar Event id results for a specified context and optionally
included user list.

@param \context $context
@param array $userids
@return array|null
@throws \dml_exception
338054
protected static function get_calendar_event_ids_by_context(\context $context, $userids = array()) {
        global $DB;

        // Calendar Events can exist at Site (CONTEXT_SYSTEM), Course Category (CONTEXT_COURSECAT),
        // Course and Course Group (CONTEXT_COURSE), User (CONTEXT_USER), or Course Modules (CONTEXT_MODULE) contexts.
        if (!in_array($context->contextlevel, [CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_USER, CONTEXT_MODULE])) {
            return [];
        }

        $whereusersql = '';
        $userparams = array();
        if (!empty($userids)) {
            list($usersql, $userparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
            $whereusersql = "AND e.userid {$usersql}";
        }

        if ($context->contextlevel == CONTEXT_MODULE) { // Course Module events.
            $params = ['cmid' => $context->instanceid];

            // Get Calendar Events for the specified Course Module context.
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {course_modules} cm
                      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 cm.id = :cmid
                           $whereusersql";
        } else if ($context->contextlevel == CONTEXT_SYSTEM) { // Site events.
            $params = [];
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {event} e
                     WHERE e.eventtype = 'site'
                           $whereusersql";
        } else { // The rest.
            $eventfields = [
                CONTEXT_COURSECAT   => 'categoryid',
                CONTEXT_COURSE      => 'courseid',
                CONTEXT_USER        => 'userid'
            ];
            $eventfield = $eventfields[$context->contextlevel];

            $eventtypes = [
                CONTEXT_COURSECAT   => 'category',
                CONTEXT_COURSE      => ['course' , 'group'],
                CONTEXT_USER        => 'user'
            ];
            list($eventtypesql, $eventtypeparams) = $DB->get_in_or_equal($eventtypes[$context->contextlevel], SQL_PARAMS_NAMED);

            $params = $eventtypeparams + ['instanceid' => $context->instanceid];

            // Get Calendar Events for the specified Moodle context.
            $sql = "SELECT DISTINCT e.id AS eventid
                      FROM {event} e
                     WHERE e.eventtype $eventtypesql
                           AND e.{$eventfield} = :instanceid
                           $whereusersql";
        }

        $params += $userparams;

        return $DB->get_records_sql($sql, $params);
    }
689445
public function get_users_in_context(\context $context) : \core_privacy\local\request\userlist_collection {
        $progress = static::get_log_tracer();

        $components = $this->get_component_list();
        $a = (object) [
            'total' => count($components),
            'progress' => 0,
            'component' => '',
            'datetime' => userdate(time()),
        ];
        $collection = new \core_privacy\local\request\userlist_collection($context);

        $progress->output(get_string('trace:fetchcomponents', 'core_privacy', $a), 1);
        foreach ($components as $component) {
            $a->component = $component;
            $a->progress++;
            $a->datetime = userdate(time());
            $progress->output(get_string('trace:preprocessingcomponent', 'core_privacy', $a), 2);
            $userlist = new local\request\userlist($context, $component);

            $this->handled_component_class_callback($component, core_userlist_provider::class, 'get_users_in_context', [$userlist]);

            // Add contexts that the component may not know about.
            \core_privacy\local\request\helper::add_shared_users_to_userlist($userlist);

            if (count($userlist)) {
                $collection->add_userlist($userlist);
            }
        }
        $progress->output(get_string('trace:done', 'core_privacy'), 1);

        return $collection;
    }
388445
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;
    }
86424
public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        // We cannot associate files with a particular user as it would require to know all the details about
        // the source file, which only the component owning it knows about. And, the 'usermodified' attribute
        // of the conversion class is not an identifier of data ownership, merely that this user was logged in
        // when the conversion was requested. As such, as the owning component should declare the source file,
        // and we can't make sense of 'usermodified', we will not be reporting anything here. Also note that
        // the clean up task will ensure that whenever a source file is delete, its conversions also are.
        return new \core_privacy\local\request\contextlist();
    }
953346
public static function get_users_in_context(userlist $userlist) {
        $context = $userlist->get_context();

        if (!$context instanceof \context_course) {
            return;
        }

        \core_completion\privacy\provider::add_course_completion_users_to_userlist($userlist);
        \core_favourites\privacy\provider::add_userids_for_context($userlist, 'courses');
    }
718154
public function participantsUserIds($userId = null)
    {
        $users = $this->participants()->select('user_id')->get()->map(function ($participant) {
            return $participant->user_id;
        });

        if ($userId) {
            $users->push($userId);
        }

        return $users->toArray();
    }
384784
public function participantsUserIds($userId = null)
    {
        $users = $this->participants()->lists('user_id');

        if ($userId) {
            $users[] = $userId;
        }

        return $users;
    }
1212869
protected function checkUserIds(array $userIds)
    {
        $checkedUserIds = array();
        foreach ($userIds as $userId) {
            if (true === is_numeric($userId) && false === in_array($userId, $checkedUserIds)) {
                $checkedUserIds[] = (int)$userId;
            }
        }
        return $checkedUserIds;
    }
1319911
public static function get_users_in_context(userlist $userlist) {
        global $DB;

        $context = $userlist->get_context();
        $models = self::get_models_with_user_data();

        foreach ($models as $modelid => $model) {

            $analyser = $model->get_analyser(['notimesplitting' => true]);

            // Analytics predictions.
            $params = [
                'contextid' => $context->id,
                'modelid' => $modelid,
            ];
            $joinusersql = $analyser->join_sample_user('ap');
            $sql = "SELECT u.id AS userid
                      FROM {analytics_predictions} ap
                           {$joinusersql}
                     WHERE ap.contextid = :contextid
                       AND ap.modelid = :modelid";
            $userlist->add_from_sql('userid', $sql, $params);

            // Indicator calculations.
            $params = [
                'contextid' => $context->id,
                'analysersamplesorigin' => $analyser->get_samples_origin(),
            ];
            $joinusersql = $analyser->join_sample_user('aic');
            $sql = "SELECT u.id AS userid
                      FROM {analytics_indicator_calc} aic
                           {$joinusersql}
                     WHERE aic.contextid = :contextid
                       AND aic.sampleorigin = :analysersamplesorigin";
            $userlist->add_from_sql('userid', $sql, $params);
        }

        // We can leave this out of the loop as there is no analyser-dependent stuff.
        list($sql, $params) = self::analytics_prediction_actions_context_sql($context->id, array_keys($models));
        $sql = "SELECT apa.userid" . $sql;
        $userlist->add_from_sql('userid', $sql, $params);
    }
592750
public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        global $DB;
        $contextlist = new \core_privacy\local\request\contextlist();

        // There are at least one blog post.
        if ($DB->record_exists_select('post', 'userid = :userid AND module IN (:blog, :blogext)', [
                'userid' => $userid, 'blog' => 'blog', 'blogext' => 'blog_external'])) {
            $sql = "
                SELECT ctx.id
                  FROM {context} ctx
                 WHERE ctx.contextlevel = :ctxlevel
                   AND ctx.instanceid = :ctxuserid";
            $params = [
                'ctxlevel' => CONTEXT_USER,
                'ctxuserid' => $userid,
            ];
            $contextlist->add_from_sql($sql, $params);

            // Add the associated context of the blog posts.
            $sql = "
                SELECT DISTINCT ctx.id
                  FROM {post} p
                  JOIN {blog_association} ba
                    ON ba.blogid = p.id
                  JOIN {context} ctx
                    ON ctx.id = ba.contextid
                 WHERE p.userid = :userid";
            $params = [
                'userid' => $userid,
            ];
            $contextlist->add_from_sql($sql, $params);
        }

        // If there is at least one external blog, we add the user context. This is done this
        // way because we can't directly add context to a contextlist.
        if ($DB->record_exists('blog_external', ['userid' => $userid])) {
            $sql = "
                SELECT ctx.id
                  FROM {context} ctx
                 WHERE ctx.contextlevel = :ctxlevel
                   AND ctx.instanceid = :ctxuserid";
            $params = [
                'ctxlevel' => CONTEXT_USER,
                'ctxuserid' => $userid,
            ];
            $contextlist->add_from_sql($sql, $params);
        }

        // Include the user contexts in which the user comments.
        $sql = "
            SELECT DISTINCT ctx.id
              FROM {context} ctx
              JOIN {comments} c
                ON c.contextid = ctx.id
             WHERE c.component = :component
               AND c.commentarea = :commentarea
               AND c.userid = :userid";
        $params = [
            'component' => 'blog',
            'commentarea' => 'format_blog',
            'userid' => $userid
        ];
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
1198394
public static function get_users_in_context(userlist $userlist) {
        $context = $userlist->get_context();

        if ($context instanceof \context_course) {
            $params = ['courseid' => $context->instanceid];

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                     WHERE bc.itemid = :courseid
                           AND bc.type = :typecourse";

            $courseparams = ['typecourse' => 'course'] + $params;

            $userlist->add_from_sql('userid', $sql, $courseparams);

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                      JOIN {course_sections} c
                           ON bc.itemid = c.id
                     WHERE c.course = :courseid
                           AND bc.type = :typesection";

            $sectionparams = ['typesection' => 'section'] + $params;

            $userlist->add_from_sql('userid', $sql, $sectionparams);
        }

        if ($context instanceof \context_module) {
            $params = [
                'cmid' => $context->instanceid,
                'typeactivity' => 'activity'
            ];

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                     WHERE bc.itemid = :cmid
                           AND bc.type = :typeactivity";

            $userlist->add_from_sql('userid', $sql, $params);
        }
    }
644693
public function findFiltersForUserAndContext($context, $userId, $locale)
    {
        $filters = $this->filterRepository->findByUserAndContextAndLocale($locale, $context, $userId);
        array_walk(
            $filters,
            function(&$filter) use ($locale) {
                $filter = new Filter($filter, $locale);
            }
        );

        return $filters;
    }
391131
public static function get_users_in_context(userlist $userlist) {
        global $DB;

        $context = $userlist->get_context();

        if (!$context instanceof \context_course) {
            return;
        }

        $params = [
            'instanceid' => $context->instanceid
        ];

        $sql = "SELECT usermodified as userid
                  FROM {post}
                 WHERE module = 'notes'
                       AND courseid = :instanceid";

        $userlist->add_from_sql('userid', $sql, $params);

        $publishstates = [
            NOTES_STATE_PUBLIC,
            NOTES_STATE_SITE
        ];

        list($publishstatesql, $publishstateparams) = $DB->get_in_or_equal($publishstates, SQL_PARAMS_NAMED);
        $params += $publishstateparams;

        $sql = "SELECT userid
                  FROM {post}
                 WHERE module = 'notes'
                       AND courseid = :instanceid
                       AND publishstate {$publishstatesql}";

        $userlist->add_from_sql('userid', $sql, $params);
    }
537990
public function get_contexts_for_userid(int $userid) : contextlist_collection {
        $progress = static::get_log_tracer();

        $components = $this->get_component_list();
        $a = (object) [
            'total' => count($components),
            'progress' => 0,
            'component' => '',
            'datetime' => userdate(time()),
        ];
        $clcollection = new contextlist_collection($userid);

        $progress->output(get_string('trace:fetchcomponents', 'core_privacy', $a), 1);
        foreach ($components as $component) {
            $a->component = $component;
            $a->progress++;
            $a->datetime = userdate(time());
            $progress->output(get_string('trace:processingcomponent', 'core_privacy', $a), 2);
            $contextlist = $this->handled_component_class_callback($component, core_user_data_provider::class,
                'get_contexts_for_userid', [$userid]);
            if ($contextlist === null) {
                $contextlist = new local\request\contextlist();
            }

            // Each contextlist is tied to its respective component.
            $contextlist->set_component($component);

            // Add contexts that the component may not know about.
            // Example of these include activity completion which modules do not know about themselves.
            $contextlist = local\request\helper::add_shared_contexts_to_contextlist_for($userid, $contextlist);

            if (count($contextlist)) {
                $clcollection->add_contextlist($contextlist);
            }
        }
        $progress->output(get_string('trace:done', 'core_privacy'), 1);

        return $clcollection;
    }
1060388
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;
    }
748384
public static function get_contexts_for_userid(int $userid) : contextlist {
        $sql = "SELECT ctx.id
                  FROM {context} ctx
            INNER JOIN {cohort} c ON c.contextid = ctx.id
            INNER JOIN {cohort_members} cm ON cm.cohortid = c.id
                 WHERE cm.userid = :userid AND (ctx.contextlevel = :contextlevel1 OR ctx.contextlevel = :contextlevel2)";
        $params = [
            'userid'        => $userid,
            'contextlevel1' => CONTEXT_SYSTEM,
            'contextlevel2' => CONTEXT_COURSECAT,
        ];
        $contextlist = new contextlist();
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
579732
public static function get_users_in_context(userlist $userlist) {
        global $DB;

        $context = $userlist->get_context();

        if (!is_a($context, \context_user::class)) {
            return;
        }

        // Add user if any messagelist data exists.
        if ($DB->record_exists('messageinbound_messagelist', ['userid' => $context->instanceid])) {
            // Only using user context, so instance ID will be the only user ID.
            $userlist->add_user($context->instanceid);
        }

        // Add users based on userkey (since we also delete those).
        \core_userkey\privacy\provider::get_user_contexts_with_script($userlist, $context, 'messageinbound_handler');
    }