@param string $context_name
@param UserInterface $userid

@return DefaultResourceContext
325017
protected function findContextByUser($context_name = 'default', $user = null)
    {
        $context_full_name = strtolower($user->getUsername()) . '_' . strtolower($context_name);

        /* @var $context DefaultResourceContext */
        $context = $this->findOneOrNullBy(array('name' => $context_full_name));

        if (is_null($context)) {
            $context = $this->createNewInstance();
            $context->setName($context_full_name);
            $context->setTitle($context_name);
            $this->persist($context);
        }

        return $context;
    }
768891
public function add_user_context(int $userid) : contextlist {
        $sql = "SELECT DISTINCT ctx.id
                  FROM {context} ctx
                 WHERE ctx.contextlevel = :contextlevel
                   AND ctx.instanceid = :instanceid";
        return $this->add_from_sql($sql, ['contextlevel' => CONTEXT_USER, 'instanceid' => $userid]);
    }
1361373
public static function add_contexts_for_userid(contextlist $contextlist, $userid) {
        $sql = "
            SELECT l.contextid
              FROM {logstore_standard_log} l
             WHERE l.userid = :userid1
                OR l.relateduserid = :userid2
                OR l.realuserid = :userid3";
        $contextlist->add_from_sql($sql, [
            'userid1' => $userid,
            'userid2' => $userid,
            'userid3' => $userid,
        ]);
    }
445468
protected static function export_user_data_in_module_contexts($userid, array $contexts) {
        global $DB;

        $contexts = array_filter($contexts, function($context) {
            return $context->contextlevel == CONTEXT_MODULE;
        });
        if (empty($contexts)) {
            return;
        }

        $path = [get_string('competencies', 'core_competency')];
        $cmids = array_map(function($context) {
            return $context->instanceid;
        }, $contexts);

        // Fetch all the modules with associations we created or modified.
        $compfields = competency::get_sql_fields('c', 'c_');
        $cmcfields = course_module_competency::get_sql_fields('cmc', 'cmc_');
        $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
        list($insql, $inparams) = $DB->get_in_or_equal($cmids, SQL_PARAMS_NAMED);
        $sql = "
            SELECT $compfields, $cmcfields, $ctxfields
              FROM {" . course_module_competency::TABLE . "} cmc
              JOIN {" . competency::TABLE . "} c
                ON c.id = cmc.competencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
              JOIN {context} ctx
                ON ctx.id = f.contextid
             WHERE cmc.usermodified = :userid
               AND cmc.cmid $insql
          ORDER BY cmc.cmid";
        $params = array_merge($inparams, ['userid' => $userid]);

        // Export the data.
        $recordset = $DB->get_recordset_sql($sql, $params);
        static::recordset_loop_and_export($recordset, 'cmc_cmid', [], function($carry, $record) {
            context_helper::preload_from_record($record);
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $cmc = new course_module_competency(null, course_module_competency::extract_record($record, 'cmc_'));
            $carry[] = array_merge(static::transform_competency_brief($competency), [
                'timecreated' => transform::datetime($cmc->get('timecreated')),
                'timemodified' => transform::datetime($cmc->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno(true)
            ]);
            return $carry;

        }, function($cmid, $data) use ($path) {
            $context = context_module::instance($cmid);
            writer::with_context($context)->export_data($path, (object) ['associations' => $data]);
        });
    }
750782
public static function set($user_id, $userEmail, $context_id) {
        global $CFG;
        $ct = self::create($user_id,$userEmail, $context_id);
        setcookie($CFG->cookiename,$ct,time() + (86400 * 45), '/'); // 86400 = 1 day
    }
503941
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;
    }
1105301
public function getResourceUserPermission(ResourceInterface $resource, UserInterface $user)
    {
        $query = $this->getRepository()->createQueryBuilder('r')
            ->select('r')
            ->where('r.resource_class = :resourceClass AND r.resource_id=:resourceId AND r.user=:user')
            ->setParameter('resourceClass', $resource->getClass())
            ->setParameter('resourceId', $resource->getId())
            ->setParameter('user', $user)
            ->getQuery();

        return $query->getOneOrNullResult();
    }
