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