MDL-55813 message: add online/offline help icons on preferences page
[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
cd03b8d7
MN
39 /**
40 * Handles searching for messages in the message area.
41 *
42 * @param int $userid The user id doing the searching
43 * @param string $search The string the user is searching
44 * @param int $limitfrom
45 * @param int $limitnum
46 * @return \core_message\output\messagearea\message_search_results
47 */
48 public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
49 global $DB;
50
51 // Get the user fields we want.
52 $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
53 $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
54
55 // Get all the messages for the user.
56 $sql = "SELECT m.id, m.useridfrom, m.useridto, m.subject, m.fullmessage, m.fullmessagehtml, m.fullmessageformat,
dd0c1403
MN
57 m.smallmessage, m.notification, m.timecreated, 0 as isread, $ufields, mc.blocked as userfrom_blocked,
58 $ufields2, mc2.blocked as userto_blocked
cd03b8d7
MN
59 FROM {message} m
60 JOIN {user} u
61 ON m.useridfrom = u.id
dd0c1403
MN
62 LEFT JOIN {message_contacts} mc
63 ON (mc.contactid = u.id AND mc.userid = ?)
cd03b8d7
MN
64 JOIN {user} u2
65 ON m.useridto = u2.id
dd0c1403 66 LEFT JOIN {message_contacts} mc2
7b55aaa1 67 ON (mc2.contactid = u2.id AND mc2.userid = ?)
cd03b8d7
MN
68 WHERE ((useridto = ? AND timeusertodeleted = 0)
69 OR (useridfrom = ? AND timeuserfromdeleted = 0))
70 AND notification = 0
71 AND u.deleted = 0
72 AND u2.deleted = 0
73 AND " . $DB->sql_like('smallmessage', '?', false) . "
74 UNION ALL
75 SELECT mr.id, mr.useridfrom, mr.useridto, mr.subject, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat,
dd0c1403
MN
76 mr.smallmessage, mr.notification, mr.timecreated, 1 as isread, $ufields, mc.blocked as userfrom_blocked,
77 $ufields2, mc2.blocked as userto_blocked
cd03b8d7
MN
78 FROM {message_read} mr
79 JOIN {user} u
80 ON mr.useridfrom = u.id
dd0c1403 81 LEFT JOIN {message_contacts} mc
7b55aaa1 82 ON (mc.contactid = u.id AND mc.userid = ?)
cd03b8d7
MN
83 JOIN {user} u2
84 ON mr.useridto = u2.id
dd0c1403
MN
85 LEFT JOIN {message_contacts} mc2
86 ON (mc2.contactid = u2.id AND mc2.userid = ?)
cd03b8d7
MN
87 WHERE ((useridto = ? AND timeusertodeleted = 0)
88 OR (useridfrom = ? AND timeuserfromdeleted = 0))
89 AND notification = 0
90 AND u.deleted = 0
91 AND u2.deleted = 0
92 AND " . $DB->sql_like('smallmessage', '?', false) . "
93 ORDER BY timecreated DESC";
dd0c1403
MN
94 $params = array($userid, $userid, $userid, $userid, '%' . $search . '%',
95 $userid, $userid, $userid, $userid, '%' . $search . '%');
cd03b8d7
MN
96
97 // Convert the messages into searchable contacts with their last message being the message that was searched.
98 $contacts = array();
99 if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
100 foreach ($messages as $message) {
101 $prefix = 'userfrom_';
102 if ($userid == $message->useridfrom) {
103 $prefix = 'userto_';
104 // If it from the user, then mark it as read, even if it wasn't by the receiver.
105 $message->isread = true;
106 }
dd0c1403
MN
107 $blockedcol = $prefix . 'blocked';
108 $message->blocked = $message->$blockedcol;
109
cd03b8d7
MN
110 $message->messageid = $message->id;
111 $contacts[] = \core_message\helper::create_contact($message, $prefix);
112 }
113 }
114
115 return new \core_message\output\messagearea\message_search_results($userid, $contacts);
116 }
117
118 /**
119 * Handles searching for people in a particular course in the message area.
120 *
121 * @param int $userid The user id doing the searching
122 * @param int $courseid The id of the course we are searching in
123 * @param string $search The string the user is searching
124 * @param int $limitfrom
125 * @param int $limitnum
126 * @return \core_message\output\messagearea\people_search_results
127 */
128 public static function search_people_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
129 global $DB;
130
131 // Get all the users in the course.
132 list($esql, $params) = get_enrolled_sql(\context_course::instance($courseid), '', 0, true);
dd0c1403 133 $sql = "SELECT u.*, mc.blocked
cd03b8d7 134 FROM {user} u
dd0c1403
MN
135 JOIN ($esql) je
136 ON je.id = u.id
137 LEFT JOIN {message_contacts} mc
138 ON (mc.contactid = u.id AND mc.userid = :userid)
cd03b8d7
MN
139 WHERE u.deleted = 0";
140 // Add more conditions.
141 $fullname = $DB->sql_fullname();
dd0c1403 142 $sql .= " AND u.id != :userid2
cd03b8d7
MN
143 AND " . $DB->sql_like($fullname, ':search', false) . "
144 ORDER BY " . $DB->sql_fullname();
dd0c1403 145 $params = array_merge(array('userid' => $userid, 'userid2' => $userid, 'search' => '%' . $search . '%'), $params);
cd03b8d7 146
cd03b8d7
MN
147 // Convert all the user records into contacts.
148 $contacts = array();
149 if ($users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
150 foreach ($users as $user) {
151 $contacts[] = \core_message\helper::create_contact($user);
152 }
153 }
154
155 return new \core_message\output\messagearea\people_search_results($contacts);
156 }
157
158 /**
159 * Handles searching for people in the message area.
160 *
161 * @param int $userid The user id doing the searching
162 * @param string $search The string the user is searching
163 * @param int $limitnum
164 * @return \core_message\output\messagearea\people_search_results
165 */
166 public static function search_people($userid, $search, $limitnum = 0) {
167 global $CFG, $DB;
168
169 require_once($CFG->dirroot . '/lib/coursecatlib.php');
170
171 // Used to search for contacts.
172 $fullname = $DB->sql_fullname();
173 $ufields = \user_picture::fields('u', array('lastaccess'));
174
175 // Users not to include.
176 $excludeusers = array($userid, $CFG->siteguest);
177 list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
178
179 // Ok, let's search for contacts first.
180 $contacts = array();
dd0c1403 181 $sql = "SELECT $ufields, mc.blocked
cd03b8d7
MN
182 FROM {user} u
183 JOIN {message_contacts} mc
184 ON u.id = mc.contactid
185 WHERE mc.userid = :userid
186 AND u.deleted = 0
187 AND u.confirmed = 1
188 AND " . $DB->sql_like($fullname, ':search', false) . "
189 AND u.id $exclude
190 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
191 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
192 0, $limitnum)) {
cd03b8d7
MN
193 foreach ($users as $user) {
194 $contacts[] = \core_message\helper::create_contact($user);
195 }
196 }
197
198 // Now, let's get the courses.
199 $courses = array();
200 if ($arrcourses = \coursecat::search_courses(array('search' => $search), array('limit' => $limitnum))) {
201 foreach ($arrcourses as $course) {
202 $data = new \stdClass();
203 $data->id = $course->id;
204 $data->shortname = $course->shortname;
205 $data->fullname = $course->fullname;
206 $courses[] = $data;
207 }
208 }
209
210 // Let's get those non-contacts. Toast them gears boi.
dd0c1403
MN
211 // Note - you can only block contacts, so these users will not be blocked, so no need to get that
212 // extra detail from the database.
cd03b8d7
MN
213 $noncontacts = array();
214 $sql = "SELECT $ufields
215 FROM {user} u
216 WHERE u.deleted = 0
217 AND u.confirmed = 1
218 AND " . $DB->sql_like($fullname, ':search', false) . "
219 AND u.id $exclude
7b55aaa1
MN
220 AND u.id NOT IN (SELECT contactid
221 FROM {message_contacts}
cd03b8d7
MN
222 WHERE userid = :userid)
223 ORDER BY " . $DB->sql_fullname();
7b55aaa1
MN
224 if ($users = $DB->get_records_sql($sql, array('userid' => $userid, 'search' => '%' . $search . '%') + $excludeparams,
225 0, $limitnum)) {
cd03b8d7
MN
226 foreach ($users as $user) {
227 $noncontacts[] = \core_message\helper::create_contact($user);
228 }
229 }
230
231 return new \core_message\output\messagearea\people_search_results($contacts, $courses, $noncontacts);
232 }
233
879e2bef
MN
234 /**
235 * Returns the contacts and their conversation to display in the contacts area.
236 *
237 * @param int $userid The user id
238 * @param int $otheruserid The id of the user we have selected, 0 if none have been selected
239 * @param int $limitfrom
240 * @param int $limitnum
1e5f751f 241 * @return \core_message\output\messagearea\contacts
879e2bef
MN
242 */
243 public static function get_conversations($userid, $otheruserid = 0, $limitfrom = 0, $limitnum = 0) {
244 $arrcontacts = array();
245 if ($conversations = message_get_recent_conversations($userid, $limitfrom, $limitnum)) {
246 foreach ($conversations as $conversation) {
247 $arrcontacts[] = \core_message\helper::create_contact($conversation);
248 }
249 }
250
1e5f751f 251 return new \core_message\output\messagearea\contacts($userid, $otheruserid, $arrcontacts);
879e2bef
MN
252 }
253
254 /**
255 * Returns the contacts to display in the contacts area.
256 *
257 * @param int $userid The user id
258 * @param int $limitfrom
259 * @param int $limitnum
1e5f751f 260 * @return \core_message\output\messagearea\contacts
879e2bef
MN
261 */
262 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
263 global $DB;
264
265 $arrcontacts = array();
dd0c1403 266 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
267 FROM {message_contacts} mc
268 JOIN {user} u
269 ON mc.contactid = u.id
270 WHERE mc.userid = :userid
271 AND u.deleted = 0
272 ORDER BY " . $DB->sql_fullname();
273 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
274 foreach ($contacts as $contact) {
275 $arrcontacts[] = \core_message\helper::create_contact($contact);
276 }
277 }
278
4d1b76ee 279 return new \core_message\output\messagearea\contacts($userid, 0, $arrcontacts, false);
879e2bef
MN
280 }
281
282 /**
283 * Returns the messages to display in the message area.
284 *
285 * @param int $userid the current user
286 * @param int $otheruserid the other user
287 * @param int $limitfrom
288 * @param int $limitnum
8ec78c48 289 * @param string $sort
1e5f751f 290 * @return \core_message\output\messagearea\messages
879e2bef 291 */
8ec78c48 292 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0, $sort = 'timecreated ASC') {
879e2bef 293 $arrmessages = array();
8ec78c48 294 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum, $sort)) {
879e2bef
MN
295 $arrmessages = \core_message\helper::create_messages($userid, $messages);
296 }
297
1e5f751f 298 return new \core_message\output\messagearea\messages($userid, $otheruserid, $arrmessages);
879e2bef 299 }
c060cd49
MN
300
301 /**
302 * Returns the most recent message between two users.
303 *
304 * @param int $userid the current user
305 * @param int $otheruserid the other user
1e5f751f 306 * @return \core_message\output\messagearea\message|null
c060cd49
MN
307 */
308 public static function get_most_recent_message($userid, $otheruserid) {
309 // We want two messages here so we get an accurate 'blocktime' value.
dec0cd99 310 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
311 // Swap the order so we now have them in historical order.
312 $messages = array_reverse($messages);
313 $arrmessages = \core_message\helper::create_messages($userid, $messages);
314 return array_pop($arrmessages);
315 }
316
317 return null;
318 }
c6e97f54
MN
319
320 /**
321 * Returns the profile information for a contact for a user.
322 *
323 * @param int $userid The user id
324 * @param int $otheruserid The id of the user whose profile we want to view.
1e5f751f 325 * @return \core_message\output\messagearea\profile
c6e97f54
MN
326 */
327 public static function get_profile($userid, $otheruserid) {
328 global $CFG, $DB;
329
330 require_once($CFG->dirroot . '/user/lib.php');
331
332 if ($user = \core_user::get_user($otheruserid)) {
333 // Create the data we are going to pass to the renderable.
334 $userfields = user_get_user_details($user, null, array('city', 'country', 'email',
bf58081d 335 'profileimageurl', 'profileimageurlsmall', 'lastaccess'));
edac7c80
DW
336 if ($userfields) {
337 $data = new \stdClass();
338 $data->userid = $userfields['id'];
339 $data->fullname = $userfields['fullname'];
340 $data->city = isset($userfields['city']) ? $userfields['city'] : '';
341 $data->country = isset($userfields['country']) ? $userfields['country'] : '';
342 $data->email = isset($userfields['email']) ? $userfields['email'] : '';
343 $data->profileimageurl = isset($userfields['profileimageurl']) ? $userfields['profileimageurl'] : '';
7b55aaa1
MN
344 if (isset($userfields['profileimageurlsmall'])) {
345 $data->profileimageurlsmall = $userfields['profileimageurlsmall'];
346 } else {
347 $data->profileimageurlsmall = '';
348 }
edac7c80
DW
349 if (isset($userfields['lastaccess'])) {
350 $data->isonline = \core_message\helper::is_online($userfields['lastaccess']);
351 } else {
352 $data->isonline = 0;
353 }
bf58081d 354 } else {
edac7c80
DW
355 // Technically the access checks in user_get_user_details are correct,
356 // but messaging has never obeyed them. In order to keep messaging working
357 // we at least need to return a minimal user record.
358 $data = new \stdClass();
359 $data->userid = $otheruserid;
360 $data->fullname = fullname($user);
361 $data->city = '';
362 $data->country = '';
363 $data->email = '';
364 $data->profileimageurl = '';
365 $data->profileimageurlsmall = '';
bf58081d
MN
366 $data->isonline = 0;
367 }
c6e97f54
MN
368 // Check if the contact has been blocked.
369 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
370 if ($contact) {
371 $data->isblocked = $contact->blocked;
372 $data->iscontact = true;
373 } else {
374 $data->isblocked = false;
375 $data->iscontact = false;
376 }
377
1e5f751f 378 return new \core_message\output\messagearea\profile($userid, $data);
c6e97f54
MN
379 }
380 }
dec0cd99
MN
381
382 /**
383 * Checks if a user can delete messages they have either received or sent.
384 *
385 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
386 * but will still seem as if it was by the user)
387 * @return bool Returns true if a user can delete the message, false otherwise.
388 */
389 public static function can_delete_conversation($userid) {
390 global $USER;
391
392 $systemcontext = \context_system::instance();
393
394 // Let's check if the user is allowed to delete this message.
395 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
396 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
397 $USER->id == $userid))) {
398 return true;
399 }
400
401 return false;
402 }
403
404 /**
405 * Deletes a conversation.
406 *
407 * This function does not verify any permissions.
408 *
409 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
410 * but will still seem as if it was by the user)
411 * @param int $otheruserid The id of the other user in the conversation
412 * @return bool
413 */
414 public static function delete_conversation($userid, $otheruserid) {
415 global $DB, $USER;
416
417 // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
418 // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
419 // This won't be a particularly heavily used function (at least I hope not), so let's hope MDL-36941 gets worked on
420 // soon for the sake of any developers' sanity when dealing with the messaging system.
421 $now = time();
422 $sql = "UPDATE {message}
423 SET timeuserfromdeleted = :time
424 WHERE useridfrom = :userid
425 AND useridto = :otheruserid
426 AND notification = 0";
427 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
428
429 $sql = "UPDATE {message}
430 SET timeusertodeleted = :time
431 WHERE useridto = :userid
432 AND useridfrom = :otheruserid
433 AND notification = 0";
434 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
435
436 $sql = "UPDATE {message_read}
437 SET timeuserfromdeleted = :time
438 WHERE useridfrom = :userid
439 AND useridto = :otheruserid
440 AND notification = 0";
441 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
442
443 $sql = "UPDATE {message_read}
444 SET timeusertodeleted = :time
445 WHERE useridto = :userid
446 AND useridfrom = :otheruserid
447 AND notification = 0";
448 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
449
450 // Now we need to trigger events for these.
451 if ($messages = \core_message\helper::get_messages($userid, $otheruserid, $now)) {
452 // Loop through and trigger a deleted event.
453 foreach ($messages as $message) {
454 $messagetable = 'message';
455 if (!empty($message->timeread)) {
456 $messagetable = 'message_read';
457 }
458
459 // Trigger event for deleting the message.
460 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
461 $USER->id, $messagetable, $message->id)->trigger();
462 }
463 }
464
465 return true;
466 }
79f6c36c
MN
467
468 /**
469 * Returns the count of unread conversations (collection of messages from a single user) for
470 * the given user.
471 *
472 * @param \stdClass $user the user who's conversations should be counted
473 * @return int the count of the user's unread conversations
474 */
475 public static function count_unread_conversations($user = null) {
476 global $USER, $DB;
477
478 if (empty($user)) {
479 $user = $USER;
480 }
481
482 return $DB->count_records_select(
483 'message',
484 'useridto = ? AND timeusertodeleted = 0 AND notification = 0',
485 [$user->id],
486 "COUNT(DISTINCT(useridfrom))");
487 }
488
489 /**
490 * Marks ALL messages being sent from $fromuserid to $touserid as read.
491 *
492 * Can be filtered by type.
493 *
494 * @param int $touserid the id of the message recipient
495 * @param int $fromuserid the id of the message sender
496 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
497 * @return void
498 */
499 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
500 global $DB;
501
502 $params = array();
503
504 if (!empty($touserid)) {
505 $params['useridto'] = $touserid;
506 }
507
508 if (!empty($fromuserid)) {
509 $params['useridfrom'] = $fromuserid;
510 }
511
512 if (!empty($type)) {
513 if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) {
514 $params['notification'] = 1;
515 } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) {
516 $params['notification'] = 0;
517 }
518 }
519
520 $sql = sprintf('SELECT m.* FROM {message} m WHERE m.%s = ?', implode('= ? AND m.', array_keys($params)));
521 $messages = $DB->get_recordset_sql($sql, array_values($params));
522
523 foreach ($messages as $message) {
524 message_mark_message_read($message, time());
525 }
526
527 $messages->close();
528 }
529
530 /**
531 * Get popup notifications for the specified users.
532 *
533 * @param int $useridto the user id who received the notification
534 * @param string $status MESSAGE_READ for retrieving read notifications, MESSAGE_UNREAD for unread, empty for both
535 * @param bool $embeduserto embed the to user details in the notification response
536 * @param bool $embeduserfrom embed the from user details in the notification response
537 * @param string $sort the column name to order by including optionally direction
538 * @param int $limit limit the number of result returned
539 * @param int $offset offset the result set by this amount
540 * @return array notification records
541 * @throws \moodle_exception
542 * @since 3.2
543 */
544 public static function get_popup_notifications($useridto = 0, $status = '', $embeduserto = false, $embeduserfrom = false,
545 $sort = 'DESC', $limit = 0, $offset = 0) {
546 global $DB, $USER;
547
548 if (!empty($status) && $status != MESSAGE_READ && $status != MESSAGE_UNREAD) {
549 throw new \moodle_exception(sprintf('invalid parameter: status: must be "%s" or "%s"',
550 MESSAGE_READ, MESSAGE_UNREAD));
551 }
552
553 $sort = strtoupper($sort);
554 if ($sort != 'DESC' && $sort != 'ASC') {
555 throw new \moodle_exception('invalid parameter: sort: must be "DESC" or "ASC"');
556 }
557
558 if (empty($useridto)) {
559 $useridto = $USER->id;
560 }
561
562 $params = array();
563
564 $buildtablesql = function($table, $prefix, $additionalfields, $messagestatus)
565 use ($status, $useridto, $embeduserto, $embeduserfrom) {
566
567 $joinsql = '';
568 $fields = "concat('$prefix', $prefix.id) as uniqueid, $prefix.id, $prefix.useridfrom, $prefix.useridto,
569 $prefix.subject, $prefix.fullmessage, $prefix.fullmessageformat,
570 $prefix.fullmessagehtml, $prefix.smallmessage, $prefix.notification, $prefix.contexturl,
571 $prefix.contexturlname, $prefix.timecreated, $prefix.timeuserfromdeleted, $prefix.timeusertodeleted,
572 $prefix.component, $prefix.eventtype, $additionalfields";
573 $where = " AND $prefix.useridto = :{$prefix}useridto";
574 $params = ["{$prefix}useridto" => $useridto];
575
576 if ($embeduserto) {
577 $embedprefix = "{$prefix}ut";
578 $fields .= ", " . get_all_user_name_fields(true, $embedprefix, '', 'userto');
579 $joinsql .= " LEFT JOIN {user} $embedprefix ON $embedprefix.id = $prefix.useridto";
580 }
581
582 if ($embeduserfrom) {
583 $embedprefix = "{$prefix}uf";
584 $fields .= ", " . get_all_user_name_fields(true, $embedprefix, '', 'userfrom');
585 $joinsql .= " LEFT JOIN {user} $embedprefix ON $embedprefix.id = $prefix.useridfrom";
586 }
587
588 if ($messagestatus == MESSAGE_READ) {
589 $isread = '1';
590 } else {
591 $isread = '0';
592 }
593
594 return array(
595 sprintf(
596 "SELECT %s
597 FROM %s %s %s
598 WHERE %s.notification = 1
599 AND %s.id IN (SELECT messageid FROM {message_popup} WHERE isread = %s)
600 %s",
601 $fields, $table, $prefix, $joinsql, $prefix, $prefix, $isread, $where
602 ),
603 $params
604 );
605 };
606
607 switch ($status) {
608 case MESSAGE_READ:
609 list($sql, $readparams) = $buildtablesql('{message_read}', 'r', 'r.timeread', MESSAGE_READ);
610 $params = array_merge($params, $readparams);
611 break;
612 case MESSAGE_UNREAD:
613 list($sql, $unreadparams) = $buildtablesql('{message}', 'u', '0 as timeread', MESSAGE_UNREAD);
614 $params = array_merge($params, $unreadparams);
615 break;
616 default:
617 list($readsql, $readparams) = $buildtablesql('{message_read}', 'r', 'r.timeread', MESSAGE_READ);
618 list($unreadsql, $unreadparams) = $buildtablesql('{message}', 'u', '0 as timeread', MESSAGE_UNREAD);
619 $sql = sprintf("SELECT * FROM (%s UNION %s) f", $readsql, $unreadsql);
620 $params = array_merge($params, $readparams, $unreadparams);
621 }
622
623 $sql .= " ORDER BY timecreated $sort, timeread $sort, id $sort";
624
625 return array_values($DB->get_records_sql($sql, $params, $offset, $limit));
626 }
627
628 /**
629 * Count the unread notifications for a user.
630 *
631 * @param int $useridto the user id who received the notification
632 * @return int count of the unread notifications
633 * @since 3.2
634 */
635 public static function count_unread_popup_notifications($useridto = 0) {
636 global $USER, $DB;
637
638 if (empty($useridto)) {
639 $useridto = $USER->id;
640 }
641
642 return $DB->count_records_sql(
643 "SELECT count(id)
644 FROM {message}
645 WHERE id IN (SELECT messageid FROM {message_popup} WHERE isread = 0)
646 AND useridto = ?",
647 [$useridto]
648 );
649 }
650
651 /**
652 * Returns message preferences.
653 *
654 * @param array $processors
655 * @param array $providers
656 * @param \stdClass $user
657 * @return \stdClass
658 * @since 3.2
659 */
660 public static function get_all_message_preferences($processors, $providers, $user) {
661 $preferences = helper::get_providers_preferences($providers, $user->id);
662 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
663
664 // For every processors put its options on the form (need to get function from processor's lib.php).
665 foreach ($processors as $processor) {
666 $processor->object->load_data($preferences, $user->id);
667 }
668
669 // Load general messaging preferences.
670 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
671 $preferences->mailformat = $user->mailformat;
672 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
673
674 return $preferences;
675 }
879e2bef 676}