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 require_once($CFG->libdir
.'/eventslib.php');
27 define('MESSAGE_SHORTLENGTH', 300);
29 define('MESSAGE_HISTORY_ALL', 1);
31 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
33 define('MESSAGE_TYPE_NOTIFICATION', 'notification');
34 define('MESSAGE_TYPE_MESSAGE', 'message');
37 * Define contants for messaging default settings population. For unambiguity of
38 * plugin developer intentions we use 4-bit value (LSB numbering):
39 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
40 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
41 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
43 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
46 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
47 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
49 define('MESSAGE_DISALLOWED', 0x04); // 0100
50 define('MESSAGE_PERMITTED', 0x08); // 1000
51 define('MESSAGE_FORCED', 0x0c); // 1100
53 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
56 * Set default value for default outputs permitted setting
58 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
61 * Set default values for polling.
63 define('MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS', 10);
64 define('MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS', 2 * MINSECS
);
65 define('MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS', 5 * MINSECS
);
68 * Returns the count of unread messages for user. Either from a specific user or from all users.
70 * @param object $user1 the first user. Defaults to $USER
71 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
72 * @return int the count of $user1's unread messages
74 function message_count_unread_messages($user1=null, $user2=null) {
81 $sql = "SELECT COUNT(m.id)
83 INNER JOIN {message_conversations} mc
84 ON mc.id = m.conversationid
85 INNER JOIN {message_conversation_members} mcm
86 ON mcm.conversationid = mc.id
87 LEFT JOIN {message_user_actions} mua
88 ON (mua.messageid = m.id AND mua.userid = ? AND (mua.action = ? OR mua.action = ?))
91 $params = [$user1->id
, \core_message\api
::MESSAGE_ACTION_DELETED
, \core_message\api
::MESSAGE_ACTION_READ
, $user1->id
];
94 $sql .= " AND m.useridfrom = ?";
95 $params[] = $user2->id
;
98 return $DB->count_records_sql($sql, $params);
102 * Try to guess how to convert the message to html.
106 * @param stdClass $message
107 * @param bool $forcetexttohtml
108 * @return string html fragment
110 function message_format_message_text($message, $forcetexttohtml = false) {
111 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
113 $options = new stdClass();
114 $options->para
= false;
115 $options->blanktarget
= true;
117 $format = $message->fullmessageformat
;
119 if (strval($message->smallmessage
) !== '') {
120 if (!empty($message->notification
)) {
121 if (strval($message->fullmessagehtml
) !== '' or strval($message->fullmessage
) !== '') {
122 $format = FORMAT_PLAIN
;
125 $messagetext = $message->smallmessage
;
127 } else if ($message->fullmessageformat
== FORMAT_HTML
) {
128 if (strval($message->fullmessagehtml
) !== '') {
129 $messagetext = $message->fullmessagehtml
;
131 $messagetext = $message->fullmessage
;
132 $format = FORMAT_MOODLE
;
136 if (strval($message->fullmessage
) !== '') {
137 $messagetext = $message->fullmessage
;
139 $messagetext = $message->fullmessagehtml
;
140 $format = FORMAT_HTML
;
144 if ($forcetexttohtml) {
145 // This is a crazy hack, why not set proper format when creating the notifications?
146 if ($format === FORMAT_PLAIN
) {
147 $format = FORMAT_MOODLE
;
150 return format_text($messagetext, $format, $options);
154 * Add the selected user as a contact for the current user
156 * @param int $contactid the ID of the user to add as a contact
157 * @param int $blocked 1 if you wish to block the contact
158 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
159 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
160 * Otherwise returns the result of update_record() or insert_record()
162 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
165 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
169 if (empty($userid)) {
173 // Check if a record already exists as we may be changing blocking status.
174 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
175 // Check if blocking status has been changed.
176 if ($contact->blocked
!= $blocked) {
177 $contact->blocked
= $blocked;
178 $DB->update_record('message_contacts', $contact);
181 // Trigger event for blocking a contact.
182 $event = \core\event\message_contact_blocked
::create(array(
183 'objectid' => $contact->id
,
184 'userid' => $contact->userid
,
185 'relateduserid' => $contact->contactid
,
186 'context' => context_user
::instance($contact->userid
)
188 $event->add_record_snapshot('message_contacts', $contact);
191 // Trigger event for unblocking a contact.
192 $event = \core\event\message_contact_unblocked
::create(array(
193 'objectid' => $contact->id
,
194 'userid' => $contact->userid
,
195 'relateduserid' => $contact->contactid
,
196 'context' => context_user
::instance($contact->userid
)
198 $event->add_record_snapshot('message_contacts', $contact);
204 // No change to blocking status.
209 // New contact record.
210 $contact = new stdClass();
211 $contact->userid
= $userid;
212 $contact->contactid
= $contactid;
213 $contact->blocked
= $blocked;
214 $contact->id
= $DB->insert_record('message_contacts', $contact);
216 $eventparams = array(
217 'objectid' => $contact->id
,
218 'userid' => $contact->userid
,
219 'relateduserid' => $contact->contactid
,
220 'context' => context_user
::instance($contact->userid
)
224 $event = \core\event\message_contact_blocked
::create($eventparams);
226 $event = \core\event\message_contact_added
::create($eventparams);
238 * @param int $contactid the user ID of the contact to remove
239 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
240 * @return bool returns the result of delete_records()
242 function message_remove_contact($contactid, $userid = 0) {
245 if (empty($userid)) {
249 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
250 $DB->delete_records('message_contacts', array('id' => $contact->id
));
252 // Trigger event for removing a contact.
253 $event = \core\event\message_contact_removed
::create(array(
254 'objectid' => $contact->id
,
255 'userid' => $contact->userid
,
256 'relateduserid' => $contact->contactid
,
257 'context' => context_user
::instance($contact->userid
)
259 $event->add_record_snapshot('message_contacts', $contact);
269 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
271 * @param int $contactid the user ID of the contact to unblock
272 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
274 * @return bool returns the result of delete_records()
276 function message_unblock_contact($contactid, $userid = 0) {
277 return message_add_contact($contactid, 0, $userid);
283 * @param int $contactid the user ID of the user to block
284 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
288 function message_block_contact($contactid, $userid = 0) {
289 return message_add_contact($contactid, 1, $userid);
293 * Load a user's contact record
295 * @param int $contactid the user ID of the user whose contact record you want
296 * @return array message contacts
298 function message_get_contact($contactid) {
300 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
304 * Search through course users.
306 * If $courseids contains the site course then this function searches
307 * through all undeleted and confirmed users.
309 * @param int|array $courseids Course ID or array of course IDs.
310 * @param string $searchtext the text to search for.
311 * @param string $sort the column name to order by.
312 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
313 * @return array An array of {@link $USER} records.
315 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
316 global $CFG, $USER, $DB;
318 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
320 $courseids = array(SITEID
);
323 // Allow an integer to be passed.
324 if (!is_array($courseids)) {
325 $courseids = array($courseids);
328 $fullname = $DB->sql_fullname();
329 $ufields = user_picture
::fields('u');
332 $order = ' ORDER BY '. $sort;
338 'userid' => $USER->id
,
339 'query' => "%$searchtext%"
342 if (empty($exceptions)) {
343 $exceptions = array();
344 } else if (!empty($exceptions) && is_string($exceptions)) {
345 $exceptions = explode(',', $exceptions);
348 // Ignore self and guest account.
349 $exceptions[] = $USER->id
;
350 $exceptions[] = $CFG->siteguest
;
352 // Exclude exceptions from the search result.
353 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'param', false);
354 $except = ' AND u.id ' . $except;
355 $params = array_merge($params_except, $params);
357 if (in_array(SITEID
, $courseids)) {
358 // Search on site level.
359 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
361 LEFT JOIN {message_contacts} mc
362 ON mc.contactid = u.id AND mc.userid = :userid
363 WHERE u.deleted = '0' AND u.confirmed = '1'
364 AND (".$DB->sql_like($fullname, ':query', false).")
368 // Search in courses.
370 // Getting the context IDs or each course.
371 $contextids = array();
372 foreach ($courseids as $courseid) {
373 $context = context_course
::instance($courseid);
374 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
376 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED
, 'context');
377 $params = array_merge($params, $contextparams);
379 // Everyone who has a role assignment in this course or higher.
380 // TODO: add enabled enrolment join here (skodak)
381 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
383 JOIN {role_assignments} ra ON ra.userid = u.id
384 LEFT JOIN {message_contacts} mc
385 ON mc.contactid = u.id AND mc.userid = :userid
386 WHERE u.deleted = '0' AND u.confirmed = '1'
387 AND (".$DB->sql_like($fullname, ':query', false).")
388 AND ra.contextid $contextwhere
397 * Format a message for display in the message history
399 * @param object $message the message object
400 * @param string $format optional date format
401 * @param string $keywords keywords to highlight
402 * @param string $class CSS class to apply to the div around the message
403 * @return string the formatted message
405 function message_format_message($message, $format='', $keywords='', $class='other') {
409 //if we haven't previously set the date format or they've supplied a new one
410 if ( empty($dateformat) ||
(!empty($format) && $dateformat != $format) ) {
412 $dateformat = $format;
414 $dateformat = get_string('strftimedatetimeshort');
417 $time = userdate($message->timecreated
, $dateformat);
419 $messagetext = message_format_message_text($message, false);
422 $messagetext = highlight($keywords, $messagetext);
425 $messagetext .= message_format_contexturl($message);
427 $messagetext = clean_text($messagetext, FORMAT_HTML
);
430 <div class='message $class'>
431 <a name="m{$message->id}"></a>
432 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
438 * Format a the context url and context url name of a message for display
440 * @param object $message the message object
441 * @return string the formatted string
443 function message_format_contexturl($message) {
446 if (!empty($message->contexturl
)) {
448 if (!empty($message->contexturlname
)) {
449 $displaytext= $message->contexturlname
;
451 $displaytext= $message->contexturl
;
453 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
454 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
455 $s .= html_writer
::end_tag('div');
462 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
464 * @param object $userfrom the message sender
465 * @param object $userto the message recipient
466 * @param string $message the message
467 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
468 * @return int|false the ID of the new message or false
470 function message_post_message($userfrom, $userto, $message, $format) {
471 global $SITE, $CFG, $USER;
473 $eventdata = new \core\message\
message();
474 $eventdata->courseid
= 1;
475 $eventdata->component
= 'moodle';
476 $eventdata->name
= 'instantmessage';
477 $eventdata->userfrom
= $userfrom;
478 $eventdata->userto
= $userto;
480 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
481 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
483 if ($format == FORMAT_HTML
) {
484 $eventdata->fullmessagehtml
= $message;
485 //some message processors may revert to sending plain text even if html is supplied
486 //so we keep both plain and html versions if we're intending to send html
487 $eventdata->fullmessage
= html_to_text($eventdata->fullmessagehtml
);
489 $eventdata->fullmessage
= $message;
490 $eventdata->fullmessagehtml
= '';
493 $eventdata->fullmessageformat
= $format;
494 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
497 $s->sitename
= format_string($SITE->shortname
, true, array('context' => context_course
::instance(SITEID
)));
498 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
500 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
501 if (!empty($eventdata->fullmessage
)) {
502 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
504 if (!empty($eventdata->fullmessagehtml
)) {
505 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
508 $eventdata->timecreated
= time();
509 $eventdata->notification
= 0;
510 return message_send($eventdata);
514 * Get all message processors, validate corresponding plugin existance and
515 * system configuration
517 * @param bool $ready only return ready-to-use processors
518 * @param bool $reset Reset list of message processors (used in unit tests)
519 * @param bool $resetonly Just reset, then exit
520 * @return mixed $processors array of objects containing information on message processors
522 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
527 $processors = array();
534 if (empty($processors)) {
535 // Get all processors, ensure the name column is the first so it will be the array key
536 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
537 foreach ($processors as &$processor){
538 $processor = \core_message\api
::get_processed_processor_object($processor);
542 // Filter out enabled and system_configured processors
543 $readyprocessors = $processors;
544 foreach ($readyprocessors as $readyprocessor) {
545 if (!($readyprocessor->enabled
&& $readyprocessor->configured
)) {
546 unset($readyprocessors[$readyprocessor->name
]);
549 return $readyprocessors;
556 * Get all message providers, validate their plugin existance and
557 * system configuration
559 * @return mixed $processors array of objects containing information on message processors
561 function get_message_providers() {
564 $pluginman = core_plugin_manager
::instance();
566 $providers = $DB->get_records('message_providers', null, 'name');
568 // Remove all the providers whose plugins are disabled or don't exist
569 foreach ($providers as $providerid => $provider) {
570 $plugin = $pluginman->get_plugin_info($provider->component
);
572 if ($plugin->get_status() === core_plugin_manager
::PLUGIN_STATUS_MISSING
) {
573 unset($providers[$providerid]); // Plugins does not exist
576 if ($plugin->is_enabled() === false) {
577 unset($providers[$providerid]); // Plugin disabled
586 * Get an instance of the message_output class for one of the output plugins.
587 * @param string $type the message output type. E.g. 'email' or 'jabber'.
588 * @return message_output message_output the requested class.
590 function get_message_processor($type) {
593 // Note, we cannot use the get_message_processors function here, becaues this
594 // code is called during install after installing each messaging plugin, and
595 // get_message_processors caches the list of installed plugins.
597 $processorfile = $CFG->dirroot
. "/message/output/{$type}/message_output_{$type}.php";
598 if (!is_readable($processorfile)) {
599 throw new coding_exception('Unknown message processor type ' . $type);
602 include_once($processorfile);
604 $processclass = 'message_output_' . $type;
605 if (!class_exists($processclass)) {
606 throw new coding_exception('Message processor ' . $type .
607 ' does not define the right class');
610 return new $processclass();
614 * Get messaging outputs default (site) preferences
616 * @return object $processors object containing information on message processors
618 function get_message_output_default_preferences() {
619 return get_config('message');
623 * Translate message default settings from binary value to the array of string
624 * representing the settings to be stored. Also validate the provided value and
625 * use default if it is malformed.
627 * @param int $plugindefault Default setting suggested by plugin
628 * @param string $processorname The name of processor
629 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
631 function translate_message_default_setting($plugindefault, $processorname) {
632 // Preset translation arrays
633 $permittedvalues = array(
634 0x04 => 'disallowed',
639 $loggedinstatusvalues = array(
640 0x00 => null, // use null if loggedin/loggedoff is not defined
645 // define the default setting
646 $processor = get_message_processor($processorname);
647 $default = $processor->get_default_messaging_settings();
649 // Validate the value. It should not exceed the maximum size
650 if (!is_int($plugindefault) ||
($plugindefault > 0x0f)) {
651 debugging(get_string('errortranslatingdefault', 'message'));
652 $plugindefault = $default;
654 // Use plugin default setting of 'permitted' is 0
655 if (!($plugindefault & MESSAGE_PERMITTED_MASK
)) {
656 $plugindefault = $default;
659 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK
];
660 $loggedin = $loggedoff = null;
662 if (($plugindefault & MESSAGE_PERMITTED_MASK
) == MESSAGE_PERMITTED
) {
663 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN
];
664 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF
];
667 return array($permitted, $loggedin, $loggedoff);
671 * Get messages sent or/and received by the specified users.
672 * Please note that this function return deleted messages too.
674 * @param int $useridto the user id who received the message
675 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
676 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
677 * @param bool $read true for retrieving read messages, false for unread
678 * @param string $sort the column name to order by including optionally direction
679 * @param int $limitfrom limit from
680 * @param int $limitnum limit num
681 * @return external_description
684 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
685 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
688 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
689 if (empty($useridto)) {
690 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
692 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
695 // Create the SQL we will be using.
696 $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
697 mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
698 mua3.timecreated as timeuserfromdeleted
700 INNER JOIN {message_conversations} mc
701 ON mc.id = mr.conversationid
702 INNER JOIN {message_conversation_members} mcm
703 ON mcm.conversationid = mc.id ";
705 $notificationsql = "SELECT mr.*, $userfields, 1 as notification
706 FROM {notifications} mr ";
708 $messagejoinsql = "LEFT JOIN {message_user_actions} mua
709 ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
710 LEFT JOIN {message_user_actions} mua2
711 ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
712 LEFT JOIN {message_user_actions} mua3
713 ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
714 $messagejoinparams = [\core_message\api
::MESSAGE_ACTION_DELETED
, \core_message\api
::MESSAGE_ACTION_READ
,
715 \core_message\api
::MESSAGE_ACTION_DELETED
];
716 $notificationsparams = [];
718 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
719 if (empty($useridto)) {
720 // Create the messaging query and params.
721 $messagesql .= "INNER JOIN {user} u
724 WHERE mr.useridfrom = ?
725 AND mr.useridfrom != mcm.userid
727 $messageparams = array_merge($messagejoinparams, [$useridfrom]);
729 // Create the notifications query and params.
730 $notificationsql .= "INNER JOIN {user} u
731 ON u.id = mr.useridto
732 WHERE mr.useridfrom = ?
734 $notificationsparams[] = $useridfrom;
736 // Create the messaging query and params.
737 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
738 $messagesql .= "LEFT JOIN {user} u
739 ON u.id = mr.useridfrom
742 AND mr.useridfrom != mcm.userid
744 $messageparams = array_merge($messagejoinparams, [$useridto]);
745 if (!empty($useridfrom)) {
746 $messagesql .= " AND mr.useridfrom = ? ";
747 $messageparams[] = $useridfrom;
750 // Create the notifications query and params.
751 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
752 $notificationsql .= "LEFT JOIN {user} u
753 ON (u.id = mr.useridfrom AND u.deleted = 0)
754 WHERE mr.useridto = ? ";
755 $notificationsparams[] = $useridto;
756 if (!empty($useridfrom)) {
757 $notificationsql .= " AND mr.useridfrom = ? ";
758 $notificationsparams[] = $useridfrom;
762 $notificationsql .= "AND mr.timeread IS NOT NULL ";
764 $notificationsql .= "AND mr.timeread IS NULL ";
766 $messagesql .= "ORDER BY $sort";
767 $notificationsql .= "ORDER BY $sort";
769 // Handle messages if needed.
770 if ($notifications === -1 ||
$notifications === 0) {
771 $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
772 // Get rid of the messages that have either been read or not read depending on the value of $read.
773 $messages = array_filter($messages, function ($message) use ($read) {
775 return !is_null($message->timeread
);
778 return is_null($message->timeread
);
783 if ($notifications === -1) {
784 return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
785 } else if ($notifications === 1) { // Just notifications.
786 return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
794 * Handles displaying processor settings in a fragment.
797 * @return bool|string
798 * @throws moodle_exception
800 function message_output_fragment_processor_settings($args = []) {
803 if (!isset($args['type'])) {
804 throw new moodle_exception('Must provide a processor type');
807 if (!isset($args['userid'])) {
808 throw new moodle_exception('Must provide a userid');
811 $type = $args['type'];
812 $userid = $args['userid'];
814 $user = core_user
::get_user($userid, '*', MUST_EXIST
);
815 $processor = get_message_processor($type);
816 $providers = message_get_providers_for_user($userid);
817 $processorwrapper = new stdClass();
818 $processorwrapper->object = $processor;
819 $preferences = \core_message\api
::get_all_message_preferences([$processorwrapper], $providers, $user);
821 $processoroutput = new \core_message\output\preferences\
processor($processor, $preferences, $user, $type);
822 $renderer = $PAGE->get_renderer('core', 'message');
824 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
828 * Checks if current user is allowed to edit messaging preferences of another user
830 * @param stdClass $user user whose preferences we are updating
833 function core_message_can_edit_message_profile($user) {
835 if ($user->id
== $USER->id
) {
836 return has_capability('moodle/user:editownmessageprofile', context_system
::instance());
838 $personalcontext = context_user
::instance($user->id
);
839 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
842 if (isguestuser($user)) {
845 // No editing of admins by non-admins.
846 if (is_siteadmin($user) and !is_siteadmin($USER)) {
854 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
856 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
860 function core_message_user_preferences() {
863 $preferences['message_blocknoncontacts'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
864 'choices' => array(0, 1));
865 $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS
,
866 'null' => NULL_NOT_ALLOWED
, 'default' => 'none',
867 'permissioncallback' => function ($user, $preferencename) {
869 require_once($CFG->libdir
.'/messagelib.php');
870 if (core_message_can_edit_message_profile($user) &&
871 preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
872 $providers = message_get_providers_for_user($user->id
);
873 foreach ($providers as $provider) {
874 if ($matches[1] === $provider->component
. '_' . $provider->name
) {
881 'cleancallback' => function ($value, $preferencename) {
882 if ($value === 'none' ||
empty($value)) {
885 $parts = explode('/,/', $value);
886 $processors = array_keys(get_message_processors());
887 array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
888 return $parts ?
join(',', $parts) : 'none';