MDL-10965 course: search only courses with completion
[moodle.git] / message / lib.php
blob759a50f90189c74fb8e00d4f39a5a502be1f83d2
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.
351 $eventdata->timecreated = time();
352 $eventdata->notification = 0;
353 return message_send($eventdata);
357 * Get all message processors, validate corresponding plugin existance and
358 * system configuration
360 * @param bool $ready only return ready-to-use processors
361 * @param bool $reset Reset list of message processors (used in unit tests)
362 * @param bool $resetonly Just reset, then exit
363 * @return mixed $processors array of objects containing information on message processors
365 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
366 global $DB, $CFG;
368 static $processors;
369 if ($reset) {
370 $processors = array();
372 if ($resetonly) {
373 return $processors;
377 if (empty($processors)) {
378 // Get all processors, ensure the name column is the first so it will be the array key
379 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
380 foreach ($processors as &$processor){
381 $processor = \core_message\api::get_processed_processor_object($processor);
384 if ($ready) {
385 // Filter out enabled and system_configured processors
386 $readyprocessors = $processors;
387 foreach ($readyprocessors as $readyprocessor) {
388 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
389 unset($readyprocessors[$readyprocessor->name]);
392 return $readyprocessors;
395 return $processors;
399 * Get all message providers, validate their plugin existance and
400 * system configuration
402 * @return mixed $processors array of objects containing information on message processors
404 function get_message_providers() {
405 global $CFG, $DB;
407 $pluginman = core_plugin_manager::instance();
409 $providers = $DB->get_records('message_providers', null, 'name');
411 // Remove all the providers whose plugins are disabled or don't exist
412 foreach ($providers as $providerid => $provider) {
413 $plugin = $pluginman->get_plugin_info($provider->component);
414 if ($plugin) {
415 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
416 unset($providers[$providerid]); // Plugins does not exist
417 continue;
419 if ($plugin->is_enabled() === false) {
420 unset($providers[$providerid]); // Plugin disabled
421 continue;
425 return $providers;
429 * Get an instance of the message_output class for one of the output plugins.
430 * @param string $type the message output type. E.g. 'email' or 'jabber'.
431 * @return message_output message_output the requested class.
433 function get_message_processor($type) {
434 global $CFG;
436 // Note, we cannot use the get_message_processors function here, becaues this
437 // code is called during install after installing each messaging plugin, and
438 // get_message_processors caches the list of installed plugins.
440 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
441 if (!is_readable($processorfile)) {
442 throw new coding_exception('Unknown message processor type ' . $type);
445 include_once($processorfile);
447 $processclass = 'message_output_' . $type;
448 if (!class_exists($processclass)) {
449 throw new coding_exception('Message processor ' . $type .
450 ' does not define the right class');
453 return new $processclass();
457 * Get messaging outputs default (site) preferences
459 * @return object $processors object containing information on message processors
461 function get_message_output_default_preferences() {
462 return get_config('message');
466 * Translate message default settings from binary value to the array of string
467 * representing the settings to be stored. Also validate the provided value and
468 * use default if it is malformed.
470 * @param int $plugindefault Default setting suggested by plugin
471 * @param string $processorname The name of processor
472 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
474 function translate_message_default_setting($plugindefault, $processorname) {
475 // Preset translation arrays
476 $permittedvalues = array(
477 0x04 => 'disallowed',
478 0x08 => 'permitted',
479 0x0c => 'forced',
482 $loggedinstatusvalues = array(
483 0x00 => null, // use null if loggedin/loggedoff is not defined
484 0x01 => 'loggedin',
485 0x02 => 'loggedoff',
488 // define the default setting
489 $processor = get_message_processor($processorname);
490 $default = $processor->get_default_messaging_settings();
492 // Validate the value. It should not exceed the maximum size
493 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
494 debugging(get_string('errortranslatingdefault', 'message'));
495 $plugindefault = $default;
497 // Use plugin default setting of 'permitted' is 0
498 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
499 $plugindefault = $default;
502 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
503 $loggedin = $loggedoff = null;
505 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
506 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
507 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
510 return array($permitted, $loggedin, $loggedoff);
514 * Get messages sent or/and received by the specified users.
515 * Please note that this function return deleted messages too. Besides, only individual conversation messages
516 * are returned to maintain backwards compatibility.
518 * @param int $useridto the user id who received the message
519 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
520 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
521 * @param bool $read true for retrieving read messages, false for unread
522 * @param string $sort the column name to order by including optionally direction
523 * @param int $limitfrom limit from
524 * @param int $limitnum limit num
525 * @return external_description
526 * @since 2.8
528 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
529 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
530 global $DB;
532 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
533 if (empty($useridto)) {
534 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
535 $messageuseridtosql = 'u.id as useridto';
536 } else {
537 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
538 $messageuseridtosql = "$useridto as useridto";
541 // Create the SQL we will be using.
542 $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
543 mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
544 mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
545 FROM {messages} mr
546 INNER JOIN {message_conversations} mc
547 ON mc.id = mr.conversationid
548 INNER JOIN {message_conversation_members} mcm
549 ON mcm.conversationid = mc.id ";
551 $notificationsql = "SELECT mr.*, $userfields, 1 as notification
552 FROM {notifications} mr ";
554 $messagejoinsql = "LEFT JOIN {message_user_actions} mua
555 ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
556 LEFT JOIN {message_user_actions} mua2
557 ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
558 LEFT JOIN {message_user_actions} mua3
559 ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
560 $messagejoinparams = [\core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ,
561 \core_message\api::MESSAGE_ACTION_DELETED];
562 $notificationsparams = [];
564 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
565 if (empty($useridto)) {
566 // Create the messaging query and params.
567 $messagesql .= "INNER JOIN {user} u
568 ON u.id = mcm.userid
569 $messagejoinsql
570 WHERE mr.useridfrom = ?
571 AND mr.useridfrom != mcm.userid
572 AND u.deleted = 0
573 AND mc.type = ? ";
574 $messageparams = array_merge($messagejoinparams, [$useridfrom, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
576 // Create the notifications query and params.
577 $notificationsql .= "INNER JOIN {user} u
578 ON u.id = mr.useridto
579 WHERE mr.useridfrom = ?
580 AND u.deleted = 0 ";
581 $notificationsparams[] = $useridfrom;
582 } else {
583 // Create the messaging query and params.
584 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
585 $messagesql .= "LEFT JOIN {user} u
586 ON u.id = mr.useridfrom
587 $messagejoinsql
588 WHERE mcm.userid = ?
589 AND mr.useridfrom != mcm.userid
590 AND u.deleted = 0
591 AND mc.type = ? ";
592 $messageparams = array_merge($messagejoinparams, [$useridto, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
594 // If we're dealing with messages only and both useridto and useridfrom are set,
595 // try to get a conversation between the users. Break early if we can't find one.
596 if (!empty($useridfrom) && $notifications == 0) {
597 $messagesql .= " AND mr.useridfrom = ? ";
598 $messageparams[] = $useridfrom;
600 // There should be an individual conversation between the users. If not, we can return early.
601 $conversationid = \core_message\api::get_conversation_between_users([$useridto, $useridfrom]);
602 if (empty($conversationid)) {
603 return [];
605 $messagesql .= " AND mc.id = ? ";
606 $messageparams[] = $conversationid;
609 // Create the notifications query and params.
610 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
611 $notificationsql .= "LEFT JOIN {user} u
612 ON (u.id = mr.useridfrom AND u.deleted = 0)
613 WHERE mr.useridto = ? ";
614 $notificationsparams[] = $useridto;
615 if (!empty($useridfrom)) {
616 $notificationsql .= " AND mr.useridfrom = ? ";
617 $notificationsparams[] = $useridfrom;
620 if ($read) {
621 $notificationsql .= "AND mr.timeread IS NOT NULL ";
622 } else {
623 $notificationsql .= "AND mr.timeread IS NULL ";
625 $messagesql .= "ORDER BY $sort";
626 $notificationsql .= "ORDER BY $sort";
628 // Handle messages if needed.
629 if ($notifications === -1 || $notifications === 0) {
630 $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
631 // Get rid of the messages that have either been read or not read depending on the value of $read.
632 $messages = array_filter($messages, function ($message) use ($read) {
633 if ($read) {
634 return !is_null($message->timeread);
637 return is_null($message->timeread);
641 // All.
642 if ($notifications === -1) {
643 return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
644 } else if ($notifications === 1) { // Just notifications.
645 return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
648 // Just messages.
649 return $messages;
653 * Handles displaying processor settings in a fragment.
655 * @param array $args
656 * @return bool|string
657 * @throws moodle_exception
659 function message_output_fragment_processor_settings($args = []) {
660 global $PAGE;
662 if (!isset($args['type'])) {
663 throw new moodle_exception('Must provide a processor type');
666 if (!isset($args['userid'])) {
667 throw new moodle_exception('Must provide a userid');
670 $type = $args['type'];
671 $userid = $args['userid'];
673 $user = core_user::get_user($userid, '*', MUST_EXIST);
674 $processor = get_message_processor($type);
675 $providers = message_get_providers_for_user($userid);
676 $processorwrapper = new stdClass();
677 $processorwrapper->object = $processor;
678 $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
680 $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
681 $renderer = $PAGE->get_renderer('core', 'message');
683 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
687 * Checks if current user is allowed to edit messaging preferences of another user
689 * @param stdClass $user user whose preferences we are updating
690 * @return bool
692 function core_message_can_edit_message_profile($user) {
693 global $USER;
694 if ($user->id == $USER->id) {
695 return has_capability('moodle/user:editownmessageprofile', context_system::instance());
696 } else {
697 $personalcontext = context_user::instance($user->id);
698 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
699 return false;
701 if (isguestuser($user)) {
702 return false;
704 // No editing of admins by non-admins.
705 if (is_siteadmin($user) and !is_siteadmin($USER)) {
706 return false;
708 return true;
713 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
715 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
717 * @return array
719 function core_message_user_preferences() {
720 $preferences = [];
721 $preferences['message_blocknoncontacts'] = array(
722 'type' => PARAM_INT,
723 'null' => NULL_NOT_ALLOWED,
724 'default' => 0,
725 'choices' => array(
726 \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
727 \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
728 \core_message\api::MESSAGE_PRIVACY_SITE
730 'cleancallback' => function ($value) {
731 global $CFG;
733 // When site-wide messaging between users is disabled, MESSAGE_PRIVACY_SITE should be converted.
734 if (empty($CFG->messagingallusers) && $value === \core_message\api::MESSAGE_PRIVACY_SITE) {
735 return \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER;
737 return $value;
740 $preferences['message_entertosend'] = array(
741 'type' => PARAM_BOOL,
742 'null' => NULL_NOT_ALLOWED,
743 'default' => false
745 $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
746 'null' => NULL_NOT_ALLOWED, 'default' => 'none',
747 'permissioncallback' => function ($user, $preferencename) {
748 global $CFG;
749 require_once($CFG->libdir.'/messagelib.php');
750 if (core_message_can_edit_message_profile($user) &&
751 preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
752 $providers = message_get_providers_for_user($user->id);
753 foreach ($providers as $provider) {
754 if ($matches[1] === $provider->component . '_' . $provider->name) {
755 return true;
759 return false;
761 'cleancallback' => function ($value, $preferencename) {
762 if ($value === 'none' || empty($value)) {
763 return 'none';
765 $parts = explode('/,/', $value);
766 $processors = array_keys(get_message_processors());
767 array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
768 return $parts ? join(',', $parts) : 'none';
770 return $preferences;
774 * Renders the popup.
776 * @param renderer_base $renderer
777 * @return string The HTML
779 function core_message_render_navbar_output(\renderer_base $renderer) {
780 global $USER, $CFG;
782 // Early bail out conditions.
783 if (!isloggedin() || isguestuser() || user_not_fully_set_up($USER) ||
784 get_user_preferences('auth_forcepasswordchange') ||
785 (!$USER->policyagreed && !is_siteadmin() &&
786 ($manager = new \core_privacy\local\sitepolicy\manager()) && $manager->is_defined())) {
787 return '';
790 $output = '';
792 // Add the messages popover.
793 if (!empty($CFG->messaging)) {
794 $unreadcount = \core_message\api::count_unread_conversations($USER);
795 $requestcount = \core_message\api::get_received_contact_requests_count($USER->id);
796 $context = [
797 'userid' => $USER->id,
798 'unreadcount' => $unreadcount + $requestcount
800 $output .= $renderer->render_from_template('core_message/message_popover', $context);
803 return $output;
807 * Render the message drawer to be included in the top of the body of each page.
809 * @return string HTML
811 function core_message_standard_after_main_region_html() {
812 return \core_message\helper::render_messaging_widget(true, null, null);