MDL-63280 core_message: Create conversation area
[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
b8ff2c44
JD
27use core_favourites\local\entity\favourite;
28
879e2bef
MN
29defined('MOODLE_INTERNAL') || die();
30
7b55aaa1
MN
31require_once($CFG->dirroot . '/lib/messagelib.php');
32
879e2bef
MN
33/**
34 * Class used to return information to display for the message area.
35 *
36 * @copyright 2016 Mark Nelson <markn@moodle.com>
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 */
39class api {
40
883ce421
MN
41 /**
42 * The action for reading a message.
43 */
44 const MESSAGE_ACTION_READ = 1;
45
46 /**
47 * The action for deleting a message.
48 */
49 const MESSAGE_ACTION_DELETED = 2;
50
f7dfa9ba
SA
51 /**
52 * The privacy setting for being messaged by anyone within courses user is member of.
53 */
54 const MESSAGE_PRIVACY_COURSEMEMBER = 0;
55
56 /**
57 * The privacy setting for being messaged only by contacts.
58 */
59 const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
60
61 /**
62 * The privacy setting for being messaged by anyone on the site.
63 */
64 const MESSAGE_PRIVACY_SITE = 2;
65
f2ac0a3e
MN
66 /**
67 * An individual conversation.
68 */
69 const MESSAGE_CONVERSATION_TYPE_INDIVIDUAL = 1;
70
71 /**
72 * A group conversation.
73 */
74 const MESSAGE_CONVERSATION_TYPE_GROUP = 2;
75
cd03b8d7
MN
76 /**
77 * Handles searching for messages in the message area.
78 *
79 * @param int $userid The user id doing the searching
80 * @param string $search The string the user is searching
81 * @param int $limitfrom
82 * @param int $limitnum
de55cb1b 83 * @return array
cd03b8d7
MN
84 */
85 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
86 global $DB;
87
88 // Get the user fields we want.
89 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
90 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
91
883ce421 92 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
f219eac7
MN
93 m.smallmessage, m.timecreated, 0 as isread, $ufields, mub.id as userfrom_blocked, $ufields2,
94 mub2.id as userto_blocked
883ce421
MN
95 FROM {messages} m
96 INNER JOIN {user} u
97 ON u.id = m.useridfrom
98 INNER JOIN {message_conversations} mc
99 ON mc.id = m.conversationid
100 INNER JOIN {message_conversation_members} mcm
101 ON mcm.conversationid = m.conversationid
102 INNER JOIN {user} u2
103 ON u2.id = mcm.userid
f219eac7
MN
104 LEFT JOIN {message_users_blocked} mub
105 ON (mub.blockeduserid = u.id AND mub.userid = ?)
106 LEFT JOIN {message_users_blocked} mub2
107 ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
883ce421
MN
108 LEFT JOIN {message_user_actions} mua
109 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
110 WHERE (m.useridfrom = ? OR mcm.userid = ?)
111 AND m.useridfrom != mcm.userid
cd03b8d7
MN
112 AND u.deleted = 0
113 AND u2.deleted = 0
883ce421 114 AND mua.id is NULL
cd03b8d7
MN
115 AND " . $DB->sql_like('smallmessage', '?', false) . "
116 ORDER BY timecreated DESC";
883ce421
MN
117
118 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
cd03b8d7
MN
119
120 // Convert the messages into searchable contacts with their last message being the message that was searched.
de55cb1b 121 $conversations = array();
cd03b8d7
MN
122 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
123 foreach ($messages as $message) {
124 $prefix = 'userfrom_';
125 if ($userid == $message->useridfrom) {
126 $prefix = 'userto_';
127 // If it from the user, then mark it as read, even if it wasn't by the receiver.
128 $message->isread = true;
129 }
dd0c1403 130 $blockedcol = $prefix . 'blocked';
f219eac7 131 $message->blocked = $message->$blockedcol ? 1 : 0;
dd0c1403 132
cd03b8d7 133 $message->messageid = $message->id;
de55cb1b 134 $conversations[] = helper::create_contact($message, $prefix);
cd03b8d7
MN
135 }
136 }
137
de55cb1b 138 return $conversations;
cd03b8d7
MN
139 }
140
141 /**
48e8bdba 142 * Handles searching for user in a particular course in the message area.
cd03b8d7
MN
143 *
144 * @param int $userid The user id doing the searching
145 * @param int $courseid The id of the course we are searching in
146 * @param string $search The string the user is searching
147 * @param int $limitfrom
148 * @param int $limitnum
de55cb1b 149 * @return array
cd03b8d7 150 */
48e8bdba 151 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
152 global $DB;
153
154 // Get all the users in the course.
155 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
f219eac7 156 $sql = "SELECT u.*, mub.id as isblocked
cd03b8d7 157 FROM {user} u
dd0c1403
MN
158 JOIN ($esql) je
159 ON je.id = u.id
f219eac7
MN
160 LEFT JOIN {message_users_blocked} mub
161 ON (mub.blockeduserid = u.id AND mub.userid = :userid)
cd03b8d7
MN
162 WHERE u.deleted = 0";
163 // Add more conditions.
164 $fullname = $DB->sql_fullname();
dd0c1403 165 $sql .= " AND u.id != :userid2
cd03b8d7
MN
166 AND " . $DB->sql_like($fullname, ':search', false) . "
167 ORDER BY " . $DB->sql_fullname();
dd0c1403 168 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 169
cd03b8d7
MN
170 // Convert all the user records into contacts.
171 $contacts = array();
172 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
173 foreach ($users as $user) {
f219eac7 174 $user->blocked = $user->isblocked ? 1 : 0;
de55cb1b 175 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
176 }
177 }
178
de55cb1b 179 return $contacts;
cd03b8d7
MN
180 }
181
182 /**
48e8bdba 183 * Handles searching for user in the message area.
cd03b8d7
MN
184 *
185 * @param int $userid The user id doing the searching
186 * @param string $search The string the user is searching
187 * @param int $limitnum
de55cb1b 188 * @return array
cd03b8d7 189 */
48e8bdba 190 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
191 global $CFG, $DB;
192
cd03b8d7
MN
193 // Used to search for contacts.
194 $fullname = $DB->sql_fullname();
195 $ufields = \user_picture::fields('u', array('lastaccess'));
196
197 // Users not to include.
198 $excludeusers = array($userid, $CFG->siteguest);
199 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
200
201 // Ok, let's search for contacts first.
202 $contacts = array();
f219eac7 203 $sql = "SELECT $ufields, mub.id as isuserblocked
cd03b8d7
MN
204 FROM {user} u
205 JOIN {message_contacts} mc
206 ON u.id = mc.contactid
f219eac7
MN
207 LEFT JOIN {message_users_blocked} mub
208 ON (mub.userid = :userid2 AND mub.blockeduserid = u.id)
cd03b8d7
MN
209 WHERE mc.userid = :userid
210 AND u.deleted = 0
211 AND u.confirmed = 1
212 AND " . $DB->sql_like($fullname, ':search', false) . "
213 AND u.id $exclude
214 ORDER BY " . $DB->sql_fullname();
f219eac7
MN
215 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'userid2' => $userid,
216 'search' => '%' . $search . '%') + $excludeparams, 0, $limitnum)) {
cd03b8d7 217 foreach ($users as $user) {
f219eac7 218 $user->blocked = $user->isuserblocked ? 1 : 0;
de55cb1b 219 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
220 }
221 }
222
223 // Now, let's get the courses.
f3249577
AG
224 // Make sure to limit searches to enrolled courses.
225 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 226 $courses = array();
93b47710
MN
227 // Really we want the user to be able to view the participants if they have the capability
228 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
229 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
230 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
442f12f8 231 if ($arrcourses = \core_course_category::search_courses(array('search' => $search), array('limit' => $limitnum),
f3249577 232 array('moodle/course:viewparticipants'))) {
cd03b8d7 233 foreach ($arrcourses as $course) {
f3249577
AG
234 if (isset($enrolledcourses[$course->id])) {
235 $data = new \stdClass();
236 $data->id = $course->id;
237 $data->shortname = $course->shortname;
238 $data->fullname = $course->fullname;
239 $courses[] = $data;
240 }
cd03b8d7
MN
241 }
242 }
243
244 // Let's get those non-contacts. Toast them gears boi.
dd0c1403
MN
245 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
246 // extra detail from the database.
cd03b8d7
MN
247 $noncontacts = array();
248 $sql = "SELECT $ufields
249 FROM {user} u
250 WHERE u.deleted = 0
251 AND u.confirmed = 1
252 AND " . $DB->sql_like($fullname, ':search', false) . "
253 AND u.id $exclude
7b55aaa1
MN
254 AND u.id NOT IN (SELECT contactid
255 FROM {message_contacts}
cd03b8d7
MN
256 WHERE userid = :userid)
257 ORDER BY " . $DB->sql_fullname();
7b55aaa1 258 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
f219eac7 259 0, $limitnum)) {
cd03b8d7 260 foreach ($users as $user) {
de55cb1b 261 $noncontacts[] = helper::create_contact($user);
cd03b8d7
MN
262 }
263 }
264
de55cb1b 265 return array($contacts, $courses, $noncontacts);
cd03b8d7
MN
266 }
267
879e2bef
MN
268 /**
269 * Returns the contacts and their conversation to display in the contacts area.
270 *
349f4261
RW
271 * ** WARNING **
272 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
273 * to retrieve too much information in a single call will cause performance problems.
274 * ** WARNING **
275 *
276 * This function has specifically been altered to break each of the data sets it
277 * requires into separate database calls. This is to avoid the performance problems
278 * observed when attempting to join large data sets (e.g. the message tables and
279 * the user table).
280 *
281 * While it is possible to gather the data in a single query, and it may even be
282 * more efficient with a correctly tuned database, we have opted to trade off some of
283 * the benefits of a single query in order to ensure this function will work on
284 * most databases with default tunings and with large data sets.
285 *
879e2bef 286 * @param int $userid The user id
879e2bef
MN
287 * @param int $limitfrom
288 * @param int $limitnum
b8ff2c44
JD
289 * @param int $type the conversation type.
290 * @param bool $favouritesonly whether to retrieve only the favourite conversations for the user, or not.
de55cb1b 291 * @return array
879e2bef 292 */
b8ff2c44
JD
293 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
294 bool $favouritesonly = false) {
349f4261
RW
295 global $DB;
296
b8ff2c44
JD
297 $favouritesql = "";
298 $favouriteparams = [];
299 if ($favouritesonly) {
300 // Ask the favourites subsystem for the user's favourite conversations.
301 $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
302 $favourites = $service->find_favourites_by_type('core_message', 'message_conversations');
303 if (empty($favourites)) {
304 return []; // No favourited conversations, so return none.
305 }
306 $favids = array_values(array_map(function ($fav) {
307 return $fav->itemid;
308 }, $favourites));
309 list ($insql, $inparams) = $DB->get_in_or_equal($favids, SQL_PARAMS_NAMED, 'favouriteids');
310 $favouritesql = " AND m.conversationid {$insql} ";
311 $favouriteparams = $inparams;
312 }
313
883ce421
MN
314 // Get the last message from each conversation that the user belongs to.
315 $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
316 FROM {messages} m
317 INNER JOIN (
318 SELECT MAX(m.id) AS messageid
319 FROM {messages} m
320 INNER JOIN (
321 SELECT m.conversationid, MAX(m.timecreated) as maxtime
322 FROM {messages} m
323 INNER JOIN {message_conversation_members} mcm
324 ON mcm.conversationid = m.conversationid
325 LEFT JOIN {message_user_actions} mua
326 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
327 WHERE mua.id is NULL
328 AND mcm.userid = :userid2
329 GROUP BY m.conversationid
330 ) maxmessage
331 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
332 GROUP BY m.conversationid
333 ) lastmessage
334 ON lastmessage.messageid = m.id
335 INNER JOIN {message_conversation_members} mcm
336 ON mcm.conversationid = m.conversationid
337 INNER JOIN {message_conversation_members} mcm2
338 ON mcm2.conversationid = m.conversationid
339 WHERE mcm.userid = m.useridfrom
b8ff2c44 340 AND mcm.id != mcm2.id $favouritesql
883ce421 341 ORDER BY m.timecreated DESC";
b8ff2c44
JD
342
343 $params = array_merge($favouriteparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
344 'userid2' => $userid]);
345 $messageset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
349f4261 346
349f4261
RW
347 $messages = [];
348 foreach ($messageset as $message) {
883ce421 349 $messages[$message->id] = $message;
349f4261
RW
350 }
351 $messageset->close();
352
883ce421
MN
353 // If there are no messages return early.
354 if (empty($messages)) {
355 return [];
356 }
357
349f4261
RW
358 // We need to pull out the list of other users that are part of each of these conversations. This
359 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
360 // tables because on large sites these tables are massive which results in extremely slow
361 // performance (typically due to join buffer exhaustion).
362 $otheruserids = array_map(function($message) use ($userid) {
363 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
364 }, array_values($messages));
365
883ce421 366 // Ok, let's get the other members in the conversations.
349f4261 367 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
883ce421 368 $userfields = \user_picture::fields('u', array('lastaccess'));
349f4261 369 $userssql = "SELECT $userfields
883ce421
MN
370 FROM {user} u
371 WHERE id $useridsql
372 AND deleted = 0";
349f4261
RW
373 $otherusers = $DB->get_records_sql($userssql, $usersparams);
374
883ce421
MN
375 // If there are no other users (user may have been deleted), then do not continue.
376 if (empty($otherusers)) {
377 return [];
378 }
379
f219eac7 380 $contactssql = "SELECT contactid
883ce421
MN
381 FROM {message_contacts}
382 WHERE userid = ?
383 AND contactid $useridsql";
384 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
349f4261
RW
385
386 // Finally, let's get the unread messages count for this user so that we can add them
883ce421
MN
387 // to the conversation. Remember we need to ignore the messages the user sent.
388 $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
389 FROM {messages} m
390 INNER JOIN {message_conversations} mc
391 ON mc.id = m.conversationid
392 INNER JOIN {message_conversation_members} mcm
393 ON m.conversationid = mcm.conversationid
394 LEFT JOIN {message_user_actions} mua
395 ON (mua.messageid = m.id AND mua.userid = ? AND
396 (mua.action = ? OR mua.action = ?))
397 WHERE mcm.userid = ?
398 AND m.useridfrom != ?
399 AND mua.id is NULL
400 GROUP BY useridfrom';
401 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
402 $userid, $userid]);
403
404 // Get rid of the table prefix.
405 $userfields = str_replace('u.', '', $userfields);
349f4261 406 $userproperties = explode(',', $userfields);
de55cb1b 407 $arrconversations = array();
349f4261
RW
408 foreach ($messages as $message) {
409 $conversation = new \stdClass();
410 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
411 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
412 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
413
883ce421
MN
414 // It's possible the other user was deleted, so, skip.
415 if (is_null($otheruser)) {
416 continue;
417 }
418
349f4261
RW
419 // Add the other user's information to the conversation, if we have one.
420 foreach ($userproperties as $prop) {
421 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
422 }
423
424 // Add the contact's information, if we have one.
425 $conversation->blocked = ($contact) ? $contact->blocked : null;
426
427 // Add the message information.
428 $conversation->messageid = $message->id;
429 $conversation->smallmessage = $message->smallmessage;
430 $conversation->useridfrom = $message->useridfrom;
431
432 // Only consider it unread if $user has unread messages.
433 if (isset($unreadcounts[$otheruserid])) {
434 $conversation->isread = false;
435 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
436 } else {
437 $conversation->isread = true;
879e2bef 438 }
349f4261 439
42e2f6c0 440 $arrconversations[$otheruserid] = helper::create_contact($conversation);
879e2bef
MN
441 }
442
de55cb1b 443 return $arrconversations;
879e2bef
MN
444 }
445
b8ff2c44
JD
446 /**
447 * Mark a conversation as a favourite for the given user.
448 *
449 * @param int $conversationid the id of the conversation to mark as a favourite.
450 * @param int $userid the id of the user to whom the favourite belongs.
451 * @return favourite the favourite object.
452 * @throws \moodle_exception if the user or conversation don't exist.
453 */
454 public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
455 if (!self::is_user_in_conversation($userid, $conversationid)) {
456 throw new \moodle_exception("Conversation doesn't exist or user is not a member");
457 }
458 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
459 return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
460 }
461
462 /**
463 * Unset a conversation as a favourite for the given user.
464 *
465 * @param int $conversationid the id of the conversation to unset as a favourite.
466 * @param int $userid the id to whom the favourite belongs.
467 * @throws \moodle_exception if the favourite does not exist for the user.
468 */
469 public static function unset_favourite_conversation(int $conversationid, int $userid) {
470 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
471 $ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, \context_system::instance());
472 }
473
879e2bef
MN
474 /**
475 * Returns the contacts to display in the contacts area.
476 *
477 * @param int $userid The user id
478 * @param int $limitfrom
479 * @param int $limitnum
de55cb1b 480 * @return array
879e2bef
MN
481 */
482 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
483 global $DB;
484
f219eac7
MN
485 $contactids = [];
486 $sql = "SELECT mc.*
879e2bef 487 FROM {message_contacts} mc
f219eac7
MN
488 WHERE mc.userid = ? OR mc.contactid = ?
489 ORDER BY timecreated DESC";
490 if ($contacts = $DB->get_records_sql($sql, [$userid, $userid], $limitfrom, $limitnum)) {
879e2bef 491 foreach ($contacts as $contact) {
f219eac7
MN
492 if ($userid == $contact->userid) {
493 $contactids[] = $contact->contactid;
494 } else {
495 $contactids[] = $contact->userid;
496 }
497 }
498 }
499
500 if (!empty($contactids)) {
501 list($insql, $inparams) = $DB->get_in_or_equal($contactids);
502
503 $sql = "SELECT u.*, mub.id as isblocked
504 FROM {user} u
505 LEFT JOIN {message_users_blocked} mub
506 ON u.id = mub.blockeduserid
507 WHERE u.id $insql";
508 if ($contacts = $DB->get_records_sql($sql, $inparams)) {
509 $arrcontacts = [];
510 foreach ($contacts as $contact) {
511 $contact->blocked = $contact->isblocked ? 1 : 0;
512 $arrcontacts[] = helper::create_contact($contact);
513 }
514
515 return $arrcontacts;
879e2bef
MN
516 }
517 }
518
f219eac7 519 return [];
879e2bef
MN
520 }
521
883ce421
MN
522 /**
523 * Returns the an array of the users the given user is in a conversation
524 * with who are a contact and the number of unread messages.
525 *
526 * @param int $userid The user id
527 * @param int $limitfrom
528 * @param int $limitnum
529 * @return array
530 */
531 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
532 global $DB;
533
534 $userfields = \user_picture::fields('u', array('lastaccess'));
535 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
536 FROM {message_contacts} mc
537 INNER JOIN {user} u
f219eac7 538 ON (u.id = mc.contactid OR u.id = mc.userid)
883ce421 539 LEFT JOIN {messages} m
f219eac7 540 ON ((m.useridfrom = mc.contactid OR m.useridfrom = mc.userid) AND m.useridfrom != ?)
883ce421
MN
541 LEFT JOIN {message_conversation_members} mcm
542 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
543 LEFT JOIN {message_user_actions} mua
544 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
f219eac7
MN
545 LEFT JOIN {message_users_blocked} mub
546 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421 547 WHERE mua.id is NULL
f219eac7
MN
548 AND mub.id is NULL
549 AND (mc.userid = ? OR mc.contactid = ?)
550 AND u.id != ?
883ce421
MN
551 AND u.deleted = 0
552 GROUP BY $userfields";
553
f219eac7
MN
554 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, $userid, self::MESSAGE_ACTION_READ,
555 $userid, $userid, $userid, $userid], $limitfrom, $limitnum);
883ce421
MN
556 }
557
558 /**
559 * Returns the an array of the users the given user is in a conversation
560 * with who are not a contact and the number of unread messages.
561 *
562 * @param int $userid The user id
563 * @param int $limitfrom
564 * @param int $limitnum
565 * @return array
566 */
567 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
568 global $DB;
569
570 $userfields = \user_picture::fields('u', array('lastaccess'));
571 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
572 FROM {user} u
573 INNER JOIN {messages} m
574 ON m.useridfrom = u.id
575 INNER JOIN {message_conversation_members} mcm
576 ON mcm.conversationid = m.conversationid
577 LEFT JOIN {message_user_actions} mua
578 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
579 LEFT JOIN {message_contacts} mc
580 ON (mc.userid = ? AND mc.contactid = u.id)
f219eac7
MN
581 LEFT JOIN {message_users_blocked} mub
582 ON (mub.userid = ? AND mub.blockeduserid = u.id)
883ce421
MN
583 WHERE mcm.userid = ?
584 AND mcm.userid != m.useridfrom
585 AND mua.id is NULL
f219eac7 586 AND mub.id is NULL
883ce421
MN
587 AND mc.id is NULL
588 AND u.deleted = 0
589 GROUP BY $userfields";
590
f219eac7 591 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
883ce421
MN
592 $limitfrom, $limitnum);
593 }
594
879e2bef
MN
595 /**
596 * Returns the messages to display in the message area.
597 *
598 * @param int $userid the current user
599 * @param int $otheruserid the other user
600 * @param int $limitfrom
601 * @param int $limitnum
8ec78c48 602 * @param string $sort
ffd7798c
MN
603 * @param int $timefrom the time from the message being sent
604 * @param int $timeto the time up until the message being sent
de55cb1b 605 * @return array
879e2bef 606 */
fb1469d8 607 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 608 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 609
ffd7798c 610 if (!empty($timefrom)) {
fb1469d8 611 // Check the cache to see if we even need to do a DB query.
ffd7798c
MN
612 $cache = \cache::make('core', 'message_time_last_message_between_users');
613 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
fb1469d8
RW
614 $lastcreated = $cache->get($key);
615
616 // The last known message time is earlier than the one being requested so we can
617 // just return an empty result set rather than having to query the DB.
ffd7798c 618 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
619 return [];
620 }
621 }
622
879e2bef 623 $arrmessages = array();
fb1469d8 624 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 625 $sort, $timefrom, $timeto)) {
fb1469d8 626
de55cb1b 627 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
628 }
629
de55cb1b 630 return $arrmessages;
879e2bef 631 }
c060cd49
MN
632
633 /**
634 * Returns the most recent message between two users.
635 *
636 * @param int $userid the current user
637 * @param int $otheruserid the other user
de55cb1b 638 * @return \stdClass|null
c060cd49
MN
639 */
640 public static function get_most_recent_message($userid, $otheruserid) {
641 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 642 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
643 // Swap the order so we now have them in historical order.
644 $messages = array_reverse($messages);
de55cb1b 645 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
646 return array_pop($arrmessages);
647 }
648
649 return null;
650 }
c6e97f54
MN
651
652 /**
653 * Returns the profile information for a contact for a user.
654 *
655 * @param int $userid The user id
656 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 657 * @return \stdClass
c6e97f54
MN
658 */
659 public static function get_profile($userid, $otheruserid) {
f219eac7 660 global $CFG, $PAGE;
c6e97f54
MN
661
662 require_once($CFG->dirroot . '/user/lib.php');
663
f4c39cb9
MN
664 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
665
666 // Create the data we are going to pass to the renderable.
667 $data = new \stdClass();
668 $data->userid = $otheruserid;
669 $data->fullname = fullname($user);
670 $data->city = '';
671 $data->country = '';
672 $data->email = '';
cb805753 673 $data->isonline = null;
f4c39cb9
MN
674 // Get the user picture data - messaging has always shown these to the user.
675 $userpicture = new \user_picture($user);
676 $userpicture->size = 1; // Size f1.
677 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
678 $userpicture->size = 0; // Size f2.
679 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
680
681 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
682 if ($userfields) {
683 if (isset($userfields['city'])) {
684 $data->city = $userfields['city'];
685 }
686 if (isset($userfields['country'])) {
687 $data->country = $userfields['country'];
bf58081d 688 }
f4c39cb9
MN
689 if (isset($userfields['email'])) {
690 $data->email = $userfields['email'];
c6e97f54 691 }
f4c39cb9
MN
692 if (isset($userfields['lastaccess'])) {
693 $data->isonline = helper::is_online($userfields['lastaccess']);
694 }
695 }
c6e97f54 696
f219eac7
MN
697 $data->isblocked = self::is_blocked($userid, $otheruserid);
698 $data->iscontact = self::is_contact($userid, $otheruserid);
f4c39cb9
MN
699
700 return $data;
c6e97f54 701 }
dec0cd99
MN
702
703 /**
704 * Checks if a user can delete messages they have either received or sent.
705 *
706 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
707 * but will still seem as if it was by the user)
15663b0b 708 * @param int $conversationid The id of the conversation
1f64514d 709 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99 710 */
15663b0b 711 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
dec0cd99
MN
712 global $USER;
713
15663b0b
MN
714 if (is_null($conversationid)) {
715 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
716 DEBUG_DEVELOPER);
717 return false;
718 }
719
dec0cd99
MN
720 $systemcontext = \context_system::instance();
721
15663b0b
MN
722 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
723 return true;
724 }
725
726 if (!self::is_user_in_conversation($userid, $conversationid)) {
727 return false;
728 }
729
730 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
731 $USER->id == $userid) {
dec0cd99
MN
732 return true;
733 }
734
735 return false;
736 }
737
738 /**
739 * Deletes a conversation.
740 *
741 * This function does not verify any permissions.
742 *
263ad984 743 * @deprecated since 3.6
dec0cd99
MN
744 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
745 * but will still seem as if it was by the user)
746 * @param int $otheruserid The id of the other user in the conversation
747 * @return bool
748 */
749 public static function delete_conversation($userid, $otheruserid) {
263ad984
MN
750 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
751 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
dec0cd99 752
b2cd17e6 753 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 754
883ce421
MN
755 // If there is no conversation, there is nothing to do.
756 if (!$conversationid) {
757 return true;
758 }
759
263ad984
MN
760 self::delete_conversation_by_id($userid, $conversationid);
761
762 return true;
763 }
764
765 /**
766 * Deletes a conversation for a specified user.
767 *
768 * This function does not verify any permissions.
769 *
770 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
771 * but will still seem as if it was by the user)
772 * @param int $conversationid The id of the other user in the conversation
773 */
774 public static function delete_conversation_by_id(int $userid, int $conversationid) {
775 global $DB, $USER;
776
883ce421
MN
777 // Get all messages belonging to this conversation that have not already been deleted by this user.
778 $sql = "SELECT m.*
779 FROM {messages} m
780 INNER JOIN {message_conversations} mc
781 ON m.conversationid = mc.id
782 LEFT JOIN {message_user_actions} mua
783 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
784 WHERE mua.id is NULL
785 AND mc.id = ?
786 ORDER BY m.timecreated ASC";
787 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
788
789 // Ok, mark these as deleted.
790 foreach ($messages as $message) {
791 $mua = new \stdClass();
792 $mua->userid = $userid;
793 $mua->messageid = $message->id;
794 $mua->action = self::MESSAGE_ACTION_DELETED;
795 $mua->timecreated = time();
796 $mua->id = $DB->insert_record('message_user_actions', $mua);
797
14de10c4
MN
798 \core\event\message_deleted::create_from_ids($userid, $USER->id,
799 $message->id, $mua->id)->trigger();
dec0cd99 800 }
dec0cd99 801 }
79f6c36c
MN
802
803 /**
804 * Returns the count of unread conversations (collection of messages from a single user) for
805 * the given user.
806 *
807 * @param \stdClass $user the user who's conversations should be counted
808 * @return int the count of the user's unread conversations
809 */
810 public static function count_unread_conversations($user = null) {
811 global $USER, $DB;
812
813 if (empty($user)) {
814 $user = $USER;
815 }
816
883ce421
MN
817 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
818 FROM {messages} m
819 INNER JOIN {message_conversations} mc
820 ON m.conversationid = mc.id
821 INNER JOIN {message_conversation_members} mcm
822 ON mc.id = mcm.conversationid
823 LEFT JOIN {message_user_actions} mua
824 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
825 WHERE mcm.userid = ?
826 AND mcm.userid != m.useridfrom
827 AND mua.id is NULL";
828
829 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
830 }
831
abf7a261
MN
832 /**
833 * Checks if a user can mark all messages as read.
834 *
835 * @param int $userid The user id of who we want to mark the messages for
836 * @param int $conversationid The id of the conversation
837 * @return bool true if user is permitted, false otherwise
838 * @since 3.6
839 */
840 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
841 global $USER;
842
843 $systemcontext = \context_system::instance();
844
845 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
846 return true;
847 }
848
849 if (!self::is_user_in_conversation($userid, $conversationid)) {
850 return false;
851 }
852
853 if ($USER->id == $userid) {
854 return true;
855 }
856
857 return false;
858 }
859
79f6c36c 860 /**
74ad60bf 861 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 862 *
74ad60bf 863 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 864 *
74ad60bf
MN
865 * @param int $userid
866 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 867 */
74ad60bf 868 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
869 global $DB;
870
883ce421
MN
871 $messagesql = "SELECT m.*
872 FROM {messages} m
873 INNER JOIN {message_conversations} mc
874 ON mc.id = m.conversationid
875 INNER JOIN {message_conversation_members} mcm
876 ON mcm.conversationid = mc.id
5aac33c7
MN
877 LEFT JOIN {message_user_actions} mua
878 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
879 WHERE mua.id is NULL
880 AND mcm.userid = ?
74ad60bf 881 AND m.useridfrom != ?";
5aac33c7
MN
882 $messageparams = [];
883 $messageparams[] = $userid;
884 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
885 $messageparams[] = $userid;
886 $messageparams[] = $userid;
887 if (!is_null($conversationid)) {
888 $messagesql .= " AND mc.id = ?";
889 $messageparams[] = $conversationid;
79f6c36c
MN
890 }
891
74ad60bf
MN
892 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
893 foreach ($messages as $message) {
894 self::mark_message_as_read($userid, $message);
895 }
896 $messages->close();
897 }
898
899 /**
900 * Marks all notifications being sent from one user to another user as read.
901 *
902 * If the from user is null then it marks all notifications as read sent to the to user.
903 *
904 * @param int $touserid the id of the message recipient
905 * @param int|null $fromuserid the id of the message sender, null if all messages
906 * @return void
907 */
908 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
909 global $DB;
910
883ce421
MN
911 $notificationsql = "SELECT n.*
912 FROM {notifications} n
74ad60bf
MN
913 WHERE useridto = ?
914 AND timeread is NULL";
883ce421 915 $notificationsparams = [$touserid];
79f6c36c 916 if (!empty($fromuserid)) {
883ce421
MN
917 $notificationsql .= " AND useridfrom = ?";
918 $notificationsparams[] = $fromuserid;
79f6c36c
MN
919 }
920
74ad60bf
MN
921 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
922 foreach ($notifications as $notification) {
923 self::mark_notification_as_read($notification);
79f6c36c 924 }
74ad60bf
MN
925 $notifications->close();
926 }
79f6c36c 927
74ad60bf
MN
928 /**
929 * Marks ALL messages being sent from $fromuserid to $touserid as read.
930 *
931 * Can be filtered by type.
932 *
933 * @deprecated since 3.5
934 * @param int $touserid the id of the message recipient
935 * @param int $fromuserid the id of the message sender
936 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
937 * @return void
938 */
939 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
940 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
941 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
942 DEBUG_DEVELOPER);
943
944 $type = strtolower($type);
945
946 $conversationid = null;
947 $ignoremessages = false;
948 if (!empty($fromuserid)) {
99248f61 949 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
950 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
951 $ignoremessages = true;
952 }
79f6c36c
MN
953 }
954
74ad60bf
MN
955 if (!empty($type)) {
956 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 957 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
958 } else if ($type == MESSAGE_TYPE_MESSAGE) {
959 if (!$ignoremessages) {
99248f61 960 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
961 }
962 }
963 } else { // We want both.
99248f61 964 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 965 if (!$ignoremessages) {
99248f61 966 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 967 }
883ce421 968 }
79f6c36c
MN
969 }
970
79f6c36c
MN
971 /**
972 * Returns message preferences.
973 *
974 * @param array $processors
975 * @param array $providers
976 * @param \stdClass $user
977 * @return \stdClass
978 * @since 3.2
979 */
980 public static function get_all_message_preferences($processors, $providers, $user) {
981 $preferences = helper::get_providers_preferences($providers, $user->id);
982 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
983
984 // For every processors put its options on the form (need to get function from processor's lib.php).
985 foreach ($processors as $processor) {
986 $processor->object->load_data($preferences, $user->id);
987 }
988
989 // Load general messaging preferences.
f7dfa9ba 990 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
991 $preferences->mailformat = $user->mailformat;
992 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
993
994 return $preferences;
995 }
5b0769db
MN
996
997 /**
998 * Count the number of users blocked by a user.
999 *
1000 * @param \stdClass $user The user object
1001 * @return int the number of blocked users
1002 */
1003 public static function count_blocked_users($user = null) {
1004 global $USER, $DB;
1005
1006 if (empty($user)) {
1007 $user = $USER;
1008 }
1009
f219eac7
MN
1010 $sql = "SELECT count(mub.id)
1011 FROM {message_users_blocked} mub
1012 WHERE mub.userid = :userid";
5b0769db
MN
1013 return $DB->count_records_sql($sql, array('userid' => $user->id));
1014 }
1015
1016 /**
1017 * Determines if a user is permitted to send another user a private message.
1018 * If no sender is provided then it defaults to the logged in user.
1019 *
1020 * @param \stdClass $recipient The user object.
1021 * @param \stdClass|null $sender The user object.
1022 * @return bool true if user is permitted, false otherwise.
1023 */
1024 public static function can_post_message($recipient, $sender = null) {
1025 global $USER;
1026
1027 if (is_null($sender)) {
1028 // The message is from the logged in user, unless otherwise specified.
1029 $sender = $USER;
1030 }
1031
7983fb83
SA
1032 $systemcontext = \context_system::instance();
1033 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1034 return false;
1035 }
1036
7983fb83 1037 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1038 return true;
1039 }
1040
7983fb83
SA
1041 // Check if the recipient can be messaged by the sender.
1042 return (self::can_contact_user($recipient, $sender));
5b0769db
MN
1043 }
1044
f7dfa9ba
SA
1045 /**
1046 * Get the messaging preference for a user.
1047 * If the user has not any messaging privacy preference:
1048 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1049 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1050 *
1051 * @param int $userid The user identifier.
1052 * @return int The default messaging preference.
1053 */
1054 public static function get_user_privacy_messaging_preference(int $userid) : int {
1055 global $CFG;
1056
1057 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1058 // otherwise, the default value will be "My contacts and anyone in my courses".
1059 if (empty($CFG->messagingallusers)) {
1060 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1061 } else {
1062 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1063 }
1064 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1065
1066 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1067 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1068 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1069 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1070 }
1071
1072 return $privacypreference;
1073 }
1074
5b0769db
MN
1075 /**
1076 * Checks if the recipient is allowing messages from users that aren't a
1077 * contact. If not then it checks to make sure the sender is in the
1078 * recipient's contacts.
1079 *
e5eba802 1080 * @deprecated since 3.6
5b0769db
MN
1081 * @param \stdClass $recipient The user object.
1082 * @param \stdClass|null $sender The user object.
1083 * @return bool true if $sender is blocked, false otherwise.
1084 */
1085 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1086 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1087
f7dfa9ba 1088 global $USER, $CFG;
5b0769db
MN
1089
1090 if (is_null($sender)) {
1091 // The message is from the logged in user, unless otherwise specified.
1092 $sender = $USER;
1093 }
1094
f7dfa9ba
SA
1095 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1096 switch ($privacypreference) {
1097 case self::MESSAGE_PRIVACY_SITE:
1098 if (!empty($CFG->messagingallusers)) {
1099 // Users can be messaged without being contacts or members of the same course.
1100 break;
1101 }
1102 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1103 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1104 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1105 // Confirm the sender and the recipient are both members of the same course.
1106 if (enrol_sharing_course($recipient, $sender)) {
1107 // All good, the recipient and the sender are members of the same course.
1108 return false;
1109 }
1110 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1111 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1112 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1113 }
1114
1115 return false;
1116 }
1117
1118 /**
1119 * Checks if the recipient has specifically blocked the sending user.
1120 *
1121 * Note: This function will always return false if the sender has the
1122 * readallmessages capability at the system context level.
1123 *
c886e2c9 1124 * @deprecated since 3.6
26dca05d
JP
1125 * @param int $recipientid User ID of the recipient.
1126 * @param int $senderid User ID of the sender.
5b0769db
MN
1127 * @return bool true if $sender is blocked, false otherwise.
1128 */
26dca05d 1129 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1130 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1131 DEBUG_DEVELOPER);
1132
1133 global $USER;
5b0769db 1134
26dca05d 1135 if (is_null($senderid)) {
5b0769db 1136 // The message is from the logged in user, unless otherwise specified.
26dca05d 1137 $senderid = $USER->id;
5b0769db
MN
1138 }
1139
1140 $systemcontext = \context_system::instance();
26dca05d 1141 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1142 return false;
1143 }
1144
f219eac7 1145 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1146 return true;
5b0769db
MN
1147 }
1148
1149 return false;
1150 }
20ab51fd
AA
1151
1152 /**
1153 * Get specified message processor, validate corresponding plugin existence and
1154 * system configuration.
1155 *
1156 * @param string $name Name of the processor.
1157 * @param bool $ready only return ready-to-use processors.
1158 * @return mixed $processor if processor present else empty array.
1159 * @since Moodle 3.2
1160 */
1161 public static function get_message_processor($name, $ready = false) {
1162 global $DB, $CFG;
1163
1164 $processor = $DB->get_record('message_processors', array('name' => $name));
1165 if (empty($processor)) {
1166 // Processor not found, return.
1167 return array();
1168 }
1169
1170 $processor = self::get_processed_processor_object($processor);
1171 if ($ready) {
1172 if ($processor->enabled && $processor->configured) {
1173 return $processor;
1174 } else {
1175 return array();
1176 }
1177 } else {
1178 return $processor;
1179 }
1180 }
1181
1182 /**
1183 * Returns weather a given processor is enabled or not.
1184 * Note:- This doesn't check if the processor is configured or not.
1185 *
1186 * @param string $name Name of the processor
1187 * @return bool
1188 */
1189 public static function is_processor_enabled($name) {
1190
1191 $cache = \cache::make('core', 'message_processors_enabled');
1192 $status = $cache->get($name);
1193
1194 if ($status === false) {
1195 $processor = self::get_message_processor($name);
1196 if (!empty($processor)) {
1197 $cache->set($name, $processor->enabled);
1198 return $processor->enabled;
1199 } else {
1200 return false;
1201 }
1202 }
1203
1204 return $status;
1205 }
1206
1207 /**
1208 * Set status of a processor.
1209 *
1210 * @param \stdClass $processor processor record.
1211 * @param 0|1 $enabled 0 or 1 to set the processor status.
1212 * @return bool
1213 * @since Moodle 3.2
1214 */
1215 public static function update_processor_status($processor, $enabled) {
1216 global $DB;
1217 $cache = \cache::make('core', 'message_processors_enabled');
1218 $cache->delete($processor->name);
1219 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1220 }
1221
1222 /**
1223 * Given a processor object, loads information about it's settings and configurations.
1224 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1225 * or @see \get_message_processors()
1226 *
1227 * @param \stdClass $processor processor object
1228 * @return \stdClass processed processor object
1229 * @since Moodle 3.2
1230 */
1231 public static function get_processed_processor_object(\stdClass $processor) {
1232 global $CFG;
1233
1234 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1235 if (is_readable($processorfile)) {
1236 include_once($processorfile);
1237 $processclass = 'message_output_' . $processor->name;
1238 if (class_exists($processclass)) {
1239 $pclass = new $processclass();
1240 $processor->object = $pclass;
1241 $processor->configured = 0;
1242 if ($pclass->is_system_configured()) {
1243 $processor->configured = 1;
1244 }
1245 $processor->hassettings = 0;
1246 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1247 $processor->hassettings = 1;
1248 }
1249 $processor->available = 1;
1250 } else {
1251 print_error('errorcallingprocessor', 'message');
1252 }
1253 } else {
1254 $processor->available = 0;
1255 }
1256 return $processor;
1257 }
883ce421
MN
1258
1259 /**
1260 * Retrieve users blocked by $user1
1261 *
1262 * @param int $userid The user id of the user whos blocked users we are returning
1263 * @return array the users blocked
1264 */
1265 public static function get_blocked_users($userid) {
1266 global $DB;
1267
1268 $userfields = \user_picture::fields('u', array('lastaccess'));
1269 $blockeduserssql = "SELECT $userfields
f219eac7 1270 FROM {message_users_blocked} mub
883ce421 1271 INNER JOIN {user} u
f219eac7 1272 ON u.id = mub.blockeduserid
883ce421 1273 WHERE u.deleted = 0
f219eac7 1274 AND mub.userid = ?
883ce421
MN
1275 GROUP BY $userfields
1276 ORDER BY u.firstname ASC";
1277 return $DB->get_records_sql($blockeduserssql, [$userid]);
1278 }
1279
1280 /**
1281 * Mark a single message as read.
1282 *
1283 * @param int $userid The user id who marked the message as read
548936a6 1284 * @param \stdClass $message The message
883ce421
MN
1285 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1286 */
548936a6 1287 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1288 global $DB;
1289
1290 if (is_null($timeread)) {
1291 $timeread = time();
1292 }
1293
5aac33c7
MN
1294 $mua = new \stdClass();
1295 $mua->userid = $userid;
1296 $mua->messageid = $message->id;
1297 $mua->action = self::MESSAGE_ACTION_READ;
1298 $mua->timecreated = $timeread;
1299 $mua->id = $DB->insert_record('message_user_actions', $mua);
1300
1301 // Get the context for the user who received the message.
1302 $context = \context_user::instance($userid, IGNORE_MISSING);
1303 // If the user no longer exists the context value will be false, in this case use the system context.
1304 if ($context === false) {
1305 $context = \context_system::instance();
883ce421 1306 }
5aac33c7
MN
1307
1308 // Trigger event for reading a message.
1309 $event = \core\event\message_viewed::create(array(
1310 'objectid' => $mua->id,
1311 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1312 'context' => $context,
1313 'relateduserid' => $message->useridfrom,
1314 'other' => array(
1315 'messageid' => $message->id
1316 )
1317 ));
1318 $event->trigger();
883ce421
MN
1319 }
1320
1321 /**
1322 * Mark a single notification as read.
1323 *
548936a6 1324 * @param \stdClass $notification The notification
883ce421
MN
1325 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1326 */
548936a6 1327 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1328 global $DB;
1329
1330 if (is_null($timeread)) {
1331 $timeread = time();
1332 }
1333
883ce421
MN
1334 if (is_null($notification->timeread)) {
1335 $updatenotification = new \stdClass();
1336 $updatenotification->id = $notification->id;
1337 $updatenotification->timeread = $timeread;
1338
1339 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1340
1341 // Trigger event for reading a notification.
1342 \core\event\notification_viewed::create_from_ids(
1343 $notification->useridfrom,
1344 $notification->useridto,
1345 $notification->id
1346 )->trigger();
883ce421
MN
1347 }
1348 }
1349
1350 /**
1351 * Checks if a user can delete a message.
1352 *
1353 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1354 * but will still seem as if it was by the user)
1355 * @param int $messageid The message id
1356 * @return bool Returns true if a user can delete the message, false otherwise.
1357 */
1358 public static function can_delete_message($userid, $messageid) {
1359 global $DB, $USER;
1360
08cb8a34
MN
1361 $systemcontext = \context_system::instance();
1362
1363 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1364
1365 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1366 return true;
883ce421
MN
1367 }
1368
08cb8a34
MN
1369 if (!self::is_user_in_conversation($userid, $conversationid)) {
1370 return false;
1371 }
883ce421 1372
08cb8a34
MN
1373 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1374 $USER->id == $userid) {
883ce421
MN
1375 return true;
1376 }
1377
1378 return false;
1379 }
1380
1381 /**
1382 * Deletes a message.
1383 *
1384 * This function does not verify any permissions.
1385 *
1386 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1387 * but will still seem as if it was by the user)
1388 * @param int $messageid The message id
1389 * @return bool
1390 */
1391 public static function delete_message($userid, $messageid) {
14de10c4 1392 global $DB, $USER;
883ce421 1393
14de10c4
MN
1394 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1395 return false;
1396 }
883ce421
MN
1397
1398 // Check if the user has already deleted this message.
1399 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1400 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1401 $mua = new \stdClass();
1402 $mua->userid = $userid;
1403 $mua->messageid = $messageid;
1404 $mua->action = self::MESSAGE_ACTION_DELETED;
1405 $mua->timecreated = time();
1406 $mua->id = $DB->insert_record('message_user_actions', $mua);
1407
1408 // Trigger event for deleting a message.
14de10c4
MN
1409 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1410 $messageid, $mua->id)->trigger();
883ce421
MN
1411
1412 return true;
1413 }
1414
1415 return false;
1416 }
1417
1418 /**
1419 * Returns the conversation between two users.
1420 *
b2cd17e6 1421 * @param array $userids
883ce421
MN
1422 * @return int|bool The id of the conversation, false if not found
1423 */
b2cd17e6 1424 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1425 global $DB;
1426
b2cd17e6 1427 $hash = helper::get_conversation_hash($userids);
883ce421 1428
f2ac0a3e
MN
1429 $params = [
1430 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1431 'convhash' => $hash
1432 ];
1433 if ($conversation = $DB->get_record('message_conversations', $params)) {
883ce421
MN
1434 return $conversation->id;
1435 }
1436
1437 return false;
1438 }
1439
1440 /**
1441 * Creates a conversation between two users.
1442 *
a66ae849 1443 * @deprecated since 3.6
b2cd17e6 1444 * @param array $userids
883ce421
MN
1445 * @return int The id of the conversation
1446 */
b2cd17e6 1447 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
1448 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1449 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1450
f2ac0a3e
MN
1451 // This method was always used for individual conversations.
1452 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1453
1454 return $conversation->id;
1455 }
1456
1457 /**
1458 * Creates a conversation with selected users and messages.
1459 *
1460 * @param int $type The type of conversation
1461 * @param int[] $userids The array of users to add to the conversation
1462 * @param string $name The name of the conversation
1463 * @return \stdClass
1464 */
1465 public static function create_conversation(int $type, array $userids, string $name = null) {
883ce421
MN
1466 global $DB;
1467
f2ac0a3e
MN
1468 // Sanity check.
1469 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1470 if (count($userids) > 2) {
1471 throw new \moodle_exception('An individual conversation can not have more than two users.');
1472 }
1473 }
1474
883ce421 1475 $conversation = new \stdClass();
f2ac0a3e
MN
1476 $conversation->type = $type;
1477 $conversation->name = $name;
1478 $conversation->convhash = null;
1479 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1480 $conversation->convhash = helper::get_conversation_hash($userids);
1481 }
883ce421
MN
1482 $conversation->timecreated = time();
1483 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1484
f2ac0a3e
MN
1485 // Add users to this conversation.
1486 $arrmembers = [];
b2cd17e6
MN
1487 foreach ($userids as $userid) {
1488 $member = new \stdClass();
1489 $member->conversationid = $conversation->id;
1490 $member->userid = $userid;
1491 $member->timecreated = time();
f2ac0a3e
MN
1492 $member->id = $DB->insert_record('message_conversation_members', $member);
1493
1494 $arrmembers[] = $member;
b2cd17e6 1495 }
883ce421 1496
f2ac0a3e
MN
1497 $conversation->members = $arrmembers;
1498
1499 return $conversation;
883ce421 1500 }
0b3eadcd 1501
e66b915c
MN
1502 /**
1503 * Checks if a user can create a group conversation.
1504 *
1505 * @param int $userid The id of the user attempting to create the conversation
1506 * @param \context $context The context they are creating the conversation from, most likely course context
1507 * @return bool
1508 */
1509 public static function can_create_group_conversation(int $userid, \context $context) : bool {
1510 global $CFG;
1511
1512 // If we can't message at all, then we can't create a conversation.
1513 if (empty($CFG->messaging)) {
1514 return false;
1515 }
1516
1517 // We need to check they have the capability to create the conversation.
1518 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 1519 }
0b3eadcd 1520
0d203bbf
MN
1521 /**
1522 * Checks if a user can create a contact request.
1523 *
1524 * @param int $userid The id of the user who is creating the contact request
1525 * @param int $requesteduserid The id of the user being requested
1526 * @return bool
1527 */
1528 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1529 global $CFG;
1530
1531 // If we can't message at all, then we can't create a contact.
1532 if (empty($CFG->messaging)) {
1533 return false;
1534 }
1535
1536 // If we can message anyone on the site then we can create a contact.
1537 if ($CFG->messagingallusers) {
1538 return true;
1539 }
1540
1541 // We need to check if they are in the same course.
1542 return enrol_sharing_course($userid, $requesteduserid);
1543 }
1544
0b3eadcd
MN
1545 /**
1546 * Handles creating a contact request.
1547 *
1548 * @param int $userid The id of the user who is creating the contact request
1549 * @param int $requesteduserid The id of the user being requested
1550 */
1551 public static function create_contact_request(int $userid, int $requesteduserid) {
1552 global $DB;
1553
1554 $request = new \stdClass();
1555 $request->userid = $userid;
1556 $request->requesteduserid = $requesteduserid;
1557 $request->timecreated = time();
1558
1559 $DB->insert_record('message_contact_requests', $request);
be016b01
MN
1560
1561 // Send a notification.
1562 $userfrom = \core_user::get_user($userid);
1563 $userfromfullname = fullname($userfrom);
1564 $userto = \core_user::get_user($requesteduserid);
1565 $url = new \moodle_url('/message/pendingcontactrequests.php');
1566
1567 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1568 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1569
1570 $message = new \core\message\message();
1571 $message->courseid = SITEID;
1572 $message->component = 'moodle';
1573 $message->name = 'messagecontactrequests';
1574 $message->notification = 1;
1575 $message->userfrom = $userfrom;
1576 $message->userto = $userto;
1577 $message->subject = $subject;
1578 $message->fullmessage = text_to_html($fullmessage);
1579 $message->fullmessageformat = FORMAT_HTML;
1580 $message->fullmessagehtml = $fullmessage;
1581 $message->smallmessage = '';
1582 $message->contexturl = $url->out(false);
1583
1584 message_send($message);
0b3eadcd
MN
1585 }
1586
1587
1588 /**
1589 * Handles confirming a contact request.
1590 *
1591 * @param int $userid The id of the user who created the contact request
1592 * @param int $requesteduserid The id of the user confirming the request
1593 */
1594 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1595 global $DB;
1596
1597 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1598 'requesteduserid' => $requesteduserid])) {
1599 self::add_contact($userid, $requesteduserid);
1600
1601 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1602 }
1603 }
1604
1605 /**
1606 * Handles declining a contact request.
1607 *
1608 * @param int $userid The id of the user who created the contact request
1609 * @param int $requesteduserid The id of the user declining the request
1610 */
1611 public static function decline_contact_request(int $userid, int $requesteduserid) {
1612 global $DB;
1613
1614 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1615 'requesteduserid' => $requesteduserid])) {
1616 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1617 }
1618 }
1619
1620 /**
1621 * Handles returning the contact requests for a user.
1622 *
1623 * This also includes the user data necessary to display information
1624 * about the user.
1625 *
1626 * It will not include blocked users.
1627 *
1628 * @param int $userid
1629 * @return array The list of contact requests
1630 */
1631 public static function get_contact_requests(int $userid) : array {
1632 global $DB;
1633
1634 // Used to search for contacts.
1635 $ufields = \user_picture::fields('u');
1636
1637 $sql = "SELECT $ufields, mcr.id as contactrequestid
1638 FROM {user} u
1639 JOIN {message_contact_requests} mcr
1640 ON u.id = mcr.userid
1641 LEFT JOIN {message_users_blocked} mub
1642 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1643 WHERE mcr.requesteduserid = ?
1644 AND u.deleted = 0
1645 AND mub.id is NULL
1646 ORDER BY mcr.timecreated DESC";
1647
1648 return $DB->get_records_sql($sql, [$userid, $userid]);
1649 }
1650
1651 /**
1652 * Handles adding a contact.
1653 *
1654 * @param int $userid The id of the user who requested to be a contact
1655 * @param int $contactid The id of the contact
1656 */
1657 public static function add_contact(int $userid, int $contactid) {
1658 global $DB;
1659
1660 $messagecontact = new \stdClass();
1661 $messagecontact->userid = $userid;
1662 $messagecontact->contactid = $contactid;
1663 $messagecontact->timecreated = time();
1664 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1665
1666 $eventparams = [
1667 'objectid' => $messagecontact->id,
1668 'userid' => $userid,
1669 'relateduserid' => $contactid,
1670 'context' => \context_user::instance($userid)
1671 ];
1672 $event = \core\event\message_contact_added::create($eventparams);
1673 $event->add_record_snapshot('message_contacts', $messagecontact);
1674 $event->trigger();
1675 }
1676
1677 /**
1678 * Handles removing a contact.
1679 *
1680 * @param int $userid The id of the user who is removing a user as a contact
1681 * @param int $contactid The id of the user to be removed as a contact
1682 */
1683 public static function remove_contact(int $userid, int $contactid) {
1684 global $DB;
1685
1686 if ($contact = self::get_contact($userid, $contactid)) {
1687 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1688
1689 $event = \core\event\message_contact_removed::create(array(
1690 'objectid' => $contact->id,
1691 'userid' => $userid,
1692 'relateduserid' => $contactid,
1693 'context' => \context_user::instance($userid)
1694 ));
1695 $event->add_record_snapshot('message_contacts', $contact);
1696 $event->trigger();
1697 }
1698 }
1699
1700 /**
1701 * Handles blocking a user.
1702 *
1703 * @param int $userid The id of the user who is blocking
1704 * @param int $usertoblockid The id of the user being blocked
1705 */
1706 public static function block_user(int $userid, int $usertoblockid) {
1707 global $DB;
1708
1709 $blocked = new \stdClass();
1710 $blocked->userid = $userid;
1711 $blocked->blockeduserid = $usertoblockid;
1712 $blocked->timecreated = time();
1713 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1714
1715 // Trigger event for blocking a contact.
1716 $event = \core\event\message_user_blocked::create(array(
1717 'objectid' => $blocked->id,
1718 'userid' => $userid,
1719 'relateduserid' => $usertoblockid,
1720 'context' => \context_user::instance($userid)
1721 ));
1722 $event->add_record_snapshot('message_users_blocked', $blocked);
1723 $event->trigger();
1724 }
1725
1726 /**
1727 * Handles unblocking a user.
1728 *
1729 * @param int $userid The id of the user who is unblocking
1730 * @param int $usertounblockid The id of the user being unblocked
1731 */
1732 public static function unblock_user(int $userid, int $usertounblockid) {
1733 global $DB;
1734
1735 if ($blockeduser = $DB->get_record('message_users_blocked',
1736 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1737 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1738
1739 // Trigger event for unblocking a contact.
1740 $event = \core\event\message_user_unblocked::create(array(
1741 'objectid' => $blockeduser->id,
1742 'userid' => $userid,
1743 'relateduserid' => $usertounblockid,
1744 'context' => \context_user::instance($userid)
1745 ));
1746 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1747 $event->trigger();
1748 }
1749 }
1750
1751 /**
1752 * Checks if users are already contacts.
1753 *
1754 * @param int $userid The id of one of the users
1755 * @param int $contactid The id of the other user
1756 * @return bool Returns true if they are a contact, false otherwise
1757 */
1758 public static function is_contact(int $userid, int $contactid) : bool {
1759 global $DB;
1760
1761 $sql = "SELECT id
1762 FROM {message_contacts} mc
1763 WHERE (mc.userid = ? AND mc.contactid = ?)
1764 OR (mc.userid = ? AND mc.contactid = ?)";
1765 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1766 }
1767
1768 /**
1769 * Returns the row in the database table message_contacts that represents the contact between two people.
1770 *
1771 * @param int $userid The id of one of the users
1772 * @param int $contactid The id of the other user
1773 * @return mixed A fieldset object containing the record, false otherwise
1774 */
1775 public static function get_contact(int $userid, int $contactid) {
1776 global $DB;
1777
1778 $sql = "SELECT mc.*
1779 FROM {message_contacts} mc
1780 WHERE (mc.userid = ? AND mc.contactid = ?)
1781 OR (mc.userid = ? AND mc.contactid = ?)";
1782 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1783 }
1784
1785 /**
1786 * Checks if a user is already blocked.
1787 *
0b3eadcd
MN
1788 * @param int $userid
1789 * @param int $blockeduserid
1790 * @return bool Returns true if they are a blocked, false otherwise
1791 */
1792 public static function is_blocked(int $userid, int $blockeduserid) : bool {
1793 global $DB;
1794
1795 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1796 }
1797
1798 /**
1799 * Checks if a contact request already exists between users.
1800 *
1801 * @param int $userid The id of the user who is creating the contact request
1802 * @param int $requesteduserid The id of the user being requested
1803 * @return bool Returns true if a contact request exists, false otherwise
1804 */
1805 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1806 global $DB;
1807
1808 $sql = "SELECT id
1809 FROM {message_contact_requests} mcr
1810 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1811 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1812 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1813 }
08cb8a34
MN
1814
1815 /**
1816 * Checks if a user is already in a conversation.
1817 *
1818 * @param int $userid The id of the user we want to check if they are in a group
1819 * @param int $conversationid The id of the conversation
1820 * @return bool Returns true if a contact request exists, false otherwise
1821 */
1822 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
1823 global $DB;
1824
1825 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
1826 'userid' => $userid]);
7983fb83
SA
1827 }
1828
1829 /**
1830 * Checks if the sender can message the recipient.
1831 *
1832 * @param \stdClass $recipient The user object.
1833 * @param \stdClass $sender The user object.
1834 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
1835 */
1836 protected static function can_contact_user(\stdClass $recipient, \stdClass $sender) : bool {
7983fb83
SA
1837 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $sender->id)) {
1838 // The sender has the ability to contact any user across the entire site.
1839 return true;
1840 }
1841
1842 // The initial value of $cancontact is null to indicate that a value has not been determined.
1843 $cancontact = null;
1844
1845 if (self::is_blocked($recipient->id, $sender->id)) {
1846 // The recipient has specifically blocked this sender.
1847 $cancontact = false;
1848 }
1849
1850 $sharedcourses = null;
1851 if (null === $cancontact) {
1852 // There are three user preference options:
1853 // - Site: Allow anyone not explicitly blocked to contact me;
1854 // - Course members: Allow anyone I am in a course with to contact me; and
1855 // - Contacts: Only allow my contacts to contact me.
1856 //
1857 // The Site option is only possible when the messagingallusers site setting is also enabled.
1858
1859 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1860 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
1861 // The user preference is to allow any user to contact them.
1862 // No need to check anything else.
1863 $cancontact = true;
1864 } else {
1865 // This user only allows their own contacts, and possibly course peers, to contact them.
1866 // If the users are contacts then we can avoid the more expensive shared courses check.
1867 $cancontact = self::is_contact($sender->id, $recipient->id);
1868
1869 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
1870 // The users are not contacts and the user allows course member messaging.
1871 // Check whether these two users share any course together.
1872 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
1873 $cancontact = (!empty($sharedcourses));
1874 }
1875 }
1876 }
1877
1878 if (false === $cancontact) {
1879 // At the moment the users cannot contact one another.
1880 // Check whether the messageanyuser capability applies in any of the shared courses.
1881 // This is intended to allow teachers to message students regardless of message settings.
1882
1883 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
1884 if (null === $sharedcourses) {
1885 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
1886 }
1887
1888 foreach ($sharedcourses as $course) {
1889 // Note: enrol_get_shared_courses will preload any shared context.
1890 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $sender->id)) {
1891 $cancontact = true;
1892 break;
1893 }
1894 }
1895 }
08cb8a34 1896
7983fb83 1897 return $cancontact;
08cb8a34 1898 }
67b81351 1899
623048af
AA
1900 /**
1901 * Add some new members to an existing conversation.
1902 *
1903 * @param array $userids User ids array to add as members.
1904 * @param int $convid The conversation id. Must exists.
1905 * @throws \dml_missing_record_exception If convid conversation doesn't exist
1906 * @throws \dml_exception If there is a database error
83e3a4fe 1907 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
1908 */
1909 public static function add_members_to_conversation(array $userids, int $convid) {
1910 global $DB;
1911
1912 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
1913
83e3a4fe
MN
1914 // We can only add members to a group conversation.
1915 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1916 throw new \moodle_exception('You can not add members to a non-group conversation.');
1917 }
1918
623048af
AA
1919 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
1920 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 1921 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
1922
1923 // Be sure we are not adding a user is already member of the conversation. Take all the members.
1924 $memberuserids = array_values($DB->get_records_menu(
1925 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
1926 );
1927
1928 // Work with existing new members.
1929 $members = array();
1930 $newuserids = array_diff($existingusers, $memberuserids);
1931 foreach ($newuserids as $userid) {
1932 $member = new \stdClass();
1933 $member->conversationid = $convid;
1934 $member->userid = $userid;
1935 $member->timecreated = time();
1936 $members[] = $member;
1937 }
1938
623048af 1939 $DB->insert_records('message_conversation_members', $members);
623048af
AA
1940 }
1941
1942 /**
1943 * Remove some members from an existing conversation.
1944 *
1945 * @param array $userids The user ids to remove from conversation members.
1946 * @param int $convid The conversation id. Must exists.
1947 * @throws \dml_exception
83e3a4fe 1948 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
1949 */
1950 public static function remove_members_from_conversation(array $userids, int $convid) {
1951 global $DB;
1952
1953 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
1954
83e3a4fe
MN
1955 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1956 throw new \moodle_exception('You can not remove members from a non-group conversation.');
1957 }
1958
623048af
AA
1959 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1960 $params['convid'] = $convid;
1961
623048af
AA
1962 $DB->delete_records_select('message_conversation_members',
1963 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
1964 }
1965
1966 /**
1967 * Count conversation members.
1968 *
1969 * @param int $convid The conversation id.
1970 * @return int Number of conversation members.
1971 * @throws \dml_exception
1972 */
1973 public static function count_conversation_members(int $convid) : int {
1974 global $DB;
08cb8a34 1975
623048af 1976 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 1977 }
55fda006 1978
1979 /**
1980 * Create message conversation area.
1981 *
1982 * @param string $component Defines the Moodle component which the area was added to
1983 * @param string $itemtype Defines the type of the component
1984 * @param int $itemid The id of the component
1985 * @param int $contextid The id of the context
1986 * @param int $enabled Allow enabled or disabled the conversation area
1987 * @param string $name The main name of the area
1988 * @return \stdClass
1989 */
1990 public static function create_conversation_area(string $component,
1991 string $itemtype,
1992 int $itemid,
1993 int $contextid,
1994 int $enabled = 0,
1995 string $name) {
1996 global $DB;
1997
1998 // Create a conversation.
1999 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_GROUP, array(), $name);
2000 // Create a conversation area.
2001 $conversationarea = new \stdClass;
2002 $conversationarea->conversationid = $conversation->id;
2003 $conversationarea->component = !empty($component) ? $component : '';
2004 $conversationarea->itemtype = $itemtype;
2005 $conversationarea->itemid = $itemid;
2006 $conversationarea->contextid = $contextid;
2007 $conversationarea->enabled = $enabled;
2008 $conversationarea->timecreated = time();
2009 $conversationarea->timemodified = $conversationarea->timecreated;
2010 $conversationarea->id = $DB->insert_record('message_conversation_area', $conversationarea);
2011
2012 return $conversationarea;
2013 }
879e2bef 2014}