MDL-36941 core_message: dont query DB unnecessarily checking read status
[moodle.git] / message / classes / api.php
CommitLineData
879e2bef
MN
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/>.
16
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 */
24
25namespace core_message;
26
879e2bef
MN
27defined('MOODLE_INTERNAL') || die();
28
7b55aaa1
MN
29require_once($CFG->dirroot . '/lib/messagelib.php');
30
879e2bef
MN
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 */
37class api {
38
883ce421
MN
39 /**
40 * The action for reading a message.
41 */
42 const MESSAGE_ACTION_READ = 1;
43
44 /**
45 * The action for deleting a message.
46 */
47 const MESSAGE_ACTION_DELETED = 2;
48
cd03b8d7
MN
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
de55cb1b 56 * @return array
cd03b8d7
MN
57 */
58 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
59 global $DB;
60
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_');
64
883ce421
MN
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
cd03b8d7
MN
85 AND u.deleted = 0
86 AND u2.deleted = 0
883ce421 87 AND mua.id is NULL
cd03b8d7
MN
88 AND " . $DB->sql_like('smallmessage', '?', false) . "
89 ORDER BY timecreated DESC";
883ce421
MN
90
91 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
cd03b8d7
MN
92
93 // Convert the messages into searchable contacts with their last message being the message that was searched.
de55cb1b 94 $conversations = array();
cd03b8d7
MN
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 }
dd0c1403
MN
103 $blockedcol = $prefix . 'blocked';
104 $message->blocked = $message->$blockedcol;
105
cd03b8d7 106 $message->messageid = $message->id;
de55cb1b 107 $conversations[] = helper::create_contact($message, $prefix);
cd03b8d7
MN
108 }
109 }
110
de55cb1b 111 return $conversations;
cd03b8d7
MN
112 }
113
114 /**
48e8bdba 115 * Handles searching for user in a particular course in the message area.
cd03b8d7
MN
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
de55cb1b 122 * @return array
cd03b8d7 123 */
48e8bdba 124 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
125 global $DB;
126
127 // Get all the users in the course.
128 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
dd0c1403 129 $sql = "SELECT u.*, mc.blocked
cd03b8d7 130 FROM {user} u
dd0c1403
MN
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)
cd03b8d7
MN
135 WHERE u.deleted = 0";
136 // Add more conditions.
137 $fullname = $DB->sql_fullname();
dd0c1403 138 $sql .= " AND u.id != :userid2
cd03b8d7
MN
139 AND " . $DB->sql_like($fullname, ':search', false) . "
140 ORDER BY " . $DB->sql_fullname();
dd0c1403 141 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 142
cd03b8d7
MN
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) {
de55cb1b 147 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
148 }
149 }
150
de55cb1b 151 return $contacts;
cd03b8d7
MN
152 }
153
154 /**
48e8bdba 155 * Handles searching for user in the message area.
cd03b8d7
MN
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
de55cb1b 160 * @return array
cd03b8d7 161 */
48e8bdba 162 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
163 global $CFG, $DB;
164
165 require_once($CFG->dirroot . '/lib/coursecatlib.php');
166
167 // Used to search for contacts.
168 $fullname = $DB->sql_fullname();
169 $ufields = \user_picture::fields('u', array('lastaccess'));
170
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);
174
175 // Ok, let's search for contacts first.
176 $contacts = array();
dd0c1403 177 $sql = "SELECT $ufields, mc.blocked
cd03b8d7
MN
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();
7b55aaa1
MN
187 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
188 0, $limitnum)) {
cd03b8d7 189 foreach ($users as $user) {
de55cb1b 190 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
191 }
192 }
193
194 // Now, let's get the courses.
f3249577
AG
195 // Make sure to limit searches to enrolled courses.
196 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 197 $courses = array();
93b47710
MN
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.
f3249577
AG
202 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum),
203 array('moodle/course:viewparticipants'))) {
cd03b8d7 204 foreach ($arrcourses as $course) {
f3249577
AG
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 }
cd03b8d7
MN
212 }
213 }
214
215 // Let's get those non-contacts. Toast them gears boi.
dd0c1403
MN
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.
cd03b8d7
MN
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
7b55aaa1
MN
225 AND u.id NOT IN (SELECT contactid
226 FROM {message_contacts}
cd03b8d7
MN
227 WHERE userid = :userid)
228 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
229 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
230 0, $limitnum)) {
cd03b8d7 231 foreach ($users as $user) {
de55cb1b 232 $noncontacts[] = helper::create_contact($user);
cd03b8d7
MN
233 }
234 }
235
de55cb1b 236 return array($contacts, $courses, $noncontacts);
cd03b8d7
MN
237 }
238
879e2bef
MN
239 /**
240 * Returns the contacts and their conversation to display in the contacts area.
241 *
349f4261
RW
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 *
879e2bef 257 * @param int $userid The user id
879e2bef
MN
258 * @param int $limitfrom
259 * @param int $limitnum
de55cb1b 260 * @return array
879e2bef 261 */
349f4261
RW
262 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
263 global $DB;
264
883ce421
MN
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);
349f4261 295
349f4261
RW
296 $messages = [];
297 foreach ($messageset as $message) {
883ce421 298 $messages[$message->id] = $message;
349f4261
RW
299 }
300 $messageset->close();
301
883ce421
MN
302 // If there are no messages return early.
303 if (empty($messages)) {
304 return [];
305 }
306
349f4261
RW
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));
314
883ce421 315 // Ok, let's get the other members in the conversations.
349f4261 316 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
883ce421 317 $userfields = \user_picture::fields('u', array('lastaccess'));
349f4261 318 $userssql = "SELECT $userfields
883ce421
MN
319 FROM {user} u
320 WHERE id $useridsql
321 AND deleted = 0";
349f4261
RW
322 $otherusers = $DB->get_records_sql($userssql, $usersparams);
323
883ce421
MN
324 // If there are no other users (user may have been deleted), then do not continue.
325 if (empty($otherusers)) {
326 return [];
327 }
328
349f4261 329 $contactssql = "SELECT contactid, blocked
883ce421
MN
330 FROM {message_contacts}
331 WHERE userid = ?
332 AND contactid $useridsql";
333 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
349f4261
RW
334
335 // Finally, let's get the unread messages count for this user so that we can add them
883ce421
MN
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]);
352
353 // Get rid of the table prefix.
354 $userfields = str_replace('u.', '', $userfields);
349f4261 355 $userproperties = explode(',', $userfields);
de55cb1b 356 $arrconversations = array();
349f4261
RW
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;
362
883ce421
MN
363 // It's possible the other user was deleted, so, skip.
364 if (is_null($otheruser)) {
365 continue;
366 }
367
349f4261
RW
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 }
372
373 // Add the contact's information, if we have one.
374 $conversation->blocked = ($contact) ? $contact->blocked : null;
375
376 // Add the message information.
377 $conversation->messageid = $message->id;
378 $conversation->smallmessage = $message->smallmessage;
379 $conversation->useridfrom = $message->useridfrom;
380
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;
879e2bef 387 }
349f4261 388
42e2f6c0 389 $arrconversations[$otheruserid] = helper::create_contact($conversation);
879e2bef
MN
390 }
391
de55cb1b 392 return $arrconversations;
879e2bef
MN
393 }
394
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
de55cb1b 401 * @return array
879e2bef
MN
402 */
403 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
404 global $DB;
405
406 $arrcontacts = array();
dd0c1403 407 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
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) {
de55cb1b 416 $arrcontacts[] = helper::create_contact($contact);
879e2bef
MN
417 }
418 }
419
de55cb1b 420 return $arrcontacts;
879e2bef
MN
421 }
422
883ce421
MN
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;
434
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";
451
452 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, self::MESSAGE_ACTION_READ,
453 $userid, $userid], $limitfrom, $limitnum);
454 }
455
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;
467
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";
485
486 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid],
487 $limitfrom, $limitnum);
488 }
489
879e2bef
MN
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
8ec78c48 497 * @param string $sort
ffd7798c
MN
498 * @param int $timefrom the time from the message being sent
499 * @param int $timeto the time up until the message being sent
de55cb1b 500 * @return array
879e2bef 501 */
fb1469d8 502 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 503 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 504
ffd7798c 505 if (!empty($timefrom)) {
fb1469d8 506 // Check the cache to see if we even need to do a DB query.
ffd7798c
MN
507 $cache = \cache::make('core', 'message_time_last_message_between_users');
508 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
fb1469d8
RW
509 $lastcreated = $cache->get($key);
510
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.
ffd7798c 513 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
514 return [];
515 }
516 }
517
879e2bef 518 $arrmessages = array();
fb1469d8 519 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 520 $sort, $timefrom, $timeto)) {
fb1469d8 521
de55cb1b 522 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
523 }
524
de55cb1b 525 return $arrmessages;
879e2bef 526 }
c060cd49
MN
527
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
de55cb1b 533 * @return \stdClass|null
c060cd49
MN
534 */
535 public static function get_most_recent_message($userid, $otheruserid) {
536 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 537 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
538 // Swap the order so we now have them in historical order.
539 $messages = array_reverse($messages);
de55cb1b 540 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
541 return array_pop($arrmessages);
542 }
543
544 return null;
545 }
c6e97f54
MN
546
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.
de55cb1b 552 * @return \stdClass
c6e97f54
MN
553 */
554 public static function get_profile($userid, $otheruserid) {
f4c39cb9 555 global $CFG, $DB, $PAGE;
c6e97f54
MN
556
557 require_once($CFG->dirroot . '/user/lib.php');
558
f4c39cb9
MN
559 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
560
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 = '';
cb805753 568 $data->isonline = null;
f4c39cb9
MN
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);
575
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'];
bf58081d 583 }
f4c39cb9
MN
584 if (isset($userfields['email'])) {
585 $data->email = $userfields['email'];
c6e97f54 586 }
f4c39cb9
MN
587 if (isset($userfields['lastaccess'])) {
588 $data->isonline = helper::is_online($userfields['lastaccess']);
589 }
590 }
c6e97f54 591
f4c39cb9
MN
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;
c6e97f54 600 }
f4c39cb9
MN
601
602 return $data;
c6e97f54 603 }
dec0cd99
MN
604
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)
1f64514d 610 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99
MN
611 */
612 public static function can_delete_conversation($userid) {
613 global $USER;
614
615 $systemcontext = \context_system::instance();
616
1f64514d 617 // Let's check if the user is allowed to delete this conversation.
dec0cd99
MN
618 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
619 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
620 $USER->id == $userid))) {
621 return true;
622 }
623
624 return false;
625 }
626
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) {
883ce421 638 global $DB, $USER;
dec0cd99 639
b2cd17e6 640 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 641
883ce421
MN
642 // If there is no conversation, there is nothing to do.
643 if (!$conversationid) {
644 return true;
645 }
646
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]);
658
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);
667
668 if ($message->useridfrom == $userid) {
669 $useridto = $otheruserid;
670 } else {
671 $useridto = $userid;
dec0cd99 672 }
883ce421
MN
673 \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
674 $USER->id, $message->id, $mua->id)->trigger();
dec0cd99
MN
675 }
676
677 return true;
678 }
79f6c36c
MN
679
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;
689
690 if (empty($user)) {
691 $user = $USER;
692 }
693
883ce421
MN
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";
705
706 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
707 }
708
709 /**
74ad60bf 710 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 711 *
74ad60bf 712 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 713 *
74ad60bf
MN
714 * @param int $userid
715 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 716 */
74ad60bf 717 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
718 global $DB;
719
883ce421
MN
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
5aac33c7
MN
726 LEFT JOIN {message_user_actions} mua
727 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
728 WHERE mua.id is NULL
729 AND mcm.userid = ?
74ad60bf 730 AND m.useridfrom != ?";
5aac33c7
MN
731 $messageparams = [];
732 $messageparams[] = $userid;
733 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
734 $messageparams[] = $userid;
735 $messageparams[] = $userid;
736 if (!is_null($conversationid)) {
737 $messagesql .= " AND mc.id = ?";
738 $messageparams[] = $conversationid;
79f6c36c
MN
739 }
740
74ad60bf
MN
741 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
742 foreach ($messages as $message) {
743 self::mark_message_as_read($userid, $message);
744 }
745 $messages->close();
746 }
747
748 /**
749 * Marks all notifications being sent from one user to another user as read.
750 *
751 * If the from user is null then it marks all notifications as read sent to the to user.
752 *
753 * @param int $touserid the id of the message recipient
754 * @param int|null $fromuserid the id of the message sender, null if all messages
755 * @return void
756 */
757 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
758 global $DB;
759
883ce421
MN
760 $notificationsql = "SELECT n.*
761 FROM {notifications} n
74ad60bf
MN
762 WHERE useridto = ?
763 AND timeread is NULL";
883ce421 764 $notificationsparams = [$touserid];
79f6c36c 765 if (!empty($fromuserid)) {
883ce421
MN
766 $notificationsql .= " AND useridfrom = ?";
767 $notificationsparams[] = $fromuserid;
79f6c36c
MN
768 }
769
74ad60bf
MN
770 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
771 foreach ($notifications as $notification) {
772 self::mark_notification_as_read($notification);
79f6c36c 773 }
74ad60bf
MN
774 $notifications->close();
775 }
79f6c36c 776
74ad60bf
MN
777 /**
778 * Marks ALL messages being sent from $fromuserid to $touserid as read.
779 *
780 * Can be filtered by type.
781 *
782 * @deprecated since 3.5
783 * @param int $touserid the id of the message recipient
784 * @param int $fromuserid the id of the message sender
785 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
786 * @return void
787 */
788 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
789 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
790 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
791 DEBUG_DEVELOPER);
792
793 $type = strtolower($type);
794
795 $conversationid = null;
796 $ignoremessages = false;
797 if (!empty($fromuserid)) {
99248f61 798 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
799 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
800 $ignoremessages = true;
801 }
79f6c36c
MN
802 }
803
74ad60bf
MN
804 if (!empty($type)) {
805 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 806 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
807 } else if ($type == MESSAGE_TYPE_MESSAGE) {
808 if (!$ignoremessages) {
99248f61 809 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
810 }
811 }
812 } else { // We want both.
99248f61 813 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 814 if (!$ignoremessages) {
99248f61 815 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 816 }
883ce421 817 }
79f6c36c
MN
818 }
819
79f6c36c
MN
820 /**
821 * Returns message preferences.
822 *
823 * @param array $processors
824 * @param array $providers
825 * @param \stdClass $user
826 * @return \stdClass
827 * @since 3.2
828 */
829 public static function get_all_message_preferences($processors, $providers, $user) {
830 $preferences = helper::get_providers_preferences($providers, $user->id);
831 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
832
833 // For every processors put its options on the form (need to get function from processor's lib.php).
834 foreach ($processors as $processor) {
835 $processor->object->load_data($preferences, $user->id);
836 }
837
838 // Load general messaging preferences.
839 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
840 $preferences->mailformat = $user->mailformat;
841 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
842
843 return $preferences;
844 }
5b0769db
MN
845
846 /**
847 * Count the number of users blocked by a user.
848 *
849 * @param \stdClass $user The user object
850 * @return int the number of blocked users
851 */
852 public static function count_blocked_users($user = null) {
853 global $USER, $DB;
854
855 if (empty($user)) {
856 $user = $USER;
857 }
858
859 $sql = "SELECT count(mc.id)
860 FROM {message_contacts} mc
861 WHERE mc.userid = :userid AND mc.blocked = 1";
862 return $DB->count_records_sql($sql, array('userid' => $user->id));
863 }
864
865 /**
866 * Determines if a user is permitted to send another user a private message.
867 * If no sender is provided then it defaults to the logged in user.
868 *
869 * @param \stdClass $recipient The user object.
870 * @param \stdClass|null $sender The user object.
871 * @return bool true if user is permitted, false otherwise.
872 */
873 public static function can_post_message($recipient, $sender = null) {
874 global $USER;
875
876 if (is_null($sender)) {
877 // The message is from the logged in user, unless otherwise specified.
878 $sender = $USER;
879 }
880
881 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
882 return false;
883 }
884
885 // The recipient blocks messages from non-contacts and the
886 // sender isn't a contact.
887 if (self::is_user_non_contact_blocked($recipient, $sender)) {
888 return false;
889 }
890
26dca05d
JP
891 $senderid = null;
892 if ($sender !== null && isset($sender->id)) {
893 $senderid = $sender->id;
894 }
5b0769db 895 // The recipient has specifically blocked this sender.
26dca05d 896 if (self::is_user_blocked($recipient->id, $senderid)) {
5b0769db
MN
897 return false;
898 }
899
900 return true;
901 }
902
903 /**
904 * Checks if the recipient is allowing messages from users that aren't a
905 * contact. If not then it checks to make sure the sender is in the
906 * recipient's contacts.
907 *
908 * @param \stdClass $recipient The user object.
909 * @param \stdClass|null $sender The user object.
910 * @return bool true if $sender is blocked, false otherwise.
911 */
912 public static function is_user_non_contact_blocked($recipient, $sender = null) {
913 global $USER, $DB;
914
915 if (is_null($sender)) {
916 // The message is from the logged in user, unless otherwise specified.
917 $sender = $USER;
918 }
919
920 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
921 if (!empty($blockednoncontacts)) {
922 // Confirm the sender is a contact of the recipient.
923 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
924 if ($exists) {
925 // All good, the recipient is a contact of the sender.
926 return false;
927 } else {
928 // Oh no, the recipient is not a contact. Looks like we can't send the message.
929 return true;
930 }
931 }
932
933 return false;
934 }
935
936 /**
937 * Checks if the recipient has specifically blocked the sending user.
938 *
939 * Note: This function will always return false if the sender has the
940 * readallmessages capability at the system context level.
941 *
26dca05d
JP
942 * @param int $recipientid User ID of the recipient.
943 * @param int $senderid User ID of the sender.
5b0769db
MN
944 * @return bool true if $sender is blocked, false otherwise.
945 */
26dca05d 946 public static function is_user_blocked($recipientid, $senderid = null) {
5b0769db
MN
947 global $USER, $DB;
948
26dca05d 949 if (is_null($senderid)) {
5b0769db 950 // The message is from the logged in user, unless otherwise specified.
26dca05d 951 $senderid = $USER->id;
5b0769db
MN
952 }
953
954 $systemcontext = \context_system::instance();
26dca05d 955 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
956 return false;
957 }
958
26dca05d
JP
959 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
960 return true;
5b0769db
MN
961 }
962
963 return false;
964 }
20ab51fd
AA
965
966 /**
967 * Get specified message processor, validate corresponding plugin existence and
968 * system configuration.
969 *
970 * @param string $name Name of the processor.
971 * @param bool $ready only return ready-to-use processors.
972 * @return mixed $processor if processor present else empty array.
973 * @since Moodle 3.2
974 */
975 public static function get_message_processor($name, $ready = false) {
976 global $DB, $CFG;
977
978 $processor = $DB->get_record('message_processors', array('name' => $name));
979 if (empty($processor)) {
980 // Processor not found, return.
981 return array();
982 }
983
984 $processor = self::get_processed_processor_object($processor);
985 if ($ready) {
986 if ($processor->enabled && $processor->configured) {
987 return $processor;
988 } else {
989 return array();
990 }
991 } else {
992 return $processor;
993 }
994 }
995
996 /**
997 * Returns weather a given processor is enabled or not.
998 * Note:- This doesn't check if the processor is configured or not.
999 *
1000 * @param string $name Name of the processor
1001 * @return bool
1002 */
1003 public static function is_processor_enabled($name) {
1004
1005 $cache = \cache::make('core', 'message_processors_enabled');
1006 $status = $cache->get($name);
1007
1008 if ($status === false) {
1009 $processor = self::get_message_processor($name);
1010 if (!empty($processor)) {
1011 $cache->set($name, $processor->enabled);
1012 return $processor->enabled;
1013 } else {
1014 return false;
1015 }
1016 }
1017
1018 return $status;
1019 }
1020
1021 /**
1022 * Set status of a processor.
1023 *
1024 * @param \stdClass $processor processor record.
1025 * @param 0|1 $enabled 0 or 1 to set the processor status.
1026 * @return bool
1027 * @since Moodle 3.2
1028 */
1029 public static function update_processor_status($processor, $enabled) {
1030 global $DB;
1031 $cache = \cache::make('core', 'message_processors_enabled');
1032 $cache->delete($processor->name);
1033 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1034 }
1035
1036 /**
1037 * Given a processor object, loads information about it's settings and configurations.
1038 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1039 * or @see \get_message_processors()
1040 *
1041 * @param \stdClass $processor processor object
1042 * @return \stdClass processed processor object
1043 * @since Moodle 3.2
1044 */
1045 public static function get_processed_processor_object(\stdClass $processor) {
1046 global $CFG;
1047
1048 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1049 if (is_readable($processorfile)) {
1050 include_once($processorfile);
1051 $processclass = 'message_output_' . $processor->name;
1052 if (class_exists($processclass)) {
1053 $pclass = new $processclass();
1054 $processor->object = $pclass;
1055 $processor->configured = 0;
1056 if ($pclass->is_system_configured()) {
1057 $processor->configured = 1;
1058 }
1059 $processor->hassettings = 0;
1060 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1061 $processor->hassettings = 1;
1062 }
1063 $processor->available = 1;
1064 } else {
1065 print_error('errorcallingprocessor', 'message');
1066 }
1067 } else {
1068 $processor->available = 0;
1069 }
1070 return $processor;
1071 }
883ce421
MN
1072
1073 /**
1074 * Retrieve users blocked by $user1
1075 *
1076 * @param int $userid The user id of the user whos blocked users we are returning
1077 * @return array the users blocked
1078 */
1079 public static function get_blocked_users($userid) {
1080 global $DB;
1081
1082 $userfields = \user_picture::fields('u', array('lastaccess'));
1083 $blockeduserssql = "SELECT $userfields
1084 FROM {message_contacts} mc
1085 INNER JOIN {user} u
1086 ON u.id = mc.contactid
1087 WHERE u.deleted = 0
1088 AND mc.userid = ?
1089 AND mc.blocked = 1
1090 GROUP BY $userfields
1091 ORDER BY u.firstname ASC";
1092 return $DB->get_records_sql($blockeduserssql, [$userid]);
1093 }
1094
1095 /**
1096 * Mark a single message as read.
1097 *
1098 * @param int $userid The user id who marked the message as read
548936a6 1099 * @param \stdClass $message The message
883ce421
MN
1100 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1101 */
548936a6 1102 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1103 global $DB;
1104
1105 if (is_null($timeread)) {
1106 $timeread = time();
1107 }
1108
5aac33c7
MN
1109 $mua = new \stdClass();
1110 $mua->userid = $userid;
1111 $mua->messageid = $message->id;
1112 $mua->action = self::MESSAGE_ACTION_READ;
1113 $mua->timecreated = $timeread;
1114 $mua->id = $DB->insert_record('message_user_actions', $mua);
1115
1116 // Get the context for the user who received the message.
1117 $context = \context_user::instance($userid, IGNORE_MISSING);
1118 // If the user no longer exists the context value will be false, in this case use the system context.
1119 if ($context === false) {
1120 $context = \context_system::instance();
883ce421 1121 }
5aac33c7
MN
1122
1123 // Trigger event for reading a message.
1124 $event = \core\event\message_viewed::create(array(
1125 'objectid' => $mua->id,
1126 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1127 'context' => $context,
1128 'relateduserid' => $message->useridfrom,
1129 'other' => array(
1130 'messageid' => $message->id
1131 )
1132 ));
1133 $event->trigger();
883ce421
MN
1134 }
1135
1136 /**
1137 * Mark a single notification as read.
1138 *
548936a6 1139 * @param \stdClass $notification The notification
883ce421
MN
1140 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1141 */
548936a6 1142 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1143 global $DB;
1144
1145 if (is_null($timeread)) {
1146 $timeread = time();
1147 }
1148
883ce421
MN
1149 if (is_null($notification->timeread)) {
1150 $updatenotification = new \stdClass();
1151 $updatenotification->id = $notification->id;
1152 $updatenotification->timeread = $timeread;
1153
1154 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1155
1156 // Trigger event for reading a notification.
1157 \core\event\notification_viewed::create_from_ids(
1158 $notification->useridfrom,
1159 $notification->useridto,
1160 $notification->id
1161 )->trigger();
883ce421
MN
1162 }
1163 }
1164
1165 /**
1166 * Checks if a user can delete a message.
1167 *
1168 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1169 * but will still seem as if it was by the user)
1170 * @param int $messageid The message id
1171 * @return bool Returns true if a user can delete the message, false otherwise.
1172 */
1173 public static function can_delete_message($userid, $messageid) {
1174 global $DB, $USER;
1175
1176 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1177 FROM {messages} m
1178 INNER JOIN {message_conversations} mc
1179 ON m.conversationid = mc.id
1180 INNER JOIN {message_conversation_members} mcm
1181 ON mcm.conversationid = mc.id
1182 WHERE mcm.userid != m.useridfrom
1183 AND m.id = ?";
1184 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1185
1186 if ($message->useridfrom == $userid) {
1187 $userdeleting = 'useridfrom';
1188 } else if ($message->useridto == $userid) {
1189 $userdeleting = 'useridto';
1190 } else {
1191 return false;
1192 }
1193
1194 $systemcontext = \context_system::instance();
1195
1196 // Let's check if the user is allowed to delete this message.
1197 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1198 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1199 $USER->id == $message->$userdeleting))) {
1200 return true;
1201 }
1202
1203 return false;
1204 }
1205
1206 /**
1207 * Deletes a message.
1208 *
1209 * This function does not verify any permissions.
1210 *
1211 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1212 * but will still seem as if it was by the user)
1213 * @param int $messageid The message id
1214 * @return bool
1215 */
1216 public static function delete_message($userid, $messageid) {
1217 global $DB;
1218
1219 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1220 FROM {messages} m
1221 INNER JOIN {message_conversations} mc
1222 ON m.conversationid = mc.id
1223 INNER JOIN {message_conversation_members} mcm
1224 ON mcm.conversationid = mc.id
1225 WHERE mcm.userid != m.useridfrom
1226 AND m.id = ?";
1227 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1228
1229 // Check if the user has already deleted this message.
1230 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1231 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1232 $mua = new \stdClass();
1233 $mua->userid = $userid;
1234 $mua->messageid = $messageid;
1235 $mua->action = self::MESSAGE_ACTION_DELETED;
1236 $mua->timecreated = time();
1237 $mua->id = $DB->insert_record('message_user_actions', $mua);
1238
1239 // Trigger event for deleting a message.
1240 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1241 $userid, $message->id, $mua->id)->trigger();
1242
1243 return true;
1244 }
1245
1246 return false;
1247 }
1248
1249 /**
1250 * Returns the conversation between two users.
1251 *
b2cd17e6 1252 * @param array $userids
883ce421
MN
1253 * @return int|bool The id of the conversation, false if not found
1254 */
b2cd17e6 1255 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1256 global $DB;
1257
b2cd17e6 1258 $hash = helper::get_conversation_hash($userids);
883ce421 1259
b2cd17e6 1260 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
883ce421
MN
1261 return $conversation->id;
1262 }
1263
1264 return false;
1265 }
1266
1267 /**
1268 * Creates a conversation between two users.
1269 *
b2cd17e6 1270 * @param array $userids
883ce421
MN
1271 * @return int The id of the conversation
1272 */
b2cd17e6 1273 public static function create_conversation_between_users(array $userids) {
883ce421
MN
1274 global $DB;
1275
1276 $conversation = new \stdClass();
b2cd17e6 1277 $conversation->convhash = helper::get_conversation_hash($userids);
883ce421
MN
1278 $conversation->timecreated = time();
1279 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1280
1281 // Add members to this conversation.
b2cd17e6
MN
1282 foreach ($userids as $userid) {
1283 $member = new \stdClass();
1284 $member->conversationid = $conversation->id;
1285 $member->userid = $userid;
1286 $member->timecreated = time();
1287 $DB->insert_record('message_conversation_members', $member);
1288 }
883ce421
MN
1289
1290 return $conversation->id;
1291 }
879e2bef 1292}