MDL-36941 core: removed 'message_working' table
[moodle.git] / message / classes / api.php
CommitLineData
879e2bef
MN
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Contains class used to return information to display for the message area.
19 *
20 * @package core_message
21 * @copyright 2016 Mark Nelson <markn@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_message;
26
879e2bef
MN
27defined('MOODLE_INTERNAL') || die();
28
7b55aaa1
MN
29require_once($CFG->dirroot . '/lib/messagelib.php');
30
879e2bef
MN
31/**
32 * Class used to return information to display for the message area.
33 *
34 * @copyright 2016 Mark Nelson <markn@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class api {
38
883ce421
MN
39 /**
40 * The action for reading a message.
41 */
42 const MESSAGE_ACTION_READ = 1;
43
44 /**
45 * The action for deleting a message.
46 */
47 const MESSAGE_ACTION_DELETED = 2;
48
cd03b8d7
MN
49 /**
50 * Handles searching for messages in the message area.
51 *
52 * @param int $userid The user id doing the searching
53 * @param string $search The string the user is searching
54 * @param int $limitfrom
55 * @param int $limitnum
de55cb1b 56 * @return array
cd03b8d7
MN
57 */
58 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
59 global $DB;
60
61 // Get the user fields we want.
62 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
63 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
64
883ce421
MN
65 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
66 m.smallmessage, m.timecreated, 0 as isread, $ufields, mcont.blocked as userfrom_blocked, $ufields2,
67 mcont2.blocked as userto_blocked
68 FROM {messages} m
69 INNER JOIN {user} u
70 ON u.id = m.useridfrom
71 INNER JOIN {message_conversations} mc
72 ON mc.id = m.conversationid
73 INNER JOIN {message_conversation_members} mcm
74 ON mcm.conversationid = m.conversationid
75 INNER JOIN {user} u2
76 ON u2.id = mcm.userid
77 LEFT JOIN {message_contacts} mcont
78 ON (mcont.contactid = u.id AND mcont.userid = ?)
79 LEFT JOIN {message_contacts} mcont2
80 ON (mcont2.contactid = u2.id AND mcont2.userid = ?)
81 LEFT JOIN {message_user_actions} mua
82 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
83 WHERE (m.useridfrom = ? OR mcm.userid = ?)
84 AND m.useridfrom != mcm.userid
cd03b8d7
MN
85 AND u.deleted = 0
86 AND u2.deleted = 0
883ce421 87 AND mua.id is NULL
cd03b8d7
MN
88 AND " . $DB->sql_like('smallmessage', '?', false) . "
89 ORDER BY timecreated DESC";
883ce421
MN
90
91 $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid, '%' . $search . '%');
cd03b8d7
MN
92
93 // Convert the messages into searchable contacts with their last message being the message that was searched.
de55cb1b 94 $conversations = array();
cd03b8d7
MN
95 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
96 foreach ($messages as $message) {
97 $prefix = 'userfrom_';
98 if ($userid == $message->useridfrom) {
99 $prefix = 'userto_';
100 // If it from the user, then mark it as read, even if it wasn't by the receiver.
101 $message->isread = true;
102 }
dd0c1403
MN
103 $blockedcol = $prefix . 'blocked';
104 $message->blocked = $message->$blockedcol;
105
cd03b8d7 106 $message->messageid = $message->id;
de55cb1b 107 $conversations[] = helper::create_contact($message, $prefix);
cd03b8d7
MN
108 }
109 }
110
de55cb1b 111 return $conversations;
cd03b8d7
MN
112 }
113
114 /**
48e8bdba 115 * Handles searching for user in a particular course in the message area.
cd03b8d7
MN
116 *
117 * @param int $userid The user id doing the searching
118 * @param int $courseid The id of the course we are searching in
119 * @param string $search The string the user is searching
120 * @param int $limitfrom
121 * @param int $limitnum
de55cb1b 122 * @return array
cd03b8d7 123 */
48e8bdba 124 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
125 global $DB;
126
127 // Get all the users in the course.
128 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
dd0c1403 129 $sql = "SELECT u.*, mc.blocked
cd03b8d7 130 FROM {user} u
dd0c1403
MN
131 JOIN ($esql) je
132 ON je.id = u.id
133 LEFT JOIN {message_contacts} mc
134 ON (mc.contactid = u.id AND mc.userid = :userid)
cd03b8d7
MN
135 WHERE u.deleted = 0";
136 // Add more conditions.
137 $fullname = $DB->sql_fullname();
dd0c1403 138 $sql .= " AND u.id != :userid2
cd03b8d7
MN
139 AND " . $DB->sql_like($fullname, ':search', false) . "
140 ORDER BY " . $DB->sql_fullname();
dd0c1403 141 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 142
cd03b8d7
MN
143 // Convert all the user records into contacts.
144 $contacts = array();
145 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
146 foreach ($users as $user) {
de55cb1b 147 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
148 }
149 }
150
de55cb1b 151 return $contacts;
cd03b8d7
MN
152 }
153
154 /**
48e8bdba 155 * Handles searching for user in the message area.
cd03b8d7
MN
156 *
157 * @param int $userid The user id doing the searching
158 * @param string $search The string the user is searching
159 * @param int $limitnum
de55cb1b 160 * @return array
cd03b8d7 161 */
48e8bdba 162 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
163 global $CFG, $DB;
164
165 require_once($CFG->dirroot . '/lib/coursecatlib.php');
166
167 // Used to search for contacts.
168 $fullname = $DB->sql_fullname();
169 $ufields = \user_picture::fields('u', array('lastaccess'));
170
171 // Users not to include.
172 $excludeusers = array($userid, $CFG->siteguest);
173 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
174
175 // Ok, let's search for contacts first.
176 $contacts = array();
dd0c1403 177 $sql = "SELECT $ufields, mc.blocked
cd03b8d7
MN
178 FROM {user} u
179 JOIN {message_contacts} mc
180 ON u.id = mc.contactid
181 WHERE mc.userid = :userid
182 AND u.deleted = 0
183 AND u.confirmed = 1
184 AND " . $DB->sql_like($fullname, ':search', false) . "
185 AND u.id $exclude
186 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
187 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
188 0, $limitnum)) {
cd03b8d7 189 foreach ($users as $user) {
de55cb1b 190 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
191 }
192 }
193
194 // Now, let's get the courses.
f3249577
AG
195 // Make sure to limit searches to enrolled courses.
196 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 197 $courses = array();
93b47710
MN
198 // Really we want the user to be able to view the participants if they have the capability
199 // 'moodle/course:viewparticipants' or 'moodle/course:enrolreview', but since the search_courses function
200 // only takes required parameters we can't. However, the chance of a user having 'moodle/course:enrolreview' but
201 // *not* 'moodle/course:viewparticipants' are pretty much zero, so it is not worth addressing.
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
883ce421
MN
265 // Get the last message from each conversation that the user belongs to.
266 $sql = "SELECT m.id, m.conversationid, m.useridfrom, mcm2.userid as useridto, m.smallmessage, m.timecreated
267 FROM {messages} m
268 INNER JOIN (
269 SELECT MAX(m.id) AS messageid
270 FROM {messages} m
271 INNER JOIN (
272 SELECT m.conversationid, MAX(m.timecreated) as maxtime
273 FROM {messages} m
274 INNER JOIN {message_conversation_members} mcm
275 ON mcm.conversationid = m.conversationid
276 LEFT JOIN {message_user_actions} mua
277 ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
278 WHERE mua.id is NULL
279 AND mcm.userid = :userid2
280 GROUP BY m.conversationid
281 ) maxmessage
282 ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
283 GROUP BY m.conversationid
284 ) lastmessage
285 ON lastmessage.messageid = m.id
286 INNER JOIN {message_conversation_members} mcm
287 ON mcm.conversationid = m.conversationid
288 INNER JOIN {message_conversation_members} mcm2
289 ON mcm2.conversationid = m.conversationid
290 WHERE mcm.userid = m.useridfrom
291 AND mcm.id != mcm2.id
292 ORDER BY m.timecreated DESC";
293 $messageset = $DB->get_recordset_sql($sql, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
294 'userid2' => $userid], $limitfrom, $limitnum);
349f4261 295
349f4261
RW
296 $messages = [];
297 foreach ($messageset as $message) {
883ce421 298 $messages[$message->id] = $message;
349f4261
RW
299 }
300 $messageset->close();
301
883ce421
MN
302 // If there are no messages return early.
303 if (empty($messages)) {
304 return [];
305 }
306
349f4261
RW
307 // We need to pull out the list of other users that are part of each of these conversations. This
308 // needs to be done in a separate query to avoid doing a join on the messages tables and the user
309 // tables because on large sites these tables are massive which results in extremely slow
310 // performance (typically due to join buffer exhaustion).
311 $otheruserids = array_map(function($message) use ($userid) {
312 return ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
313 }, array_values($messages));
314
883ce421 315 // Ok, let's get the other members in the conversations.
349f4261 316 list($useridsql, $usersparams) = $DB->get_in_or_equal($otheruserids);
883ce421 317 $userfields = \user_picture::fields('u', array('lastaccess'));
349f4261 318 $userssql = "SELECT $userfields
883ce421
MN
319 FROM {user} u
320 WHERE id $useridsql
321 AND deleted = 0";
349f4261
RW
322 $otherusers = $DB->get_records_sql($userssql, $usersparams);
323
883ce421
MN
324 // If there are no other users (user may have been deleted), then do not continue.
325 if (empty($otherusers)) {
326 return [];
327 }
328
349f4261 329 $contactssql = "SELECT contactid, blocked
883ce421
MN
330 FROM {message_contacts}
331 WHERE userid = ?
332 AND contactid $useridsql";
333 $contacts = $DB->get_records_sql($contactssql, array_merge([$userid], $usersparams));
349f4261
RW
334
335 // Finally, let's get the unread messages count for this user so that we can add them
883ce421
MN
336 // to the conversation. Remember we need to ignore the messages the user sent.
337 $unreadcountssql = 'SELECT m.useridfrom, count(m.id) as count
338 FROM {messages} m
339 INNER JOIN {message_conversations} mc
340 ON mc.id = m.conversationid
341 INNER JOIN {message_conversation_members} mcm
342 ON m.conversationid = mcm.conversationid
343 LEFT JOIN {message_user_actions} mua
344 ON (mua.messageid = m.id AND mua.userid = ? AND
345 (mua.action = ? OR mua.action = ?))
346 WHERE mcm.userid = ?
347 AND m.useridfrom != ?
348 AND mua.id is NULL
349 GROUP BY useridfrom';
350 $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
351 $userid, $userid]);
352
353 // Get rid of the table prefix.
354 $userfields = str_replace('u.', '', $userfields);
349f4261 355 $userproperties = explode(',', $userfields);
de55cb1b 356 $arrconversations = array();
349f4261
RW
357 foreach ($messages as $message) {
358 $conversation = new \stdClass();
359 $otheruserid = ($message->useridfrom == $userid) ? $message->useridto : $message->useridfrom;
360 $otheruser = isset($otherusers[$otheruserid]) ? $otherusers[$otheruserid] : null;
361 $contact = isset($contacts[$otheruserid]) ? $contacts[$otheruserid] : null;
362
883ce421
MN
363 // It's possible the other user was deleted, so, skip.
364 if (is_null($otheruser)) {
365 continue;
366 }
367
349f4261
RW
368 // Add the other user's information to the conversation, if we have one.
369 foreach ($userproperties as $prop) {
370 $conversation->$prop = ($otheruser) ? $otheruser->$prop : null;
371 }
372
373 // Add the contact's information, if we have one.
374 $conversation->blocked = ($contact) ? $contact->blocked : null;
375
376 // Add the message information.
377 $conversation->messageid = $message->id;
378 $conversation->smallmessage = $message->smallmessage;
379 $conversation->useridfrom = $message->useridfrom;
380
381 // Only consider it unread if $user has unread messages.
382 if (isset($unreadcounts[$otheruserid])) {
383 $conversation->isread = false;
384 $conversation->unreadcount = $unreadcounts[$otheruserid]->count;
385 } else {
386 $conversation->isread = true;
879e2bef 387 }
349f4261 388
42e2f6c0 389 $arrconversations[$otheruserid] = helper::create_contact($conversation);
879e2bef
MN
390 }
391
de55cb1b 392 return $arrconversations;
879e2bef
MN
393 }
394
395 /**
396 * Returns the contacts to display in the contacts area.
397 *
398 * @param int $userid The user id
399 * @param int $limitfrom
400 * @param int $limitnum
de55cb1b 401 * @return array
879e2bef
MN
402 */
403 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
404 global $DB;
405
406 $arrcontacts = array();
dd0c1403 407 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
408 FROM {message_contacts} mc
409 JOIN {user} u
410 ON mc.contactid = u.id
411 WHERE mc.userid = :userid
412 AND u.deleted = 0
413 ORDER BY " . $DB->sql_fullname();
414 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
415 foreach ($contacts as $contact) {
de55cb1b 416 $arrcontacts[] = helper::create_contact($contact);
879e2bef
MN
417 }
418 }
419
de55cb1b 420 return $arrcontacts;
879e2bef
MN
421 }
422
883ce421
MN
423 /**
424 * Returns the an array of the users the given user is in a conversation
425 * with who are a contact and the number of unread messages.
426 *
427 * @param int $userid The user id
428 * @param int $limitfrom
429 * @param int $limitnum
430 * @return array
431 */
432 public static function get_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
433 global $DB;
434
435 $userfields = \user_picture::fields('u', array('lastaccess'));
436 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
437 FROM {message_contacts} mc
438 INNER JOIN {user} u
439 ON u.id = mc.contactid
440 LEFT JOIN {messages} m
441 ON m.useridfrom = mc.contactid
442 LEFT JOIN {message_conversation_members} mcm
443 ON mcm.conversationid = m.conversationid AND mcm.userid = ? AND mcm.userid != m.useridfrom
444 LEFT JOIN {message_user_actions} mua
445 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
446 WHERE mua.id is NULL
447 AND mc.userid = ?
448 AND mc.blocked = 0
449 AND u.deleted = 0
450 GROUP BY $userfields";
451
452 return $DB->get_records_sql($unreadcountssql, [$userid, $userid, self::MESSAGE_ACTION_READ,
453 $userid, $userid], $limitfrom, $limitnum);
454 }
455
456 /**
457 * Returns the an array of the users the given user is in a conversation
458 * with who are not a contact and the number of unread messages.
459 *
460 * @param int $userid The user id
461 * @param int $limitfrom
462 * @param int $limitnum
463 * @return array
464 */
465 public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
466 global $DB;
467
468 $userfields = \user_picture::fields('u', array('lastaccess'));
469 $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
470 FROM {user} u
471 INNER JOIN {messages} m
472 ON m.useridfrom = u.id
473 INNER JOIN {message_conversation_members} mcm
474 ON mcm.conversationid = m.conversationid
475 LEFT JOIN {message_user_actions} mua
476 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
477 LEFT JOIN {message_contacts} mc
478 ON (mc.userid = ? AND mc.contactid = u.id)
479 WHERE mcm.userid = ?
480 AND mcm.userid != m.useridfrom
481 AND mua.id is NULL
482 AND mc.id is NULL
483 AND u.deleted = 0
484 GROUP BY $userfields";
485
486 return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid],
487 $limitfrom, $limitnum);
488 }
489
879e2bef
MN
490 /**
491 * Returns the messages to display in the message area.
492 *
493 * @param int $userid the current user
494 * @param int $otheruserid the other user
495 * @param int $limitfrom
496 * @param int $limitnum
8ec78c48 497 * @param string $sort
ffd7798c
MN
498 * @param int $timefrom the time from the message being sent
499 * @param int $timeto the time up until the message being sent
de55cb1b 500 * @return array
879e2bef 501 */
fb1469d8 502 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 503 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
fb1469d8 504
ffd7798c 505 if (!empty($timefrom)) {
fb1469d8 506 // Check the cache to see if we even need to do a DB query.
ffd7798c
MN
507 $cache = \cache::make('core', 'message_time_last_message_between_users');
508 $key = helper::get_last_message_time_created_cache_key($otheruserid, $userid);
fb1469d8
RW
509 $lastcreated = $cache->get($key);
510
511 // The last known message time is earlier than the one being requested so we can
512 // just return an empty result set rather than having to query the DB.
ffd7798c 513 if ($lastcreated && $lastcreated < $timefrom) {
fb1469d8
RW
514 return [];
515 }
516 }
517
879e2bef 518 $arrmessages = array();
fb1469d8 519 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
ffd7798c 520 $sort, $timefrom, $timeto)) {
fb1469d8 521
de55cb1b 522 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
523 }
524
de55cb1b 525 return $arrmessages;
879e2bef 526 }
c060cd49
MN
527
528 /**
529 * Returns the most recent message between two users.
530 *
531 * @param int $userid the current user
532 * @param int $otheruserid the other user
de55cb1b 533 * @return \stdClass|null
c060cd49
MN
534 */
535 public static function get_most_recent_message($userid, $otheruserid) {
536 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 537 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
538 // Swap the order so we now have them in historical order.
539 $messages = array_reverse($messages);
de55cb1b 540 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
541 return array_pop($arrmessages);
542 }
543
544 return null;
545 }
c6e97f54
MN
546
547 /**
548 * Returns the profile information for a contact for a user.
549 *
550 * @param int $userid The user id
551 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 552 * @return \stdClass
c6e97f54
MN
553 */
554 public static function get_profile($userid, $otheruserid) {
f4c39cb9 555 global $CFG, $DB, $PAGE;
c6e97f54
MN
556
557 require_once($CFG->dirroot . '/user/lib.php');
558
f4c39cb9
MN
559 $user = \core_user::get_user($otheruserid, '*', MUST_EXIST);
560
561 // Create the data we are going to pass to the renderable.
562 $data = new \stdClass();
563 $data->userid = $otheruserid;
564 $data->fullname = fullname($user);
565 $data->city = '';
566 $data->country = '';
567 $data->email = '';
cb805753 568 $data->isonline = null;
f4c39cb9
MN
569 // Get the user picture data - messaging has always shown these to the user.
570 $userpicture = new \user_picture($user);
571 $userpicture->size = 1; // Size f1.
572 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
573 $userpicture->size = 0; // Size f2.
574 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
575
576 $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess'));
577 if ($userfields) {
578 if (isset($userfields['city'])) {
579 $data->city = $userfields['city'];
580 }
581 if (isset($userfields['country'])) {
582 $data->country = $userfields['country'];
bf58081d 583 }
f4c39cb9
MN
584 if (isset($userfields['email'])) {
585 $data->email = $userfields['email'];
c6e97f54 586 }
f4c39cb9
MN
587 if (isset($userfields['lastaccess'])) {
588 $data->isonline = helper::is_online($userfields['lastaccess']);
589 }
590 }
c6e97f54 591
f4c39cb9
MN
592 // Check if the contact has been blocked.
593 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
594 if ($contact) {
595 $data->isblocked = (bool) $contact->blocked;
596 $data->iscontact = true;
597 } else {
598 $data->isblocked = false;
599 $data->iscontact = false;
c6e97f54 600 }
f4c39cb9
MN
601
602 return $data;
c6e97f54 603 }
dec0cd99
MN
604
605 /**
606 * Checks if a user can delete messages they have either received or sent.
607 *
608 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
609 * but will still seem as if it was by the user)
1f64514d 610 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99
MN
611 */
612 public static function can_delete_conversation($userid) {
613 global $USER;
614
615 $systemcontext = \context_system::instance();
616
1f64514d 617 // Let's check if the user is allowed to delete this conversation.
dec0cd99
MN
618 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
619 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
620 $USER->id == $userid))) {
621 return true;
622 }
623
624 return false;
625 }
626
627 /**
628 * Deletes a conversation.
629 *
630 * This function does not verify any permissions.
631 *
632 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
633 * but will still seem as if it was by the user)
634 * @param int $otheruserid The id of the other user in the conversation
635 * @return bool
636 */
637 public static function delete_conversation($userid, $otheruserid) {
883ce421 638 global $DB, $USER;
dec0cd99 639
b2cd17e6 640 $conversationid = self::get_conversation_between_users([$userid, $otheruserid]);
dec0cd99 641
883ce421
MN
642 // If there is no conversation, there is nothing to do.
643 if (!$conversationid) {
644 return true;
645 }
646
647 // Get all messages belonging to this conversation that have not already been deleted by this user.
648 $sql = "SELECT m.*
649 FROM {messages} m
650 INNER JOIN {message_conversations} mc
651 ON m.conversationid = mc.id
652 LEFT JOIN {message_user_actions} mua
653 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
654 WHERE mua.id is NULL
655 AND mc.id = ?
656 ORDER BY m.timecreated ASC";
657 $messages = $DB->get_records_sql($sql, [$userid, self::MESSAGE_ACTION_DELETED, $conversationid]);
658
659 // Ok, mark these as deleted.
660 foreach ($messages as $message) {
661 $mua = new \stdClass();
662 $mua->userid = $userid;
663 $mua->messageid = $message->id;
664 $mua->action = self::MESSAGE_ACTION_DELETED;
665 $mua->timecreated = time();
666 $mua->id = $DB->insert_record('message_user_actions', $mua);
667
668 if ($message->useridfrom == $userid) {
669 $useridto = $otheruserid;
670 } else {
671 $useridto = $userid;
dec0cd99 672 }
883ce421
MN
673 \core\event\message_deleted::create_from_ids($message->useridfrom, $useridto,
674 $USER->id, $message->id, $mua->id)->trigger();
dec0cd99
MN
675 }
676
677 return true;
678 }
79f6c36c
MN
679
680 /**
681 * Returns the count of unread conversations (collection of messages from a single user) for
682 * the given user.
683 *
684 * @param \stdClass $user the user who's conversations should be counted
685 * @return int the count of the user's unread conversations
686 */
687 public static function count_unread_conversations($user = null) {
688 global $USER, $DB;
689
690 if (empty($user)) {
691 $user = $USER;
692 }
693
883ce421
MN
694 $sql = "SELECT COUNT(DISTINCT(m.conversationid))
695 FROM {messages} m
696 INNER JOIN {message_conversations} mc
697 ON m.conversationid = mc.id
698 INNER JOIN {message_conversation_members} mcm
699 ON mc.id = mcm.conversationid
700 LEFT JOIN {message_user_actions} mua
701 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
702 WHERE mcm.userid = ?
703 AND mcm.userid != m.useridfrom
704 AND mua.id is NULL";
705
706 return $DB->count_records_sql($sql, [$user->id, self::MESSAGE_ACTION_READ, $user->id]);
79f6c36c
MN
707 }
708
709 /**
710 * Marks ALL messages being sent from $fromuserid to $touserid as read.
711 *
712 * Can be filtered by type.
713 *
714 * @param int $touserid the id of the message recipient
715 * @param int $fromuserid the id of the message sender
716 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
717 * @return void
718 */
719 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
720 global $DB;
721
883ce421
MN
722 $type = strtolower($type);
723
724 // Create the SQL we will be using.
725 $messagesql = "SELECT m.*
726 FROM {messages} m
727 INNER JOIN {message_conversations} mc
728 ON mc.id = m.conversationid
729 INNER JOIN {message_conversation_members} mcm
730 ON mcm.conversationid = mc.id
731 WHERE mcm.userid = ?";
732 $messageparams = [$touserid];
733 if (!empty($fromuserid)) {
734 $messagesql .= " AND m.useridfrom = ?";
735 $messageparams[] = $fromuserid;
79f6c36c
MN
736 }
737
883ce421
MN
738 $notificationsql = "SELECT n.*
739 FROM {notifications} n
740 WHERE useridto = ?";
741 $notificationsparams = [$touserid];
79f6c36c 742 if (!empty($fromuserid)) {
883ce421
MN
743 $notificationsql .= " AND useridfrom = ?";
744 $notificationsparams[] = $fromuserid;
79f6c36c
MN
745 }
746
883ce421
MN
747 $messages = [];
748 $notifications = [];
79f6c36c
MN
749 if (!empty($type)) {
750 if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) {
883ce421 751 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
79f6c36c 752 } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) {
883ce421 753 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
79f6c36c 754 }
883ce421
MN
755 } else { // We want both.
756 $messages = $DB->get_recordset_sql($messagesql, $messageparams);
757 $notifications = $DB->get_recordset_sql($notificationsql, $notificationsparams);
79f6c36c
MN
758 }
759
79f6c36c 760 foreach ($messages as $message) {
548936a6 761 self::mark_message_as_read($touserid, $message);
79f6c36c
MN
762 }
763
883ce421 764 foreach ($notifications as $notification) {
548936a6 765 self::mark_notification_as_read($notification);
883ce421 766 }
79f6c36c
MN
767 }
768
79f6c36c
MN
769 /**
770 * Returns message preferences.
771 *
772 * @param array $processors
773 * @param array $providers
774 * @param \stdClass $user
775 * @return \stdClass
776 * @since 3.2
777 */
778 public static function get_all_message_preferences($processors, $providers, $user) {
779 $preferences = helper::get_providers_preferences($providers, $user->id);
780 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
781
782 // For every processors put its options on the form (need to get function from processor's lib.php).
783 foreach ($processors as $processor) {
784 $processor->object->load_data($preferences, $user->id);
785 }
786
787 // Load general messaging preferences.
788 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
789 $preferences->mailformat = $user->mailformat;
790 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
791
792 return $preferences;
793 }
5b0769db
MN
794
795 /**
796 * Count the number of users blocked by a user.
797 *
798 * @param \stdClass $user The user object
799 * @return int the number of blocked users
800 */
801 public static function count_blocked_users($user = null) {
802 global $USER, $DB;
803
804 if (empty($user)) {
805 $user = $USER;
806 }
807
808 $sql = "SELECT count(mc.id)
809 FROM {message_contacts} mc
810 WHERE mc.userid = :userid AND mc.blocked = 1";
811 return $DB->count_records_sql($sql, array('userid' => $user->id));
812 }
813
814 /**
815 * Determines if a user is permitted to send another user a private message.
816 * If no sender is provided then it defaults to the logged in user.
817 *
818 * @param \stdClass $recipient The user object.
819 * @param \stdClass|null $sender The user object.
820 * @return bool true if user is permitted, false otherwise.
821 */
822 public static function can_post_message($recipient, $sender = null) {
823 global $USER;
824
825 if (is_null($sender)) {
826 // The message is from the logged in user, unless otherwise specified.
827 $sender = $USER;
828 }
829
830 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
831 return false;
832 }
833
834 // The recipient blocks messages from non-contacts and the
835 // sender isn't a contact.
836 if (self::is_user_non_contact_blocked($recipient, $sender)) {
837 return false;
838 }
839
26dca05d
JP
840 $senderid = null;
841 if ($sender !== null && isset($sender->id)) {
842 $senderid = $sender->id;
843 }
5b0769db 844 // The recipient has specifically blocked this sender.
26dca05d 845 if (self::is_user_blocked($recipient->id, $senderid)) {
5b0769db
MN
846 return false;
847 }
848
849 return true;
850 }
851
852 /**
853 * Checks if the recipient is allowing messages from users that aren't a
854 * contact. If not then it checks to make sure the sender is in the
855 * recipient's contacts.
856 *
857 * @param \stdClass $recipient The user object.
858 * @param \stdClass|null $sender The user object.
859 * @return bool true if $sender is blocked, false otherwise.
860 */
861 public static function is_user_non_contact_blocked($recipient, $sender = null) {
862 global $USER, $DB;
863
864 if (is_null($sender)) {
865 // The message is from the logged in user, unless otherwise specified.
866 $sender = $USER;
867 }
868
869 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
870 if (!empty($blockednoncontacts)) {
871 // Confirm the sender is a contact of the recipient.
872 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
873 if ($exists) {
874 // All good, the recipient is a contact of the sender.
875 return false;
876 } else {
877 // Oh no, the recipient is not a contact. Looks like we can't send the message.
878 return true;
879 }
880 }
881
882 return false;
883 }
884
885 /**
886 * Checks if the recipient has specifically blocked the sending user.
887 *
888 * Note: This function will always return false if the sender has the
889 * readallmessages capability at the system context level.
890 *
26dca05d
JP
891 * @param int $recipientid User ID of the recipient.
892 * @param int $senderid User ID of the sender.
5b0769db
MN
893 * @return bool true if $sender is blocked, false otherwise.
894 */
26dca05d 895 public static function is_user_blocked($recipientid, $senderid = null) {
5b0769db
MN
896 global $USER, $DB;
897
26dca05d 898 if (is_null($senderid)) {
5b0769db 899 // The message is from the logged in user, unless otherwise specified.
26dca05d 900 $senderid = $USER->id;
5b0769db
MN
901 }
902
903 $systemcontext = \context_system::instance();
26dca05d 904 if (has_capability('moodle/site:readallmessages', $systemcontext, $senderid)) {
5b0769db
MN
905 return false;
906 }
907
26dca05d
JP
908 if ($DB->get_field('message_contacts', 'blocked', ['userid' => $recipientid, 'contactid' => $senderid])) {
909 return true;
5b0769db
MN
910 }
911
912 return false;
913 }
20ab51fd
AA
914
915 /**
916 * Get specified message processor, validate corresponding plugin existence and
917 * system configuration.
918 *
919 * @param string $name Name of the processor.
920 * @param bool $ready only return ready-to-use processors.
921 * @return mixed $processor if processor present else empty array.
922 * @since Moodle 3.2
923 */
924 public static function get_message_processor($name, $ready = false) {
925 global $DB, $CFG;
926
927 $processor = $DB->get_record('message_processors', array('name' => $name));
928 if (empty($processor)) {
929 // Processor not found, return.
930 return array();
931 }
932
933 $processor = self::get_processed_processor_object($processor);
934 if ($ready) {
935 if ($processor->enabled && $processor->configured) {
936 return $processor;
937 } else {
938 return array();
939 }
940 } else {
941 return $processor;
942 }
943 }
944
945 /**
946 * Returns weather a given processor is enabled or not.
947 * Note:- This doesn't check if the processor is configured or not.
948 *
949 * @param string $name Name of the processor
950 * @return bool
951 */
952 public static function is_processor_enabled($name) {
953
954 $cache = \cache::make('core', 'message_processors_enabled');
955 $status = $cache->get($name);
956
957 if ($status === false) {
958 $processor = self::get_message_processor($name);
959 if (!empty($processor)) {
960 $cache->set($name, $processor->enabled);
961 return $processor->enabled;
962 } else {
963 return false;
964 }
965 }
966
967 return $status;
968 }
969
970 /**
971 * Set status of a processor.
972 *
973 * @param \stdClass $processor processor record.
974 * @param 0|1 $enabled 0 or 1 to set the processor status.
975 * @return bool
976 * @since Moodle 3.2
977 */
978 public static function update_processor_status($processor, $enabled) {
979 global $DB;
980 $cache = \cache::make('core', 'message_processors_enabled');
981 $cache->delete($processor->name);
982 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
983 }
984
985 /**
986 * Given a processor object, loads information about it's settings and configurations.
987 * This is not a public api, instead use @see \core_message\api::get_message_processor()
988 * or @see \get_message_processors()
989 *
990 * @param \stdClass $processor processor object
991 * @return \stdClass processed processor object
992 * @since Moodle 3.2
993 */
994 public static function get_processed_processor_object(\stdClass $processor) {
995 global $CFG;
996
997 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
998 if (is_readable($processorfile)) {
999 include_once($processorfile);
1000 $processclass = 'message_output_' . $processor->name;
1001 if (class_exists($processclass)) {
1002 $pclass = new $processclass();
1003 $processor->object = $pclass;
1004 $processor->configured = 0;
1005 if ($pclass->is_system_configured()) {
1006 $processor->configured = 1;
1007 }
1008 $processor->hassettings = 0;
1009 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
1010 $processor->hassettings = 1;
1011 }
1012 $processor->available = 1;
1013 } else {
1014 print_error('errorcallingprocessor', 'message');
1015 }
1016 } else {
1017 $processor->available = 0;
1018 }
1019 return $processor;
1020 }
883ce421
MN
1021
1022 /**
1023 * Retrieve users blocked by $user1
1024 *
1025 * @param int $userid The user id of the user whos blocked users we are returning
1026 * @return array the users blocked
1027 */
1028 public static function get_blocked_users($userid) {
1029 global $DB;
1030
1031 $userfields = \user_picture::fields('u', array('lastaccess'));
1032 $blockeduserssql = "SELECT $userfields
1033 FROM {message_contacts} mc
1034 INNER JOIN {user} u
1035 ON u.id = mc.contactid
1036 WHERE u.deleted = 0
1037 AND mc.userid = ?
1038 AND mc.blocked = 1
1039 GROUP BY $userfields
1040 ORDER BY u.firstname ASC";
1041 return $DB->get_records_sql($blockeduserssql, [$userid]);
1042 }
1043
1044 /**
1045 * Mark a single message as read.
1046 *
1047 * @param int $userid The user id who marked the message as read
548936a6 1048 * @param \stdClass $message The message
883ce421
MN
1049 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1050 */
548936a6 1051 public static function mark_message_as_read($userid, $message, $timeread = null) {
883ce421
MN
1052 global $DB;
1053
1054 if (is_null($timeread)) {
1055 $timeread = time();
1056 }
1057
883ce421
MN
1058 // Check if the user has already read this message.
1059 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
548936a6 1060 'messageid' => $message->id, 'action' => self::MESSAGE_ACTION_READ])) {
883ce421
MN
1061 $mua = new \stdClass();
1062 $mua->userid = $userid;
548936a6 1063 $mua->messageid = $message->id;
883ce421
MN
1064 $mua->action = self::MESSAGE_ACTION_READ;
1065 $mua->timecreated = $timeread;
1066 $mua->id = $DB->insert_record('message_user_actions', $mua);
1067
1068 // Get the context for the user who received the message.
1069 $context = \context_user::instance($userid, IGNORE_MISSING);
1070 // If the user no longer exists the context value will be false, in this case use the system context.
1071 if ($context === false) {
1072 $context = \context_system::instance();
1073 }
1074
1075 // Trigger event for reading a message.
1076 $event = \core\event\message_viewed::create(array(
1077 'objectid' => $mua->id,
1078 'userid' => $userid, // Using the user who read the message as they are the ones performing the action.
1079 'context' => $context,
1080 'relateduserid' => $message->useridfrom,
1081 'other' => array(
548936a6 1082 'messageid' => $message->id
883ce421
MN
1083 )
1084 ));
1085 $event->trigger();
1086 }
1087 }
1088
1089 /**
1090 * Mark a single notification as read.
1091 *
548936a6 1092 * @param \stdClass $notification The notification
883ce421
MN
1093 * @param int|null $timeread The time the message was marked as read, if null will default to time()
1094 */
548936a6 1095 public static function mark_notification_as_read($notification, $timeread = null) {
883ce421
MN
1096 global $DB;
1097
1098 if (is_null($timeread)) {
1099 $timeread = time();
1100 }
1101
883ce421
MN
1102 if (is_null($notification->timeread)) {
1103 $updatenotification = new \stdClass();
1104 $updatenotification->id = $notification->id;
1105 $updatenotification->timeread = $timeread;
1106
1107 $DB->update_record('notifications', $updatenotification);
376a79c2
MN
1108
1109 // Trigger event for reading a notification.
1110 \core\event\notification_viewed::create_from_ids(
1111 $notification->useridfrom,
1112 $notification->useridto,
1113 $notification->id
1114 )->trigger();
883ce421
MN
1115 }
1116 }
1117
1118 /**
1119 * Checks if a user can delete a message.
1120 *
1121 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1122 * but will still seem as if it was by the user)
1123 * @param int $messageid The message id
1124 * @return bool Returns true if a user can delete the message, false otherwise.
1125 */
1126 public static function can_delete_message($userid, $messageid) {
1127 global $DB, $USER;
1128
1129 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1130 FROM {messages} m
1131 INNER JOIN {message_conversations} mc
1132 ON m.conversationid = mc.id
1133 INNER JOIN {message_conversation_members} mcm
1134 ON mcm.conversationid = mc.id
1135 WHERE mcm.userid != m.useridfrom
1136 AND m.id = ?";
1137 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1138
1139 if ($message->useridfrom == $userid) {
1140 $userdeleting = 'useridfrom';
1141 } else if ($message->useridto == $userid) {
1142 $userdeleting = 'useridto';
1143 } else {
1144 return false;
1145 }
1146
1147 $systemcontext = \context_system::instance();
1148
1149 // Let's check if the user is allowed to delete this message.
1150 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1151 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1152 $USER->id == $message->$userdeleting))) {
1153 return true;
1154 }
1155
1156 return false;
1157 }
1158
1159 /**
1160 * Deletes a message.
1161 *
1162 * This function does not verify any permissions.
1163 *
1164 * @param int $userid the user id of who we want to delete the message for (this may be done by the admin
1165 * but will still seem as if it was by the user)
1166 * @param int $messageid The message id
1167 * @return bool
1168 */
1169 public static function delete_message($userid, $messageid) {
1170 global $DB;
1171
1172 $sql = "SELECT m.id, m.useridfrom, mcm.userid as useridto
1173 FROM {messages} m
1174 INNER JOIN {message_conversations} mc
1175 ON m.conversationid = mc.id
1176 INNER JOIN {message_conversation_members} mcm
1177 ON mcm.conversationid = mc.id
1178 WHERE mcm.userid != m.useridfrom
1179 AND m.id = ?";
1180 $message = $DB->get_record_sql($sql, [$messageid], MUST_EXIST);
1181
1182 // Check if the user has already deleted this message.
1183 if (!$DB->record_exists('message_user_actions', ['userid' => $userid,
1184 'messageid' => $messageid, 'action' => self::MESSAGE_ACTION_DELETED])) {
1185 $mua = new \stdClass();
1186 $mua->userid = $userid;
1187 $mua->messageid = $messageid;
1188 $mua->action = self::MESSAGE_ACTION_DELETED;
1189 $mua->timecreated = time();
1190 $mua->id = $DB->insert_record('message_user_actions', $mua);
1191
1192 // Trigger event for deleting a message.
1193 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1194 $userid, $message->id, $mua->id)->trigger();
1195
1196 return true;
1197 }
1198
1199 return false;
1200 }
1201
1202 /**
1203 * Returns the conversation between two users.
1204 *
b2cd17e6 1205 * @param array $userids
883ce421
MN
1206 * @return int|bool The id of the conversation, false if not found
1207 */
b2cd17e6 1208 public static function get_conversation_between_users(array $userids) {
883ce421
MN
1209 global $DB;
1210
b2cd17e6 1211 $hash = helper::get_conversation_hash($userids);
883ce421 1212
b2cd17e6 1213 if ($conversation = $DB->get_record('message_conversations', ['convhash' => $hash])) {
883ce421
MN
1214 return $conversation->id;
1215 }
1216
1217 return false;
1218 }
1219
1220 /**
1221 * Creates a conversation between two users.
1222 *
b2cd17e6 1223 * @param array $userids
883ce421
MN
1224 * @return int The id of the conversation
1225 */
b2cd17e6 1226 public static function create_conversation_between_users(array $userids) {
883ce421
MN
1227 global $DB;
1228
1229 $conversation = new \stdClass();
b2cd17e6 1230 $conversation->convhash = helper::get_conversation_hash($userids);
883ce421
MN
1231 $conversation->timecreated = time();
1232 $conversation->id = $DB->insert_record('message_conversations', $conversation);
1233
1234 // Add members to this conversation.
b2cd17e6
MN
1235 foreach ($userids as $userid) {
1236 $member = new \stdClass();
1237 $member->conversationid = $conversation->id;
1238 $member->userid = $userid;
1239 $member->timecreated = time();
1240 $DB->insert_record('message_conversation_members', $member);
1241 }
883ce421
MN
1242
1243 return $conversation->id;
1244 }
879e2bef 1245}