Notification using browser API
Get array of UserMessage

@param int $from_user_id sender user id
@param int $to_user_id   recipient user id

@return array
351006
public static function receiveMessages(int $from_user_id, int $to_user_id = USER_ID): array
    {
        // Direction A -> B
        $message_collection = new UsersMessageEntityRepository();
        $messages = $message_collection
            ->setWhereFromUserId($from_user_id)
            ->setWhereToUserId($to_user_id)
            ->getAsArrayOfObjects();

        // Direction B -> A
        $message_collection = new UsersMessageEntityRepository();
        $message_collection
            ->setWhereFromUserId($to_user_id)
            ->setWhereToUserId($from_user_id);

        // Combine messages
        $messages = array_merge($messages, $message_collection
            ->getAsArrayOfObjects());

        // Sort by time
        usort($messages, function($a, $b) {
            /** @var UsersMessageEntity $a */
            /** @var UsersMessageEntity $b */
            $a = $a->getTs();
            $b = $b->getTs();

            if ($a === $b) {
                return 0;
            }

            return ($a < $b) ? 1 : -1;
        });

        return $messages;
    }
1013643
public function endpoint_sendmessage($to = NULL, $from = NULL, $body = NULL)
        {
            return $this->sendmessage($to, $from, $body);
        }
784242
public function getMessages()
    {
        $message = new IncomingMessage(Location::PATTERN, $this->event->get('ToUserName'), $this->event->get('FromUserName'),
            $this->event);
        $message->setLocation($this->getLocation());

        return [$message];
    }
1067117
protected function getDefaultMessage($from, $encoding, $to, $subject, $body) {
        if(is_string($from)) {
            $from = array('email' => $from, 'name' => $from);
        }

        $message = new MailMessage();
        $message->setFrom($from['email'], $from['name'])
            ->setEncoding($encoding)
            ->setSubject($subject)
            ->setBody($body)
            ->setTo($to);

        return $message;
    }
910866
public function GetNotifications($NotifyUserID, $Offset = '0', $Limit = '30') {
      $this->ActivityQuery(FALSE);
      $this->FireEvent('BeforeGetNotifications');
      $Result = $this->SQL
         ->Where('NotifyUserID', $NotifyUserID)
         ->Limit($Limit, $Offset)
         ->OrderBy('a.ActivityID', 'desc')
         ->Get();
      $Result->DatasetType(DATASET_TYPE_ARRAY);
      
      self::GetUsers($Result->ResultArray());
      Gdn::UserModel()->JoinUsers($Result->ResultArray(), array('ActivityUserID', 'RegardingUserID'), array('Join' => array('Name', 'Photo', 'Email', 'Gender')));
      $this->CalculateData($Result->ResultArray());
      
      return $Result;
   }
734867
public static function create_from_ids($userfromid, $usertoid, $notificationid) {
        // We may be sending a notification from the 'noreply' address, which means we are not actually sending a
        // notification from a valid user. In this case, we will set the userid to 0.
        // Check if the userid is valid.
        if (!\core_user::is_real_user($userfromid)) {
            $userfromid = 0;
        }

        // Get the context for the user who received the notification.
        $context = \context_user::instance($usertoid, IGNORE_MISSING);
        // If the user no longer exists the context value will be false, in this case use the system context.
        if ($context === false) {
            $context = \context_system::instance();
        }

        $event = self::create(
            [
                'objectid' => $notificationid,
                'userid' => $usertoid, // Using the user who read the notification as they are the ones performing the action.
                'context' => $context,
                'relateduserid' => $userfromid
            ]
        );

        return $event;
    }
