NOBUG: Fixed SVG browser compatibility
[moodle.git] / message / lib.php
blob90f7a293ef4dd3e09e814ca4e9ed104ca631ef8a
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 = ? AND notification = 0
224 AND timeusertodeleted = 0",
225 array($user1->id, $user2->id), "COUNT('id')");
226 } else {
227 return $DB->count_records_select('message', "useridto = ? AND notification = 0
228 AND timeusertodeleted = 0",
229 array($user1->id), "COUNT('id')");
234 * Try to guess how to convert the message to html.
236 * @access private
238 * @param stdClass $message
239 * @param bool $forcetexttohtml
240 * @return string html fragment
242 function message_format_message_text($message, $forcetexttohtml = false) {
243 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
245 $options = new stdClass();
246 $options->para = false;
247 $options->blanktarget = true;
249 $format = $message->fullmessageformat;
251 if (strval($message->smallmessage) !== '') {
252 if ($message->notification == 1) {
253 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
254 $format = FORMAT_PLAIN;
257 $messagetext = $message->smallmessage;
259 } else if ($message->fullmessageformat == FORMAT_HTML) {
260 if (strval($message->fullmessagehtml) !== '') {
261 $messagetext = $message->fullmessagehtml;
262 } else {
263 $messagetext = $message->fullmessage;
264 $format = FORMAT_MOODLE;
267 } else {
268 if (strval($message->fullmessage) !== '') {
269 $messagetext = $message->fullmessage;
270 } else {
271 $messagetext = $message->fullmessagehtml;
272 $format = FORMAT_HTML;
276 if ($forcetexttohtml) {
277 // This is a crazy hack, why not set proper format when creating the notifications?
278 if ($format === FORMAT_PLAIN) {
279 $format = FORMAT_MOODLE;
282 return format_text($messagetext, $format, $options);
286 * Add the selected user as a contact for the current user
288 * @param int $contactid the ID of the user to add as a contact
289 * @param int $blocked 1 if you wish to block the contact
290 * @param int $userid the user ID of the user we want to add the contact for, defaults to current user if not specified.
291 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
292 * Otherwise returns the result of update_record() or insert_record()
294 function message_add_contact($contactid, $blocked = 0, $userid = 0) {
295 global $USER, $DB;
297 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
298 return false;
301 if (empty($userid)) {
302 $userid = $USER->id;
305 // Check if a record already exists as we may be changing blocking status.
306 if (($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) !== false) {
307 // Check if blocking status has been changed.
308 if ($contact->blocked != $blocked) {
309 $contact->blocked = $blocked;
310 $DB->update_record('message_contacts', $contact);
312 if ($blocked == 1) {
313 // Trigger event for blocking a contact.
314 $event = \core\event\message_contact_blocked::create(array(
315 'objectid' => $contact->id,
316 'userid' => $contact->userid,
317 'relateduserid' => $contact->contactid,
318 'context' => context_user::instance($contact->userid)
320 $event->add_record_snapshot('message_contacts', $contact);
321 $event->trigger();
322 } else {
323 // Trigger event for unblocking a contact.
324 $event = \core\event\message_contact_unblocked::create(array(
325 'objectid' => $contact->id,
326 'userid' => $contact->userid,
327 'relateduserid' => $contact->contactid,
328 'context' => context_user::instance($contact->userid)
330 $event->add_record_snapshot('message_contacts', $contact);
331 $event->trigger();
334 return true;
335 } else {
336 // No change to blocking status.
337 return true;
340 } else {
341 // New contact record.
342 $contact = new stdClass();
343 $contact->userid = $userid;
344 $contact->contactid = $contactid;
345 $contact->blocked = $blocked;
346 $contact->id = $DB->insert_record('message_contacts', $contact);
348 $eventparams = array(
349 'objectid' => $contact->id,
350 'userid' => $contact->userid,
351 'relateduserid' => $contact->contactid,
352 'context' => context_user::instance($contact->userid)
355 if ($blocked) {
356 $event = \core\event\message_contact_blocked::create($eventparams);
357 } else {
358 $event = \core\event\message_contact_added::create($eventparams);
360 // Trigger event.
361 $event->trigger();
363 return true;
368 * remove a contact
370 * @param int $contactid the user ID of the contact to remove
371 * @param int $userid the user ID of the user we want to remove the contacts for, defaults to current user if not specified.
372 * @return bool returns the result of delete_records()
374 function message_remove_contact($contactid, $userid = 0) {
375 global $USER, $DB;
377 if (empty($userid)) {
378 $userid = $USER->id;
381 if ($contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $contactid))) {
382 $DB->delete_records('message_contacts', array('id' => $contact->id));
384 // Trigger event for removing a contact.
385 $event = \core\event\message_contact_removed::create(array(
386 'objectid' => $contact->id,
387 'userid' => $contact->userid,
388 'relateduserid' => $contact->contactid,
389 'context' => context_user::instance($contact->userid)
391 $event->add_record_snapshot('message_contacts', $contact);
392 $event->trigger();
394 return true;
397 return false;
401 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
403 * @param int $contactid the user ID of the contact to unblock
404 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
405 * if not specified.
406 * @return bool returns the result of delete_records()
408 function message_unblock_contact($contactid, $userid = 0) {
409 return message_add_contact($contactid, 0, $userid);
413 * Block a user.
415 * @param int $contactid the user ID of the user to block
416 * @param int $userid the user ID of the user we want to unblock the contact for, defaults to current user
417 * if not specified.
418 * @return bool
420 function message_block_contact($contactid, $userid = 0) {
421 return message_add_contact($contactid, 1, $userid);
425 * Checks if a user can delete a message.
427 * @param stdClass $message the message to delete
428 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
429 * but will still seem as if it was by the user)
430 * @return bool Returns true if a user can delete the message, false otherwise.
432 function message_can_delete_message($message, $userid) {
433 global $USER;
435 if ($message->useridfrom == $userid) {
436 $userdeleting = 'useridfrom';
437 } else if ($message->useridto == $userid) {
438 $userdeleting = 'useridto';
439 } else {
440 return false;
443 $systemcontext = context_system::instance();
445 // Let's check if the user is allowed to delete this message.
446 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
447 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
448 $USER->id == $message->$userdeleting))) {
449 return true;
452 return false;
456 * Deletes a message.
458 * This function does not verify any permissions.
460 * @param stdClass $message the message to delete
461 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
462 * but will still seem as if it was by the user)
463 * @return bool
465 function message_delete_message($message, $userid) {
466 global $DB;
468 // The column we want to alter.
469 if ($message->useridfrom == $userid) {
470 $coltimedeleted = 'timeuserfromdeleted';
471 } else if ($message->useridto == $userid) {
472 $coltimedeleted = 'timeusertodeleted';
473 } else {
474 return false;
477 // Don't update it if it's already been deleted.
478 if ($message->$coltimedeleted > 0) {
479 return false;
482 // Get the table we want to update.
483 if (isset($message->timeread)) {
484 $messagetable = 'message_read';
485 } else {
486 $messagetable = 'message';
489 // Mark the message as deleted.
490 $updatemessage = new stdClass();
491 $updatemessage->id = $message->id;
492 $updatemessage->$coltimedeleted = time();
493 $success = $DB->update_record($messagetable, $updatemessage);
495 if ($success) {
496 // Trigger event for deleting a message.
497 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
498 $userid, $messagetable, $message->id)->trigger();
501 return $success;
505 * Load a user's contact record
507 * @param int $contactid the user ID of the user whose contact record you want
508 * @return array message contacts
510 function message_get_contact($contactid) {
511 global $USER, $DB;
512 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
516 * Search through course users.
518 * If $courseids contains the site course then this function searches
519 * through all undeleted and confirmed users.
521 * @param int|array $courseids Course ID or array of course IDs.
522 * @param string $searchtext the text to search for.
523 * @param string $sort the column name to order by.
524 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
525 * @return array An array of {@link $USER} records.
527 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
528 global $CFG, $USER, $DB;
530 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
531 if (!$courseids) {
532 $courseids = array(SITEID);
535 // Allow an integer to be passed.
536 if (!is_array($courseids)) {
537 $courseids = array($courseids);
540 $fullname = $DB->sql_fullname();
541 $ufields = user_picture::fields('u');
543 if (!empty($sort)) {
544 $order = ' ORDER BY '. $sort;
545 } else {
546 $order = '';
549 $params = array(
550 'userid' => $USER->id,
551 'query' => "%$searchtext%"
554 if (empty($exceptions)) {
555 $exceptions = array();
556 } else if (!empty($exceptions) && is_string($exceptions)) {
557 $exceptions = explode(',', $exceptions);
560 // Ignore self and guest account.
561 $exceptions[] = $USER->id;
562 $exceptions[] = $CFG->siteguest;
564 // Exclude exceptions from the search result.
565 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
566 $except = ' AND u.id ' . $except;
567 $params = array_merge($params_except, $params);
569 if (in_array(SITEID, $courseids)) {
570 // Search on site level.
571 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
572 FROM {user} u
573 LEFT JOIN {message_contacts} mc
574 ON mc.contactid = u.id AND mc.userid = :userid
575 WHERE u.deleted = '0' AND u.confirmed = '1'
576 AND (".$DB->sql_like($fullname, ':query', false).")
577 $except
578 $order", $params);
579 } else {
580 // Search in courses.
582 // Getting the context IDs or each course.
583 $contextids = array();
584 foreach ($courseids as $courseid) {
585 $context = context_course::instance($courseid);
586 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
588 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
589 $params = array_merge($params, $contextparams);
591 // Everyone who has a role assignment in this course or higher.
592 // TODO: add enabled enrolment join here (skodak)
593 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
594 FROM {user} u
595 JOIN {role_assignments} ra ON ra.userid = u.id
596 LEFT JOIN {message_contacts} mc
597 ON mc.contactid = u.id AND mc.userid = :userid
598 WHERE u.deleted = '0' AND u.confirmed = '1'
599 AND (".$DB->sql_like($fullname, ':query', false).")
600 AND ra.contextid $contextwhere
601 $except
602 $order", $params);
604 return $users;
609 * Format a message for display in the message history
611 * @param object $message the message object
612 * @param string $format optional date format
613 * @param string $keywords keywords to highlight
614 * @param string $class CSS class to apply to the div around the message
615 * @return string the formatted message
617 function message_format_message($message, $format='', $keywords='', $class='other') {
619 static $dateformat;
621 //if we haven't previously set the date format or they've supplied a new one
622 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
623 if ($format) {
624 $dateformat = $format;
625 } else {
626 $dateformat = get_string('strftimedatetimeshort');
629 $time = userdate($message->timecreated, $dateformat);
631 $messagetext = message_format_message_text($message, false);
633 if ($keywords) {
634 $messagetext = highlight($keywords, $messagetext);
637 $messagetext .= message_format_contexturl($message);
639 $messagetext = clean_text($messagetext, FORMAT_HTML);
641 return <<<TEMPLATE
642 <div class='message $class'>
643 <a name="m{$message->id}"></a>
644 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
645 </div>
646 TEMPLATE;
650 * Format a the context url and context url name of a message for display
652 * @param object $message the message object
653 * @return string the formatted string
655 function message_format_contexturl($message) {
656 $s = null;
658 if (!empty($message->contexturl)) {
659 $displaytext = null;
660 if (!empty($message->contexturlname)) {
661 $displaytext= $message->contexturlname;
662 } else {
663 $displaytext= $message->contexturl;
665 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
666 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
667 $s .= html_writer::end_tag('div');
670 return $s;
674 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
676 * @param object $userfrom the message sender
677 * @param object $userto the message recipient
678 * @param string $message the message
679 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
680 * @return int|false the ID of the new message or false
682 function message_post_message($userfrom, $userto, $message, $format) {
683 global $SITE, $CFG, $USER;
685 $eventdata = new \core\message\message();
686 $eventdata->courseid = 1;
687 $eventdata->component = 'moodle';
688 $eventdata->name = 'instantmessage';
689 $eventdata->userfrom = $userfrom;
690 $eventdata->userto = $userto;
692 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
693 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
695 if ($format == FORMAT_HTML) {
696 $eventdata->fullmessagehtml = $message;
697 //some message processors may revert to sending plain text even if html is supplied
698 //so we keep both plain and html versions if we're intending to send html
699 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
700 } else {
701 $eventdata->fullmessage = $message;
702 $eventdata->fullmessagehtml = '';
705 $eventdata->fullmessageformat = $format;
706 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
708 $s = new stdClass();
709 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
710 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
712 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
713 if (!empty($eventdata->fullmessage)) {
714 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
716 if (!empty($eventdata->fullmessagehtml)) {
717 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
720 $eventdata->timecreated = time();
721 $eventdata->notification = 0;
722 return message_send($eventdata);
726 * Moves messages from a particular user from the message table (unread messages) to message_read
727 * This is typically only used when a user is deleted
729 * @param object $userid User id
730 * @return boolean success
732 function message_move_userfrom_unread2read($userid) {
733 global $DB;
735 // move all unread messages from message table to message_read
736 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
737 foreach ($messages as $message) {
738 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
741 return true;
745 * Mark a single message as read
747 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
748 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
749 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
750 * @return int the ID of the message in the message_read table
752 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
753 global $DB;
755 $message->timeread = $timeread;
757 $messageid = $message->id;
758 unset($message->id);//unset because it will get a new id on insert into message_read
760 //If any processors have pending actions abort them
761 if (!$messageworkingempty) {
762 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
764 $messagereadid = $DB->insert_record('message_read', $message);
766 $DB->delete_records('message', array('id' => $messageid));
768 // Get the context for the user who received the message.
769 $context = context_user::instance($message->useridto, IGNORE_MISSING);
770 // If the user no longer exists the context value will be false, in this case use the system context.
771 if ($context === false) {
772 $context = context_system::instance();
775 // Trigger event for reading a message.
776 $event = \core\event\message_viewed::create(array(
777 'objectid' => $messagereadid,
778 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
779 'context' => $context,
780 'relateduserid' => $message->useridfrom,
781 'other' => array(
782 'messageid' => $messageid
785 $event->trigger();
787 return $messagereadid;
791 * Get all message processors, validate corresponding plugin existance and
792 * system configuration
794 * @param bool $ready only return ready-to-use processors
795 * @param bool $reset Reset list of message processors (used in unit tests)
796 * @param bool $resetonly Just reset, then exit
797 * @return mixed $processors array of objects containing information on message processors
799 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
800 global $DB, $CFG;
802 static $processors;
803 if ($reset) {
804 $processors = array();
806 if ($resetonly) {
807 return $processors;
811 if (empty($processors)) {
812 // Get all processors, ensure the name column is the first so it will be the array key
813 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
814 foreach ($processors as &$processor){
815 $processor = \core_message\api::get_processed_processor_object($processor);
818 if ($ready) {
819 // Filter out enabled and system_configured processors
820 $readyprocessors = $processors;
821 foreach ($readyprocessors as $readyprocessor) {
822 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
823 unset($readyprocessors[$readyprocessor->name]);
826 return $readyprocessors;
829 return $processors;
833 * Get all message providers, validate their plugin existance and
834 * system configuration
836 * @return mixed $processors array of objects containing information on message processors
838 function get_message_providers() {
839 global $CFG, $DB;
841 $pluginman = core_plugin_manager::instance();
843 $providers = $DB->get_records('message_providers', null, 'name');
845 // Remove all the providers whose plugins are disabled or don't exist
846 foreach ($providers as $providerid => $provider) {
847 $plugin = $pluginman->get_plugin_info($provider->component);
848 if ($plugin) {
849 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
850 unset($providers[$providerid]); // Plugins does not exist
851 continue;
853 if ($plugin->is_enabled() === false) {
854 unset($providers[$providerid]); // Plugin disabled
855 continue;
859 return $providers;
863 * Get an instance of the message_output class for one of the output plugins.
864 * @param string $type the message output type. E.g. 'email' or 'jabber'.
865 * @return message_output message_output the requested class.
867 function get_message_processor($type) {
868 global $CFG;
870 // Note, we cannot use the get_message_processors function here, becaues this
871 // code is called during install after installing each messaging plugin, and
872 // get_message_processors caches the list of installed plugins.
874 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
875 if (!is_readable($processorfile)) {
876 throw new coding_exception('Unknown message processor type ' . $type);
879 include_once($processorfile);
881 $processclass = 'message_output_' . $type;
882 if (!class_exists($processclass)) {
883 throw new coding_exception('Message processor ' . $type .
884 ' does not define the right class');
887 return new $processclass();
891 * Get messaging outputs default (site) preferences
893 * @return object $processors object containing information on message processors
895 function get_message_output_default_preferences() {
896 return get_config('message');
900 * Translate message default settings from binary value to the array of string
901 * representing the settings to be stored. Also validate the provided value and
902 * use default if it is malformed.
904 * @param int $plugindefault Default setting suggested by plugin
905 * @param string $processorname The name of processor
906 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
908 function translate_message_default_setting($plugindefault, $processorname) {
909 // Preset translation arrays
910 $permittedvalues = array(
911 0x04 => 'disallowed',
912 0x08 => 'permitted',
913 0x0c => 'forced',
916 $loggedinstatusvalues = array(
917 0x00 => null, // use null if loggedin/loggedoff is not defined
918 0x01 => 'loggedin',
919 0x02 => 'loggedoff',
922 // define the default setting
923 $processor = get_message_processor($processorname);
924 $default = $processor->get_default_messaging_settings();
926 // Validate the value. It should not exceed the maximum size
927 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
928 debugging(get_string('errortranslatingdefault', 'message'));
929 $plugindefault = $default;
931 // Use plugin default setting of 'permitted' is 0
932 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
933 $plugindefault = $default;
936 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
937 $loggedin = $loggedoff = null;
939 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
940 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
941 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
944 return array($permitted, $loggedin, $loggedoff);
948 * Get messages sent or/and received by the specified users.
949 * Please note that this function return deleted messages too.
951 * @param int $useridto the user id who received the message
952 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
953 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
954 * @param bool $read true for retrieving read messages, false for unread
955 * @param string $sort the column name to order by including optionally direction
956 * @param int $limitfrom limit from
957 * @param int $limitnum limit num
958 * @return external_description
959 * @since 2.8
961 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
962 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
963 global $DB;
965 $messagetable = $read ? '{message_read}' : '{message}';
966 $params = array('deleted' => 0);
968 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
969 if (empty($useridto)) {
970 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
971 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
972 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
973 $params['useridfrom'] = $useridfrom;
974 } else {
975 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
976 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
977 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
978 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
979 $params['useridto'] = $useridto;
980 if (!empty($useridfrom)) {
981 $usersql .= " AND mr.useridfrom = :useridfrom";
982 $params['useridfrom'] = $useridfrom;
986 // Now, if retrieve notifications, conversations or both.
987 $typesql = "";
988 if ($notifications !== -1) {
989 $typesql = "AND mr.notification = :notification";
990 $params['notification'] = ($notifications) ? 1 : 0;
993 $sql = "SELECT mr.*, $userfields
994 FROM $messagetable mr
995 $joinsql
996 WHERE $usersql
997 $typesql
998 ORDER BY $sort";
1000 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1001 return $messages;
1005 * Handles displaying processor settings in a fragment.
1007 * @param array $args
1008 * @return bool|string
1009 * @throws moodle_exception
1011 function message_output_fragment_processor_settings($args = []) {
1012 global $PAGE;
1014 if (!isset($args['type'])) {
1015 throw new moodle_exception('Must provide a processor type');
1018 if (!isset($args['userid'])) {
1019 throw new moodle_exception('Must provide a userid');
1022 $type = $args['type'];
1023 $userid = $args['userid'];
1025 $user = core_user::get_user($userid, '*', MUST_EXIST);
1026 $processor = get_message_processor($type);
1027 $providers = message_get_providers_for_user($userid);
1028 $processorwrapper = new stdClass();
1029 $processorwrapper->object = $processor;
1030 $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
1032 $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
1033 $renderer = $PAGE->get_renderer('core', 'message');
1035 return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
1039 * Checks if current user is allowed to edit messaging preferences of another user
1041 * @param stdClass $user user whose preferences we are updating
1042 * @return bool
1044 function core_message_can_edit_message_profile($user) {
1045 global $USER;
1046 if ($user->id == $USER->id) {
1047 return has_capability('moodle/user:editownmessageprofile', context_system::instance());
1048 } else {
1049 $personalcontext = context_user::instance($user->id);
1050 if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
1051 return false;
1053 if (isguestuser($user)) {
1054 return false;
1056 // No editing of admins by non-admins.
1057 if (is_siteadmin($user) and !is_siteadmin($USER)) {
1058 return false;
1060 return true;
1065 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
1067 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
1069 * @return array
1071 function core_message_user_preferences() {
1073 $preferences = [];
1074 $preferences['message_blocknoncontacts'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
1075 'choices' => array(0, 1));
1076 $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
1077 'null' => NULL_NOT_ALLOWED, 'default' => 'none',
1078 'permissioncallback' => function ($user, $preferencename) {
1079 global $CFG;
1080 require_once($CFG->libdir.'/messagelib.php');
1081 if (core_message_can_edit_message_profile($user) &&
1082 preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
1083 $providers = message_get_providers_for_user($user->id);
1084 foreach ($providers as $provider) {
1085 if ($matches[1] === $provider->component . '_' . $provider->name) {
1086 return true;
1090 return false;
1092 'cleancallback' => function ($value, $preferencename) {
1093 if ($value === 'none' || empty($value)) {
1094 return 'none';
1096 $parts = explode('/,/', $value);
1097 $processors = array_keys(get_message_processors());
1098 array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
1099 return $parts ? join(',', $parts) : 'none';
1101 return $preferences;