2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Library functions for messaging
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define('MESSAGE_SHORTLENGTH', 300);
27 define('MESSAGE_HISTORY_ALL', 1);
29 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
31 define('MESSAGE_TYPE_NOTIFICATION', 'notification');
32 define('MESSAGE_TYPE_MESSAGE', 'message');
35 * Define contants for messaging default settings population. For unambiguity of
36 * plugin developer intentions we use 4-bit value (LSB numbering):
37 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
38 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
39 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
41 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
44 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
45 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
47 define('MESSAGE_DISALLOWED', 0x04); // 0100
48 define('MESSAGE_PERMITTED', 0x08); // 1000
49 define('MESSAGE_FORCED', 0x0c); // 1100
51 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
54 * Set default value for default outputs permitted setting
56 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
59 * Set default values for polling.
61 define('MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS', 10);
62 define('MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS', 2 * MINSECS
);
63 define('MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS', 5 * MINSECS
);
66 * Returns the count of unread messages for user. Either from a specific user or from all users.
68 * @param object $user1 the first user. Defaults to $USER
69 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
70 * @return int the count of $user1's unread messages
72 function message_count_unread_messages($user1=null, $user2=null) {
79 $sql = "SELECT COUNT(m.id)
81 INNER JOIN {message_conversations} mc
82 ON mc.id = m.conversationid
83 INNER JOIN {message_conversation_members} mcm
84 ON mcm.conversationid = mc.id
85 LEFT JOIN {message_user_actions} mua
86 ON (mua.messageid = m.id AND mua.userid = ? AND (mua.action = ? OR mua.action = ?))
89 $params = [$user1->id
, \core_message\api
::MESSAGE_ACTION_DELETED
, \core_message\api
::MESSAGE_ACTION_READ
, $user1->id
];
92 $sql .= " AND m.useridfrom = ?";
93 $params[] = $user2->id
;
95 $sql .= " AND m.useridfrom <> ?";
96 $params[] = $user1->id
;
99 return $DB->count_records_sql($sql, $params);
103 * Try to guess how to convert the message to html.
107 * @param stdClass $message
108 * @param bool $forcetexttohtml
109 * @return string html fragment
111 function message_format_message_text($message, $forcetexttohtml = false) {
112 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
114 $options = new stdClass();
115 $options->para
= false;
116 $options->blanktarget
= true;
118 $format = $message->fullmessageformat
;
120 if (strval($message->smallmessage
) !== '') {
121 if (!empty($message->notification
)) {
122 if (strval($message->fullmessagehtml
) !== '' or strval($message->fullmessage
) !== '') {
123 $format = FORMAT_PLAIN
;
126 $messagetext = $message->smallmessage
;
128 } else if ($message->fullmessageformat
== FORMAT_HTML
) {
129 if (strval($message->fullmessagehtml
) !== '') {
130 $messagetext = $message->fullmessagehtml
;
132 $messagetext = $message->fullmessage
;
133 $format = FORMAT_MOODLE
;
137 if (strval($message->fullmessage
) !== '') {
138 $messagetext = $message->fullmessage
;
140 $messagetext = $message->fullmessagehtml
;
141 $format = FORMAT_HTML
;
145 if ($forcetexttohtml) {
146 // This is a crazy hack, why not set proper format when creating the notifications?
147 if ($format === FORMAT_PLAIN
) {
148 $format = FORMAT_MOODLE
;
151 return format_text($messagetext, $format, $options);
155 * Add the selected user as a contact for the current user
157 * @param int $contactid the ID of the user to add as a contact
158 * @param int $blocked 1 if you wish to block the contact
159 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
160 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
161 * Otherwise returns the result of update_record() or insert_record()
163 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
166 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
170 if (empty($userid)) {
174 // Check if a record already exists as we may be changing blocking status.
175 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
176 // Check if blocking status has been changed.
177 if ($contact->blocked
!= $blocked) {
178 $contact->blocked
= $blocked;
179 $DB->update_record('message_contacts', $contact);
182 // Trigger event for blocking a contact.
183 $event = \core\event\message_contact_blocked
::create(array(
184 'objectid' => $contact->id
,
185 'userid' => $contact->userid
,
186 'relateduserid' => $contact->contactid
,
187 'context' => context_user
::instance($contact->userid
)
189 $event->add_record_snapshot('message_contacts', $contact);
192 // Trigger event for unblocking a contact.
193 $event = \core\event\message_contact_unblocked
::create(array(
194 'objectid' => $contact->id
,
195 'userid' => $contact->userid
,
196 'relateduserid' => $contact->contactid
,
197 'context' => context_user
::instance($contact->userid
)
199 $event->add_record_snapshot('message_contacts', $contact);
205 // No change to blocking status.
210 // New contact record.
211 $contact = new stdClass();
212 $contact->userid
= $userid;
213 $contact->contactid
= $contactid;
214 $contact->blocked
= $blocked;
215 $contact->id
= $DB->insert_record('message_contacts', $contact);
217 $eventparams = array(
218 'objectid' => $contact->id
,
219 'userid' => $contact->userid
,
220 'relateduserid' => $contact->contactid
,
221 'context' => context_user
::instance($contact->userid
)
225 $event = \core\event\message_contact_blocked
::create($eventparams);
227 $event = \core\event\message_contact_added
::create($eventparams);
239 * @param int $contactid the user ID of the contact to remove
240 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
241 * @return bool returns the result of delete_records()
243 function message_remove_contact($contactid, $userid = 0) {
246 if (empty($userid)) {
250 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
251 $DB->delete_records('message_contacts', array('id' => $contact->id
));
253 // Trigger event for removing a contact.
254 $event = \core\event\message_contact_removed
::create(array(
255 'objectid' => $contact->id
,
256 'userid' => $contact->userid
,
257 'relateduserid' => $contact->contactid
,
258 'context' => context_user
::instance($contact->userid
)
260 $event->add_record_snapshot('message_contacts', $contact);
270 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
272 * @param int $contactid the user ID of the contact to unblock
273 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
275 * @return bool returns the result of delete_records()
277 function message_unblock_contact($contactid, $userid = 0) {
278 return message_add_contact($contactid, 0, $userid);
284 * @param int $contactid the user ID of the user to block
285 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
289 function message_block_contact($contactid, $userid = 0) {
290 return message_add_contact($contactid, 1, $userid);
294 * Load a user's contact record
296 * @param int $contactid the user ID of the user whose contact record you want
297 * @return array message contacts
299 function message_get_contact($contactid) {
301 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
305 * Search through course users.
307 * If $courseids contains the site course then this function searches
308 * through all undeleted and confirmed users.
310 * @param int|array $courseids Course ID or array of course IDs.
311 * @param string $searchtext the text to search for.
312 * @param string $sort the column name to order by.
313 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
314 * @return array An array of {@link $USER} records.
316 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
317 global $CFG, $USER, $DB;
319 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
321 $courseids = array(SITEID
);
324 // Allow an integer to be passed.
325 if (!is_array($courseids)) {
326 $courseids = array($courseids);
329 $fullname = $DB->sql_fullname();
330 $ufields = user_picture
::fields('u');
333 $order = ' ORDER BY '. $sort;
339 'userid' => $USER->id
,
340 'query' => "%$searchtext%"
343 if (empty($exceptions)) {
344 $exceptions = array();
345 } else if (!empty($exceptions) && is_string($exceptions)) {
346 $exceptions = explode(',', $exceptions);
349 // Ignore self and guest account.
350 $exceptions[] = $USER->id
;
351 $exceptions[] = $CFG->siteguest
;
353 // Exclude exceptions from the search result.
354 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'param', false);
355 $except = ' AND u.id ' . $except;
356 $params = array_merge($params_except, $params);
358 if (in_array(SITEID
, $courseids)) {
359 // Search on site level.
360 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
362 LEFT JOIN {message_contacts} mc
363 ON mc.contactid = u.id AND mc.userid = :userid
364 WHERE u.deleted = '0' AND u.confirmed = '1'
365 AND (".$DB->sql_like($fullname, ':query', false).")
369 // Search in courses.
371 // Getting the context IDs or each course.
372 $contextids = array();
373 foreach ($courseids as $courseid) {
374 $context = context_course
::instance($courseid);
375 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
377 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED
, 'context');
378 $params = array_merge($params, $contextparams);
380 // Everyone who has a role assignment in this course or higher.
381 // TODO: add enabled enrolment join here (skodak)
382 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
384 JOIN {role_assignments} ra ON ra.userid = u.id
385 LEFT JOIN {message_contacts} mc
386 ON mc.contactid = u.id AND mc.userid = :userid
387 WHERE u.deleted = '0' AND u.confirmed = '1'
388 AND (".$DB->sql_like($fullname, ':query', false).")
389 AND ra.contextid $contextwhere
398 * Format a message for display in the message history
400 * @param object $message the message object
401 * @param string $format optional date format
402 * @param string $keywords keywords to highlight
403 * @param string $class CSS class to apply to the div around the message
404 * @return string the formatted message
406 function message_format_message($message, $format='', $keywords='', $class='other') {
410 //if we haven't previously set the date format or they've supplied a new one
411 if ( empty($dateformat) ||
(!empty($format) && $dateformat != $format) ) {
413 $dateformat = $format;
415 $dateformat = get_string('strftimedatetimeshort');
418 $time = userdate($message->timecreated
, $dateformat);
420 $messagetext = message_format_message_text($message, false);
423 $messagetext = highlight($keywords, $messagetext);
426 $messagetext .= message_format_contexturl($message);
428 $messagetext = clean_text($messagetext, FORMAT_HTML
);
431 <div class='message $class'>
432 <a name="m{$message->id}"></a>
433 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
439 * Format a the context url and context url name of a message for display
441 * @param object $message the message object
442 * @return string the formatted string
444 function message_format_contexturl($message) {
447 if (!empty($message->contexturl
)) {
449 if (!empty($message->contexturlname
)) {
450 $displaytext= $message->contexturlname
;
452 $displaytext= $message->contexturl
;
454 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
455 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
456 $s .= html_writer
::end_tag('div');
463 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
465 * @param object $userfrom the message sender
466 * @param object $userto the message recipient
467 * @param string $message the message
468 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
469 * @return int|false the ID of the new message or false
471 function message_post_message($userfrom, $userto, $message, $format) {
472 global $SITE, $CFG, $USER;
474 $eventdata = new \core\message\
message();
475 $eventdata->courseid
= 1;
476 $eventdata->component
= 'moodle';
477 $eventdata->name
= 'instantmessage';
478 $eventdata->userfrom
= $userfrom;
479 $eventdata->userto
= $userto;
481 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
482 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
484 if ($format == FORMAT_HTML
) {
485 $eventdata->fullmessagehtml
= $message;
486 //some message processors may revert to sending plain text even if html is supplied
487 //so we keep both plain and html versions if we're intending to send html
488 $eventdata->fullmessage
= html_to_text($eventdata->fullmessagehtml
);
490 $eventdata->fullmessage
= $message;
491 $eventdata->fullmessagehtml
= '';
494 $eventdata->fullmessageformat
= $format;
495 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
498 $s->sitename
= format_string($SITE->shortname
, true, array('context' => context_course
::instance(SITEID
)));
499 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
501 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
502 if (!empty($eventdata->fullmessage
)) {
503 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
505 if (!empty($eventdata->fullmessagehtml
)) {
506 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
509 $eventdata->timecreated
= time();
510 $eventdata->notification
= 0;
511 return message_send($eventdata);
515 * Get all message processors, validate corresponding plugin existance and
516 * system configuration
518 * @param bool $ready only return ready-to-use processors
519 * @param bool $reset Reset list of message processors (used in unit tests)
520 * @param bool $resetonly Just reset, then exit
521 * @return mixed $processors array of objects containing information on message processors
523 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
528 $processors = array();
535 if (empty($processors)) {
536 // Get all processors, ensure the name column is the first so it will be the array key
537 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
538 foreach ($processors as &$processor){
539 $processor = \core_message\api
::get_processed_processor_object($processor);
543 // Filter out enabled and system_configured processors
544 $readyprocessors = $processors;
545 foreach ($readyprocessors as $readyprocessor) {
546 if (!($readyprocessor->enabled
&& $readyprocessor->configured
)) {
547 unset($readyprocessors[$readyprocessor->name
]);
550 return $readyprocessors;
557 * Get all message providers, validate their plugin existance and
558 * system configuration
560 * @return mixed $processors array of objects containing information on message processors
562 function get_message_providers() {
565 $pluginman = core_plugin_manager
::instance();
567 $providers = $DB->get_records('message_providers', null, 'name');
569 // Remove all the providers whose plugins are disabled or don't exist
570 foreach ($providers as $providerid => $provider) {
571 $plugin = $pluginman->get_plugin_info($provider->component
);
573 if ($plugin->get_status() === core_plugin_manager
::PLUGIN_STATUS_MISSING
) {
574 unset($providers[$providerid]); // Plugins does not exist
577 if ($plugin->is_enabled() === false) {
578 unset($providers[$providerid]); // Plugin disabled
587 * Get an instance of the message_output class for one of the output plugins.
588 * @param string $type the message output type. E.g. 'email' or 'jabber'.
589 * @return message_output message_output the requested class.
591 function get_message_processor($type) {
594 // Note, we cannot use the get_message_processors function here, becaues this
595 // code is called during install after installing each messaging plugin, and
596 // get_message_processors caches the list of installed plugins.
598 $processorfile = $CFG->dirroot
. "/message/output/{$type}/message_output_{$type}.php";
599 if (!is_readable($processorfile)) {
600 throw new coding_exception('Unknown message processor type ' . $type);
603 include_once($processorfile);
605 $processclass = 'message_output_' . $type;
606 if (!class_exists($processclass)) {
607 throw new coding_exception('Message processor ' . $type .
608 ' does not define the right class');
611 return new $processclass();
615 * Get messaging outputs default (site) preferences
617 * @return object $processors object containing information on message processors
619 function get_message_output_default_preferences() {
620 return get_config('message');
624 * Translate message default settings from binary value to the array of string
625 * representing the settings to be stored. Also validate the provided value and
626 * use default if it is malformed.
628 * @param int $plugindefault Default setting suggested by plugin
629 * @param string $processorname The name of processor
630 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
632 function translate_message_default_setting($plugindefault, $processorname) {
633 // Preset translation arrays
634 $permittedvalues = array(
635 0x04 => 'disallowed',
640 $loggedinstatusvalues = array(
641 0x00 => null, // use null if loggedin/loggedoff is not defined
646 // define the default setting
647 $processor = get_message_processor($processorname);
648 $default = $processor->get_default_messaging_settings();
650 // Validate the value. It should not exceed the maximum size
651 if (!is_int($plugindefault) ||
($plugindefault > 0x0f)) {
652 debugging(get_string('errortranslatingdefault', 'message'));
653 $plugindefault = $default;
655 // Use plugin default setting of 'permitted' is 0
656 if (!($plugindefault & MESSAGE_PERMITTED_MASK
)) {
657 $plugindefault = $default;
660 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK
];
661 $loggedin = $loggedoff = null;
663 if (($plugindefault & MESSAGE_PERMITTED_MASK
) == MESSAGE_PERMITTED
) {
664 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN
];
665 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF
];
668 return array($permitted, $loggedin, $loggedoff);
672 * Get messages sent or/and received by the specified users.
673 * Please note that this function return deleted messages too.
675 * @param int $useridto the user id who received the message
676 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
677 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
678 * @param bool $read true for retrieving read messages, false for unread
679 * @param string $sort the column name to order by including optionally direction
680 * @param int $limitfrom limit from
681 * @param int $limitnum limit num
682 * @return external_description
685 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
686 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
689 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
690 if (empty($useridto)) {
691 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
692 $messageuseridtosql = 'u.id as useridto';
694 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
695 $messageuseridtosql = "$useridto as useridto";
698 // Create the SQL we will be using.
699 $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
700 mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
701 mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
703 INNER JOIN {message_conversations} mc
704 ON mc.id = mr.conversationid
705 INNER JOIN {message_conversation_members} mcm
706 ON mcm.conversationid = mc.id ";
708 $notificationsql = "SELECT mr.*, $userfields, 1 as notification
709 FROM {notifications} mr ";
711 $messagejoinsql = "LEFT JOIN {message_user_actions} mua
712 ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
713 LEFT JOIN {message_user_actions} mua2
714 ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
715 LEFT JOIN {message_user_actions} mua3
716 ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
717 $messagejoinparams = [\core_message\api
::MESSAGE_ACTION_DELETED
, \core_message\api
::MESSAGE_ACTION_READ
,
718 \core_message\api
::MESSAGE_ACTION_DELETED
];
719 $notificationsparams = [];
721 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
722 if (empty($useridto)) {
723 // Create the messaging query and params.
724 $messagesql .= "INNER JOIN {user} u
727 WHERE mr.useridfrom = ?
728 AND mr.useridfrom != mcm.userid
730 $messageparams = array_merge($messagejoinparams, [$useridfrom]);
732 // Create the notifications query and params.
733 $notificationsql .= "INNER JOIN {user} u
734 ON u.id = mr.useridto
735 WHERE mr.useridfrom = ?
737 $notificationsparams[] = $useridfrom;
739 // Create the messaging query and params.
740 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
741 $messagesql .= "LEFT JOIN {user} u
742 ON u.id = mr.useridfrom
745 AND mr.useridfrom != mcm.userid
747 $messageparams = array_merge($messagejoinparams, [$useridto]);
748 if (!empty($useridfrom)) {
749 $messagesql .= " AND mr.useridfrom = ? ";
750 $messageparams[] = $useridfrom;
753 // Create the notifications query and params.
754 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
755 $notificationsql .= "LEFT JOIN {user} u
756 ON (u.id = mr.useridfrom AND u.deleted = 0)
757 WHERE mr.useridto = ? ";
758 $notificationsparams[] = $useridto;
759 if (!empty($useridfrom)) {
760 $notificationsql .= " AND mr.useridfrom = ? ";
761 $notificationsparams[] = $useridfrom;
765 $notificationsql .= "AND mr.timeread IS NOT NULL ";
767 $notificationsql .= "AND mr.timeread IS NULL ";
769 $messagesql .= "ORDER BY $sort";
770 $notificationsql .= "ORDER BY $sort";
772 // Handle messages if needed.
773 if ($notifications === -1 ||
$notifications === 0) {
774 $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
775 // Get rid of the messages that have either been read or not read depending on the value of $read.
776 $messages = array_filter($messages, function ($message) use ($read) {
778 return !is_null($message->timeread
);
781 return is_null($message->timeread
);
786 if ($notifications === -1) {
787 return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
788 } else if ($notifications === 1) { // Just notifications.
789 return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
797 * Handles displaying processor settings in a fragment.
800 * @return bool|string
801 * @throws moodle_exception
803 function message_output_fragment_processor_settings($args = []) {
806 if (!isset($args['type'])) {
807 throw new moodle_exception('Must provide a processor type');
810 if (!isset($args['userid'])) {
811 throw new moodle_exception('Must provide a userid');
814 $type = $args['type'];
815 $userid = $args['userid'];
817 $user = core_user
::get_user($userid, '*', MUST_EXIST
);
818 $processor = get_message_processor($type);
819 $providers = message_get_providers_for_user($userid);
820 $processorwrapper = new stdClass();
821 $processorwrapper->object = $processor;
822 $preferences = \core_message\api
::get_all_message_preferences([$processorwrapper], $providers, $user);
824 $processoroutput = new \core_message\output\preferences\
processor($processor, $preferences, $user, $type);
825 $renderer = $PAGE->get_renderer('core', 'message');
827 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
831 * Checks if current user is allowed to edit messaging preferences of another user
833 * @param stdClass $user user whose preferences we are updating
836 function core_message_can_edit_message_profile($user) {
838 if ($user->id
== $USER->id
) {
839 return has_capability('moodle/user:editownmessageprofile', context_system
::instance());
841 $personalcontext = context_user
::instance($user->id
);
842 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
845 if (isguestuser($user)) {
848 // No editing of admins by non-admins.
849 if (is_siteadmin($user) and !is_siteadmin($USER)) {
857 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
859 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
863 function core_message_user_preferences() {
866 $preferences['message_blocknoncontacts'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
867 'choices' => array(0, 1));
868 $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS
,
869 'null' => NULL_NOT_ALLOWED
, 'default' => 'none',
870 'permissioncallback' => function ($user, $preferencename) {
872 require_once($CFG->libdir
.'/messagelib.php');
873 if (core_message_can_edit_message_profile($user) &&
874 preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
875 $providers = message_get_providers_for_user($user->id
);
876 foreach ($providers as $provider) {
877 if ($matches[1] === $provider->component
. '_' . $provider->name
) {
884 'cleancallback' => function ($value, $preferencename) {
885 if ($value === 'none' ||
empty($value)) {
888 $parts = explode('/,/', $value);
889 $processors = array_keys(get_message_processors());
890 array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
891 return $parts ?
join(',', $parts) : 'none';