weekly release 3.4dev
[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
cd03b8d7
MN
39 /**
40 * Handles searching for messages in the message area.
41 *
42 * @param int $userid The user id doing the searching
43 * @param string $search The string the user is searching
44 * @param int $limitfrom
45 * @param int $limitnum
de55cb1b 46 * @return array
cd03b8d7
MN
47 */
48 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
49 global $DB;
50
51 // Get the user fields we want.
52 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
53 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
54
55 // Get all the messages for the user.
56 $sql = "SELECT m.id, m.useridfrom, m.useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
dd0c1403
MN
57 m.smallmessage, m.notification, m.timecreated, 0 as isread, $ufields, mc.blocked as userfrom_blocked,
58 $ufields2, mc2.blocked as userto_blocked
cd03b8d7
MN
59 FROM {message} m
60 JOIN {user} u
61 ON m.useridfrom = u.id
dd0c1403
MN
62 LEFT JOIN {message_contacts} mc
63 ON (mc.contactid = u.id AND mc.userid = ?)
cd03b8d7
MN
64 JOIN {user} u2
65 ON m.useridto = u2.id
dd0c1403 66 LEFT JOIN {message_contacts} mc2
7b55aaa1 67 ON (mc2.contactid = u2.id AND mc2.userid = ?)
cd03b8d7
MN
68 WHERE ((useridto = ? AND timeusertodeleted = 0)
69 OR (useridfrom = ? AND timeuserfromdeleted = 0))
70 AND notification = 0
71 AND u.deleted = 0
72 AND u2.deleted = 0
73 AND " . $DB->sql_like('smallmessage', '?', false) . "
74 UNION ALL
75 SELECT mr.id, mr.useridfrom, mr.useridto, mr.subject, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat,
dd0c1403
MN
76 mr.smallmessage, mr.notification, mr.timecreated, 1 as isread, $ufields, mc.blocked as userfrom_blocked,
77 $ufields2, mc2.blocked as userto_blocked
cd03b8d7
MN
78 FROM {message_read} mr
79 JOIN {user} u
80 ON mr.useridfrom = u.id
dd0c1403 81 LEFT JOIN {message_contacts} mc
7b55aaa1 82 ON (mc.contactid = u.id AND mc.userid = ?)
cd03b8d7
MN
83 JOIN {user} u2
84 ON mr.useridto = u2.id
dd0c1403
MN
85 LEFT JOIN {message_contacts} mc2
86 ON (mc2.contactid = u2.id AND mc2.userid = ?)
cd03b8d7
MN
87 WHERE ((useridto = ? AND timeusertodeleted = 0)
88 OR (useridfrom = ? AND timeuserfromdeleted = 0))
89 AND notification = 0
90 AND u.deleted = 0
91 AND u2.deleted = 0
92 AND " . $DB->sql_like('smallmessage', '?', false) . "
93 ORDER BY timecreated DESC";
dd0c1403
MN
94 $params = array($userid, $userid, $userid, $userid, '%' . $search . '%',
95 $userid, $userid, $userid, $userid, '%' . $search . '%');
cd03b8d7
MN
96
97 // Convert the messages into searchable contacts with their last message being the message that was searched.
de55cb1b 98 $conversations = array();
cd03b8d7
MN
99 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
100 foreach ($messages as $message) {
101 $prefix = 'userfrom_';
102 if ($userid == $message->useridfrom) {
103 $prefix = 'userto_';
104 // If it from the user, then mark it as read, even if it wasn't by the receiver.
105 $message->isread = true;
106 }
dd0c1403
MN
107 $blockedcol = $prefix . 'blocked';
108 $message->blocked = $message->$blockedcol;
109
cd03b8d7 110 $message->messageid = $message->id;
de55cb1b 111 $conversations[] = helper::create_contact($message, $prefix);
cd03b8d7
MN
112 }
113 }
114
de55cb1b 115 return $conversations;
cd03b8d7
MN
116 }
117
118 /**
48e8bdba 119 * Handles searching for user in a particular course in the message area.
cd03b8d7
MN
120 *
121 * @param int $userid The user id doing the searching
122 * @param int $courseid The id of the course we are searching in
123 * @param string $search The string the user is searching
124 * @param int $limitfrom
125 * @param int $limitnum
de55cb1b 126 * @return array
cd03b8d7 127 */
48e8bdba 128 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
129 global $DB;
130
131 // Get all the users in the course.
132 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
dd0c1403 133 $sql = "SELECT u.*, mc.blocked
cd03b8d7 134 FROM {user} u
dd0c1403
MN
135 JOIN ($esql) je
136 ON je.id = u.id
137 LEFT JOIN {message_contacts} mc
138 ON (mc.contactid = u.id AND mc.userid = :userid)
cd03b8d7
MN
139 WHERE u.deleted = 0";
140 // Add more conditions.
141 $fullname = $DB->sql_fullname();
dd0c1403 142 $sql .= " AND u.id != :userid2
cd03b8d7
MN
143 AND " . $DB->sql_like($fullname, ':search', false) . "
144 ORDER BY " . $DB->sql_fullname();
dd0c1403 145 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 146
cd03b8d7
MN
147 // Convert all the user records into contacts.
148 $contacts = array();
149 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
150 foreach ($users as $user) {
de55cb1b 151 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
152 }
153 }
154
de55cb1b 155 return $contacts;
cd03b8d7
MN
156 }
157
158 /**
48e8bdba 159 * Handles searching for user in the message area.
cd03b8d7
MN
160 *
161 * @param int $userid The user id doing the searching
162 * @param string $search The string the user is searching
163 * @param int $limitnum
de55cb1b 164 * @return array
cd03b8d7 165 */
48e8bdba 166 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
167 global $CFG, $DB;
168
169 require_once($CFG->dirroot . '/lib/coursecatlib.php');
170
171 // Used to search for contacts.
172 $fullname = $DB->sql_fullname();
173 $ufields = \user_picture::fields('u', array('lastaccess'));
174
175 // Users not to include.
176 $excludeusers = array($userid, $CFG->siteguest);
177 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
178
179 // Ok, let's search for contacts first.
180 $contacts = array();
dd0c1403 181 $sql = "SELECT $ufields, mc.blocked
cd03b8d7
MN
182 FROM {user} u
183 JOIN {message_contacts} mc
184 ON u.id = mc.contactid
185 WHERE mc.userid = :userid
186 AND u.deleted = 0
187 AND u.confirmed = 1
188 AND " . $DB->sql_like($fullname, ':search', false) . "
189 AND u.id $exclude
190 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
191 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
192 0, $limitnum)) {
cd03b8d7 193 foreach ($users as $user) {
de55cb1b 194 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
195 }
196 }
197
198 // Now, let's get the courses.
f3249577
AG
199 // Make sure to limit searches to enrolled courses.
200 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 201 $courses = array();
f3249577
AG
202 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum),
203 array('moodle/course:viewparticipants'))) {
cd03b8d7 204 foreach ($arrcourses as $course) {
f3249577
AG
205 if (isset($enrolledcourses[$course->id])) {
206 $data = new \stdClass();
207 $data->id = $course->id;
208 $data->shortname = $course->shortname;
209 $data->fullname = $course->fullname;
210 $courses[] = $data;
211 }
cd03b8d7
MN
212 }
213 }
214
215 // Let's get those non-contacts. Toast them gears boi.
dd0c1403
MN
216 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
217 // extra detail from the database.
cd03b8d7
MN
218 $noncontacts = array();
219 $sql = "SELECT $ufields
220 FROM {user} u
221 WHERE u.deleted = 0
222 AND u.confirmed = 1
223 AND " . $DB->sql_like($fullname, ':search', false) . "
224 AND u.id $exclude
7b55aaa1
MN
225 AND u.id NOT IN (SELECT contactid
226 FROM {message_contacts}
cd03b8d7
MN
227 WHERE userid = :userid)
228 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
229 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
230 0, $limitnum)) {
cd03b8d7 231 foreach ($users as $user) {
de55cb1b 232 $noncontacts[] = helper::create_contact($user);
cd03b8d7
MN
233 }
234 }
235
de55cb1b 236 return array($contacts, $courses, $noncontacts);
cd03b8d7
MN
237 }
238
879e2bef
MN
239 /**
240 * Returns the contacts and their conversation to display in the contacts area.
241 *
349f4261
RW
242 * ** WARNING **
243 * It is HIGHLY recommended to use a sensible limit when calling this function. Trying
244 * to retrieve too much information in a single call will cause performance problems.
245 * ** WARNING **
246 *
247 * This function has specifically been altered to break each of the data sets it
248 * requires into separate database calls. This is to avoid the performance problems
249 * observed when attempting to join large data sets (e.g. the message tables and
250 * the user table).
251 *
252 * While it is possible to gather the data in a single query, and it may even be
253 * more efficient with a correctly tuned database, we have opted to trade off some of
254 * the benefits of a single query in order to ensure this function will work on
255 * most databases with default tunings and with large data sets.
256 *
879e2bef 257 * @param int $userid The user id
879e2bef
MN
258 * @param int $limitfrom
259 * @param int $limitnum
de55cb1b 260 * @return array
879e2bef 261 */
349f4261
RW
262 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
263 global $DB;
264
265 // The case statement is used to make sure the same key is generated
266 // whether a user sent or received a message (it's the same conversation).
267 // E.g. If there is a message from user 1 to user 2 and then from user 2 to user 1 the result set
268 // will group those into a single record, since 1 -> 2 and 2 -> 1 is the same conversation.
269 $case1 = $DB->sql_concat('useridfrom', "'-'", 'useridto');
270 $case2 = $DB->sql_concat('useridto', "'-'", 'useridfrom');
271 $convocase = "CASE WHEN useridfrom > useridto
272 THEN $case1
273 ELSE $case2 END";
274 $convosig = "$convocase AS convo_signature";
275
276 // This is a snippet to join the message tables and filter out any messages the user has deleted
277 // and ignore notifications. The fields are specified by name so that the union works on MySQL.
278 $allmessages = "SELECT
279 id, useridfrom, useridto, subject, fullmessage, fullmessageformat,
280 fullmessagehtml, smallmessage, notification, contexturl,
281 contexturlname, timecreated, timeuserfromdeleted, timeusertodeleted,
282 component, eventtype, 0 as timeread
283 FROM {message}
284 WHERE
285 (useridto = ? AND timeusertodeleted = 0 AND notification = 0)
286 OR
287 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)
288 UNION ALL
289 SELECT
290 id, useridfrom, useridto, subject, fullmessage, fullmessageformat,
291 fullmessagehtml, smallmessage, notification, contexturl,
292 contexturlname, timecreated, timeuserfromdeleted, timeusertodeleted,
293 component, eventtype, timeread
294 FROM {message_read}
295 WHERE
296 (useridto = ? AND timeusertodeleted = 0 AND notification = 0)
297 OR
298 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)";
299 $allmessagesparams = [$userid, $userid, $userid, $userid];
300
301 // Create a transaction to protect against concurrency issues.
302 $transaction = $DB->start_delegated_transaction();
303
304 // First we need to get the list of conversations from the database ordered by the conversation
305 // with the most recent message first.
306 //
307 // This query will join the two message tables and then group the results by the combination
308 // of useridfrom and useridto (the 'convo_signature').
309 $conversationssql = "SELECT $convosig, max(timecreated) as timecreated
310 FROM ($allmessages) x
311 GROUP BY $convocase
42e2f6c0 312 ORDER BY timecreated DESC, max(id) DESC";
349f4261
RW
313 $conversationrecords = $DB->get_records_sql($conversationssql, $allmessagesparams, $limitfrom, $limitnum);
314
315 // This user has no conversations so we can return early here.
316 if (empty($conversationrecords)) {
bb2924d0 317 $transaction->allow_commit();
349f4261
RW
318 return [];
319 }
320
321 // Next we need to get the max id of the messages sent at the latest time for each conversation.
322 // This needs to be a separate query to above because there is no guarantee that the message with
323 // the highest id will also have the highest timecreated value (in fact that is fairly likely due
324 // to the split between the message tables).
325 //
326 // E.g. if we just added max(id) to the conversation query above and ran it on data like:
327 // id, userfrom, userto, timecreated
328 // 1, 1, 2, 2
329 // 2, 2, 1, 1
330 //
331 // Then the result of the query would be:
332 // convo_signature, timecreated, id
333 // 2-1, 2, 2
334 //
335 // That would be incorrect since the message with id 2 actually has a lower timecreated. Hence why
336 // the two queries need to be split.
337 //
338 // The same result could also be achieved with an inner join in a single query however we're specifically
339 // avoiding multiple joins in the messaging queries because of the size of the messaging tables.
340 $whereclauses = [];
341 $createdtimes = [];
342 foreach ($conversationrecords as $convoid => $record) {
343 $whereclauses[] = "($convocase = '$convoid' AND timecreated = {$record->timecreated})";
344 $createdtimes[] = $record->timecreated;
345 }
346 $messageidwhere = implode(' OR ', $whereclauses);
347 list($timecreatedsql, $timecreatedparams) = $DB->get_in_or_equal($createdtimes);
348
349 $allmessagestimecreated = "SELECT id, useridfrom, useridto, timecreated
350 FROM {message}
351 WHERE
352 (useridto = ? AND timeusertodeleted = 0 AND notification = 0)
353 OR
354 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)
355 AND timecreated $timecreatedsql
356 UNION ALL
357 SELECT id, useridfrom, useridto, timecreated
358 FROM {message_read}
359 WHERE
360 (useridto = ? AND timeusertodeleted = 0 AND notification = 0)
361 OR
362 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)
363 AND timecreated $timecreatedsql";
42e2f6c0 364 $messageidsql = "SELECT $convosig, max(id) as id, timecreated
349f4261
RW
365 FROM ($allmessagestimecreated) x
366 WHERE $messageidwhere
367 GROUP BY $convocase, timecreated";
368 $messageidparams = array_merge([$userid, $userid], $timecreatedparams, [$userid, $userid], $timecreatedparams);
42e2f6c0 369 $messageidrecords = $DB->get_records_sql($messageidsql, $messageidparams);
349f4261
RW
370
371 // Ok, let's recap. We've pulled a descending ordered list of conversations by latest time created
372 // for the given user. For each of those conversations we've grabbed the max id for messages
373 // created at that time.
374 //
375 // So at this point we have the list of ids for the most recent message in each of the user's most
376 // recent conversations. Now we need to pull all of the message and user data for each message id.
42e2f6c0
RW
377 $whereclauses = [];
378 foreach ($messageidrecords as $record) {
c9b82e40 379 $whereclauses[] = "(id = {$record->id} AND timecreated = {$record->timecreated})";
42e2f6c0
RW
380 }
381 $messagewhere = implode(' OR ', $whereclauses);
c9b82e40
RW
382 $messagesunionsql = "SELECT
383 id, useridfrom, useridto, smallmessage, 0 as timeread
384 FROM {message}
385 WHERE
386 {$messagewhere}
387 UNION ALL
388 SELECT
389 id, useridfrom, useridto, smallmessage, timeread
390 FROM {message_read}
391 WHERE
392 {$messagewhere}";
349f4261 393 $messagesql = "SELECT $convosig, m.smallmessage, m.id, m.useridto, m.useridfrom, m.timeread
c9b82e40 394 FROM ($messagesunionsql) m";
349f4261
RW
395
396 // We need to handle the case where the $messageids contains two ids from the same conversation
397 // (which can happen because there can be id clashes between the read and unread tables). In
398 // this case we will prioritise the unread message.
42e2f6c0 399 $messageset = $DB->get_recordset_sql($messagesql, $allmessagesparams);
349f4261
RW
400 $messages = [];
401 foreach ($messageset as $message) {
402 $id = $message->convo_signature;
403 if (!isset($messages[$id]) || empty($message->timeread)) {
404 $messages[$id] = $message;
405 }
406 }
407 $messageset->close();
408
409 // We need to pull out the list of other users that are part of each of these conversations. This
410 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
411 // tables because on large sites these tables are massive which results in extremely slow
412 // performance (typically due to join buffer exhaustion).
413 $otheruserids = array_map(function($message) use ($userid) {
414 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
415 }, array_values($messages));
416
417 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
418 $userfields = \user_picture::fields('', array('lastaccess'));
419 $userssql = "SELECT $userfields
420 FROM {user}
f512355b
MN
421 WHERE id $useridsql
422 AND deleted = 0";
349f4261
RW
423 $otherusers = $DB->get_records_sql($userssql, $usersparams);
424
425 // Similar to the above use case, we need to pull the contact information and again this has
426 // specifically been separated into another query to avoid having to do joins on the message
427 // tables.
428 $contactssql = "SELECT contactid, blocked
429 FROM {message_contacts}
430 WHERE userid = ? AND contactid $useridsql";
431 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $otheruserids));
432
433 // Finally, let's get the unread messages count for this user so that we can add them
434 // to the conversation.
435 $unreadcountssql = 'SELECT useridfrom, count(*) as count
436 FROM {message}
437 WHERE useridto = ?
438 AND timeusertodeleted = 0
439 AND notification = 0
440 GROUP BY useridfrom';
441 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid]);
442
443 // We can close off the transaction now.
0c44da78 444 $transaction->allow_commit();
349f4261
RW
445
446 // Now we need to order the messages back into the same order of the conversations.
447 $orderedconvosigs = array_keys($conversationrecords);
448 usort($messages, function($a, $b) use ($orderedconvosigs) {
449 $aindex = array_search($a->convo_signature, $orderedconvosigs);
450 $bindex = array_search($b->convo_signature, $orderedconvosigs);
451
452 return ($aindex < $bindex) ? -1 : 1;
453 });
454
455 // Preload the contexts before we construct the conversation to prevent the
456 // create_contact helper from needing to query the DB so often.
457 $ctxselect = \context_helper::get_preload_record_columns_sql('ctx');
458 $sql = "SELECT {$ctxselect}
459 FROM {context} ctx
460 WHERE ctx.contextlevel = ? AND
461 ctx.instanceid {$useridsql}";
462 $contexts = [];
463 $contexts = $DB->get_records_sql($sql, array_merge([CONTEXT_USER], $usersparams));
464 foreach ($contexts as $context) {
465 \context_helper::preload_from_record($context);
466 }
467
468 $userproperties = explode(',', $userfields);
de55cb1b 469 $arrconversations = array();
349f4261
RW
470 // The last step now is to bring all of the data we've gathered together to create
471 // a conversation (or contact, as the API is named...).
472 foreach ($messages as $message) {
473 $conversation = new \stdClass();
474 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
475 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
476 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
477
478 // Add the other user's information to the conversation, if we have one.
479 foreach ($userproperties as $prop) {
480 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
481 }
482
f512355b
MN
483 // Do not process a conversation with a deleted user.
484 if (empty($conversation->id)) {
485 continue;
486 }
487
349f4261
RW
488 // Add the contact's information, if we have one.
489 $conversation->blocked = ($contact) ? $contact->blocked : null;
490
491 // Add the message information.
492 $conversation->messageid = $message->id;
493 $conversation->smallmessage = $message->smallmessage;
494 $conversation->useridfrom = $message->useridfrom;
495
496 // Only consider it unread if $user has unread messages.
497 if (isset($unreadcounts[$otheruserid])) {
498 $conversation->isread = false;
499 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
500 } else {
501 $conversation->isread = true;
879e2bef 502 }
349f4261 503
42e2f6c0 504 $arrconversations[$otheruserid] = helper::create_contact($conversation);
879e2bef
MN
505 }
506
de55cb1b 507 return $arrconversations;
879e2bef
MN
508 }
509
510 /**
511 * Returns the contacts to display in the contacts area.
512 *
513 * @param int $userid The user id
514 * @param int $limitfrom
515 * @param int $limitnum
de55cb1b 516 * @return array
879e2bef
MN
517 */
518 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
519 global $DB;
520
521 $arrcontacts = array();
dd0c1403 522 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
523 FROM {message_contacts} mc
524 JOIN {user} u
525 ON mc.contactid = u.id
526 WHERE mc.userid = :userid
527 AND u.deleted = 0
528 ORDER BY " . $DB->sql_fullname();
529 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
530 foreach ($contacts as $contact) {
de55cb1b 531 $arrcontacts[] = helper::create_contact($contact);
879e2bef
MN
532 }
533 }
534
de55cb1b 535 return $arrcontacts;
879e2bef
MN
536 }
537
538 /**
539 * Returns the messages to display in the message area.
540 *
541 * @param int $userid the current user
542 * @param int $otheruserid the other user
543 * @param int $limitfrom
544 * @param int $limitnum
8ec78c48 545 * @param string $sort
ffd7798c
MN
546 * @param int $timefrom the time from the message being sent
547 * @param int $timeto the time up until the message being sent
de55cb1b 548 * @return array
879e2bef 549 */
fb1469d8 550 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 551 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 552
ffd7798c 553 if (!empty($timefrom)) {
fb1469d8 554 // Check the cache to see if we even need to do a DB query.
ffd7798c
MN
555 $cache = \cache::make('core', 'message_time_last_message_between_users');
556 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
fb1469d8
RW
557 $lastcreated = $cache->get($key);
558
559 // The last known message time is earlier than the one being requested so we can
560 // just return an empty result set rather than having to query the DB.
ffd7798c 561 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
562 return [];
563 }
564 }
565
879e2bef 566 $arrmessages = array();
fb1469d8 567 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 568 $sort, $timefrom, $timeto)) {
fb1469d8 569
de55cb1b 570 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
571 }
572
de55cb1b 573 return $arrmessages;
879e2bef 574 }
c060cd49
MN
575
576 /**
577 * Returns the most recent message between two users.
578 *
579 * @param int $userid the current user
580 * @param int $otheruserid the other user
de55cb1b 581 * @return \stdClass|null
c060cd49
MN
582 */
583 public static function get_most_recent_message($userid, $otheruserid) {
584 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 585 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
586 // Swap the order so we now have them in historical order.
587 $messages = array_reverse($messages);
de55cb1b 588 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
589 return array_pop($arrmessages);
590 }
591
592 return null;
593 }
c6e97f54
MN
594
595 /**
596 * Returns the profile information for a contact for a user.
597 *
598 * @param int $userid The user id
599 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 600 * @return \stdClass
c6e97f54
MN
601 */
602 public static function get_profile($userid, $otheruserid) {
f4c39cb9 603 global $CFG, $DB, $PAGE;
c6e97f54
MN
604
605 require_once($CFG->dirroot . '/user/lib.php');
606
f4c39cb9
MN
607 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
608
609 // Create the data we are going to pass to the renderable.
610 $data = new \stdClass();
611 $data->userid = $otheruserid;
612 $data->fullname = fullname($user);
613 $data->city = '';
614 $data->country = '';
615 $data->email = '';
cb805753 616 $data->isonline = null;
f4c39cb9
MN
617 // Get the user picture data - messaging has always shown these to the user.
618 $userpicture = new \user_picture($user);
619 $userpicture->size = 1; // Size f1.
620 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
621 $userpicture->size = 0; // Size f2.
622 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
623
624 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
625 if ($userfields) {
626 if (isset($userfields['city'])) {
627 $data->city = $userfields['city'];
628 }
629 if (isset($userfields['country'])) {
630 $data->country = $userfields['country'];
bf58081d 631 }
f4c39cb9
MN
632 if (isset($userfields['email'])) {
633 $data->email = $userfields['email'];
c6e97f54 634 }
f4c39cb9
MN
635 if (isset($userfields['lastaccess'])) {
636 $data->isonline = helper::is_online($userfields['lastaccess']);
637 }
638 }
c6e97f54 639
f4c39cb9
MN
640 // Check if the contact has been blocked.
641 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
642 if ($contact) {
643 $data->isblocked = (bool) $contact->blocked;
644 $data->iscontact = true;
645 } else {
646 $data->isblocked = false;
647 $data->iscontact = false;
c6e97f54 648 }
f4c39cb9
MN
649
650 return $data;
c6e97f54 651 }
dec0cd99
MN
652
653 /**
654 * Checks if a user can delete messages they have either received or sent.
655 *
656 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
657 * but will still seem as if it was by the user)
1f64514d 658 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99
MN
659 */
660 public static function can_delete_conversation($userid) {
661 global $USER;
662
663 $systemcontext = \context_system::instance();
664
1f64514d 665 // Let's check if the user is allowed to delete this conversation.
dec0cd99
MN
666 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
667 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
668 $USER->id == $userid))) {
669 return true;
670 }
671
672 return false;
673 }
674
675 /**
676 * Deletes a conversation.
677 *
678 * This function does not verify any permissions.
679 *
680 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
681 * but will still seem as if it was by the user)
682 * @param int $otheruserid The id of the other user in the conversation
683 * @return bool
684 */
685 public static function delete_conversation($userid, $otheruserid) {
1f64514d 686 global $DB;
dec0cd99
MN
687
688 // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
689 // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
690 // This won't be a particularly heavily used function (at least I hope not), so let's hope MDL-36941 gets worked on
691 // soon for the sake of any developers' sanity when dealing with the messaging system.
692 $now = time();
693 $sql = "UPDATE {message}
694 SET timeuserfromdeleted = :time
695 WHERE useridfrom = :userid
696 AND useridto = :otheruserid
697 AND notification = 0";
698 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
699
700 $sql = "UPDATE {message}
701 SET timeusertodeleted = :time
702 WHERE useridto = :userid
703 AND useridfrom = :otheruserid
704 AND notification = 0";
705 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
706
707 $sql = "UPDATE {message_read}
708 SET timeuserfromdeleted = :time
709 WHERE useridfrom = :userid
710 AND useridto = :otheruserid
711 AND notification = 0";
712 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
713
714 $sql = "UPDATE {message_read}
715 SET timeusertodeleted = :time
716 WHERE useridto = :userid
717 AND useridfrom = :otheruserid
718 AND notification = 0";
719 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
720
721 // Now we need to trigger events for these.
de55cb1b 722 if ($messages = helper::get_messages($userid, $otheruserid, $now)) {
dec0cd99
MN
723 // Loop through and trigger a deleted event.
724 foreach ($messages as $message) {
725 $messagetable = 'message';
726 if (!empty($message->timeread)) {
727 $messagetable = 'message_read';
728 }
729
730 // Trigger event for deleting the message.
731 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1f64514d 732 $userid, $messagetable, $message->id)->trigger();
dec0cd99
MN
733 }
734 }
735
736 return true;
737 }
79f6c36c
MN
738
739 /**
740 * Returns the count of unread conversations (collection of messages from a single user) for
741 * the given user.
742 *
743 * @param \stdClass $user the user who's conversations should be counted
744 * @return int the count of the user's unread conversations
745 */
746 public static function count_unread_conversations($user = null) {
747 global $USER, $DB;
748
749 if (empty($user)) {
750 $user = $USER;
751 }
752
753 return $DB->count_records_select(
754 'message',
755 'useridto = ? AND timeusertodeleted = 0 AND notification = 0',
756 [$user->id],
757 "COUNT(DISTINCT(useridfrom))");
758 }
759
760 /**
761 * Marks ALL messages being sent from $fromuserid to $touserid as read.
762 *
763 * Can be filtered by type.
764 *
765 * @param int $touserid the id of the message recipient
766 * @param int $fromuserid the id of the message sender
767 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
768 * @return void
769 */
770 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
771 global $DB;
772
773 $params = array();
774
775 if (!empty($touserid)) {
776 $params['useridto'] = $touserid;
777 }
778
779 if (!empty($fromuserid)) {
780 $params['useridfrom'] = $fromuserid;
781 }
782
783 if (!empty($type)) {
784 if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) {
785 $params['notification'] = 1;
786 } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) {
787 $params['notification'] = 0;
788 }
789 }
790
dff7c82e 791 $messages = $DB->get_recordset('message', $params);
79f6c36c
MN
792
793 foreach ($messages as $message) {
794 message_mark_message_read($message, time());
795 }
796
797 $messages->close();
798 }
799
79f6c36c
MN
800 /**
801 * Returns message preferences.
802 *
803 * @param array $processors
804 * @param array $providers
805 * @param \stdClass $user
806 * @return \stdClass
807 * @since 3.2
808 */
809 public static function get_all_message_preferences($processors, $providers, $user) {
810 $preferences = helper::get_providers_preferences($providers, $user->id);
811 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
812
813 // For every processors put its options on the form (need to get function from processor's lib.php).
814 foreach ($processors as $processor) {
815 $processor->object->load_data($preferences, $user->id);
816 }
817
818 // Load general messaging preferences.
819 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
820 $preferences->mailformat = $user->mailformat;
821 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
822
823 return $preferences;
824 }
5b0769db
MN
825
826 /**
827 * Count the number of users blocked by a user.
828 *
829 * @param \stdClass $user The user object
830 * @return int the number of blocked users
831 */
832 public static function count_blocked_users($user = null) {
833 global $USER, $DB;
834
835 if (empty($user)) {
836 $user = $USER;
837 }
838
839 $sql = "SELECT count(mc.id)
840 FROM {message_contacts} mc
841 WHERE mc.userid = :userid AND mc.blocked = 1";
842 return $DB->count_records_sql($sql, array('userid' => $user->id));
843 }
844
845 /**
846 * Determines if a user is permitted to send another user a private message.
847 * If no sender is provided then it defaults to the logged in user.
848 *
849 * @param \stdClass $recipient The user object.
850 * @param \stdClass|null $sender The user object.
851 * @return bool true if user is permitted, false otherwise.
852 */
853 public static function can_post_message($recipient, $sender = null) {
854 global $USER;
855
856 if (is_null($sender)) {
857 // The message is from the logged in user, unless otherwise specified.
858 $sender = $USER;
859 }
860
861 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
862 return false;
863 }
864
865 // The recipient blocks messages from non-contacts and the
866 // sender isn't a contact.
867 if (self::is_user_non_contact_blocked($recipient, $sender)) {
868 return false;
869 }
870
26dca05d
JP
871 $senderid = null;
872 if ($sender !== null && isset($sender->id)) {
873 $senderid = $sender->id;
874 }
5b0769db 875 // The recipient has specifically blocked this sender.
26dca05d 876 if (self::is_user_blocked($recipient->id, $senderid)) {
5b0769db
MN
877 return false;
878 }
879
880 return true;
881 }
882
883 /**
884 * Checks if the recipient is allowing messages from users that aren't a
885 * contact. If not then it checks to make sure the sender is in the
886 * recipient's contacts.
887 *
888 * @param \stdClass $recipient The user object.
889 * @param \stdClass|null $sender The user object.
890 * @return bool true if $sender is blocked, false otherwise.
891 */
892 public static function is_user_non_contact_blocked($recipient, $sender = null) {
893 global $USER, $DB;
894
895 if (is_null($sender)) {
896 // The message is from the logged in user, unless otherwise specified.
897 $sender = $USER;
898 }
899
900 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
901 if (!empty($blockednoncontacts)) {
902 // Confirm the sender is a contact of the recipient.
903 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
904 if ($exists) {
905 // All good, the recipient is a contact of the sender.
906 return false;
907 } else {
908 // Oh no, the recipient is not a contact. Looks like we can't send the message.
909 return true;
910 }
911 }
912
913 return false;
914 }
915
916 /**
917 * Checks if the recipient has specifically blocked the sending user.
918 *
919 * Note: This function will always return false if the sender has the
920 * readallmessages capability at the system context level.
921 *
26dca05d
JP
922 * @param int $recipientid User ID of the recipient.
923 * @param int $senderid User ID of the sender.
5b0769db
MN
924 * @return bool true if $sender is blocked, false otherwise.
925 */
26dca05d 926 public static function is_user_blocked($recipientid, $senderid = null) {
5b0769db
MN
927 global $USER, $DB;
928
26dca05d 929 if (is_null($senderid)) {
5b0769db 930 // The message is from the logged in user, unless otherwise specified.
26dca05d 931 $senderid = $USER->id;
5b0769db
MN
932 }
933
934 $systemcontext = \context_system::instance();
26dca05d 935 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
936 return false;
937 }
938
26dca05d
JP
939 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
940 return true;
5b0769db
MN
941 }
942
943 return false;
944 }
20ab51fd
AA
945
946 /**
947 * Get specified message processor, validate corresponding plugin existence and
948 * system configuration.
949 *
950 * @param string $name Name of the processor.
951 * @param bool $ready only return ready-to-use processors.
952 * @return mixed $processor if processor present else empty array.
953 * @since Moodle 3.2
954 */
955 public static function get_message_processor($name, $ready = false) {
956 global $DB, $CFG;
957
958 $processor = $DB->get_record('message_processors', array('name' => $name));
959 if (empty($processor)) {
960 // Processor not found, return.
961 return array();
962 }
963
964 $processor = self::get_processed_processor_object($processor);
965 if ($ready) {
966 if ($processor->enabled && $processor->configured) {
967 return $processor;
968 } else {
969 return array();
970 }
971 } else {
972 return $processor;
973 }
974 }
975
976 /**
977 * Returns weather a given processor is enabled or not.
978 * Note:- This doesn't check if the processor is configured or not.
979 *
980 * @param string $name Name of the processor
981 * @return bool
982 */
983 public static function is_processor_enabled($name) {
984
985 $cache = \cache::make('core', 'message_processors_enabled');
986 $status = $cache->get($name);
987
988 if ($status === false) {
989 $processor = self::get_message_processor($name);
990 if (!empty($processor)) {
991 $cache->set($name, $processor->enabled);
992 return $processor->enabled;
993 } else {
994 return false;
995 }
996 }
997
998 return $status;
999 }
1000
1001 /**
1002 * Set status of a processor.
1003 *
1004 * @param \stdClass $processor processor record.
1005 * @param 0|1 $enabled 0 or 1 to set the processor status.
1006 * @return bool
1007 * @since Moodle 3.2
1008 */
1009 public static function update_processor_status($processor, $enabled) {
1010 global $DB;
1011 $cache = \cache::make('core', 'message_processors_enabled');
1012 $cache->delete($processor->name);
1013 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
1014 }
1015
1016 /**
1017 * Given a processor object, loads information about it's settings and configurations.
1018 * This is not a public api, instead use @see \core_message\api::get_message_processor()
1019 * or @see \get_message_processors()
1020 *
1021 * @param \stdClass $processor processor object
1022 * @return \stdClass processed processor object
1023 * @since Moodle 3.2
1024 */
1025 public static function get_processed_processor_object(\stdClass $processor) {
1026 global $CFG;
1027
1028 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
1029 if (is_readable($processorfile)) {
1030 include_once($processorfile);
1031 $processclass = 'message_output_' . $processor->name;
1032 if (class_exists($processclass)) {
1033 $pclass = new $processclass();
1034 $processor->object = $pclass;
1035 $processor->configured = 0;
1036 if ($pclass->is_system_configured()) {
1037 $processor->configured = 1;
1038 }
1039 $processor->hassettings = 0;
1040 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1041 $processor->hassettings = 1;
1042 }
1043 $processor->available = 1;
1044 } else {
1045 print_error('errorcallingprocessor', 'message');
1046 }
1047 } else {
1048 $processor->available = 0;
1049 }
1050 return $processor;
1051 }
879e2bef 1052}