Get a list of unread messages for a user

@param   integer  $uid    User ID
@param   integer  $limit  Number of records to return
@return  mixed    False if errors, array on success
431274
public function getUnreadMessages($uid, $limit=null)
	{
		if (!$uid)
		{
			return array();
		}

		$r = $this->getTableName();
		$m = Message::blank()->getTableName();
		$s = Seen::blank()->getTableName();

		$entries = Message::all()
			->select($m . '.*,' . $r . '.expires,' . $r . '.actionid')
			//->join($m, $m . '.id', $r . '.mid', 'inner')
			->join($r, $m . '.id', $r . '.mid', 'inner')
			->whereEquals($r . '.uid', $uid)
			->where($r . '.state', '!=', 2)
			->whereRaw($m . ".id NOT IN (SELECT s.mid FROM `" . $s . "` AS s WHERE s.uid=" . $uid . ")")
			->order($r . '.created', 'desc');

		if ($limit)
		{
			$entries->limit($limit);
		}

		return $entries->rows();
	}
162192
public function getUniqueEmails($uid, $body = false)
    {
        Argument::i()
            ->test(1, 'int', 'string', 'array')
            ->test(2, 'bool');

        //if not connected
        if (!$this->socket) {
            //then connect
            $this->connect();
        }

        //if the total in this mailbox is 0
        //it means they probably didn't select a mailbox
        //or the mailbox selected is empty
        if ($this->total == 0) {
            //we might as well return an empty array
            return array();
        }

        //if uid is an array
        if (is_array($uid)) {
            $uid = implode(',', $uid);
        }

        //lets call it
        $items = array('UID', 'FLAGS', 'BODY[HEADER]');

        if ($body) {
            $items = array('UID', 'FLAGS', 'BODY[]');
        }

        $first = is_numeric($uid) ? true : false;

        return $this->getEmailResponse('UID FETCH', array($uid, $this->getList($items)), $first);
    }
298200
public function getPosts( $limit = 100 ) {

        return $this->parseGetPosts(
            $this->service->api( $this->getWallGetRequestUrl( $limit ), 'GET' ),
            'response',
            [
                'id',
                'text'
            ],
            [
                'service_id_author' => 'from_id',
                'service_id_post'   => 'id',
                'time_created'      => 'date',
                'content'           => 'text'
            ] );
    }
1087419
public function getRuleData($uid) {

        if (empty($this->ruleData) && !empty($uid)){

            $rule_data = $this->config['auth_cache'] ? Cache::get($this->getRuleKey($uid)) : [];


            if (empty($rule_data) || !is_array($rule_data)){

                $join = '__AUTH_RULE__ b';

                $where = [];
                $groups = $this->getRoleUser($uid);
                $where['a.role_id'] = ['in',$groups];

                $where['b.status'] = 1;

                $rule_data = Db::name('auth_access')->alias("a")
                    ->field('b.name,b.condition')
                    ->join($join,'a.rule_name = b.name')
                    ->where($where)
                    ->select();

                if (empty($rule_data)) return false;

                if ($this->config['auth_cache'])
                    Cache::set($this->getRuleKey($uid),$rule_data);

            }

            $this->ruleData = $rule_data;

        }

        return $this->ruleData;
    }
323103
protected function getUserInfo($uid) {
        static $userinfo=array();
        if(!isset($userinfo[$uid])){
             $userinfo[$uid] = Db::table($this->prefix.$this->_config['auth_user'])->where(array('uid'=>$uid))->find();
        }
        return $userinfo[$uid];
    }
350884
public static function isOverLimit($uID)
    {
        if (Config::get('concrete.user.private_messages.throttle_max') == 0) {
            return false;
        }
        if (Config::get('concrete.user.private_messages.throttle_max_timespan') == 0) {
            return false;
        }
        $db = Loader::db();
        $dt = new DateTime();
        $dt->modify('-'.Config::get('concrete.user.private_messages.throttle_max_timespan').' minutes');
        $v = array($uID, $dt->format('Y-m-d H:i:s'));
        $q = "SELECT COUNT(msgID) as sent_count FROM UserPrivateMessages WHERE uAuthorID = ? AND msgDateCreated >= ?";
        $count = $db->getOne($q, $v);

        if ($count > Config::get('concrete.user.private_messages.throttle_max')) {
            self::notifyAdmin($uID);

            return true;
        } else {
            return false;
        }
    }
