Merge branch 'MDL-63625-master' of git://github.com/marinaglancy/moodle
[moodle.git] / message / lib.php
bloba85e65ad91c5c36945b13301817bbcf43e1c64cf
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.
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/>.
17 /**
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');
34 /**
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
53 /**
54 * Set default value for default outputs permitted setting
56 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
58 /**
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);
65 /**
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) {
73 global $USER, $DB;
75 if (empty($user1)) {
76 $user1 = $USER;
79 $sql = "SELECT COUNT(m.id)
80 FROM {messages} m
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 = ?))
87 WHERE mua.id is NULL
88 AND mcm.userid = ?";
89 $params = [$user1->id, \core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ, $user1->id];
91 if (!empty($user2)) {
92 $sql .= " AND m.useridfrom = ?";
93 $params[] = $user2->id;
94 } else {
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.
105 * @access private
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;
131 } else {
132 $messagetext = $message->fullmessage;
133 $format = FORMAT_MOODLE;
136 } else {
137 if (strval($message->fullmessage) !== '') {
138 $messagetext = $message->fullmessage;
139 } else {
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 * Search through course users.
157 * If $courseids contains the site course then this function searches
158 * through all undeleted and confirmed users.
160 * @param int|array $courseids Course ID or array of course IDs.
161 * @param string $searchtext the text to search for.
162 * @param string $sort the column name to order by.
163 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
164 * @return array An array of {@link $USER} records.
166 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
167 global $CFG, $USER, $DB;
169 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
170 if (!$courseids) {
171 $courseids = array(SITEID);
174 // Allow an integer to be passed.
175 if (!is_array($courseids)) {
176 $courseids = array($courseids);
179 $fullname = $DB->sql_fullname();
180 $ufields = user_picture::fields('u');
182 if (!empty($sort)) {
183 $order = ' ORDER BY '. $sort;
184 } else {
185 $order = '';
188 $params = array(
189 'userid' => $USER->id,
190 'userid2' => $USER->id,
191 'query' => "%$searchtext%"
194 if (empty($exceptions)) {
195 $exceptions = array();
196 } else if (!empty($exceptions) && is_string($exceptions)) {
197 $exceptions = explode(',', $exceptions);
200 // Ignore self and guest account.
201 $exceptions[] = $USER->id;
202 $exceptions[] = $CFG->siteguest;
204 // Exclude exceptions from the search result.
205 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
206 $except = ' AND u.id ' . $except;
207 $params = array_merge($params_except, $params);
209 if (in_array(SITEID, $courseids)) {
210 // Search on site level.
211 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mub.id as userblockedid
212 FROM {user} u
213 LEFT JOIN {message_contacts} mc
214 ON mc.contactid = u.id AND mc.userid = :userid
215 LEFT JOIN {message_users_blocked} mub
216 ON mub.userid = :userid2 AND mub.blockeduserid = u.id
217 WHERE u.deleted = '0' AND u.confirmed = '1'
218 AND (".$DB->sql_like($fullname, ':query', false).")
219 $except
220 $order", $params);
221 } else {
222 // Search in courses.
224 // Getting the context IDs or each course.
225 $contextids = array();
226 foreach ($courseids as $courseid) {
227 $context = context_course::instance($courseid);
228 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
230 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
231 $params = array_merge($params, $contextparams);
233 // Everyone who has a role assignment in this course or higher.
234 // TODO: add enabled enrolment join here (skodak)
235 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mub.id as userblockedid
236 FROM {user} u
237 JOIN {role_assignments} ra ON ra.userid = u.id
238 LEFT JOIN {message_contacts} mc
239 ON mc.contactid = u.id AND mc.userid = :userid
240 LEFT JOIN {message_users_blocked} mub
241 ON mub.userid = :userid2 AND mub.blockeduserid = u.id
242 WHERE u.deleted = '0' AND u.confirmed = '1'
243 AND (".$DB->sql_like($fullname, ':query', false).")
244 AND ra.contextid $contextwhere
245 $except
246 $order", $params);
248 return $users;
253 * Format a message for display in the message history
255 * @param object $message the message object
256 * @param string $format optional date format
257 * @param string $keywords keywords to highlight
258 * @param string $class CSS class to apply to the div around the message
259 * @return string the formatted message
261 function message_format_message($message, $format='', $keywords='', $class='other') {
263 static $dateformat;
265 //if we haven't previously set the date format or they've supplied a new one
266 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
267 if ($format) {
268 $dateformat = $format;
269 } else {
270 $dateformat = get_string('strftimedatetimeshort');
273 $time = userdate($message->timecreated, $dateformat);
275 $messagetext = message_format_message_text($message, false);
277 if ($keywords) {
278 $messagetext = highlight($keywords, $messagetext);
281 $messagetext .= message_format_contexturl($message);
283 $messagetext = clean_text($messagetext, FORMAT_HTML);
285 return <<<TEMPLATE
286 <div class='message $class'>
287 <a name="m{$message->id}"></a>
288 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
289 </div>
290 TEMPLATE;
294 * Format a the context url and context url name of a message for display
296 * @param object $message the message object
297 * @return string the formatted string
299 function message_format_contexturl($message) {
300 $s = null;
302 if (!empty($message->contexturl)) {
303 $displaytext = null;
304 if (!empty($message->contexturlname)) {
305 $displaytext= $message->contexturlname;
306 } else {
307 $displaytext= $message->contexturl;
309 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
310 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
311 $s .= html_writer::end_tag('div');
314 return $s;
318 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
320 * @param object $userfrom the message sender
321 * @param object $userto the message recipient
322 * @param string $message the message
323 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
324 * @return int|false the ID of the new message or false
326 function message_post_message($userfrom, $userto, $message, $format) {
327 global $SITE, $CFG, $USER;
329 $eventdata = new \core\message\message();
330 $eventdata->courseid = 1;
331 $eventdata->component = 'moodle';
332 $eventdata->name = 'instantmessage';
333 $eventdata->userfrom = $userfrom;
334 $eventdata->userto = $userto;
336 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
337 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
339 if ($format == FORMAT_HTML) {
340 $eventdata->fullmessagehtml = $message;
341 //some message processors may revert to sending plain text even if html is supplied
342 //so we keep both plain and html versions if we're intending to send html
343 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
344 } else {
345 $eventdata->fullmessage = $message;
346 $eventdata->fullmessagehtml = '';
349 $eventdata->fullmessageformat = $format;
350 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
352 $s = new stdClass();
353 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
354 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
356 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
357 if (!empty($eventdata->fullmessage)) {
358 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
360 if (!empty($eventdata->fullmessagehtml)) {
361 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
364 $eventdata->timecreated = time();
365 $eventdata->notification = 0;
366 return message_send($eventdata);
370 * Get all message processors, validate corresponding plugin existance and
371 * system configuration
373 * @param bool $ready only return ready-to-use processors
374 * @param bool $reset Reset list of message processors (used in unit tests)
375 * @param bool $resetonly Just reset, then exit
376 * @return mixed $processors array of objects containing information on message processors
378 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
379 global $DB, $CFG;
381 static $processors;
382 if ($reset) {
383 $processors = array();
385 if ($resetonly) {
386 return $processors;
390 if (empty($processors)) {
391 // Get all processors, ensure the name column is the first so it will be the array key
392 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
393 foreach ($processors as &$processor){
394 $processor = \core_message\api::get_processed_processor_object($processor);
397 if ($ready) {
398 // Filter out enabled and system_configured processors
399 $readyprocessors = $processors;
400 foreach ($readyprocessors as $readyprocessor) {
401 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
402 unset($readyprocessors[$readyprocessor->name]);
405 return $readyprocessors;
408 return $processors;
412 * Get all message providers, validate their plugin existance and
413 * system configuration
415 * @return mixed $processors array of objects containing information on message processors
417 function get_message_providers() {
418 global $CFG, $DB;
420 $pluginman = core_plugin_manager::instance();
422 $providers = $DB->get_records('message_providers', null, 'name');
424 // Remove all the providers whose plugins are disabled or don't exist
425 foreach ($providers as $providerid => $provider) {
426 $plugin = $pluginman->get_plugin_info($provider->component);
427 if ($plugin) {
428 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
429 unset($providers[$providerid]); // Plugins does not exist
430 continue;
432 if ($plugin->is_enabled() === false) {
433 unset($providers[$providerid]); // Plugin disabled
434 continue;
438 return $providers;
442 * Get an instance of the message_output class for one of the output plugins.
443 * @param string $type the message output type. E.g. 'email' or 'jabber'.
444 * @return message_output message_output the requested class.
446 function get_message_processor($type) {
447 global $CFG;
449 // Note, we cannot use the get_message_processors function here, becaues this
450 // code is called during install after installing each messaging plugin, and
451 // get_message_processors caches the list of installed plugins.
453 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
454 if (!is_readable($processorfile)) {
455 throw new coding_exception('Unknown message processor type ' . $type);
458 include_once($processorfile);
460 $processclass = 'message_output_' . $type;
461 if (!class_exists($processclass)) {
462 throw new coding_exception('Message processor ' . $type .
463 ' does not define the right class');
466 return new $processclass();
470 * Get messaging outputs default (site) preferences
472 * @return object $processors object containing information on message processors
474 function get_message_output_default_preferences() {
475 return get_config('message');
479 * Translate message default settings from binary value to the array of string
480 * representing the settings to be stored. Also validate the provided value and
481 * use default if it is malformed.
483 * @param int $plugindefault Default setting suggested by plugin
484 * @param string $processorname The name of processor
485 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
487 function translate_message_default_setting($plugindefault, $processorname) {
488 // Preset translation arrays
489 $permittedvalues = array(
490 0x04 => 'disallowed',
491 0x08 => 'permitted',
492 0x0c => 'forced',
495 $loggedinstatusvalues = array(
496 0x00 => null, // use null if loggedin/loggedoff is not defined
497 0x01 => 'loggedin',
498 0x02 => 'loggedoff',
501 // define the default setting
502 $processor = get_message_processor($processorname);
503 $default = $processor->get_default_messaging_settings();
505 // Validate the value. It should not exceed the maximum size
506 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
507 debugging(get_string('errortranslatingdefault', 'message'));
508 $plugindefault = $default;
510 // Use plugin default setting of 'permitted' is 0
511 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
512 $plugindefault = $default;
515 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
516 $loggedin = $loggedoff = null;
518 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
519 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
520 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
523 return array($permitted, $loggedin, $loggedoff);
527 * Get messages sent or/and received by the specified users.
528 * Please note that this function return deleted messages too.
530 * @param int $useridto the user id who received the message
531 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
532 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
533 * @param bool $read true for retrieving read messages, false for unread
534 * @param string $sort the column name to order by including optionally direction
535 * @param int $limitfrom limit from
536 * @param int $limitnum limit num
537 * @return external_description
538 * @since 2.8
540 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
541 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
542 global $DB;
544 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
545 if (empty($useridto)) {
546 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
547 $messageuseridtosql = 'u.id as useridto';
548 } else {
549 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
550 $messageuseridtosql = "$useridto as useridto";
553 // Create the SQL we will be using.
554 $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
555 mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
556 mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
557 FROM {messages} mr
558 INNER JOIN {message_conversations} mc
559 ON mc.id = mr.conversationid
560 INNER JOIN {message_conversation_members} mcm
561 ON mcm.conversationid = mc.id ";
563 $notificationsql = "SELECT mr.*, $userfields, 1 as notification
564 FROM {notifications} mr ";
566 $messagejoinsql = "LEFT JOIN {message_user_actions} mua
567 ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
568 LEFT JOIN {message_user_actions} mua2
569 ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
570 LEFT JOIN {message_user_actions} mua3
571 ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
572 $messagejoinparams = [\core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ,
573 \core_message\api::MESSAGE_ACTION_DELETED];
574 $notificationsparams = [];
576 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
577 if (empty($useridto)) {
578 // Create the messaging query and params.
579 $messagesql .= "INNER JOIN {user} u
580 ON u.id = mcm.userid
581 $messagejoinsql
582 WHERE mr.useridfrom = ?
583 AND mr.useridfrom != mcm.userid
584 AND u.deleted = 0 ";
585 $messageparams = array_merge($messagejoinparams, [$useridfrom]);
587 // Create the notifications query and params.
588 $notificationsql .= "INNER JOIN {user} u
589 ON u.id = mr.useridto
590 WHERE mr.useridfrom = ?
591 AND u.deleted = 0 ";
592 $notificationsparams[] = $useridfrom;
593 } else {
594 // Create the messaging query and params.
595 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
596 $messagesql .= "LEFT JOIN {user} u
597 ON u.id = mr.useridfrom
598 $messagejoinsql
599 WHERE mcm.userid = ?
600 AND mr.useridfrom != mcm.userid
601 AND u.deleted = 0 ";
602 $messageparams = array_merge($messagejoinparams, [$useridto]);
603 if (!empty($useridfrom)) {
604 $messagesql .= " AND mr.useridfrom = ? ";
605 $messageparams[] = $useridfrom;
608 // Create the notifications query and params.
609 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
610 $notificationsql .= "LEFT JOIN {user} u
611 ON (u.id = mr.useridfrom AND u.deleted = 0)
612 WHERE mr.useridto = ? ";
613 $notificationsparams[] = $useridto;
614 if (!empty($useridfrom)) {
615 $notificationsql .= " AND mr.useridfrom = ? ";
616 $notificationsparams[] = $useridfrom;
619 if ($read) {
620 $notificationsql .= "AND mr.timeread IS NOT NULL ";
621 } else {
622 $notificationsql .= "AND mr.timeread IS NULL ";
624 $messagesql .= "ORDER BY $sort";
625 $notificationsql .= "ORDER BY $sort";
627 // Handle messages if needed.
628 if ($notifications === -1 || $notifications === 0) {
629 $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
630 // Get rid of the messages that have either been read or not read depending on the value of $read.
631 $messages = array_filter($messages, function ($message) use ($read) {
632 if ($read) {
633 return !is_null($message->timeread);
636 return is_null($message->timeread);
640 // All.
641 if ($notifications === -1) {
642 return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
643 } else if ($notifications === 1) { // Just notifications.
644 return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
647 // Just messages.
648 return $messages;
652 * Handles displaying processor settings in a fragment.
654 * @param array $args
655 * @return bool|string
656 * @throws moodle_exception
658 function message_output_fragment_processor_settings($args = []) {
659 global $PAGE;
661 if (!isset($args['type'])) {
662 throw new moodle_exception('Must provide a processor type');
665 if (!isset($args['userid'])) {
666 throw new moodle_exception('Must provide a userid');
669 $type = $args['type'];
670 $userid = $args['userid'];
672 $user = core_user::get_user($userid, '*', MUST_EXIST);
673 $processor = get_message_processor($type);
674 $providers = message_get_providers_for_user($userid);
675 $processorwrapper = new stdClass();
676 $processorwrapper->object = $processor;
677 $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
679 $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
680 $renderer = $PAGE->get_renderer('core', 'message');
682 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
686 * Checks if current user is allowed to edit messaging preferences of another user
688 * @param stdClass $user user whose preferences we are updating
689 * @return bool
691 function core_message_can_edit_message_profile($user) {
692 global $USER;
693 if ($user->id == $USER->id) {
694 return has_capability('moodle/user:editownmessageprofile', context_system::instance());
695 } else {
696 $personalcontext = context_user::instance($user->id);
697 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
698 return false;
700 if (isguestuser($user)) {
701 return false;
703 // No editing of admins by non-admins.
704 if (is_siteadmin($user) and !is_siteadmin($USER)) {
705 return false;
707 return true;
712 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
714 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
716 * @return array
718 function core_message_user_preferences() {
719 $preferences = [];
720 $preferences['message_blocknoncontacts'] = array(
721 'type' => PARAM_INT,
722 'null' => NULL_NOT_ALLOWED,
723 'default' => 0,
724 'choices' => array(
725 \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
726 \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
727 \core_message\api::MESSAGE_PRIVACY_SITE
729 'cleancallback' => function ($value) {
730 global $CFG;
732 // When site-wide messaging between users is disabled, MESSAGE_PRIVACY_SITE should be converted.
733 if (empty($CFG->messagingallusers) && $value === \core_message\api::MESSAGE_PRIVACY_SITE) {
734 return \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER;
736 return $value;
739 $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
740 'null' => NULL_NOT_ALLOWED, 'default' => 'none',
741 'permissioncallback' => function ($user, $preferencename) {
742 global $CFG;
743 require_once($CFG->libdir.'/messagelib.php');
744 if (core_message_can_edit_message_profile($user) &&
745 preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
746 $providers = message_get_providers_for_user($user->id);
747 foreach ($providers as $provider) {
748 if ($matches[1] === $provider->component . '_' . $provider->name) {
749 return true;
753 return false;
755 'cleancallback' => function ($value, $preferencename) {
756 if ($value === 'none' || empty($value)) {
757 return 'none';
759 $parts = explode('/,/', $value);
760 $processors = array_keys(get_message_processors());
761 array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
762 return $parts ? join(',', $parts) : 'none';
764 return $preferences;