MDL-36941 core_message: fixed minor CiBoT complaints
[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
74ad60bf
MN
726 WHERE mcm.userid = ?
727 AND m.useridfrom != ?";
728 $messageparams[] = $userid;
729 $messageparams[] = $userid;
730 if (!is_null($conversationid)) {
731 $messagesql .= " AND mc.id = ?";
732 $messageparams[] = $conversationid;
79f6c36c
MN
733 }
734
74ad60bf
MN
735 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
736 foreach ($messages as $message) {
737 self::mark_message_as_read($userid, $message);
738 }
739 $messages->close();
740 }
741
742 /**
743 * Marks all notifications being sent from one user to another user as read.
744 *
745 * If the from user is null then it marks all notifications as read sent to the to user.
746 *
747 * @param int $touserid the id of the message recipient
748 * @param int|null $fromuserid the id of the message sender, null if all messages
749 * @return void
750 */
751 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
752 global $DB;
753
883ce421
MN
754 $notificationsql = "SELECT n.*
755 FROM {notifications} n
74ad60bf
MN
756 WHERE useridto = ?
757 AND timeread is NULL";
883ce421 758 $notificationsparams = [$touserid];
79f6c36c 759 if (!empty($fromuserid)) {
883ce421
MN
760 $notificationsql .= " AND useridfrom = ?";
761 $notificationsparams[] = $fromuserid;
79f6c36c
MN
762 }
763
74ad60bf
MN
764 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
765 foreach ($notifications as $notification) {
766 self::mark_notification_as_read($notification);
79f6c36c 767 }
74ad60bf
MN
768 $notifications->close();
769 }
79f6c36c 770
74ad60bf
MN
771 /**
772 * Marks ALL messages being sent from $fromuserid to $touserid as read.
773 *
774 * Can be filtered by type.
775 *
776 * @deprecated since 3.5
777 * @param int $touserid the id of the message recipient
778 * @param int $fromuserid the id of the message sender
779 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
780 * @return void
781 */
782 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
783 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
784 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
785 DEBUG_DEVELOPER);
786
787 $type = strtolower($type);
788
789 $conversationid = null;
790 $ignoremessages = false;
791 if (!empty($fromuserid)) {
99248f61 792 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
793 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
794 $ignoremessages = true;
795 }
79f6c36c
MN
796 }
797
74ad60bf
MN
798 if (!empty($type)) {
799 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 800 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
801 } else if ($type == MESSAGE_TYPE_MESSAGE) {
802 if (!$ignoremessages) {
99248f61 803 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
804 }
805 }
806 } else { // We want both.
99248f61 807 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 808 if (!$ignoremessages) {
99248f61 809 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 810 }
883ce421 811 }
79f6c36c
MN
812 }
813
79f6c36c
MN
814 /**
815 * Returns message preferences.
816 *
817 * @param array $processors
818 * @param array $providers
819 * @param \stdClass $user
820 * @return \stdClass
821 * @since 3.2
822 */
823 public static function get_all_message_preferences($processors, $providers, $user) {
824 $preferences = helper::get_providers_preferences($providers, $user->id);
825 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
826
827 // For every processors put its options on the form (need to get function from processor's lib.php).
828 foreach ($processors as $processor) {
829 $processor->object->load_data($preferences, $user->id);
830 }
831
832 // Load general messaging preferences.
833 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
834 $preferences->mailformat = $user->mailformat;
835 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
836
837 return $preferences;
838 }
5b0769db
MN
839
840 /**
841 * Count the number of users blocked by a user.
842 *
843 * @param \stdClass $user The user object
844 * @return int the number of blocked users
845 */
846 public static function count_blocked_users($user = null) {
847 global $USER, $DB;
848
849 if (empty($user)) {
850 $user = $USER;
851 }
852
853 $sql = "SELECT count(mc.id)
854 FROM {message_contacts} mc
855 WHERE mc.userid = :userid AND mc.blocked = 1";
856 return $DB->count_records_sql($sql, array('userid' => $user->id));
857 }
858
859 /**
860 * Determines if a user is permitted to send another user a private message.
861 * If no sender is provided then it defaults to the logged in user.
862 *
863 * @param \stdClass $recipient The user object.
864 * @param \stdClass|null $sender The user object.
865 * @return bool true if user is permitted, false otherwise.
866 */
867 public static function can_post_message($recipient, $sender = null) {
868 global $USER;
869
870 if (is_null($sender)) {
871 // The message is from the logged in user, unless otherwise specified.
872 $sender = $USER;
873 }
874
875 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
876 return false;
877 }
878
879 // The recipient blocks messages from non-contacts and the
880 // sender isn't a contact.
881 if (self::is_user_non_contact_blocked($recipient, $sender)) {
882 return false;
883 }
884
26dca05d
JP
885 $senderid = null;
886 if ($sender !== null && isset($sender->id)) {
887 $senderid = $sender->id;
888 }
5b0769db 889 // The recipient has specifically blocked this sender.
26dca05d 890 if (self::is_user_blocked($recipient->id, $senderid)) {
5b0769db
MN
891 return false;
892 }
893
894 return true;
895 }
896
897 /**
898 * Checks if the recipient is allowing messages from users that aren't a
899 * contact. If not then it checks to make sure the sender is in the
900 * recipient's contacts.
901 *
902 * @param \stdClass $recipient The user object.
903 * @param \stdClass|null $sender The user object.
904 * @return bool true if $sender is blocked, false otherwise.
905 */
906 public static function is_user_non_contact_blocked($recipient, $sender = null) {
907 global $USER, $DB;
908
909 if (is_null($sender)) {
910 // The message is from the logged in user, unless otherwise specified.
911 $sender = $USER;
912 }
913
914 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
915 if (!empty($blockednoncontacts)) {
916 // Confirm the sender is a contact of the recipient.
917 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
918 if ($exists) {
919 // All good, the recipient is a contact of the sender.
920 return false;
921 } else {
922 // Oh no, the recipient is not a contact. Looks like we can't send the message.
923 return true;
924 }
925 }
926
927 return false;
928 }
929
930 /**
931 * Checks if the recipient has specifically blocked the sending user.
932 *
933 * Note: This function will always return false if the sender has the
934 * readallmessages capability at the system context level.
935 *
26dca05d
JP
936 * @param int $recipientid User ID of the recipient.
937 * @param int $senderid User ID of the sender.
5b0769db
MN
938 * @return bool true if $sender is blocked, false otherwise.
939 */
26dca05d 940 public static function is_user_blocked($recipientid, $senderid = null) {
5b0769db
MN
941 global $USER, $DB;
942
26dca05d 943 if (is_null($senderid)) {
5b0769db 944 // The message is from the logged in user, unless otherwise specified.
26dca05d 945 $senderid = $USER->id;
5b0769db
MN
946 }
947
948 $systemcontext = \context_system::instance();
26dca05d 949 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
950 return false;
951 }
952
26dca05d
JP
953 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
954 return true;
5b0769db
MN
955 }
956
957 return false;
958 }
20ab51fd
AA
959
960 /**
961 * Get specified message processor, validate corresponding plugin existence and
962 * system configuration.
963 *
964 * @param string $name Name of the processor.
965 * @param bool $ready only return ready-to-use processors.
966 * @return mixed $processor if processor present else empty array.
967 * @since Moodle 3.2
968 */
969 public static function get_message_processor($name, $ready = false) {
970 global $DB, $CFG;
971
972 $processor = $DB->get_record('message_processors', array('name' => $name));
973 if (empty($processor)) {
974 // Processor not found, return.
975 return array();
976 }
977
978 $processor = self::get_processed_processor_object($processor);
979 if ($ready) {
980 if ($processor->enabled && $processor->configured) {
981 return $processor;
982 } else {
983 return array();
984 }
985 } else {
986 return $processor;
987 }
988 }
989
990 /**
991 * Returns weather a given processor is enabled or not.
992 * Note:- This doesn't check if the processor is configured or not.
993 *
994 * @param string $name Name of the processor
995 * @return bool
996 */
997 public static function is_processor_enabled($name) {
998
999 $cache = \cache::make('core', 'message_processors_enabled');
1000 $status = $cache->get($name);
1001
1002 if ($status === false) {
1003 $processor = self::get_message_processor($name);
1004 if (!empty($processor)) {
1005 $cache->set($name, $processor->enabled);
1006 return $processor->enabled;
1007 } else {
1008 return false;
1009 }
1010 }
1011
1012 return $status;
1013 }
1014
1015 /**
1016 * Set status of a processor.
1017 *
1018 * @param \stdClass $processor processor record.
1019 * @param 0|1 $enabled 0 or 1 to set the processor status.
1020 * @return bool
1021 * @since Moodle 3.2
1022 */
1023 public static function update_processor_status($processor, $enabled) {
1024 global $DB;
1025 $cache = \cache::make('core', 'message_processors_enabled');
1026 $cache->delete($processor->name);
1027 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1028 }
1029
1030 /**
1031 * Given a processor object, loads information about it's settings and configurations.
1032 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1033 * or @see \get_message_processors()
1034 *
1035 * @param \stdClass $processor processor object
1036 * @return \stdClass processed processor object
1037 * @since Moodle 3.2
1038 */
1039 public static function get_processed_processor_object(\stdClass $processor) {
1040 global $CFG;
1041
1042 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1043 if (is_readable($processorfile)) {
1044 include_once($processorfile);
1045 $processclass = 'message_output_' . $processor->name;
1046 if (class_exists($processclass)) {
1047 $pclass = new $processclass();
1048 $processor->object = $pclass;
1049 $processor->configured = 0;
1050 if ($pclass->is_system_configured()) {
1051 $processor->configured = 1;
1052 }
1053 $processor->hassettings = 0;
1054 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1055 $processor->hassettings = 1;
1056 }
1057 $processor->available = 1;
1058 } else {
1059 print_error('errorcallingprocessor', 'message');
1060 }
1061 } else {
1062 $processor->available = 0;
1063 }
1064 return $processor;
1065 }
883ce421
MN
1066
1067 /**
1068 * Retrieve users blocked by $user1
1069 *
1070 * @param int $userid The user id of the user whos blocked users we are returning
1071 * @return array the users blocked
1072 */
1073 public static function get_blocked_users($userid) {
1074 global $DB;
1075
1076 $userfields = \user_picture::fields('u', array('lastaccess'));
1077 $blockeduserssql = "SELECT $userfields
1078 FROM {message_contacts} mc
1079 INNER JOIN {user} u
1080 ON u.id = mc.contactid
1081 WHERE u.deleted = 0
1082 AND mc.userid = ?
1083 AND mc.blocked = 1
1084 GROUP BY $userfields
1085 ORDER BY u.firstname ASC";
1086 return $DB->get_records_sql($blockeduserssql, [$userid]);
1087 }
1088
1089 /**
1090 * Mark a single message as read.
1091 *
1092 * @param int $userid The user id who marked the message as read
548936a6 1093 * @param \stdClass $message The message
883ce421
MN
1094 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1095 */
548936a6 1096 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1097 global $DB;
1098
1099 if (is_null($timeread)) {
1100 $timeread = time();
1101 }
1102
883ce421
MN
1103 // Check if the user has already read this message.
1104 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
548936a6 1105 'messageid' => $message->id, 'action' => self::MESSAGE_ACTION_READ])) {
883ce421
MN
1106 $mua = new \stdClass();
1107 $mua->userid = $userid;
548936a6 1108 $mua->messageid = $message->id;
883ce421
MN
1109 $mua->action = self::MESSAGE_ACTION_READ;
1110 $mua->timecreated = $timeread;
1111 $mua->id = $DB->insert_record('message_user_actions', $mua);
1112
1113 // Get the context for the user who received the message.
1114 $context = \context_user::instance($userid, IGNORE_MISSING);
1115 // If the user no longer exists the context value will be false, in this case use the system context.
1116 if ($context === false) {
1117 $context = \context_system::instance();
1118 }
1119
1120 // Trigger event for reading a message.
1121 $event = \core\event\message_viewed::create(array(
1122 'objectid' => $mua->id,
1123 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1124 'context' => $context,
1125 'relateduserid' => $message->useridfrom,
1126 'other' => array(
548936a6 1127 'messageid' => $message->id
883ce421
MN
1128 )
1129 ));
1130 $event->trigger();
1131 }
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}