1046710
public static function get_conversations_between_users(int $userid1, int $userid2,
                                                           int $limitfrom = 0, int $limitnum = 20) : array {

        global $DB;

        if ($userid1 == $userid2) {
            return array();
        }

        // Get all conversation where both user1 and user2 are members.
        // TODO: Add subname value. Waiting for definite table structure.
        $sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
                  FROM {message_conversations} mc
            INNER JOIN {message_conversation_members} mcm1
                    ON mc.id = mcm1.conversationid
            INNER JOIN {message_conversation_members} mcm2
                    ON mc.id = mcm2.conversationid
                 WHERE mcm1.userid = :userid1
                   AND mcm2.userid = :userid2
                   AND mc.enabled != 0
              ORDER BY mc.timecreated DESC";

        return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
    }
1175939
public function findOneByUidIgnoreHidden($uid)
    {
        $query = $this->createQuery();
        $query->getQuerySettings()->setIgnoreEnableFields(TRUE);
        //$query->getQuerySettings()->setRespectStoragePage(FALSE);

        $query->matching(
            $query->equals('uid', $uid )
        );

        return $query->execute()->getFirst();
    }
312082
public function index(User $user, $unread = false)
    {
        $notifications = [];
        $rows = $user->notifications;
        if ($unread) {
            $rows = $user->unreadNotifications;
        }

        foreach ($rows as $k => $notification) {
            $notifications[] = [
                'id'         => $notification->id,
                'created_at' => $notification->created_at->format('l d F H:i'),
                'type'       => $notification->type,
                'message'    => $notification->data['message'],
                'read_at'    => $notification->read_at,
                'user_id'    => $user->id,
            ];
        }

        return json_response($notifications);
    }
40489
public function delete_msg($uid){
    if ( $this->is_connected() ){
      return imap_delete($this->stream, $this->get_msg_no($uid));
    }
    return false;
  }
847815
static function fetchListForUser( $userID, $offset = false, $limit = false )
    {
        $objectList = eZPersistentObject::fetchObjectList( eZContentBrowseBookmark::definition(),
                                                            null,
                                                            array( 'user_id' => $userID ),
                                                            array( 'id' => 'desc' ),
                                                            array( 'offset' => $offset, 'length' => $limit ),
                                                            true );
        return $objectList;
    }
839038
public static function getById($uid)
    {    
		if ($uid == USER_ANONYMOUS) return new User\Anonymous();
        $fields = self::getDbConnection()->fetchAssoc( 'SELECT * FROM '.User::TABLE.' WHERE id = ?', array( $uid ) );
        if (!$fields) throw new \Exception('User:'.$uid.' is not found'); 
        return self::fetch($fields);    
  	}
1302070
public function findContentByUid($uid)
    {
        $results = $this->findContentsByUids(array($uid));
        if (0 < count($results)) {
            return reset($results);
        }

        return;
    }
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;
    }
1341863
public function getRawMessage($cb, $uid, $byUid = true)
    {
        $this->onResponse->push($cb);
        $this->fetch(['FLAGS', 'BODY[]'], $uid, null, $byUid, self::TAG_GETRAWMESSAGE);
    }
