MDL-63211 core_message: add temporary pending contact requests page
[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 }
5b0769db 916 // The recipient has specifically blocked this sender.
26dca05d 917 if (self::is_user_blocked($recipient->id, $senderid)) {
5b0769db
MN
918 return false;
919 }
920
921 return true;
922 }
923
924 /**
925 * Checks if the recipient is allowing messages from users that aren't a
926 * contact. If not then it checks to make sure the sender is in the
927 * recipient's contacts.
928 *
929 * @param \stdClass $recipient The user object.
930 * @param \stdClass|null $sender The user object.
931 * @return bool true if $sender is blocked, false otherwise.
932 */
933 public static function is_user_non_contact_blocked($recipient, $sender = null) {
f219eac7 934 global $USER;
5b0769db
MN
935
936 if (is_null($sender)) {
937 // The message is from the logged in user, unless otherwise specified.
938 $sender = $USER;
939 }
940
941 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
942 if (!empty($blockednoncontacts)) {
943 // Confirm the sender is a contact of the recipient.
f219eac7 944 if (self::is_contact($sender->id, $recipient->id)) {
5b0769db
MN
945 // All good, the recipient is a contact of the sender.
946 return false;
947 } else {
948 // Oh no, the recipient is not a contact. Looks like we can't send the message.
949 return true;
950 }
951 }
952
953 return false;
954 }
955
956 /**
957 * Checks if the recipient has specifically blocked the sending user.
958 *
959 * Note: This function will always return false if the sender has the
960 * readallmessages capability at the system context level.
961 *
26dca05d
JP
962 * @param int $recipientid User ID of the recipient.
963 * @param int $senderid User ID of the sender.
5b0769db
MN
964 * @return bool true if $sender is blocked, false otherwise.
965 */
26dca05d 966 public static function is_user_blocked($recipientid, $senderid = null) {
5b0769db
MN
967 global $USER, $DB;
968
26dca05d 969 if (is_null($senderid)) {
5b0769db 970 // The message is from the logged in user, unless otherwise specified.
26dca05d 971 $senderid = $USER->id;
5b0769db
MN
972 }
973
974 $systemcontext = \context_system::instance();
26dca05d 975 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
976 return false;
977 }
978
f219eac7 979 if (self::is_blocked($recipientid, $senderid)) {
26dca05d 980 return true;
5b0769db
MN
981 }
982
983 return false;
984 }
20ab51fd
AA
985
986 /**
987 * Get specified message processor, validate corresponding plugin existence and
988 * system configuration.
989 *
990 * @param string $name Name of the processor.
991 * @param bool $ready only return ready-to-use processors.
992 * @return mixed $processor if processor present else empty array.
993 * @since Moodle 3.2
994 */
995 public static function get_message_processor($name, $ready = false) {
996 global $DB, $CFG;
997
998 $processor = $DB->get_record('message_processors', array('name' => $name));
999 if (empty($processor)) {
1000 // Processor not found, return.
1001 return array();
1002 }
1003
1004 $processor = self::get_processed_processor_object($processor);
1005 if ($ready) {
1006 if ($processor->enabled && $processor->configured) {
1007 return $processor;
1008 } else {
1009 return array();
1010 }
1011 } else {
1012 return $processor;
1013 }
1014 }
1015
1016 /**
1017 * Returns weather a given processor is enabled or not.
1018 * Note:- This doesn't check if the processor is configured or not.
1019 *
1020 * @param string $name Name of the processor
1021 * @return bool
1022 */
1023 public static function is_processor_enabled($name) {
1024
1025 $cache = \cache::make('core', 'message_processors_enabled');
1026 $status = $cache->get($name);
1027
1028 if ($status === false) {
1029 $processor = self::get_message_processor($name);
1030 if (!empty($processor)) {
1031 $cache->set($name, $processor->enabled);
1032 return $processor->enabled;
1033 } else {
1034 return false;
1035 }
1036 }
1037
1038 return $status;
1039 }
1040
1041 /**
1042 * Set status of a processor.
1043 *
1044 * @param \stdClass $processor processor record.
1045 * @param 0|1 $enabled 0 or 1 to set the processor status.
1046 * @return bool
1047 * @since Moodle 3.2
1048 */
1049 public static function update_processor_status($processor, $enabled) {
1050 global $DB;
1051 $cache = \cache::make('core', 'message_processors_enabled');
1052 $cache->delete($processor->name);
1053 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1054 }
1055
1056 /**
1057 * Given a processor object, loads information about it's settings and configurations.
1058 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1059 * or @see \get_message_processors()
1060 *
1061 * @param \stdClass $processor processor object
1062 * @return \stdClass processed processor object
1063 * @since Moodle 3.2
1064 */
1065 public static function get_processed_processor_object(\stdClass $processor) {
1066 global $CFG;
1067
1068 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1069 if (is_readable($processorfile)) {
1070 include_once($processorfile);
1071 $processclass = 'message_output_' . $processor->name;
1072 if (class_exists($processclass)) {
1073 $pclass = new $processclass();
1074 $processor->object = $pclass;
1075 $processor->configured = 0;
1076 if ($pclass->is_system_configured()) {
1077 $processor->configured = 1;
1078 }
1079 $processor->hassettings = 0;
1080 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1081 $processor->hassettings = 1;
1082 }
1083 $processor->available = 1;
1084 } else {
1085 print_error('errorcallingprocessor', 'message');
1086 }
1087 } else {
1088 $processor->available = 0;
1089 }
1090 return $processor;
1091 }
883ce421
MN
1092
1093 /**
1094 * Retrieve users blocked by $user1
1095 *
1096 * @param int $userid The user id of the user whos blocked users we are returning
1097 * @return array the users blocked
1098 */
1099 public static function get_blocked_users($userid) {
1100 global $DB;
1101
1102 $userfields = \user_picture::fields('u', array('lastaccess'));
1103 $blockeduserssql = "SELECT $userfields
f219eac7 1104 FROM {message_users_blocked} mub
883ce421 1105 INNER JOIN {user} u
f219eac7 1106 ON u.id = mub.blockeduserid
883ce421 1107 WHERE u.deleted = 0
f219eac7 1108 AND mub.userid = ?
883ce421
MN
1109 GROUP BY $userfields
1110 ORDER BY u.firstname ASC";
1111 return $DB->get_records_sql($blockeduserssql, [$userid]);
1112 }
1113
1114 /**
1115 * Mark a single message as read.
1116 *
1117 * @param int $userid The user id who marked the message as read
548936a6 1118 * @param \stdClass $message The message
883ce421
MN
1119 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1120 */
548936a6 1121 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1122 global $DB;
1123
1124 if (is_null($timeread)) {
1125 $timeread = time();
1126 }
1127
5aac33c7
MN
1128 $mua = new \stdClass();
1129 $mua->userid = $userid;
1130 $mua->messageid = $message->id;
1131 $mua->action = self::MESSAGE_ACTION_READ;
1132 $mua->timecreated = $timeread;
1133 $mua->id = $DB->insert_record('message_user_actions', $mua);
1134
1135 // Get the context for the user who received the message.
1136 $context = \context_user::instance($userid, IGNORE_MISSING);
1137 // If the user no longer exists the context value will be false, in this case use the system context.
1138 if ($context === false) {
1139 $context = \context_system::instance();
883ce421 1140 }
5aac33c7
MN
1141
1142 // Trigger event for reading a message.
1143 $event = \core\event\message_viewed::create(array(
1144 'objectid' => $mua->id,
1145 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1146 'context' => $context,
1147 'relateduserid' => $message->useridfrom,
1148 'other' => array(
1149 'messageid' => $message->id
1150 )
1151 ));
1152 $event->trigger();
883ce421
MN
1153 }
1154
1155 /**
1156 * Mark a single notification as read.
1157 *
548936a6 1158 * @param \stdClass $notification The notification
883ce421
MN
1159 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1160 */
548936a6 1161 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1162 global $DB;
1163
1164 if (is_null($timeread)) {
1165 $timeread = time();
1166 }
1167
883ce421
MN
1168 if (is_null($notification->timeread)) {
1169 $updatenotification = new \stdClass();
1170 $updatenotification->id = $notification->id;
1171 $updatenotification->timeread = $timeread;
1172
1173 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1174
1175 // Trigger event for reading a notification.
1176 \core\event\notification_viewed::create_from_ids(
1177 $notification->useridfrom,
1178 $notification->useridto,
1179 $notification->id
1180 )->trigger();
883ce421
MN
1181 }
1182 }
1183
1184 /**
1185 * Checks if a user can delete a message.
1186 *
1187 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1188 * but will still seem as if it was by the user)
1189 * @param int $messageid The message id
1190 * @return bool Returns true if a user can delete the message, false otherwise.
1191 */
1192 public static function can_delete_message($userid, $messageid) {
1193 global $DB, $USER;
1194
1195 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1196 FROM {messages} m
1197 INNER JOIN {message_conversations} mc
1198 ON m.conversationid = mc.id
1199 INNER JOIN {message_conversation_members} mcm
1200 ON mcm.conversationid = mc.id
1201 WHERE mcm.userid != m.useridfrom
1202 AND m.id = ?";
1203 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1204
1205 if ($message->useridfrom == $userid) {
1206 $userdeleting = 'useridfrom';
1207 } else if ($message->useridto == $userid) {
1208 $userdeleting = 'useridto';
1209 } else {
1210 return false;
1211 }
1212
1213 $systemcontext = \context_system::instance();
1214
1215 // Let's check if the user is allowed to delete this message.
1216 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1217 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1218 $USER->id == $message->$userdeleting))) {
1219 return true;
1220 }
1221
1222 return false;
1223 }
1224
1225 /**
1226 * Deletes a message.
1227 *
1228 * This function does not verify any permissions.
1229 *
1230 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1231 * but will still seem as if it was by the user)
1232 * @param int $messageid The message id
1233 * @return bool
1234 */
1235 public static function delete_message($userid, $messageid) {
1236 global $DB;
1237
1238 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1239 FROM {messages} m
1240 INNER JOIN {message_conversations} mc
1241 ON m.conversationid = mc.id
1242 INNER JOIN {message_conversation_members} mcm
1243 ON mcm.conversationid = mc.id
1244 WHERE mcm.userid != m.useridfrom
1245 AND m.id = ?";
1246 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1247
1248 // Check if the user has already deleted this message.
1249 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1250 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1251 $mua = new \stdClass();
1252 $mua->userid = $userid;
1253 $mua->messageid = $messageid;
1254 $mua->action = self::MESSAGE_ACTION_DELETED;
1255 $mua->timecreated = time();
1256 $mua->id = $DB->insert_record('message_user_actions', $mua);
1257
1258 // Trigger event for deleting a message.
1259 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1260 $userid, $message->id, $mua->id)->trigger();
1261
1262 return true;
1263 }
1264
1265 return false;
1266 }
1267
1268 /**
1269 * Returns the conversation between two users.
1270 *
b2cd17e6 1271 * @param array $userids
883ce421
MN
1272 * @return int|bool The id of the conversation, false if not found
1273 */
b2cd17e6 1274 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1275 global $DB;
1276
b2cd17e6 1277 $hash = helper::get_conversation_hash($userids);
883ce421 1278
b2cd17e6 1279 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
883ce421
MN
1280 return $conversation->id;
1281 }
1282
1283 return false;
1284 }
1285
1286 /**
1287 * Creates a conversation between two users.
1288 *
b2cd17e6 1289 * @param array $userids
883ce421
MN
1290 * @return int The id of the conversation
1291 */
b2cd17e6 1292 public static function create_conversation_between_users(array $userids) {
883ce421
MN
1293 global $DB;
1294
1295 $conversation = new \stdClass();
b2cd17e6 1296 $conversation->convhash = helper::get_conversation_hash($userids);
883ce421
MN
1297 $conversation->timecreated = time();
1298 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1299
1300 // Add members to this conversation.
b2cd17e6
MN
1301 foreach ($userids as $userid) {
1302 $member = new \stdClass();
1303 $member->conversationid = $conversation->id;
1304 $member->userid = $userid;
1305 $member->timecreated = time();
1306 $DB->insert_record('message_conversation_members', $member);
1307 }
883ce421
MN
1308
1309 return $conversation->id;
1310 }
0b3eadcd
MN
1311
1312 /**
1313 * Handles creating a contact request.
1314 *
1315 * @param int $userid The id of the user who is creating the contact request
1316 * @param int $requesteduserid The id of the user being requested
1317 */
1318 public static function create_contact_request(int $userid, int $requesteduserid) {
1319 global $DB;
1320
1321 $request = new \stdClass();
1322 $request->userid = $userid;
1323 $request->requesteduserid = $requesteduserid;
1324 $request->timecreated = time();
1325
1326 $DB->insert_record('message_contact_requests', $request);
1327 }
1328
1329
1330 /**
1331 * Handles confirming a contact request.
1332 *
1333 * @param int $userid The id of the user who created the contact request
1334 * @param int $requesteduserid The id of the user confirming the request
1335 */
1336 public static function confirm_contact_request(int $userid, int $requesteduserid) {
1337 global $DB;
1338
1339 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1340 'requesteduserid' => $requesteduserid])) {
1341 self::add_contact($userid, $requesteduserid);
1342
1343 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1344 }
1345 }
1346
1347 /**
1348 * Handles declining a contact request.
1349 *
1350 * @param int $userid The id of the user who created the contact request
1351 * @param int $requesteduserid The id of the user declining the request
1352 */
1353 public static function decline_contact_request(int $userid, int $requesteduserid) {
1354 global $DB;
1355
1356 if ($request = $DB->get_record('message_contact_requests', ['userid' => $userid,
1357 'requesteduserid' => $requesteduserid])) {
1358 $DB->delete_records('message_contact_requests', ['id' => $request->id]);
1359 }
1360 }
1361
1362 /**
1363 * Handles returning the contact requests for a user.
1364 *
1365 * This also includes the user data necessary to display information
1366 * about the user.
1367 *
1368 * It will not include blocked users.
1369 *
1370 * @param int $userid
1371 * @return array The list of contact requests
1372 */
1373 public static function get_contact_requests(int $userid) : array {
1374 global $DB;
1375
1376 // Used to search for contacts.
1377 $ufields = \user_picture::fields('u');
1378
1379 $sql = "SELECT $ufields, mcr.id as contactrequestid
1380 FROM {user} u
1381 JOIN {message_contact_requests} mcr
1382 ON u.id = mcr.userid
1383 LEFT JOIN {message_users_blocked} mub
1384 ON (mub.userid = ? AND mub.blockeduserid = u.id)
1385 WHERE mcr.requesteduserid = ?
1386 AND u.deleted = 0
1387 AND mub.id is NULL
1388 ORDER BY mcr.timecreated DESC";
1389
1390 return $DB->get_records_sql($sql, [$userid, $userid]);
1391 }
1392
1393 /**
1394 * Handles adding a contact.
1395 *
1396 * @param int $userid The id of the user who requested to be a contact
1397 * @param int $contactid The id of the contact
1398 */
1399 public static function add_contact(int $userid, int $contactid) {
1400 global $DB;
1401
1402 $messagecontact = new \stdClass();
1403 $messagecontact->userid = $userid;
1404 $messagecontact->contactid = $contactid;
1405 $messagecontact->timecreated = time();
1406 $messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
1407
1408 $eventparams = [
1409 'objectid' => $messagecontact->id,
1410 'userid' => $userid,
1411 'relateduserid' => $contactid,
1412 'context' => \context_user::instance($userid)
1413 ];
1414 $event = \core\event\message_contact_added::create($eventparams);
1415 $event->add_record_snapshot('message_contacts', $messagecontact);
1416 $event->trigger();
1417 }
1418
1419 /**
1420 * Handles removing a contact.
1421 *
1422 * @param int $userid The id of the user who is removing a user as a contact
1423 * @param int $contactid The id of the user to be removed as a contact
1424 */
1425 public static function remove_contact(int $userid, int $contactid) {
1426 global $DB;
1427
1428 if ($contact = self::get_contact($userid, $contactid)) {
1429 $DB->delete_records('message_contacts', ['id' => $contact->id]);
1430
1431 $event = \core\event\message_contact_removed::create(array(
1432 'objectid' => $contact->id,
1433 'userid' => $userid,
1434 'relateduserid' => $contactid,
1435 'context' => \context_user::instance($userid)
1436 ));
1437 $event->add_record_snapshot('message_contacts', $contact);
1438 $event->trigger();
1439 }
1440 }
1441
1442 /**
1443 * Handles blocking a user.
1444 *
1445 * @param int $userid The id of the user who is blocking
1446 * @param int $usertoblockid The id of the user being blocked
1447 */
1448 public static function block_user(int $userid, int $usertoblockid) {
1449 global $DB;
1450
1451 $blocked = new \stdClass();
1452 $blocked->userid = $userid;
1453 $blocked->blockeduserid = $usertoblockid;
1454 $blocked->timecreated = time();
1455 $blocked->id = $DB->insert_record('message_users_blocked', $blocked);
1456
1457 // Trigger event for blocking a contact.
1458 $event = \core\event\message_user_blocked::create(array(
1459 'objectid' => $blocked->id,
1460 'userid' => $userid,
1461 'relateduserid' => $usertoblockid,
1462 'context' => \context_user::instance($userid)
1463 ));
1464 $event->add_record_snapshot('message_users_blocked', $blocked);
1465 $event->trigger();
1466 }
1467
1468 /**
1469 * Handles unblocking a user.
1470 *
1471 * @param int $userid The id of the user who is unblocking
1472 * @param int $usertounblockid The id of the user being unblocked
1473 */
1474 public static function unblock_user(int $userid, int $usertounblockid) {
1475 global $DB;
1476
1477 if ($blockeduser = $DB->get_record('message_users_blocked',
1478 ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
1479 $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);
1480
1481 // Trigger event for unblocking a contact.
1482 $event = \core\event\message_user_unblocked::create(array(
1483 'objectid' => $blockeduser->id,
1484 'userid' => $userid,
1485 'relateduserid' => $usertounblockid,
1486 'context' => \context_user::instance($userid)
1487 ));
1488 $event->add_record_snapshot('message_users_blocked', $blockeduser);
1489 $event->trigger();
1490 }
1491 }
1492
1493 /**
1494 * Checks if users are already contacts.
1495 *
1496 * @param int $userid The id of one of the users
1497 * @param int $contactid The id of the other user
1498 * @return bool Returns true if they are a contact, false otherwise
1499 */
1500 public static function is_contact(int $userid, int $contactid) : bool {
1501 global $DB;
1502
1503 $sql = "SELECT id
1504 FROM {message_contacts} mc
1505 WHERE (mc.userid = ? AND mc.contactid = ?)
1506 OR (mc.userid = ? AND mc.contactid = ?)";
1507 return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
1508 }
1509
1510 /**
1511 * Returns the row in the database table message_contacts that represents the contact between two people.
1512 *
1513 * @param int $userid The id of one of the users
1514 * @param int $contactid The id of the other user
1515 * @return mixed A fieldset object containing the record, false otherwise
1516 */
1517 public static function get_contact(int $userid, int $contactid) {
1518 global $DB;
1519
1520 $sql = "SELECT mc.*
1521 FROM {message_contacts} mc
1522 WHERE (mc.userid = ? AND mc.contactid = ?)
1523 OR (mc.userid = ? AND mc.contactid = ?)";
1524 return $DB->get_record_sql($sql, [$userid, $contactid, $contactid, $userid]);
1525 }
1526
1527 /**
1528 * Checks if a user is already blocked.
1529 *
1530 * This is different than self::is_user_blocked() as it does not check any capabilities.
1531 * It simply checks if an entry exists in the DB.
1532 *
1533 * @param int $userid
1534 * @param int $blockeduserid
1535 * @return bool Returns true if they are a blocked, false otherwise
1536 */
1537 public static function is_blocked(int $userid, int $blockeduserid) : bool {
1538 global $DB;
1539
1540 return $DB->record_exists('message_users_blocked', ['userid' => $userid, 'blockeduserid' => $blockeduserid]);
1541 }
1542
1543 /**
1544 * Checks if a contact request already exists between users.
1545 *
1546 * @param int $userid The id of the user who is creating the contact request
1547 * @param int $requesteduserid The id of the user being requested
1548 * @return bool Returns true if a contact request exists, false otherwise
1549 */
1550 public static function does_contact_request_exist(int $userid, int $requesteduserid) : bool {
1551 global $DB;
1552
1553 $sql = "SELECT id
1554 FROM {message_contact_requests} mcr
1555 WHERE (mcr.userid = ? AND mcr.requesteduserid = ?)
1556 OR (mcr.userid = ? AND mcr.requesteduserid = ?)";
1557 return $DB->record_exists_sql($sql, [$userid, $requesteduserid, $requesteduserid, $userid]);
1558 }
879e2bef 1559}