MDL-63907 core_message: Pass user object to show_online_status.
[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 316 $data->isonline = null;
4cdc9f73 317 $user = \core_user::get_user($data->userid);
318 if (self::show_online_status($user)) {
cb805753
MN
319 $data->isonline = self::is_online($userfields->lastaccess);
320 }
1f64514d
MN
321 $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
322 $data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
c33b7d89 323 $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
879e2bef 324
de55cb1b 325 return $data;
879e2bef 326 }
bf58081d 327
cb805753
MN
328 /**
329 * Helper function for checking if we should show the user's online status.
330 *
331 * @param \stdClass $user
332 * @return boolean
333 */
334 public static function show_online_status($user) {
335 global $CFG;
336
337 require_once($CFG->dirroot . '/user/lib.php');
338
339 if ($lastaccess = user_get_user_details($user, null, array('lastaccess'))) {
340 if (isset($lastaccess['lastaccess'])) {
341 return true;
342 }
343 }
344
345 return false;
346 }
347
bf58081d
MN
348 /**
349 * Helper function for checking the time meets the 'online' condition.
350 *
351 * @param int $lastaccess
352 * @return boolean
353 */
354 public static function is_online($lastaccess) {
355 global $CFG;
356
357 // Variable to check if we consider this user online or not.
358 $timetoshowusers = 300; // Seconds default.
359 if (isset($CFG->block_online_users_timetosee)) {
360 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
361 }
362 $time = time() - $timetoshowusers;
363
364 return $lastaccess >= $time;
365 }
79f6c36c
MN
366
367 /**
368 * Get providers preferences.
369 *
370 * @param array $providers
371 * @param int $userid
372 * @return \stdClass
373 */
374 public static function get_providers_preferences($providers, $userid) {
375 $preferences = new \stdClass();
376
377 // Get providers preferences.
378 foreach ($providers as $provider) {
379 foreach (array('loggedin', 'loggedoff') as $state) {
380 $linepref = get_user_preferences('message_provider_' . $provider->component . '_' . $provider->name
381 . '_' . $state, '', $userid);
382 if ($linepref == '') {
383 continue;
384 }
385 $lineprefarray = explode(',', $linepref);
386 $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array();
387 foreach ($lineprefarray as $pref) {
388 $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1;
389 }
390 }
391 }
392
393 return $preferences;
394 }
395
396 /**
397 * Requires the JS libraries for the toggle contact button.
398 *
399 * @return void
400 */
401 public static function togglecontact_requirejs() {
402 global $PAGE;
403
404 static $done = false;
405 if ($done) {
406 return;
407 }
408
409 $PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button'));
410 $done = true;
411 }
412
413 /**
414 * Returns the attributes to place on a contact button.
415 *
416 * @param object $user User object.
417 * @param bool $iscontact
418 * @return array
419 */
420 public static function togglecontact_link_params($user, $iscontact = false) {
421 $params = array(
422 'data-userid' => $user->id,
423 'data-is-contact' => $iscontact,
424 'id' => 'toggle-contact-button',
425 'role' => 'button',
426 'class' => 'ajax-contact-button',
427 );
428
429 return $params;
430 }
ffd7798c 431
b2cd17e6
MN
432 /**
433 * Returns the conversation hash between users for easy look-ups in the DB.
434 *
435 * @param array $userids
436 * @return string
437 */
438 public static function get_conversation_hash(array $userids) {
439 sort($userids);
440
441 return sha1(implode('-', $userids));
442 }
443
4699b8bc
AN
444 /**
445 * Returns the cache key for the time created value of the last message of this conversation.
446 *
447 * @param int $convid The conversation identifier.
448 * @return string The key.
449 */
450 public static function get_last_message_time_created_cache_key(int $convid) {
451 return $convid;
452 }
453
78348dfc
MN
454 /**
455 * Checks if legacy messages exist for a given user.
456 *
457 * @param int $userid
458 * @return bool
459 */
460 public static function legacy_messages_exist($userid) {
461 global $DB;
462
463 $sql = "SELECT id
464 FROM {message} m
465 WHERE useridfrom = ?
466 OR useridto = ?";
467 $messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);
468
469 $sql = "SELECT id
470 FROM {message_read} m
471 WHERE useridfrom = ?
472 OR useridto = ?";
473 $messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);
474
475 return $messageexists || $messagereadexists;
476 }
2a2b86f1
JD
477
478 /**
479 * Returns conversation member info for the supplied users, relative to the supplied referenceuserid.
480 *
481 * This is the basic structure used when returning members, and includes information about the relationship between each member
482 * and the referenceuser, such as a whether the referenceuser has marked the member as a contact, or has blocked them.
483 *
484 * @param int $referenceuserid the id of the user which check contact and blocked status.
485 * @param array $userids
486 * @return array the array of objects containing member info, indexed by userid.
487 * @throws \coding_exception
488 * @throws \dml_exception
489 */
490 public static function get_member_info(int $referenceuserid, array $userids) : array {
491 global $DB, $PAGE;
492
493 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
494 $userfields = \user_picture::fields('u', array('lastaccess'));
eb5865da 495 $userssql = "SELECT $userfields, u.deleted, mc.id AS contactid, mub.id AS blockedid
2a2b86f1
JD
496 FROM {user} u
497 LEFT JOIN {message_contacts} mc
498 ON (mc.userid = ? AND mc.contactid = u.id)
499 LEFT JOIN {message_users_blocked} mub
500 ON (mub.userid = ? AND mub.blockeduserid = u.id)
eb5865da 501 WHERE u.id $useridsql";
2a2b86f1
JD
502 $usersparams = array_merge([$referenceuserid, $referenceuserid], $usersparams);
503 $otherusers = $DB->get_records_sql($userssql, $usersparams);
504
505 $members = [];
506 foreach ($otherusers as $member) {
507 // Set basic data.
508 $data = new \stdClass();
509 $data->id = $member->id;
510 $data->fullname = fullname($member);
511
512 // Set the user picture data.
513 $userpicture = new \user_picture($member);
514 $userpicture->size = 1; // Size f1.
515 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
516 $userpicture->size = 0; // Size f2.
517 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
518
519 // Set online status indicators.
520 $data->isonline = self::show_online_status($member) ? self::is_online($member->lastaccess) : null;
521 $data->showonlinestatus = is_null($data->isonline) ? false : true;
522
523 // Set contact and blocked status indicators.
524 $data->iscontact = ($member->contactid) ? true : false;
525 $data->isblocked = ($member->blockedid) ? true : false;
526
eb5865da
JD
527 $data->isdeleted = ($member->deleted) ? true : false;
528
2a2b86f1
JD
529 $members[$data->id] = $data;
530 }
531 return $members;
532 }
eb35e0b1
JD
533
534 /**
535 * Backwards compatibility formatter, transforming the new output of get_conversations() into the old format.
536 *
537 * @param array $conversations the array of conversations, which must come from get_conversations().
538 * @return array the array of conversations, formatted in the legacy style.
539 */
540 public static function get_conversations_legacy_formatter(array $conversations) : array {
541 // Transform new data format back into the old format, just for BC during the deprecation life cycle.
542 $tmp = [];
543 foreach ($conversations as $id => $conv) {
544 $data = new \stdClass();
545 // The logic for the 'other user' is as follows:
546 // If a conversation is of type 'individual', the other user is always the member who is not the current user.
547 // If the conversation is of type 'group', the other user is always the sender of the most recent message.
548 // The get_conversations method already follows this logic, so we just need the first member.
549 $otheruser = reset($conv->members);
550 $data->userid = $otheruser->id;
551 $data->useridfrom = $conv->messages[0]->useridfrom ?? null;
552 $data->fullname = $conv->members[$otheruser->id]->fullname;
553 $data->profileimageurl = $conv->members[$otheruser->id]->profileimageurl;
554 $data->profileimageurlsmall = $conv->members[$otheruser->id]->profileimageurlsmall;
555 $data->ismessaging = isset($conv->messages[0]->text) ? true : false;
556 $data->lastmessage = $conv->messages[0]->text ?? null;
557 $data->messageid = $conv->messages[0]->id ?? null;
558 $data->isonline = $conv->members[$otheruser->id]->isonline ?? null;
559 $data->isblocked = $conv->members[$otheruser->id]->isblocked ?? null;
560 $data->isread = $conv->isread;
561 $data->unreadcount = $conv->unreadcount;
562 $tmp[$data->userid] = $data;
563 }
564 return $tmp;
565 }
eda6bc19 566}