173686
public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 20) : array {
        global $CFG, $DB;

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

        // Used to search for contacts.
        $fullname = $DB->sql_fullname();

        // Users not to include.
        $excludeusers = array($CFG->siteguest);
        if (!$selfconversation = self::get_self_conversation($userid)) {
            // Userid should only be excluded when she hasn't a self-conversation.
            $excludeusers[] = $userid;
        }
        list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);

        $params = array('search' => '%' . $DB->sql_like_escape($search) . '%', 'userid1' => $userid, 'userid2' => $userid);

        // Ok, let's search for contacts first.
        $sql = "SELECT u.id
                  FROM {user} u
                  JOIN {message_contacts} mc
                    ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
                 WHERE u.deleted = 0
                   AND u.confirmed = 1
                   AND " . $DB->sql_like($fullname, ':search', false) . "
                   AND u.id $exclude
              ORDER BY " . $DB->sql_fullname();
        $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);

        $contacts = [];
        if (!empty($foundusers)) {
            $contacts = helper::get_member_info($userid, array_keys($foundusers));
            foreach ($contacts as $memberuserid => $memberinfo) {
                $contacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0, 1000);
            }
        }

        // Let's get those non-contacts.
        // Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
        // and stop once we have enough matching the 'visible' criteria.
        // TODO: MDL-63983 - Improve the performance of non-contact searches when site-wide messaging is disabled (default).

        // Use a local generator to achieve this iteration.
        $getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use($fullname, $exclude, $params, $excludeparams) {
            global $DB;
            $sql = "SELECT u.*
                  FROM {user} u
                 WHERE u.deleted = 0
                   AND u.confirmed = 1
                   AND " . $DB->sql_like($fullname, ':search', false) . "
                   AND u.id $exclude
                   AND NOT EXISTS (SELECT mc.id
                                     FROM {message_contacts} mc
                                    WHERE (mc.userid = u.id AND mc.contactid = :userid1)
                                       OR (mc.userid = :userid2 AND mc.contactid = u.id))
              ORDER BY " . $DB->sql_fullname();
            while ($records = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum)) {
                yield $records;
                $limitfrom += $limitnum;
            }
        };

        // Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
        // The generator cannot function without a sensible limiter, so set one if this is not set.
        $batchlimit = ($limitnum == 0) ? 20 : $limitnum;

        // We need to make the offset param work with the generator.
        // Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
        // those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
        // position within those valid records ourselves.
        // See MDL-63983 dealing with performance improvements to this area of code.
        $noofvalidseenrecords = 0;
        $returnedusers = [];
        foreach ($getnoncontactusers(0, $batchlimit) as $users) {
            foreach ($users as $id => $user) {
                // User visibility checks: only return users who are visible to the user performing the search.
                // Which visibility check to use depends on the 'messagingallusers' (site wide messaging) setting:
                // - If enabled, return matched users whose profiles are visible to the current user anywhere (site or course).
                // - If disabled, only return matched users whose course profiles are visible to the current user.
                $userdetails = \core_message\helper::search_get_user_details($user);

                // Return the user only if the searched field is returned.
                // Otherwise it means that the $USER was not allowed to search the returned user.
                if (!empty($userdetails) and !empty($userdetails['fullname'])) {
                    // We know we've matched, but only save the record if it's within the offset area we need.
                    if ($limitfrom == 0) {
                        // No offset specified, so just save.
                        $returnedusers[$id] = $user;
                    } else {
                        // There is an offset in play.
                        // If we've passed enough records already (> offset value), then we can save this one.
                        if ($noofvalidseenrecords >= $limitfrom) {
                            $returnedusers[$id] = $user;
                        }
                    }
                    if (count($returnedusers) == $limitnum) {
                        break 2;
                    }
                    $noofvalidseenrecords++;
                }
            }
        }
        $foundusers = $returnedusers;

        $noncontacts = [];
        if (!empty($foundusers)) {
            $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
            foreach ($noncontacts as $memberuserid => $memberinfo) {
                if ($memberuserid !== $userid) {
                    $noncontacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0,
                        1000);
                } else {
                    $noncontacts[$memberuserid]->conversations[$selfconversation->id] = $selfconversation;
                }
            }
        }

        return array(array_values($contacts), array_values($noncontacts));
    }
134618
public function getUserFeed($limit = 0)
    {
        $params = array();
        if ($limit > 0) {
            $params['count'] = $limit;
        }

        return $this->_makeCall('users/self/feed', true, $params);
    }