Merge branch 'MDL-62945-master' of https://github.com/HuongNV13/moodle
[moodle.git] / message / lib.php
blob2c1df4ad8a2fe30faf3f5f52a353e89769f0002d
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;
96 return $DB->count_records_sql($sql, $params);
99 /**
100 * Try to guess how to convert the message to html.
102 * @access private
104 * @param stdClass $message
105 * @param bool $forcetexttohtml
106 * @return string html fragment
108 function message_format_message_text($message, $forcetexttohtml = false) {
109 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
111 $options = new stdClass();
112 $options->para = false;
113 $options->blanktarget = true;
115 $format = $message->fullmessageformat;
117 if (strval($message->smallmessage) !== '') {
118 if (!empty($message->notification)) {
119 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
120 $format = FORMAT_PLAIN;
123 $messagetext = $message->smallmessage;
125 } else if ($message->fullmessageformat == FORMAT_HTML) {
126 if (strval($message->fullmessagehtml) !== '') {
127 $messagetext = $message->fullmessagehtml;
128 } else {
129 $messagetext = $message->fullmessage;
130 $format = FORMAT_MOODLE;
133 } else {
134 if (strval($message->fullmessage) !== '') {
135 $messagetext = $message->fullmessage;
136 } else {
137 $messagetext = $message->fullmessagehtml;
138 $format = FORMAT_HTML;
142 if ($forcetexttohtml) {
143 // This is a crazy hack, why not set proper format when creating the notifications?
144 if ($format === FORMAT_PLAIN) {
145 $format = FORMAT_MOODLE;
148 return format_text($messagetext, $format, $options);
152 * Add the selected user as a contact for the current user
154 * @param int $contactid the ID of the user to add as a contact
155 * @param int $blocked 1 if you wish to block the contact
156 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
157 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
158 * Otherwise returns the result of update_record() or insert_record()
160 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
161 global $USER, $DB;
163 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
164 return false;
167 if (empty($userid)) {
168 $userid = $USER->id;
171 // Check if a record already exists as we may be changing blocking status.
172 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
173 // Check if blocking status has been changed.
174 if ($contact->blocked != $blocked) {
175 $contact->blocked = $blocked;
176 $DB->update_record('message_contacts', $contact);
178 if ($blocked == 1) {
179 // Trigger event for blocking a contact.
180 $event = \core\event\message_contact_blocked::create(array(
181 'objectid' => $contact->id,
182 'userid' => $contact->userid,
183 'relateduserid' => $contact->contactid,
184 'context' => context_user::instance($contact->userid)
186 $event->add_record_snapshot('message_contacts', $contact);
187 $event->trigger();
188 } else {
189 // Trigger event for unblocking a contact.
190 $event = \core\event\message_contact_unblocked::create(array(
191 'objectid' => $contact->id,
192 'userid' => $contact->userid,
193 'relateduserid' => $contact->contactid,
194 'context' => context_user::instance($contact->userid)
196 $event->add_record_snapshot('message_contacts', $contact);
197 $event->trigger();
200 return true;
201 } else {
202 // No change to blocking status.
203 return true;
206 } else {
207 // New contact record.
208 $contact = new stdClass();
209 $contact->userid = $userid;
210 $contact->contactid = $contactid;
211 $contact->blocked = $blocked;
212 $contact->id = $DB->insert_record('message_contacts', $contact);
214 $eventparams = array(
215 'objectid' => $contact->id,
216 'userid' => $contact->userid,
217 'relateduserid' => $contact->contactid,
218 'context' => context_user::instance($contact->userid)
221 if ($blocked) {
222 $event = \core\event\message_contact_blocked::create($eventparams);
223 } else {
224 $event = \core\event\message_contact_added::create($eventparams);
226 // Trigger event.
227 $event->trigger();
229 return true;
234 * remove a contact
236 * @param int $contactid the user ID of the contact to remove
237 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
238 * @return bool returns the result of delete_records()
240 function message_remove_contact($contactid, $userid = 0) {
241 global $USER, $DB;
243 if (empty($userid)) {
244 $userid = $USER->id;
247 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
248 $DB->delete_records('message_contacts', array('id' => $contact->id));
250 // Trigger event for removing a contact.
251 $event = \core\event\message_contact_removed::create(array(
252 'objectid' => $contact->id,
253 'userid' => $contact->userid,
254 'relateduserid' => $contact->contactid,
255 'context' => context_user::instance($contact->userid)
257 $event->add_record_snapshot('message_contacts', $contact);
258 $event->trigger();
260 return true;
263 return false;
267 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
269 * @param int $contactid the user ID of the contact to unblock
270 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
271 * if not specified.
272 * @return bool returns the result of delete_records()
274 function message_unblock_contact($contactid, $userid = 0) {
275 return message_add_contact($contactid, 0, $userid);
279 * Block a user.
281 * @param int $contactid the user ID of the user to block
282 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
283 * if not specified.
284 * @return bool
286 function message_block_contact($contactid, $userid = 0) {
287 return message_add_contact($contactid, 1, $userid);
291 * Load a user's contact record
293 * @param int $contactid the user ID of the user whose contact record you want
294 * @return array message contacts
296 function message_get_contact($contactid) {
297 global $USER, $DB;
298 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
302 * Search through course users.
304 * If $courseids contains the site course then this function searches
305 * through all undeleted and confirmed users.
307 * @param int|array $courseids Course ID or array of course IDs.
308 * @param string $searchtext the text to search for.
309 * @param string $sort the column name to order by.
310 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
311 * @return array An array of {@link $USER} records.
313 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
314 global $CFG, $USER, $DB;
316 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
317 if (!$courseids) {
318 $courseids = array(SITEID);
321 // Allow an integer to be passed.
322 if (!is_array($courseids)) {
323 $courseids = array($courseids);
326 $fullname = $DB->sql_fullname();
327 $ufields = user_picture::fields('u');
329 if (!empty($sort)) {
330 $order = ' ORDER BY '. $sort;
331 } else {
332 $order = '';
335 $params = array(
336 'userid' => $USER->id,
337 'query' => "%$searchtext%"
340 if (empty($exceptions)) {
341 $exceptions = array();
342 } else if (!empty($exceptions) && is_string($exceptions)) {
343 $exceptions = explode(',', $exceptions);
346 // Ignore self and guest account.
347 $exceptions[] = $USER->id;
348 $exceptions[] = $CFG->siteguest;
350 // Exclude exceptions from the search result.
351 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
352 $except = ' AND u.id ' . $except;
353 $params = array_merge($params_except, $params);
355 if (in_array(SITEID, $courseids)) {
356 // Search on site level.
357 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
358 FROM {user} u
359 LEFT JOIN {message_contacts} mc
360 ON mc.contactid = u.id AND mc.userid = :userid
361 WHERE u.deleted = '0' AND u.confirmed = '1'
362 AND (".$DB->sql_like($fullname, ':query', false).")
363 $except
364 $order", $params);
365 } else {
366 // Search in courses.
368 // Getting the context IDs or each course.
369 $contextids = array();
370 foreach ($courseids as $courseid) {
371 $context = context_course::instance($courseid);
372 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
374 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
375 $params = array_merge($params, $contextparams);
377 // Everyone who has a role assignment in this course or higher.
378 // TODO: add enabled enrolment join here (skodak)
379 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
380 FROM {user} u
381 JOIN {role_assignments} ra ON ra.userid = u.id
382 LEFT JOIN {message_contacts} mc
383 ON mc.contactid = u.id AND mc.userid = :userid
384 WHERE u.deleted = '0' AND u.confirmed = '1'
385 AND (".$DB->sql_like($fullname, ':query', false).")
386 AND ra.contextid $contextwhere
387 $except
388 $order", $params);
390 return $users;
395 * Format a message for display in the message history
397 * @param object $message the message object
398 * @param string $format optional date format
399 * @param string $keywords keywords to highlight
400 * @param string $class CSS class to apply to the div around the message
401 * @return string the formatted message
403 function message_format_message($message, $format='', $keywords='', $class='other') {
405 static $dateformat;
407 //if we haven't previously set the date format or they've supplied a new one
408 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
409 if ($format) {
410 $dateformat = $format;
411 } else {
412 $dateformat = get_string('strftimedatetimeshort');
415 $time = userdate($message->timecreated, $dateformat);
417 $messagetext = message_format_message_text($message, false);
419 if ($keywords) {
420 $messagetext = highlight($keywords, $messagetext);
423 $messagetext .= message_format_contexturl($message);
425 $messagetext = clean_text($messagetext, FORMAT_HTML);
427 return <<<TEMPLATE
428 <div class='message $class'>
429 <a name="m{$message->id}"></a>
430 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
431 </div>
432 TEMPLATE;
436 * Format a the context url and context url name of a message for display
438 * @param object $message the message object
439 * @return string the formatted string
441 function message_format_contexturl($message) {
442 $s = null;
444 if (!empty($message->contexturl)) {
445 $displaytext = null;
446 if (!empty($message->contexturlname)) {
447 $displaytext= $message->contexturlname;
448 } else {
449 $displaytext= $message->contexturl;
451 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
452 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
453 $s .= html_writer::end_tag('div');
456 return $s;
460 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
462 * @param object $userfrom the message sender
463 * @param object $userto the message recipient
464 * @param string $message the message
465 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
466 * @return int|false the ID of the new message or false
468 function message_post_message($userfrom, $userto, $message, $format) {
469 global $SITE, $CFG, $USER;
471 $eventdata = new \core\message\message();
472 $eventdata->courseid = 1;
473 $eventdata->component = 'moodle';
474 $eventdata->name = 'instantmessage';
475 $eventdata->userfrom = $userfrom;
476 $eventdata->userto = $userto;
478 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
479 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
481 if ($format == FORMAT_HTML) {
482 $eventdata->fullmessagehtml = $message;
483 //some message processors may revert to sending plain text even if html is supplied
484 //so we keep both plain and html versions if we're intending to send html
485 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
486 } else {
487 $eventdata->fullmessage = $message;
488 $eventdata->fullmessagehtml = '';
491 $eventdata->fullmessageformat = $format;
492 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
494 $s = new stdClass();
495 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
496 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
498 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
499 if (!empty($eventdata->fullmessage)) {
500 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
502 if (!empty($eventdata->fullmessagehtml)) {
503 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
506 $eventdata->timecreated = time();
507 $eventdata->notification = 0;
508 return message_send($eventdata);
512 * Get all message processors, validate corresponding plugin existance and
513 * system configuration
515 * @param bool $ready only return ready-to-use processors
516 * @param bool $reset Reset list of message processors (used in unit tests)
517 * @param bool $resetonly Just reset, then exit
518 * @return mixed $processors array of objects containing information on message processors
520 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
521 global $DB, $CFG;
523 static $processors;
524 if ($reset) {
525 $processors = array();
527 if ($resetonly) {
528 return $processors;
532 if (empty($processors)) {
533 // Get all processors, ensure the name column is the first so it will be the array key
534 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
535 foreach ($processors as &$processor){
536 $processor = \core_message\api::get_processed_processor_object($processor);
539 if ($ready) {
540 // Filter out enabled and system_configured processors
541 $readyprocessors = $processors;
542 foreach ($readyprocessors as $readyprocessor) {
543 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
544 unset($readyprocessors[$readyprocessor->name]);
547 return $readyprocessors;
550 return $processors;
554 * Get all message providers, validate their plugin existance and
555 * system configuration
557 * @return mixed $processors array of objects containing information on message processors
559 function get_message_providers() {
560 global $CFG, $DB;
562 $pluginman = core_plugin_manager::instance();
564 $providers = $DB->get_records('message_providers', null, 'name');
566 // Remove all the providers whose plugins are disabled or don't exist
567 foreach ($providers as $providerid => $provider) {
568 $plugin = $pluginman->get_plugin_info($provider->component);
569 if ($plugin) {
570 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
571 unset($providers[$providerid]); // Plugins does not exist
572 continue;
574 if ($plugin->is_enabled() === false) {
575 unset($providers[$providerid]); // Plugin disabled
576 continue;
580 return $providers;
584 * Get an instance of the message_output class for one of the output plugins.
585 * @param string $type the message output type. E.g. 'email' or 'jabber'.
586 * @return message_output message_output the requested class.
588 function get_message_processor($type) {
589 global $CFG;
591 // Note, we cannot use the get_message_processors function here, becaues this
592 // code is called during install after installing each messaging plugin, and
593 // get_message_processors caches the list of installed plugins.
595 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
596 if (!is_readable($processorfile)) {
597 throw new coding_exception('Unknown message processor type ' . $type);
600 include_once($processorfile);
602 $processclass = 'message_output_' . $type;
603 if (!class_exists($processclass)) {
604 throw new coding_exception('Message processor ' . $type .
605 ' does not define the right class');
608 return new $processclass();
612 * Get messaging outputs default (site) preferences
614 * @return object $processors object containing information on message processors
616 function get_message_output_default_preferences() {
617 return get_config('message');
621 * Translate message default settings from binary value to the array of string
622 * representing the settings to be stored. Also validate the provided value and
623 * use default if it is malformed.
625 * @param int $plugindefault Default setting suggested by plugin
626 * @param string $processorname The name of processor
627 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
629 function translate_message_default_setting($plugindefault, $processorname) {
630 // Preset translation arrays
631 $permittedvalues = array(
632 0x04 => 'disallowed',
633 0x08 => 'permitted',
634 0x0c => 'forced',
637 $loggedinstatusvalues = array(
638 0x00 => null, // use null if loggedin/loggedoff is not defined
639 0x01 => 'loggedin',
640 0x02 => 'loggedoff',
643 // define the default setting
644 $processor = get_message_processor($processorname);
645 $default = $processor->get_default_messaging_settings();
647 // Validate the value. It should not exceed the maximum size
648 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
649 debugging(get_string('errortranslatingdefault', 'message'));
650 $plugindefault = $default;
652 // Use plugin default setting of 'permitted' is 0
653 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
654 $plugindefault = $default;
657 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
658 $loggedin = $loggedoff = null;
660 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
661 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
662 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
665 return array($permitted, $loggedin, $loggedoff);
669 * Get messages sent or/and received by the specified users.
670 * Please note that this function return deleted messages too.
672 * @param int $useridto the user id who received the message
673 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
674 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
675 * @param bool $read true for retrieving read messages, false for unread
676 * @param string $sort the column name to order by including optionally direction
677 * @param int $limitfrom limit from
678 * @param int $limitnum limit num
679 * @return external_description
680 * @since 2.8
682 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
683 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
684 global $DB;
686 // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
687 if (empty($useridto)) {
688 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
689 $messageuseridtosql = 'u.id as useridto';
690 } else {
691 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
692 $messageuseridtosql = "$useridto as useridto";
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, $messageuseridtosql
699 FROM {messages} mr
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
722 ON u.id = mcm.userid
723 $messagejoinsql
724 WHERE mr.useridfrom = ?
725 AND mr.useridfrom != mcm.userid
726 AND u.deleted = 0 ";
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 = ?
733 AND u.deleted = 0 ";
734 $notificationsparams[] = $useridfrom;
735 } else {
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
740 $messagejoinsql
741 WHERE mcm.userid = ?
742 AND mr.useridfrom != mcm.userid
743 AND u.deleted = 0 ";
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;
761 if ($read) {
762 $notificationsql .= "AND mr.timeread IS NOT NULL ";
763 } else {
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) {
774 if ($read) {
775 return !is_null($message->timeread);
778 return is_null($message->timeread);
782 // All.
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);
789 // Just messages.
790 return $messages;
794 * Handles displaying processor settings in a fragment.
796 * @param array $args
797 * @return bool|string
798 * @throws moodle_exception
800 function message_output_fragment_processor_settings($args = []) {
801 global $PAGE;
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
831 * @return bool
833 function core_message_can_edit_message_profile($user) {
834 global $USER;
835 if ($user->id == $USER->id) {
836 return has_capability('moodle/user:editownmessageprofile', context_system::instance());
837 } else {
838 $personalcontext = context_user::instance($user->id);
839 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
840 return false;
842 if (isguestuser($user)) {
843 return false;
845 // No editing of admins by non-admins.
846 if (is_siteadmin($user) and !is_siteadmin($USER)) {
847 return false;
849 return true;
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()}
858 * @return array
860 function core_message_user_preferences() {
862 $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) {
868 global $CFG;
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) {
875 return true;
879 return false;
881 'cleancallback' => function ($value, $preferencename) {
882 if ($value === 'none' || empty($value)) {
883 return 'none';
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';
890 return $preferences;