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