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