MDL-63280 core_message: added constants for enabled/disabled
[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 */
79 const MESSAGE_CONVERSATION_AREA_ENABLED = 1;
80
81 /**
82 * The state for a disabled conversation area.
83 */
84 const MESSAGE_CONVERSATION_AREA_DISABLED = 0;
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 *
608 * @param int $userid the current user
609 * @param int $otheruserid the other user
610 * @param int $limitfrom
611 * @param int $limitnum
8ec78c48 612 * @param string $sort
ffd7798c
MN
613 * @param int $timefrom the time from the message being sent
614 * @param int $timeto the time up until the message being sent
de55cb1b 615 * @return array
879e2bef 616 */
fb1469d8 617 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 618 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 619
ffd7798c 620 if (!empty($timefrom)) {
fb1469d8 621 // Check the cache to see if we even need to do a DB query.
ffd7798c
MN
622 $cache = \cache::make('core', 'message_time_last_message_between_users');
623 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
fb1469d8
RW
624 $lastcreated = $cache->get($key);
625
626 // The last known message time is earlier than the one being requested so we can
627 // just return an empty result set rather than having to query the DB.
ffd7798c 628 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
629 return [];
630 }
631 }
632
879e2bef 633 $arrmessages = array();
fb1469d8 634 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 635 $sort, $timefrom, $timeto)) {
fb1469d8 636
de55cb1b 637 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
638 }
639
de55cb1b 640 return $arrmessages;
879e2bef 641 }
c060cd49
MN
642
643 /**
644 * Returns the most recent message between two users.
645 *
646 * @param int $userid the current user
647 * @param int $otheruserid the other user
de55cb1b 648 * @return \stdClass|null
c060cd49
MN
649 */
650 public static function get_most_recent_message($userid, $otheruserid) {
651 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 652 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
653 // Swap the order so we now have them in historical order.
654 $messages = array_reverse($messages);
de55cb1b 655 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
656 return array_pop($arrmessages);
657 }
658
659 return null;
660 }
c6e97f54
MN
661
662 /**
663 * Returns the profile information for a contact for a user.
664 *
665 * @param int $userid The user id
666 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 667 * @return \stdClass
c6e97f54
MN
668 */
669 public static function get_profile($userid, $otheruserid) {
f219eac7 670 global $CFG, $PAGE;
c6e97f54
MN
671
672 require_once($CFG->dirroot . '/user/lib.php');
673
f4c39cb9
MN
674 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
675
676 // Create the data we are going to pass to the renderable.
677 $data = new \stdClass();
678 $data->userid = $otheruserid;
679 $data->fullname = fullname($user);
680 $data->city = '';
681 $data->country = '';
682 $data->email = '';
cb805753 683 $data->isonline = null;
f4c39cb9
MN
684 // Get the user picture data - messaging has always shown these to the user.
685 $userpicture = new \user_picture($user);
686 $userpicture->size = 1; // Size f1.
687 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
688 $userpicture->size = 0; // Size f2.
689 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
690
691 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
692 if ($userfields) {
693 if (isset($userfields['city'])) {
694 $data->city = $userfields['city'];
695 }
696 if (isset($userfields['country'])) {
697 $data->country = $userfields['country'];
bf58081d 698 }
f4c39cb9
MN
699 if (isset($userfields['email'])) {
700 $data->email = $userfields['email'];
c6e97f54 701 }
f4c39cb9
MN
702 if (isset($userfields['lastaccess'])) {
703 $data->isonline = helper::is_online($userfields['lastaccess']);
704 }
705 }
c6e97f54 706
f219eac7
MN
707 $data->isblocked = self::is_blocked($userid, $otheruserid);
708 $data->iscontact = self::is_contact($userid, $otheruserid);
f4c39cb9
MN
709
710 return $data;
c6e97f54 711 }
dec0cd99
MN
712
713 /**
714 * Checks if a user can delete messages they have either received or sent.
715 *
716 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
717 * but will still seem as if it was by the user)
15663b0b 718 * @param int $conversationid The id of the conversation
1f64514d 719 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99 720 */
15663b0b 721 public static function can_delete_conversation(int $userid, int $conversationid = null) : bool {
dec0cd99
MN
722 global $USER;
723
15663b0b
MN
724 if (is_null($conversationid)) {
725 debugging('\core_message\api::can_delete_conversation() now expects a \'conversationid\' to be passed.',
726 DEBUG_DEVELOPER);
727 return false;
728 }
729
dec0cd99
MN
730 $systemcontext = \context_system::instance();
731
15663b0b
MN
732 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
733 return true;
734 }
735
736 if (!self::is_user_in_conversation($userid, $conversationid)) {
737 return false;
738 }
739
740 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
741 $USER->id == $userid) {
dec0cd99
MN
742 return true;
743 }
744
745 return false;
746 }
747
748 /**
749 * Deletes a conversation.
750 *
751 * This function does not verify any permissions.
752 *
263ad984 753 * @deprecated since 3.6
dec0cd99
MN
754 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
755 * but will still seem as if it was by the user)
756 * @param int $otheruserid The id of the other user in the conversation
757 * @return bool
758 */
759 public static function delete_conversation($userid, $otheruserid) {
263ad984
MN
760 debugging('\core_message\api::delete_conversation() is deprecated, please use ' .
761 '\core_message\api::delete_conversation_by_id() instead.', DEBUG_DEVELOPER);
dec0cd99 762
b2cd17e6 763 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 764
883ce421
MN
765 // If there is no conversation, there is nothing to do.
766 if (!$conversationid) {
767 return true;
768 }
769
263ad984
MN
770 self::delete_conversation_by_id($userid, $conversationid);
771
772 return true;
773 }
774
775 /**
776 * Deletes a conversation for a specified user.
777 *
778 * This function does not verify any permissions.
779 *
780 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
781 * but will still seem as if it was by the user)
782 * @param int $conversationid The id of the other user in the conversation
783 */
784 public static function delete_conversation_by_id(int $userid, int $conversationid) {
785 global $DB, $USER;
786
883ce421
MN
787 // Get all messages belonging to this conversation that have not already been deleted by this user.
788 $sql = "SELECT m.*
789 FROM {messages} m
790 INNER JOIN {message_conversations} mc
791 ON m.conversationid = mc.id
792 LEFT JOIN {message_user_actions} mua
793 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
794 WHERE mua.id is NULL
795 AND mc.id = ?
796 ORDER BY m.timecreated ASC";
797 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
798
799 // Ok, mark these as deleted.
800 foreach ($messages as $message) {
801 $mua = new \stdClass();
802 $mua->userid = $userid;
803 $mua->messageid = $message->id;
804 $mua->action = self::MESSAGE_ACTION_DELETED;
805 $mua->timecreated = time();
806 $mua->id = $DB->insert_record('message_user_actions', $mua);
807
14de10c4
MN
808 \core\event\message_deleted::create_from_ids($userid, $USER->id,
809 $message->id, $mua->id)->trigger();
dec0cd99 810 }
dec0cd99 811 }
79f6c36c
MN
812
813 /**
814 * Returns the count of unread conversations (collection of messages from a single user) for
815 * the given user.
816 *
817 * @param \stdClass $user the user who's conversations should be counted
818 * @return int the count of the user's unread conversations
819 */
820 public static function count_unread_conversations($user = null) {
821 global $USER, $DB;
822
823 if (empty($user)) {
824 $user = $USER;
825 }
826
883ce421
MN
827 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
828 FROM {messages} m
829 INNER JOIN {message_conversations} mc
830 ON m.conversationid = mc.id
831 INNER JOIN {message_conversation_members} mcm
832 ON mc.id = mcm.conversationid
833 LEFT JOIN {message_user_actions} mua
834 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
835 WHERE mcm.userid = ?
836 AND mcm.userid != m.useridfrom
837 AND mua.id is NULL";
838
839 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
840 }
841
abf7a261
MN
842 /**
843 * Checks if a user can mark all messages as read.
844 *
845 * @param int $userid The user id of who we want to mark the messages for
846 * @param int $conversationid The id of the conversation
847 * @return bool true if user is permitted, false otherwise
848 * @since 3.6
849 */
850 public static function can_mark_all_messages_as_read(int $userid, int $conversationid) : bool {
851 global $USER;
852
853 $systemcontext = \context_system::instance();
854
855 if (has_capability('moodle/site:readallmessages', $systemcontext)) {
856 return true;
857 }
858
859 if (!self::is_user_in_conversation($userid, $conversationid)) {
860 return false;
861 }
862
863 if ($USER->id == $userid) {
864 return true;
865 }
866
867 return false;
868 }
869
79f6c36c 870 /**
74ad60bf 871 * Marks all messages being sent to a user in a particular conversation.
79f6c36c 872 *
74ad60bf 873 * If $conversationdid is null then it marks all messages as read sent to $userid.
79f6c36c 874 *
74ad60bf
MN
875 * @param int $userid
876 * @param int|null $conversationid The conversation the messages belong to mark as read, if null mark all
79f6c36c 877 */
74ad60bf 878 public static function mark_all_messages_as_read($userid, $conversationid = null) {
79f6c36c
MN
879 global $DB;
880
883ce421
MN
881 $messagesql = "SELECT m.*
882 FROM {messages} m
883 INNER JOIN {message_conversations} mc
884 ON mc.id = m.conversationid
885 INNER JOIN {message_conversation_members} mcm
886 ON mcm.conversationid = mc.id
5aac33c7
MN
887 LEFT JOIN {message_user_actions} mua
888 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
889 WHERE mua.id is NULL
890 AND mcm.userid = ?
74ad60bf 891 AND m.useridfrom != ?";
5aac33c7
MN
892 $messageparams = [];
893 $messageparams[] = $userid;
894 $messageparams[] = self::MESSAGE_ACTION_READ;
74ad60bf
MN
895 $messageparams[] = $userid;
896 $messageparams[] = $userid;
897 if (!is_null($conversationid)) {
898 $messagesql .= " AND mc.id = ?";
899 $messageparams[] = $conversationid;
79f6c36c
MN
900 }
901
74ad60bf
MN
902 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
903 foreach ($messages as $message) {
904 self::mark_message_as_read($userid, $message);
905 }
906 $messages->close();
907 }
908
909 /**
910 * Marks all notifications being sent from one user to another user as read.
911 *
912 * If the from user is null then it marks all notifications as read sent to the to user.
913 *
914 * @param int $touserid the id of the message recipient
915 * @param int|null $fromuserid the id of the message sender, null if all messages
916 * @return void
917 */
918 public static function mark_all_notifications_as_read($touserid, $fromuserid = null) {
919 global $DB;
920
883ce421
MN
921 $notificationsql = "SELECT n.*
922 FROM {notifications} n
74ad60bf
MN
923 WHERE useridto = ?
924 AND timeread is NULL";
883ce421 925 $notificationsparams = [$touserid];
79f6c36c 926 if (!empty($fromuserid)) {
883ce421
MN
927 $notificationsql .= " AND useridfrom = ?";
928 $notificationsparams[] = $fromuserid;
79f6c36c
MN
929 }
930
74ad60bf
MN
931 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
932 foreach ($notifications as $notification) {
933 self::mark_notification_as_read($notification);
79f6c36c 934 }
74ad60bf
MN
935 $notifications->close();
936 }
79f6c36c 937
74ad60bf
MN
938 /**
939 * Marks ALL messages being sent from $fromuserid to $touserid as read.
940 *
941 * Can be filtered by type.
942 *
943 * @deprecated since 3.5
944 * @param int $touserid the id of the message recipient
945 * @param int $fromuserid the id of the message sender
946 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
947 * @return void
948 */
949 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
950 debugging('\core_message\api::mark_all_read_for_user is deprecated. Please either use ' .
951 '\core_message\api::mark_all_notifications_read_for_user or \core_message\api::mark_all_messages_read_for_user',
952 DEBUG_DEVELOPER);
953
954 $type = strtolower($type);
955
956 $conversationid = null;
957 $ignoremessages = false;
958 if (!empty($fromuserid)) {
99248f61 959 $conversationid = self::get_conversation_between_users([$touserid, $fromuserid]);
74ad60bf
MN
960 if (!$conversationid) { // If there is no conversation between the users then there are no messages to mark.
961 $ignoremessages = true;
962 }
79f6c36c
MN
963 }
964
74ad60bf
MN
965 if (!empty($type)) {
966 if ($type == MESSAGE_TYPE_NOTIFICATION) {
99248f61 967 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf
MN
968 } else if ($type == MESSAGE_TYPE_MESSAGE) {
969 if (!$ignoremessages) {
99248f61 970 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf
MN
971 }
972 }
973 } else { // We want both.
99248f61 974 self::mark_all_notifications_as_read($touserid, $fromuserid);
74ad60bf 975 if (!$ignoremessages) {
99248f61 976 self::mark_all_messages_as_read($touserid, $conversationid);
74ad60bf 977 }
883ce421 978 }
79f6c36c
MN
979 }
980
79f6c36c
MN
981 /**
982 * Returns message preferences.
983 *
984 * @param array $processors
985 * @param array $providers
986 * @param \stdClass $user
987 * @return \stdClass
988 * @since 3.2
989 */
990 public static function get_all_message_preferences($processors, $providers, $user) {
991 $preferences = helper::get_providers_preferences($providers, $user->id);
992 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
993
994 // For every processors put its options on the form (need to get function from processor's lib.php).
995 foreach ($processors as $processor) {
996 $processor->object->load_data($preferences, $user->id);
997 }
998
999 // Load general messaging preferences.
f7dfa9ba 1000 $preferences->blocknoncontacts = self::get_user_privacy_messaging_preference($user->id);
79f6c36c
MN
1001 $preferences->mailformat = $user->mailformat;
1002 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
1003
1004 return $preferences;
1005 }
5b0769db
MN
1006
1007 /**
1008 * Count the number of users blocked by a user.
1009 *
1010 * @param \stdClass $user The user object
1011 * @return int the number of blocked users
1012 */
1013 public static function count_blocked_users($user = null) {
1014 global $USER, $DB;
1015
1016 if (empty($user)) {
1017 $user = $USER;
1018 }
1019
f219eac7
MN
1020 $sql = "SELECT count(mub.id)
1021 FROM {message_users_blocked} mub
1022 WHERE mub.userid = :userid";
5b0769db
MN
1023 return $DB->count_records_sql($sql, array('userid' => $user->id));
1024 }
1025
1026 /**
1027 * Determines if a user is permitted to send another user a private message.
1028 * If no sender is provided then it defaults to the logged in user.
1029 *
1030 * @param \stdClass $recipient The user object.
1031 * @param \stdClass|null $sender The user object.
1032 * @return bool true if user is permitted, false otherwise.
1033 */
1034 public static function can_post_message($recipient, $sender = null) {
1035 global $USER;
1036
1037 if (is_null($sender)) {
1038 // The message is from the logged in user, unless otherwise specified.
1039 $sender = $USER;
1040 }
1041
7983fb83
SA
1042 $systemcontext = \context_system::instance();
1043 if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
5b0769db
MN
1044 return false;
1045 }
1046
7983fb83 1047 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
c886e2c9
MN
1048 return true;
1049 }
1050
7983fb83
SA
1051 // Check if the recipient can be messaged by the sender.
1052 return (self::can_contact_user($recipient, $sender));
5b0769db
MN
1053 }
1054
f7dfa9ba
SA
1055 /**
1056 * Get the messaging preference for a user.
1057 * If the user has not any messaging privacy preference:
1058 * - When $CFG->messagingallusers = false the default user preference is MESSAGE_PRIVACY_COURSEMEMBER.
1059 * - When $CFG->messagingallusers = true the default user preference is MESSAGE_PRIVACY_SITE.
1060 *
1061 * @param int $userid The user identifier.
1062 * @return int The default messaging preference.
1063 */
1064 public static function get_user_privacy_messaging_preference(int $userid) : int {
1065 global $CFG;
1066
1067 // When $CFG->messagingallusers is enabled, default value for the messaging preference will be "Anyone on the site";
1068 // otherwise, the default value will be "My contacts and anyone in my courses".
1069 if (empty($CFG->messagingallusers)) {
1070 $defaultprefvalue = self::MESSAGE_PRIVACY_COURSEMEMBER;
1071 } else {
1072 $defaultprefvalue = self::MESSAGE_PRIVACY_SITE;
1073 }
1074 $privacypreference = get_user_preferences('message_blocknoncontacts', $defaultprefvalue, $userid);
1075
1076 // When the $CFG->messagingallusers privacy setting is disabled, MESSAGE_PRIVACY_SITE is
1077 // also disabled, so it has to be replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1078 if (empty($CFG->messagingallusers) && $privacypreference == self::MESSAGE_PRIVACY_SITE) {
1079 $privacypreference = self::MESSAGE_PRIVACY_COURSEMEMBER;
1080 }
1081
1082 return $privacypreference;
1083 }
1084
5b0769db
MN
1085 /**
1086 * Checks if the recipient is allowing messages from users that aren't a
1087 * contact. If not then it checks to make sure the sender is in the
1088 * recipient's contacts.
1089 *
e5eba802 1090 * @deprecated since 3.6
5b0769db
MN
1091 * @param \stdClass $recipient The user object.
1092 * @param \stdClass|null $sender The user object.
1093 * @return bool true if $sender is blocked, false otherwise.
1094 */
1095 public static function is_user_non_contact_blocked($recipient, $sender = null) {
e5eba802
SA
1096 debugging('\core_message\api::is_user_non_contact_blocked() is deprecated', DEBUG_DEVELOPER);
1097
f7dfa9ba 1098 global $USER, $CFG;
5b0769db
MN
1099
1100 if (is_null($sender)) {
1101 // The message is from the logged in user, unless otherwise specified.
1102 $sender = $USER;
1103 }
1104
f7dfa9ba
SA
1105 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1106 switch ($privacypreference) {
1107 case self::MESSAGE_PRIVACY_SITE:
1108 if (!empty($CFG->messagingallusers)) {
1109 // Users can be messaged without being contacts or members of the same course.
1110 break;
1111 }
1112 // When the $CFG->messagingallusers privacy setting is disabled, continue with the next
1113 // case, because MESSAGE_PRIVACY_SITE is replaced to MESSAGE_PRIVACY_COURSEMEMBER.
1114 case self::MESSAGE_PRIVACY_COURSEMEMBER:
1115 // Confirm the sender and the recipient are both members of the same course.
1116 if (enrol_sharing_course($recipient, $sender)) {
1117 // All good, the recipient and the sender are members of the same course.
1118 return false;
1119 }
1120 case self::MESSAGE_PRIVACY_ONLYCONTACTS:
1121 // True if they aren't contacts (they can't send a message because of the privacy settings), false otherwise.
1122 return !self::is_contact($sender->id, $recipient->id);
5b0769db
MN
1123 }
1124
1125 return false;
1126 }
1127
1128 /**
1129 * Checks if the recipient has specifically blocked the sending user.
1130 *
1131 * Note: This function will always return false if the sender has the
1132 * readallmessages capability at the system context level.
1133 *
c886e2c9 1134 * @deprecated since 3.6
26dca05d
JP
1135 * @param int $recipientid User ID of the recipient.
1136 * @param int $senderid User ID of the sender.
5b0769db
MN
1137 * @return bool true if $sender is blocked, false otherwise.
1138 */
26dca05d 1139 public static function is_user_blocked($recipientid, $senderid = null) {
c886e2c9
MN
1140 debugging('\core_message\api::is_user_blocked is deprecated and should not be used.',
1141 DEBUG_DEVELOPER);
1142
1143 global $USER;
5b0769db 1144
26dca05d 1145 if (is_null($senderid)) {
5b0769db 1146 // The message is from the logged in user, unless otherwise specified.
26dca05d 1147 $senderid = $USER->id;
5b0769db
MN
1148 }
1149
1150 $systemcontext = \context_system::instance();
26dca05d 1151 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
1152 return false;
1153 }
1154
f219eac7 1155 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 1156 return true;
5b0769db
MN
1157 }
1158
1159 return false;
1160 }
20ab51fd
AA
1161
1162 /**
1163 * Get specified message processor, validate corresponding plugin existence and
1164 * system configuration.
1165 *
1166 * @param string $name Name of the processor.
1167 * @param bool $ready only return ready-to-use processors.
1168 * @return mixed $processor if processor present else empty array.
1169 * @since Moodle 3.2
1170 */
1171 public static function get_message_processor($name, $ready = false) {
1172 global $DB, $CFG;
1173
1174 $processor = $DB->get_record('message_processors', array('name' => $name));
1175 if (empty($processor)) {
1176 // Processor not found, return.
1177 return array();
1178 }
1179
1180 $processor = self::get_processed_processor_object($processor);
1181 if ($ready) {
1182 if ($processor->enabled && $processor->configured) {
1183 return $processor;
1184 } else {
1185 return array();
1186 }
1187 } else {
1188 return $processor;
1189 }
1190 }
1191
1192 /**
1193 * Returns weather a given processor is enabled or not.
1194 * Note:- This doesn't check if the processor is configured or not.
1195 *
1196 * @param string $name Name of the processor
1197 * @return bool
1198 */
1199 public static function is_processor_enabled($name) {
1200
1201 $cache = \cache::make('core', 'message_processors_enabled');
1202 $status = $cache->get($name);
1203
1204 if ($status === false) {
1205 $processor = self::get_message_processor($name);
1206 if (!empty($processor)) {
1207 $cache->set($name, $processor->enabled);
1208 return $processor->enabled;
1209 } else {
1210 return false;
1211 }
1212 }
1213
1214 return $status;
1215 }
1216
1217 /**
1218 * Set status of a processor.
1219 *
1220 * @param \stdClass $processor processor record.
1221 * @param 0|1 $enabled 0 or 1 to set the processor status.
1222 * @return bool
1223 * @since Moodle 3.2
1224 */
1225 public static function update_processor_status($processor, $enabled) {
1226 global $DB;
1227 $cache = \cache::make('core', 'message_processors_enabled');
1228 $cache->delete($processor->name);
1229 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1230 }
1231
1232 /**
1233 * Given a processor object, loads information about it's settings and configurations.
1234 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1235 * or @see \get_message_processors()
1236 *
1237 * @param \stdClass $processor processor object
1238 * @return \stdClass processed processor object
1239 * @since Moodle 3.2
1240 */
1241 public static function get_processed_processor_object(\stdClass $processor) {
1242 global $CFG;
1243
1244 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1245 if (is_readable($processorfile)) {
1246 include_once($processorfile);
1247 $processclass = 'message_output_' . $processor->name;
1248 if (class_exists($processclass)) {
1249 $pclass = new $processclass();
1250 $processor->object = $pclass;
1251 $processor->configured = 0;
1252 if ($pclass->is_system_configured()) {
1253 $processor->configured = 1;
1254 }
1255 $processor->hassettings = 0;
1256 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1257 $processor->hassettings = 1;
1258 }
1259 $processor->available = 1;
1260 } else {
1261 print_error('errorcallingprocessor', 'message');
1262 }
1263 } else {
1264 $processor->available = 0;
1265 }
1266 return $processor;
1267 }
883ce421
MN
1268
1269 /**
1270 * Retrieve users blocked by $user1
1271 *
1272 * @param int $userid The user id of the user whos blocked users we are returning
1273 * @return array the users blocked
1274 */
1275 public static function get_blocked_users($userid) {
1276 global $DB;
1277
1278 $userfields = \user_picture::fields('u', array('lastaccess'));
1279 $blockeduserssql = "SELECT $userfields
f219eac7 1280 FROM {message_users_blocked} mub
883ce421 1281 INNER JOIN {user} u
f219eac7 1282 ON u.id = mub.blockeduserid
883ce421 1283 WHERE u.deleted = 0
f219eac7 1284 AND mub.userid = ?
883ce421
MN
1285 GROUP BY $userfields
1286 ORDER BY u.firstname ASC";
1287 return $DB->get_records_sql($blockeduserssql, [$userid]);
1288 }
1289
1290 /**
1291 * Mark a single message as read.
1292 *
1293 * @param int $userid The user id who marked the message as read
548936a6 1294 * @param \stdClass $message The message
883ce421
MN
1295 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1296 */
548936a6 1297 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1298 global $DB;
1299
1300 if (is_null($timeread)) {
1301 $timeread = time();
1302 }
1303
5aac33c7
MN
1304 $mua = new \stdClass();
1305 $mua->userid = $userid;
1306 $mua->messageid = $message->id;
1307 $mua->action = self::MESSAGE_ACTION_READ;
1308 $mua->timecreated = $timeread;
1309 $mua->id = $DB->insert_record('message_user_actions', $mua);
1310
1311 // Get the context for the user who received the message.
1312 $context = \context_user::instance($userid, IGNORE_MISSING);
1313 // If the user no longer exists the context value will be false, in this case use the system context.
1314 if ($context === false) {
1315 $context = \context_system::instance();
883ce421 1316 }
5aac33c7
MN
1317
1318 // Trigger event for reading a message.
1319 $event = \core\event\message_viewed::create(array(
1320 'objectid' => $mua->id,
1321 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1322 'context' => $context,
1323 'relateduserid' => $message->useridfrom,
1324 'other' => array(
1325 'messageid' => $message->id
1326 )
1327 ));
1328 $event->trigger();
883ce421
MN
1329 }
1330
1331 /**
1332 * Mark a single notification as read.
1333 *
548936a6 1334 * @param \stdClass $notification The notification
883ce421
MN
1335 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1336 */
548936a6 1337 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1338 global $DB;
1339
1340 if (is_null($timeread)) {
1341 $timeread = time();
1342 }
1343
883ce421
MN
1344 if (is_null($notification->timeread)) {
1345 $updatenotification = new \stdClass();
1346 $updatenotification->id = $notification->id;
1347 $updatenotification->timeread = $timeread;
1348
1349 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1350
1351 // Trigger event for reading a notification.
1352 \core\event\notification_viewed::create_from_ids(
1353 $notification->useridfrom,
1354 $notification->useridto,
1355 $notification->id
1356 )->trigger();
883ce421
MN
1357 }
1358 }
1359
1360 /**
1361 * Checks if a user can delete a message.
1362 *
1363 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1364 * but will still seem as if it was by the user)
1365 * @param int $messageid The message id
1366 * @return bool Returns true if a user can delete the message, false otherwise.
1367 */
1368 public static function can_delete_message($userid, $messageid) {
1369 global $DB, $USER;
1370
08cb8a34
MN
1371 $systemcontext = \context_system::instance();
1372
1373 $conversationid = $DB->get_field('messages', 'conversationid', ['id' => $messageid], MUST_EXIST);
1374
1375 if (has_capability('moodle/site:deleteanymessage', $systemcontext)) {
1376 return true;
883ce421
MN
1377 }
1378
08cb8a34
MN
1379 if (!self::is_user_in_conversation($userid, $conversationid)) {
1380 return false;
1381 }
883ce421 1382
08cb8a34
MN
1383 if (has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1384 $USER->id == $userid) {
883ce421
MN
1385 return true;
1386 }
1387
1388 return false;
1389 }
1390
1391 /**
1392 * Deletes a message.
1393 *
1394 * This function does not verify any permissions.
1395 *
1396 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1397 * but will still seem as if it was by the user)
1398 * @param int $messageid The message id
1399 * @return bool
1400 */
1401 public static function delete_message($userid, $messageid) {
14de10c4 1402 global $DB, $USER;
883ce421 1403
14de10c4
MN
1404 if (!$DB->record_exists('messages', ['id' => $messageid])) {
1405 return false;
1406 }
883ce421
MN
1407
1408 // Check if the user has already deleted this message.
1409 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1410 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1411 $mua = new \stdClass();
1412 $mua->userid = $userid;
1413 $mua->messageid = $messageid;
1414 $mua->action = self::MESSAGE_ACTION_DELETED;
1415 $mua->timecreated = time();
1416 $mua->id = $DB->insert_record('message_user_actions', $mua);
1417
1418 // Trigger event for deleting a message.
14de10c4
MN
1419 \core\event\message_deleted::create_from_ids($userid, $USER->id,
1420 $messageid, $mua->id)->trigger();
883ce421
MN
1421
1422 return true;
1423 }
1424
1425 return false;
1426 }
1427
1428 /**
1429 * Returns the conversation between two users.
1430 *
b2cd17e6 1431 * @param array $userids
883ce421
MN
1432 * @return int|bool The id of the conversation, false if not found
1433 */
b2cd17e6 1434 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1435 global $DB;
1436
b2cd17e6 1437 $hash = helper::get_conversation_hash($userids);
883ce421 1438
f2ac0a3e
MN
1439 $params = [
1440 'type' => self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
1441 'convhash' => $hash
1442 ];
1443 if ($conversation = $DB->get_record('message_conversations', $params)) {
883ce421
MN
1444 return $conversation->id;
1445 }
1446
1447 return false;
1448 }
1449
1450 /**
1451 * Creates a conversation between two users.
1452 *
a66ae849 1453 * @deprecated since 3.6
b2cd17e6 1454 * @param array $userids
883ce421
MN
1455 * @return int The id of the conversation
1456 */
b2cd17e6 1457 public static function create_conversation_between_users(array $userids) {
a66ae849
MN
1458 debugging('\core_message\api::create_conversation_between_users is deprecated, please use ' .
1459 '\core_message\api::create_conversation instead.', DEBUG_DEVELOPER);
1460
f2ac0a3e
MN
1461 // This method was always used for individual conversations.
1462 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $userids);
1463
1464 return $conversation->id;
1465 }
1466
1467 /**
1468 * Creates a conversation with selected users and messages.
1469 *
1470 * @param int $type The type of conversation
1471 * @param int[] $userids The array of users to add to the conversation
1472 * @param string $name The name of the conversation
1473 * @return \stdClass
1474 */
1475 public static function create_conversation(int $type, array $userids, string $name = null) {
883ce421
MN
1476 global $DB;
1477
f2ac0a3e
MN
1478 // Sanity check.
1479 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1480 if (count($userids) > 2) {
1481 throw new \moodle_exception('An individual conversation can not have more than two users.');
1482 }
1483 }
1484
883ce421 1485 $conversation = new \stdClass();
f2ac0a3e
MN
1486 $conversation->type = $type;
1487 $conversation->name = $name;
1488 $conversation->convhash = null;
1489 if ($type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
1490 $conversation->convhash = helper::get_conversation_hash($userids);
1491 }
883ce421
MN
1492 $conversation->timecreated = time();
1493 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1494
f2ac0a3e
MN
1495 // Add users to this conversation.
1496 $arrmembers = [];
b2cd17e6
MN
1497 foreach ($userids as $userid) {
1498 $member = new \stdClass();
1499 $member->conversationid = $conversation->id;
1500 $member->userid = $userid;
1501 $member->timecreated = time();
f2ac0a3e
MN
1502 $member->id = $DB->insert_record('message_conversation_members', $member);
1503
1504 $arrmembers[] = $member;
b2cd17e6 1505 }
883ce421 1506
f2ac0a3e
MN
1507 $conversation->members = $arrmembers;
1508
1509 return $conversation;
883ce421 1510 }
0b3eadcd 1511
e66b915c
MN
1512 /**
1513 * Checks if a user can create a group conversation.
1514 *
1515 * @param int $userid The id of the user attempting to create the conversation
1516 * @param \context $context The context they are creating the conversation from, most likely course context
1517 * @return bool
1518 */
1519 public static function can_create_group_conversation(int $userid, \context $context) : bool {
1520 global $CFG;
1521
1522 // If we can't message at all, then we can't create a conversation.
1523 if (empty($CFG->messaging)) {
1524 return false;
1525 }
1526
1527 // We need to check they have the capability to create the conversation.
1528 return has_capability('moodle/course:creategroupconversations', $context, $userid);
883ce421 1529 }
0b3eadcd 1530
0d203bbf
MN
1531 /**
1532 * Checks if a user can create a contact request.
1533 *
1534 * @param int $userid The id of the user who is creating the contact request
1535 * @param int $requesteduserid The id of the user being requested
1536 * @return bool
1537 */
1538 public static function can_create_contact(int $userid, int $requesteduserid) : bool {
1539 global $CFG;
1540
1541 // If we can't message at all, then we can't create a contact.
1542 if (empty($CFG->messaging)) {
1543 return false;
1544 }
1545
1546 // If we can message anyone on the site then we can create a contact.
1547 if ($CFG->messagingallusers) {
1548 return true;
1549 }
1550
1551 // We need to check if they are in the same course.
1552 return enrol_sharing_course($userid, $requesteduserid);
1553 }
1554
0b3eadcd
MN
1555 /**
1556 * Handles creating a contact request.
1557 *
1558 * @param int $userid The id of the user who is creating the contact request
1559 * @param int $requesteduserid The id of the user being requested
1560 */
1561 public static function create_contact_request(int $userid, int $requesteduserid) {
1562 global $DB;
1563
1564 $request = new \stdClass();
1565 $request->userid = $userid;
1566 $request->requesteduserid = $requesteduserid;
1567 $request->timecreated = time();
1568
1569 $DB->insert_record('message_contact_requests', $request);
be016b01
MN
1570
1571 // Send a notification.
1572 $userfrom = \core_user::get_user($userid);
1573 $userfromfullname = fullname($userfrom);
1574 $userto = \core_user::get_user($requesteduserid);
1575 $url = new \moodle_url('/message/pendingcontactrequests.php');
1576
1577 $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
1578 $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);
1579
1580 $message = new \core\message\message();
1581 $message->courseid = SITEID;
1582 $message->component = 'moodle';
1583 $message->name = 'messagecontactrequests';
1584 $message->notification = 1;
1585 $message->userfrom = $userfrom;
1586 $message->userto = $userto;
1587 $message->subject = $subject;
1588 $message->fullmessage = text_to_html($fullmessage);
1589 $message->fullmessageformat = FORMAT_HTML;
1590 $message->fullmessagehtml = $fullmessage;
1591 $message->smallmessage = '';
1592 $message->contexturl = $url->out(false);
1593
1594 message_send($message);
0b3eadcd
MN
1595 }
1596
1597
1598 /**
1599 * Handles confirming a contact request.
1600 *
1601 * @param int $userid The id of the user who created the contact request
1602 * @param int $requesteduserid The id of the user confirming the request
1603 */
1604 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1605 global $DB;
1606
1607 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1608 'requesteduserid' => $requesteduserid])) {
1609 self::add_contact($userid, $requesteduserid);
1610
1611 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1612 }
1613 }
1614
1615 /**
1616 * Handles declining a contact request.
1617 *
1618 * @param int $userid The id of the user who created the contact request
1619 * @param int $requesteduserid The id of the user declining the request
1620 */
1621 public static function decline_contact_request(int $userid, int $requesteduserid) {
1622 global $DB;
1623
1624 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1625 'requesteduserid' => $requesteduserid])) {
1626 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1627 }
1628 }
1629
1630 /**
1631 * Handles returning the contact requests for a user.
1632 *
1633 * This also includes the user data necessary to display information
1634 * about the user.
1635 *
1636 * It will not include blocked users.
1637 *
1638 * @param int $userid
1639 * @return array The list of contact requests
1640 */
1641 public static function get_contact_requests(int $userid) : array {
1642 global $DB;
1643
1644 // Used to search for contacts.
1645 $ufields = \user_picture::fields('u');
1646
1647 $sql = "SELECT $ufields, mcr.id as contactrequestid
1648 FROM {user} u
1649 JOIN {message_contact_requests} mcr
1650 ON u.id = mcr.userid
1651 LEFT JOIN {message_users_blocked} mub
1652 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1653 WHERE mcr.requesteduserid = ?
1654 AND u.deleted = 0
1655 AND mub.id is NULL
1656 ORDER BY mcr.timecreated DESC";
1657
1658 return $DB->get_records_sql($sql, [$userid, $userid]);
1659 }
1660
1661 /**
1662 * Handles adding a contact.
1663 *
1664 * @param int $userid The id of the user who requested to be a contact
1665 * @param int $contactid The id of the contact
1666 */
1667 public static function add_contact(int $userid, int $contactid) {
1668 global $DB;
1669
1670 $messagecontact = new \stdClass();
1671 $messagecontact->userid = $userid;
1672 $messagecontact->contactid = $contactid;
1673 $messagecontact->timecreated = time();
1674 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1675
1676 $eventparams = [
1677 'objectid' => $messagecontact->id,
1678 'userid' => $userid,
1679 'relateduserid' => $contactid,
1680 'context' => \context_user::instance($userid)
1681 ];
1682 $event = \core\event\message_contact_added::create($eventparams);
1683 $event->add_record_snapshot('message_contacts', $messagecontact);
1684 $event->trigger();
1685 }
1686
1687 /**
1688 * Handles removing a contact.
1689 *
1690 * @param int $userid The id of the user who is removing a user as a contact
1691 * @param int $contactid The id of the user to be removed as a contact
1692 */
1693 public static function remove_contact(int $userid, int $contactid) {
1694 global $DB;
1695
1696 if ($contact = self::get_contact($userid, $contactid)) {
1697 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1698
1699 $event = \core\event\message_contact_removed::create(array(
1700 'objectid' => $contact->id,
1701 'userid' => $userid,
1702 'relateduserid' => $contactid,
1703 'context' => \context_user::instance($userid)
1704 ));
1705 $event->add_record_snapshot('message_contacts', $contact);
1706 $event->trigger();
1707 }
1708 }
1709
1710 /**
1711 * Handles blocking a user.
1712 *
1713 * @param int $userid The id of the user who is blocking
1714 * @param int $usertoblockid The id of the user being blocked
1715 */
1716 public static function block_user(int $userid, int $usertoblockid) {
1717 global $DB;
1718
1719 $blocked = new \stdClass();
1720 $blocked->userid = $userid;
1721 $blocked->blockeduserid = $usertoblockid;
1722 $blocked->timecreated = time();
1723 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1724
1725 // Trigger event for blocking a contact.
1726 $event = \core\event\message_user_blocked::create(array(
1727 'objectid' => $blocked->id,
1728 'userid' => $userid,
1729 'relateduserid' => $usertoblockid,
1730 'context' => \context_user::instance($userid)
1731 ));
1732 $event->add_record_snapshot('message_users_blocked', $blocked);
1733 $event->trigger();
1734 }
1735
1736 /**
1737 * Handles unblocking a user.
1738 *
1739 * @param int $userid The id of the user who is unblocking
1740 * @param int $usertounblockid The id of the user being unblocked
1741 */
1742 public static function unblock_user(int $userid, int $usertounblockid) {
1743 global $DB;
1744
1745 if ($blockeduser = $DB->get_record('message_users_blocked',
1746 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1747 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1748
1749 // Trigger event for unblocking a contact.
1750 $event = \core\event\message_user_unblocked::create(array(
1751 'objectid' => $blockeduser->id,
1752 'userid' => $userid,
1753 'relateduserid' => $usertounblockid,
1754 'context' => \context_user::instance($userid)
1755 ));
1756 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1757 $event->trigger();
1758 }
1759 }
1760
1761 /**
1762 * Checks if users are already contacts.
1763 *
1764 * @param int $userid The id of one of the users
1765 * @param int $contactid The id of the other user
1766 * @return bool Returns true if they are a contact, false otherwise
1767 */
1768 public static function is_contact(int $userid, int $contactid) : bool {
1769 global $DB;
1770
1771 $sql = "SELECT id
1772 FROM {message_contacts} mc
1773 WHERE (mc.userid = ? AND mc.contactid = ?)
1774 OR (mc.userid = ? AND mc.contactid = ?)";
1775 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1776 }
1777
1778 /**
1779 * Returns the row in the database table message_contacts that represents the contact between two people.
1780 *
1781 * @param int $userid The id of one of the users
1782 * @param int $contactid The id of the other user
1783 * @return mixed A fieldset object containing the record, false otherwise
1784 */
1785 public static function get_contact(int $userid, int $contactid) {
1786 global $DB;
1787
1788 $sql = "SELECT mc.*
1789 FROM {message_contacts} mc
1790 WHERE (mc.userid = ? AND mc.contactid = ?)
1791 OR (mc.userid = ? AND mc.contactid = ?)";
1792 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1793 }
1794
1795 /**
1796 * Checks if a user is already blocked.
1797 *
0b3eadcd
MN
1798 * @param int $userid
1799 * @param int $blockeduserid
1800 * @return bool Returns true if they are a blocked, false otherwise
1801 */
1802 public static function is_blocked(int $userid, int $blockeduserid) : bool {
1803 global $DB;
1804
1805 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1806 }
1807
1808 /**
1809 * Checks if a contact request already exists between users.
1810 *
1811 * @param int $userid The id of the user who is creating the contact request
1812 * @param int $requesteduserid The id of the user being requested
1813 * @return bool Returns true if a contact request exists, false otherwise
1814 */
1815 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1816 global $DB;
1817
1818 $sql = "SELECT id
1819 FROM {message_contact_requests} mcr
1820 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1821 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1822 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1823 }
08cb8a34
MN
1824
1825 /**
1826 * Checks if a user is already in a conversation.
1827 *
1828 * @param int $userid The id of the user we want to check if they are in a group
1829 * @param int $conversationid The id of the conversation
1830 * @return bool Returns true if a contact request exists, false otherwise
1831 */
1832 public static function is_user_in_conversation(int $userid, int $conversationid) : bool {
1833 global $DB;
1834
1835 return $DB->record_exists('message_conversation_members', ['conversationid' => $conversationid,
1836 'userid' => $userid]);
7983fb83
SA
1837 }
1838
1839 /**
1840 * Checks if the sender can message the recipient.
1841 *
1842 * @param \stdClass $recipient The user object.
1843 * @param \stdClass $sender The user object.
1844 * @return bool true if recipient hasn't blocked sender and sender can contact to recipient, false otherwise.
1845 */
1846 protected static function can_contact_user(\stdClass $recipient, \stdClass $sender) : bool {
7983fb83
SA
1847 if (has_capability('moodle/site:messageanyuser', \context_system::instance(), $sender->id)) {
1848 // The sender has the ability to contact any user across the entire site.
1849 return true;
1850 }
1851
1852 // The initial value of $cancontact is null to indicate that a value has not been determined.
1853 $cancontact = null;
1854
1855 if (self::is_blocked($recipient->id, $sender->id)) {
1856 // The recipient has specifically blocked this sender.
1857 $cancontact = false;
1858 }
1859
1860 $sharedcourses = null;
1861 if (null === $cancontact) {
1862 // There are three user preference options:
1863 // - Site: Allow anyone not explicitly blocked to contact me;
1864 // - Course members: Allow anyone I am in a course with to contact me; and
1865 // - Contacts: Only allow my contacts to contact me.
1866 //
1867 // The Site option is only possible when the messagingallusers site setting is also enabled.
1868
1869 $privacypreference = self::get_user_privacy_messaging_preference($recipient->id);
1870 if (self::MESSAGE_PRIVACY_SITE === $privacypreference) {
1871 // The user preference is to allow any user to contact them.
1872 // No need to check anything else.
1873 $cancontact = true;
1874 } else {
1875 // This user only allows their own contacts, and possibly course peers, to contact them.
1876 // If the users are contacts then we can avoid the more expensive shared courses check.
1877 $cancontact = self::is_contact($sender->id, $recipient->id);
1878
1879 if (!$cancontact && self::MESSAGE_PRIVACY_COURSEMEMBER === $privacypreference) {
1880 // The users are not contacts and the user allows course member messaging.
1881 // Check whether these two users share any course together.
1882 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
1883 $cancontact = (!empty($sharedcourses));
1884 }
1885 }
1886 }
1887
1888 if (false === $cancontact) {
1889 // At the moment the users cannot contact one another.
1890 // Check whether the messageanyuser capability applies in any of the shared courses.
1891 // This is intended to allow teachers to message students regardless of message settings.
1892
1893 // Note: You cannot use empty($sharedcourses) here because this may be an empty array.
1894 if (null === $sharedcourses) {
1895 $sharedcourses = enrol_get_shared_courses($recipient->id, $sender->id, true);
1896 }
1897
1898 foreach ($sharedcourses as $course) {
1899 // Note: enrol_get_shared_courses will preload any shared context.
1900 if (has_capability('moodle/site:messageanyuser', \context_course::instance($course->id), $sender->id)) {
1901 $cancontact = true;
1902 break;
1903 }
1904 }
1905 }
08cb8a34 1906
7983fb83 1907 return $cancontact;
08cb8a34 1908 }
67b81351 1909
623048af
AA
1910 /**
1911 * Add some new members to an existing conversation.
1912 *
1913 * @param array $userids User ids array to add as members.
1914 * @param int $convid The conversation id. Must exists.
1915 * @throws \dml_missing_record_exception If convid conversation doesn't exist
1916 * @throws \dml_exception If there is a database error
83e3a4fe 1917 * @throws \moodle_exception If trying to add a member(s) to a non-group conversation
623048af
AA
1918 */
1919 public static function add_members_to_conversation(array $userids, int $convid) {
1920 global $DB;
1921
1922 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
1923
83e3a4fe
MN
1924 // We can only add members to a group conversation.
1925 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1926 throw new \moodle_exception('You can not add members to a non-group conversation.');
1927 }
1928
623048af
AA
1929 // Be sure we are not trying to add a non existing user to the conversation. Work only with existing users.
1930 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
4abe3d25 1931 $existingusers = $DB->get_fieldset_select('user', 'id', "id $useridcondition", $params);
623048af
AA
1932
1933 // Be sure we are not adding a user is already member of the conversation. Take all the members.
1934 $memberuserids = array_values($DB->get_records_menu(
1935 'message_conversation_members', ['conversationid' => $convid], 'id', 'id, userid')
1936 );
1937
1938 // Work with existing new members.
1939 $members = array();
1940 $newuserids = array_diff($existingusers, $memberuserids);
1941 foreach ($newuserids as $userid) {
1942 $member = new \stdClass();
1943 $member->conversationid = $convid;
1944 $member->userid = $userid;
1945 $member->timecreated = time();
1946 $members[] = $member;
1947 }
1948
623048af 1949 $DB->insert_records('message_conversation_members', $members);
623048af
AA
1950 }
1951
1952 /**
1953 * Remove some members from an existing conversation.
1954 *
1955 * @param array $userids The user ids to remove from conversation members.
1956 * @param int $convid The conversation id. Must exists.
1957 * @throws \dml_exception
83e3a4fe 1958 * @throws \moodle_exception If trying to remove a member(s) from a non-group conversation
623048af
AA
1959 */
1960 public static function remove_members_from_conversation(array $userids, int $convid) {
1961 global $DB;
1962
1963 $conversation = $DB->get_record('message_conversations', ['id' => $convid], '*', MUST_EXIST);
1964
83e3a4fe
MN
1965 if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_GROUP) {
1966 throw new \moodle_exception('You can not remove members from a non-group conversation.');
1967 }
1968
623048af
AA
1969 list($useridcondition, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
1970 $params['convid'] = $convid;
1971
623048af
AA
1972 $DB->delete_records_select('message_conversation_members',
1973 "conversationid = :convid AND userid $useridcondition", $params);
623048af
AA
1974 }
1975
1976 /**
1977 * Count conversation members.
1978 *
1979 * @param int $convid The conversation id.
1980 * @return int Number of conversation members.
1981 * @throws \dml_exception
1982 */
1983 public static function count_conversation_members(int $convid) : int {
1984 global $DB;
08cb8a34 1985
623048af 1986 return $DB->count_records('message_conversation_members', ['conversationid' => $convid]);
08cb8a34 1987 }
55fda006 1988
1989 /**
1990 * Create message conversation area.
1991 *
1992 * @param string $component Defines the Moodle component which the area was added to
1993 * @param string $itemtype Defines the type of the component
1994 * @param int $itemid The id of the component
1995 * @param int $contextid The id of the context
55fda006 1996 * @param string $name The main name of the area
f0e137c5 1997 * @param int $enabled Enable or disable the conversation area
55fda006 1998 * @return \stdClass
1999 */
f0e137c5 2000 public static function create_conversation_area(string $component, string $itemtype, int $itemid, int $contextid, string $name,
5571af16 2001 int $enabled = self::MESSAGE_CONVERSATION_AREA_DISABLED) {
55fda006 2002 global $DB;
2003
2004 // Create a conversation.
2005 $conversation = self::create_conversation(self::MESSAGE_CONVERSATION_TYPE_GROUP, array(), $name);
f0e137c5 2006
55fda006 2007 // Create a conversation area.
2008 $conversationarea = new \stdClass;
2009 $conversationarea->conversationid = $conversation->id;
f0e137c5 2010 $conversationarea->component = $component;
55fda006 2011 $conversationarea->itemtype = $itemtype;
2012 $conversationarea->itemid = $itemid;
2013 $conversationarea->contextid = $contextid;
2014 $conversationarea->enabled = $enabled;
2015 $conversationarea->timecreated = time();
2016 $conversationarea->timemodified = $conversationarea->timecreated;
2017 $conversationarea->id = $DB->insert_record('message_conversation_area', $conversationarea);
2018
2019 return $conversationarea;
2020 }
e7f46714 2021
f0e137c5
MN
2022 /**
2023 * Checks whether or not a conversation area is enabled.
2024 *
2025 * @param string $component Defines the Moodle component which the area was added to.
2026 * @param string $itemtype Defines the type of the component.
2027 * @param int $itemid The id of the component.
2028 * @param int $contextid The id of the context.
2029 * @return bool Returns if a conversation area exists and is enabled, false otherwise
2030 */
2031 public static function is_conversation_area_enabled(string $component, string $itemtype, int $itemid, int $contextid) : bool {
2032 global $DB;
2033
2034 return $DB->record_exists('message_conversation_area',
2035 [
2036 'itemid' => $itemid,
2037 'contextid' => $contextid,
2038 'component' => $component,
2039 'itemtype' => $itemtype,
5571af16 2040 'enabled' => self::MESSAGE_CONVERSATION_AREA_ENABLED
f0e137c5
MN
2041 ]
2042 );
2043 }
2044
e7f46714 2045 /**
2046 * Get conversation area.
2047 *
2048 * @param string $component Defines the Moodle component which the area was added to.
2049 * @param string $itemtype Defines the type of the component.
2050 * @param int $itemid The id of the component.
2051 * @param int $contextid The id of the context.
2052 * @return object message_conversation_area.
2053 */
f0e137c5 2054 public static function get_conversation_area(string $component, string $itemtype, int $itemid, int $contextid) {
e7f46714 2055 global $DB;
2056
f0e137c5
MN
2057 return $DB->get_record('message_conversation_area',
2058 [
2059 'itemid' => $itemid,
2060 'contextid' => $contextid,
2061 'component' => $component,
2062 'itemtype' => $itemtype
2063 ]
2064 );
e7f46714 2065 }
2066
2067 /**
2068 * Enable a conversation area.
2069 *
2070 * @param int $conversationareaid The id of a conversation area.
2071 * @return void
2072 */
2073 public static function enable_conversation_area(int $conversationareaid) {
2074 global $DB;
2075
2076 $conversationarea = new \stdClass();
2077 $conversationarea->id = $conversationareaid;
5571af16 2078 $conversationarea->enabled = self::MESSAGE_CONVERSATION_AREA_ENABLED;
f0e137c5 2079 $conversationarea->timemodified = time();
e7f46714 2080 $DB->update_record('message_conversation_area', $conversationarea);
2081 }
2082
2083 /**
2084 * Disable a conversation area.
2085 *
2086 * @param int $conversationareaid The id of a conversation area.
2087 * @return void
2088 */
2089 public static function disable_conversation_area(int $conversationareaid) {
2090 global $DB;
2091
2092 $conversationarea = new \stdClass();
2093 $conversationarea->id = $conversationareaid;
5571af16 2094 $conversationarea->enabled = self::MESSAGE_CONVERSATION_AREA_DISABLED;
f0e137c5 2095 $conversationarea->timemodified = time();
e7f46714 2096 $DB->update_record('message_conversation_area', $conversationarea);
2097 }
2098
2099 /**
2100 * Update the name of a conversation.
2101 *
2102 * @param int $conversationid The id of a conversation.
2103 * @param string $name The main name of the area
2104 * @return void
2105 */
2106 public static function update_conversation_name(int $conversationid, string $name) {
2107 global $DB;
2108
2109 if ($conversation = $DB->get_record('message_conversations', array('id' => $conversationid))) {
2110 if ($name <> $conversation->name) {
2111 $conversation->name = $name;
f0e137c5 2112 $conversation->timemodified = time();
e7f46714 2113 $DB->update_record('message_conversations', $conversation);
2114 }
2115 }
2116 }
879e2bef 2117}