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