Returns an array of unique conversations that require processing.

@param int $userid The ID of the user we are sending a digest to.
@return moodle_recordset A moodle_recordset instance.
965428
private function get_conversations_for_user(int $userid) : moodle_recordset {
        global $DB;

        // We shouldn't be joining directly on the group table as group
        // conversations may (in the future) be something created that
        // isn't related to an actual group in a course. However, for
        // now this will have to do before 3.7 code freeze.
        // See related MDL-63814.
        $sql = "SELECT DISTINCT mc.id, mc.name, c.id as courseid, c.fullname as coursename, g.id as groupid,
                                g.picture, g.hidepicture
                  FROM {message_conversations} mc
                  JOIN {groups} g
                    ON mc.itemid = g.id
                  JOIN {course} c
                    ON g.courseid = c.id
                  JOIN {message_email_messages} mem
                    ON mem.conversationid = mc.id
                 WHERE mem.useridto = ?
                   AND mem.id <= ?";

        return $DB->get_recordset_sql($sql, [$userid, $this->maxid]);
    }
1327344
public function getConversationMessageById($conversationId, $userID, $channel)
    {
        $conversation = $this->query()->with(['messages', 'messages.sender', 'messages.files', 'firstUser', 'secondUser', 'files'])->find($conversationId);

        $collection = (object) null;
        $collection->conversationId = $conversationId;
        $collection->channel_name = $channel;
        $collection->user = ($conversation->firstUser->id == $userID) ? $conversation->secondUser : $conversation->firstUser;
        $collection->messages = $conversation->messages;
        $collection->files = $conversation->files;

        return collect($collection);
    }
330536
public static function mark_all_conversation_messages_as_read(int $userid, int $conversationid) {
        global $CFG;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $params = array(
            'userid' => $userid,
            'conversationid' => $conversationid,
        );
        $params = self::validate_parameters(self::mark_all_conversation_messages_as_read_parameters(), $params);

        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        if (\core_message\api::can_mark_all_messages_as_read($params['userid'], $params['conversationid'])) {
            \core_message\api::mark_all_messages_as_read($params['userid'], $params['conversationid']);
        } else {
            throw new moodle_exception('accessdenied', 'admin');
        }
    }
1110085
public static function unmute_conversations(int $userid, array $conversationids) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = ['userid' => $userid, 'conversationids' => $conversationids];
        $params = self::validate_parameters(self::unmute_conversations_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        foreach ($params['conversationids'] as $conversationid) {
            \core_message\api::unmute_conversation($params['userid'], $conversationid);
        }

        return [];
    }
635565
public static function get_contexts_for_userid(int $userid) : contextlist {
        list($join, $where, $params) = \core_completion\privacy\provider::get_course_completion_join_sql($userid, 'cc', 'c.id');
        $sql = "SELECT ctx.id
                FROM {context} ctx
                JOIN {course} c ON ctx.instanceid = c.id AND ctx.contextlevel = :contextcourse
                {$join}
                WHERE {$where}";
        $params['contextcourse'] = CONTEXT_COURSE;
        $contextlist = new contextlist();
        $contextlist->add_from_sql($sql, $params);

        \core_favourites\privacy\provider::add_contexts_for_userid($contextlist, $userid, 'core_course', 'courses');

        return $contextlist;
    }
859877
public static function get_contexts_for_userid(int $userid) : contextlist {
        global $DB;

        $contextlist = new contextlist();

        $publishstates = [
            NOTES_STATE_PUBLIC,
            NOTES_STATE_SITE
        ];
        list($publishstatesql, $publishstateparams) = $DB->get_in_or_equal($publishstates, SQL_PARAMS_NAMED);

        // Retrieve all the Course contexts associated with notes written by the user, and also written about the user.
        // Only notes written about the user that are public or site wide will be exported.
        $sql = "SELECT c.id
                  FROM {context} c
            INNER JOIN {post} p ON p.courseid = c.instanceid AND c.contextlevel = :contextcoursewrittenby
                 WHERE p.module = 'notes'
                   AND p.usermodified = :usermodified
                 UNION
                SELECT c.id
                  FROM {context} c
            INNER JOIN {post} p ON p.courseid = c.instanceid AND c.contextlevel = :contextcoursewrittenfor
                 WHERE p.module = 'notes'
                   AND p.userid = :userid
                   AND p.publishstate {$publishstatesql}";

        $params = [
            'contextcoursewrittenby'  => CONTEXT_COURSE,
            'usermodified'            => $userid,
            'contextcoursewrittenfor' => CONTEXT_COURSE,
            'userid'                  => $userid
        ];
        $params += $publishstateparams;

        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
1171121
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;
    }
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;
    }
