MDL-63632 forum: Delete where not discussion author
[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      * Handles searching for messages in the message area.
51      *
52      * @param int $userid The user id doing the searching
53      * @param string $search The string the user is searching
54      * @param int $limitfrom
55      * @param int $limitnum
56      * @return array
57      */
58     public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
59         global $DB;
61         // Get the user fields we want.
62         $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
63         $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
65         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
66                        m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
67                        mub2.id as userto_blocked
68                   FROM {messages} m
69             INNER JOIN {user} u
70                     ON u.id = m.useridfrom
71             INNER JOIN {message_conversations} mc
72                     ON mc.id = m.conversationid
73             INNER JOIN {message_conversation_members} mcm
74                     ON mcm.conversationid = m.conversationid
75             INNER JOIN {user} u2
76                     ON u2.id = mcm.userid
77              LEFT JOIN {message_users_blocked} mub
78                     ON (mub.blockeduserid = u.id AND mub.userid = ?)
79              LEFT JOIN {message_users_blocked} mub2
80                     ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
81              LEFT JOIN {message_user_actions} mua
82                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
83                  WHERE (m.useridfrom = ? OR mcm.userid = ?)
84                    AND m.useridfrom != mcm.userid
85                    AND u.deleted = 0
86                    AND u2.deleted = 0
87                    AND mua.id is NULL
88                    AND " . $DB->sql_like('smallmessage', '?', false) . "
89               ORDER BY timecreated DESC";
91         $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
93         // Convert the messages into searchable contacts with their last message being the message that was searched.
94         $conversations = array();
95         if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
96             foreach ($messages as $message) {
97                 $prefix = 'userfrom_';
98                 if ($userid == $message->useridfrom) {
99                     $prefix = 'userto_';
100                     // If it from the user, then mark it as read, even if it wasn't by the receiver.
101                     $message->isread = true;
102                 }
103                 $blockedcol = $prefix . 'blocked';
104                 $message->blocked = $message->$blockedcol ? 1 : 0;
106                 $message->messageid = $message->id;
107                 $conversations[] = helper::create_contact($message, $prefix);
108             }
109         }
111         return $conversations;
112     }
114     /**
115      * Handles searching for user in a particular course in the message area.
116      *
117      * @param int $userid The user id doing the searching
118      * @param int $courseid The id of the course we are searching in
119      * @param string $search The string the user is searching
120      * @param int $limitfrom
121      * @param int $limitnum
122      * @return array
123      */
124     public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
125         global $DB;
127         // Get all the users in the course.
128         list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
129         $sql = "SELECT u.*, mub.id as isblocked
130                   FROM {user} u
131                   JOIN ($esql) je
132                     ON je.id = u.id
133              LEFT JOIN {message_users_blocked} mub
134                     ON (mub.blockeduserid = u.id AND mub.userid = :userid)
135                  WHERE u.deleted = 0";
136         // Add more conditions.
137         $fullname = $DB->sql_fullname();
138         $sql .= " AND u.id != :userid2
139                   AND " . $DB->sql_like($fullname, ':search', false) . "
140              ORDER BY " . $DB->sql_fullname();
141         $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
143         // Convert all the user records into contacts.
144         $contacts = array();
145         if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
146             foreach ($users as $user) {
147                 $user->blocked = $user->isblocked ? 1 : 0;
148                 $contacts[] = helper::create_contact($user);
149             }
150         }
152         return $contacts;
153     }
155     /**
156      * Handles searching for user in the message area.
157      *
158      * @param int $userid The user id doing the searching
159      * @param string $search The string the user is searching
160      * @param int $limitnum
161      * @return array
162      */
163     public static function search_users($userid, $search, $limitnum = 0) {
164         global $CFG, $DB;
166         // Used to search for contacts.
167         $fullname = $DB->sql_fullname();
168         $ufields = \user_picture::fields('u', array('lastaccess'));
170         // Users not to include.
171         $excludeusers = array($userid, $CFG->siteguest);
172         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
174         // Ok, let's search for contacts first.
175         $contacts = array();
176         $sql = "SELECT $ufields, mub.id as isuserblocked
177                   FROM {user} u
178                   JOIN {message_contacts} mc
179                     ON u.id = mc.contactid
180              LEFT JOIN {message_users_blocked} mub
181                     ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
182                  WHERE mc.userid = :userid
183                    AND u.deleted = 0
184                    AND u.confirmed = 1
185                    AND " . $DB->sql_like($fullname, ':search', false) . "
186                    AND u.id $exclude
187               ORDER BY " . $DB->sql_fullname();
188         if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
189                 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
190             foreach ($users as $user) {
191                 $user->blocked = $user->isuserblocked ? 1 : 0;
192                 $contacts[] = helper::create_contact($user);
193             }
194         }
196         // Now, let's get the courses.
197         // Make sure to limit searches to enrolled courses.
198         $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
199         $courses = array();
200         // Really we want the user to be able to view the participants if they have the capability
201         // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
202         // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
203         // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
204         if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
205                 array('moodle/course:viewparticipants'))) {
206             foreach ($arrcourses as $course) {
207                 if (isset($enrolledcourses[$course->id])) {
208                     $data = new \stdClass();
209                     $data->id = $course->id;
210                     $data->shortname = $course->shortname;
211                     $data->fullname = $course->fullname;
212                     $courses[] = $data;
213                 }
214             }
215         }
217         // Let's get those non-contacts. Toast them gears boi.
218         // Note - you can only block contacts, so these users will not be blocked, so no need to get that
219         // extra detail from the database.
220         $noncontacts = array();
221         $sql = "SELECT $ufields
222                   FROM {user} u
223                  WHERE u.deleted = 0
224                    AND u.confirmed = 1
225                    AND " . $DB->sql_like($fullname, ':search', false) . "
226                    AND u.id $exclude
227                    AND u.id NOT IN (SELECT contactid
228                                       FROM {message_contacts}
229                                      WHERE userid = :userid)
230               ORDER BY " . $DB->sql_fullname();
231         if ($users = $DB->get_records_sql($sql,  array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
232                 0, $limitnum)) {
233             foreach ($users as $user) {
234                 $noncontacts[] = helper::create_contact($user);
235             }
236         }
238         return array($contacts, $courses, $noncontacts);
239     }
241     /**
242      * Returns the contacts and their conversation to display in the contacts area.
243      *
244      * ** WARNING **
245      * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
246      * to retrieve too much information in a single call will cause performance problems.
247      * ** WARNING **
248      *
249      * This function has specifically been altered to break each of the data sets it
250      * requires into separate database calls. This is to avoid the performance problems
251      * observed when attempting to join large data sets (e.g. the message tables and
252      * the user table).
253      *
254      * While it is possible to gather the data in a single query, and it may even be
255      * more efficient with a correctly tuned database, we have opted to trade off some of
256      * the benefits of a single query in order to ensure this function will work on
257      * most databases with default tunings and with large data sets.
258      *
259      * @param int $userid The user id
260      * @param int $limitfrom
261      * @param int $limitnum
262      * @return array
263      */
264     public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
265         global $DB;
267         // Get the last message from each conversation that the user belongs to.
268         $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
269                   FROM {messages} m
270             INNER JOIN (
271                           SELECT MAX(m.id) AS messageid
272                             FROM {messages} m
273                       INNER JOIN (
274                                       SELECT m.conversationid, MAX(m.timecreated) as maxtime
275                                         FROM {messages} m
276                                   INNER JOIN {message_conversation_members} mcm
277                                           ON mcm.conversationid = m.conversationid
278                                    LEFT JOIN {message_user_actions} mua
279                                           ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
280                                        WHERE mua.id is NULL
281                                          AND mcm.userid = :userid2
282                                     GROUP BY m.conversationid
283                                  ) maxmessage
284                                ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
285                          GROUP BY m.conversationid
286                        ) lastmessage
287                     ON lastmessage.messageid = m.id
288             INNER JOIN {message_conversation_members} mcm
289                     ON mcm.conversationid = m.conversationid
290             INNER JOIN {message_conversation_members} mcm2
291                     ON mcm2.conversationid = m.conversationid
292                  WHERE mcm.userid = m.useridfrom
293                    AND mcm.id != mcm2.id
294               ORDER BY m.timecreated DESC";
295         $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
296             'userid2' => $userid], $limitfrom, $limitnum);
298         $messages = [];
299         foreach ($messageset as $message) {
300             $messages[$message->id] = $message;
301         }
302         $messageset->close();
304         // If there are no messages return early.
305         if (empty($messages)) {
306             return [];
307         }
309         // We need to pull out the list of other users that are part of each of these conversations. This
310         // needs to be done in a separate query to avoid doing a join on the messages tables and the user
311         // tables because on large sites these tables are massive which results in extremely slow
312         // performance (typically due to join buffer exhaustion).
313         $otheruserids = array_map(function($message) use ($userid) {
314             return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
315         }, array_values($messages));
317         // Ok, let's get the other members in the conversations.
318         list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
319         $userfields = \user_picture::fields('u', array('lastaccess'));
320         $userssql = "SELECT $userfields
321                        FROM {user} u
322                       WHERE id $useridsql
323                         AND deleted = 0";
324         $otherusers = $DB->get_records_sql($userssql, $usersparams);
326         // If there are no other users (user may have been deleted), then do not continue.
327         if (empty($otherusers)) {
328             return [];
329         }
331         $contactssql = "SELECT contactid
332                           FROM {message_contacts}
333                          WHERE userid = ?
334                            AND contactid $useridsql";
335         $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
337         // Finally, let's get the unread messages count for this user so that we can add them
338         // to the conversation. Remember we need to ignore the messages the user sent.
339         $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
340                               FROM {messages} m
341                         INNER JOIN {message_conversations} mc
342                                 ON mc.id = m.conversationid
343                         INNER JOIN {message_conversation_members} mcm
344                                 ON m.conversationid = mcm.conversationid
345                          LEFT JOIN {message_user_actions} mua
346                                 ON (mua.messageid = m.id AND mua.userid = ? AND
347                                    (mua.action = ? OR mua.action = ?))
348                              WHERE mcm.userid = ?
349                                AND m.useridfrom != ?
350                                AND mua.id is NULL
351                           GROUP BY useridfrom';
352         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
353             $userid, $userid]);
355         // Get rid of the table prefix.
356         $userfields = str_replace('u.', '', $userfields);
357         $userproperties = explode(',', $userfields);
358         $arrconversations = array();
359         foreach ($messages as $message) {
360             $conversation = new \stdClass();
361             $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
362             $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
363             $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
365             // It's possible the other user was deleted, so, skip.
366             if (is_null($otheruser)) {
367                 continue;
368             }
370             // Add the other user's information to the conversation, if we have one.
371             foreach ($userproperties as $prop) {
372                 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
373             }
375             // Add the contact's information, if we have one.
376             $conversation->blocked = ($contact) ? $contact->blocked : null;
378             // Add the message information.
379             $conversation->messageid = $message->id;
380             $conversation->smallmessage = $message->smallmessage;
381             $conversation->useridfrom = $message->useridfrom;
383             // Only consider it unread if $user has unread messages.
384             if (isset($unreadcounts[$otheruserid])) {
385                 $conversation->isread = false;
386                 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
387             } else {
388                 $conversation->isread = true;
389             }
391             $arrconversations[$otheruserid] = helper::create_contact($conversation);
392         }
394         return $arrconversations;
395     }
397     /**
398      * Returns the contacts to display in the contacts area.
399      *
400      * @param int $userid The user id
401      * @param int $limitfrom
402      * @param int $limitnum
403      * @return array
404      */
405     public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
406         global $DB;
408         $contactids = [];
409         $sql = "SELECT mc.*
410                   FROM {message_contacts} mc
411                  WHERE mc.userid = ? OR mc.contactid = ?
412               ORDER BY timecreated DESC";
413         if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
414             foreach ($contacts as $contact) {
415                 if ($userid == $contact->userid) {
416                     $contactids[] = $contact->contactid;
417                 } else {
418                     $contactids[] = $contact->userid;
419                 }
420             }
421         }
423         if (!empty($contactids)) {
424             list($insql, $inparams) = $DB->get_in_or_equal($contactids);
426             $sql = "SELECT u.*, mub.id as isblocked
427                       FROM {user} u
428                  LEFT JOIN {message_users_blocked} mub
429                         ON u.id = mub.blockeduserid
430                      WHERE u.id $insql";
431             if ($contacts = $DB->get_records_sql($sql, $inparams)) {
432                 $arrcontacts = [];
433                 foreach ($contacts as $contact) {
434                     $contact->blocked = $contact->isblocked ? 1 : 0;
435                     $arrcontacts[] = helper::create_contact($contact);
436                 }
438                 return $arrcontacts;
439             }
440         }
442         return [];
443     }
445     /**
446      * Returns the an array of the users the given user is in a conversation
447      * with who are a contact and the number of unread messages.
448      *
449      * @param int $userid The user id
450      * @param int $limitfrom
451      * @param int $limitnum
452      * @return array
453      */
454     public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
455         global $DB;
457         $userfields = \user_picture::fields('u', array('lastaccess'));
458         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
459                               FROM {message_contacts} mc
460                         INNER JOIN {user} u
461                                 ON (u.id = mc.contactid OR u.id = mc.userid)
462                          LEFT JOIN {messages} m
463                                 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
464                          LEFT JOIN {message_conversation_members} mcm
465                                 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
466                          LEFT JOIN {message_user_actions} mua
467                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
468                          LEFT JOIN {message_users_blocked} mub
469                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
470                              WHERE mua.id is NULL
471                                AND mub.id is NULL
472                                AND (mc.userid = ? OR mc.contactid = ?)
473                                AND u.id != ?
474                                AND u.deleted = 0
475                           GROUP BY $userfields";
477         return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
478             $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
479     }
481     /**
482      * Returns the an array of the users the given user is in a conversation
483      * with who are not a contact and the number of unread messages.
484      *
485      * @param int $userid The user id
486      * @param int $limitfrom
487      * @param int $limitnum
488      * @return array
489      */
490     public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
491         global $DB;
493         $userfields = \user_picture::fields('u', array('lastaccess'));
494         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
495                               FROM {user} u
496                         INNER JOIN {messages} m
497                                 ON m.useridfrom = u.id
498                         INNER JOIN {message_conversation_members} mcm
499                                 ON mcm.conversationid = m.conversationid
500                          LEFT JOIN {message_user_actions} mua
501                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
502                          LEFT JOIN {message_contacts} mc
503                                 ON (mc.userid = ? AND mc.contactid = u.id)
504                          LEFT JOIN {message_users_blocked} mub
505                                 ON (mub.userid = ? AND mub.blockeduserid = u.id)
506                              WHERE mcm.userid = ?
507                                AND mcm.userid != m.useridfrom
508                                AND mua.id is NULL
509                                AND mub.id is NULL
510                                AND mc.id is NULL
511                                AND u.deleted = 0
512                           GROUP BY $userfields";
514         return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
515             $limitfrom, $limitnum);
516     }
518     /**
519      * Returns the messages to display in the message area.
520      *
521      * @param int $userid the current user
522      * @param int $otheruserid the other user
523      * @param int $limitfrom
524      * @param int $limitnum
525      * @param string $sort
526      * @param int $timefrom the time from the message being sent
527      * @param int $timeto the time up until the message being sent
528      * @return array
529      */
530     public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
531         $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
533         if (!empty($timefrom)) {
534             // Check the cache to see if we even need to do a DB query.
535             $cache = \cache::make('core', 'message_time_last_message_between_users');
536             $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
537             $lastcreated = $cache->get($key);
539             // The last known message time is earlier than the one being requested so we can
540             // just return an empty result set rather than having to query the DB.
541             if ($lastcreated && $lastcreated < $timefrom) {
542                 return [];
543             }
544         }
546         $arrmessages = array();
547         if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
548                                              $sort, $timefrom, $timeto)) {
550             $arrmessages = helper::create_messages($userid, $messages);
551         }
553         return $arrmessages;
554     }
556     /**
557      * Returns the most recent message between two users.
558      *
559      * @param int $userid the current user
560      * @param int $otheruserid the other user
561      * @return \stdClass|null
562      */
563     public static function get_most_recent_message($userid, $otheruserid) {
564         // We want two messages here so we get an accurate 'blocktime' value.
565         if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
566             // Swap the order so we now have them in historical order.
567             $messages = array_reverse($messages);
568             $arrmessages = helper::create_messages($userid, $messages);
569             return array_pop($arrmessages);
570         }
572         return null;
573     }
575     /**
576      * Returns the profile information for a contact for a user.
577      *
578      * @param int $userid The user id
579      * @param int $otheruserid The id of the user whose profile we want to view.
580      * @return \stdClass
581      */
582     public static function get_profile($userid, $otheruserid) {
583         global $CFG, $PAGE;
585         require_once($CFG->dirroot . '/user/lib.php');
587         $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
589         // Create the data we are going to pass to the renderable.
590         $data = new \stdClass();
591         $data->userid = $otheruserid;
592         $data->fullname = fullname($user);
593         $data->city = '';
594         $data->country = '';
595         $data->email = '';
596         $data->isonline = null;
597         // Get the user picture data - messaging has always shown these to the user.
598         $userpicture = new \user_picture($user);
599         $userpicture->size = 1; // Size f1.
600         $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
601         $userpicture->size = 0; // Size f2.
602         $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
604         $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
605         if ($userfields) {
606             if (isset($userfields['city'])) {
607                 $data->city = $userfields['city'];
608             }
609             if (isset($userfields['country'])) {
610                 $data->country = $userfields['country'];
611             }
612             if (isset($userfields['email'])) {
613                 $data->email = $userfields['email'];
614             }
615             if (isset($userfields['lastaccess'])) {
616                 $data->isonline = helper::is_online($userfields['lastaccess']);
617             }
618         }
620         $data->isblocked = self::is_blocked($userid, $otheruserid);
621         $data->iscontact = self::is_contact($userid, $otheruserid);
623         return $data;
624     }
626     /**
627      * Checks if a user can delete messages they have either received or sent.
628      *
629      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
630      *  but will still seem as if it was by the user)
631      * @return bool Returns true if a user can delete the conversation, false otherwise.
632      */
633     public static function can_delete_conversation($userid) {
634         global $USER;
636         $systemcontext = \context_system::instance();
638         // Let's check if the user is allowed to delete this conversation.
639         if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
640             ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
641                 $USER->id == $userid))) {
642             return true;
643         }
645         return false;
646     }
648     /**
649      * Deletes a conversation.
650      *
651      * This function does not verify any permissions.
652      *
653      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
654      *  but will still seem as if it was by the user)
655      * @param int $otheruserid The id of the other user in the conversation
656      * @return bool
657      */
658     public static function delete_conversation($userid, $otheruserid) {
659         global $DB, $USER;
661         $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
663         // If there is no conversation, there is nothing to do.
664         if (!$conversationid) {
665             return true;
666         }
668         // Get all messages belonging to this conversation that have not already been deleted by this user.
669         $sql = "SELECT m.*
670                  FROM {messages} m
671            INNER JOIN {message_conversations} mc
672                    ON m.conversationid = mc.id
673             LEFT JOIN {message_user_actions} mua
674                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
675                 WHERE mua.id is NULL
676                   AND mc.id = ?
677              ORDER BY m.timecreated ASC";
678         $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
680         // Ok, mark these as deleted.
681         foreach ($messages as $message) {
682             $mua = new \stdClass();
683             $mua->userid = $userid;
684             $mua->messageid = $message->id;
685             $mua->action = self::MESSAGE_ACTION_DELETED;
686             $mua->timecreated = time();
687             $mua->id = $DB->insert_record('message_user_actions', $mua);
689             if ($message->useridfrom == $userid) {
690                 $useridto = $otheruserid;
691             } else {
692                 $useridto = $userid;
693             }
694             \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
695                 $USER->id, $message->id, $mua->id)->trigger();
696         }
698         return true;
699     }
701     /**
702      * Returns the count of unread conversations (collection of messages from a single user) for
703      * the given user.
704      *
705      * @param \stdClass $user the user who's conversations should be counted
706      * @return int the count of the user's unread conversations
707      */
708     public static function count_unread_conversations($user = null) {
709         global $USER, $DB;
711         if (empty($user)) {
712             $user = $USER;
713         }
715         $sql = "SELECT COUNT(DISTINCT(m.conversationid))
716                   FROM {messages} m
717             INNER JOIN {message_conversations} mc
718                     ON m.conversationid = mc.id
719             INNER JOIN {message_conversation_members} mcm
720                     ON mc.id = mcm.conversationid
721              LEFT JOIN {message_user_actions} mua
722                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
723                  WHERE mcm.userid = ?
724                    AND mcm.userid != m.useridfrom
725                    AND mua.id is NULL";
727         return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
728     }
730     /**
731      * Marks all messages being sent to a user in a particular conversation.
732      *
733      * If $conversationdid is null then it marks all messages as read sent to $userid.
734      *
735      * @param int $userid
736      * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
737      */
738     public static function mark_all_messages_as_read($userid, $conversationid = null) {
739         global $DB;
741         $messagesql = "SELECT m.*
742                          FROM {messages} m
743                    INNER JOIN {message_conversations} mc
744                            ON mc.id = m.conversationid
745                    INNER JOIN {message_conversation_members} mcm
746                            ON mcm.conversationid = mc.id
747                     LEFT JOIN {message_user_actions} mua
748                            ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
749                         WHERE mua.id is NULL
750                           AND mcm.userid = ?
751                           AND m.useridfrom != ?";
752         $messageparams = [];
753         $messageparams[] = $userid;
754         $messageparams[] = self::MESSAGE_ACTION_READ;
755         $messageparams[] = $userid;
756         $messageparams[] = $userid;
757         if (!is_null($conversationid)) {
758             $messagesql .= " AND mc.id = ?";
759             $messageparams[] = $conversationid;
760         }
762         $messages = $DB->get_recordset_sql($messagesql, $messageparams);
763         foreach ($messages as $message) {
764             self::mark_message_as_read($userid, $message);
765         }
766         $messages->close();
767     }
769     /**
770      * Marks all notifications being sent from one user to another user as read.
771      *
772      * If the from user is null then it marks all notifications as read sent to the to user.
773      *
774      * @param int $touserid the id of the message recipient
775      * @param int|null $fromuserid the id of the message sender, null if all messages
776      * @return void
777      */
778     public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
779         global $DB;
781         $notificationsql = "SELECT n.*
782                               FROM {notifications} n
783                              WHERE useridto = ?
784                                AND timeread is NULL";
785         $notificationsparams = [$touserid];
786         if (!empty($fromuserid)) {
787             $notificationsql .= " AND useridfrom = ?";
788             $notificationsparams[] = $fromuserid;
789         }
791         $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
792         foreach ($notifications as $notification) {
793             self::mark_notification_as_read($notification);
794         }
795         $notifications->close();
796     }
798     /**
799      * Marks ALL messages being sent from $fromuserid to $touserid as read.
800      *
801      * Can be filtered by type.
802      *
803      * @deprecated since 3.5
804      * @param int $touserid the id of the message recipient
805      * @param int $fromuserid the id of the message sender
806      * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
807      * @return void
808      */
809     public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
810         debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
811             '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
812             DEBUG_DEVELOPER);
814         $type = strtolower($type);
816         $conversationid = null;
817         $ignoremessages = false;
818         if (!empty($fromuserid)) {
819             $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
820             if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
821                 $ignoremessages = true;
822             }
823         }
825         if (!empty($type)) {
826             if ($type == MESSAGE_TYPE_NOTIFICATION) {
827                 self::mark_all_notifications_as_read($touserid, $fromuserid);
828             } else if ($type == MESSAGE_TYPE_MESSAGE) {
829                 if (!$ignoremessages) {
830                     self::mark_all_messages_as_read($touserid, $conversationid);
831                 }
832             }
833         } else { // We want both.
834             self::mark_all_notifications_as_read($touserid, $fromuserid);
835             if (!$ignoremessages) {
836                 self::mark_all_messages_as_read($touserid, $conversationid);
837             }
838         }
839     }
841     /**
842      * Returns message preferences.
843      *
844      * @param array $processors
845      * @param array $providers
846      * @param \stdClass $user
847      * @return \stdClass
848      * @since 3.2
849      */
850     public static function get_all_message_preferences($processors, $providers, $user) {
851         $preferences = helper::get_providers_preferences($providers, $user->id);
852         $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
854         // For every processors put its options on the form (need to get function from processor's lib.php).
855         foreach ($processors as $processor) {
856             $processor->object->load_data($preferences, $user->id);
857         }
859         // Load general messaging preferences.
860         $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
861         $preferences->mailformat = $user->mailformat;
862         $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
864         return $preferences;
865     }
867     /**
868      * Count the number of users blocked by a user.
869      *
870      * @param \stdClass $user The user object
871      * @return int the number of blocked users
872      */
873     public static function count_blocked_users($user = null) {
874         global $USER, $DB;
876         if (empty($user)) {
877             $user = $USER;
878         }
880         $sql = "SELECT count(mub.id)
881                   FROM {message_users_blocked} mub
882                  WHERE mub.userid = :userid";
883         return $DB->count_records_sql($sql, array('userid' => $user->id));
884     }
886     /**
887      * Determines if a user is permitted to send another user a private message.
888      * If no sender is provided then it defaults to the logged in user.
889      *
890      * @param \stdClass $recipient The user object.
891      * @param \stdClass|null $sender The user object.
892      * @return bool true if user is permitted, false otherwise.
893      */
894     public static function can_post_message($recipient, $sender = null) {
895         global $USER;
897         if (is_null($sender)) {
898             // The message is from the logged in user, unless otherwise specified.
899             $sender = $USER;
900         }
902         if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
903             return false;
904         }
906         // The recipient blocks messages from non-contacts and the
907         // sender isn't a contact.
908         if (self::is_user_non_contact_blocked($recipient, $sender)) {
909             return false;
910         }
912         $senderid = null;
913         if ($sender !== null && isset($sender->id)) {
914             $senderid = $sender->id;
915         }
917         $systemcontext = \context_system::instance();
918         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
919             return true;
920         }
922         // The recipient has specifically blocked this sender.
923         if (self::is_blocked($recipient->id, $senderid)) {
924             return false;
925         }
927         return true;
928     }
930     /**
931      * Checks if the recipient is allowing messages from users that aren't a
932      * contact. If not then it checks to make sure the sender is in the
933      * recipient's contacts.
934      *
935      * @param \stdClass $recipient The user object.
936      * @param \stdClass|null $sender The user object.
937      * @return bool true if $sender is blocked, false otherwise.
938      */
939     public static function is_user_non_contact_blocked($recipient, $sender = null) {
940         global $USER;
942         if (is_null($sender)) {
943             // The message is from the logged in user, unless otherwise specified.
944             $sender = $USER;
945         }
947         $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
948         if (!empty($blockednoncontacts)) {
949             // Confirm the sender is a contact of the recipient.
950             if (self::is_contact($sender->id, $recipient->id)) {
951                 // All good, the recipient is a contact of the sender.
952                 return false;
953             } else {
954                 // Oh no, the recipient is not a contact. Looks like we can't send the message.
955                 return true;
956             }
957         }
959         return false;
960     }
962     /**
963      * Checks if the recipient has specifically blocked the sending user.
964      *
965      * Note: This function will always return false if the sender has the
966      * readallmessages capability at the system context level.
967      *
968      * @deprecated since 3.6
969      * @param int $recipientid User ID of the recipient.
970      * @param int $senderid User ID of the sender.
971      * @return bool true if $sender is blocked, false otherwise.
972      */
973     public static function is_user_blocked($recipientid, $senderid = null) {
974         debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
975             DEBUG_DEVELOPER);
977         global $USER;
979         if (is_null($senderid)) {
980             // The message is from the logged in user, unless otherwise specified.
981             $senderid = $USER->id;
982         }
984         $systemcontext = \context_system::instance();
985         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
986             return false;
987         }
989         if (self::is_blocked($recipientid, $senderid)) {
990             return true;
991         }
993         return false;
994     }
996     /**
997      * Get specified message processor, validate corresponding plugin existence and
998      * system configuration.
999      *
1000      * @param string $name  Name of the processor.
1001      * @param bool $ready only return ready-to-use processors.
1002      * @return mixed $processor if processor present else empty array.
1003      * @since Moodle 3.2
1004      */
1005     public static function get_message_processor($name, $ready = false) {
1006         global $DB, $CFG;
1008         $processor = $DB->get_record('message_processors', array('name' => $name));
1009         if (empty($processor)) {
1010             // Processor not found, return.
1011             return array();
1012         }
1014         $processor = self::get_processed_processor_object($processor);
1015         if ($ready) {
1016             if ($processor->enabled && $processor->configured) {
1017                 return $processor;
1018             } else {
1019                 return array();
1020             }
1021         } else {
1022             return $processor;
1023         }
1024     }
1026     /**
1027      * Returns weather a given processor is enabled or not.
1028      * Note:- This doesn't check if the processor is configured or not.
1029      *
1030      * @param string $name Name of the processor
1031      * @return bool
1032      */
1033     public static function is_processor_enabled($name) {
1035         $cache = \cache::make('core', 'message_processors_enabled');
1036         $status = $cache->get($name);
1038         if ($status === false) {
1039             $processor = self::get_message_processor($name);
1040             if (!empty($processor)) {
1041                 $cache->set($name, $processor->enabled);
1042                 return $processor->enabled;
1043             } else {
1044                 return false;
1045             }
1046         }
1048         return $status;
1049     }
1051     /**
1052      * Set status of a processor.
1053      *
1054      * @param \stdClass $processor processor record.
1055      * @param 0|1 $enabled 0 or 1 to set the processor status.
1056      * @return bool
1057      * @since Moodle 3.2
1058      */
1059     public static function update_processor_status($processor, $enabled) {
1060         global $DB;
1061         $cache = \cache::make('core', 'message_processors_enabled');
1062         $cache->delete($processor->name);
1063         return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1064     }
1066     /**
1067      * Given a processor object, loads information about it's settings and configurations.
1068      * This is not a public api, instead use @see \core_message\api::get_message_processor()
1069      * or @see \get_message_processors()
1070      *
1071      * @param \stdClass $processor processor object
1072      * @return \stdClass processed processor object
1073      * @since Moodle 3.2
1074      */
1075     public static function get_processed_processor_object(\stdClass $processor) {
1076         global $CFG;
1078         $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1079         if (is_readable($processorfile)) {
1080             include_once($processorfile);
1081             $processclass = 'message_output_' . $processor->name;
1082             if (class_exists($processclass)) {
1083                 $pclass = new $processclass();
1084                 $processor->object = $pclass;
1085                 $processor->configured = 0;
1086                 if ($pclass->is_system_configured()) {
1087                     $processor->configured = 1;
1088                 }
1089                 $processor->hassettings = 0;
1090                 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1091                     $processor->hassettings = 1;
1092                 }
1093                 $processor->available = 1;
1094             } else {
1095                 print_error('errorcallingprocessor', 'message');
1096             }
1097         } else {
1098             $processor->available = 0;
1099         }
1100         return $processor;
1101     }
1103     /**
1104      * Retrieve users blocked by $user1
1105      *
1106      * @param int $userid The user id of the user whos blocked users we are returning
1107      * @return array the users blocked
1108      */
1109     public static function get_blocked_users($userid) {
1110         global $DB;
1112         $userfields = \user_picture::fields('u', array('lastaccess'));
1113         $blockeduserssql = "SELECT $userfields
1114                               FROM {message_users_blocked} mub
1115                         INNER JOIN {user} u
1116                                 ON u.id = mub.blockeduserid
1117                              WHERE u.deleted = 0
1118                                AND mub.userid = ?
1119                           GROUP BY $userfields
1120                           ORDER BY u.firstname ASC";
1121         return $DB->get_records_sql($blockeduserssql, [$userid]);
1122     }
1124     /**
1125      * Mark a single message as read.
1126      *
1127      * @param int $userid The user id who marked the message as read
1128      * @param \stdClass $message The message
1129      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1130      */
1131     public static function mark_message_as_read($userid, $message, $timeread = null) {
1132         global $DB;
1134         if (is_null($timeread)) {
1135             $timeread = time();
1136         }
1138         $mua = new \stdClass();
1139         $mua->userid = $userid;
1140         $mua->messageid = $message->id;
1141         $mua->action = self::MESSAGE_ACTION_READ;
1142         $mua->timecreated = $timeread;
1143         $mua->id = $DB->insert_record('message_user_actions', $mua);
1145         // Get the context for the user who received the message.
1146         $context = \context_user::instance($userid, IGNORE_MISSING);
1147         // If the user no longer exists the context value will be false, in this case use the system context.
1148         if ($context === false) {
1149             $context = \context_system::instance();
1150         }
1152         // Trigger event for reading a message.
1153         $event = \core\event\message_viewed::create(array(
1154             'objectid' => $mua->id,
1155             'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1156             'context' => $context,
1157             'relateduserid' => $message->useridfrom,
1158             'other' => array(
1159                 'messageid' => $message->id
1160             )
1161         ));
1162         $event->trigger();
1163     }
1165     /**
1166      * Mark a single notification as read.
1167      *
1168      * @param \stdClass $notification The notification
1169      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1170      */
1171     public static function mark_notification_as_read($notification, $timeread = null) {
1172         global $DB;
1174         if (is_null($timeread)) {
1175             $timeread = time();
1176         }
1178         if (is_null($notification->timeread)) {
1179             $updatenotification = new \stdClass();
1180             $updatenotification->id = $notification->id;
1181             $updatenotification->timeread = $timeread;
1183             $DB->update_record('notifications', $updatenotification);
1185             // Trigger event for reading a notification.
1186             \core\event\notification_viewed::create_from_ids(
1187                 $notification->useridfrom,
1188                 $notification->useridto,
1189                 $notification->id
1190             )->trigger();
1191         }
1192     }
1194     /**
1195      * Checks if a user can delete a message.
1196      *
1197      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1198      *  but will still seem as if it was by the user)
1199      * @param int $messageid The message id
1200      * @return bool Returns true if a user can delete the message, false otherwise.
1201      */
1202     public static function can_delete_message($userid, $messageid) {
1203         global $DB, $USER;
1205         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1206                   FROM {messages} m
1207             INNER JOIN {message_conversations} mc
1208                     ON m.conversationid = mc.id
1209             INNER JOIN {message_conversation_members} mcm
1210                     ON mcm.conversationid = mc.id
1211                  WHERE mcm.userid != m.useridfrom
1212                    AND m.id = ?";
1213         $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1215         if ($message->useridfrom == $userid) {
1216             $userdeleting = 'useridfrom';
1217         } else if ($message->useridto == $userid) {
1218             $userdeleting = 'useridto';
1219         } else {
1220             return false;
1221         }
1223         $systemcontext = \context_system::instance();
1225         // Let's check if the user is allowed to delete this message.
1226         if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1227             ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1228                 $USER->id == $message->$userdeleting))) {
1229             return true;
1230         }
1232         return false;
1233     }
1235     /**
1236      * Deletes a message.
1237      *
1238      * This function does not verify any permissions.
1239      *
1240      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1241      *  but will still seem as if it was by the user)
1242      * @param int $messageid The message id
1243      * @return bool
1244      */
1245     public static function delete_message($userid, $messageid) {
1246         global $DB;
1248         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1249                   FROM {messages} m
1250             INNER JOIN {message_conversations} mc
1251                     ON m.conversationid = mc.id
1252             INNER JOIN {message_conversation_members} mcm
1253                     ON mcm.conversationid = mc.id
1254                  WHERE mcm.userid != m.useridfrom
1255                    AND m.id = ?";
1256         $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1258         // Check if the user has already deleted this message.
1259         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1260                 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1261             $mua = new \stdClass();
1262             $mua->userid = $userid;
1263             $mua->messageid = $messageid;
1264             $mua->action = self::MESSAGE_ACTION_DELETED;
1265             $mua->timecreated = time();
1266             $mua->id = $DB->insert_record('message_user_actions', $mua);
1268             // Trigger event for deleting a message.
1269             \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1270                 $userid, $message->id, $mua->id)->trigger();
1272             return true;
1273         }
1275         return false;
1276     }
1278     /**
1279      * Returns the conversation between two users.
1280      *
1281      * @param array $userids
1282      * @return int|bool The id of the conversation, false if not found
1283      */
1284     public static function get_conversation_between_users(array $userids) {
1285         global $DB;
1287         $hash = helper::get_conversation_hash($userids);
1289         if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1290             return $conversation->id;
1291         }
1293         return false;
1294     }
1296     /**
1297      * Creates a conversation between two users.
1298      *
1299      * @param array $userids
1300      * @return int The id of the conversation
1301      */
1302     public static function create_conversation_between_users(array $userids) {
1303         global $DB;
1305         $conversation = new \stdClass();
1306         $conversation->convhash = helper::get_conversation_hash($userids);
1307         $conversation->timecreated = time();
1308         $conversation->id = $DB->insert_record('message_conversations', $conversation);
1310         // Add members to this conversation.
1311         foreach ($userids as $userid) {
1312             $member = new \stdClass();
1313             $member->conversationid = $conversation->id;
1314             $member->userid = $userid;
1315             $member->timecreated = time();
1316             $DB->insert_record('message_conversation_members', $member);
1317         }
1319         return $conversation->id;
1320     }
1322     /**
1323      * Checks if a user can create a contact request.
1324      *
1325      * @param int $userid The id of the user who is creating the contact request
1326      * @param int $requesteduserid The id of the user being requested
1327      * @return bool
1328      */
1329     public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1330         global $CFG;
1332         // If we can't message at all, then we can't create a contact.
1333         if (empty($CFG->messaging)) {
1334             return false;
1335         }
1337         // If we can message anyone on the site then we can create a contact.
1338         if ($CFG->messagingallusers) {
1339             return true;
1340         }
1342         // We need to check if they are in the same course.
1343         return enrol_sharing_course($userid, $requesteduserid);
1344     }
1346     /**
1347      * Handles creating a contact request.
1348      *
1349      * @param int $userid The id of the user who is creating the contact request
1350      * @param int $requesteduserid The id of the user being requested
1351      */
1352     public static function create_contact_request(int $userid, int $requesteduserid) {
1353         global $DB;
1355         $request = new \stdClass();
1356         $request->userid = $userid;
1357         $request->requesteduserid = $requesteduserid;
1358         $request->timecreated = time();
1360         $DB->insert_record('message_contact_requests', $request);
1362         // Send a notification.
1363         $userfrom = \core_user::get_user($userid);
1364         $userfromfullname = fullname($userfrom);
1365         $userto = \core_user::get_user($requesteduserid);
1366         $url = new \moodle_url('/message/pendingcontactrequests.php');
1368         $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1369         $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1371         $message = new \core\message\message();
1372         $message->courseid = SITEID;
1373         $message->component = 'moodle';
1374         $message->name = 'messagecontactrequests';
1375         $message->notification = 1;
1376         $message->userfrom = $userfrom;
1377         $message->userto = $userto;
1378         $message->subject = $subject;
1379         $message->fullmessage = text_to_html($fullmessage);
1380         $message->fullmessageformat = FORMAT_HTML;
1381         $message->fullmessagehtml = $fullmessage;
1382         $message->smallmessage = '';
1383         $message->contexturl = $url->out(false);
1385         message_send($message);
1386     }
1389     /**
1390      * Handles confirming a contact request.
1391      *
1392      * @param int $userid The id of the user who created the contact request
1393      * @param int $requesteduserid The id of the user confirming the request
1394      */
1395     public static function confirm_contact_request(int $userid, int $requesteduserid) {
1396         global $DB;
1398         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1399                 'requesteduserid' => $requesteduserid])) {
1400             self::add_contact($userid, $requesteduserid);
1402             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1403         }
1404     }
1406     /**
1407      * Handles declining a contact request.
1408      *
1409      * @param int $userid The id of the user who created the contact request
1410      * @param int $requesteduserid The id of the user declining the request
1411      */
1412     public static function decline_contact_request(int $userid, int $requesteduserid) {
1413         global $DB;
1415         if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1416                 'requesteduserid' => $requesteduserid])) {
1417             $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1418         }
1419     }
1421     /**
1422      * Handles returning the contact requests for a user.
1423      *
1424      * This also includes the user data necessary to display information
1425      * about the user.
1426      *
1427      * It will not include blocked users.
1428      *
1429      * @param int $userid
1430      * @return array The list of contact requests
1431      */
1432     public static function get_contact_requests(int $userid) : array {
1433         global $DB;
1435         // Used to search for contacts.
1436         $ufields = \user_picture::fields('u');
1438         $sql = "SELECT $ufields, mcr.id as contactrequestid
1439                   FROM {user} u
1440                   JOIN {message_contact_requests} mcr
1441                     ON u.id = mcr.userid
1442              LEFT JOIN {message_users_blocked} mub
1443                     ON (mub.userid = ? AND mub.blockeduserid = u.id)
1444                  WHERE mcr.requesteduserid = ?
1445                    AND u.deleted = 0
1446                    AND mub.id is NULL
1447               ORDER BY mcr.timecreated DESC";
1449         return $DB->get_records_sql($sql, [$userid, $userid]);
1450     }
1452     /**
1453      * Handles adding a contact.
1454      *
1455      * @param int $userid The id of the user who requested to be a contact
1456      * @param int $contactid The id of the contact
1457      */
1458     public static function add_contact(int $userid, int $contactid) {
1459         global $DB;
1461         $messagecontact = new \stdClass();
1462         $messagecontact->userid = $userid;
1463         $messagecontact->contactid = $contactid;
1464         $messagecontact->timecreated = time();
1465         $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1467         $eventparams = [
1468             'objectid' => $messagecontact->id,
1469             'userid' => $userid,
1470             'relateduserid' => $contactid,
1471             'context' => \context_user::instance($userid)
1472         ];
1473         $event = \core\event\message_contact_added::create($eventparams);
1474         $event->add_record_snapshot('message_contacts', $messagecontact);
1475         $event->trigger();
1476     }
1478     /**
1479      * Handles removing a contact.
1480      *
1481      * @param int $userid The id of the user who is removing a user as a contact
1482      * @param int $contactid The id of the user to be removed as a contact
1483      */
1484     public static function remove_contact(int $userid, int $contactid) {
1485         global $DB;
1487         if ($contact = self::get_contact($userid, $contactid)) {
1488             $DB->delete_records('message_contacts', ['id' => $contact->id]);
1490             $event = \core\event\message_contact_removed::create(array(
1491                 'objectid' => $contact->id,
1492                 'userid' => $userid,
1493                 'relateduserid' => $contactid,
1494                 'context' => \context_user::instance($userid)
1495             ));
1496             $event->add_record_snapshot('message_contacts', $contact);
1497             $event->trigger();
1498         }
1499     }
1501     /**
1502      * Handles blocking a user.
1503      *
1504      * @param int $userid The id of the user who is blocking
1505      * @param int $usertoblockid The id of the user being blocked
1506      */
1507     public static function block_user(int $userid, int $usertoblockid) {
1508         global $DB;
1510         $blocked = new \stdClass();
1511         $blocked->userid = $userid;
1512         $blocked->blockeduserid = $usertoblockid;
1513         $blocked->timecreated = time();
1514         $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1516         // Trigger event for blocking a contact.
1517         $event = \core\event\message_user_blocked::create(array(
1518             'objectid' => $blocked->id,
1519             'userid' => $userid,
1520             'relateduserid' => $usertoblockid,
1521             'context' => \context_user::instance($userid)
1522         ));
1523         $event->add_record_snapshot('message_users_blocked', $blocked);
1524         $event->trigger();
1525     }
1527     /**
1528      * Handles unblocking a user.
1529      *
1530      * @param int $userid The id of the user who is unblocking
1531      * @param int $usertounblockid The id of the user being unblocked
1532      */
1533     public static function unblock_user(int $userid, int $usertounblockid) {
1534         global $DB;
1536         if ($blockeduser = $DB->get_record('message_users_blocked',
1537                 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1538             $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1540             // Trigger event for unblocking a contact.
1541             $event = \core\event\message_user_unblocked::create(array(
1542                 'objectid' => $blockeduser->id,
1543                 'userid' => $userid,
1544                 'relateduserid' => $usertounblockid,
1545                 'context' => \context_user::instance($userid)
1546             ));
1547             $event->add_record_snapshot('message_users_blocked', $blockeduser);
1548             $event->trigger();
1549         }
1550     }
1552     /**
1553      * Checks if users are already contacts.
1554      *
1555      * @param int $userid The id of one of the users
1556      * @param int $contactid The id of the other user
1557      * @return bool Returns true if they are a contact, false otherwise
1558      */
1559     public static function is_contact(int $userid, int $contactid) : bool {
1560         global $DB;
1562         $sql = "SELECT id
1563                   FROM {message_contacts} mc
1564                  WHERE (mc.userid = ? AND mc.contactid = ?)
1565                     OR (mc.userid = ? AND mc.contactid = ?)";
1566         return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1567     }
1569     /**
1570      * Returns the row in the database table message_contacts that represents the contact between two people.
1571      *
1572      * @param int $userid The id of one of the users
1573      * @param int $contactid The id of the other user
1574      * @return mixed A fieldset object containing the record, false otherwise
1575      */
1576     public static function get_contact(int $userid, int $contactid) {
1577         global $DB;
1579         $sql = "SELECT mc.*
1580                   FROM {message_contacts} mc
1581                  WHERE (mc.userid = ? AND mc.contactid = ?)
1582                     OR (mc.userid = ? AND mc.contactid = ?)";
1583         return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1584     }
1586     /**
1587      * Checks if a user is already blocked.
1588      *
1589      * @param int $userid
1590      * @param int $blockeduserid
1591      * @return bool Returns true if they are a blocked, false otherwise
1592      */
1593     public static function is_blocked(int $userid, int $blockeduserid) : bool {
1594         global $DB;
1596         return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1597     }
1599     /**
1600      * Checks if a contact request already exists between users.
1601      *
1602      * @param int $userid The id of the user who is creating the contact request
1603      * @param int $requesteduserid The id of the user being requested
1604      * @return bool Returns true if a contact request exists, false otherwise
1605      */
1606     public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1607         global $DB;
1609         $sql = "SELECT id
1610                   FROM {message_contact_requests} mcr
1611                  WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1612                     OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1613         return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1614     }