1203282
protected function get_notifiable_users($userid) {
        // Potential users should be active users only.
        $potentialusers = get_enrolled_users($this->context, "mod/assign:receivegradernotifications",
                                             null, 'u.*', null, null, null, true);

        $notifiableusers = array();
        if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
            if ($groups = groups_get_all_groups($this->get_course()->id, $userid, $this->get_course_module()->groupingid)) {
                foreach ($groups as $group) {
                    foreach ($potentialusers as $potentialuser) {
                        if ($potentialuser->id == $userid) {
                            // Do not send self.
                            continue;
                        }
                        if (groups_is_member($group->id, $potentialuser->id)) {
                            $notifiableusers[$potentialuser->id] = $potentialuser;
                        }
                    }
                }
            } else {
                // User not in group, try to find graders without group.
                foreach ($potentialusers as $potentialuser) {
                    if ($potentialuser->id == $userid) {
                        // Do not send self.
                        continue;
                    }
                    if (!groups_has_membership($this->get_course_module(), $potentialuser->id)) {
                        $notifiableusers[$potentialuser->id] = $potentialuser;
                    }
                }
            }
        } else {
            foreach ($potentialusers as $potentialuser) {
                if ($potentialuser->id == $userid) {
                    // Do not send self.
                    continue;
                }
                // Must be enrolled.
                if (is_enrolled($this->get_course_context(), $potentialuser->id)) {
                    $notifiableusers[$potentialuser->id] = $potentialuser;
                }
            }
        }
        return $notifiableusers;
    }
54969
public function getNotificationFeed($user_id)
    {
        $user_feed = $this->config->get("stream-laravel::notification_feed");
        return $this->client->feed($user_feed, $user_id);
    }
413809
public static function get_user_message_preferences($userid = 0) {
        global $CFG, $PAGE;

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

        $user = self::validate_preferences_permissions($params['userid']);

        // Filter out enabled, available system_configured and user_configured processors only.
        $readyprocessors = array_filter(get_message_processors(), function($processor) {
            return $processor->enabled &&
                $processor->configured &&
                $processor->object->is_user_configured() &&
                // Filter out processors that don't have and message preferences to configure.
                $processor->object->has_message_preferences();
        });

        $providers = array_filter(message_get_providers_for_user($user->id), function($provider) {
            return $provider->component === 'moodle';
        });
        $preferences = \core_message\api::get_all_message_preferences($readyprocessors, $providers, $user);
        $notificationlistoutput = new \core_message\output\preferences\message_notification_list($readyprocessors,
            $providers, $preferences, $user);

        $renderer = $PAGE->get_renderer('core_message');

        $entertosend = get_user_preferences('message_entertosend', $CFG->messagingdefaultpressenter, $user);

        $result = array(
            'warnings' => array(),
            'preferences' => $notificationlistoutput->export_for_template($renderer),
            'blocknoncontacts' => \core_message\api::get_user_privacy_messaging_preference($user->id),
            'entertosend' => $entertosend
        );
        return $result;
    }
78779
public function notify($to, $message)
    {
        $params = [
            'token'   => $this->config['token'],
            'user'    => $to,
            'device'  => Arr::get($this->config, 'device', ''),
            'title'   => Arr::get($this->config, 'title', ''),
            'message' => $message,
        ];

        if (isset($this->config['sound'])) {
            $params['sound'] = in_array($this->config['sound'], $this->allowedSounds) ? $$this->config['sound'] : 'pushover';
        }

        return $this->send($this->buildUrlFromString('messages.json'), $params);
    }
479145
public static function messageuser_link_params(int $useridto) : array {
        global $USER;

        return [
            'id' => 'message-user-button',
            'role' => 'button',
            'data-conversationid' => api::get_conversation_between_users([$USER->id, $useridto]),
            'data-userid' => $useridto,
        ];
    }
