Merge branch 'wip-MDL-56625-master' of git://github.com/abgreeve/moodle
[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.
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 226 foreach ($users as $user) {
de55cb1b 227 $noncontacts[] = helper::create_contact($user);
cd03b8d7
MN
228 }
229 }
230
de55cb1b 231 return array($contacts, $courses, $noncontacts);
cd03b8d7
MN
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
879e2bef
MN
238 * @param int $limitfrom
239 * @param int $limitnum
de55cb1b 240 * @return array
879e2bef 241 */
de55cb1b
MN
242 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 0) {
243 $arrconversations = array();
879e2bef
MN
244 if ($conversations = message_get_recent_conversations($userid, $limitfrom, $limitnum)) {
245 foreach ($conversations as $conversation) {
de55cb1b 246 $arrconversations[$conversation->id] = helper::create_contact($conversation);
879e2bef
MN
247 }
248 }
249
de55cb1b 250 return $arrconversations;
879e2bef
MN
251 }
252
253 /**
254 * Returns the contacts to display in the contacts area.
255 *
256 * @param int $userid The user id
257 * @param int $limitfrom
258 * @param int $limitnum
de55cb1b 259 * @return array
879e2bef
MN
260 */
261 public static function get_contacts($userid, $limitfrom = 0, $limitnum = 0) {
262 global $DB;
263
264 $arrcontacts = array();
dd0c1403 265 $sql = "SELECT u.*, mc.blocked
879e2bef
MN
266 FROM {message_contacts} mc
267 JOIN {user} u
268 ON mc.contactid = u.id
269 WHERE mc.userid = :userid
270 AND u.deleted = 0
271 ORDER BY " . $DB->sql_fullname();
272 if ($contacts = $DB->get_records_sql($sql, array('userid' => $userid), $limitfrom, $limitnum)) {
273 foreach ($contacts as $contact) {
de55cb1b 274 $arrcontacts[] = helper::create_contact($contact);
879e2bef
MN
275 }
276 }
277
de55cb1b 278 return $arrcontacts;
879e2bef
MN
279 }
280
281 /**
282 * Returns the messages to display in the message area.
283 *
284 * @param int $userid the current user
285 * @param int $otheruserid the other user
286 * @param int $limitfrom
287 * @param int $limitnum
8ec78c48 288 * @param string $sort
de55cb1b 289 * @return array
879e2bef 290 */
8ec78c48 291 public static function get_messages($userid, $otheruserid, $limitfrom = 0, $limitnum = 0, $sort = 'timecreated ASC') {
879e2bef 292 $arrmessages = array();
de55cb1b
MN
293 if ($messages = helper::get_messages($userid, $otheruserid, 0, $limitfrom, $limitnum, $sort)) {
294 $arrmessages = helper::create_messages($userid, $messages);
879e2bef
MN
295 }
296
de55cb1b 297 return $arrmessages;
879e2bef 298 }
c060cd49
MN
299
300 /**
301 * Returns the most recent message between two users.
302 *
303 * @param int $userid the current user
304 * @param int $otheruserid the other user
de55cb1b 305 * @return \stdClass|null
c060cd49
MN
306 */
307 public static function get_most_recent_message($userid, $otheruserid) {
308 // We want two messages here so we get an accurate 'blocktime' value.
de55cb1b 309 if ($messages = helper::get_messages($userid, $otheruserid, 0, 0, 2, 'timecreated DESC')) {
c060cd49
MN
310 // Swap the order so we now have them in historical order.
311 $messages = array_reverse($messages);
de55cb1b 312 $arrmessages = helper::create_messages($userid, $messages);
c060cd49
MN
313 return array_pop($arrmessages);
314 }
315
316 return null;
317 }
c6e97f54
MN
318
319 /**
320 * Returns the profile information for a contact for a user.
321 *
322 * @param int $userid The user id
323 * @param int $otheruserid The id of the user whose profile we want to view.
de55cb1b 324 * @return \stdClass
c6e97f54
MN
325 */
326 public static function get_profile($userid, $otheruserid) {
327 global $CFG, $DB;
328
329 require_once($CFG->dirroot . '/user/lib.php');
330
331 if ($user = \core_user::get_user($otheruserid)) {
332 // Create the data we are going to pass to the renderable.
333 $userfields = user_get_user_details($user, null, array('city', 'country', 'email',
bf58081d 334 'profileimageurl', 'profileimageurlsmall', 'lastaccess'));
edac7c80
DW
335 if ($userfields) {
336 $data = new \stdClass();
337 $data->userid = $userfields['id'];
338 $data->fullname = $userfields['fullname'];
339 $data->city = isset($userfields['city']) ? $userfields['city'] : '';
340 $data->country = isset($userfields['country']) ? $userfields['country'] : '';
341 $data->email = isset($userfields['email']) ? $userfields['email'] : '';
342 $data->profileimageurl = isset($userfields['profileimageurl']) ? $userfields['profileimageurl'] : '';
7b55aaa1
MN
343 if (isset($userfields['profileimageurlsmall'])) {
344 $data->profileimageurlsmall = $userfields['profileimageurlsmall'];
345 } else {
346 $data->profileimageurlsmall = '';
347 }
edac7c80 348 if (isset($userfields['lastaccess'])) {
de55cb1b 349 $data->isonline = helper::is_online($userfields['lastaccess']);
edac7c80 350 } else {
1f64514d 351 $data->isonline = false;
edac7c80 352 }
bf58081d 353 } else {
edac7c80
DW
354 // Technically the access checks in user_get_user_details are correct,
355 // but messaging has never obeyed them. In order to keep messaging working
356 // we at least need to return a minimal user record.
357 $data = new \stdClass();
358 $data->userid = $otheruserid;
359 $data->fullname = fullname($user);
360 $data->city = '';
361 $data->country = '';
362 $data->email = '';
363 $data->profileimageurl = '';
364 $data->profileimageurlsmall = '';
1f64514d 365 $data->isonline = false;
bf58081d 366 }
c6e97f54
MN
367 // Check if the contact has been blocked.
368 $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
369 if ($contact) {
1f64514d 370 $data->isblocked = (bool) $contact->blocked;
c6e97f54
MN
371 $data->iscontact = true;
372 } else {
373 $data->isblocked = false;
374 $data->iscontact = false;
375 }
376
de55cb1b 377 return $data;
c6e97f54
MN
378 }
379 }
dec0cd99
MN
380
381 /**
382 * Checks if a user can delete messages they have either received or sent.
383 *
384 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
385 * but will still seem as if it was by the user)
1f64514d 386 * @return bool Returns true if a user can delete the conversation, false otherwise.
dec0cd99
MN
387 */
388 public static function can_delete_conversation($userid) {
389 global $USER;
390
391 $systemcontext = \context_system::instance();
392
1f64514d 393 // Let's check if the user is allowed to delete this conversation.
dec0cd99
MN
394 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
395 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
396 $USER->id == $userid))) {
397 return true;
398 }
399
400 return false;
401 }
402
403 /**
404 * Deletes a conversation.
405 *
406 * This function does not verify any permissions.
407 *
408 * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
409 * but will still seem as if it was by the user)
410 * @param int $otheruserid The id of the other user in the conversation
411 * @return bool
412 */
413 public static function delete_conversation($userid, $otheruserid) {
1f64514d 414 global $DB;
dec0cd99
MN
415
416 // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
417 // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
418 // This won't be a particularly heavily used function (at least I hope not), so let's hope MDL-36941 gets worked on
419 // soon for the sake of any developers' sanity when dealing with the messaging system.
420 $now = time();
421 $sql = "UPDATE {message}
422 SET timeuserfromdeleted = :time
423 WHERE useridfrom = :userid
424 AND useridto = :otheruserid
425 AND notification = 0";
426 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
427
428 $sql = "UPDATE {message}
429 SET timeusertodeleted = :time
430 WHERE useridto = :userid
431 AND useridfrom = :otheruserid
432 AND notification = 0";
433 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
434
435 $sql = "UPDATE {message_read}
436 SET timeuserfromdeleted = :time
437 WHERE useridfrom = :userid
438 AND useridto = :otheruserid
439 AND notification = 0";
440 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
441
442 $sql = "UPDATE {message_read}
443 SET timeusertodeleted = :time
444 WHERE useridto = :userid
445 AND useridfrom = :otheruserid
446 AND notification = 0";
447 $DB->execute($sql, array('time' => $now, 'userid' => $userid, 'otheruserid' => $otheruserid));
448
449 // Now we need to trigger events for these.
de55cb1b 450 if ($messages = helper::get_messages($userid, $otheruserid, $now)) {
dec0cd99
MN
451 // Loop through and trigger a deleted event.
452 foreach ($messages as $message) {
453 $messagetable = 'message';
454 if (!empty($message->timeread)) {
455 $messagetable = 'message_read';
456 }
457
458 // Trigger event for deleting the message.
459 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1f64514d 460 $userid, $messagetable, $message->id)->trigger();
dec0cd99
MN
461 }
462 }
463
464 return true;
465 }
79f6c36c
MN
466
467 /**
468 * Returns the count of unread conversations (collection of messages from a single user) for
469 * the given user.
470 *
471 * @param \stdClass $user the user who's conversations should be counted
472 * @return int the count of the user's unread conversations
473 */
474 public static function count_unread_conversations($user = null) {
475 global $USER, $DB;
476
477 if (empty($user)) {
478 $user = $USER;
479 }
480
481 return $DB->count_records_select(
482 'message',
483 'useridto = ? AND timeusertodeleted = 0 AND notification = 0',
484 [$user->id],
485 "COUNT(DISTINCT(useridfrom))");
486 }
487
488 /**
489 * Marks ALL messages being sent from $fromuserid to $touserid as read.
490 *
491 * Can be filtered by type.
492 *
493 * @param int $touserid the id of the message recipient
494 * @param int $fromuserid the id of the message sender
495 * @param string $type filter the messages by type, either MESSAGE_TYPE_NOTIFICATION, MESSAGE_TYPE_MESSAGE or '' for all.
496 * @return void
497 */
498 public static function mark_all_read_for_user($touserid, $fromuserid = 0, $type = '') {
499 global $DB;
500
501 $params = array();
502
503 if (!empty($touserid)) {
504 $params['useridto'] = $touserid;
505 }
506
507 if (!empty($fromuserid)) {
508 $params['useridfrom'] = $fromuserid;
509 }
510
511 if (!empty($type)) {
512 if (strtolower($type) == MESSAGE_TYPE_NOTIFICATION) {
513 $params['notification'] = 1;
514 } else if (strtolower($type) == MESSAGE_TYPE_MESSAGE) {
515 $params['notification'] = 0;
516 }
517 }
518
dff7c82e 519 $messages = $DB->get_recordset('message', $params);
79f6c36c
MN
520
521 foreach ($messages as $message) {
522 message_mark_message_read($message, time());
523 }
524
525 $messages->close();
526 }
527
79f6c36c
MN
528 /**
529 * Returns message preferences.
530 *
531 * @param array $processors
532 * @param array $providers
533 * @param \stdClass $user
534 * @return \stdClass
535 * @since 3.2
536 */
537 public static function get_all_message_preferences($processors, $providers, $user) {
538 $preferences = helper::get_providers_preferences($providers, $user->id);
539 $preferences->userdefaultemail = $user->email; // May be displayed by the email processor.
540
541 // For every processors put its options on the form (need to get function from processor's lib.php).
542 foreach ($processors as $processor) {
543 $processor->object->load_data($preferences, $user->id);
544 }
545
546 // Load general messaging preferences.
547 $preferences->blocknoncontacts = get_user_preferences('message_blocknoncontacts', '', $user->id);
548 $preferences->mailformat = $user->mailformat;
549 $preferences->mailcharset = get_user_preferences('mailcharset', '', $user->id);
550
551 return $preferences;
552 }
5b0769db
MN
553
554 /**
555 * Count the number of users blocked by a user.
556 *
557 * @param \stdClass $user The user object
558 * @return int the number of blocked users
559 */
560 public static function count_blocked_users($user = null) {
561 global $USER, $DB;
562
563 if (empty($user)) {
564 $user = $USER;
565 }
566
567 $sql = "SELECT count(mc.id)
568 FROM {message_contacts} mc
569 WHERE mc.userid = :userid AND mc.blocked = 1";
570 return $DB->count_records_sql($sql, array('userid' => $user->id));
571 }
572
573 /**
574 * Determines if a user is permitted to send another user a private message.
575 * If no sender is provided then it defaults to the logged in user.
576 *
577 * @param \stdClass $recipient The user object.
578 * @param \stdClass|null $sender The user object.
579 * @return bool true if user is permitted, false otherwise.
580 */
581 public static function can_post_message($recipient, $sender = null) {
582 global $USER;
583
584 if (is_null($sender)) {
585 // The message is from the logged in user, unless otherwise specified.
586 $sender = $USER;
587 }
588
589 if (!has_capability('moodle/site:sendmessage', \context_system::instance(), $sender)) {
590 return false;
591 }
592
593 // The recipient blocks messages from non-contacts and the
594 // sender isn't a contact.
595 if (self::is_user_non_contact_blocked($recipient, $sender)) {
596 return false;
597 }
598
599 // The recipient has specifically blocked this sender.
600 if (self::is_user_blocked($recipient, $sender)) {
601 return false;
602 }
603
604 return true;
605 }
606
607 /**
608 * Checks if the recipient is allowing messages from users that aren't a
609 * contact. If not then it checks to make sure the sender is in the
610 * recipient's contacts.
611 *
612 * @param \stdClass $recipient The user object.
613 * @param \stdClass|null $sender The user object.
614 * @return bool true if $sender is blocked, false otherwise.
615 */
616 public static function is_user_non_contact_blocked($recipient, $sender = null) {
617 global $USER, $DB;
618
619 if (is_null($sender)) {
620 // The message is from the logged in user, unless otherwise specified.
621 $sender = $USER;
622 }
623
624 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
625 if (!empty($blockednoncontacts)) {
626 // Confirm the sender is a contact of the recipient.
627 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
628 if ($exists) {
629 // All good, the recipient is a contact of the sender.
630 return false;
631 } else {
632 // Oh no, the recipient is not a contact. Looks like we can't send the message.
633 return true;
634 }
635 }
636
637 return false;
638 }
639
640 /**
641 * Checks if the recipient has specifically blocked the sending user.
642 *
643 * Note: This function will always return false if the sender has the
644 * readallmessages capability at the system context level.
645 *
646 * @param object $recipient User object.
647 * @param object $sender User object.
648 * @return bool true if $sender is blocked, false otherwise.
649 */
650 public static function is_user_blocked($recipient, $sender = null) {
651 global $USER, $DB;
652
653 if (is_null($sender)) {
654 // The message is from the logged in user, unless otherwise specified.
655 $sender = $USER;
656 }
657
658 $systemcontext = \context_system::instance();
659 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender)) {
660 return false;
661 }
662
663 if ($contact = $DB->get_record('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id))) {
664 if ($contact->blocked) {
665 return true;
666 }
667 }
668
669 return false;
670 }
879e2bef 671}