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