Returns the count of unread conversations (collection of messages from a single user) for
the given user.

@param \stdClass $user the user who's conversations should be counted
@return int the count of the user's unread conversations
429112
public static function count_unread_conversations($user = null) {
        global $USER, $DB;

        if (empty($user)) {
            $user = $USER;
        }

        $sql = "SELECT COUNT(DISTINCT(m.conversationid))
                  FROM {messages} m
            INNER JOIN {message_conversations} mc
                    ON m.conversationid = mc.id
            INNER JOIN {message_conversation_members} mcm
                    ON mc.id = mcm.conversationid
             LEFT JOIN {message_user_actions} mua
                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
                 WHERE mcm.userid = ?
                   AND mc.enabled = ?
                   AND mcm.userid != m.useridfrom
                   AND mua.id is NULL";

        return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id,
            self::MESSAGE_CONVERSATION_ENABLED]);
    }
1001935
public function countUserFinishedPapers(Exercise $exercise, User $user)
    {
        return (int) $this->getEntityManager()
            ->createQuery('
                SELECT COUNT(p)
                FROM UJM\ExoBundle\Entity\Attempt\Paper AS p
                WHERE p.user = :user
                  AND p.exercise = :exercise
                  AND p.end IS NOT NULL
            ')
            ->setParameters([
                'user' => $user,
                'exercise' => $exercise,
            ])
            ->getSingleScalarResult();
    }
1131959
public function get_from_user_and_posts(stdClass $user, array $posts) {
        $postids = array_map(function($post) {
            return $post->get_id();
        }, $posts);
        return $this->get_from_user_id_and_post_ids($user->id, $postids);
    }
113609
public function getConversation(Message $message, User $user)
    {
        return $this->messageRepo->findAncestors($message, $user);
    }
491879
protected function getUser($user)
    {
        $userClass = $this->checkUserClass();
        if (is_numeric($user)) {
            $user = $userClass::find()->id($user)->one();
        } elseif (is_string($user) && strlen($user)) {
            $user = $userClass::find()->guid($user)->one();
        }
        if (!$user || $user->getIsNewRecord()) {
            throw new Exception('User Not Registered.');
        }
        return $user;
    }
627482
public function getUnreadMessagesCount($uid)
	{
		if (!$uid)
		{
			return 0;
		}

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

		$entries = Message::blank()
			->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 . ")");

		return $entries->total();
	}
349550
protected function sync_unenrol(stdClass $tool) {
        global $DB;

        $ltiplugin = enrol_get_plugin('lti');

        if (!$this->should_sync_unenrol($tool->membersyncmode)) {
            return 0;
        }

        if (empty($this->currentusers)) {
            return 0;
        }

        $unenrolcount = 0;

        $ltiusersrs = $DB->get_recordset('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC', 'userid');
        // Go through the users and check if any were never listed, if so, remove them.
        foreach ($ltiusersrs as $ltiuser) {
            if (!in_array($ltiuser->userid, $this->currentusers)) {
                $instance = new stdClass();
                $instance->id = $tool->enrolid;
                $instance->courseid = $tool->courseid;
                $instance->enrol = 'lti';
                $ltiplugin->unenrol_user($instance, $ltiuser->userid);
                // Increment unenrol count.
                $unenrolcount++;
            }
        }
        $ltiusersrs->close();

        return $unenrolcount;
    }
619296
public function trash($user)
    {
        return MessageNotification::where('user_id', $user->getKey())
            ->where('message_id', $this->id)
            ->delete();
    }
684101
public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
        global $DB;

        $userfields = \user_picture::fields('u', array('lastaccess'));
        $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
                              FROM {user} u
                        INNER JOIN {messages} m
                                ON m.useridfrom = u.id
                        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 = ? AND mua.action = ?)
                         LEFT JOIN {message_contacts} mc
                                ON (mc.userid = ? AND mc.contactid = u.id)
                         LEFT JOIN {message_users_blocked} mub
                                ON (mub.userid = ? AND mub.blockeduserid = u.id)
                             WHERE mcm.userid = ?
                               AND mcm.userid != m.useridfrom
                               AND mua.id is NULL
                               AND mub.id is NULL
                               AND mc.id is NULL
                               AND u.deleted = 0
                          GROUP BY $userfields";

        return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
            $limitfrom, $limitnum);
    }
144148
public function count($type = FALSE)
  {   
	$count = 0;
	
	$messages = $this->_session_get();
	
	if (is_array($messages)){
	
		if ($type === FALSE)
		{
			$count = count($messages);
		}
		else {
			
			foreach($messages as $message){
				
				if ($message->type == $type){
					
					$count++;
				}
			}
			
		}
	}
		
	return $count;
  }
572656
public static function getEmptyBlames($user)
    {
        $blames = static::getAllBlames($user);
        $emptyGroups = [];
        $noInit = static::buildNoInitModel();
        foreach ($blames as $blame) {
            if (static::find()->createdBy($user)->
                    andWhere(['like', $noInit->multiBlamesAttribute, $blame->getGUID()])->exists()) {
                continue;
            }
            $emptyGroups[] = $blame;
        }
        return $emptyGroups;
    }
639149
def inbox_count_for(user):
    
    return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count()
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;
    }
158582
public function getQuestionnairesByUser(UserInterface $user)
    {
        $questionnaires = $this->createQueryBuilder('us')
            ->where('us.user = :user')
            ->setParameter('user', $user)
            ->getQuery()
            ->getResult();

        $resource = array();
        $now = new \DateTime();

        /** @var UserSessionInterface $questionnaire */
        foreach ($questionnaires as $questionnaire) {
            $configuration = $questionnaire->getConfiguration();

            if (!is_null($configuration->getEndAt())) {
                continue;
            }

            if ($configuration->getMaxQuestions() - $configuration->getQuestions()->count() == 0) {
                if (is_null($configuration->getStartAt()) || $configuration->getStartAt() <= $now) {
                    $resource[] = $questionnaire;
                }
            }
        }

        return $resource;
    }
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);
    }
372234
public function get_by_user(string $id_user){
    $cfg =& $this->class_cfg;
    // Current datetime
    $now = date('Y-m-d H:i:s');
    // Get the user's group
    $id_group = $this->db->select_one('bbn_users', 'id_group', ['id' => $id_user]);
    // Get all user's internal messages
    $messages = $this->db->get_rows("
      SELECT {$cfg['table']}.*
      FROM {$cfg['tables']['users']}
        RIGHT JOIN {$cfg['table']}
	        ON {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_user']}
	        AND {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']}
      WHERE (
        {$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL
        OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
      )
      AND (
        {$cfg['table']}.{$cfg['arch']['imessages']['end']} IS NULL
        OR {$cfg['table']}.{$cfg['arch']['imessages']['end']} > ?
      )
      AND (
        (
          {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = ?
          OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} = ?
        )
        OR (
          {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} IS NULL
          OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} IS NULL
        )
      )
      AND (
        {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} IS NULL
        OR {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} = 0
      )",
      $now,
      $now,
      hex2bin($id_user),
      hex2bin($id_group)
    );
    // Get and return the imessage's info from notes archive
    return $this->from_notes($messages);
  }
233355
public function getUserEntity($user)
    {
        if (is_numeric($user)) {
            $userEntity = $this->entityTypeManager
                ->getStorage('user')
                ->load($user);
        } else {
            $userEntities = $this->entityTypeManager
                ->getStorage('user')
                ->loadByProperties(['name' => $user]);
            $userEntity = reset($userEntities);
        }

        return $userEntity;
    }