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