MDL-63850 core_message: '$referenceuserid' used when returning requests
[moodle.git] / message / classes / helper.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 helper class 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
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Helper class for the message area.
31 *
32 * @copyright 2016 Mark Nelson <markn@moodle.com>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 */
35class helper {
36
37 /**
38 * Helper function to retrieve the messages between two users
39 *
d1e8e69d 40 * @deprecated since 3.6
879e2bef
MN
41 * @param int $userid the current user
42 * @param int $otheruserid the other user
dec0cd99 43 * @param int $timedeleted the time the message was deleted
879e2bef
MN
44 * @param int $limitfrom
45 * @param int $limitnum
46 * @param string $sort
ffd7798c
MN
47 * @param int $timefrom the time from the message being sent
48 * @param int $timeto the time up until the message being sent
879e2bef
MN
49 * @return array of messages
50 */
7b55aaa1 51 public static function get_messages($userid, $otheruserid, $timedeleted = 0, $limitfrom = 0, $limitnum = 0,
ffd7798c 52 $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
d1e8e69d
MN
53 debugging('\core_message\helper::get_messages() is deprecated, please use ' .
54 '\core_message\helper::get_conversation_messages() instead.', DEBUG_DEVELOPER);
55
879e2bef
MN
56 global $DB;
57
e159b53b
MN
58 $hash = self::get_conversation_hash([$userid, $otheruserid]);
59
60 $sql = "SELECT m.id, m.useridfrom, m.subject, m.fullmessage, m.fullmessagehtml,
61 m.fullmessageformat, m.smallmessage, m.timecreated, muaread.timecreated AS timeread
62 FROM {message_conversations} mc
63 INNER JOIN {messages} m
64 ON m.conversationid = mc.id
65 LEFT JOIN {message_user_actions} muaread
66 ON (muaread.messageid = m.id
67 AND muaread.userid = :userid1
68 AND muaread.action = :readaction)";
69 $params = ['userid1' => $userid, 'readaction' => api::MESSAGE_ACTION_READ, 'convhash' => $hash];
ebc746dc 70
883ce421
MN
71 if (empty($timedeleted)) {
72 $sql .= " LEFT JOIN {message_user_actions} mua
e159b53b
MN
73 ON (mua.messageid = m.id
74 AND mua.userid = :userid2
75 AND mua.action = :deleteaction
76 AND mua.timecreated is NOT NULL)";
883ce421
MN
77 } else {
78 $sql .= " INNER JOIN {message_user_actions} mua
e159b53b
MN
79 ON (mua.messageid = m.id
80 AND mua.userid = :userid2
81 AND mua.action = :deleteaction
82 AND mua.timecreated = :timedeleted)";
83 $params['timedeleted'] = $timedeleted;
883ce421 84 }
fb1469d8 85
e159b53b
MN
86 $params['userid2'] = $userid;
87 $params['deleteaction'] = api::MESSAGE_ACTION_DELETED;
88
89 $sql .= " WHERE mc.convhash = :convhash";
fb1469d8 90
ffd7798c 91 if (!empty($timefrom)) {
e159b53b
MN
92 $sql .= " AND m.timecreated >= :timefrom";
93 $params['timefrom'] = $timefrom;
fb1469d8
RW
94 }
95
ffd7798c 96 if (!empty($timeto)) {
e159b53b
MN
97 $sql .= " AND m.timecreated <= :timeto";
98 $params['timeto'] = $timeto;
883ce421
MN
99 }
100
101 if (empty($timedeleted)) {
102 $sql .= " AND mua.id is NULL";
fb1469d8
RW
103 }
104
883ce421 105 $sql .= " ORDER BY m.$sort";
879e2bef 106
e159b53b
MN
107 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
108 foreach ($messages as &$message) {
109 $message->useridto = ($message->useridfrom == $userid) ? $otheruserid : $userid;
110 }
111
112 return $messages;
879e2bef
MN
113 }
114
fb04293b
SA
115 /**
116 * Helper function to retrieve conversation messages.
117 *
118 * @param int $userid The current user.
119 * @param int $convid The conversation identifier.
120 * @param int $timedeleted The time the message was deleted
121 * @param int $limitfrom Return a subset of records, starting at this point (optional).
122 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
123 * @param string $sort The column name to order by including optionally direction.
124 * @param int $timefrom The time from the message being sent.
125 * @param int $timeto The time up until the message being sent.
126 * @return array of messages
127 */
128 public static function get_conversation_messages(int $userid, int $convid, int $timedeleted = 0, int $limitfrom = 0,
129 int $limitnum = 0, string $sort = 'timecreated ASC', int $timefrom = 0,
130 int $timeto = 0) : array {
131 global $DB;
132
133 $sql = "SELECT m.id, m.useridfrom, m.subject, m.fullmessage, m.fullmessagehtml,
134 m.fullmessageformat, m.smallmessage, m.timecreated, muaread.timecreated AS timeread
135 FROM {message_conversations} mc
136 INNER JOIN {messages} m
137 ON m.conversationid = mc.id
138 LEFT JOIN {message_user_actions} muaread
139 ON (muaread.messageid = m.id
140 AND muaread.userid = :userid1
141 AND muaread.action = :readaction)";
142 $params = ['userid1' => $userid, 'readaction' => api::MESSAGE_ACTION_READ, 'convid' => $convid];
143
144 if (empty($timedeleted)) {
145 $sql .= " LEFT JOIN {message_user_actions} mua
146 ON (mua.messageid = m.id
147 AND mua.userid = :userid2
148 AND mua.action = :deleteaction
149 AND mua.timecreated is NOT NULL)";
150 } else {
151 $sql .= " INNER JOIN {message_user_actions} mua
152 ON (mua.messageid = m.id
153 AND mua.userid = :userid2
154 AND mua.action = :deleteaction
155 AND mua.timecreated = :timedeleted)";
156 $params['timedeleted'] = $timedeleted;
157 }
158
159 $params['userid2'] = $userid;
160 $params['deleteaction'] = api::MESSAGE_ACTION_DELETED;
161
162 $sql .= " WHERE mc.id = :convid";
163
164 if (!empty($timefrom)) {
165 $sql .= " AND m.timecreated >= :timefrom";
166 $params['timefrom'] = $timefrom;
167 }
168
169 if (!empty($timeto)) {
170 $sql .= " AND m.timecreated <= :timeto";
171 $params['timeto'] = $timeto;
172 }
173
174 if (empty($timedeleted)) {
175 $sql .= " AND mua.id is NULL";
176 }
177
178 $sql .= " ORDER BY m.$sort";
179
180 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
181
182 return $messages;
183 }
184
d89d0d65
SA
185 /**
186 * Helper function to return a conversation messages with the involved members (only the ones
187 * who have sent any of these messages).
188 *
189 * @param int $userid The current userid.
190 * @param int $convid The conversation id.
191 * @param array $messages The formated array messages.
192 * @return array A conversation array with the messages and the involved members.
193 */
194 public static function format_conversation_messages(int $userid, int $convid, array $messages) : array {
195 global $USER;
196
197 // Create the conversation array.
198 $conversation = array(
199 'id' => $convid,
200 );
201
202 // Store the messages.
203 $arrmessages = array();
204
d89d0d65
SA
205 foreach ($messages as $message) {
206 // Store the message information.
207 $msg = new \stdClass();
208 $msg->id = $message->id;
209 $msg->useridfrom = $message->useridfrom;
210 $msg->text = message_format_message_text($message);
211 $msg->timecreated = $message->timecreated;
212 $arrmessages[] = $msg;
213 }
214 // Add the messages to the conversation.
215 $conversation['messages'] = $arrmessages;
216
217 // Get the users who have sent any of the $messages.
218 $memberids = array_unique(array_map(function($message) {
219 return $message->useridfrom;
220 }, $messages));
221 // Get members information.
222 $arrmembers = self::get_member_info($userid, $memberids);
223 // Add the members to the conversation.
224 $conversation['members'] = $arrmembers;
225
226 return $conversation;
227 }
228
879e2bef 229 /**
de55cb1b 230 * Helper function to return an array of messages.
879e2bef 231 *
d1e8e69d 232 * @deprecated since 3.6
879e2bef
MN
233 * @param int $userid
234 * @param array $messages
de55cb1b 235 * @return array
879e2bef
MN
236 */
237 public static function create_messages($userid, $messages) {
d1e8e69d
MN
238 debugging('\core_message\helper::create_messages() is deprecated, please use ' .
239 '\core_message\helper::create_conversation_messages() instead.', DEBUG_DEVELOPER);
240
879e2bef
MN
241 // Store the messages.
242 $arrmessages = array();
243
8ec78c48
MN
244 // We always view messages from oldest to newest, ensure we have it in that order.
245 $lastmessage = end($messages);
246 $firstmessage = reset($messages);
247 if ($lastmessage->timecreated < $firstmessage->timecreated) {
248 $messages = array_reverse($messages);
249 }
250
879e2bef
MN
251 // Keeps track of the last day, month and year combo we were viewing.
252 $day = '';
253 $month = '';
254 $year = '';
255 foreach ($messages as $message) {
256 // Check if we are now viewing a different block period.
3090f52f 257 $displayblocktime = false;
879e2bef
MN
258 $date = usergetdate($message->timecreated);
259 if ($day != $date['mday'] || $month != $date['month'] || $year != $date['year']) {
260 $day = $date['mday'];
261 $month = $date['month'];
262 $year = $date['year'];
3090f52f 263 $displayblocktime = true;
879e2bef
MN
264 }
265 // Store the message to pass to the renderable.
266 $msg = new \stdClass();
3090f52f 267 $msg->id = $message->id;
879e2bef
MN
268 $msg->text = message_format_message_text($message);
269 $msg->currentuserid = $userid;
270 $msg->useridfrom = $message->useridfrom;
271 $msg->useridto = $message->useridto;
3090f52f 272 $msg->displayblocktime = $displayblocktime;
879e2bef 273 $msg->timecreated = $message->timecreated;
3090f52f 274 $msg->timeread = $message->timeread;
de55cb1b 275 $arrmessages[] = $msg;
879e2bef
MN
276 }
277
278 return $arrmessages;
279 }
280
281 /**
de55cb1b 282 * Helper function for creating a contact object.
879e2bef
MN
283 *
284 * @param \stdClass $contact
cd03b8d7 285 * @param string $prefix
de55cb1b 286 * @return \stdClass
879e2bef 287 */
cd03b8d7 288 public static function create_contact($contact, $prefix = '') {
bf58081d 289 global $PAGE;
879e2bef
MN
290
291 // Create the data we are going to pass to the renderable.
cd03b8d7 292 $userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix);
879e2bef
MN
293 $data = new \stdClass();
294 $data->userid = $userfields->id;
89a70ba1 295 $data->useridfrom = null;
879e2bef
MN
296 $data->fullname = fullname($userfields);
297 // Get the user picture data.
298 $userpicture = new \user_picture($userfields);
299 $userpicture->size = 1; // Size f1.
300 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
301 $userpicture->size = 0; // Size f2.
302 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
303 // Store the message if we have it.
5bf0ff27 304 $data->ismessaging = false;
cd03b8d7
MN
305 $data->lastmessage = null;
306 $data->messageid = null;
879e2bef 307 if (isset($contact->smallmessage)) {
5bf0ff27 308 $data->ismessaging = true;
54d83992
RW
309 // Strip the HTML tags from the message for displaying in the contact area.
310 $data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS);
89a70ba1 311 $data->useridfrom = $contact->useridfrom;
cd03b8d7
MN
312 if (isset($contact->messageid)) {
313 $data->messageid = $contact->messageid;
314 }
879e2bef 315 }
cb805753
MN
316 $data->isonline = null;
317 if (self::show_online_status($userfields)) {
318 $data->isonline = self::is_online($userfields->lastaccess);
319 }
1f64514d
MN
320 $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
321 $data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
c33b7d89 322 $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
879e2bef 323
de55cb1b 324 return $data;
879e2bef 325 }
bf58081d 326
cb805753
MN
327 /**
328 * Helper function for checking if we should show the user's online status.
329 *
330 * @param \stdClass $user
331 * @return boolean
332 */
333 public static function show_online_status($user) {
334 global $CFG;
335
336 require_once($CFG->dirroot . '/user/lib.php');
337
338 if ($lastaccess = user_get_user_details($user, null, array('lastaccess'))) {
339 if (isset($lastaccess['lastaccess'])) {
340 return true;
341 }
342 }
343
344 return false;
345 }
346
bf58081d
MN
347 /**
348 * Helper function for checking the time meets the 'online' condition.
349 *
350 * @param int $lastaccess
351 * @return boolean
352 */
353 public static function is_online($lastaccess) {
354 global $CFG;
355
356 // Variable to check if we consider this user online or not.
357 $timetoshowusers = 300; // Seconds default.
358 if (isset($CFG->block_online_users_timetosee)) {
359 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
360 }
361 $time = time() - $timetoshowusers;
362
363 return $lastaccess >= $time;
364 }
79f6c36c
MN
365
366 /**
367 * Get providers preferences.
368 *
369 * @param array $providers
370 * @param int $userid
371 * @return \stdClass
372 */
373 public static function get_providers_preferences($providers, $userid) {
374 $preferences = new \stdClass();
375
376 // Get providers preferences.
377 foreach ($providers as $provider) {
378 foreach (array('loggedin', 'loggedoff') as $state) {
379 $linepref = get_user_preferences('message_provider_' . $provider->component . '_' . $provider->name
380 . '_' . $state, '', $userid);
381 if ($linepref == '') {
382 continue;
383 }
384 $lineprefarray = explode(',', $linepref);
385 $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array();
386 foreach ($lineprefarray as $pref) {
387 $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1;
388 }
389 }
390 }
391
392 return $preferences;
393 }
394
395 /**
396 * Requires the JS libraries for the toggle contact button.
397 *
398 * @return void
399 */
400 public static function togglecontact_requirejs() {
401 global $PAGE;
402
403 static $done = false;
404 if ($done) {
405 return;
406 }
407
408 $PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button'));
409 $done = true;
410 }
411
412 /**
413 * Returns the attributes to place on a contact button.
414 *
415 * @param object $user User object.
416 * @param bool $iscontact
417 * @return array
418 */
419 public static function togglecontact_link_params($user, $iscontact = false) {
420 $params = array(
421 'data-userid' => $user->id,
422 'data-is-contact' => $iscontact,
423 'id' => 'toggle-contact-button',
424 'role' => 'button',
425 'class' => 'ajax-contact-button',
426 );
427
428 return $params;
429 }
ffd7798c 430
b2cd17e6
MN
431 /**
432 * Returns the conversation hash between users for easy look-ups in the DB.
433 *
434 * @param array $userids
435 * @return string
436 */
437 public static function get_conversation_hash(array $userids) {
438 sort($userids);
439
440 return sha1(implode('-', $userids));
441 }
442
4699b8bc
AN
443 /**
444 * Returns the cache key for the time created value of the last message of this conversation.
445 *
446 * @param int $convid The conversation identifier.
447 * @return string The key.
448 */
449 public static function get_last_message_time_created_cache_key(int $convid) {
450 return $convid;
451 }
452
78348dfc
MN
453 /**
454 * Checks if legacy messages exist for a given user.
455 *
456 * @param int $userid
457 * @return bool
458 */
459 public static function legacy_messages_exist($userid) {
460 global $DB;
461
462 $sql = "SELECT id
463 FROM {message} m
464 WHERE useridfrom = ?
465 OR useridto = ?";
466 $messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);
467
468 $sql = "SELECT id
469 FROM {message_read} m
470 WHERE useridfrom = ?
471 OR useridto = ?";
472 $messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);
473
474 return $messageexists || $messagereadexists;
475 }
2a2b86f1
JD
476
477 /**
478 * Returns conversation member info for the supplied users, relative to the supplied referenceuserid.
479 *
480 * This is the basic structure used when returning members, and includes information about the relationship between each member
481 * and the referenceuser, such as a whether the referenceuser has marked the member as a contact, or has blocked them.
482 *
483 * @param int $referenceuserid the id of the user which check contact and blocked status.
484 * @param array $userids
054834b0 485 * @param bool $includecontactrequests Do we want to include contact requests with this data?
2a2b86f1
JD
486 * @return array the array of objects containing member info, indexed by userid.
487 * @throws \coding_exception
488 * @throws \dml_exception
489 */
054834b0 490 public static function get_member_info(int $referenceuserid, array $userids, bool $includecontactrequests = false) : array {
2a2b86f1
JD
491 global $DB, $PAGE;
492
6981de10
MN
493 // Prevent exception being thrown when array is empty.
494 if (empty($userids)) {
495 return [];
496 }
497
2a2b86f1
JD
498 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
499 $userfields = \user_picture::fields('u', array('lastaccess'));
eb5865da 500 $userssql = "SELECT $userfields, u.deleted, mc.id AS contactid, mub.id AS blockedid
2a2b86f1
JD
501 FROM {user} u
502 LEFT JOIN {message_contacts} mc
503 ON (mc.userid = ? AND mc.contactid = u.id)
504 LEFT JOIN {message_users_blocked} mub
505 ON (mub.userid = ? AND mub.blockeduserid = u.id)
eb5865da 506 WHERE u.id $useridsql";
2a2b86f1
JD
507 $usersparams = array_merge([$referenceuserid, $referenceuserid], $usersparams);
508 $otherusers = $DB->get_records_sql($userssql, $usersparams);
509
510 $members = [];
511 foreach ($otherusers as $member) {
512 // Set basic data.
513 $data = new \stdClass();
514 $data->id = $member->id;
515 $data->fullname = fullname($member);
516
517 // Set the user picture data.
518 $userpicture = new \user_picture($member);
519 $userpicture->size = 1; // Size f1.
520 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
521 $userpicture->size = 0; // Size f2.
522 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
523
524 // Set online status indicators.
525 $data->isonline = self::show_online_status($member) ? self::is_online($member->lastaccess) : null;
526 $data->showonlinestatus = is_null($data->isonline) ? false : true;
527
528 // Set contact and blocked status indicators.
529 $data->iscontact = ($member->contactid) ? true : false;
530 $data->isblocked = ($member->blockedid) ? true : false;
531
eb5865da
JD
532 $data->isdeleted = ($member->deleted) ? true : false;
533
2a2b86f1
JD
534 $members[$data->id] = $data;
535 }
054834b0
MN
536
537 // Check if we want to include contact requests as well.
538 if (!empty($members) && $includecontactrequests) {
539 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
540
5c675c50
MN
541 $wheresql = "(userid $useridsql AND requesteduserid = ?) OR (userid = ? AND requesteduserid $useridsql)";
542 $params = array_merge($usersparams, [$referenceuserid, $referenceuserid], $usersparams);
543 if ($contactrequests = $DB->get_records_select('message_contact_requests', $wheresql, $params,
544 'timecreated ASC, id ASC')) {
054834b0
MN
545 foreach ($contactrequests as $contactrequest) {
546 if (isset($members[$contactrequest->userid])) {
547 $members[$contactrequest->userid]->contactrequests[] = $contactrequest;
548 }
549 if (isset($members[$contactrequest->requesteduserid])) {
550 $members[$contactrequest->requesteduserid]->contactrequests[] = $contactrequest;
551 }
552 }
553 }
554 }
555
2a2b86f1
JD
556 return $members;
557 }
eb35e0b1
JD
558
559 /**
560 * Backwards compatibility formatter, transforming the new output of get_conversations() into the old format.
561 *
562 * @param array $conversations the array of conversations, which must come from get_conversations().
563 * @return array the array of conversations, formatted in the legacy style.
564 */
565 public static function get_conversations_legacy_formatter(array $conversations) : array {
566 // Transform new data format back into the old format, just for BC during the deprecation life cycle.
567 $tmp = [];
568 foreach ($conversations as $id => $conv) {
569 $data = new \stdClass();
570 // The logic for the 'other user' is as follows:
571 // If a conversation is of type 'individual', the other user is always the member who is not the current user.
572 // If the conversation is of type 'group', the other user is always the sender of the most recent message.
573 // The get_conversations method already follows this logic, so we just need the first member.
574 $otheruser = reset($conv->members);
575 $data->userid = $otheruser->id;
576 $data->useridfrom = $conv->messages[0]->useridfrom ?? null;
577 $data->fullname = $conv->members[$otheruser->id]->fullname;
578 $data->profileimageurl = $conv->members[$otheruser->id]->profileimageurl;
579 $data->profileimageurlsmall = $conv->members[$otheruser->id]->profileimageurlsmall;
580 $data->ismessaging = isset($conv->messages[0]->text) ? true : false;
74fc14e5 581 $data->lastmessage = $conv->messages[0]->text ? clean_param($conv->messages[0]->text, PARAM_NOTAGS) : null;
eb35e0b1
JD
582 $data->messageid = $conv->messages[0]->id ?? null;
583 $data->isonline = $conv->members[$otheruser->id]->isonline ?? null;
584 $data->isblocked = $conv->members[$otheruser->id]->isblocked ?? null;
585 $data->isread = $conv->isread;
586 $data->unreadcount = $conv->unreadcount;
587 $tmp[$data->userid] = $data;
588 }
589 return $tmp;
590 }
eda6bc19 591}