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