39a4461b9c4cb722669332d44b990a52a2a95e1a
[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, mcont.blocked as userfrom_blocked, $ufields2,
67                        mcont2.blocked 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_contacts} mcont
78                     ON (mcont.contactid = u.id AND mcont.userid = ?)
79              LEFT JOIN {message_contacts} mcont2
80                     ON (mcont2.contactid = u2.id AND mcont2.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;
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.*, mc.blocked
130                   FROM {user} u
131                   JOIN ($esql) je
132                     ON je.id = u.id
133              LEFT JOIN {message_contacts} mc
134                     ON (mc.contactid = u.id AND mc.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                 $contacts[] = helper::create_contact($user);
148             }
149         }
151         return $contacts;
152     }
154     /**
155      * Handles searching for user in the message area.
156      *
157      * @param int $userid The user id doing the searching
158      * @param string $search The string the user is searching
159      * @param int $limitnum
160      * @return array
161      */
162     public static function search_users($userid, $search, $limitnum = 0) {
163         global $CFG, $DB;
165         require_once($CFG->dirroot . '/lib/coursecatlib.php');
167         // Used to search for contacts.
168         $fullname = $DB->sql_fullname();
169         $ufields = \user_picture::fields('u', array('lastaccess'));
171         // Users not to include.
172         $excludeusers = array($userid, $CFG->siteguest);
173         list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
175         // Ok, let's search for contacts first.
176         $contacts = array();
177         $sql = "SELECT $ufields, mc.blocked
178                   FROM {user} u
179                   JOIN {message_contacts} mc
180                     ON u.id = mc.contactid
181                  WHERE mc.userid = :userid
182                    AND u.deleted = 0
183                    AND u.confirmed = 1
184                    AND " . $DB->sql_like($fullname, ':search', false) . "
185                    AND u.id $exclude
186               ORDER BY " . $DB->sql_fullname();
187         if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
188             0, $limitnum)) {
189             foreach ($users as $user) {
190                 $contacts[] = helper::create_contact($user);
191             }
192         }
194         // Now, let's get the courses.
195         // Make sure to limit searches to enrolled courses.
196         $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
197         $courses = array();
198         // Really we want the user to be able to view the participants if they have the capability
199         // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
200         // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
201         // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
202         if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum),
203                 array('moodle/course:viewparticipants'))) {
204             foreach ($arrcourses as $course) {
205                 if (isset($enrolledcourses[$course->id])) {
206                     $data = new \stdClass();
207                     $data->id = $course->id;
208                     $data->shortname = $course->shortname;
209                     $data->fullname = $course->fullname;
210                     $courses[] = $data;
211                 }
212             }
213         }
215         // Let's get those non-contacts. Toast them gears boi.
216         // Note - you can only block contacts, so these users will not be blocked, so no need to get that
217         // extra detail from the database.
218         $noncontacts = array();
219         $sql = "SELECT $ufields
220                   FROM {user} u
221                  WHERE u.deleted = 0
222                    AND u.confirmed = 1
223                    AND " . $DB->sql_like($fullname, ':search', false) . "
224                    AND u.id $exclude
225                    AND u.id NOT IN (SELECT contactid
226                                       FROM {message_contacts}
227                                      WHERE userid = :userid)
228               ORDER BY " . $DB->sql_fullname();
229         if ($users = $DB->get_records_sql($sql,  array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
230             0, $limitnum)) {
231             foreach ($users as $user) {
232                 $noncontacts[] = helper::create_contact($user);
233             }
234         }
236         return array($contacts, $courses, $noncontacts);
237     }
239     /**
240      * Returns the contacts and their conversation to display in the contacts area.
241      *
242      * ** WARNING **
243      * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
244      * to retrieve too much information in a single call will cause performance problems.
245      * ** WARNING **
246      *
247      * This function has specifically been altered to break each of the data sets it
248      * requires into separate database calls. This is to avoid the performance problems
249      * observed when attempting to join large data sets (e.g. the message tables and
250      * the user table).
251      *
252      * While it is possible to gather the data in a single query, and it may even be
253      * more efficient with a correctly tuned database, we have opted to trade off some of
254      * the benefits of a single query in order to ensure this function will work on
255      * most databases with default tunings and with large data sets.
256      *
257      * @param int $userid The user id
258      * @param int $limitfrom
259      * @param int $limitnum
260      * @return array
261      */
262     public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
263         global $DB;
265         // Get the last message from each conversation that the user belongs to.
266         $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
267                   FROM {messages} m
268             INNER JOIN (
269                           SELECT MAX(m.id) AS messageid
270                             FROM {messages} m
271                       INNER JOIN (
272                                       SELECT m.conversationid, MAX(m.timecreated) as maxtime
273                                         FROM {messages} m
274                                   INNER JOIN {message_conversation_members} mcm
275                                           ON mcm.conversationid = m.conversationid
276                                    LEFT JOIN {message_user_actions} mua
277                                           ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
278                                        WHERE mua.id is NULL
279                                          AND mcm.userid = :userid2
280                                     GROUP BY m.conversationid
281                                  ) maxmessage
282                                ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
283                          GROUP BY m.conversationid
284                        ) lastmessage
285                     ON lastmessage.messageid = m.id
286             INNER JOIN {message_conversation_members} mcm
287                     ON mcm.conversationid = m.conversationid
288             INNER JOIN {message_conversation_members} mcm2
289                     ON mcm2.conversationid = m.conversationid
290                  WHERE mcm.userid = m.useridfrom
291                    AND mcm.id != mcm2.id
292               ORDER BY m.timecreated DESC";
293         $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
294             'userid2' => $userid], $limitfrom, $limitnum);
296         $messages = [];
297         foreach ($messageset as $message) {
298             $messages[$message->id] = $message;
299         }
300         $messageset->close();
302         // If there are no messages return early.
303         if (empty($messages)) {
304             return [];
305         }
307         // We need to pull out the list of other users that are part of each of these conversations. This
308         // needs to be done in a separate query to avoid doing a join on the messages tables and the user
309         // tables because on large sites these tables are massive which results in extremely slow
310         // performance (typically due to join buffer exhaustion).
311         $otheruserids = array_map(function($message) use ($userid) {
312             return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
313         }, array_values($messages));
315         // Ok, let's get the other members in the conversations.
316         list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
317         $userfields = \user_picture::fields('u', array('lastaccess'));
318         $userssql = "SELECT $userfields
319                        FROM {user} u
320                       WHERE id $useridsql
321                         AND deleted = 0";
322         $otherusers = $DB->get_records_sql($userssql, $usersparams);
324         // If there are no other users (user may have been deleted), then do not continue.
325         if (empty($otherusers)) {
326             return [];
327         }
329         $contactssql = "SELECT contactid, blocked
330                           FROM {message_contacts}
331                          WHERE userid = ?
332                            AND contactid $useridsql";
333         $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
335         // Finally, let's get the unread messages count for this user so that we can add them
336         // to the conversation. Remember we need to ignore the messages the user sent.
337         $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
338                               FROM {messages} m
339                         INNER JOIN {message_conversations} mc
340                                 ON mc.id = m.conversationid
341                         INNER JOIN {message_conversation_members} mcm
342                                 ON m.conversationid = mcm.conversationid
343                          LEFT JOIN {message_user_actions} mua
344                                 ON (mua.messageid = m.id AND mua.userid = ? AND
345                                    (mua.action = ? OR mua.action = ?))
346                              WHERE mcm.userid = ?
347                                AND m.useridfrom != ?
348                                AND mua.id is NULL
349                           GROUP BY useridfrom';
350         $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
351             $userid, $userid]);
353         // Get rid of the table prefix.
354         $userfields = str_replace('u.', '', $userfields);
355         $userproperties = explode(',', $userfields);
356         $arrconversations = array();
357         foreach ($messages as $message) {
358             $conversation = new \stdClass();
359             $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
360             $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
361             $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
363             // It's possible the other user was deleted, so, skip.
364             if (is_null($otheruser)) {
365                 continue;
366             }
368             // Add the other user's information to the conversation, if we have one.
369             foreach ($userproperties as $prop) {
370                 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
371             }
373             // Add the contact's information, if we have one.
374             $conversation->blocked = ($contact) ? $contact->blocked : null;
376             // Add the message information.
377             $conversation->messageid = $message->id;
378             $conversation->smallmessage = $message->smallmessage;
379             $conversation->useridfrom = $message->useridfrom;
381             // Only consider it unread if $user has unread messages.
382             if (isset($unreadcounts[$otheruserid])) {
383                 $conversation->isread = false;
384                 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
385             } else {
386                 $conversation->isread = true;
387             }
389             $arrconversations[$otheruserid] = helper::create_contact($conversation);
390         }
392         return $arrconversations;
393     }
395     /**
396      * Returns the contacts to display in the contacts area.
397      *
398      * @param int $userid The user id
399      * @param int $limitfrom
400      * @param int $limitnum
401      * @return array
402      */
403     public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
404         global $DB;
406         $arrcontacts = array();
407         $sql = "SELECT u.*, mc.blocked
408                   FROM {message_contacts} mc
409                   JOIN {user} u
410                     ON mc.contactid = u.id
411                  WHERE mc.userid = :userid
412                    AND u.deleted = 0
413               ORDER BY " . $DB->sql_fullname();
414         if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
415             foreach ($contacts as $contact) {
416                 $arrcontacts[] = helper::create_contact($contact);
417             }
418         }
420         return $arrcontacts;
421     }
423     /**
424      * Returns the an array of the users the given user is in a conversation
425      * with who are a contact and the number of unread messages.
426      *
427      * @param int $userid The user id
428      * @param int $limitfrom
429      * @param int $limitnum
430      * @return array
431      */
432     public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
433         global $DB;
435         $userfields = \user_picture::fields('u', array('lastaccess'));
436         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
437                               FROM {message_contacts} mc
438                         INNER JOIN {user} u
439                                 ON u.id = mc.contactid
440                          LEFT JOIN {messages} m
441                                 ON m.useridfrom = mc.contactid
442                          LEFT JOIN {message_conversation_members} mcm
443                                 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
444                          LEFT JOIN {message_user_actions} mua
445                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
446                              WHERE mua.id is NULL
447                                AND mc.userid = ?
448                                AND mc.blocked = 0
449                                AND u.deleted = 0
450                           GROUP BY $userfields";
452         return $DB->get_records_sql($unreadcountssql, [$userid, $userid, self::MESSAGE_ACTION_READ,
453             $userid, $userid], $limitfrom, $limitnum);
454     }
456     /**
457      * Returns the an array of the users the given user is in a conversation
458      * with who are not a contact and the number of unread messages.
459      *
460      * @param int $userid The user id
461      * @param int $limitfrom
462      * @param int $limitnum
463      * @return array
464      */
465     public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
466         global $DB;
468         $userfields = \user_picture::fields('u', array('lastaccess'));
469         $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
470                               FROM {user} u
471                         INNER JOIN {messages} m
472                                 ON m.useridfrom = u.id
473                         INNER JOIN {message_conversation_members} mcm
474                                 ON mcm.conversationid = m.conversationid
475                          LEFT JOIN {message_user_actions} mua
476                                 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
477                          LEFT JOIN {message_contacts} mc
478                                 ON (mc.userid = ? AND mc.contactid = u.id)
479                              WHERE mcm.userid = ?
480                                AND mcm.userid != m.useridfrom
481                                AND mua.id is NULL
482                                AND mc.id is NULL
483                                AND u.deleted = 0
484                           GROUP BY $userfields";
486         return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid],
487             $limitfrom, $limitnum);
488     }
490     /**
491      * Returns the messages to display in the message area.
492      *
493      * @param int $userid the current user
494      * @param int $otheruserid the other user
495      * @param int $limitfrom
496      * @param int $limitnum
497      * @param string $sort
498      * @param int $timefrom the time from the message being sent
499      * @param int $timeto the time up until the message being sent
500      * @return array
501      */
502     public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
503         $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
505         if (!empty($timefrom)) {
506             // Check the cache to see if we even need to do a DB query.
507             $cache = \cache::make('core', 'message_time_last_message_between_users');
508             $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
509             $lastcreated = $cache->get($key);
511             // The last known message time is earlier than the one being requested so we can
512             // just return an empty result set rather than having to query the DB.
513             if ($lastcreated && $lastcreated < $timefrom) {
514                 return [];
515             }
516         }
518         $arrmessages = array();
519         if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
520                                              $sort, $timefrom, $timeto)) {
522             $arrmessages = helper::create_messages($userid, $messages);
523         }
525         return $arrmessages;
526     }
528     /**
529      * Returns the most recent message between two users.
530      *
531      * @param int $userid the current user
532      * @param int $otheruserid the other user
533      * @return \stdClass|null
534      */
535     public static function get_most_recent_message($userid, $otheruserid) {
536         // We want two messages here so we get an accurate 'blocktime' value.
537         if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
538             // Swap the order so we now have them in historical order.
539             $messages = array_reverse($messages);
540             $arrmessages = helper::create_messages($userid, $messages);
541             return array_pop($arrmessages);
542         }
544         return null;
545     }
547     /**
548      * Returns the profile information for a contact for a user.
549      *
550      * @param int $userid The user id
551      * @param int $otheruserid The id of the user whose profile we want to view.
552      * @return \stdClass
553      */
554     public static function get_profile($userid, $otheruserid) {
555         global $CFG, $DB, $PAGE;
557         require_once($CFG->dirroot . '/user/lib.php');
559         $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
561         // Create the data we are going to pass to the renderable.
562         $data = new \stdClass();
563         $data->userid = $otheruserid;
564         $data->fullname = fullname($user);
565         $data->city = '';
566         $data->country = '';
567         $data->email = '';
568         $data->isonline = null;
569         // Get the user picture data - messaging has always shown these to the user.
570         $userpicture = new \user_picture($user);
571         $userpicture->size = 1; // Size f1.
572         $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
573         $userpicture->size = 0; // Size f2.
574         $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
576         $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
577         if ($userfields) {
578             if (isset($userfields['city'])) {
579                 $data->city = $userfields['city'];
580             }
581             if (isset($userfields['country'])) {
582                 $data->country = $userfields['country'];
583             }
584             if (isset($userfields['email'])) {
585                 $data->email = $userfields['email'];
586             }
587             if (isset($userfields['lastaccess'])) {
588                 $data->isonline = helper::is_online($userfields['lastaccess']);
589             }
590         }
592         // Check if the contact has been blocked.
593         $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
594         if ($contact) {
595             $data->isblocked = (bool) $contact->blocked;
596             $data->iscontact = true;
597         } else {
598             $data->isblocked = false;
599             $data->iscontact = false;
600         }
602         return $data;
603     }
605     /**
606      * Checks if a user can delete messages they have either received or sent.
607      *
608      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
609      *  but will still seem as if it was by the user)
610      * @return bool Returns true if a user can delete the conversation, false otherwise.
611      */
612     public static function can_delete_conversation($userid) {
613         global $USER;
615         $systemcontext = \context_system::instance();
617         // Let's check if the user is allowed to delete this conversation.
618         if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
619             ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
620                 $USER->id == $userid))) {
621             return true;
622         }
624         return false;
625     }
627     /**
628      * Deletes a conversation.
629      *
630      * This function does not verify any permissions.
631      *
632      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
633      *  but will still seem as if it was by the user)
634      * @param int $otheruserid The id of the other user in the conversation
635      * @return bool
636      */
637     public static function delete_conversation($userid, $otheruserid) {
638         global $DB, $USER;
640         $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
642         // If there is no conversation, there is nothing to do.
643         if (!$conversationid) {
644             return true;
645         }
647         // Get all messages belonging to this conversation that have not already been deleted by this user.
648         $sql = "SELECT m.*
649                  FROM {messages} m
650            INNER JOIN {message_conversations} mc
651                    ON m.conversationid = mc.id
652             LEFT JOIN {message_user_actions} mua
653                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
654                 WHERE mua.id is NULL
655                   AND mc.id = ?
656              ORDER BY m.timecreated ASC";
657         $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
659         // Ok, mark these as deleted.
660         foreach ($messages as $message) {
661             $mua = new \stdClass();
662             $mua->userid = $userid;
663             $mua->messageid = $message->id;
664             $mua->action = self::MESSAGE_ACTION_DELETED;
665             $mua->timecreated = time();
666             $mua->id = $DB->insert_record('message_user_actions', $mua);
668             if ($message->useridfrom == $userid) {
669                 $useridto = $otheruserid;
670             } else {
671                 $useridto = $userid;
672             }
673             \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
674                 $USER->id, $message->id, $mua->id)->trigger();
675         }
677         return true;
678     }
680     /**
681      * Returns the count of unread conversations (collection of messages from a single user) for
682      * the given user.
683      *
684      * @param \stdClass $user the user who's conversations should be counted
685      * @return int the count of the user's unread conversations
686      */
687     public static function count_unread_conversations($user = null) {
688         global $USER, $DB;
690         if (empty($user)) {
691             $user = $USER;
692         }
694         $sql = "SELECT COUNT(DISTINCT(m.conversationid))
695                   FROM {messages} m
696             INNER JOIN {message_conversations} mc
697                     ON m.conversationid = mc.id
698             INNER JOIN {message_conversation_members} mcm
699                     ON mc.id = mcm.conversationid
700              LEFT JOIN {message_user_actions} mua
701                     ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
702                  WHERE mcm.userid = ?
703                    AND mcm.userid != m.useridfrom
704                    AND mua.id is NULL";
706         return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
707     }
709     /**
710      * Marks all messages being sent to a user in a particular conversation.
711      *
712      * If $conversationdid is null then it marks all messages as read sent to $userid.
713      *
714      * @param int $userid
715      * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
716      */
717     public static function mark_all_messages_as_read($userid, $conversationid = null) {
718         global $DB;
720         $messagesql = "SELECT m.*
721                          FROM {messages} m
722                    INNER JOIN {message_conversations} mc
723                            ON mc.id = m.conversationid
724                    INNER JOIN {message_conversation_members} mcm
725                            ON mcm.conversationid = mc.id
726                         WHERE mcm.userid = ?
727                           AND m.useridfrom != ?";
728         $messageparams[] = $userid;
729         $messageparams[] = $userid;
730         if (!is_null($conversationid)) {
731             $messagesql .= " AND mc.id = ?";
732             $messageparams[] = $conversationid;
733         }
735         $messages = $DB->get_recordset_sql($messagesql, $messageparams);
736         foreach ($messages as $message) {
737             self::mark_message_as_read($userid, $message);
738         }
739         $messages->close();
740     }
742     /**
743      * Marks all notifications being sent from one user to another user as read.
744      *
745      * If the from user is null then it marks all notifications as read sent to the to user.
746      *
747      * @param int $touserid the id of the message recipient
748      * @param int|null $fromuserid the id of the message sender, null if all messages
749      * @return void
750      */
751     public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
752         global $DB;
754         $notificationsql = "SELECT n.*
755                               FROM {notifications} n
756                              WHERE useridto = ?
757                                AND timeread is NULL";
758         $notificationsparams = [$touserid];
759         if (!empty($fromuserid)) {
760             $notificationsql .= " AND useridfrom = ?";
761             $notificationsparams[] = $fromuserid;
762         }
764         $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
765         foreach ($notifications as $notification) {
766             self::mark_notification_as_read($notification);
767         }
768         $notifications->close();
769     }
771     /**
772      * Marks ALL messages being sent from $fromuserid to $touserid as read.
773      *
774      * Can be filtered by type.
775      *
776      * @deprecated since 3.5
777      * @param int $touserid the id of the message recipient
778      * @param int $fromuserid the id of the message sender
779      * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
780      * @return void
781      */
782     public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
783         debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
784             '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
785             DEBUG_DEVELOPER);
787         $type = strtolower($type);
789         $conversationid = null;
790         $ignoremessages = false;
791         if (!empty($fromuserid)) {
792             $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
793             if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
794                 $ignoremessages = true;
795             }
796         }
798         if (!empty($type)) {
799             if ($type == MESSAGE_TYPE_NOTIFICATION) {
800                 self::mark_all_notifications_as_read($touserid, $fromuserid);
801             } else if ($type == MESSAGE_TYPE_MESSAGE) {
802                 if (!$ignoremessages) {
803                     self::mark_all_messages_as_read($touserid, $conversationid);
804                 }
805             }
806         } else { // We want both.
807             self::mark_all_notifications_as_read($touserid, $fromuserid);
808             if (!$ignoremessages) {
809                 self::mark_all_messages_as_read($touserid, $conversationid);
810             }
811         }
812     }
814     /**
815      * Returns message preferences.
816      *
817      * @param array $processors
818      * @param array $providers
819      * @param \stdClass $user
820      * @return \stdClass
821      * @since 3.2
822      */
823     public static function get_all_message_preferences($processors, $providers, $user) {
824         $preferences = helper::get_providers_preferences($providers, $user->id);
825         $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
827         // For every processors put its options on the form (need to get function from processor's lib.php).
828         foreach ($processors as $processor) {
829             $processor->object->load_data($preferences, $user->id);
830         }
832         // Load general messaging preferences.
833         $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
834         $preferences->mailformat = $user->mailformat;
835         $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
837         return $preferences;
838     }
840     /**
841      * Count the number of users blocked by a user.
842      *
843      * @param \stdClass $user The user object
844      * @return int the number of blocked users
845      */
846     public static function count_blocked_users($user = null) {
847         global $USER, $DB;
849         if (empty($user)) {
850             $user = $USER;
851         }
853         $sql = "SELECT count(mc.id)
854                   FROM {message_contacts} mc
855                  WHERE mc.userid = :userid AND mc.blocked = 1";
856         return $DB->count_records_sql($sql, array('userid' => $user->id));
857     }
859     /**
860      * Determines if a user is permitted to send another user a private message.
861      * If no sender is provided then it defaults to the logged in user.
862      *
863      * @param \stdClass $recipient The user object.
864      * @param \stdClass|null $sender The user object.
865      * @return bool true if user is permitted, false otherwise.
866      */
867     public static function can_post_message($recipient, $sender = null) {
868         global $USER;
870         if (is_null($sender)) {
871             // The message is from the logged in user, unless otherwise specified.
872             $sender = $USER;
873         }
875         if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
876             return false;
877         }
879         // The recipient blocks messages from non-contacts and the
880         // sender isn't a contact.
881         if (self::is_user_non_contact_blocked($recipient, $sender)) {
882             return false;
883         }
885         $senderid = null;
886         if ($sender !== null && isset($sender->id)) {
887             $senderid = $sender->id;
888         }
889         // The recipient has specifically blocked this sender.
890         if (self::is_user_blocked($recipient->id, $senderid)) {
891             return false;
892         }
894         return true;
895     }
897     /**
898      * Checks if the recipient is allowing messages from users that aren't a
899      * contact. If not then it checks to make sure the sender is in the
900      * recipient's contacts.
901      *
902      * @param \stdClass $recipient The user object.
903      * @param \stdClass|null $sender The user object.
904      * @return bool true if $sender is blocked, false otherwise.
905      */
906     public static function is_user_non_contact_blocked($recipient, $sender = null) {
907         global $USER, $DB;
909         if (is_null($sender)) {
910             // The message is from the logged in user, unless otherwise specified.
911             $sender = $USER;
912         }
914         $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
915         if (!empty($blockednoncontacts)) {
916             // Confirm the sender is a contact of the recipient.
917             $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
918             if ($exists) {
919                 // All good, the recipient is a contact of the sender.
920                 return false;
921             } else {
922                 // Oh no, the recipient is not a contact. Looks like we can't send the message.
923                 return true;
924             }
925         }
927         return false;
928     }
930     /**
931      * Checks if the recipient has specifically blocked the sending user.
932      *
933      * Note: This function will always return false if the sender has the
934      * readallmessages capability at the system context level.
935      *
936      * @param int $recipientid User ID of the recipient.
937      * @param int $senderid User ID of the sender.
938      * @return bool true if $sender is blocked, false otherwise.
939      */
940     public static function is_user_blocked($recipientid, $senderid = null) {
941         global $USER, $DB;
943         if (is_null($senderid)) {
944             // The message is from the logged in user, unless otherwise specified.
945             $senderid = $USER->id;
946         }
948         $systemcontext = \context_system::instance();
949         if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
950             return false;
951         }
953         if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
954             return true;
955         }
957         return false;
958     }
960     /**
961      * Get specified message processor, validate corresponding plugin existence and
962      * system configuration.
963      *
964      * @param string $name  Name of the processor.
965      * @param bool $ready only return ready-to-use processors.
966      * @return mixed $processor if processor present else empty array.
967      * @since Moodle 3.2
968      */
969     public static function get_message_processor($name, $ready = false) {
970         global $DB, $CFG;
972         $processor = $DB->get_record('message_processors', array('name' => $name));
973         if (empty($processor)) {
974             // Processor not found, return.
975             return array();
976         }
978         $processor = self::get_processed_processor_object($processor);
979         if ($ready) {
980             if ($processor->enabled && $processor->configured) {
981                 return $processor;
982             } else {
983                 return array();
984             }
985         } else {
986             return $processor;
987         }
988     }
990     /**
991      * Returns weather a given processor is enabled or not.
992      * Note:- This doesn't check if the processor is configured or not.
993      *
994      * @param string $name Name of the processor
995      * @return bool
996      */
997     public static function is_processor_enabled($name) {
999         $cache = \cache::make('core', 'message_processors_enabled');
1000         $status = $cache->get($name);
1002         if ($status === false) {
1003             $processor = self::get_message_processor($name);
1004             if (!empty($processor)) {
1005                 $cache->set($name, $processor->enabled);
1006                 return $processor->enabled;
1007             } else {
1008                 return false;
1009             }
1010         }
1012         return $status;
1013     }
1015     /**
1016      * Set status of a processor.
1017      *
1018      * @param \stdClass $processor processor record.
1019      * @param 0|1 $enabled 0 or 1 to set the processor status.
1020      * @return bool
1021      * @since Moodle 3.2
1022      */
1023     public static function update_processor_status($processor, $enabled) {
1024         global $DB;
1025         $cache = \cache::make('core', 'message_processors_enabled');
1026         $cache->delete($processor->name);
1027         return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1028     }
1030     /**
1031      * Given a processor object, loads information about it's settings and configurations.
1032      * This is not a public api, instead use @see \core_message\api::get_message_processor()
1033      * or @see \get_message_processors()
1034      *
1035      * @param \stdClass $processor processor object
1036      * @return \stdClass processed processor object
1037      * @since Moodle 3.2
1038      */
1039     public static function get_processed_processor_object(\stdClass $processor) {
1040         global $CFG;
1042         $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1043         if (is_readable($processorfile)) {
1044             include_once($processorfile);
1045             $processclass = 'message_output_' . $processor->name;
1046             if (class_exists($processclass)) {
1047                 $pclass = new $processclass();
1048                 $processor->object = $pclass;
1049                 $processor->configured = 0;
1050                 if ($pclass->is_system_configured()) {
1051                     $processor->configured = 1;
1052                 }
1053                 $processor->hassettings = 0;
1054                 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1055                     $processor->hassettings = 1;
1056                 }
1057                 $processor->available = 1;
1058             } else {
1059                 print_error('errorcallingprocessor', 'message');
1060             }
1061         } else {
1062             $processor->available = 0;
1063         }
1064         return $processor;
1065     }
1067     /**
1068      * Retrieve users blocked by $user1
1069      *
1070      * @param int $userid The user id of the user whos blocked users we are returning
1071      * @return array the users blocked
1072      */
1073     public static function get_blocked_users($userid) {
1074         global $DB;
1076         $userfields = \user_picture::fields('u', array('lastaccess'));
1077         $blockeduserssql = "SELECT $userfields
1078                               FROM {message_contacts} mc
1079                         INNER JOIN {user} u
1080                                 ON u.id = mc.contactid
1081                              WHERE u.deleted = 0
1082                                AND mc.userid = ?
1083                                AND mc.blocked = 1
1084                           GROUP BY $userfields
1085                           ORDER BY u.firstname ASC";
1086         return $DB->get_records_sql($blockeduserssql, [$userid]);
1087     }
1089     /**
1090      * Mark a single message as read.
1091      *
1092      * @param int $userid The user id who marked the message as read
1093      * @param \stdClass $message The message
1094      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1095      */
1096     public static function mark_message_as_read($userid, $message, $timeread = null) {
1097         global $DB;
1099         if (is_null($timeread)) {
1100             $timeread = time();
1101         }
1103         // Check if the user has already read this message.
1104         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1105                 'messageid' => $message->id, 'action' => self::MESSAGE_ACTION_READ])) {
1106             $mua = new \stdClass();
1107             $mua->userid = $userid;
1108             $mua->messageid = $message->id;
1109             $mua->action = self::MESSAGE_ACTION_READ;
1110             $mua->timecreated = $timeread;
1111             $mua->id = $DB->insert_record('message_user_actions', $mua);
1113             // Get the context for the user who received the message.
1114             $context = \context_user::instance($userid, IGNORE_MISSING);
1115             // If the user no longer exists the context value will be false, in this case use the system context.
1116             if ($context === false) {
1117                 $context = \context_system::instance();
1118             }
1120             // Trigger event for reading a message.
1121             $event = \core\event\message_viewed::create(array(
1122                 'objectid' => $mua->id,
1123                 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1124                 'context' => $context,
1125                 'relateduserid' => $message->useridfrom,
1126                 'other' => array(
1127                     'messageid' => $message->id
1128                 )
1129             ));
1130             $event->trigger();
1131         }
1132     }
1134     /**
1135      * Mark a single notification as read.
1136      *
1137      * @param \stdClass $notification The notification
1138      * @param int|null $timeread The time the message was marked as read, if null will default to time()
1139      */
1140     public static function mark_notification_as_read($notification, $timeread = null) {
1141         global $DB;
1143         if (is_null($timeread)) {
1144             $timeread = time();
1145         }
1147         if (is_null($notification->timeread)) {
1148             $updatenotification = new \stdClass();
1149             $updatenotification->id = $notification->id;
1150             $updatenotification->timeread = $timeread;
1152             $DB->update_record('notifications', $updatenotification);
1154             // Trigger event for reading a notification.
1155             \core\event\notification_viewed::create_from_ids(
1156                 $notification->useridfrom,
1157                 $notification->useridto,
1158                 $notification->id
1159             )->trigger();
1160         }
1161     }
1163     /**
1164      * Checks if a user can delete a message.
1165      *
1166      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1167      *  but will still seem as if it was by the user)
1168      * @param int $messageid The message id
1169      * @return bool Returns true if a user can delete the message, false otherwise.
1170      */
1171     public static function can_delete_message($userid, $messageid) {
1172         global $DB, $USER;
1174         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1175                   FROM {messages} m
1176             INNER JOIN {message_conversations} mc
1177                     ON m.conversationid = mc.id
1178             INNER JOIN {message_conversation_members} mcm
1179                     ON mcm.conversationid = mc.id
1180                  WHERE mcm.userid != m.useridfrom
1181                    AND m.id = ?";
1182         $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1184         if ($message->useridfrom == $userid) {
1185             $userdeleting = 'useridfrom';
1186         } else if ($message->useridto == $userid) {
1187             $userdeleting = 'useridto';
1188         } else {
1189             return false;
1190         }
1192         $systemcontext = \context_system::instance();
1194         // Let's check if the user is allowed to delete this message.
1195         if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1196             ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1197                 $USER->id == $message->$userdeleting))) {
1198             return true;
1199         }
1201         return false;
1202     }
1204     /**
1205      * Deletes a message.
1206      *
1207      * This function does not verify any permissions.
1208      *
1209      * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1210      *  but will still seem as if it was by the user)
1211      * @param int $messageid The message id
1212      * @return bool
1213      */
1214     public static function delete_message($userid, $messageid) {
1215         global $DB;
1217         $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1218                   FROM {messages} m
1219             INNER JOIN {message_conversations} mc
1220                     ON m.conversationid = mc.id
1221             INNER JOIN {message_conversation_members} mcm
1222                     ON mcm.conversationid = mc.id
1223                  WHERE mcm.userid != m.useridfrom
1224                    AND m.id = ?";
1225         $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1227         // Check if the user has already deleted this message.
1228         if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1229                 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1230             $mua = new \stdClass();
1231             $mua->userid = $userid;
1232             $mua->messageid = $messageid;
1233             $mua->action = self::MESSAGE_ACTION_DELETED;
1234             $mua->timecreated = time();
1235             $mua->id = $DB->insert_record('message_user_actions', $mua);
1237             // Trigger event for deleting a message.
1238             \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1239                 $userid, $message->id, $mua->id)->trigger();
1241             return true;
1242         }
1244         return false;
1245     }
1247     /**
1248      * Returns the conversation between two users.
1249      *
1250      * @param array $userids
1251      * @return int|bool The id of the conversation, false if not found
1252      */
1253     public static function get_conversation_between_users(array $userids) {
1254         global $DB;
1256         $hash = helper::get_conversation_hash($userids);
1258         if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
1259             return $conversation->id;
1260         }
1262         return false;
1263     }
1265     /**
1266      * Creates a conversation between two users.
1267      *
1268      * @param array $userids
1269      * @return int The id of the conversation
1270      */
1271     public static function create_conversation_between_users(array $userids) {
1272         global $DB;
1274         $conversation = new \stdClass();
1275         $conversation->convhash = helper::get_conversation_hash($userids);
1276         $conversation->timecreated = time();
1277         $conversation->id = $DB->insert_record('message_conversations', $conversation);
1279         // Add members to this conversation.
1280         foreach ($userids as $userid) {
1281             $member = new \stdClass();
1282             $member->conversationid = $conversation->id;
1283             $member->userid = $userid;
1284             $member->timecreated = time();
1285             $DB->insert_record('message_conversation_members', $member);
1286         }
1288         return $conversation->id;
1289     }