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