68599
public function retrieveAll($userId)
    {
        if (!isset($this->userMeta[$userId])) {
            $data                    = $this->getModel()->where('user_id', '=', $userId)->get();
            $this->userMeta[$userId] = $this->processRetrievedData($userId, $data);
        }
        return Arr::get($this->userMeta, $userId);
    }
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;
    }
1043512
public static function getSessionWithUserId($userid)
	{
		// get list of all sessions
		$sessions = \App::get('session')->getStore()->all(array(
			'guest'    => 0,
			'distinct' => 1
		));

		// see if any session matches our userid
		foreach ($sessions as $session)
		{
			if ($session->userid == $userid)
			{
				return $session;
			}
		}

		// nothing found
		return null;
	}
1064817
public static function get_conversation_counts(int $userid) : array {
        global $DB;

        // Some restrictions we need to be aware of:
        // - Individual conversations containing soft-deleted user must be counted.
        // - Individual conversations containing only deleted messages must NOT be counted.
        // - Self-conversations with 0 messages must be counted.
        // - Self-conversations containing only deleted messages must NOT be counted.
        // - Group conversations with 0 messages must be counted.
        // - Linked conversations which are disabled (enabled = 0) must NOT be counted.
        // - Any type of conversation can be included in the favourites count, however, the type counts and the favourites count
        // are mutually exclusive; any conversations which are counted in favourites cannot be counted elsewhere.

        // First, ask the favourites service to give us the join SQL for favourited conversations,
        // so we can include favourite information in the query.
        $usercontext = \context_user::instance($userid);
        $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
        list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_message', 'message_conversations', 'fav', 'mc.id');

        $sql = "SELECT mc.type, fav.itemtype, COUNT(DISTINCT mc.id) as count, MAX(maxvisibleconvmessage.convid) as maxconvidmessage
                  FROM {message_conversations} mc
            INNER JOIN {message_conversation_members} mcm
                    ON mcm.conversationid = mc.id
             LEFT JOIN (
                              SELECT m.conversationid as convid, MAX(m.timecreated) as maxtime
                                FROM {messages} m
                          INNER JOIN {message_conversation_members} mcm
                                  ON mcm.conversationid = m.conversationid
                           LEFT JOIN {message_user_actions} mua
                                  ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
                               WHERE mua.id is NULL
                                 AND mcm.userid = :userid2
                            GROUP BY m.conversationid
                       ) maxvisibleconvmessage
                    ON maxvisibleconvmessage.convid = mc.id
               $favsql
                 WHERE mcm.userid = :userid3
                   AND mc.enabled = :enabled
                   AND (
                          (mc.type = :individualtype AND maxvisibleconvmessage.convid IS NOT NULL) OR
                          (mc.type = :grouptype) OR
                          (mc.type = :selftype)
                       )
              GROUP BY mc.type, fav.itemtype
              ORDER BY mc.type ASC";

        $params = [
            'userid' => $userid,
            'userid2' => $userid,
            'userid3' => $userid,
            'userid4' => $userid,
            'userid5' => $userid,
            'action' => self::MESSAGE_ACTION_DELETED,
            'enabled' => self::MESSAGE_CONVERSATION_ENABLED,
            'individualtype' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
            'grouptype' => self::MESSAGE_CONVERSATION_TYPE_GROUP,
            'selftype' => self::MESSAGE_CONVERSATION_TYPE_SELF,
        ] + $favparams;

        // Assemble the return array.
        $counts = [
            'favourites' => 0,
            'types' => [
                self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
                self::MESSAGE_CONVERSATION_TYPE_GROUP => 0,
                self::MESSAGE_CONVERSATION_TYPE_SELF => 0
            ]
        ];

        // For the self-conversations, get the total number of messages (to know if the conversation is new or it has been emptied).
        $selfmessagessql = "SELECT COUNT(m.id)
                              FROM {messages} m
                        INNER JOIN {message_conversations} mc
                                ON mc.id = m.conversationid
                             WHERE mc.type = ? AND convhash = ?";
        $selfmessagestotal = $DB->count_records_sql(
            $selfmessagessql,
            [self::MESSAGE_CONVERSATION_TYPE_SELF, helper::get_conversation_hash([$userid])]
        );

        $countsrs = $DB->get_recordset_sql($sql, $params);
        foreach ($countsrs as $key => $val) {
            // Empty self-conversations with deleted messages should be excluded.
            if ($val->type == self::MESSAGE_CONVERSATION_TYPE_SELF && empty($val->maxconvidmessage) && $selfmessagestotal > 0) {
                continue;
            }
            if (!empty($val->itemtype)) {
                $counts['favourites'] += $val->count;
                continue;
            }
            $counts['types'][$val->type] = $val->count;
        }
        $countsrs->close();

        return $counts;
    }
