Merge branch 'MDL-60364' of https://github.com/NeillM/moodle
[moodle.git] / message / classes / api.php
blob206552921262a99127b390b68278c4a5133ed226
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.
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/>.
17 /**
18 * Contains class used to return information to display for the message area.
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
25 namespace core_message;
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/lib/messagelib.php');
31 /**
32 * Class used to return information to display for the message area.
34 * @copyright 2016 Mark Nelson <markn@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class api {
39 /**
40 * Handles searching for messages in the message area.
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
46 * @return array
48 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
49 global $DB;
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_');
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,
57 m.smallmessage, m.notification, m.timecreated, 0 as isread, $ufields, mc.blocked as userfrom_blocked,
58 $ufields2, mc2.blocked as userto_blocked
59 FROM {message} m
60 JOIN {user} u
61 ON m.useridfrom = u.id
62 LEFT JOIN {message_contacts} mc
63 ON (mc.contactid = u.id AND mc.userid = ?)
64 JOIN {user} u2
65 ON m.useridto = u2.id
66 LEFT JOIN {message_contacts} mc2
67 ON (mc2.contactid = u2.id AND mc2.userid = ?)
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,
76 mr.smallmessage, mr.notification, mr.timecreated, 1 as isread, $ufields, mc.blocked as userfrom_blocked,
77 $ufields2, mc2.blocked as userto_blocked
78 FROM {message_read} mr
79 JOIN {user} u
80 ON mr.useridfrom = u.id
81 LEFT JOIN {message_contacts} mc
82 ON (mc.contactid = u.id AND mc.userid = ?)
83 JOIN {user} u2
84 ON mr.useridto = u2.id
85 LEFT JOIN {message_contacts} mc2
86 ON (mc2.contactid = u2.id AND mc2.userid = ?)
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";
94 $params = array($userid, $userid, $userid, $userid, '%' . $search . '%',
95 $userid, $userid, $userid, $userid, '%' . $search . '%');
97 // Convert the messages into searchable contacts with their last message being the message that was searched.
98 $conversations = array();
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;
107 $blockedcol = $prefix . 'blocked';
108 $message->blocked = $message->$blockedcol;
110 $message->messageid = $message->id;
111 $conversations[] = helper::create_contact($message, $prefix);
115 return $conversations;
119 * Handles searching for user in a particular course in the message area.
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
126 * @return array
128 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
129 global $DB;
131 // Get all the users in the course.
132 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
133 $sql = "SELECT u.*, mc.blocked
134 FROM {user} u
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)
139 WHERE u.deleted = 0";
140 // Add more conditions.
141 $fullname = $DB->sql_fullname();
142 $sql .= " AND u.id != :userid2
143 AND " . $DB->sql_like($fullname, ':search', false) . "
144 ORDER BY " . $DB->sql_fullname();
145 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
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) {
151 $contacts[] = helper::create_contact($user);
155 return $contacts;
159 * Handles searching for user in the message area.
161 * @param int $userid The user id doing the searching
162 * @param string $search The string the user is searching
163 * @param int $limitnum
164 * @return array
166 public static function search_users($userid, $search, $limitnum = 0) {
167 global $CFG, $DB;
169 require_once($CFG->dirroot . '/lib/coursecatlib.php');
171 // Used to search for contacts.
172 $fullname = $DB->sql_fullname();
173 $ufields = \user_picture::fields('u', array('lastaccess'));
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);
179 // Ok, let's search for contacts first.
180 $contacts = array();
181 $sql = "SELECT $ufields, mc.blocked
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();
191 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
192 0, $limitnum)) {
193 foreach ($users as $user) {
194 $contacts[] = helper::create_contact($user);
198 // Now, let's get the courses.
199 // Make sure to limit searches to enrolled courses.
200 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
201 $courses = array();
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.
206 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum),
207 array('moodle/course:viewparticipants'))) {
208 foreach ($arrcourses as $course) {
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;
219 // Let's get those non-contacts. Toast them gears boi.
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.
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
229 AND u.id NOT IN (SELECT contactid
230 FROM {message_contacts}
231 WHERE userid = :userid)
232 ORDER BY " . $DB->sql_fullname();
233 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
234 0, $limitnum)) {
235 foreach ($users as $user) {
236 $noncontacts[] = helper::create_contact($user);
240 return array($contacts, $courses, $noncontacts);
244 * Returns the contacts and their conversation to display in the contacts area.
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 **
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).
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.
261 * @param int $userid The user id
262 * @param int $limitfrom
263 * @param int $limitnum
264 * @return array
266 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20) {
267 global $DB;
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";
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)
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
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)
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
316 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)";
317 $allmessagesparams = [$userid, $userid, $userid, $userid];
319 // Create a transaction to protect against concurrency issues.
320 $transaction = $DB->start_delegated_transaction();
322 // First we need to get the list of conversations from the database ordered by the conversation
323 // with the most recent message first.
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
330 ORDER BY timecreated DESC, max(id) DESC";
331 $conversationrecords = $DB->get_records_sql($conversationssql, $allmessagesparams, $limitfrom, $limitnum);
333 // This user has no conversations so we can return early here.
334 if (empty($conversationrecords)) {
335 $transaction->allow_commit();
336 return [];
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).
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
349 // Then the result of the query would be:
350 // convo_signature, timecreated, id
351 // 2-1, 2, 2
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.
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;
364 $messageidwhere = implode(' OR ', $whereclauses);
365 list($timecreatedsql, $timecreatedparams) = $DB->get_in_or_equal($createdtimes);
367 $allmessagestimecreated = "SELECT id, useridfrom, useridto, timecreated
368 FROM {message}
369 WHERE
370 (useridto = ? AND timeusertodeleted = 0 AND notification = 0)
371 AND timecreated $timecreatedsql
372 UNION ALL
373 SELECT id, useridfrom, useridto, timecreated
374 FROM {message}
375 WHERE
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)
383 AND timecreated $timecreatedsql
384 UNION ALL
385 SELECT id, useridfrom, useridto, timecreated
386 FROM {message_read}
387 WHERE
388 (useridfrom = ? AND timeuserfromdeleted = 0 AND notification = 0)
389 AND timecreated $timecreatedsql";
390 $messageidsql = "SELECT $convosig, max(id) as id, timecreated
391 FROM ($allmessagestimecreated) x
392 WHERE $messageidwhere
393 GROUP BY $convocase, timecreated";
394 $messageidparams = array_merge([$userid], $timecreatedparams, [$userid], $timecreatedparams,
395 [$userid], $timecreatedparams, [$userid], $timecreatedparams);
396 $messageidrecords = $DB->get_records_sql($messageidsql, $messageidparams);
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.
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.
404 $whereclauses = [];
405 foreach ($messageidrecords as $record) {
406 $whereclauses[] = "(id = {$record->id} AND timecreated = {$record->timecreated})";
408 $messagewhere = implode(' OR ', $whereclauses);
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}";
420 $messagesql = "SELECT $convosig, m.smallmessage, m.id, m.useridto, m.useridfrom, m.timeread
421 FROM ($messagesunionsql) m";
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.
426 $messageset = $DB->get_recordset_sql($messagesql, $allmessagesparams);
427 $messages = [];
428 foreach ($messageset as $message) {
429 $id = $message->convo_signature;
430 if (!isset($messages[$id]) || empty($message->timeread)) {
431 $messages[$id] = $message;
434 $messageset->close();
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));
444 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
445 $userfields = \user_picture::fields('', array('lastaccess'));
446 $userssql = "SELECT $userfields
447 FROM {user}
448 WHERE id $useridsql
449 AND deleted = 0";
450 $otherusers = $DB->get_records_sql($userssql, $usersparams);
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));
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]);
470 // We can close off the transaction now.
471 $transaction->allow_commit();
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);
479 return ($aindex < $bindex) ? -1 : 1;
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);
495 $userproperties = explode(',', $userfields);
496 $arrconversations = array();
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;
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;
510 // Do not process a conversation with a deleted user.
511 if (empty($conversation->id)) {
512 continue;
515 // Add the contact's information, if we have one.
516 $conversation->blocked = ($contact) ? $contact->blocked : null;
518 // Add the message information.
519 $conversation->messageid = $message->id;
520 $conversation->smallmessage = $message->smallmessage;
521 $conversation->useridfrom = $message->useridfrom;
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;
531 $arrconversations[$otheruserid] = helper::create_contact($conversation);
534 return $arrconversations;
538 * Returns the contacts to display in the contacts area.
540 * @param int $userid The user id
541 * @param int $limitfrom
542 * @param int $limitnum
543 * @return array
545 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
546 global $DB;
548 $arrcontacts = array();
549 $sql = "SELECT u.*, mc.blocked
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) {
558 $arrcontacts[] = helper::create_contact($contact);
562 return $arrcontacts;
566 * Returns the messages to display in the message area.
568 * @param int $userid the current user
569 * @param int $otheruserid the other user
570 * @param int $limitfrom
571 * @param int $limitnum
572 * @param string $sort
573 * @param int $timefrom the time from the message being sent
574 * @param int $timeto the time up until the message being sent
575 * @return array
577 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
578 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
580 if (!empty($timefrom)) {
581 // Check the cache to see if we even need to do a DB query.
582 $cache = \cache::make('core', 'message_time_last_message_between_users');
583 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
584 $lastcreated = $cache->get($key);
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.
588 if ($lastcreated && $lastcreated < $timefrom) {
589 return [];
593 $arrmessages = array();
594 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
595 $sort, $timefrom, $timeto)) {
597 $arrmessages = helper::create_messages($userid, $messages);
600 return $arrmessages;
604 * Returns the most recent message between two users.
606 * @param int $userid the current user
607 * @param int $otheruserid the other user
608 * @return \stdClass|null
610 public static function get_most_recent_message($userid, $otheruserid) {
611 // We want two messages here so we get an accurate 'blocktime' value.
612 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
613 // Swap the order so we now have them in historical order.
614 $messages = array_reverse($messages);
615 $arrmessages = helper::create_messages($userid, $messages);
616 return array_pop($arrmessages);
619 return null;
623 * Returns the profile information for a contact for a user.
625 * @param int $userid The user id
626 * @param int $otheruserid The id of the user whose profile we want to view.
627 * @return \stdClass
629 public static function get_profile($userid, $otheruserid) {
630 global $CFG, $DB, $PAGE;
632 require_once($CFG->dirroot . '/user/lib.php');
634 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
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 = '';
643 $data->isonline = null;
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);
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'];
656 if (isset($userfields['country'])) {
657 $data->country = $userfields['country'];
659 if (isset($userfields['email'])) {
660 $data->email = $userfields['email'];
662 if (isset($userfields['lastaccess'])) {
663 $data->isonline = helper::is_online($userfields['lastaccess']);
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;
677 return $data;
681 * Checks if a user can delete messages they have either received or sent.
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)
685 * @return bool Returns true if a user can delete the conversation, false otherwise.
687 public static function can_delete_conversation($userid) {
688 global $USER;
690 $systemcontext = \context_system::instance();
692 // Let's check if the user is allowed to delete this conversation.
693 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
694 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
695 $USER->id == $userid))) {
696 return true;
699 return false;
703 * Deletes a conversation.
705 * This function does not verify any permissions.
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
712 public static function delete_conversation($userid, $otheruserid) {
713 global $DB;
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));
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));
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));
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));
748 // Now we need to trigger events for these.
749 if ($messages = helper::get_messages($userid, $otheruserid, $now)) {
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';
757 // Trigger event for deleting the message.
758 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
759 $userid, $messagetable, $message->id)->trigger();
763 return true;
767 * Returns the count of unread conversations (collection of messages from a single user) for
768 * the given user.
770 * @param \stdClass $user the user who's conversations should be counted
771 * @return int the count of the user's unread conversations
773 public static function count_unread_conversations($user = null) {
774 global $USER, $DB;
776 if (empty($user)) {
777 $user = $USER;
780 return $DB->count_records_select(
781 'message',
782 'useridto = ? AND timeusertodeleted = 0 AND notification = 0',
783 [$user->id],
784 "COUNT(DISTINCT(useridfrom))");
788 * Marks ALL messages being sent from $fromuserid to $touserid as read.
790 * Can be filtered by type.
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
797 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
798 global $DB;
800 $params = array();
802 if (!empty($touserid)) {
803 $params['useridto'] = $touserid;
806 if (!empty($fromuserid)) {
807 $params['useridfrom'] = $fromuserid;
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;
818 $messages = $DB->get_recordset('message', $params);
820 foreach ($messages as $message) {
821 message_mark_message_read($message, time());
824 $messages->close();
828 * Returns message preferences.
830 * @param array $processors
831 * @param array $providers
832 * @param \stdClass $user
833 * @return \stdClass
834 * @since 3.2
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.
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);
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);
850 return $preferences;
854 * Count the number of users blocked by a user.
856 * @param \stdClass $user The user object
857 * @return int the number of blocked users
859 public static function count_blocked_users($user = null) {
860 global $USER, $DB;
862 if (empty($user)) {
863 $user = $USER;
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));
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.
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.
880 public static function can_post_message($recipient, $sender = null) {
881 global $USER;
883 if (is_null($sender)) {
884 // The message is from the logged in user, unless otherwise specified.
885 $sender = $USER;
888 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
889 return false;
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;
898 $senderid = null;
899 if ($sender !== null && isset($sender->id)) {
900 $senderid = $sender->id;
902 // The recipient has specifically blocked this sender.
903 if (self::is_user_blocked($recipient->id, $senderid)) {
904 return false;
907 return true;
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.
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.
919 public static function is_user_non_contact_blocked($recipient, $sender = null) {
920 global $USER, $DB;
922 if (is_null($sender)) {
923 // The message is from the logged in user, unless otherwise specified.
924 $sender = $USER;
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;
940 return false;
944 * Checks if the recipient has specifically blocked the sending user.
946 * Note: This function will always return false if the sender has the
947 * readallmessages capability at the system context level.
949 * @param int $recipientid User ID of the recipient.
950 * @param int $senderid User ID of the sender.
951 * @return bool true if $sender is blocked, false otherwise.
953 public static function is_user_blocked($recipientid, $senderid = null) {
954 global $USER, $DB;
956 if (is_null($senderid)) {
957 // The message is from the logged in user, unless otherwise specified.
958 $senderid = $USER->id;
961 $systemcontext = \context_system::instance();
962 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
963 return false;
966 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
967 return true;
970 return false;
974 * Get specified message processor, validate corresponding plugin existence and
975 * system configuration.
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
982 public static function get_message_processor($name, $ready = false) {
983 global $DB, $CFG;
985 $processor = $DB->get_record('message_processors', array('name' => $name));
986 if (empty($processor)) {
987 // Processor not found, return.
988 return array();
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();
998 } else {
999 return $processor;
1004 * Returns weather a given processor is enabled or not.
1005 * Note:- This doesn't check if the processor is configured or not.
1007 * @param string $name Name of the processor
1008 * @return bool
1010 public static function is_processor_enabled($name) {
1012 $cache = \cache::make('core', 'message_processors_enabled');
1013 $status = $cache->get($name);
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;
1025 return $status;
1029 * Set status of a processor.
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
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));
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()
1048 * @param \stdClass $processor processor object
1049 * @return \stdClass processed processor object
1050 * @since Moodle 3.2
1052 public static function get_processed_processor_object(\stdClass $processor) {
1053 global $CFG;
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;
1066 $processor->hassettings = 0;
1067 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1068 $processor->hassettings = 1;
1070 $processor->available = 1;
1071 } else {
1072 print_error('errorcallingprocessor', 'message');
1074 } else {
1075 $processor->available = 0;
1077 return $processor;