MDL-56139 message: ajax poll for new messages in message area
[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
de55cb1b 46 * @return array
cd03b8d7
MN
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.
de55cb1b 98 $conversations = array();
cd03b8d7
MN
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 110 $message->messageid = $message->id;
de55cb1b 111 $conversations[] = helper::create_contact($message, $prefix);
cd03b8d7
MN
112 }
113 }
114
de55cb1b 115 return $conversations;
cd03b8d7
MN
116 }
117
118 /**
48e8bdba 119 * Handles searching for user in a particular course in the message area.
cd03b8d7
MN
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
de55cb1b 126 * @return array
cd03b8d7 127 */
48e8bdba 128 public static function search_users_in_course($userid, $courseid, $search, $limitfrom = 0, $limitnum = 0) {
cd03b8d7
MN
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) {
de55cb1b 151 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
152 }
153 }
154
de55cb1b 155 return $contacts;
cd03b8d7
MN
156 }
157
158 /**
48e8bdba 159 * Handles searching for user in the message area.
cd03b8d7
MN
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
de55cb1b 164 * @return array
cd03b8d7 165 */
48e8bdba 166 public static function search_users($userid, $search, $limitnum = 0) {
cd03b8d7
MN
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 193 foreach ($users as $user) {
de55cb1b 194 $contacts[] = helper::create_contact($user);
cd03b8d7
MN
195 }
196 }
197
198 // Now, let's get the courses.
f3249577
AG
199 // Make sure to limit searches to enrolled courses.
200 $enrolledcourses = enrol_get_my_courses(array('id', 'cacherev'));
cd03b8d7 201 $courses = array();
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 *
242 * @param int $userid The user id
879e2bef
MN
243 * @param int $limitfrom
244 * @param int $limitnum
de55cb1b 245 * @return array
879e2bef 246 */
de55cb1b
MN
247 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 0) {
248 $arrconversations = array();
879e2bef
MN
249 if ($conversations = message_get_recent_conversations($userid, $limitfrom, $limitnum)) {
250 foreach ($conversations as $conversation) {
de55cb1b 251 $arrconversations[$conversation->id] = helper::create_contact($conversation);
879e2bef
MN
252 }
253 }
254
de55cb1b 255 return $arrconversations;
879e2bef
MN
256 }
257
258 /**
259 * Returns the contacts to display in the contacts area.
260 *
261 * @param int $userid The user id
262 * @param int $limitfrom
263 * @param int $limitnum
de55cb1b 264 * @return array
879e2bef
MN
265 */
266 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
267 global $DB;
268
269 $arrcontacts = array();
dd0c1403 270 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
271 FROM {message_contacts} mc
272 JOIN {user} u
273 ON mc.contactid = u.id
274 WHERE mc.userid = :userid
275 AND u.deleted = 0
276 ORDER BY " . $DB->sql_fullname();
277 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
278 foreach ($contacts as $contact) {
de55cb1b 279 $arrcontacts[] = helper::create_contact($contact);
879e2bef
MN
280 }
281 }
282
de55cb1b 283 return $arrcontacts;
879e2bef
MN
284 }
285
286 /**
287 * Returns the messages to display in the message area.
288 *
289 * @param int $userid the current user
290 * @param int $otheruserid the other user
291 * @param int $limitfrom
292 * @param int $limitnum
8ec78c48 293 * @param string $sort
fb1469d8
RW
294 * @param int $createdfrom the timestamp from which the messages were created
295 * @param int $createdto the time up until which the message was created
de55cb1b 296 * @return array
879e2bef 297 */
fb1469d8
RW
298 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0,
299 $sort = 'timecreated ASC', $createdfrom = 0, $createdto = 0) {
300
301 if (!empty($createdfrom)) {
302 // Check the cache to see if we even need to do a DB query.
303 $cache = \cache::make('core', 'message_last_created');
304 $ids = [$otheruserid, $userid];
305 sort($ids);
306 $key = implode('_', $ids);
307 $lastcreated = $cache->get($key);
308
309 // The last known message time is earlier than the one being requested so we can
310 // just return an empty result set rather than having to query the DB.
311 if ($lastcreated && $lastcreated < $createdfrom) {
312 return [];
313 }
314 }
315
879e2bef 316 $arrmessages = array();
fb1469d8
RW
317 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum,
318 $sort, $createdfrom, $createdto)) {
319
de55cb1b 320 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
321 }
322
de55cb1b 323 return $arrmessages;
879e2bef 324 }
c060cd49
MN
325
326 /**
327 * Returns the most recent message between two users.
328 *
329 * @param int $userid the current user
330 * @param int $otheruserid the other user
de55cb1b 331 * @return \stdClass|null
c060cd49
MN
332 */
333 public static function get_most_recent_message($userid, $otheruserid) {
334 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 335 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
336 // Swap the order so we now have them in historical order.
337 $messages = array_reverse($messages);
de55cb1b 338 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
339 return array_pop($arrmessages);
340 }
341
342 return null;
343 }
c6e97f54
MN
344
345 /**
346 * Returns the profile information for a contact for a user.
347 *
348 * @param int $userid The user id
349 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 350 * @return \stdClass
c6e97f54
MN
351 */
352 public static function get_profile($userid, $otheruserid) {
353 global $CFG, $DB;
354
355 require_once($CFG->dirroot . '/user/lib.php');
356
357 if ($user = \core_user::get_user($otheruserid)) {
358 // Create the data we are going to pass to the renderable.
359 $userfields = user_get_user_details($user, null, array('city', 'country', 'email',
bf58081d 360 'profileimageurl', 'profileimageurlsmall', 'lastaccess'));
edac7c80
DW
361 if ($userfields) {
362 $data = new \stdClass();
363 $data->userid = $userfields['id'];
364 $data->fullname = $userfields['fullname'];
365 $data->city = isset($userfields['city']) ? $userfields['city'] : '';
366 $data->country = isset($userfields['country']) ? $userfields['country'] : '';
367 $data->email = isset($userfields['email']) ? $userfields['email'] : '';
368 $data->profileimageurl = isset($userfields['profileimageurl']) ? $userfields['profileimageurl'] : '';
7b55aaa1
MN
369 if (isset($userfields['profileimageurlsmall'])) {
370 $data->profileimageurlsmall = $userfields['profileimageurlsmall'];
371 } else {
372 $data->profileimageurlsmall = '';
373 }
edac7c80 374 if (isset($userfields['lastaccess'])) {
de55cb1b 375 $data->isonline = helper::is_online($userfields['lastaccess']);
edac7c80 376 } else {
1f64514d 377 $data->isonline = false;
edac7c80 378 }
bf58081d 379 } else {
edac7c80
DW
380 // Technically the access checks in user_get_user_details are correct,
381 // but messaging has never obeyed them. In order to keep messaging working
382 // we at least need to return a minimal user record.
383 $data = new \stdClass();
384 $data->userid = $otheruserid;
385 $data->fullname = fullname($user);
386 $data->city = '';
387 $data->country = '';
388 $data->email = '';
389 $data->profileimageurl = '';
390 $data->profileimageurlsmall = '';
1f64514d 391 $data->isonline = false;
bf58081d 392 }
c6e97f54
MN
393 // Check if the contact has been blocked.
394 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
395 if ($contact) {
1f64514d 396 $data->isblocked = (bool) $contact->blocked;
c6e97f54
MN
397 $data->iscontact = true;
398 } else {
399 $data->isblocked = false;
400 $data->iscontact = false;
401 }
402
de55cb1b 403 return $data;
c6e97f54
MN
404 }
405 }
dec0cd99
MN
406
407 /**
408 * Checks if a user can delete messages they have either received or sent.
409 *
410 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
411 * but will still seem as if it was by the user)
1f64514d 412 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99
MN
413 */
414 public static function can_delete_conversation($userid) {
415 global $USER;
416
417 $systemcontext = \context_system::instance();
418
1f64514d 419 // Let's check if the user is allowed to delete this conversation.
dec0cd99
MN
420 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
421 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
422 $USER->id == $userid))) {
423 return true;
424 }
425
426 return false;
427 }
428
429 /**
430 * Deletes a conversation.
431 *
432 * This function does not verify any permissions.
433 *
434 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
435 * but will still seem as if it was by the user)
436 * @param int $otheruserid The id of the other user in the conversation
437 * @return bool
438 */
439 public static function delete_conversation($userid, $otheruserid) {
1f64514d 440 global $DB;
dec0cd99
MN
441
442 // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
443 // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
444 // This won't be a particularly heavily used function (at least I hope not), so let's hope MDL-36941 gets worked on
445 // soon for the sake of any developers' sanity when dealing with the messaging system.
446 $now = time();
447 $sql = "UPDATE {message}
448 SET timeuserfromdeleted = :time
449 WHERE useridfrom = :userid
450 AND useridto = :otheruserid
451 AND notification = 0";
452 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
453
454 $sql = "UPDATE {message}
455 SET timeusertodeleted = :time
456 WHERE useridto = :userid
457 AND useridfrom = :otheruserid
458 AND notification = 0";
459 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
460
461 $sql = "UPDATE {message_read}
462 SET timeuserfromdeleted = :time
463 WHERE useridfrom = :userid
464 AND useridto = :otheruserid
465 AND notification = 0";
466 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
467
468 $sql = "UPDATE {message_read}
469 SET timeusertodeleted = :time
470 WHERE useridto = :userid
471 AND useridfrom = :otheruserid
472 AND notification = 0";
473 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
474
475 // Now we need to trigger events for these.
de55cb1b 476 if ($messages = helper::get_messages($userid, $otheruserid, $now)) {
dec0cd99
MN
477 // Loop through and trigger a deleted event.
478 foreach ($messages as $message) {
479 $messagetable = 'message';
480 if (!empty($message->timeread)) {
481 $messagetable = 'message_read';
482 }
483
484 // Trigger event for deleting the message.
485 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1f64514d 486 $userid, $messagetable, $message->id)->trigger();
dec0cd99
MN
487 }
488 }
489
490 return true;
491 }
79f6c36c
MN
492
493 /**
494 * Returns the count of unread conversations (collection of messages from a single user) for
495 * the given user.
496 *
497 * @param \stdClass $user the user who's conversations should be counted
498 * @return int the count of the user's unread conversations
499 */
500 public static function count_unread_conversations($user = null) {
501 global $USER, $DB;
502
503 if (empty($user)) {
504 $user = $USER;
505 }
506
507 return $DB->count_records_select(
508 'message',
509 'useridto = ? AND timeusertodeleted = 0 AND notification = 0',
510 [$user->id],
511 "COUNT(DISTINCT(useridfrom))");
512 }
513
514 /**
515 * Marks ALL messages being sent from $fromuserid to $touserid as read.
516 *
517 * Can be filtered by type.
518 *
519 * @param int $touserid the id of the message recipient
520 * @param int $fromuserid the id of the message sender
521 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
522 * @return void
523 */
524 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
525 global $DB;
526
527 $params = array();
528
529 if (!empty($touserid)) {
530 $params['useridto'] = $touserid;
531 }
532
533 if (!empty($fromuserid)) {
534 $params['useridfrom'] = $fromuserid;
535 }
536
537 if (!empty($type)) {
538 if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) {
539 $params['notification'] = 1;
540 } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) {
541 $params['notification'] = 0;
542 }
543 }
544
dff7c82e 545 $messages = $DB->get_recordset('message', $params);
79f6c36c
MN
546
547 foreach ($messages as $message) {
548 message_mark_message_read($message, time());
549 }
550
551 $messages->close();
552 }
553
79f6c36c
MN
554 /**
555 * Returns message preferences.
556 *
557 * @param array $processors
558 * @param array $providers
559 * @param \stdClass $user
560 * @return \stdClass
561 * @since 3.2
562 */
563 public static function get_all_message_preferences($processors, $providers, $user) {
564 $preferences = helper::get_providers_preferences($providers, $user->id);
565 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
566
567 // For every processors put its options on the form (need to get function from processor's lib.php).
568 foreach ($processors as $processor) {
569 $processor->object->load_data($preferences, $user->id);
570 }
571
572 // Load general messaging preferences.
573 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
574 $preferences->mailformat = $user->mailformat;
575 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
576
577 return $preferences;
578 }
5b0769db
MN
579
580 /**
581 * Count the number of users blocked by a user.
582 *
583 * @param \stdClass $user The user object
584 * @return int the number of blocked users
585 */
586 public static function count_blocked_users($user = null) {
587 global $USER, $DB;
588
589 if (empty($user)) {
590 $user = $USER;
591 }
592
593 $sql = "SELECT count(mc.id)
594 FROM {message_contacts} mc
595 WHERE mc.userid = :userid AND mc.blocked = 1";
596 return $DB->count_records_sql($sql, array('userid' => $user->id));
597 }
598
599 /**
600 * Determines if a user is permitted to send another user a private message.
601 * If no sender is provided then it defaults to the logged in user.
602 *
603 * @param \stdClass $recipient The user object.
604 * @param \stdClass|null $sender The user object.
605 * @return bool true if user is permitted, false otherwise.
606 */
607 public static function can_post_message($recipient, $sender = null) {
608 global $USER;
609
610 if (is_null($sender)) {
611 // The message is from the logged in user, unless otherwise specified.
612 $sender = $USER;
613 }
614
615 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
616 return false;
617 }
618
619 // The recipient blocks messages from non-contacts and the
620 // sender isn't a contact.
621 if (self::is_user_non_contact_blocked($recipient, $sender)) {
622 return false;
623 }
624
625 // The recipient has specifically blocked this sender.
626 if (self::is_user_blocked($recipient, $sender)) {
627 return false;
628 }
629
630 return true;
631 }
632
633 /**
634 * Checks if the recipient is allowing messages from users that aren't a
635 * contact. If not then it checks to make sure the sender is in the
636 * recipient's contacts.
637 *
638 * @param \stdClass $recipient The user object.
639 * @param \stdClass|null $sender The user object.
640 * @return bool true if $sender is blocked, false otherwise.
641 */
642 public static function is_user_non_contact_blocked($recipient, $sender = null) {
643 global $USER, $DB;
644
645 if (is_null($sender)) {
646 // The message is from the logged in user, unless otherwise specified.
647 $sender = $USER;
648 }
649
650 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
651 if (!empty($blockednoncontacts)) {
652 // Confirm the sender is a contact of the recipient.
653 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
654 if ($exists) {
655 // All good, the recipient is a contact of the sender.
656 return false;
657 } else {
658 // Oh no, the recipient is not a contact. Looks like we can't send the message.
659 return true;
660 }
661 }
662
663 return false;
664 }
665
666 /**
667 * Checks if the recipient has specifically blocked the sending user.
668 *
669 * Note: This function will always return false if the sender has the
670 * readallmessages capability at the system context level.
671 *
672 * @param object $recipient User object.
673 * @param object $sender User object.
674 * @return bool true if $sender is blocked, false otherwise.
675 */
676 public static function is_user_blocked($recipient, $sender = null) {
677 global $USER, $DB;
678
679 if (is_null($sender)) {
680 // The message is from the logged in user, unless otherwise specified.
681 $sender = $USER;
682 }
683
684 $systemcontext = \context_system::instance();
685 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender)) {
686 return false;
687 }
688
689 if ($contact = $DB->get_record('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id))) {
690 if ($contact->blocked) {
691 return true;
692 }
693 }
694
695 return false;
696 }
20ab51fd
AA
697
698 /**
699 * Get specified message processor, validate corresponding plugin existence and
700 * system configuration.
701 *
702 * @param string $name Name of the processor.
703 * @param bool $ready only return ready-to-use processors.
704 * @return mixed $processor if processor present else empty array.
705 * @since Moodle 3.2
706 */
707 public static function get_message_processor($name, $ready = false) {
708 global $DB, $CFG;
709
710 $processor = $DB->get_record('message_processors', array('name' => $name));
711 if (empty($processor)) {
712 // Processor not found, return.
713 return array();
714 }
715
716 $processor = self::get_processed_processor_object($processor);
717 if ($ready) {
718 if ($processor->enabled && $processor->configured) {
719 return $processor;
720 } else {
721 return array();
722 }
723 } else {
724 return $processor;
725 }
726 }
727
728 /**
729 * Returns weather a given processor is enabled or not.
730 * Note:- This doesn't check if the processor is configured or not.
731 *
732 * @param string $name Name of the processor
733 * @return bool
734 */
735 public static function is_processor_enabled($name) {
736
737 $cache = \cache::make('core', 'message_processors_enabled');
738 $status = $cache->get($name);
739
740 if ($status === false) {
741 $processor = self::get_message_processor($name);
742 if (!empty($processor)) {
743 $cache->set($name, $processor->enabled);
744 return $processor->enabled;
745 } else {
746 return false;
747 }
748 }
749
750 return $status;
751 }
752
753 /**
754 * Set status of a processor.
755 *
756 * @param \stdClass $processor processor record.
757 * @param 0|1 $enabled 0 or 1 to set the processor status.
758 * @return bool
759 * @since Moodle 3.2
760 */
761 public static function update_processor_status($processor, $enabled) {
762 global $DB;
763 $cache = \cache::make('core', 'message_processors_enabled');
764 $cache->delete($processor->name);
765 return $DB->set_field('message_processors', 'enabled', $enabled, array('id' => $processor->id));
766 }
767
768 /**
769 * Given a processor object, loads information about it's settings and configurations.
770 * This is not a public api, instead use @see \core_message\api::get_message_processor()
771 * or @see \get_message_processors()
772 *
773 * @param \stdClass $processor processor object
774 * @return \stdClass processed processor object
775 * @since Moodle 3.2
776 */
777 public static function get_processed_processor_object(\stdClass $processor) {
778 global $CFG;
779
780 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
781 if (is_readable($processorfile)) {
782 include_once($processorfile);
783 $processclass = 'message_output_' . $processor->name;
784 if (class_exists($processclass)) {
785 $pclass = new $processclass();
786 $processor->object = $pclass;
787 $processor->configured = 0;
788 if ($pclass->is_system_configured()) {
789 $processor->configured = 1;
790 }
791 $processor->hassettings = 0;
792 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
793 $processor->hassettings = 1;
794 }
795 $processor->available = 1;
796 } else {
797 print_error('errorcallingprocessor', 'message');
798 }
799 } else {
800 $processor->available = 0;
801 }
802 return $processor;
803 }
879e2bef 804}