528276
public static function delete_conversations_by_id($userid, array $conversationids) {
        global $CFG;

        // Check if private messaging between users is allowed.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate params.
        $params = [
            'userid' => $userid,
            'conversationids' => $conversationids,
        ];
        $params = self::validate_parameters(self::delete_conversations_by_id_parameters(), $params);

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        foreach ($params['conversationids'] as $conversationid) {
            if (\core_message\api::can_delete_conversation($user->id, $conversationid)) {
                \core_message\api::delete_conversation_by_id($user->id, $conversationid);
            } else {
                throw new moodle_exception("You do not have permission to delete the conversation '$conversationid'");
            }
        }

        return [];
    }
1063137
public function setHasRespondents($userId)
    {
        if (! $this->_get('gor_has_respondents')) {
            $values['gor_has_respondents'] = 1;
            $values['gor_changed']         = new \MUtil_Db_Expr_CurrentTimestamp();
            $values['gor_changed_by']      = $userId;

            $where = $this->db->quoteInto('gor_id_organization = ?', $this->_id);

            $this->db->update('gems__organizations', $values, $where);

            // Invalidate cache / change value
            $this->_set('gor_has_respondents', 1);
        }

        return $this;
    }
542901
public function getUserVoted($userId)
    {
        return (new Query())->from('{{%podium_poll_vote}}')->where([
            'poll_id' => $this->id,
            'caster_id' => $userId
        ])->count('id') ? true : false;
    }
384784
public function participantsUserIds($userId = null)
    {
        $users = $this->participants()->lists('user_id');

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

        return $users;
    }
1018539
public static function get_contexts_for_userid(int $userid) : contextlist {
        $contextlist = new contextlist();

        $contextlist->add_from_sql('SELECT ctx.id
            FROM {modules} m
            JOIN {course_modules} cm ON cm.module = m.id AND m.name = :modname
            JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :contextlevel
            JOIN {wiki_subwikis} s ON cm.instance = s.wikiid
            LEFT JOIN {wiki_pages} p ON p.subwikiid = s.id
            LEFT JOIN {wiki_versions} v ON v.pageid = p.id AND v.userid = :userid3
            LEFT JOIN {wiki_locks} l ON l.pageid = p.id AND l.userid = :userid4
            LEFT JOIN {comments} com ON com.itemid = p.id AND com.commentarea = :commentarea
                AND com.contextid = ctx.id AND com.userid = :userid5
            WHERE s.userid = :userid1 OR p.userid = :userid2 OR v.id IS NOT NULL OR l.id IS NOT NULL OR com.id IS NOT NULL',
            ['modname' => 'wiki', 'contextlevel' => CONTEXT_MODULE, 'userid1' => $userid, 'userid2' => $userid,
                'userid3' => $userid, 'userid4' => $userid, 'commentarea' => 'wiki_page', 'userid5' => $userid]);

        return $contextlist;
    }