Merge branch 'MDL-63632-master' of git://github.com/andrewnicols/moodle
[moodle.git] / message / classes / api.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Contains class used to return information to display for the message area.
19  *
20  * @package    core_message
21  * @copyright  2016 Mark Nelson <markn@moodle.com>
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 namespace core_message;
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/lib/messagelib.php');
31 /**
32  * Class used to return information to display for the message area.
33  *
34  * @copyright  2016 Mark Nelson <markn@moodle.com>
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class api {
39     /**
40      * The action for reading a message.
41      */
42     const MESSAGE_ACTION_READ = 1;
44     /**
45      * The action for deleting a message.
46      */
47     const MESSAGE_ACTION_DELETED = 2;
49     /**
50      * The privacy setting for being messaged by anyone within courses user is member of.
51      */
52     const MESSAGE_PRIVACY_COURSEMEMBER = 0;
54     /**
55      * The privacy setting for being messaged only by contacts.
56      */
57     const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
59     /**
60      * The privacy setting for being messaged by anyone on the site.
61      */
62     const MESSAGE_PRIVACY_SITE = 2;
64     /**
65      * Handles searching for messages in the message area.
66      *
67      * @param int $userid The user id doing the searching
68      * @param string $search The string the user is searching
69      * @param int $limitfrom
70      * @param int $limitnum
71      * @return array
72      */
73     public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
74         global $DB;
76         // Get the user fields we want.
77         $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
78         $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
80         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
81                        m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
82                        mub2.id as userto_blocked
83                   FROM {messages} m
84             INNER JOIN {user} u
85                     ON u.id = m.useridfrom
86             INNER JOIN {message_conversations} mc
87                     ON mc.id = m.conversationid
88             INNER JOIN {message_conversation_members} mcm
89                     ON mcm.conversationid = m.conversationid
90             INNER JOIN {user} u2
91                     ON u2.id = mcm.userid
92              LEFT JOIN {message_users_blocked} mub
93                     ON (mub.blockeduserid = u.id AND mub.userid = ?)
94              LEFT JOIN {message_users_blocked} mub2
95                     ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
96              LEFT JOIN {message_user_actions} mua
97                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
98                  WHERE (m.useridfrom = ? OR mcm.userid = ?)
99                    AND m.useridfrom != mcm.userid
100                    AND u.deleted = 0
101                    AND u2.deleted = 0
102                    AND mua.id is NULL
103                    AND " . $DB->sql_like('smallmessage', '?', false) . "
104               ORDER BY timecreated DESC";
106         $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
108         // Convert the messages into searchable contacts with their last message being the message that was searched.
109         $conversations = array();
110         if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
111             foreach ($messages as $message) {
112                 $prefix = 'userfrom_';
113                 if ($userid == $message->useridfrom) {
114                     $prefix = 'userto_';
115                     // If it from the user, then mark it as read, even if it wasn't by the receiver.
116                     $message->isread = true;
117                 }
118                 $blockedcol = $prefix . 'blocked';
119                 $message->blocked = $message->$blockedcol ? 1 : 0;
121                 $message->messageid = $message->id;
122                 $conversations[] = helper::create_contact($message, $prefix);
123             }
124         }
126         return $conversations;
127     }
129     /**
130      * Handles searching for user in a particular course in the message area.
131      *
132      * @param int $userid The user id doing the searching
133      * @param int $courseid The id of the course we are searching in
134      * @param string $search The string the user is searching
135      * @param int $limitfrom
136      * @param int $limitnum
137      * @return array
138      */
139     public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
140         global $DB;
142         // Get all the users in the course.
143         list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
144         $sql = "SELECT u.*, mub.id as isblocked
145                   FROM {user} u
146                   JOIN ($esql) je
147                     ON je.id = u.id
148              LEFT JOIN {message_users_blocked} mub
149                     ON (mub.blockeduserid = u.id AND mub.userid = :userid)
150                  WHERE u.deleted = 0";
151         // Add more conditions.
152         $fullname = $DB->sql_fullname();
153         $sql .= " AND u.id != :userid2
154                   AND " . $DB->sql_like($fullname, ':search', false) . "
155              ORDER BY " . $DB->sql_fullname();
156         $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
158         // Convert all the user records into contacts.
159         $contacts = array();
160         if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
161             foreach ($users as $user) {
162                 $user->blocked = $user->isblocked ? 1 : 0;
163                 $contacts[] = helper::create_contact($user);
164             }
165         }
167         return $contacts;
168     }
170     /**
171      * Handles searching for user in the message area.
172      *
173      * @param int $userid The user id doing the searching
174      * @param string $search The string the user is searching
175      * @param int $limitnum
176      * @return array
177      */
178     public static function search_users($userid, $search, $limitnum = 0) {
179         global $CFG, $DB;
181         // Used to search for contacts.
182         $fullname = $DB->sql_fullname();
183         $ufields = \user_picture::fields('u', array('lastaccess'));
185         // Users not to include.
186         $excludeusers = array($userid, $CFG->siteguest);
187         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
189         // Ok, let's search for contacts first.
190         $contacts = array();
191         $sql = "SELECT $ufields, mub.id as isuserblocked
192                   FROM {user} u
193                   JOIN {message_contacts} mc
194                     ON u.id = mc.contactid
195              LEFT JOIN {message_users_blocked} mub
196                     ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
197                  WHERE mc.userid = :userid
198                    AND u.deleted = 0
199                    AND u.confirmed = 1
200                    AND " . $DB->sql_like($fullname, ':search', false) . "
201                    AND u.id $exclude
202               ORDER BY " . $DB->sql_fullname();
203         if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
204                 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
205             foreach ($users as $user) {
206                 $user->blocked = $user->isuserblocked ? 1 : 0;
207                 $contacts[] = helper::create_contact($user);
208             }
209         }
211         // Now, let's get the courses.
212         // Make sure to limit searches to enrolled courses.
213         $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
214         $courses = array();
215         // Really we want the user to be able to view the participants if they have the capability
216         // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
217         // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
218         // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
219         if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
220                 array('moodle/course:viewparticipants'))) {
221             foreach ($arrcourses as $course) {
222                 if (isset($enrolledcourses[$course->id])) {
223                     $data = new \stdClass();
224                     $data->id = $course->id;
225                     $data->shortname = $course->shortname;
226                     $data->fullname = $course->fullname;
227                     $courses[] = $data;
228                 }
229             }
230         }
232         // Let's get those non-contacts. Toast them gears boi.
233         // Note - you can only block contacts, so these users will not be blocked, so no need to get that
234         // extra detail from the database.
235         $noncontacts = array();
236         $sql = "SELECT $ufields
237                   FROM {user} u
238                  WHERE u.deleted = 0
239                    AND u.confirmed = 1
240                    AND " . $DB->sql_like($fullname, ':search', false) . "
241                    AND u.id $exclude
242                    AND u.id NOT IN (SELECT contactid
243                                       FROM {message_contacts}
244                                      WHERE userid = :userid)
245               ORDER BY " . $DB->sql_fullname();
246         if ($users = $DB->get_records_sql($sql,  array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
247                 0, $limitnum)) {
248             foreach ($users as $user) {
249                 $noncontacts[] = helper::create_contact($user);
250             }
251         }
253         return array($contacts, $courses, $noncontacts);
254     }
256     /**
257      * Returns the contacts and their conversation to display in the contacts area.
258      *
259      * ** WARNING **
260      * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
261      * to retrieve too much information in a single call will cause performance problems.
262      * ** WARNING **
263      *
264      * This function has specifically been altered to break each of the data sets it
265      * requires into separate database calls. This is to avoid the performance problems
266      * observed when attempting to join large data sets (e.g. the message tables and
267      * the user table).
268      *
269      * While it is possible to gather the data in a single query, and it may even be
270      * more efficient with a correctly tuned database, we have opted to trade off some of
271      * the benefits of a single query in order to ensure this function will work on
272      * most databases with default tunings and with large data sets.
273      *
274      * @param int $userid The user id
275      * @param int $limitfrom
276      * @param int $limitnum
277      * @return array
278      */
279     public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
280         global $DB;
282         // Get the last message from each conversation that the user belongs to.
283         $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
284                   FROM {messages} m
285             INNER JOIN (
286                           SELECT MAX(m.id) AS messageid
287                             FROM {messages} m
288                       INNER JOIN (
289                                       SELECT m.conversationid, MAX(m.timecreated) as maxtime
290                                         FROM {messages} m
291                                   INNER JOIN {message_conversation_members} mcm
292                                           ON mcm.conversationid = m.conversationid
293                                    LEFT JOIN {message_user_actions} mua
294                                           ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
295                                        WHERE mua.id is NULL
296                                          AND mcm.userid = :userid2
297                                     GROUP BY m.conversationid
298                                  ) maxmessage
299                                ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
300                          GROUP BY m.conversationid
301                        ) lastmessage
302                     ON lastmessage.messageid = m.id
303             INNER JOIN {message_conversation_members} mcm
304                     ON mcm.conversationid = m.conversationid
305             INNER JOIN {message_conversation_members} mcm2
306                     ON mcm2.conversationid = m.conversationid
307                  WHERE mcm.userid = m.useridfrom
308                    AND mcm.id != mcm2.id
309               ORDER BY m.timecreated DESC";
310         $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
311             'userid2' => $userid], $limitfrom, $limitnum);
313         $messages = [];
314         foreach ($messageset as $message) {
315             $messages[$message->id] = $message;
316         }
317         $messageset->close();
319         // If there are no messages return early.
320         if (empty($messages)) {
321             return [];
322         }
324         // We need to pull out the list of other users that are part of each of these conversations. This
325         // needs to be done in a separate query to avoid doing a join on the messages tables and the user
326         // tables because on large sites these tables are massive which results in extremely slow
327         // performance (typically due to join buffer exhaustion).
328         $otheruserids = array_map(function($message) use ($userid) {
329             return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
330         }, array_values($messages));
332         // Ok, let's get the other members in the conversations.
333         list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
334         $userfields = \user_picture::fields('u', array('lastaccess'));
335         $userssql = "SELECT $userfields
336                        FROM {user} u
337                       WHERE id $useridsql
338                         AND deleted = 0";
339         $otherusers = $DB->get_records_sql($userssql, $usersparams);
341         // If there are no other users (user may have been deleted), then do not continue.
342         if (empty($otherusers)) {
343             return [];
344         }
346         $contactssql = "SELECT contactid
347                           FROM {message_contacts}
348                          WHERE userid = ?
349                            AND contactid $useridsql";
350         $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
352         // Finally, let's get the unread messages count for this user so that we can add them
353         // to the conversation. Remember we need to ignore the messages the user sent.
354         $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
355                               FROM {messages} m
356                         INNER JOIN {message_conversations} mc
357                                 ON mc.id = m.conversationid
358                         INNER JOIN {message_conversation_members} mcm
359                                 ON m.conversationid = mcm.conversationid
360                          LEFT JOIN {message_user_actions} mua
361                                 ON (mua.messageid = m.id AND mua.userid = ? AND
362                                    (mua.action = ? OR mua.action = ?))
363                              WHERE mcm.userid = ?
364                                AND m.useridfrom != ?
365                                AND mua.id is NULL
366                           GROUP BY useridfrom';
367         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
368             $userid, $userid]);
370         // Get rid of the table prefix.
371         $userfields = str_replace('u.', '', $userfields);
372         $userproperties = explode(',', $userfields);
373         $arrconversations = array();
374         foreach ($messages as $message) {
375             $conversation = new \stdClass();
376             $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
377             $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
378             $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
380             // It's possible the other user was deleted, so, skip.
381             if (is_null($otheruser)) {
382                 continue;
383             }
385             // Add the other user's information to the conversation, if we have one.
386             foreach ($userproperties as $prop) {
387                 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
388             }
390             // Add the contact's information, if we have one.
391             $conversation->blocked = ($contact) ? $contact->blocked : null;
393             // Add the message information.
394             $conversation->messageid = $message->id;
395             $conversation->smallmessage = $message->smallmessage;
396             $conversation->useridfrom = $message->useridfrom;
398             // Only consider it unread if $user has unread messages.
399             if (isset($unreadcounts[$otheruserid])) {
400                 $conversation->isread = false;
401                 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
402             } else {
403                 $conversation->isread = true;
404             }
406             $arrconversations[$otheruserid] = helper::create_contact($conversation);
407         }
409         return $arrconversations;
410     }
412     /**
413      * Returns the contacts to display in the contacts area.
414      *
415      * @param int $userid The user id
416      * @param int $limitfrom
417      * @param int $limitnum
418      * @return array
419      */
420     public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
421         global $DB;
423         $contactids = [];
424         $sql = "SELECT mc.*
425                   FROM {message_contacts} mc
426                  WHERE mc.userid = ? OR mc.contactid = ?
427               ORDER BY timecreated DESC";
428         if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
429             foreach ($contacts as $contact) {
430                 if ($userid == $contact->userid) {
431                     $contactids[] = $contact->contactid;
432                 } else {
433                     $contactids[] = $contact->userid;
434                 }
435             }
436         }
438         if (!empty($contactids)) {
439             list($insql, $inparams) = $DB->get_in_or_equal($contactids);
441             $sql = "SELECT u.*, mub.id as isblocked
442                       FROM {user} u
443                  LEFT JOIN {message_users_blocked} mub
444                         ON u.id = mub.blockeduserid
445                      WHERE u.id $insql";
446             if ($contacts = $DB->get_records_sql($sql, $inparams)) {
447                 $arrcontacts = [];
448                 foreach ($contacts as $contact) {
449                     $contact->blocked = $contact->isblocked ? 1 : 0;
450                     $arrcontacts[] = helper::create_contact($contact);
451                 }
453                 return $arrcontacts;
454             }
455         }
457         return [];
458     }
460     /**
461      * Returns the an array of the users the given user is in a conversation
462      * with who are a contact and the number of unread messages.
463      *
464      * @param int $userid The user id
465      * @param int $limitfrom
466      * @param int $limitnum
467      * @return array
468      */
469     public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
470         global $DB;
472         $userfields = \user_picture::fields('u', array('lastaccess'));
473         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
474                               FROM {message_contacts} mc
475                         INNER JOIN {user} u
476                                 ON (u.id = mc.contactid OR u.id = mc.userid)
477                          LEFT JOIN {messages} m
478                                 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
479                          LEFT JOIN {message_conversation_members} mcm
480                                 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
481                          LEFT JOIN {message_user_actions} mua
482                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
483                          LEFT JOIN {message_users_blocked} mub
484                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
485                              WHERE mua.id is NULL
486                                AND mub.id is NULL
487                                AND (mc.userid = ? OR mc.contactid = ?)
488                                AND u.id != ?
489                                AND u.deleted = 0
490                           GROUP BY $userfields";
492         return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
493             $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
494     }
496     /**
497      * Returns the an array of the users the given user is in a conversation
498      * with who are not a contact and the number of unread messages.
499      *
500      * @param int $userid The user id
501      * @param int $limitfrom
502      * @param int $limitnum
503      * @return array
504      */
505     public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
506         global $DB;
508         $userfields = \user_picture::fields('u', array('lastaccess'));
509         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
510                               FROM {user} u
511                         INNER JOIN {messages} m
512                                 ON m.useridfrom = u.id
513                         INNER JOIN {message_conversation_members} mcm
514                                 ON mcm.conversationid = m.conversationid
515                          LEFT JOIN {message_user_actions} mua
516                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
517                          LEFT JOIN {message_contacts} mc
518                                 ON (mc.userid = ? AND mc.contactid = u.id)
519                          LEFT JOIN {message_users_blocked} mub
520                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
521                              WHERE mcm.userid = ?
522                                AND mcm.userid != m.useridfrom
523                                AND mua.id is NULL
524                                AND mub.id is NULL
525                                AND mc.id is NULL
526                                AND u.deleted = 0
527                           GROUP BY $userfields";
529         return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
530             $limitfrom, $limitnum);
531     }
533     /**
534      * Returns the messages to display in the message area.
535      *
536      * @param int $userid the current user
537      * @param int $otheruserid the other user
538      * @param int $limitfrom
539      * @param int $limitnum
540      * @param string $sort
541      * @param int $timefrom the time from the message being sent
542      * @param int $timeto the time up until the message being sent
543      * @return array
544      */
545     public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
546         $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
548         if (!empty($timefrom)) {
549             // Check the cache to see if we even need to do a DB query.
550             $cache = \cache::make('core', 'message_time_last_message_between_users');
551             $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
552             $lastcreated = $cache->get($key);
554             // The last known message time is earlier than the one being requested so we can
555             // just return an empty result set rather than having to query the DB.
556             if ($lastcreated && $lastcreated < $timefrom) {
557                 return [];
558             }
559         }
561         $arrmessages = array();
562         if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
563                                              $sort, $timefrom, $timeto)) {
565             $arrmessages = helper::create_messages($userid, $messages);
566         }
568         return $arrmessages;
569     }
571     /**
572      * Returns the most recent message between two users.
573      *
574      * @param int $userid the current user
575      * @param int $otheruserid the other user
576      * @return \stdClass|null
577      */
578     public static function get_most_recent_message($userid, $otheruserid) {
579         // We want two messages here so we get an accurate 'blocktime' value.
580         if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
581             // Swap the order so we now have them in historical order.
582             $messages = array_reverse($messages);
583             $arrmessages = helper::create_messages($userid, $messages);
584             return array_pop($arrmessages);
585         }
587         return null;
588     }
590     /**
591      * Returns the profile information for a contact for a user.
592      *
593      * @param int $userid The user id
594      * @param int $otheruserid The id of the user whose profile we want to view.
595      * @return \stdClass
596      */
597     public static function get_profile($userid, $otheruserid) {
598         global $CFG, $PAGE;
600         require_once($CFG->dirroot . '/user/lib.php');
602         $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
604         // Create the data we are going to pass to the renderable.
605         $data = new \stdClass();
606         $data->userid = $otheruserid;
607         $data->fullname = fullname($user);
608         $data->city = '';
609         $data->country = '';
610         $data->email = '';
611         $data->isonline = null;
612         // Get the user picture data - messaging has always shown these to the user.
613         $userpicture = new \user_picture($user);
614         $userpicture->size = 1; // Size f1.
615         $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
616         $userpicture->size = 0; // Size f2.
617         $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
619         $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
620         if ($userfields) {
621             if (isset($userfields['city'])) {
622                 $data->city = $userfields['city'];
623             }
624             if (isset($userfields['country'])) {
625                 $data->country = $userfields['country'];
626             }
627             if (isset($userfields['email'])) {
628                 $data->email = $userfields['email'];
629             }
630             if (isset($userfields['lastaccess'])) {
631                 $data->isonline = helper::is_online($userfields['lastaccess']);
632             }
633         }
635         $data->isblocked = self::is_blocked($userid, $otheruserid);
636         $data->iscontact = self::is_contact($userid, $otheruserid);
638         return $data;
639     }
641     /**
642      * Checks if a user can delete messages they have either received or sent.
643      *
644      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
645      *  but will still seem as if it was by the user)
646      * @param int $conversationid The id of the conversation
647      * @return bool Returns true if a user can delete the conversation, false otherwise.
648      */
649     public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
650         global $USER;
652         if (is_null($conversationid)) {
653             debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
654                 DEBUG_DEVELOPER);
655             return false;
656         }
658         $systemcontext = \context_system::instance();
660         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
661             return true;
662         }
664         if (!self::is_user_in_conversation($userid, $conversationid)) {
665             return false;
666         }
668         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
669                 $USER->id == $userid) {
670             return true;
671         }
673         return false;
674     }
676     /**
677      * Deletes a conversation.
678      *
679      * This function does not verify any permissions.
680      *
681      * @deprecated since 3.6
682      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
683      *  but will still seem as if it was by the user)
684      * @param int $otheruserid The id of the other user in the conversation
685      * @return bool
686      */
687     public static function delete_conversation($userid, $otheruserid) {
688         debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
689             '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
691         $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
693         // If there is no conversation, there is nothing to do.
694         if (!$conversationid) {
695             return true;
696         }
698         self::delete_conversation_by_id($userid, $conversationid);
700         return true;
701     }
703     /**
704      * Deletes a conversation for a specified user.
705      *
706      * This function does not verify any permissions.
707      *
708      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
709      *  but will still seem as if it was by the user)
710      * @param int $conversationid The id of the other user in the conversation
711      */
712     public static function delete_conversation_by_id(int $userid, int $conversationid) {
713         global $DB, $USER;
715         // Get all messages belonging to this conversation that have not already been deleted by this user.
716         $sql = "SELECT m.*
717                  FROM {messages} m
718            INNER JOIN {message_conversations} mc
719                    ON m.conversationid = mc.id
720             LEFT JOIN {message_user_actions} mua
721                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
722                 WHERE mua.id is NULL
723                   AND mc.id = ?
724              ORDER BY m.timecreated ASC";
725         $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
727         // Ok, mark these as deleted.
728         foreach ($messages as $message) {
729             $mua = new \stdClass();
730             $mua->userid = $userid;
731             $mua->messageid = $message->id;
732             $mua->action = self::MESSAGE_ACTION_DELETED;
733             $mua->timecreated = time();
734             $mua->id = $DB->insert_record('message_user_actions', $mua);
736             \core\event\message_deleted::create_from_ids($userid, $USER->id,
737                 $message->id, $mua->id)->trigger();
738         }
739     }
741     /**
742      * Returns the count of unread conversations (collection of messages from a single user) for
743      * the given user.
744      *
745      * @param \stdClass $user the user who's conversations should be counted
746      * @return int the count of the user's unread conversations
747      */
748     public static function count_unread_conversations($user = null) {
749         global $USER, $DB;
751         if (empty($user)) {
752             $user = $USER;
753         }
755         $sql = "SELECT COUNT(DISTINCT(m.conversationid))
756                   FROM {messages} m
757             INNER JOIN {message_conversations} mc
758                     ON m.conversationid = mc.id
759             INNER JOIN {message_conversation_members} mcm
760                     ON mc.id = mcm.conversationid
761              LEFT JOIN {message_user_actions} mua
762                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
763                  WHERE mcm.userid = ?
764                    AND mcm.userid != m.useridfrom
765                    AND mua.id is NULL";
767         return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
768     }
770     /**
771      * Marks all messages being sent to a user in a particular conversation.
772      *
773      * If $conversationdid is null then it marks all messages as read sent to $userid.
774      *
775      * @param int $userid
776      * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
777      */
778     public static function mark_all_messages_as_read($userid, $conversationid = null) {
779         global $DB;
781         $messagesql = "SELECT m.*
782                          FROM {messages} m
783                    INNER JOIN {message_conversations} mc
784                            ON mc.id = m.conversationid
785                    INNER JOIN {message_conversation_members} mcm
786                            ON mcm.conversationid = mc.id
787                     LEFT JOIN {message_user_actions} mua
788                            ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
789                         WHERE mua.id is NULL
790                           AND mcm.userid = ?
791                           AND m.useridfrom != ?";
792         $messageparams = [];
793         $messageparams[] = $userid;
794         $messageparams[] = self::MESSAGE_ACTION_READ;
795         $messageparams[] = $userid;
796         $messageparams[] = $userid;
797         if (!is_null($conversationid)) {
798             $messagesql .= " AND mc.id = ?";
799             $messageparams[] = $conversationid;
800         }
802         $messages = $DB->get_recordset_sql($messagesql, $messageparams);
803         foreach ($messages as $message) {
804             self::mark_message_as_read($userid, $message);
805         }
806         $messages->close();
807     }
809     /**
810      * Marks all notifications being sent from one user to another user as read.
811      *
812      * If the from user is null then it marks all notifications as read sent to the to user.
813      *
814      * @param int $touserid the id of the message recipient
815      * @param int|null $fromuserid the id of the message sender, null if all messages
816      * @return void
817      */
818     public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
819         global $DB;
821         $notificationsql = "SELECT n.*
822                               FROM {notifications} n
823                              WHERE useridto = ?
824                                AND timeread is NULL";
825         $notificationsparams = [$touserid];
826         if (!empty($fromuserid)) {
827             $notificationsql .= " AND useridfrom = ?";
828             $notificationsparams[] = $fromuserid;
829         }
831         $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
832         foreach ($notifications as $notification) {
833             self::mark_notification_as_read($notification);
834         }
835         $notifications->close();
836     }
838     /**
839      * Marks ALL messages being sent from $fromuserid to $touserid as read.
840      *
841      * Can be filtered by type.
842      *
843      * @deprecated since 3.5
844      * @param int $touserid the id of the message recipient
845      * @param int $fromuserid the id of the message sender
846      * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
847      * @return void
848      */
849     public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
850         debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
851             '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
852             DEBUG_DEVELOPER);
854         $type = strtolower($type);
856         $conversationid = null;
857         $ignoremessages = false;
858         if (!empty($fromuserid)) {
859             $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
860             if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
861                 $ignoremessages = true;
862             }
863         }
865         if (!empty($type)) {
866             if ($type == MESSAGE_TYPE_NOTIFICATION) {
867                 self::mark_all_notifications_as_read($touserid, $fromuserid);
868             } else if ($type == MESSAGE_TYPE_MESSAGE) {
869                 if (!$ignoremessages) {
870                     self::mark_all_messages_as_read($touserid, $conversationid);
871                 }
872             }
873         } else { // We want both.
874             self::mark_all_notifications_as_read($touserid, $fromuserid);
875             if (!$ignoremessages) {
876                 self::mark_all_messages_as_read($touserid, $conversationid);
877             }
878         }
879     }
881     /**
882      * Returns message preferences.
883      *
884      * @param array $processors
885      * @param array $providers
886      * @param \stdClass $user
887      * @return \stdClass
888      * @since 3.2
889      */
890     public static function get_all_message_preferences($processors, $providers, $user) {
891         $preferences = helper::get_providers_preferences($providers, $user->id);
892         $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
894         // For every processors put its options on the form (need to get function from processor's lib.php).
895         foreach ($processors as $processor) {
896             $processor->object->load_data($preferences, $user->id);
897         }
899         // Load general messaging preferences.
900         $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
901         $preferences->mailformat = $user->mailformat;
902         $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
904         return $preferences;
905     }
907     /**
908      * Count the number of users blocked by a user.
909      *
910      * @param \stdClass $user The user object
911      * @return int the number of blocked users
912      */
913     public static function count_blocked_users($user = null) {
914         global $USER, $DB;
916         if (empty($user)) {
917             $user = $USER;
918         }
920         $sql = "SELECT count(mub.id)
921                   FROM {message_users_blocked} mub
922                  WHERE mub.userid = :userid";
923         return $DB->count_records_sql($sql, array('userid' => $user->id));
924     }
926     /**
927      * Determines if a user is permitted to send another user a private message.
928      * If no sender is provided then it defaults to the logged in user.
929      *
930      * @param \stdClass $recipient The user object.
931      * @param \stdClass|null $sender The user object.
932      * @return bool true if user is permitted, false otherwise.
933      */
934     public static function can_post_message($recipient, $sender = null) {
935         global $USER;
937         if (is_null($sender)) {
938             // The message is from the logged in user, unless otherwise specified.
939             $sender = $USER;
940         }
942         if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
943             return false;
944         }
946         // The recipient blocks messages from non-contacts and the
947         // sender isn't a contact.
948         if (self::is_user_non_contact_blocked($recipient, $sender)) {
949             return false;
950         }
952         $senderid = null;
953         if ($sender !== null && isset($sender->id)) {
954             $senderid = $sender->id;
955         }
957         $systemcontext = \context_system::instance();
958         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
959             return true;
960         }
962         // The recipient has specifically blocked this sender.
963         if (self::is_blocked($recipient->id, $senderid)) {
964             return false;
965         }
967         return true;
968     }
970     /**
971      * Get the messaging preference for a user.
972      * If the user has not any messaging privacy preference:
973      * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
974      * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
975      *
976      * @param  int    $userid The user identifier.
977      * @return int    The default messaging preference.
978      */
979     public static function get_user_privacy_messaging_preference(int $userid) : int {
980         global $CFG;
982         // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
983         // otherwise, the default value will be "My contacts and anyone in my courses".
984         if (empty($CFG->messagingallusers)) {
985             $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
986         } else {
987             $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
988         }
989         $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
991         // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
992         // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
993         if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
994             $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
995         }
997         return $privacypreference;
998     }
1000     /**
1001      * Checks if the recipient is allowing messages from users that aren't a
1002      * contact. If not then it checks to make sure the sender is in the
1003      * recipient's contacts.
1004      *
1005      * @param \stdClass $recipient The user object.
1006      * @param \stdClass|null $sender The user object.
1007      * @return bool true if $sender is blocked, false otherwise.
1008      */
1009     public static function is_user_non_contact_blocked($recipient, $sender = null) {
1010         global $USER, $CFG;
1012         if (is_null($sender)) {
1013             // The message is from the logged in user, unless otherwise specified.
1014             $sender = $USER;
1015         }
1017         $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1018         switch ($privacypreference) {
1019             case self::MESSAGE_PRIVACY_SITE:
1020                 if (!empty($CFG->messagingallusers)) {
1021                     // Users can be messaged without being contacts or members of the same course.
1022                     break;
1023                 }
1024                 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1025                 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1026             case self::MESSAGE_PRIVACY_COURSEMEMBER:
1027                 // Confirm the sender and the recipient are both members of the same course.
1028                 if (enrol_sharing_course($recipient, $sender)) {
1029                     // All good, the recipient and the sender are members of the same course.
1030                     return false;
1031                 }
1032             case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1033                 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1034                 return !self::is_contact($sender->id, $recipient->id);
1035         }
1037         return false;
1038     }
1040     /**
1041      * Checks if the recipient has specifically blocked the sending user.
1042      *
1043      * Note: This function will always return false if the sender has the
1044      * readallmessages capability at the system context level.
1045      *
1046      * @deprecated since 3.6
1047      * @param int $recipientid User ID of the recipient.
1048      * @param int $senderid User ID of the sender.
1049      * @return bool true if $sender is blocked, false otherwise.
1050      */
1051     public static function is_user_blocked($recipientid, $senderid = null) {
1052         debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1053             DEBUG_DEVELOPER);
1055         global $USER;
1057         if (is_null($senderid)) {
1058             // The message is from the logged in user, unless otherwise specified.
1059             $senderid = $USER->id;
1060         }
1062         $systemcontext = \context_system::instance();
1063         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
1064             return false;
1065         }
1067         if (self::is_blocked($recipientid, $senderid)) {
1068             return true;
1069         }
1071         return false;
1072     }
1074     /**
1075      * Get specified message processor, validate corresponding plugin existence and
1076      * system configuration.
1077      *
1078      * @param string $name  Name of the processor.
1079      * @param bool $ready only return ready-to-use processors.
1080      * @return mixed $processor if processor present else empty array.
1081      * @since Moodle 3.2
1082      */
1083     public static function get_message_processor($name, $ready = false) {
1084         global $DB, $CFG;
1086         $processor = $DB->get_record('message_processors', array('name' => $name));
1087         if (empty($processor)) {
1088             // Processor not found, return.
1089             return array();
1090         }
1092         $processor = self::get_processed_processor_object($processor);
1093         if ($ready) {
1094             if ($processor->enabled && $processor->configured) {
1095                 return $processor;
1096             } else {
1097                 return array();
1098             }
1099         } else {
1100             return $processor;
1101         }
1102     }
1104     /**
1105      * Returns weather a given processor is enabled or not.
1106      * Note:- This doesn't check if the processor is configured or not.
1107      *
1108      * @param string $name Name of the processor
1109      * @return bool
1110      */
1111     public static function is_processor_enabled($name) {
1113         $cache = \cache::make('core', 'message_processors_enabled');
1114         $status = $cache->get($name);
1116         if ($status === false) {
1117             $processor = self::get_message_processor($name);
1118             if (!empty($processor)) {
1119                 $cache->set($name, $processor->enabled);
1120                 return $processor->enabled;
1121             } else {
1122                 return false;
1123             }
1124         }
1126         return $status;
1127     }
1129     /**
1130      * Set status of a processor.
1131      *
1132      * @param \stdClass $processor processor record.
1133      * @param 0|1 $enabled 0 or 1 to set the processor status.
1134      * @return bool
1135      * @since Moodle 3.2
1136      */
1137     public static function update_processor_status($processor, $enabled) {
1138         global $DB;
1139         $cache = \cache::make('core', 'message_processors_enabled');
1140         $cache->delete($processor->name);
1141         return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1142     }
1144     /**
1145      * Given a processor object, loads information about it's settings and configurations.
1146      * This is not a public api, instead use @see \core_message\api::get_message_processor()
1147      * or @see \get_message_processors()
1148      *
1149      * @param \stdClass $processor processor object
1150      * @return \stdClass processed processor object
1151      * @since Moodle 3.2
1152      */
1153     public static function get_processed_processor_object(\stdClass $processor) {
1154         global $CFG;
1156         $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1157         if (is_readable($processorfile)) {
1158             include_once($processorfile);
1159             $processclass = 'message_output_' . $processor->name;
1160             if (class_exists($processclass)) {
1161                 $pclass = new $processclass();
1162                 $processor->object = $pclass;
1163                 $processor->configured = 0;
1164                 if ($pclass->is_system_configured()) {
1165                     $processor->configured = 1;
1166                 }
1167                 $processor->hassettings = 0;
1168                 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1169                     $processor->hassettings = 1;
1170                 }
1171                 $processor->available = 1;
1172             } else {
1173                 print_error('errorcallingprocessor', 'message');
1174             }
1175         } else {
1176             $processor->available = 0;
1177         }
1178         return $processor;
1179     }
1181     /**
1182      * Retrieve users blocked by $user1
1183      *
1184      * @param int $userid The user id of the user whos blocked users we are returning
1185      * @return array the users blocked
1186      */
1187     public static function get_blocked_users($userid) {
1188         global $DB;
1190         $userfields = \user_picture::fields('u', array('lastaccess'));
1191         $blockeduserssql = "SELECT $userfields
1192                               FROM {message_users_blocked} mub
1193                         INNER JOIN {user} u
1194                                 ON u.id = mub.blockeduserid
1195                              WHERE u.deleted = 0
1196                                AND mub.userid = ?
1197                           GROUP BY $userfields
1198                           ORDER BY u.firstname ASC";
1199         return $DB->get_records_sql($blockeduserssql, [$userid]);
1200     }
1202     /**
1203      * Mark a single message as read.
1204      *
1205      * @param int $userid The user id who marked the message as read
1206      * @param \stdClass $message The message
1207      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1208      */
1209     public static function mark_message_as_read($userid, $message, $timeread = null) {
1210         global $DB;
1212         if (is_null($timeread)) {
1213             $timeread = time();
1214         }
1216         $mua = new \stdClass();
1217         $mua->userid = $userid;
1218         $mua->messageid = $message->id;
1219         $mua->action = self::MESSAGE_ACTION_READ;
1220         $mua->timecreated = $timeread;
1221         $mua->id = $DB->insert_record('message_user_actions', $mua);
1223         // Get the context for the user who received the message.
1224         $context = \context_user::instance($userid, IGNORE_MISSING);
1225         // If the user no longer exists the context value will be false, in this case use the system context.
1226         if ($context === false) {
1227             $context = \context_system::instance();
1228         }
1230         // Trigger event for reading a message.
1231         $event = \core\event\message_viewed::create(array(
1232             'objectid' => $mua->id,
1233             'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1234             'context' => $context,
1235             'relateduserid' => $message->useridfrom,
1236             'other' => array(
1237                 'messageid' => $message->id
1238             )
1239         ));
1240         $event->trigger();
1241     }
1243     /**
1244      * Mark a single notification as read.
1245      *
1246      * @param \stdClass $notification The notification
1247      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1248      */
1249     public static function mark_notification_as_read($notification, $timeread = null) {
1250         global $DB;
1252         if (is_null($timeread)) {
1253             $timeread = time();
1254         }
1256         if (is_null($notification->timeread)) {
1257             $updatenotification = new \stdClass();
1258             $updatenotification->id = $notification->id;
1259             $updatenotification->timeread = $timeread;
1261             $DB->update_record('notifications', $updatenotification);
1263             // Trigger event for reading a notification.
1264             \core\event\notification_viewed::create_from_ids(
1265                 $notification->useridfrom,
1266                 $notification->useridto,
1267                 $notification->id
1268             )->trigger();
1269         }
1270     }
1272     /**
1273      * Checks if a user can delete a message.
1274      *
1275      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1276      *  but will still seem as if it was by the user)
1277      * @param int $messageid The message id
1278      * @return bool Returns true if a user can delete the message, false otherwise.
1279      */
1280     public static function can_delete_message($userid, $messageid) {
1281         global $DB, $USER;
1283         $systemcontext = \context_system::instance();
1285         $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1287         if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1288             return true;
1289         }
1291         if (!self::is_user_in_conversation($userid, $conversationid)) {
1292             return false;
1293         }
1295         if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1296                 $USER->id == $userid) {
1297             return true;
1298         }
1300         return false;
1301     }
1303     /**
1304      * Deletes a message.
1305      *
1306      * This function does not verify any permissions.
1307      *
1308      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1309      *  but will still seem as if it was by the user)
1310      * @param int $messageid The message id
1311      * @return bool
1312      */
1313     public static function delete_message($userid, $messageid) {
1314         global $DB, $USER;
1316         if (!$DB->record_exists('messages', ['id' => $messageid])) {
1317             return false;
1318         }
1320         // Check if the user has already deleted this message.
1321         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1322                 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1323             $mua = new \stdClass();
1324             $mua->userid = $userid;
1325             $mua->messageid = $messageid;
1326             $mua->action = self::MESSAGE_ACTION_DELETED;
1327             $mua->timecreated = time();
1328             $mua->id = $DB->insert_record('message_user_actions', $mua);
1330             // Trigger event for deleting a message.
1331             \core\event\message_deleted::create_from_ids($userid, $USER->id,
1332                 $messageid, $mua->id)->trigger();
1334             return true;
1335         }
1337         return false;
1338     }
1340     /**
1341      * Returns the conversation between two users.
1342      *
1343      * @param array $userids
1344      * @return int|bool The id of the conversation, false if not found
1345      */
1346     public static function get_conversation_between_users(array $userids) {
1347         global $DB;
1349         $hash = helper::get_conversation_hash($userids);
1351         if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1352             return $conversation->id;
1353         }
1355         return false;
1356     }
1358     /**
1359      * Creates a conversation between two users.
1360      *
1361      * @param array $userids
1362      * @return int The id of the conversation
1363      */
1364     public static function create_conversation_between_users(array $userids) {
1365         global $DB;
1367         $conversation = new \stdClass();
1368         $conversation->convhash = helper::get_conversation_hash($userids);
1369         $conversation->timecreated = time();
1370         $conversation->id = $DB->insert_record('message_conversations', $conversation);
1372         // Add members to this conversation.
1373         foreach ($userids as $userid) {
1374             $member = new \stdClass();
1375             $member->conversationid = $conversation->id;
1376             $member->userid = $userid;
1377             $member->timecreated = time();
1378             $DB->insert_record('message_conversation_members', $member);
1379         }
1381         return $conversation->id;
1382     }
1384     /**
1385      * Checks if a user can create a contact request.
1386      *
1387      * @param int $userid The id of the user who is creating the contact request
1388      * @param int $requesteduserid The id of the user being requested
1389      * @return bool
1390      */
1391     public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1392         global $CFG;
1394         // If we can't message at all, then we can't create a contact.
1395         if (empty($CFG->messaging)) {
1396             return false;
1397         }
1399         // If we can message anyone on the site then we can create a contact.
1400         if ($CFG->messagingallusers) {
1401             return true;
1402         }
1404         // We need to check if they are in the same course.
1405         return enrol_sharing_course($userid, $requesteduserid);
1406     }
1408     /**
1409      * Handles creating a contact request.
1410      *
1411      * @param int $userid The id of the user who is creating the contact request
1412      * @param int $requesteduserid The id of the user being requested
1413      */
1414     public static function create_contact_request(int $userid, int $requesteduserid) {
1415         global $DB;
1417         $request = new \stdClass();
1418         $request->userid = $userid;
1419         $request->requesteduserid = $requesteduserid;
1420         $request->timecreated = time();
1422         $DB->insert_record('message_contact_requests', $request);
1424         // Send a notification.
1425         $userfrom = \core_user::get_user($userid);
1426         $userfromfullname = fullname($userfrom);
1427         $userto = \core_user::get_user($requesteduserid);
1428         $url = new \moodle_url('/message/pendingcontactrequests.php');
1430         $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1431         $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1433         $message = new \core\message\message();
1434         $message->courseid = SITEID;
1435         $message->component = 'moodle';
1436         $message->name = 'messagecontactrequests';
1437         $message->notification = 1;
1438         $message->userfrom = $userfrom;
1439         $message->userto = $userto;
1440         $message->subject = $subject;
1441         $message->fullmessage = text_to_html($fullmessage);
1442         $message->fullmessageformat = FORMAT_HTML;
1443         $message->fullmessagehtml = $fullmessage;
1444         $message->smallmessage = '';
1445         $message->contexturl = $url->out(false);
1447         message_send($message);
1448     }
1451     /**
1452      * Handles confirming a contact request.
1453      *
1454      * @param int $userid The id of the user who created the contact request
1455      * @param int $requesteduserid The id of the user confirming the request
1456      */
1457     public static function confirm_contact_request(int $userid, int $requesteduserid) {
1458         global $DB;
1460         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1461                 'requesteduserid' => $requesteduserid])) {
1462             self::add_contact($userid, $requesteduserid);
1464             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1465         }
1466     }
1468     /**
1469      * Handles declining a contact request.
1470      *
1471      * @param int $userid The id of the user who created the contact request
1472      * @param int $requesteduserid The id of the user declining the request
1473      */
1474     public static function decline_contact_request(int $userid, int $requesteduserid) {
1475         global $DB;
1477         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1478                 'requesteduserid' => $requesteduserid])) {
1479             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1480         }
1481     }
1483     /**
1484      * Handles returning the contact requests for a user.
1485      *
1486      * This also includes the user data necessary to display information
1487      * about the user.
1488      *
1489      * It will not include blocked users.
1490      *
1491      * @param int $userid
1492      * @return array The list of contact requests
1493      */
1494     public static function get_contact_requests(int $userid) : array {
1495         global $DB;
1497         // Used to search for contacts.
1498         $ufields = \user_picture::fields('u');
1500         $sql = "SELECT $ufields, mcr.id as contactrequestid
1501                   FROM {user} u
1502                   JOIN {message_contact_requests} mcr
1503                     ON u.id = mcr.userid
1504              LEFT JOIN {message_users_blocked} mub
1505                     ON (mub.userid = ? AND mub.blockeduserid = u.id)
1506                  WHERE mcr.requesteduserid = ?
1507                    AND u.deleted = 0
1508                    AND mub.id is NULL
1509               ORDER BY mcr.timecreated DESC";
1511         return $DB->get_records_sql($sql, [$userid, $userid]);
1512     }
1514     /**
1515      * Handles adding a contact.
1516      *
1517      * @param int $userid The id of the user who requested to be a contact
1518      * @param int $contactid The id of the contact
1519      */
1520     public static function add_contact(int $userid, int $contactid) {
1521         global $DB;
1523         $messagecontact = new \stdClass();
1524         $messagecontact->userid = $userid;
1525         $messagecontact->contactid = $contactid;
1526         $messagecontact->timecreated = time();
1527         $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1529         $eventparams = [
1530             'objectid' => $messagecontact->id,
1531             'userid' => $userid,
1532             'relateduserid' => $contactid,
1533             'context' => \context_user::instance($userid)
1534         ];
1535         $event = \core\event\message_contact_added::create($eventparams);
1536         $event->add_record_snapshot('message_contacts', $messagecontact);
1537         $event->trigger();
1538     }
1540     /**
1541      * Handles removing a contact.
1542      *
1543      * @param int $userid The id of the user who is removing a user as a contact
1544      * @param int $contactid The id of the user to be removed as a contact
1545      */
1546     public static function remove_contact(int $userid, int $contactid) {
1547         global $DB;
1549         if ($contact = self::get_contact($userid, $contactid)) {
1550             $DB->delete_records('message_contacts', ['id' => $contact->id]);
1552             $event = \core\event\message_contact_removed::create(array(
1553                 'objectid' => $contact->id,
1554                 'userid' => $userid,
1555                 'relateduserid' => $contactid,
1556                 'context' => \context_user::instance($userid)
1557             ));
1558             $event->add_record_snapshot('message_contacts', $contact);
1559             $event->trigger();
1560         }
1561     }
1563     /**
1564      * Handles blocking a user.
1565      *
1566      * @param int $userid The id of the user who is blocking
1567      * @param int $usertoblockid The id of the user being blocked
1568      */
1569     public static function block_user(int $userid, int $usertoblockid) {
1570         global $DB;
1572         $blocked = new \stdClass();
1573         $blocked->userid = $userid;
1574         $blocked->blockeduserid = $usertoblockid;
1575         $blocked->timecreated = time();
1576         $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1578         // Trigger event for blocking a contact.
1579         $event = \core\event\message_user_blocked::create(array(
1580             'objectid' => $blocked->id,
1581             'userid' => $userid,
1582             'relateduserid' => $usertoblockid,
1583             'context' => \context_user::instance($userid)
1584         ));
1585         $event->add_record_snapshot('message_users_blocked', $blocked);
1586         $event->trigger();
1587     }
1589     /**
1590      * Handles unblocking a user.
1591      *
1592      * @param int $userid The id of the user who is unblocking
1593      * @param int $usertounblockid The id of the user being unblocked
1594      */
1595     public static function unblock_user(int $userid, int $usertounblockid) {
1596         global $DB;
1598         if ($blockeduser = $DB->get_record('message_users_blocked',
1599                 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1600             $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1602             // Trigger event for unblocking a contact.
1603             $event = \core\event\message_user_unblocked::create(array(
1604                 'objectid' => $blockeduser->id,
1605                 'userid' => $userid,
1606                 'relateduserid' => $usertounblockid,
1607                 'context' => \context_user::instance($userid)
1608             ));
1609             $event->add_record_snapshot('message_users_blocked', $blockeduser);
1610             $event->trigger();
1611         }
1612     }
1614     /**
1615      * Checks if users are already contacts.
1616      *
1617      * @param int $userid The id of one of the users
1618      * @param int $contactid The id of the other user
1619      * @return bool Returns true if they are a contact, false otherwise
1620      */
1621     public static function is_contact(int $userid, int $contactid) : bool {
1622         global $DB;
1624         $sql = "SELECT id
1625                   FROM {message_contacts} mc
1626                  WHERE (mc.userid = ? AND mc.contactid = ?)
1627                     OR (mc.userid = ? AND mc.contactid = ?)";
1628         return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1629     }
1631     /**
1632      * Returns the row in the database table message_contacts that represents the contact between two people.
1633      *
1634      * @param int $userid The id of one of the users
1635      * @param int $contactid The id of the other user
1636      * @return mixed A fieldset object containing the record, false otherwise
1637      */
1638     public static function get_contact(int $userid, int $contactid) {
1639         global $DB;
1641         $sql = "SELECT mc.*
1642                   FROM {message_contacts} mc
1643                  WHERE (mc.userid = ? AND mc.contactid = ?)
1644                     OR (mc.userid = ? AND mc.contactid = ?)";
1645         return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1646     }
1648     /**
1649      * Checks if a user is already blocked.
1650      *
1651      * @param int $userid
1652      * @param int $blockeduserid
1653      * @return bool Returns true if they are a blocked, false otherwise
1654      */
1655     public static function is_blocked(int $userid, int $blockeduserid) : bool {
1656         global $DB;
1658         return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1659     }
1661     /**
1662      * Checks if a contact request already exists between users.
1663      *
1664      * @param int $userid The id of the user who is creating the contact request
1665      * @param int $requesteduserid The id of the user being requested
1666      * @return bool Returns true if a contact request exists, false otherwise
1667      */
1668     public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1669         global $DB;
1671         $sql = "SELECT id
1672                   FROM {message_contact_requests} mcr
1673                  WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1674                     OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1675         return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1676     }
1678     /**
1679      * Checks if a user is already in a conversation.
1680      *
1681      * @param int $userid The id of the user we want to check if they are in a group
1682      * @param int $conversationid The id of the conversation
1683      * @return bool Returns true if a contact request exists, false otherwise
1684      */
1685     public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
1686         global $DB;
1688         return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
1689             'userid' => $userid]);
1691     }