1047188
public static function get_contexts_for_userid(int $userid) : contextlist {
        global $DB;

        $contextlist = new \core_privacy\local\request\contextlist();

        $models = self::get_models_with_user_data();

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

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

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

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

        // We can leave this out of the loop as there is no analyser-dependent stuff.
        list($sql, $params) = self::analytics_prediction_actions_user_sql($userid, array_keys($models));
        $sql = "SELECT DISTINCT ap.contextid" . $sql;
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
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;
    }
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;
    }
614814
private function createBatch($userId)
    {
        $entity = new EBatch();
        $entity->setUserRef($userId);
        $result = $this->daoBatch->create($entity);
        return $result;
    }
1204317
protected function findContext($context_name = 'default')
    {
        $user = $this->getSecurityManager()->findAuthenticatedUser();

        $context = $this->findContextByUser($context_name, $user);

        return $context;
    }
423361
protected static function export_user_data_templates_in_context($userid, context $context) {
        global $DB;

        $tfields = template::get_sql_fields('t', 't_');
        $cfields = competency::get_sql_fields('c', 'c_');
        $tcfields = template_competency::get_sql_fields('tc', 'tc_');
        $tchfields = template_cohort::get_sql_fields('tch', 'tch_');

        $templates = [];
        $inittemplate = function($record) use (&$templates, $userid) {
            $template = new template(null, template::extract_record($record, 't_'));
            $templates[$template->get('id')] = array_merge(static::transform_template_brief($template), [
                'timemodified' => transform::datetime($template->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno($template->get('usermodified') == $userid),
                'competencies' => [],
                'cohorts' => []
            ]);
        };

        // Find the template competencies.
        $sql = "
            SELECT $tfields, $cfields, $tcfields
              FROM {" . template_competency::TABLE . "} tc
              JOIN {" . template::TABLE . "} t
                ON t.id = tc.templateid
              JOIN {" . competency::TABLE . "} c
                ON c.id = tc.competencyid
             WHERE t.contextid = :contextid
               AND tc.usermodified = :userid
          ORDER BY t.id, tc.id";
        $params = ['userid' => $userid, 'contextid' => $context->id];
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $templateid = $record->t_id;
            if (!isset($templates[$templateid])) {
                $inittemplate($record);
            }
            $tplcomp = new template_competency(null, template_competency::extract_record($record, 'tc_'));
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $templates[$templateid]['competencies'][] = array_merge(
                static::transform_competency_brief($competency),
                [
                    'timemodified' => transform::datetime($tplcomp->get('timemodified')),
                    'created_or_modified_by_you' => transform::yesno($tplcomp->get('usermodified') == $userid)
                ]
            );
        }
        $recordset->close();

        // Find the template cohorts.
        $sql = "
            SELECT $tfields, $tchfields, c.name AS cohortname
              FROM {" . template_cohort::TABLE . "} tch
              JOIN {" . template::TABLE . "} t
                ON t.id = tch.templateid
              JOIN {cohort} c
                ON c.id = tch.cohortid
             WHERE t.contextid = :contextid
               AND tch.usermodified = :userid
          ORDER BY t.id, tch.id";
        $params = ['userid' => $userid, 'contextid' => $context->id];
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $templateid = $record->t_id;
            if (!isset($templates[$templateid])) {
                $inittemplate($record);
            }
            $tplcohort = new template_cohort(null, template_cohort::extract_record($record, 'tch_'));
            $templates[$templateid]['cohorts'][] = [
                'name' => $record->cohortname,
                'timemodified' => transform::datetime($tplcohort->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno($tplcohort->get('usermodified') == $userid)
            ];
        }
        $recordset->close();

        // Find the modified templates which we haven't been found yet.
        $templateids = array_keys($templates);
        $insql = "IS NOT NULL";
        $inparams = [];
        if (!empty($templateids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($templateids, SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $tfields
              FROM {" . template::TABLE . "} t
             WHERE t.contextid = :contextid
               AND t.usermodified = :userid
               AND t.id $insql
          ORDER BY t.id";
        $params = array_merge($inparams, ['userid' => $userid, 'contextid' => $context->id]);
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $inittemplate($record);
        }
        $recordset->close();

        // Export all the things!
        writer::with_context($context)->export_related_data([get_string('competencies', 'core_competency')],
            'templates', (object) ['templates' => array_values($templates)]);
    }
1091997
public static function get_users_in_context(userlist $userlist) {

        $context = $userlist->get_context();
        if ($context->contextlevel != CONTEXT_MODULE) {
            return;
        }

        $params = [
            'modulename' => 'assign',
            'contextid' => $context->id,
            'contextlevel' => CONTEXT_MODULE
        ];

        $sql = "SELECT g.userid, g.grader
                  FROM {context} ctx
                  JOIN {course_modules} cm ON cm.id = ctx.instanceid
                  JOIN {modules} m ON m.id = cm.module AND m.name = :modulename
                  JOIN {assign} a ON a.id = cm.instance
                  JOIN {assign_grades} g ON a.id = g.assignment
                 WHERE ctx.id = :contextid AND ctx.contextlevel = :contextlevel";
        $userlist->add_from_sql('userid', $sql, $params);
        $userlist->add_from_sql('grader', $sql, $params);

        $sql = "SELECT o.userid
                  FROM {context} ctx
                  JOIN {course_modules} cm ON cm.id = ctx.instanceid
                  JOIN {modules} m ON m.id = cm.module AND m.name = :modulename
                  JOIN {assign} a ON a.id = cm.instance
                  JOIN {assign_overrides} o ON a.id = o.assignid
                 WHERE ctx.id = :contextid AND ctx.contextlevel = :contextlevel";
        $userlist->add_from_sql('userid', $sql, $params);

        $sql = "SELECT s.userid
                  FROM {context} ctx
                  JOIN {course_modules} cm ON cm.id = ctx.instanceid
                  JOIN {modules} m ON m.id = cm.module AND m.name = :modulename
                  JOIN {assign} a ON a.id = cm.instance
                  JOIN {assign_submission} s ON a.id = s.assignment
                 WHERE ctx.id = :contextid AND ctx.contextlevel = :contextlevel";
        $userlist->add_from_sql('userid', $sql, $params);

        $sql = "SELECT uf.userid
                  FROM {context} ctx
                  JOIN {course_modules} cm ON cm.id = ctx.instanceid
                  JOIN {modules} m ON m.id = cm.module AND m.name = :modulename
                  JOIN {assign} a ON a.id = cm.instance
                  JOIN {assign_user_flags} uf ON a.id = uf.assignment
                 WHERE ctx.id = :contextid AND ctx.contextlevel = :contextlevel";
        $userlist->add_from_sql('userid', $sql, $params);

        $sql = "SELECT um.userid
                  FROM {context} ctx
                  JOIN {course_modules} cm ON cm.id = ctx.instanceid
                  JOIN {modules} m ON m.id = cm.module AND m.name = :modulename
                  JOIN {assign} a ON a.id = cm.instance
                  JOIN {assign_user_mapping} um ON a.id = um.assignment
                 WHERE ctx.id = :contextid AND ctx.contextlevel = :contextlevel";
        $userlist->add_from_sql('userid', $sql, $params);

        manager::plugintype_class_callback('assignsubmission', self::ASSIGNSUBMISSION_USER_INTERFACE,
                'get_userids_from_context', [$userlist]);
        manager::plugintype_class_callback('assignfeedback', self::ASSIGNFEEDBACK_USER_INTERFACE,
                'get_userids_from_context', [$userlist]);
    }
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;
    }
1111653
public function load($userId)
    {
        try {
            return $this->innerGateway->load($userId);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
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);
    }