MDL-63466 core_message: deprecated methods and services
[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
205 // We always view messages from oldest to newest, ensure we have it in that order.
206 $lastmessage = end($messages);
207 $firstmessage = reset($messages);
208 if ($lastmessage->timecreated < $firstmessage->timecreated) {
209 $messages = array_reverse($messages);
210 }
211
212 foreach ($messages as $message) {
213 // Store the message information.
214 $msg = new \stdClass();
215 $msg->id = $message->id;
216 $msg->useridfrom = $message->useridfrom;
217 $msg->text = message_format_message_text($message);
218 $msg->timecreated = $message->timecreated;
219 $arrmessages[] = $msg;
220 }
221 // Add the messages to the conversation.
222 $conversation['messages'] = $arrmessages;
223
224 // Get the users who have sent any of the $messages.
225 $memberids = array_unique(array_map(function($message) {
226 return $message->useridfrom;
227 }, $messages));
228 // Get members information.
229 $arrmembers = self::get_member_info($userid, $memberids);
230 // Add the members to the conversation.
231 $conversation['members'] = $arrmembers;
232
233 return $conversation;
234 }
235
879e2bef 236 /**
de55cb1b 237 * Helper function to return an array of messages.
879e2bef 238 *
d1e8e69d 239 * @deprecated since 3.6
879e2bef
MN
240 * @param int $userid
241 * @param array $messages
de55cb1b 242 * @return array
879e2bef
MN
243 */
244 public static function create_messages($userid, $messages) {
d1e8e69d
MN
245 debugging('\core_message\helper::create_messages() is deprecated, please use ' .
246 '\core_message\helper::create_conversation_messages() instead.', DEBUG_DEVELOPER);
247
879e2bef
MN
248 // Store the messages.
249 $arrmessages = array();
250
8ec78c48
MN
251 // We always view messages from oldest to newest, ensure we have it in that order.
252 $lastmessage = end($messages);
253 $firstmessage = reset($messages);
254 if ($lastmessage->timecreated < $firstmessage->timecreated) {
255 $messages = array_reverse($messages);
256 }
257
879e2bef
MN
258 // Keeps track of the last day, month and year combo we were viewing.
259 $day = '';
260 $month = '';
261 $year = '';
262 foreach ($messages as $message) {
263 // Check if we are now viewing a different block period.
3090f52f 264 $displayblocktime = false;
879e2bef
MN
265 $date = usergetdate($message->timecreated);
266 if ($day != $date['mday'] || $month != $date['month'] || $year != $date['year']) {
267 $day = $date['mday'];
268 $month = $date['month'];
269 $year = $date['year'];
3090f52f 270 $displayblocktime = true;
879e2bef
MN
271 }
272 // Store the message to pass to the renderable.
273 $msg = new \stdClass();
3090f52f 274 $msg->id = $message->id;
879e2bef
MN
275 $msg->text = message_format_message_text($message);
276 $msg->currentuserid = $userid;
277 $msg->useridfrom = $message->useridfrom;
278 $msg->useridto = $message->useridto;
3090f52f 279 $msg->displayblocktime = $displayblocktime;
879e2bef 280 $msg->timecreated = $message->timecreated;
3090f52f 281 $msg->timeread = $message->timeread;
de55cb1b 282 $arrmessages[] = $msg;
879e2bef
MN
283 }
284
285 return $arrmessages;
286 }
287
288 /**
de55cb1b 289 * Helper function for creating a contact object.
879e2bef
MN
290 *
291 * @param \stdClass $contact
cd03b8d7 292 * @param string $prefix
de55cb1b 293 * @return \stdClass
879e2bef 294 */
cd03b8d7 295 public static function create_contact($contact, $prefix = '') {
bf58081d 296 global $PAGE;
879e2bef
MN
297
298 // Create the data we are going to pass to the renderable.
cd03b8d7 299 $userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix);
879e2bef
MN
300 $data = new \stdClass();
301 $data->userid = $userfields->id;
89a70ba1 302 $data->useridfrom = null;
879e2bef
MN
303 $data->fullname = fullname($userfields);
304 // Get the user picture data.
305 $userpicture = new \user_picture($userfields);
306 $userpicture->size = 1; // Size f1.
307 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
308 $userpicture->size = 0; // Size f2.
309 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
310 // Store the message if we have it.
5bf0ff27 311 $data->ismessaging = false;
cd03b8d7
MN
312 $data->lastmessage = null;
313 $data->messageid = null;
879e2bef 314 if (isset($contact->smallmessage)) {
5bf0ff27 315 $data->ismessaging = true;
54d83992
RW
316 // Strip the HTML tags from the message for displaying in the contact area.
317 $data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS);
89a70ba1 318 $data->useridfrom = $contact->useridfrom;
cd03b8d7
MN
319 if (isset($contact->messageid)) {
320 $data->messageid = $contact->messageid;
321 }
879e2bef 322 }
cb805753
MN
323 $data->isonline = null;
324 if (self::show_online_status($userfields)) {
325 $data->isonline = self::is_online($userfields->lastaccess);
326 }
1f64514d
MN
327 $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
328 $data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
c33b7d89 329 $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
879e2bef 330
de55cb1b 331 return $data;
879e2bef 332 }
bf58081d 333
cb805753
MN
334 /**
335 * Helper function for checking if we should show the user's online status.
336 *
337 * @param \stdClass $user
338 * @return boolean
339 */
340 public static function show_online_status($user) {
341 global $CFG;
342
343 require_once($CFG->dirroot . '/user/lib.php');
344
345 if ($lastaccess = user_get_user_details($user, null, array('lastaccess'))) {
346 if (isset($lastaccess['lastaccess'])) {
347 return true;
348 }
349 }
350
351 return false;
352 }
353
bf58081d
MN
354 /**
355 * Helper function for checking the time meets the 'online' condition.
356 *
357 * @param int $lastaccess
358 * @return boolean
359 */
360 public static function is_online($lastaccess) {
361 global $CFG;
362
363 // Variable to check if we consider this user online or not.
364 $timetoshowusers = 300; // Seconds default.
365 if (isset($CFG->block_online_users_timetosee)) {
366 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
367 }
368 $time = time() - $timetoshowusers;
369
370 return $lastaccess >= $time;
371 }
79f6c36c
MN
372
373 /**
374 * Get providers preferences.
375 *
376 * @param array $providers
377 * @param int $userid
378 * @return \stdClass
379 */
380 public static function get_providers_preferences($providers, $userid) {
381 $preferences = new \stdClass();
382
383 // Get providers preferences.
384 foreach ($providers as $provider) {
385 foreach (array('loggedin', 'loggedoff') as $state) {
386 $linepref = get_user_preferences('message_provider_' . $provider->component . '_' . $provider->name
387 . '_' . $state, '', $userid);
388 if ($linepref == '') {
389 continue;
390 }
391 $lineprefarray = explode(',', $linepref);
392 $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array();
393 foreach ($lineprefarray as $pref) {
394 $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1;
395 }
396 }
397 }
398
399 return $preferences;
400 }
401
402 /**
403 * Requires the JS libraries for the toggle contact button.
404 *
405 * @return void
406 */
407 public static function togglecontact_requirejs() {
408 global $PAGE;
409
410 static $done = false;
411 if ($done) {
412 return;
413 }
414
415 $PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button'));
416 $done = true;
417 }
418
419 /**
420 * Returns the attributes to place on a contact button.
421 *
422 * @param object $user User object.
423 * @param bool $iscontact
424 * @return array
425 */
426 public static function togglecontact_link_params($user, $iscontact = false) {
427 $params = array(
428 'data-userid' => $user->id,
429 'data-is-contact' => $iscontact,
430 'id' => 'toggle-contact-button',
431 'role' => 'button',
432 'class' => 'ajax-contact-button',
433 );
434
435 return $params;
436 }
ffd7798c 437
b2cd17e6
MN
438 /**
439 * Returns the conversation hash between users for easy look-ups in the DB.
440 *
441 * @param array $userids
442 * @return string
443 */
444 public static function get_conversation_hash(array $userids) {
445 sort($userids);
446
447 return sha1(implode('-', $userids));
448 }
449
78348dfc
MN
450 /**
451 * Checks if legacy messages exist for a given user.
452 *
453 * @param int $userid
454 * @return bool
455 */
456 public static function legacy_messages_exist($userid) {
457 global $DB;
458
459 $sql = "SELECT id
460 FROM {message} m
461 WHERE useridfrom = ?
462 OR useridto = ?";
463 $messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);
464
465 $sql = "SELECT id
466 FROM {message_read} m
467 WHERE useridfrom = ?
468 OR useridto = ?";
469 $messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);
470
471 return $messageexists || $messagereadexists;
472 }
2a2b86f1
JD
473
474 /**
475 * Returns conversation member info for the supplied users, relative to the supplied referenceuserid.
476 *
477 * This is the basic structure used when returning members, and includes information about the relationship between each member
478 * and the referenceuser, such as a whether the referenceuser has marked the member as a contact, or has blocked them.
479 *
480 * @param int $referenceuserid the id of the user which check contact and blocked status.
481 * @param array $userids
482 * @return array the array of objects containing member info, indexed by userid.
483 * @throws \coding_exception
484 * @throws \dml_exception
485 */
486 public static function get_member_info(int $referenceuserid, array $userids) : array {
487 global $DB, $PAGE;
488
489 list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
490 $userfields = \user_picture::fields('u', array('lastaccess'));
491 $userssql = "SELECT $userfields, mc.id AS contactid, mub.id AS blockedid
492 FROM {user} u
493 LEFT JOIN {message_contacts} mc
494 ON (mc.userid = ? AND mc.contactid = u.id)
495 LEFT JOIN {message_users_blocked} mub
496 ON (mub.userid = ? AND mub.blockeduserid = u.id)
497 WHERE u.id $useridsql
498 AND u.deleted = 0";
499 $usersparams = array_merge([$referenceuserid, $referenceuserid], $usersparams);
500 $otherusers = $DB->get_records_sql($userssql, $usersparams);
501
502 $members = [];
503 foreach ($otherusers as $member) {
504 // Set basic data.
505 $data = new \stdClass();
506 $data->id = $member->id;
507 $data->fullname = fullname($member);
508
509 // Set the user picture data.
510 $userpicture = new \user_picture($member);
511 $userpicture->size = 1; // Size f1.
512 $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
513 $userpicture->size = 0; // Size f2.
514 $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
515
516 // Set online status indicators.
517 $data->isonline = self::show_online_status($member) ? self::is_online($member->lastaccess) : null;
518 $data->showonlinestatus = is_null($data->isonline) ? false : true;
519
520 // Set contact and blocked status indicators.
521 $data->iscontact = ($member->contactid) ? true : false;
522 $data->isblocked = ($member->blockedid) ? true : false;
523
524 $members[$data->id] = $data;
525 }
526 return $members;
527 }
eda6bc19 528}