MDL-56553 tool_usertours: change add a block step to position right
[moodle.git] / message / lib.php
blobd79fdc7042111ff5b9cd592728962bdadddb5399
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 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');
36 /**
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
55 /**
56 * Set default value for default outputs permitted setting
58 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
60 /**
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);
67 /**
68 * Retrieve users blocked by $user1
70 * @param object $user1 the user whose messages are being viewed
71 * @param object $user2 the user $user1 is talking to. If they are being blocked
72 * they will have a variable called 'isblocked' added to their user object
73 * @return array the users blocked by $user1
75 function message_get_blocked_users($user1=null, $user2=null) {
76 global $DB, $USER;
78 if (empty($user1)) {
79 $user1 = $USER;
82 if (!empty($user2)) {
83 $user2->isblocked = false;
86 $blockedusers = array();
88 $userfields = user_picture::fields('u', array('lastaccess'));
89 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
90 FROM {message_contacts} mc
91 JOIN {user} u ON u.id = mc.contactid
92 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
93 WHERE u.deleted = 0 AND mc.userid = :user1id2 AND mc.blocked = 1
94 GROUP BY $userfields
95 ORDER BY u.firstname ASC";
96 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
98 foreach($rs as $rd) {
99 $blockedusers[] = $rd;
101 if (!empty($user2) && $user2->id == $rd->id) {
102 $user2->isblocked = true;
105 $rs->close();
107 return $blockedusers;
111 * Retrieve $user1's contacts (online, offline and strangers)
113 * @param object $user1 the user whose messages are being viewed
114 * @param object $user2 the user $user1 is talking to. If they are a contact
115 * they will have a variable called 'iscontact' added to their user object
116 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
118 function message_get_contacts($user1=null, $user2=null) {
119 global $DB, $CFG, $USER;
121 if (empty($user1)) {
122 $user1 = $USER;
125 if (!empty($user2)) {
126 $user2->iscontact = false;
129 $timetoshowusers = 300; //Seconds default
130 if (isset($CFG->block_online_users_timetosee)) {
131 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
134 // time which a user is counting as being active since
135 $timefrom = time()-$timetoshowusers;
137 // people in our contactlist who are online
138 $onlinecontacts = array();
139 // people in our contactlist who are offline
140 $offlinecontacts = array();
141 // people who are not in our contactlist but have sent us a message
142 $strangers = array();
144 $userfields = user_picture::fields('u', array('lastaccess'));
146 // get all in our contactlist who are not blocked in our contact list
147 // and count messages we have waiting from each of them
148 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
149 FROM {message_contacts} mc
150 JOIN {user} u ON u.id = mc.contactid
151 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
152 WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0
153 GROUP BY $userfields
154 ORDER BY u.firstname ASC";
156 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
157 foreach ($rs as $rd) {
158 if ($rd->lastaccess >= $timefrom) {
159 // they have been active recently, so are counted online
160 $onlinecontacts[] = $rd;
162 } else {
163 $offlinecontacts[] = $rd;
166 if (!empty($user2) && $user2->id == $rd->id) {
167 $user2->iscontact = true;
170 $rs->close();
172 // get messages from anyone who isn't in our contact list and count the number
173 // of messages we have from each of them
174 $strangersql = "SELECT $userfields, count(m.id) as messagecount
175 FROM {message} m
176 JOIN {user} u ON u.id = m.useridfrom
177 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
178 WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ?
179 GROUP BY $userfields
180 ORDER BY u.firstname ASC";
182 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
183 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
184 foreach ($rs as $rd) {
185 $strangers[$rd->id] = $rd;
187 $rs->close();
189 // Add noreply user and support user to the list, if they don't exist.
190 $supportuser = core_user::get_support_user();
191 if (!isset($strangers[$supportuser->id])) {
192 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
193 if ($supportuser->messagecount > 0) {
194 $strangers[$supportuser->id] = $supportuser;
198 $noreplyuser = core_user::get_noreply_user();
199 if (!isset($strangers[$noreplyuser->id])) {
200 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
201 if ($noreplyuser->messagecount > 0) {
202 $strangers[$noreplyuser->id] = $noreplyuser;
205 return array($onlinecontacts, $offlinecontacts, $strangers);
209 * Returns the count of unread messages for user. Either from a specific user or from all users.
211 * @param object $user1 the first user. Defaults to $USER
212 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
213 * @return int the count of $user1's unread messages
215 function message_count_unread_messages($user1=null, $user2=null) {
216 global $USER, $DB;
218 if (empty($user1)) {
219 $user1 = $USER;
222 if (!empty($user2)) {
223 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
224 array($user1->id, $user2->id), "COUNT('id')");
225 } else {
226 return $DB->count_records_select('message', "useridto = ?",
227 array($user1->id), "COUNT('id')");
232 * Get the users recent conversations meaning all the people they've recently
233 * sent or received a message from plus the most recent message sent to or received from each other user
235 * @param object|int $userorid the current user or user id
236 * @param int $limitfrom can be used for paging
237 * @param int $limitto can be used for paging
238 * @return array
240 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
241 global $DB;
243 if (is_object($userorid)) {
244 $user = $userorid;
245 } else {
246 $userid = $userorid;
247 $user = new stdClass();
248 $user->id = $userid;
251 $userfields = user_picture::fields('otheruser', array('lastaccess'));
253 // This query retrieves the most recent message received from or sent to
254 // seach other user.
256 // If two messages have the same timecreated, we take the one with the
257 // larger id.
259 // There is a separate query for read and unread messages as they are stored
260 // in different tables. They were originally retrieved in one query but it
261 // was so large that it was difficult to be confident in its correctness.
262 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
263 $sql = "SELECT $uniquefield, $userfields,
264 message.id as mid, message.notification, message.useridfrom, message.useridto,
265 message.smallmessage, message.fullmessage, message.fullmessagehtml,
266 message.fullmessageformat, message.timecreated,
267 contact.id as contactlistid, contact.blocked
268 FROM {message_read} message
269 JOIN (
270 SELECT MAX(id) AS messageid,
271 matchedmessage.useridto,
272 matchedmessage.useridfrom
273 FROM {message_read} matchedmessage
274 INNER JOIN (
275 SELECT MAX(recentmessages.timecreated) timecreated,
276 recentmessages.useridfrom,
277 recentmessages.useridto
278 FROM {message_read} recentmessages
279 WHERE (
280 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
281 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
283 GROUP BY recentmessages.useridfrom, recentmessages.useridto
284 ) recent ON matchedmessage.useridto = recent.useridto
285 AND matchedmessage.useridfrom = recent.useridfrom
286 AND matchedmessage.timecreated = recent.timecreated
287 WHERE (
288 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
289 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
291 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
292 ) messagesubset ON messagesubset.messageid = message.id
293 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
294 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
295 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.contactid = otheruser.id
296 WHERE otheruser.deleted = 0 AND message.notification = 0
297 ORDER BY message.timecreated DESC";
298 $params = array(
299 'userid1' => $user->id,
300 'userid2' => $user->id,
301 'userid3' => $user->id,
302 'userid4' => $user->id,
303 'userid5' => $user->id,
304 'userid6' => $user->id,
305 'userid7' => $user->id
307 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
309 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
310 // exact same query as the one above, except for the table we are querying. So, simply replace references to
311 // the 'message_read' table with the 'message' table.
312 $sql = str_replace('{message_read}', '{message}', $sql);
313 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
315 $unreadcountssql = 'SELECT useridfrom, count(*) as count
316 FROM {message}
317 WHERE useridto = :userid
318 AND timeusertodeleted = 0
319 AND notification = 0
320 GROUP BY useridfrom';
321 $unreadcounts = $DB->get_records_sql($unreadcountssql, array('userid' => $user->id));
323 // Union the 2 result sets together looking for the message with the most
324 // recent timecreated for each other user.
325 // $conversation->id (the array key) is the other user's ID.
326 $conversations = array();
327 $conversation_arrays = array($unread, $read);
328 foreach ($conversation_arrays as $conversation_array) {
329 foreach ($conversation_array as $conversation) {
330 // Only consider it unread if $user has unread messages.
331 if (isset($unreadcounts[$conversation->useridfrom])) {
332 $conversation->isread = 0;
333 $conversation->unreadcount = $unreadcounts[$conversation->useridfrom]->count;
334 } else {
335 $conversation->isread = 1;
338 if (!isset($conversations[$conversation->id])) {
339 $conversations[$conversation->id] = $conversation;
340 } else {
341 $current = $conversations[$conversation->id];
342 // We need to maintain the isread and unreadcount values from existing
343 // parts of the conversation if we're replacing it.
344 $conversation->isread = ($conversation->isread && $current->isread);
345 if (isset($current->unreadcount) && !isset($conversation->unreadcount)) {
346 $conversation->unreadcount = $current->unreadcount;
349 if ($current->timecreated < $conversation->timecreated) {
350 $conversations[$conversation->id] = $conversation;
351 } else if ($current->timecreated == $conversation->timecreated) {
352 if ($current->mid < $conversation->mid) {
353 $conversations[$conversation->id] = $conversation;
360 // Sort the conversations by $conversation->timecreated, newest to oldest
361 // There may be multiple conversations with the same timecreated
362 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
363 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
364 $conversations = array_reverse($conversations);
366 return $conversations;
370 * Try to guess how to convert the message to html.
372 * @access private
374 * @param stdClass $message
375 * @param bool $forcetexttohtml
376 * @return string html fragment
378 function message_format_message_text($message, $forcetexttohtml = false) {
379 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
381 $options = new stdClass();
382 $options->para = false;
383 $options->blanktarget = true;
385 $format = $message->fullmessageformat;
387 if (strval($message->smallmessage) !== '') {
388 if ($message->notification == 1) {
389 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
390 $format = FORMAT_PLAIN;
393 $messagetext = $message->smallmessage;
395 } else if ($message->fullmessageformat == FORMAT_HTML) {
396 if (strval($message->fullmessagehtml) !== '') {
397 $messagetext = $message->fullmessagehtml;
398 } else {
399 $messagetext = $message->fullmessage;
400 $format = FORMAT_MOODLE;
403 } else {
404 if (strval($message->fullmessage) !== '') {
405 $messagetext = $message->fullmessage;
406 } else {
407 $messagetext = $message->fullmessagehtml;
408 $format = FORMAT_HTML;
412 if ($forcetexttohtml) {
413 // This is a crazy hack, why not set proper format when creating the notifications?
414 if ($format === FORMAT_PLAIN) {
415 $format = FORMAT_MOODLE;
418 return format_text($messagetext, $format, $options);
422 * Add the selected user as a contact for the current user
424 * @param int $contactid the ID of the user to add as a contact
425 * @param int $blocked 1 if you wish to block the contact
426 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
427 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
428 * Otherwise returns the result of update_record() or insert_record()
430 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
431 global $USER, $DB;
433 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
434 return false;
437 if (empty($userid)) {
438 $userid = $USER->id;
441 // Check if a record already exists as we may be changing blocking status.
442 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
443 // Check if blocking status has been changed.
444 if ($contact->blocked != $blocked) {
445 $contact->blocked = $blocked;
446 $DB->update_record('message_contacts', $contact);
448 if ($blocked == 1) {
449 // Trigger event for blocking a contact.
450 $event = \core\event\message_contact_blocked::create(array(
451 'objectid' => $contact->id,
452 'userid' => $contact->userid,
453 'relateduserid' => $contact->contactid,
454 'context' => context_user::instance($contact->userid)
456 $event->add_record_snapshot('message_contacts', $contact);
457 $event->trigger();
458 } else {
459 // Trigger event for unblocking a contact.
460 $event = \core\event\message_contact_unblocked::create(array(
461 'objectid' => $contact->id,
462 'userid' => $contact->userid,
463 'relateduserid' => $contact->contactid,
464 'context' => context_user::instance($contact->userid)
466 $event->add_record_snapshot('message_contacts', $contact);
467 $event->trigger();
470 return true;
471 } else {
472 // No change to blocking status.
473 return true;
476 } else {
477 // New contact record.
478 $contact = new stdClass();
479 $contact->userid = $userid;
480 $contact->contactid = $contactid;
481 $contact->blocked = $blocked;
482 $contact->id = $DB->insert_record('message_contacts', $contact);
484 $eventparams = array(
485 'objectid' => $contact->id,
486 'userid' => $contact->userid,
487 'relateduserid' => $contact->contactid,
488 'context' => context_user::instance($contact->userid)
491 if ($blocked) {
492 $event = \core\event\message_contact_blocked::create($eventparams);
493 } else {
494 $event = \core\event\message_contact_added::create($eventparams);
496 // Trigger event.
497 $event->trigger();
499 return true;
504 * remove a contact
506 * @param int $contactid the user ID of the contact to remove
507 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
508 * @return bool returns the result of delete_records()
510 function message_remove_contact($contactid, $userid = 0) {
511 global $USER, $DB;
513 if (empty($userid)) {
514 $userid = $USER->id;
517 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
518 $DB->delete_records('message_contacts', array('id' => $contact->id));
520 // Trigger event for removing a contact.
521 $event = \core\event\message_contact_removed::create(array(
522 'objectid' => $contact->id,
523 'userid' => $contact->userid,
524 'relateduserid' => $contact->contactid,
525 'context' => context_user::instance($contact->userid)
527 $event->add_record_snapshot('message_contacts', $contact);
528 $event->trigger();
530 return true;
533 return false;
537 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
539 * @param int $contactid the user ID of the contact to unblock
540 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
541 * if not specified.
542 * @return bool returns the result of delete_records()
544 function message_unblock_contact($contactid, $userid = 0) {
545 return message_add_contact($contactid, 0, $userid);
549 * Block a user.
551 * @param int $contactid the user ID of the user to block
552 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
553 * if not specified.
554 * @return bool
556 function message_block_contact($contactid, $userid = 0) {
557 return message_add_contact($contactid, 1, $userid);
561 * Checks if a user can delete a message.
563 * @param stdClass $message the message to delete
564 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
565 * but will still seem as if it was by the user)
566 * @return bool Returns true if a user can delete the message, false otherwise.
568 function message_can_delete_message($message, $userid) {
569 global $USER;
571 if ($message->useridfrom == $userid) {
572 $userdeleting = 'useridfrom';
573 } else if ($message->useridto == $userid) {
574 $userdeleting = 'useridto';
575 } else {
576 return false;
579 $systemcontext = context_system::instance();
581 // Let's check if the user is allowed to delete this message.
582 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
583 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
584 $USER->id == $message->$userdeleting))) {
585 return true;
588 return false;
592 * Deletes a message.
594 * This function does not verify any permissions.
596 * @param stdClass $message the message to delete
597 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
598 * but will still seem as if it was by the user)
599 * @return bool
601 function message_delete_message($message, $userid) {
602 global $DB;
604 // The column we want to alter.
605 if ($message->useridfrom == $userid) {
606 $coltimedeleted = 'timeuserfromdeleted';
607 } else if ($message->useridto == $userid) {
608 $coltimedeleted = 'timeusertodeleted';
609 } else {
610 return false;
613 // Don't update it if it's already been deleted.
614 if ($message->$coltimedeleted > 0) {
615 return false;
618 // Get the table we want to update.
619 if (isset($message->timeread)) {
620 $messagetable = 'message_read';
621 } else {
622 $messagetable = 'message';
625 // Mark the message as deleted.
626 $updatemessage = new stdClass();
627 $updatemessage->id = $message->id;
628 $updatemessage->$coltimedeleted = time();
629 $success = $DB->update_record($messagetable, $updatemessage);
631 if ($success) {
632 // Trigger event for deleting a message.
633 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
634 $userid, $messagetable, $message->id)->trigger();
637 return $success;
641 * Load a user's contact record
643 * @param int $contactid the user ID of the user whose contact record you want
644 * @return array message contacts
646 function message_get_contact($contactid) {
647 global $USER, $DB;
648 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
652 * Search through course users.
654 * If $courseids contains the site course then this function searches
655 * through all undeleted and confirmed users.
657 * @param int|array $courseids Course ID or array of course IDs.
658 * @param string $searchtext the text to search for.
659 * @param string $sort the column name to order by.
660 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
661 * @return array An array of {@link $USER} records.
663 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
664 global $CFG, $USER, $DB;
666 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
667 if (!$courseids) {
668 $courseids = array(SITEID);
671 // Allow an integer to be passed.
672 if (!is_array($courseids)) {
673 $courseids = array($courseids);
676 $fullname = $DB->sql_fullname();
677 $ufields = user_picture::fields('u');
679 if (!empty($sort)) {
680 $order = ' ORDER BY '. $sort;
681 } else {
682 $order = '';
685 $params = array(
686 'userid' => $USER->id,
687 'query' => "%$searchtext%"
690 if (empty($exceptions)) {
691 $exceptions = array();
692 } else if (!empty($exceptions) && is_string($exceptions)) {
693 $exceptions = explode(',', $exceptions);
696 // Ignore self and guest account.
697 $exceptions[] = $USER->id;
698 $exceptions[] = $CFG->siteguest;
700 // Exclude exceptions from the search result.
701 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
702 $except = ' AND u.id ' . $except;
703 $params = array_merge($params_except, $params);
705 if (in_array(SITEID, $courseids)) {
706 // Search on site level.
707 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
708 FROM {user} u
709 LEFT JOIN {message_contacts} mc
710 ON mc.contactid = u.id AND mc.userid = :userid
711 WHERE u.deleted = '0' AND u.confirmed = '1'
712 AND (".$DB->sql_like($fullname, ':query', false).")
713 $except
714 $order", $params);
715 } else {
716 // Search in courses.
718 // Getting the context IDs or each course.
719 $contextids = array();
720 foreach ($courseids as $courseid) {
721 $context = context_course::instance($courseid);
722 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
724 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
725 $params = array_merge($params, $contextparams);
727 // Everyone who has a role assignment in this course or higher.
728 // TODO: add enabled enrolment join here (skodak)
729 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
730 FROM {user} u
731 JOIN {role_assignments} ra ON ra.userid = u.id
732 LEFT JOIN {message_contacts} mc
733 ON mc.contactid = u.id AND mc.userid = :userid
734 WHERE u.deleted = '0' AND u.confirmed = '1'
735 AND (".$DB->sql_like($fullname, ':query', false).")
736 AND ra.contextid $contextwhere
737 $except
738 $order", $params);
740 return $users;
745 * Format a message for display in the message history
747 * @param object $message the message object
748 * @param string $format optional date format
749 * @param string $keywords keywords to highlight
750 * @param string $class CSS class to apply to the div around the message
751 * @return string the formatted message
753 function message_format_message($message, $format='', $keywords='', $class='other') {
755 static $dateformat;
757 //if we haven't previously set the date format or they've supplied a new one
758 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
759 if ($format) {
760 $dateformat = $format;
761 } else {
762 $dateformat = get_string('strftimedatetimeshort');
765 $time = userdate($message->timecreated, $dateformat);
767 $messagetext = message_format_message_text($message, false);
769 if ($keywords) {
770 $messagetext = highlight($keywords, $messagetext);
773 $messagetext .= message_format_contexturl($message);
775 $messagetext = clean_text($messagetext, FORMAT_HTML);
777 return <<<TEMPLATE
778 <div class='message $class'>
779 <a name="m{$message->id}"></a>
780 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
781 </div>
782 TEMPLATE;
786 * Format a the context url and context url name of a message for display
788 * @param object $message the message object
789 * @return string the formatted string
791 function message_format_contexturl($message) {
792 $s = null;
794 if (!empty($message->contexturl)) {
795 $displaytext = null;
796 if (!empty($message->contexturlname)) {
797 $displaytext= $message->contexturlname;
798 } else {
799 $displaytext= $message->contexturl;
801 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
802 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
803 $s .= html_writer::end_tag('div');
806 return $s;
810 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
812 * @param object $userfrom the message sender
813 * @param object $userto the message recipient
814 * @param string $message the message
815 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
816 * @return int|false the ID of the new message or false
818 function message_post_message($userfrom, $userto, $message, $format) {
819 global $SITE, $CFG, $USER;
821 $eventdata = new \core\message\message();
822 $eventdata->courseid = 1;
823 $eventdata->component = 'moodle';
824 $eventdata->name = 'instantmessage';
825 $eventdata->userfrom = $userfrom;
826 $eventdata->userto = $userto;
828 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
829 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
831 if ($format == FORMAT_HTML) {
832 $eventdata->fullmessagehtml = $message;
833 //some message processors may revert to sending plain text even if html is supplied
834 //so we keep both plain and html versions if we're intending to send html
835 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
836 } else {
837 $eventdata->fullmessage = $message;
838 $eventdata->fullmessagehtml = '';
841 $eventdata->fullmessageformat = $format;
842 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
844 $s = new stdClass();
845 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
846 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
848 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
849 if (!empty($eventdata->fullmessage)) {
850 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
852 if (!empty($eventdata->fullmessagehtml)) {
853 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
856 $eventdata->timecreated = time();
857 $eventdata->notification = 0;
858 return message_send($eventdata);
862 * Moves messages from a particular user from the message table (unread messages) to message_read
863 * This is typically only used when a user is deleted
865 * @param object $userid User id
866 * @return boolean success
868 function message_move_userfrom_unread2read($userid) {
869 global $DB;
871 // move all unread messages from message table to message_read
872 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
873 foreach ($messages as $message) {
874 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
877 return true;
881 * Mark a single message as read
883 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
884 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
885 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
886 * @return int the ID of the message in the message_read table
888 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
889 global $DB;
891 $message->timeread = $timeread;
893 $messageid = $message->id;
894 unset($message->id);//unset because it will get a new id on insert into message_read
896 //If any processors have pending actions abort them
897 if (!$messageworkingempty) {
898 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
900 $messagereadid = $DB->insert_record('message_read', $message);
902 $DB->delete_records('message', array('id' => $messageid));
904 // Get the context for the user who received the message.
905 $context = context_user::instance($message->useridto, IGNORE_MISSING);
906 // If the user no longer exists the context value will be false, in this case use the system context.
907 if ($context === false) {
908 $context = context_system::instance();
911 // Trigger event for reading a message.
912 $event = \core\event\message_viewed::create(array(
913 'objectid' => $messagereadid,
914 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
915 'context' => $context,
916 'relateduserid' => $message->useridfrom,
917 'other' => array(
918 'messageid' => $messageid
921 $event->trigger();
923 return $messagereadid;
927 * Get all message processors, validate corresponding plugin existance and
928 * system configuration
930 * @param bool $ready only return ready-to-use processors
931 * @param bool $reset Reset list of message processors (used in unit tests)
932 * @param bool $resetonly Just reset, then exit
933 * @return mixed $processors array of objects containing information on message processors
935 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
936 global $DB, $CFG;
938 static $processors;
939 if ($reset) {
940 $processors = array();
942 if ($resetonly) {
943 return $processors;
947 if (empty($processors)) {
948 // Get all processors, ensure the name column is the first so it will be the array key
949 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
950 foreach ($processors as &$processor){
951 $processor = \core_message\api::get_processed_processor_object($processor);
954 if ($ready) {
955 // Filter out enabled and system_configured processors
956 $readyprocessors = $processors;
957 foreach ($readyprocessors as $readyprocessor) {
958 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
959 unset($readyprocessors[$readyprocessor->name]);
962 return $readyprocessors;
965 return $processors;
969 * Get all message providers, validate their plugin existance and
970 * system configuration
972 * @return mixed $processors array of objects containing information on message processors
974 function get_message_providers() {
975 global $CFG, $DB;
977 $pluginman = core_plugin_manager::instance();
979 $providers = $DB->get_records('message_providers', null, 'name');
981 // Remove all the providers whose plugins are disabled or don't exist
982 foreach ($providers as $providerid => $provider) {
983 $plugin = $pluginman->get_plugin_info($provider->component);
984 if ($plugin) {
985 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
986 unset($providers[$providerid]); // Plugins does not exist
987 continue;
989 if ($plugin->is_enabled() === false) {
990 unset($providers[$providerid]); // Plugin disabled
991 continue;
995 return $providers;
999 * Get an instance of the message_output class for one of the output plugins.
1000 * @param string $type the message output type. E.g. 'email' or 'jabber'.
1001 * @return message_output message_output the requested class.
1003 function get_message_processor($type) {
1004 global $CFG;
1006 // Note, we cannot use the get_message_processors function here, becaues this
1007 // code is called during install after installing each messaging plugin, and
1008 // get_message_processors caches the list of installed plugins.
1010 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
1011 if (!is_readable($processorfile)) {
1012 throw new coding_exception('Unknown message processor type ' . $type);
1015 include_once($processorfile);
1017 $processclass = 'message_output_' . $type;
1018 if (!class_exists($processclass)) {
1019 throw new coding_exception('Message processor ' . $type .
1020 ' does not define the right class');
1023 return new $processclass();
1027 * Get messaging outputs default (site) preferences
1029 * @return object $processors object containing information on message processors
1031 function get_message_output_default_preferences() {
1032 return get_config('message');
1036 * Translate message default settings from binary value to the array of string
1037 * representing the settings to be stored. Also validate the provided value and
1038 * use default if it is malformed.
1040 * @param int $plugindefault Default setting suggested by plugin
1041 * @param string $processorname The name of processor
1042 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
1044 function translate_message_default_setting($plugindefault, $processorname) {
1045 // Preset translation arrays
1046 $permittedvalues = array(
1047 0x04 => 'disallowed',
1048 0x08 => 'permitted',
1049 0x0c => 'forced',
1052 $loggedinstatusvalues = array(
1053 0x00 => null, // use null if loggedin/loggedoff is not defined
1054 0x01 => 'loggedin',
1055 0x02 => 'loggedoff',
1058 // define the default setting
1059 $processor = get_message_processor($processorname);
1060 $default = $processor->get_default_messaging_settings();
1062 // Validate the value. It should not exceed the maximum size
1063 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
1064 debugging(get_string('errortranslatingdefault', 'message'));
1065 $plugindefault = $default;
1067 // Use plugin default setting of 'permitted' is 0
1068 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
1069 $plugindefault = $default;
1072 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
1073 $loggedin = $loggedoff = null;
1075 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
1076 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
1077 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
1080 return array($permitted, $loggedin, $loggedoff);
1084 * Get messages sent or/and received by the specified users.
1085 * Please note that this function return deleted messages too.
1087 * @param int $useridto the user id who received the message
1088 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
1089 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
1090 * @param bool $read true for retrieving read messages, false for unread
1091 * @param string $sort the column name to order by including optionally direction
1092 * @param int $limitfrom limit from
1093 * @param int $limitnum limit num
1094 * @return external_description
1095 * @since 2.8
1097 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
1098 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
1099 global $DB;
1101 $messagetable = $read ? '{message_read}' : '{message}';
1102 $params = array('deleted' => 0);
1104 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
1105 if (empty($useridto)) {
1106 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
1107 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
1108 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
1109 $params['useridfrom'] = $useridfrom;
1110 } else {
1111 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
1112 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
1113 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
1114 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
1115 $params['useridto'] = $useridto;
1116 if (!empty($useridfrom)) {
1117 $usersql .= " AND mr.useridfrom = :useridfrom";
1118 $params['useridfrom'] = $useridfrom;
1122 // Now, if retrieve notifications, conversations or both.
1123 $typesql = "";
1124 if ($notifications !== -1) {
1125 $typesql = "AND mr.notification = :notification";
1126 $params['notification'] = ($notifications) ? 1 : 0;
1129 $sql = "SELECT mr.*, $userfields
1130 FROM $messagetable mr
1131 $joinsql
1132 WHERE $usersql
1133 $typesql
1134 ORDER BY $sort";
1136 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1137 return $messages;
1141 * Handles displaying processor settings in a fragment.
1143 * @param array $args
1144 * @return bool|string
1145 * @throws moodle_exception
1147 function message_output_fragment_processor_settings($args = []) {
1148 global $PAGE;
1150 if (!isset($args['type'])) {
1151 throw new moodle_exception('Must provide a processor type');
1154 if (!isset($args['userid'])) {
1155 throw new moodle_exception('Must provide a userid');
1158 $type = $args['type'];
1159 $userid = $args['userid'];
1161 $user = core_user::get_user($userid, '*', MUST_EXIST);
1162 $processor = get_message_processor($type);
1163 $providers = message_get_providers_for_user($userid);
1164 $processorwrapper = new stdClass();
1165 $processorwrapper->object = $processor;
1166 $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
1168 $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
1169 $renderer = $PAGE->get_renderer('core', 'message');
1171 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));