198623
private function get_notifications(stdClass $user, ?int $groupid) : array {
        $notifications = $this->notifications;
        $forum = $this->forum;
        $renderer = $this->renderer;
        $capabilitymanager = $this->capabilitymanager;

        if ($forum->is_cutoff_date_reached()) {
            $notifications[] = (new notification(
                    get_string('cutoffdatereached', 'forum'),
                    notification::NOTIFY_INFO
            ))->set_show_closebutton();
        } else if ($forum->is_due_date_reached()) {
            $notifications[] = (new notification(
                    get_string('thisforumisdue', 'forum', userdate($forum->get_due_date())),
                    notification::NOTIFY_INFO
            ))->set_show_closebutton();
        } else if ($forum->has_due_date()) {
            $notifications[] = (new notification(
                    get_string('thisforumhasduedate', 'forum', userdate($forum->get_due_date())),
                    notification::NOTIFY_INFO
            ))->set_show_closebutton();
        }

        if ($forum->has_blocking_enabled()) {
            $notifications[] = (new notification(
                get_string('thisforumisthrottled', 'forum', [
                    'blockafter' => $forum->get_block_after(),
                    'blockperiod' => get_string('secondstotime' . $forum->get_block_period())
                ])
            ))->set_show_closebutton();
        }

        if ($forum->is_in_group_mode() && !$capabilitymanager->can_access_all_groups($user)) {
            if ($groupid === null) {
                if (!$capabilitymanager->can_post_to_my_groups($user)) {
                    $notifications[] = (new notification(
                        get_string('cannotadddiscussiongroup', 'mod_forum'),
                        \core\output\notification::NOTIFY_WARNING
                    ))->set_show_closebutton();
                } else {
                    $notifications[] = (new notification(
                        get_string('cannotadddiscussionall', 'mod_forum'),
                        \core\output\notification::NOTIFY_WARNING
                    ))->set_show_closebutton();
                }
            } else if (!$capabilitymanager->can_access_group($user, $groupid)) {
                $notifications[] = (new notification(
                    get_string('cannotadddiscussion', 'mod_forum'),
                    \core\output\notification::NOTIFY_WARNING
                ))->set_show_closebutton();
            }
        }

        if ('qanda' === $forum->get_type() && !$capabilitymanager->can_manage_forum($user)) {
            $notifications[] = (new notification(
                get_string('qandanotify', 'forum'),
                notification::NOTIFY_INFO
            ))->set_show_closebutton();
        }

        if ('eachuser' === $forum->get_type()) {
            $notifications[] = (new notification(
                get_string('allowsdiscussions', 'forum'),
                notification::NOTIFY_INFO)
            )->set_show_closebutton();
        }

        return array_map(function($notification) {
            return $notification->export_for_template($this->renderer);
        }, $notifications);
    }
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);
    }
170142
public function message($from, $to, $body, $type = 'chat', $style='', $timestamp = null) {
        if(!$timestamp) $timestamp = microtime(true) * 1000;
		$data = array_merge($this->reqdata(), array(
			'nick' => $this->endpoint->nick,
			'to' => $to,
			'type' => $type,
			'body' => $body,
			'style' => $style,
			'timestamp' => $timestamp,
		));
        if($from) $data['from'] = $from;
		return $this->request('messages', $data, 'POST');
	}
1096952
public function transferRoles(User $from, User $to)
    {
        $roles = $from->getEntityRoles();

        foreach ($roles as $role) {
            $to->addRole($role);
        }

        $this->objectManager->flush();

        return count($roles);
    }
676236
protected static function createMessage(string $to, string $subject, string $from = 'default'): Swift_Message
    {
        $fromName = $from === 'default' ? self::$config['from']['default'] : $from;
        $from     = self::$config['from'][$fromName];

        return (new Swift_Message())
            ->setContentType('text/html')
            ->setSubject($subject)
            ->setFrom([$from['address'] => $from['name']])
            ->setTo($to)
            ;
    }
1234415
public function getRecipientsFromPost(array $referenced_entity) {
    $recipients = [];

    $post = Post::load($referenced_entity['target_id']);
    $recipient_user = $post->get('field_recipient_user')->getValue();
    if (!empty($recipient_user)) {
      $recipients[] = [
        'target_type' => 'user',
        'target_id' => $recipient_user['0']['target_id'],
      ];
    }

    return $recipients;
  }