Merge branch 'MDL-56621-master-fix' of http://github.com/damyon/moodle
[moodle.git] / message / lib.php
blob641a14e106b43cbd907bbc804d889a7cc0504a43
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_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
50 define('MESSAGE_UNREAD', 'unread');
51 define('MESSAGE_READ', 'read');
52 define('MESSAGE_TYPE_NOTIFICATION', 'notification');
53 define('MESSAGE_TYPE_MESSAGE', 'message');
55 /**
56 * Define contants for messaging default settings population. For unambiguity of
57 * plugin developer intentions we use 4-bit value (LSB numbering):
58 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
59 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
60 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
62 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
65 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
66 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
68 define('MESSAGE_DISALLOWED', 0x04); // 0100
69 define('MESSAGE_PERMITTED', 0x08); // 1000
70 define('MESSAGE_FORCED', 0x0c); // 1100
72 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
74 /**
75 * Set default value for default outputs permitted setting
77 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
79 /**
80 * Retrieve users blocked by $user1
82 * @param object $user1 the user whose messages are being viewed
83 * @param object $user2 the user $user1 is talking to. If they are being blocked
84 * they will have a variable called 'isblocked' added to their user object
85 * @return array the users blocked by $user1
87 function message_get_blocked_users($user1=null, $user2=null) {
88 global $DB, $USER;
90 if (empty($user1)) {
91 $user1 = $USER;
94 if (!empty($user2)) {
95 $user2->isblocked = false;
98 $blockedusers = array();
100 $userfields = user_picture::fields('u', array('lastaccess'));
101 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
102 FROM {message_contacts} mc
103 JOIN {user} u ON u.id = mc.contactid
104 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
105 WHERE u.deleted = 0 AND mc.userid = :user1id2 AND mc.blocked = 1
106 GROUP BY $userfields
107 ORDER BY u.firstname ASC";
108 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
110 foreach($rs as $rd) {
111 $blockedusers[] = $rd;
113 if (!empty($user2) && $user2->id == $rd->id) {
114 $user2->isblocked = true;
117 $rs->close();
119 return $blockedusers;
123 * Retrieve $user1's contacts (online, offline and strangers)
125 * @param object $user1 the user whose messages are being viewed
126 * @param object $user2 the user $user1 is talking to. If they are a contact
127 * they will have a variable called 'iscontact' added to their user object
128 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
130 function message_get_contacts($user1=null, $user2=null) {
131 global $DB, $CFG, $USER;
133 if (empty($user1)) {
134 $user1 = $USER;
137 if (!empty($user2)) {
138 $user2->iscontact = false;
141 $timetoshowusers = 300; //Seconds default
142 if (isset($CFG->block_online_users_timetosee)) {
143 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
146 // time which a user is counting as being active since
147 $timefrom = time()-$timetoshowusers;
149 // people in our contactlist who are online
150 $onlinecontacts = array();
151 // people in our contactlist who are offline
152 $offlinecontacts = array();
153 // people who are not in our contactlist but have sent us a message
154 $strangers = array();
156 $userfields = user_picture::fields('u', array('lastaccess'));
158 // get all in our contactlist who are not blocked in our contact list
159 // and count messages we have waiting from each of them
160 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
161 FROM {message_contacts} mc
162 JOIN {user} u ON u.id = mc.contactid
163 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
164 WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0
165 GROUP BY $userfields
166 ORDER BY u.firstname ASC";
168 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
169 foreach ($rs as $rd) {
170 if ($rd->lastaccess >= $timefrom) {
171 // they have been active recently, so are counted online
172 $onlinecontacts[] = $rd;
174 } else {
175 $offlinecontacts[] = $rd;
178 if (!empty($user2) && $user2->id == $rd->id) {
179 $user2->iscontact = true;
182 $rs->close();
184 // get messages from anyone who isn't in our contact list and count the number
185 // of messages we have from each of them
186 $strangersql = "SELECT $userfields, count(m.id) as messagecount
187 FROM {message} m
188 JOIN {user} u ON u.id = m.useridfrom
189 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
190 WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ?
191 GROUP BY $userfields
192 ORDER BY u.firstname ASC";
194 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
195 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
196 foreach ($rs as $rd) {
197 $strangers[$rd->id] = $rd;
199 $rs->close();
201 // Add noreply user and support user to the list, if they don't exist.
202 $supportuser = core_user::get_support_user();
203 if (!isset($strangers[$supportuser->id])) {
204 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
205 if ($supportuser->messagecount > 0) {
206 $strangers[$supportuser->id] = $supportuser;
210 $noreplyuser = core_user::get_noreply_user();
211 if (!isset($strangers[$noreplyuser->id])) {
212 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
213 if ($noreplyuser->messagecount > 0) {
214 $strangers[$noreplyuser->id] = $noreplyuser;
217 return array($onlinecontacts, $offlinecontacts, $strangers);
221 * Returns the count of unread messages for user. Either from a specific user or from all users.
223 * @param object $user1 the first user. Defaults to $USER
224 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
225 * @return int the count of $user1's unread messages
227 function message_count_unread_messages($user1=null, $user2=null) {
228 global $USER, $DB;
230 if (empty($user1)) {
231 $user1 = $USER;
234 if (!empty($user2)) {
235 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
236 array($user1->id, $user2->id), "COUNT('id')");
237 } else {
238 return $DB->count_records_select('message', "useridto = ?",
239 array($user1->id), "COUNT('id')");
244 * Get the users recent conversations meaning all the people they've recently
245 * sent or received a message from plus the most recent message sent to or received from each other user
247 * @param object|int $userorid the current user or user id
248 * @param int $limitfrom can be used for paging
249 * @param int $limitto can be used for paging
250 * @return array
252 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
253 global $DB;
255 if (is_object($userorid)) {
256 $user = $userorid;
257 } else {
258 $userid = $userorid;
259 $user = new stdClass();
260 $user->id = $userid;
263 $userfields = user_picture::fields('otheruser', array('lastaccess'));
265 // This query retrieves the most recent message received from or sent to
266 // seach other user.
268 // If two messages have the same timecreated, we take the one with the
269 // larger id.
271 // There is a separate query for read and unread messages as they are stored
272 // in different tables. They were originally retrieved in one query but it
273 // was so large that it was difficult to be confident in its correctness.
274 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
275 $sql = "SELECT $uniquefield, $userfields,
276 message.id as mid, message.notification, message.useridfrom, message.useridto,
277 message.smallmessage, message.fullmessage, message.fullmessagehtml,
278 message.fullmessageformat, message.timecreated,
279 contact.id as contactlistid, contact.blocked
280 FROM {message_read} message
281 JOIN (
282 SELECT MAX(id) AS messageid,
283 matchedmessage.useridto,
284 matchedmessage.useridfrom
285 FROM {message_read} matchedmessage
286 INNER JOIN (
287 SELECT MAX(recentmessages.timecreated) timecreated,
288 recentmessages.useridfrom,
289 recentmessages.useridto
290 FROM {message_read} recentmessages
291 WHERE (
292 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
293 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
295 GROUP BY recentmessages.useridfrom, recentmessages.useridto
296 ) recent ON matchedmessage.useridto = recent.useridto
297 AND matchedmessage.useridfrom = recent.useridfrom
298 AND matchedmessage.timecreated = recent.timecreated
299 WHERE (
300 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
301 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
303 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
304 ) messagesubset ON messagesubset.messageid = message.id
305 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
306 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
307 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.contactid = otheruser.id
308 WHERE otheruser.deleted = 0 AND message.notification = 0
309 ORDER BY message.timecreated DESC";
310 $params = array(
311 'userid1' => $user->id,
312 'userid2' => $user->id,
313 'userid3' => $user->id,
314 'userid4' => $user->id,
315 'userid5' => $user->id,
316 'userid6' => $user->id,
317 'userid7' => $user->id
319 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
321 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
322 // exact same query as the one above, except for the table we are querying. So, simply replace references to
323 // the 'message_read' table with the 'message' table.
324 $sql = str_replace('{message_read}', '{message}', $sql);
325 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
327 $unreadcountssql = 'SELECT useridfrom, count(*) as count
328 FROM {message}
329 WHERE useridto = :userid
330 AND timeusertodeleted = 0
331 AND notification = 0
332 GROUP BY useridfrom';
333 $unreadcounts = $DB->get_records_sql($unreadcountssql, array('userid' => $user->id));
335 // Union the 2 result sets together looking for the message with the most
336 // recent timecreated for each other user.
337 // $conversation->id (the array key) is the other user's ID.
338 $conversations = array();
339 $conversation_arrays = array($unread, $read);
340 foreach ($conversation_arrays as $conversation_array) {
341 foreach ($conversation_array as $conversation) {
342 // Only consider it unread if $user has unread messages.
343 if (isset($unreadcounts[$conversation->useridfrom])) {
344 $conversation->isread = 0;
345 $conversation->unreadcount = $unreadcounts[$conversation->useridfrom]->count;
346 } else {
347 $conversation->isread = 1;
350 if (!isset($conversations[$conversation->id])) {
351 $conversations[$conversation->id] = $conversation;
352 } else {
353 $current = $conversations[$conversation->id];
354 // We need to maintain the isread and unreadcount values from existing
355 // parts of the conversation if we're replacing it.
356 $conversation->isread = ($conversation->isread && $current->isread);
357 if (isset($current->unreadcount) && !isset($conversation->unreadcount)) {
358 $conversation->unreadcount = $current->unreadcount;
361 if ($current->timecreated < $conversation->timecreated) {
362 $conversations[$conversation->id] = $conversation;
363 } else if ($current->timecreated == $conversation->timecreated) {
364 if ($current->mid < $conversation->mid) {
365 $conversations[$conversation->id] = $conversation;
372 // Sort the conversations by $conversation->timecreated, newest to oldest
373 // There may be multiple conversations with the same timecreated
374 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
375 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
376 $conversations = array_reverse($conversations);
378 return $conversations;
382 * Try to guess how to convert the message to html.
384 * @access private
386 * @param stdClass $message
387 * @param bool $forcetexttohtml
388 * @return string html fragment
390 function message_format_message_text($message, $forcetexttohtml = false) {
391 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
393 $options = new stdClass();
394 $options->para = false;
395 $options->blanktarget = true;
397 $format = $message->fullmessageformat;
399 if (strval($message->smallmessage) !== '') {
400 if ($message->notification == 1) {
401 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
402 $format = FORMAT_PLAIN;
405 $messagetext = $message->smallmessage;
407 } else if ($message->fullmessageformat == FORMAT_HTML) {
408 if (strval($message->fullmessagehtml) !== '') {
409 $messagetext = $message->fullmessagehtml;
410 } else {
411 $messagetext = $message->fullmessage;
412 $format = FORMAT_MOODLE;
415 } else {
416 if (strval($message->fullmessage) !== '') {
417 $messagetext = $message->fullmessage;
418 } else {
419 $messagetext = $message->fullmessagehtml;
420 $format = FORMAT_HTML;
424 if ($forcetexttohtml) {
425 // This is a crazy hack, why not set proper format when creating the notifications?
426 if ($format === FORMAT_PLAIN) {
427 $format = FORMAT_MOODLE;
430 return format_text($messagetext, $format, $options);
434 * Add the selected user as a contact for the current user
436 * @param int $contactid the ID of the user to add as a contact
437 * @param int $blocked 1 if you wish to block the contact
438 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
439 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
440 * Otherwise returns the result of update_record() or insert_record()
442 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
443 global $USER, $DB;
445 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
446 return false;
449 if (empty($userid)) {
450 $userid = $USER->id;
453 // Check if a record already exists as we may be changing blocking status.
454 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
455 // Check if blocking status has been changed.
456 if ($contact->blocked != $blocked) {
457 $contact->blocked = $blocked;
458 $DB->update_record('message_contacts', $contact);
460 if ($blocked == 1) {
461 // Trigger event for blocking a contact.
462 $event = \core\event\message_contact_blocked::create(array(
463 'objectid' => $contact->id,
464 'userid' => $contact->userid,
465 'relateduserid' => $contact->contactid,
466 'context' => context_user::instance($contact->userid)
468 $event->add_record_snapshot('message_contacts', $contact);
469 $event->trigger();
470 } else {
471 // Trigger event for unblocking a contact.
472 $event = \core\event\message_contact_unblocked::create(array(
473 'objectid' => $contact->id,
474 'userid' => $contact->userid,
475 'relateduserid' => $contact->contactid,
476 'context' => context_user::instance($contact->userid)
478 $event->add_record_snapshot('message_contacts', $contact);
479 $event->trigger();
482 return true;
483 } else {
484 // No change to blocking status.
485 return true;
488 } else {
489 // New contact record.
490 $contact = new stdClass();
491 $contact->userid = $userid;
492 $contact->contactid = $contactid;
493 $contact->blocked = $blocked;
494 $contact->id = $DB->insert_record('message_contacts', $contact);
496 $eventparams = array(
497 'objectid' => $contact->id,
498 'userid' => $contact->userid,
499 'relateduserid' => $contact->contactid,
500 'context' => context_user::instance($contact->userid)
503 if ($blocked) {
504 $event = \core\event\message_contact_blocked::create($eventparams);
505 } else {
506 $event = \core\event\message_contact_added::create($eventparams);
508 // Trigger event.
509 $event->trigger();
511 return true;
516 * remove a contact
518 * @param int $contactid the user ID of the contact to remove
519 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
520 * @return bool returns the result of delete_records()
522 function message_remove_contact($contactid, $userid = 0) {
523 global $USER, $DB;
525 if (empty($userid)) {
526 $userid = $USER->id;
529 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
530 $DB->delete_records('message_contacts', array('id' => $contact->id));
532 // Trigger event for removing a contact.
533 $event = \core\event\message_contact_removed::create(array(
534 'objectid' => $contact->id,
535 'userid' => $contact->userid,
536 'relateduserid' => $contact->contactid,
537 'context' => context_user::instance($contact->userid)
539 $event->add_record_snapshot('message_contacts', $contact);
540 $event->trigger();
542 return true;
545 return false;
549 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
551 * @param int $contactid the user ID of the contact to unblock
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 returns the result of delete_records()
556 function message_unblock_contact($contactid, $userid = 0) {
557 return message_add_contact($contactid, 0, $userid);
561 * Block a user.
563 * @param int $contactid the user ID of the user to block
564 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
565 * if not specified.
566 * @return bool
568 function message_block_contact($contactid, $userid = 0) {
569 return message_add_contact($contactid, 1, $userid);
573 * Checks if a user can delete a message.
575 * @param stdClass $message the message to delete
576 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
577 * but will still seem as if it was by the user)
578 * @return bool Returns true if a user can delete the message, false otherwise.
580 function message_can_delete_message($message, $userid) {
581 global $USER;
583 if ($message->useridfrom == $userid) {
584 $userdeleting = 'useridfrom';
585 } else if ($message->useridto == $userid) {
586 $userdeleting = 'useridto';
587 } else {
588 return false;
591 $systemcontext = context_system::instance();
593 // Let's check if the user is allowed to delete this message.
594 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
595 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
596 $USER->id == $message->$userdeleting))) {
597 return true;
600 return false;
604 * Deletes a message.
606 * This function does not verify any permissions.
608 * @param stdClass $message the message to delete
609 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
610 * but will still seem as if it was by the user)
611 * @return bool
613 function message_delete_message($message, $userid) {
614 global $DB;
616 // The column we want to alter.
617 if ($message->useridfrom == $userid) {
618 $coltimedeleted = 'timeuserfromdeleted';
619 } else if ($message->useridto == $userid) {
620 $coltimedeleted = 'timeusertodeleted';
621 } else {
622 return false;
625 // Don't update it if it's already been deleted.
626 if ($message->$coltimedeleted > 0) {
627 return false;
630 // Get the table we want to update.
631 if (isset($message->timeread)) {
632 $messagetable = 'message_read';
633 } else {
634 $messagetable = 'message';
637 // Mark the message as deleted.
638 $updatemessage = new stdClass();
639 $updatemessage->id = $message->id;
640 $updatemessage->$coltimedeleted = time();
641 $success = $DB->update_record($messagetable, $updatemessage);
643 if ($success) {
644 // Trigger event for deleting a message.
645 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
646 $userid, $messagetable, $message->id)->trigger();
649 return $success;
653 * Load a user's contact record
655 * @param int $contactid the user ID of the user whose contact record you want
656 * @return array message contacts
658 function message_get_contact($contactid) {
659 global $USER, $DB;
660 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
664 * Search through course users.
666 * If $courseids contains the site course then this function searches
667 * through all undeleted and confirmed users.
669 * @param int|array $courseids Course ID or array of course IDs.
670 * @param string $searchtext the text to search for.
671 * @param string $sort the column name to order by.
672 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
673 * @return array An array of {@link $USER} records.
675 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
676 global $CFG, $USER, $DB;
678 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
679 if (!$courseids) {
680 $courseids = array(SITEID);
683 // Allow an integer to be passed.
684 if (!is_array($courseids)) {
685 $courseids = array($courseids);
688 $fullname = $DB->sql_fullname();
689 $ufields = user_picture::fields('u');
691 if (!empty($sort)) {
692 $order = ' ORDER BY '. $sort;
693 } else {
694 $order = '';
697 $params = array(
698 'userid' => $USER->id,
699 'query' => "%$searchtext%"
702 if (empty($exceptions)) {
703 $exceptions = array();
704 } else if (!empty($exceptions) && is_string($exceptions)) {
705 $exceptions = explode(',', $exceptions);
708 // Ignore self and guest account.
709 $exceptions[] = $USER->id;
710 $exceptions[] = $CFG->siteguest;
712 // Exclude exceptions from the search result.
713 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
714 $except = ' AND u.id ' . $except;
715 $params = array_merge($params_except, $params);
717 if (in_array(SITEID, $courseids)) {
718 // Search on site level.
719 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
720 FROM {user} u
721 LEFT JOIN {message_contacts} mc
722 ON mc.contactid = u.id AND mc.userid = :userid
723 WHERE u.deleted = '0' AND u.confirmed = '1'
724 AND (".$DB->sql_like($fullname, ':query', false).")
725 $except
726 $order", $params);
727 } else {
728 // Search in courses.
730 // Getting the context IDs or each course.
731 $contextids = array();
732 foreach ($courseids as $courseid) {
733 $context = context_course::instance($courseid);
734 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
736 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
737 $params = array_merge($params, $contextparams);
739 // Everyone who has a role assignment in this course or higher.
740 // TODO: add enabled enrolment join here (skodak)
741 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
742 FROM {user} u
743 JOIN {role_assignments} ra ON ra.userid = u.id
744 LEFT JOIN {message_contacts} mc
745 ON mc.contactid = u.id AND mc.userid = :userid
746 WHERE u.deleted = '0' AND u.confirmed = '1'
747 AND (".$DB->sql_like($fullname, ':query', false).")
748 AND ra.contextid $contextwhere
749 $except
750 $order", $params);
752 return $users;
757 * Format a message for display in the message history
759 * @param object $message the message object
760 * @param string $format optional date format
761 * @param string $keywords keywords to highlight
762 * @param string $class CSS class to apply to the div around the message
763 * @return string the formatted message
765 function message_format_message($message, $format='', $keywords='', $class='other') {
767 static $dateformat;
769 //if we haven't previously set the date format or they've supplied a new one
770 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
771 if ($format) {
772 $dateformat = $format;
773 } else {
774 $dateformat = get_string('strftimedatetimeshort');
777 $time = userdate($message->timecreated, $dateformat);
779 $messagetext = message_format_message_text($message, false);
781 if ($keywords) {
782 $messagetext = highlight($keywords, $messagetext);
785 $messagetext .= message_format_contexturl($message);
787 $messagetext = clean_text($messagetext, FORMAT_HTML);
789 return <<<TEMPLATE
790 <div class='message $class'>
791 <a name="m{$message->id}"></a>
792 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
793 </div>
794 TEMPLATE;
798 * Format a the context url and context url name of a message for display
800 * @param object $message the message object
801 * @return string the formatted string
803 function message_format_contexturl($message) {
804 $s = null;
806 if (!empty($message->contexturl)) {
807 $displaytext = null;
808 if (!empty($message->contexturlname)) {
809 $displaytext= $message->contexturlname;
810 } else {
811 $displaytext= $message->contexturl;
813 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
814 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
815 $s .= html_writer::end_tag('div');
818 return $s;
822 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
824 * @param object $userfrom the message sender
825 * @param object $userto the message recipient
826 * @param string $message the message
827 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
828 * @return int|false the ID of the new message or false
830 function message_post_message($userfrom, $userto, $message, $format) {
831 global $SITE, $CFG, $USER;
833 $eventdata = new \core\message\message();
834 $eventdata->courseid = 1;
835 $eventdata->component = 'moodle';
836 $eventdata->name = 'instantmessage';
837 $eventdata->userfrom = $userfrom;
838 $eventdata->userto = $userto;
840 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
841 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
843 if ($format == FORMAT_HTML) {
844 $eventdata->fullmessagehtml = $message;
845 //some message processors may revert to sending plain text even if html is supplied
846 //so we keep both plain and html versions if we're intending to send html
847 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
848 } else {
849 $eventdata->fullmessage = $message;
850 $eventdata->fullmessagehtml = '';
853 $eventdata->fullmessageformat = $format;
854 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
856 $s = new stdClass();
857 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
858 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
860 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
861 if (!empty($eventdata->fullmessage)) {
862 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
864 if (!empty($eventdata->fullmessagehtml)) {
865 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
868 $eventdata->timecreated = time();
869 $eventdata->notification = 0;
870 return message_send($eventdata);
874 * Moves messages from a particular user from the message table (unread messages) to message_read
875 * This is typically only used when a user is deleted
877 * @param object $userid User id
878 * @return boolean success
880 function message_move_userfrom_unread2read($userid) {
881 global $DB;
883 // move all unread messages from message table to message_read
884 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
885 foreach ($messages as $message) {
886 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
889 return true;
893 * Mark a single message as read
895 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
896 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
897 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
898 * @return int the ID of the message in the message_read table
900 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
901 global $DB;
903 $message->timeread = $timeread;
905 $messageid = $message->id;
906 unset($message->id);//unset because it will get a new id on insert into message_read
908 //If any processors have pending actions abort them
909 if (!$messageworkingempty) {
910 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
912 $messagereadid = $DB->insert_record('message_read', $message);
914 $DB->delete_records('message', array('id' => $messageid));
916 // Get the context for the user who received the message.
917 $context = context_user::instance($message->useridto, IGNORE_MISSING);
918 // If the user no longer exists the context value will be false, in this case use the system context.
919 if ($context === false) {
920 $context = context_system::instance();
923 // Trigger event for reading a message.
924 $event = \core\event\message_viewed::create(array(
925 'objectid' => $messagereadid,
926 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
927 'context' => $context,
928 'relateduserid' => $message->useridfrom,
929 'other' => array(
930 'messageid' => $messageid
933 $event->trigger();
935 return $messagereadid;
939 * Get all message processors, validate corresponding plugin existance and
940 * system configuration
942 * @param bool $ready only return ready-to-use processors
943 * @param bool $reset Reset list of message processors (used in unit tests)
944 * @param bool $resetonly Just reset, then exit
945 * @return mixed $processors array of objects containing information on message processors
947 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
948 global $DB, $CFG;
950 static $processors;
951 if ($reset) {
952 $processors = array();
954 if ($resetonly) {
955 return $processors;
959 if (empty($processors)) {
960 // Get all processors, ensure the name column is the first so it will be the array key
961 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
962 foreach ($processors as &$processor){
963 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
964 if (is_readable($processorfile)) {
965 include_once($processorfile);
966 $processclass = 'message_output_' . $processor->name;
967 if (class_exists($processclass)) {
968 $pclass = new $processclass();
969 $processor->object = $pclass;
970 $processor->configured = 0;
971 if ($pclass->is_system_configured()) {
972 $processor->configured = 1;
974 $processor->hassettings = 0;
975 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
976 $processor->hassettings = 1;
978 $processor->available = 1;
979 } else {
980 print_error('errorcallingprocessor', 'message');
982 } else {
983 $processor->available = 0;
987 if ($ready) {
988 // Filter out enabled and system_configured processors
989 $readyprocessors = $processors;
990 foreach ($readyprocessors as $readyprocessor) {
991 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
992 unset($readyprocessors[$readyprocessor->name]);
995 return $readyprocessors;
998 return $processors;
1002 * Get all message providers, validate their plugin existance and
1003 * system configuration
1005 * @return mixed $processors array of objects containing information on message processors
1007 function get_message_providers() {
1008 global $CFG, $DB;
1010 $pluginman = core_plugin_manager::instance();
1012 $providers = $DB->get_records('message_providers', null, 'name');
1014 // Remove all the providers whose plugins are disabled or don't exist
1015 foreach ($providers as $providerid => $provider) {
1016 $plugin = $pluginman->get_plugin_info($provider->component);
1017 if ($plugin) {
1018 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
1019 unset($providers[$providerid]); // Plugins does not exist
1020 continue;
1022 if ($plugin->is_enabled() === false) {
1023 unset($providers[$providerid]); // Plugin disabled
1024 continue;
1028 return $providers;
1032 * Get an instance of the message_output class for one of the output plugins.
1033 * @param string $type the message output type. E.g. 'email' or 'jabber'.
1034 * @return message_output message_output the requested class.
1036 function get_message_processor($type) {
1037 global $CFG;
1039 // Note, we cannot use the get_message_processors function here, becaues this
1040 // code is called during install after installing each messaging plugin, and
1041 // get_message_processors caches the list of installed plugins.
1043 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
1044 if (!is_readable($processorfile)) {
1045 throw new coding_exception('Unknown message processor type ' . $type);
1048 include_once($processorfile);
1050 $processclass = 'message_output_' . $type;
1051 if (!class_exists($processclass)) {
1052 throw new coding_exception('Message processor ' . $type .
1053 ' does not define the right class');
1056 return new $processclass();
1060 * Get messaging outputs default (site) preferences
1062 * @return object $processors object containing information on message processors
1064 function get_message_output_default_preferences() {
1065 return get_config('message');
1069 * Translate message default settings from binary value to the array of string
1070 * representing the settings to be stored. Also validate the provided value and
1071 * use default if it is malformed.
1073 * @param int $plugindefault Default setting suggested by plugin
1074 * @param string $processorname The name of processor
1075 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
1077 function translate_message_default_setting($plugindefault, $processorname) {
1078 // Preset translation arrays
1079 $permittedvalues = array(
1080 0x04 => 'disallowed',
1081 0x08 => 'permitted',
1082 0x0c => 'forced',
1085 $loggedinstatusvalues = array(
1086 0x00 => null, // use null if loggedin/loggedoff is not defined
1087 0x01 => 'loggedin',
1088 0x02 => 'loggedoff',
1091 // define the default setting
1092 $processor = get_message_processor($processorname);
1093 $default = $processor->get_default_messaging_settings();
1095 // Validate the value. It should not exceed the maximum size
1096 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
1097 debugging(get_string('errortranslatingdefault', 'message'));
1098 $plugindefault = $default;
1100 // Use plugin default setting of 'permitted' is 0
1101 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
1102 $plugindefault = $default;
1105 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
1106 $loggedin = $loggedoff = null;
1108 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
1109 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
1110 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
1113 return array($permitted, $loggedin, $loggedoff);
1117 * Get messages sent or/and received by the specified users.
1118 * Please note that this function return deleted messages too.
1120 * @param int $useridto the user id who received the message
1121 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
1122 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
1123 * @param bool $read true for retrieving read messages, false for unread
1124 * @param string $sort the column name to order by including optionally direction
1125 * @param int $limitfrom limit from
1126 * @param int $limitnum limit num
1127 * @return external_description
1128 * @since 2.8
1130 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
1131 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
1132 global $DB;
1134 $messagetable = $read ? '{message_read}' : '{message}';
1135 $params = array('deleted' => 0);
1137 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
1138 if (empty($useridto)) {
1139 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
1140 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
1141 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
1142 $params['useridfrom'] = $useridfrom;
1143 } else {
1144 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
1145 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
1146 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
1147 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
1148 $params['useridto'] = $useridto;
1149 if (!empty($useridfrom)) {
1150 $usersql .= " AND mr.useridfrom = :useridfrom";
1151 $params['useridfrom'] = $useridfrom;
1155 // Now, if retrieve notifications, conversations or both.
1156 $typesql = "";
1157 if ($notifications !== -1) {
1158 $typesql = "AND mr.notification = :notification";
1159 $params['notification'] = ($notifications) ? 1 : 0;
1162 $sql = "SELECT mr.*, $userfields
1163 FROM $messagetable mr
1164 $joinsql
1165 WHERE $usersql
1166 $typesql
1167 ORDER BY $sort";
1169 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1170 return $messages;
1174 * Handles displaying processor settings in a fragment.
1176 * @param array $args
1177 * @return bool|string
1178 * @throws moodle_exception
1180 function message_output_fragment_processor_settings($args = []) {
1181 global $PAGE;
1183 if (!isset($args['type'])) {
1184 throw new moodle_exception('Must provide a processor type');
1187 if (!isset($args['userid'])) {
1188 throw new moodle_exception('Must provide a userid');
1191 $type = $args['type'];
1192 $userid = $args['userid'];
1194 $user = core_user::get_user($userid, '*', MUST_EXIST);
1195 $processor = get_message_processor($type);
1196 $providers = message_get_providers_for_user($userid);
1197 $processorwrapper = new stdClass();
1198 $processorwrapper->object = $processor;
1199 $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
1201 $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
1202 $renderer = $PAGE->get_renderer('core', 'message');
1204 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));