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