MDL-46960 completionlib: adjustments to caching
[moodle.git] / message / lib.php
blob92e06dd463c15deba5ff9ab93f1a4bc9e0f97cd7
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 /**
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
69 /**
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 /**
75 * Print the selector that allows the user to view their contacts, course participants, their recent
76 * conversations etc
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86 * @param bool $showactionlinks show action links (add/remove contact etc)
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
88 * @return void
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
91 global $PAGE;
93 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
95 //if 0 unread messages and they've requested unread messages then show contacts
96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97 $viewing = MESSAGE_VIEW_CONTACTS;
100 //if they have no blocked users and they've requested blocked users switch them over to contacts
101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102 $viewing = MESSAGE_VIEW_CONTACTS;
105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
118 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
120 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
121 message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
123 $courseidtoshow = intval(substr($viewing, 7));
125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
133 // Only show the search button if we're viewing our own contacts.
134 if ($viewing == MESSAGE_VIEW_CONTACTS && $user2 == null) {
135 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
136 echo html_writer::start_tag('fieldset');
137 $managebuttonclass = 'visible';
138 $strmanagecontacts = get_string('search','message');
139 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
140 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
141 echo html_writer::end_tag('fieldset');
142 echo html_writer::end_tag('form');
145 echo html_writer::end_tag('div');
149 * Print course participants. Called by message_print_contact_selector()
151 * @param object $context the course context
152 * @param int $courseid the course ID
153 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
154 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
155 * @param string $titletodisplay Optionally specify a title to display above the participants
156 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
157 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
158 * @return void
160 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
161 global $DB, $USER, $PAGE, $OUTPUT;
163 if (empty($titletodisplay)) {
164 $titletodisplay = get_string('participants');
167 $countparticipants = count_enrolled_users($context);
169 list($esql, $params) = get_enrolled_sql($context);
170 $params['mcuserid'] = $USER->id;
171 $ufields = user_picture::fields('u');
173 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
174 FROM {user} u
175 JOIN ($esql) je ON je.id = u.id
176 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
177 WHERE u.deleted = 0";
179 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
181 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
182 echo $OUTPUT->render($pagingbar);
184 echo html_writer::start_tag('div', array('id' => 'message_participants', 'class' => 'boxaligncenter'));
186 echo html_writer::tag('div' , $titletodisplay, array('class' => 'heading'));
188 $users = '';
189 foreach ($participants as $participant) {
190 if ($participant->id != $USER->id) {
192 $iscontact = false;
193 $isblocked = false;
194 if ( $participant->contactlistid ) {
195 if ($participant->blocked == 0) {
196 // Is contact. Is not blocked.
197 $iscontact = true;
198 $isblocked = false;
199 } else {
200 // Is blocked.
201 $iscontact = false;
202 $isblocked = true;
206 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
207 $content = message_print_contactlist_user($participant, $iscontact, $isblocked,
208 $contactselecturl, $showactionlinks, $user2);
209 $users .= html_writer::tag('li', $content);
212 if (strlen($users) > 0) {
213 echo html_writer::tag('ul', $users, array('id' => 'message-courseparticipants', 'class' => 'message-contacts'));
216 echo html_writer::end_tag('div');
220 * Retrieve users blocked by $user1
222 * @param object $user1 the user whose messages are being viewed
223 * @param object $user2 the user $user1 is talking to. If they are being blocked
224 * they will have a variable called 'isblocked' added to their user object
225 * @return array the users blocked by $user1
227 function message_get_blocked_users($user1=null, $user2=null) {
228 global $DB, $USER;
230 if (empty($user1)) {
231 $user1 = $USER;
234 if (!empty($user2)) {
235 $user2->isblocked = false;
238 $blockedusers = array();
240 $userfields = user_picture::fields('u', array('lastaccess'));
241 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
242 FROM {message_contacts} mc
243 JOIN {user} u ON u.id = mc.contactid
244 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
245 WHERE mc.userid = :user1id2 AND mc.blocked = 1
246 GROUP BY $userfields
247 ORDER BY u.firstname ASC";
248 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
250 foreach($rs as $rd) {
251 $blockedusers[] = $rd;
253 if (!empty($user2) && $user2->id == $rd->id) {
254 $user2->isblocked = true;
257 $rs->close();
259 return $blockedusers;
263 * Print users blocked by $user1. Called by message_print_contact_selector()
265 * @param array $blockedusers the users blocked by $user1
266 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
267 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
268 * @param string $titletodisplay Optionally specify a title to display above the participants
269 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
270 * @return void
272 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
273 global $OUTPUT;
275 $countblocked = count($blockedusers);
277 echo html_writer::start_tag('div', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
279 if (!empty($titletodisplay)) {
280 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
283 if ($countblocked) {
284 echo html_writer::tag('div', get_string('blockedusers', 'message', $countblocked), array('class' => 'heading'));
286 $isuserblocked = true;
287 $isusercontact = false;
288 $blockeduserslist = '';
289 foreach ($blockedusers as $blockeduser) {
290 $content = message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked,
291 $contactselecturl, $showactionlinks, $user2);
292 $blockeduserslist .= html_writer::tag('li', $content);
294 echo html_writer::tag('ul', $blockeduserslist, array('id' => 'message-blockedusers', 'class' => 'message-contacts'));
297 echo html_writer::end_tag('div');
301 * Retrieve $user1's contacts (online, offline and strangers)
303 * @param object $user1 the user whose messages are being viewed
304 * @param object $user2 the user $user1 is talking to. If they are a contact
305 * they will have a variable called 'iscontact' added to their user object
306 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
308 function message_get_contacts($user1=null, $user2=null) {
309 global $DB, $CFG, $USER;
311 if (empty($user1)) {
312 $user1 = $USER;
315 if (!empty($user2)) {
316 $user2->iscontact = false;
319 $timetoshowusers = 300; //Seconds default
320 if (isset($CFG->block_online_users_timetosee)) {
321 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
324 // time which a user is counting as being active since
325 $timefrom = time()-$timetoshowusers;
327 // people in our contactlist who are online
328 $onlinecontacts = array();
329 // people in our contactlist who are offline
330 $offlinecontacts = array();
331 // people who are not in our contactlist but have sent us a message
332 $strangers = array();
334 $userfields = user_picture::fields('u', array('lastaccess'));
336 // get all in our contactlist who are not blocked in our contact list
337 // and count messages we have waiting from each of them
338 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
339 FROM {message_contacts} mc
340 JOIN {user} u ON u.id = mc.contactid
341 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
342 WHERE mc.userid = ? AND mc.blocked = 0
343 GROUP BY $userfields
344 ORDER BY u.firstname ASC";
346 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
347 foreach ($rs as $rd) {
348 if ($rd->lastaccess >= $timefrom) {
349 // they have been active recently, so are counted online
350 $onlinecontacts[] = $rd;
352 } else {
353 $offlinecontacts[] = $rd;
356 if (!empty($user2) && $user2->id == $rd->id) {
357 $user2->iscontact = true;
360 $rs->close();
362 // get messages from anyone who isn't in our contact list and count the number
363 // of messages we have from each of them
364 $strangersql = "SELECT $userfields, count(m.id) as messagecount
365 FROM {message} m
366 JOIN {user} u ON u.id = m.useridfrom
367 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
368 WHERE mc.id IS NULL AND m.useridto = ?
369 GROUP BY $userfields
370 ORDER BY u.firstname ASC";
372 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
373 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
374 foreach ($rs as $rd) {
375 $strangers[$rd->id] = $rd;
377 $rs->close();
379 // Add noreply user and support user to the list, if they don't exist.
380 $supportuser = core_user::get_support_user();
381 if (!isset($strangers[$supportuser->id])) {
382 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
383 if ($supportuser->messagecount > 0) {
384 $strangers[$supportuser->id] = $supportuser;
388 $noreplyuser = core_user::get_noreply_user();
389 if (!isset($strangers[$noreplyuser->id])) {
390 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
391 if ($noreplyuser->messagecount > 0) {
392 $strangers[$noreplyuser->id] = $noreplyuser;
395 return array($onlinecontacts, $offlinecontacts, $strangers);
399 * Print $user1's contacts. Called by message_print_contact_selector()
401 * @param array $onlinecontacts $user1's contacts which are online
402 * @param array $offlinecontacts $user1's contacts which are offline
403 * @param array $strangers users which are not contacts but who have messaged $user1
404 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
405 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
406 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
407 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
408 * @param string $titletodisplay Optionally specify a title to display above the participants
409 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
410 * @return void
412 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
413 global $CFG, $PAGE, $OUTPUT;
415 $countonlinecontacts = count($onlinecontacts);
416 $countofflinecontacts = count($offlinecontacts);
417 $countstrangers = count($strangers);
418 $isuserblocked = null;
420 if ($countonlinecontacts + $countofflinecontacts == 0) {
421 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
424 if (!empty($titletodisplay)) {
425 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
428 if($countonlinecontacts) {
429 // Print out list of online contacts.
431 if (empty($titletodisplay)) {
432 echo html_writer::tag('div',
433 get_string('onlinecontacts', 'message', $countonlinecontacts),
434 array('class' => 'heading'));
437 $isuserblocked = false;
438 $isusercontact = true;
439 $contacts = '';
440 foreach ($onlinecontacts as $contact) {
441 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
442 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
443 $contactselecturl, $showactionlinks, $user2);
444 $contacts .= html_writer::tag('li', $content);
447 if (strlen($contacts) > 0) {
448 echo html_writer::tag('ul', $contacts, array('id' => 'message-onlinecontacts', 'class' => 'message-contacts'));
452 if ($countofflinecontacts) {
453 // Print out list of offline contacts.
455 if (empty($titletodisplay)) {
456 echo html_writer::tag('div',
457 get_string('offlinecontacts', 'message', $countofflinecontacts),
458 array('class' => 'heading'));
461 $isuserblocked = false;
462 $isusercontact = true;
463 $contacts = '';
464 foreach ($offlinecontacts as $contact) {
465 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
466 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
467 $contactselecturl, $showactionlinks, $user2);
468 $contacts .= html_writer::tag('li', $content);
471 if (strlen($contacts) > 0) {
472 echo html_writer::tag('ul', $contacts, array('id' => 'message-offlinecontacts', 'class' => 'message-contacts'));
477 // Print out list of incoming contacts.
478 if ($countstrangers) {
479 echo html_writer::tag('div', get_string('incomingcontacts', 'message', $countstrangers), array('class' => 'heading'));
481 $isuserblocked = false;
482 $isusercontact = false;
483 $contacts = '';
484 foreach ($strangers as $stranger) {
485 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
486 $content = message_print_contactlist_user($stranger, $isusercontact, $isuserblocked,
487 $contactselecturl, $showactionlinks, $user2);
488 $contacts .= html_writer::tag('li', $content);
491 if (strlen($contacts) > 0) {
492 echo html_writer::tag('ul', $contacts, array('id' => 'message-incommingcontacts', 'class' => 'message-contacts'));
497 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
498 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
503 * Print a select box allowing the user to choose to view new messages, course participants etc.
505 * Called by message_print_contact_selector()
506 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
507 * @param array $courses array of course objects. The courses the user is enrolled in.
508 * @param array $coursecontexts array of course contexts. Keyed on course id.
509 * @param int $countunreadtotal how many unread messages does the user have?
510 * @param int $countblocked how many users has the current user blocked?
511 * @param stdClass $user1 The user whose messages we are viewing.
512 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
513 * @return void
515 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
516 global $PAGE;
517 $options = array();
519 if ($countunreadtotal>0) { //if there are unread messages
520 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
523 $str = get_string('contacts', 'message');
524 $options[MESSAGE_VIEW_CONTACTS] = $str;
526 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
527 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
529 if (!empty($courses)) {
530 $courses_options = array();
532 foreach($courses as $course) {
533 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
534 //Not using short_text() as we want the end of the course name. Not the beginning.
535 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
536 if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
537 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
538 } else {
539 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
544 if (!empty($courses_options)) {
545 $options[] = array(get_string('courses') => $courses_options);
549 if ($countblocked>0) {
550 $str = get_string('blockedusers','message', $countblocked);
551 $options[MESSAGE_VIEW_BLOCKED] = $str;
554 $select = new single_select($PAGE->url, 'viewing', $options, $viewing, false);
555 $select->set_label(get_string('messagenavigation', 'message'));
557 $renderer = $PAGE->get_renderer('core');
558 echo $renderer->render($select);
562 * Load the course contexts for all of the users courses
564 * @param array $courses array of course objects. The courses the user is enrolled in.
565 * @return array of course contexts
567 function message_get_course_contexts($courses) {
568 $coursecontexts = array();
570 foreach($courses as $course) {
571 $coursecontexts[$course->id] = context_course::instance($course->id);
574 return $coursecontexts;
578 * strip off action parameters like 'removecontact'
580 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
581 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
583 function message_remove_url_params($moodleurl) {
584 $newurl = new moodle_url($moodleurl);
585 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
586 return $newurl->out();
590 * Count the number of messages with a field having a specified value.
591 * if $field is empty then return count of the whole array
592 * if $field is non-existent then return 0
594 * @param array $messagearray array of message objects
595 * @param string $field the field to inspect on the message objects
596 * @param string $value the value to test the field against
598 function message_count_messages($messagearray, $field='', $value='') {
599 if (!is_array($messagearray)) return 0;
600 if ($field == '' or empty($messagearray)) return count($messagearray);
602 $count = 0;
603 foreach ($messagearray as $message) {
604 $count += ($message->$field == $value) ? 1 : 0;
606 return $count;
610 * Returns the count of unread messages for user. Either from a specific user or from all users.
612 * @param object $user1 the first user. Defaults to $USER
613 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
614 * @return int the count of $user1's unread messages
616 function message_count_unread_messages($user1=null, $user2=null) {
617 global $USER, $DB;
619 if (empty($user1)) {
620 $user1 = $USER;
623 if (!empty($user2)) {
624 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
625 array($user1->id, $user2->id), "COUNT('id')");
626 } else {
627 return $DB->count_records_select('message', "useridto = ?",
628 array($user1->id), "COUNT('id')");
633 * Count the number of users blocked by $user1
635 * @param object $user1 user object
636 * @return int the number of blocked users
638 function message_count_blocked_users($user1=null) {
639 global $USER, $DB;
641 if (empty($user1)) {
642 $user1 = $USER;
645 $sql = "SELECT count(mc.id)
646 FROM {message_contacts} mc
647 WHERE mc.userid = :userid AND mc.blocked = 1";
648 $params = array('userid' => $user1->id);
650 return $DB->count_records_sql($sql, $params);
654 * Print the search form and search results if a search has been performed
656 * @param boolean $advancedsearch show basic or advanced search form
657 * @param object $user1 the current user
658 * @return boolean true if a search was performed
660 function message_print_search($advancedsearch = false, $user1=null) {
661 $frm = data_submitted();
663 $doingsearch = false;
664 if ($frm) {
665 if (confirm_sesskey()) {
666 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
667 } else {
668 $frm = false;
672 if (!empty($frm->combinedsearch)) {
673 $combinedsearchstring = $frm->combinedsearch;
674 } else {
675 //$combinedsearchstring = get_string('searchcombined','message').'...';
676 $combinedsearchstring = '';
679 if ($doingsearch) {
680 if ($advancedsearch) {
682 $messagesearch = '';
683 if (!empty($frm->keywords)) {
684 $messagesearch = $frm->keywords;
686 $personsearch = '';
687 if (!empty($frm->name)) {
688 $personsearch = $frm->name;
690 include('search_advanced.html');
691 } else {
692 include('search.html');
695 $showicontext = false;
696 message_print_search_results($frm, $showicontext, $user1);
698 return true;
699 } else {
701 if ($advancedsearch) {
702 $personsearch = $messagesearch = '';
703 include('search_advanced.html');
704 } else {
705 include('search.html');
707 return false;
712 * Get the users recent conversations meaning all the people they've recently
713 * sent or received a message from plus the most recent message sent to or received from each other user
715 * @param object $user the current user
716 * @param int $limitfrom can be used for paging
717 * @param int $limitto can be used for paging
718 * @return array
720 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
721 global $DB;
723 $userfields = user_picture::fields('otheruser', array('lastaccess'));
725 // This query retrieves the most recent message received from or sent to
726 // seach other user.
728 // If two messages have the same timecreated, we take the one with the
729 // larger id.
731 // There is a separate query for read and unread messages as they are stored
732 // in different tables. They were originally retrieved in one query but it
733 // was so large that it was difficult to be confident in its correctness.
734 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
735 $sql = "SELECT $uniquefield, $userfields,
736 message.id as mid, message.notification, message.smallmessage, message.fullmessage,
737 message.fullmessagehtml, message.fullmessageformat, message.timecreated,
738 contact.id as contactlistid, contact.blocked
739 FROM {message_read} message
740 JOIN (
741 SELECT MAX(id) AS messageid,
742 matchedmessage.useridto,
743 matchedmessage.useridfrom
744 FROM {message_read} matchedmessage
745 INNER JOIN (
746 SELECT MAX(recentmessages.timecreated) timecreated,
747 recentmessages.useridfrom,
748 recentmessages.useridto
749 FROM {message_read} recentmessages
750 WHERE (recentmessages.useridfrom = :userid1 OR recentmessages.useridto = :userid2)
751 GROUP BY recentmessages.useridfrom, recentmessages.useridto
752 ) recent ON matchedmessage.useridto = recent.useridto
753 AND matchedmessage.useridfrom = recent.useridfrom
754 AND matchedmessage.timecreated = recent.timecreated
755 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
756 ) messagesubset ON messagesubset.messageid = message.id
757 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
758 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
759 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.userid = otheruser.id
760 WHERE otheruser.deleted = 0 AND message.notification = 0
761 ORDER BY message.timecreated DESC";
762 $params = array(
763 'userid1' => $user->id,
764 'userid2' => $user->id,
765 'userid3' => $user->id,
766 'userid4' => $user->id,
767 'userid5' => $user->id,
769 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
771 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
772 // exact same query as the one above, except for the table we are querying. So, simply replace references to
773 // the 'message_read' table with the 'message' table.
774 $sql = str_replace('{message_read}', '{message}', $sql);
775 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
777 // Union the 2 result sets together looking for the message with the most
778 // recent timecreated for each other user.
779 // $conversation->id (the array key) is the other user's ID.
780 $conversation_arrays = array($unread, $read);
781 foreach ($conversation_arrays as $conversation_array) {
782 foreach ($conversation_array as $conversation) {
783 if (!isset($conversations[$conversation->id])) {
784 $conversations[$conversation->id] = $conversation;
785 } else {
786 $current = $conversations[$conversation->id];
787 if ($current->timecreated < $conversation->timecreated) {
788 $conversations[$conversation->id] = $conversation;
789 } else if ($current->timecreated == $conversation->timecreated) {
790 if ($current->mid < $conversation->mid) {
791 $conversations[$conversation->id] = $conversation;
798 // Sort the conversations by $conversation->timecreated, newest to oldest
799 // There may be multiple conversations with the same timecreated
800 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
801 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
802 $conversations = array_reverse($conversations);
804 return $conversations;
808 * Get the users recent event notifications
810 * @param object $user the current user
811 * @param int $limitfrom can be used for paging
812 * @param int $limitto can be used for paging
813 * @return array
815 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
816 global $DB;
818 $userfields = user_picture::fields('u', array('lastaccess'));
819 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
820 FROM {message_read} mr
821 JOIN {user} u ON u.id=mr.useridfrom
822 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
823 ORDER BY mr.timecreated DESC";
824 $params = array('userid1' => $user->id, 'notification' => 1);
826 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
827 return $notifications;
831 * Print the user's recent conversations
833 * @param stdClass $user the current user
834 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
836 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
837 global $USER;
839 echo html_writer::start_tag('p', array('class' => 'heading'));
840 echo get_string('mostrecentconversations', 'message');
841 echo html_writer::end_tag('p');
843 if (empty($user1)) {
844 $user1 = $USER;
847 $conversations = message_get_recent_conversations($user1);
849 // Attach context url information to create the "View this conversation" type links
850 foreach($conversations as $conversation) {
851 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
852 $conversation->contexturlname = get_string('thisconversation', 'message');
855 $showotheruser = true;
856 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
860 * Print the user's recent notifications
862 * @param stdClass $user the current user
864 function message_print_recent_notifications($user=null) {
865 global $USER;
867 echo html_writer::start_tag('p', array('class' => 'heading'));
868 echo get_string('mostrecentnotifications', 'message');
869 echo html_writer::end_tag('p');
871 if (empty($user)) {
872 $user = $USER;
875 $notifications = message_get_recent_notifications($user);
877 $showicontext = false;
878 $showotheruser = false;
879 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
883 * Print a list of recent messages
885 * @access private
887 * @param array $messages the messages to display
888 * @param stdClass $user the current user
889 * @param bool $showotheruser display information on the other user?
890 * @param bool $showicontext show text next to the action icons?
891 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
892 * @param bool $showactionlinks
893 * @return void
895 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
896 global $OUTPUT;
897 static $dateformat;
899 if (empty($dateformat)) {
900 $dateformat = get_string('strftimedatetimeshort');
903 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
904 foreach ($messages as $message) {
905 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
907 if ($showotheruser) {
908 $strcontact = $strblock = $strhistory = null;
910 if ($showactionlinks) {
911 if ( $message->contactlistid ) {
912 if ($message->blocked == 0) { // The other user isn't blocked.
913 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
914 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
915 } else { // The other user is blocked.
916 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
917 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
919 } else {
920 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
921 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
924 //should we show just the icon or icon and text?
925 $histicontext = 'icon';
926 if ($showicontext) {
927 $histicontext = 'both';
929 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
931 echo html_writer::start_tag('span', array('class' => 'otheruser'));
933 echo html_writer::start_tag('span', array('class' => 'pix'));
934 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
935 echo html_writer::end_tag('span');
937 echo html_writer::start_tag('span', array('class' => 'contact'));
939 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
940 $action = null;
941 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
943 echo html_writer::end_tag('span');//end contact
945 if ($showactionlinks) {
946 echo $strcontact.$strblock.$strhistory;
948 echo html_writer::end_tag('span');//end otheruser
951 $messagetext = message_format_message_text($message, $forcetexttohtml);
953 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
954 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
955 echo message_format_contexturl($message);
956 echo html_writer::end_tag('div');//end singlemessage
958 echo html_writer::end_tag('div');//end messagerecent
962 * Try to guess how to convert the message to html.
964 * @access private
966 * @param stdClass $message
967 * @param bool $forcetexttohtml
968 * @return string html fragment
970 function message_format_message_text($message, $forcetexttohtml = false) {
971 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
973 $options = new stdClass();
974 $options->para = false;
976 $format = $message->fullmessageformat;
978 if ($message->smallmessage !== '') {
979 if ($message->notification == 1) {
980 if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
981 $format = FORMAT_PLAIN;
984 $messagetext = $message->smallmessage;
986 } else if ($message->fullmessageformat == FORMAT_HTML) {
987 if ($message->fullmessagehtml !== '') {
988 $messagetext = $message->fullmessagehtml;
989 } else {
990 $messagetext = $message->fullmessage;
991 $format = FORMAT_MOODLE;
994 } else {
995 if ($message->fullmessage !== '') {
996 $messagetext = $message->fullmessage;
997 } else {
998 $messagetext = $message->fullmessagehtml;
999 $format = FORMAT_HTML;
1003 if ($forcetexttohtml) {
1004 // This is a crazy hack, why not set proper format when creating the notifications?
1005 if ($format === FORMAT_PLAIN) {
1006 $format = FORMAT_MOODLE;
1009 return format_text($messagetext, $format, $options);
1013 * Add the selected user as a contact for the current user
1015 * @param int $contactid the ID of the user to add as a contact
1016 * @param int $blocked 1 if you wish to block the contact
1017 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
1018 * Otherwise returns the result of update_record() or insert_record()
1020 function message_add_contact($contactid, $blocked=0) {
1021 global $USER, $DB;
1023 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
1024 return false;
1027 // Check if a record already exists as we may be changing blocking status.
1028 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
1029 // Check if blocking status has been changed.
1030 if ($contact->blocked !== $blocked) {
1031 $contact->blocked = $blocked;
1032 $DB->update_record('message_contacts', $contact);
1034 if ($blocked == 1) {
1035 // Trigger event for blocking a contact.
1036 $event = \core\event\message_contact_blocked::create(array(
1037 'objectid' => $contact->id,
1038 'userid' => $contact->userid,
1039 'relateduserid' => $contact->contactid,
1040 'context' => context_user::instance($contact->userid)
1042 $event->add_record_snapshot('message_contacts', $contact);
1043 $event->trigger();
1044 } else {
1045 // Trigger event for unblocking a contact.
1046 $event = \core\event\message_contact_unblocked::create(array(
1047 'objectid' => $contact->id,
1048 'userid' => $contact->userid,
1049 'relateduserid' => $contact->contactid,
1050 'context' => context_user::instance($contact->userid)
1052 $event->add_record_snapshot('message_contacts', $contact);
1053 $event->trigger();
1056 return true;
1057 } else {
1058 // No change to blocking status.
1059 return true;
1062 } else {
1063 // New contact record.
1064 $contact = new stdClass();
1065 $contact->userid = $USER->id;
1066 $contact->contactid = $contactid;
1067 $contact->blocked = $blocked;
1068 $contact->id = $DB->insert_record('message_contacts', $contact);
1070 $eventparams = array(
1071 'objectid' => $contact->id,
1072 'userid' => $contact->userid,
1073 'relateduserid' => $contact->contactid,
1074 'context' => context_user::instance($contact->userid)
1077 if ($blocked) {
1078 $event = \core\event\message_contact_blocked::create($eventparams);
1079 } else {
1080 $event = \core\event\message_contact_added::create($eventparams);
1082 // Trigger event.
1083 $event->trigger();
1085 return true;
1090 * remove a contact
1092 * @param int $contactid the user ID of the contact to remove
1093 * @return bool returns the result of delete_records()
1095 function message_remove_contact($contactid) {
1096 global $USER, $DB;
1098 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1099 $DB->delete_records('message_contacts', array('id' => $contact->id));
1101 // Trigger event for removing a contact.
1102 $event = \core\event\message_contact_removed::create(array(
1103 'objectid' => $contact->id,
1104 'userid' => $contact->userid,
1105 'relateduserid' => $contact->contactid,
1106 'context' => context_user::instance($contact->userid)
1108 $event->add_record_snapshot('message_contacts', $contact);
1109 $event->trigger();
1111 return true;
1114 return false;
1118 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1120 * @param int $contactid the user ID of the contact to unblock
1121 * @return bool returns the result of delete_records()
1123 function message_unblock_contact($contactid) {
1124 return message_add_contact($contactid, 0);
1128 * Block a user.
1130 * @param int $contactid the user ID of the user to block
1131 * @return bool
1133 function message_block_contact($contactid) {
1134 return message_add_contact($contactid, 1);
1138 * Load a user's contact record
1140 * @param int $contactid the user ID of the user whose contact record you want
1141 * @return array message contacts
1143 function message_get_contact($contactid) {
1144 global $USER, $DB;
1145 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1149 * Print the results of a message search
1151 * @param mixed $frm submitted form data
1152 * @param bool $showicontext show text next to action icons?
1153 * @param object $currentuser the current user
1154 * @return void
1156 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1157 global $USER, $DB, $OUTPUT;
1159 if (empty($currentuser)) {
1160 $currentuser = $USER;
1163 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1165 $personsearch = false;
1166 $personsearchstring = null;
1167 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1168 $personsearch = true;
1169 $personsearchstring = $frm->name;
1170 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1171 $personsearch = true;
1172 $personsearchstring = $frm->combinedsearch;
1175 // Search for person.
1176 if ($personsearch) {
1177 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1178 $users = array();
1179 $mycourses = enrol_get_my_courses('id');
1180 $mycoursesids = array();
1181 foreach ($mycourses as $mycourse) {
1182 $mycoursesids[] = $mycourse->id;
1184 $susers = message_search_users($mycoursesids, $personsearchstring);
1185 foreach ($susers as $suser) {
1186 $users[$suser->id] = $suser;
1188 } else {
1189 $users = message_search_users(SITEID, $personsearchstring);
1192 if (!empty($users)) {
1193 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1194 echo get_string('userssearchresults', 'message', count($users));
1195 echo html_writer::end_tag('p');
1197 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1198 foreach ($users as $user) {
1200 if ( $user->contactlistid ) {
1201 if ($user->blocked == 0) { // User is not blocked.
1202 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1203 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1204 } else { // blocked
1205 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1206 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1208 } else {
1209 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1210 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1213 // Should we show just the icon or icon and text?
1214 $histicontext = 'icon';
1215 if ($showicontext) {
1216 $histicontext = 'both';
1218 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1220 echo html_writer::start_tag('tr');
1222 echo html_writer::start_tag('td', array('class' => 'pix'));
1223 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1224 echo html_writer::end_tag('td');
1226 echo html_writer::start_tag('td',array('class' => 'contact'));
1227 $action = null;
1228 $link = new moodle_url("/message/index.php?id=$user->id");
1229 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1230 echo html_writer::end_tag('td');
1232 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1233 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1234 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1236 echo html_writer::end_tag('tr');
1238 echo html_writer::end_tag('table');
1240 } else {
1241 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1242 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1243 echo html_writer::end_tag('p');
1247 // search messages for keywords
1248 $messagesearch = false;
1249 $messagesearchstring = null;
1250 if (!empty($frm->keywords)) {
1251 $messagesearch = true;
1252 $messagesearchstring = clean_text(trim($frm->keywords));
1253 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1254 $messagesearch = true;
1255 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1258 if ($messagesearch) {
1259 if ($messagesearchstring) {
1260 $keywords = explode(' ', $messagesearchstring);
1261 } else {
1262 $keywords = array();
1264 $tome = false;
1265 $fromme = false;
1266 $courseid = 'none';
1268 if (empty($frm->keywordsoption)) {
1269 $frm->keywordsoption = 'allmine';
1272 switch ($frm->keywordsoption) {
1273 case 'tome':
1274 $tome = true;
1275 break;
1276 case 'fromme':
1277 $fromme = true;
1278 break;
1279 case 'allmine':
1280 $tome = true;
1281 $fromme = true;
1282 break;
1283 case 'allusers':
1284 $courseid = SITEID;
1285 break;
1286 case 'courseusers':
1287 $courseid = $frm->courseid;
1288 break;
1289 default:
1290 $tome = true;
1291 $fromme = true;
1294 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1296 // Get a list of contacts.
1297 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1298 $contacts = array();
1301 // Print heading with number of results.
1302 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1303 $countresults = count($messages);
1304 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1305 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1306 } else {
1307 echo get_string('keywordssearchresults', 'message', $countresults);
1309 echo html_writer::end_tag('p');
1311 // Print table headings.
1312 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1314 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1315 $headertdend = html_writer::end_tag('td');
1316 echo html_writer::start_tag('tr');
1317 echo $headertdstart.get_string('from').$headertdend;
1318 echo $headertdstart.get_string('to').$headertdend;
1319 echo $headertdstart.get_string('message', 'message').$headertdend;
1320 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1321 echo html_writer::end_tag('tr');
1323 $blockedcount = 0;
1324 $dateformat = get_string('strftimedatetimeshort');
1325 $strcontext = get_string('context', 'message');
1326 foreach ($messages as $message) {
1328 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1329 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1330 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1331 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1334 $blockedcount ++;
1335 continue;
1338 // Load user-to record.
1339 if ($message->useridto !== $USER->id) {
1340 $userto = core_user::get_user($message->useridto);
1341 $tocontact = (array_key_exists($message->useridto, $contacts) and
1342 ($contacts[$message->useridto]->blocked == 0) );
1343 $toblocked = (array_key_exists($message->useridto, $contacts) and
1344 ($contacts[$message->useridto]->blocked == 1) );
1345 } else {
1346 $userto = false;
1347 $tocontact = false;
1348 $toblocked = false;
1351 // Load user-from record.
1352 if ($message->useridfrom !== $USER->id) {
1353 $userfrom = core_user::get_user($message->useridfrom);
1354 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1355 ($contacts[$message->useridfrom]->blocked == 0) );
1356 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1357 ($contacts[$message->useridfrom]->blocked == 1) );
1358 } else {
1359 $userfrom = false;
1360 $fromcontact = false;
1361 $fromblocked = false;
1364 // Find date string for this message.
1365 $date = usergetdate($message->timecreated);
1366 $datestring = $date['year'].$date['mon'].$date['mday'];
1368 // Print out message row.
1369 echo html_writer::start_tag('tr', array('valign' => 'top'));
1371 echo html_writer::start_tag('td', array('class' => 'contact'));
1372 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1373 echo html_writer::end_tag('td');
1375 echo html_writer::start_tag('td', array('class' => 'contact'));
1376 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1377 echo html_writer::end_tag('td');
1379 echo html_writer::start_tag('td', array('class' => 'summary'));
1380 echo message_get_fragment($message->smallmessage, $keywords);
1381 echo html_writer::start_tag('div', array('class' => 'link'));
1383 // If the user clicks the context link display message sender on the left.
1384 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1385 $leftsideuserid = $rightsideuserid = null;
1386 if ($currentuser->id == $message->useridto) {
1387 $leftsideuserid = $message->useridto;
1388 $rightsideuserid = $message->useridfrom;
1389 } else {
1390 $leftsideuserid = $message->useridfrom;
1391 $rightsideuserid = $message->useridto;
1393 message_history_link($leftsideuserid, $rightsideuserid, false,
1394 $messagesearchstring, 'm'.$message->id, $strcontext);
1395 echo html_writer::end_tag('div');
1396 echo html_writer::end_tag('td');
1398 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1400 echo html_writer::end_tag('tr');
1404 if ($blockedcount > 0) {
1405 echo html_writer::start_tag('tr');
1406 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1407 echo html_writer::end_tag('tr');
1409 echo html_writer::end_tag('table');
1411 } else {
1412 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1416 if (!$personsearch && !$messagesearch) {
1417 //they didn't enter any search terms
1418 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1421 echo html_writer::end_tag('div');
1425 * Print information on a user. Used when printing search results.
1427 * @param object/bool $user the user to display or false if you just want $USER
1428 * @param bool $iscontact is the user being displayed a contact?
1429 * @param bool $isblocked is the user being displayed blocked?
1430 * @param bool $includeicontext include text next to the action icons?
1431 * @return void
1433 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1434 global $USER, $OUTPUT;
1436 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1438 if ($user === false) {
1439 echo $OUTPUT->user_picture($USER, $userpictureparams);
1440 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1441 $userpictureparams['link'] = false;
1442 echo $OUTPUT->user_picture($USER, $userpictureparams);
1443 echo fullname($user);
1444 } else {
1445 echo $OUTPUT->user_picture($user, $userpictureparams);
1447 $link = new moodle_url("/message/index.php?id=$user->id");
1448 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1449 get_string('sendmessageto', 'message', fullname($user))));
1451 $return = false;
1452 $script = null;
1453 if ($iscontact) {
1454 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1455 } else {
1456 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1459 if ($isblocked) {
1460 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1461 } else {
1462 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1468 * Print a message contact link
1470 * @param int $userid the ID of the user to apply to action to
1471 * @param string $linktype can be add, remove, block or unblock
1472 * @param bool $return if true return the link as a string. If false echo the link.
1473 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1474 * @param bool $text include text next to the icons?
1475 * @param bool $icon include a graphical icon?
1476 * @return string if $return is true otherwise bool
1478 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1479 global $OUTPUT, $PAGE;
1481 //hold onto the strings as we're probably creating a bunch of links
1482 static $str;
1484 if (empty($script)) {
1485 //strip off previous action params like 'removecontact'
1486 $script = message_remove_url_params($PAGE->url);
1489 if (empty($str->blockcontact)) {
1490 $str = new stdClass();
1491 $str->blockcontact = get_string('blockcontact', 'message');
1492 $str->unblockcontact = get_string('unblockcontact', 'message');
1493 $str->removecontact = get_string('removecontact', 'message');
1494 $str->addcontact = get_string('addcontact', 'message');
1497 $command = $linktype.'contact';
1498 $string = $str->{$command};
1500 $safealttext = s($string);
1502 $safestring = '';
1503 if (!empty($text)) {
1504 $safestring = $safealttext;
1507 $img = '';
1508 if ($icon) {
1509 $iconpath = null;
1510 switch ($linktype) {
1511 case 'block':
1512 $iconpath = 't/block';
1513 break;
1514 case 'unblock':
1515 $iconpath = 't/unblock';
1516 break;
1517 case 'remove':
1518 $iconpath = 't/removecontact';
1519 break;
1520 case 'add':
1521 default:
1522 $iconpath = 't/addcontact';
1525 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1528 $output = '<span class="'.$linktype.'contact">'.
1529 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1530 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1531 $img.
1532 $safestring.'</a></span>';
1534 if ($return) {
1535 return $output;
1536 } else {
1537 echo $output;
1538 return true;
1543 * echo or return a link to take the user to the full message history between themselves and another user
1545 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1546 * @param int $userid2 the ID of the other user
1547 * @param bool $return true to return the link as a string. False to echo the link.
1548 * @param string $keywords any keywords to highlight in the message history
1549 * @param string $position anchor name to jump to within the message history
1550 * @param string $linktext optionally specify the link text
1551 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1553 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1554 global $OUTPUT, $PAGE;
1555 static $strmessagehistory;
1557 if (empty($strmessagehistory)) {
1558 $strmessagehistory = get_string('messagehistory', 'message');
1561 if ($position) {
1562 $position = "#$position";
1564 if ($keywords) {
1565 $keywords = "&search=".urlencode($keywords);
1568 if ($linktext == 'icon') { // Icon only
1569 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1570 } else if ($linktext == 'both') { // Icon and standard name
1571 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1572 $fulllink .= '&nbsp;'.$strmessagehistory;
1573 } else if ($linktext) { // Custom name
1574 $fulllink = $linktext;
1575 } else { // Standard name only
1576 $fulllink = $strmessagehistory;
1579 $popupoptions = array(
1580 'height' => 500,
1581 'width' => 500,
1582 'menubar' => false,
1583 'location' => false,
1584 'status' => true,
1585 'scrollbars' => true,
1586 'resizable' => true);
1588 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1589 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1590 $link->param('viewing', $PAGE->url->get_param('viewing'));
1592 $action = null;
1593 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1595 $str = '<span class="history">'.$str.'</span>';
1597 if ($return) {
1598 return $str;
1599 } else {
1600 echo $str;
1601 return true;
1607 * Search through course users.
1609 * If $courseids contains the site course then this function searches
1610 * through all undeleted and confirmed users.
1612 * @param int|array $courseids Course ID or array of course IDs.
1613 * @param string $searchtext the text to search for.
1614 * @param string $sort the column name to order by.
1615 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1616 * @return array An array of {@link $USER} records.
1618 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1619 global $CFG, $USER, $DB;
1621 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1622 if (!$courseids) {
1623 $courseids = array(SITEID);
1626 // Allow an integer to be passed.
1627 if (!is_array($courseids)) {
1628 $courseids = array($courseids);
1631 $fullname = $DB->sql_fullname();
1632 $ufields = user_picture::fields('u');
1634 if (!empty($sort)) {
1635 $order = ' ORDER BY '. $sort;
1636 } else {
1637 $order = '';
1640 $params = array(
1641 'userid' => $USER->id,
1642 'query' => "%$searchtext%"
1645 if (empty($exceptions)) {
1646 $exceptions = array();
1647 } else if (!empty($exceptions) && is_string($exceptions)) {
1648 $exceptions = explode(',', $exceptions);
1651 // Ignore self and guest account.
1652 $exceptions[] = $USER->id;
1653 $exceptions[] = $CFG->siteguest;
1655 // Exclude exceptions from the search result.
1656 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1657 $except = ' AND u.id ' . $except;
1658 $params = array_merge($params_except, $params);
1660 if (in_array(SITEID, $courseids)) {
1661 // Search on site level.
1662 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1663 FROM {user} u
1664 LEFT JOIN {message_contacts} mc
1665 ON mc.contactid = u.id AND mc.userid = :userid
1666 WHERE u.deleted = '0' AND u.confirmed = '1'
1667 AND (".$DB->sql_like($fullname, ':query', false).")
1668 $except
1669 $order", $params);
1670 } else {
1671 // Search in courses.
1673 // Getting the context IDs or each course.
1674 $contextids = array();
1675 foreach ($courseids as $courseid) {
1676 $context = context_course::instance($courseid);
1677 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1679 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1680 $params = array_merge($params, $contextparams);
1682 // Everyone who has a role assignment in this course or higher.
1683 // TODO: add enabled enrolment join here (skodak)
1684 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1685 FROM {user} u
1686 JOIN {role_assignments} ra ON ra.userid = u.id
1687 LEFT JOIN {message_contacts} mc
1688 ON mc.contactid = u.id AND mc.userid = :userid
1689 WHERE u.deleted = '0' AND u.confirmed = '1'
1690 AND (".$DB->sql_like($fullname, ':query', false).")
1691 AND ra.contextid $contextwhere
1692 $except
1693 $order", $params);
1695 return $users;
1700 * Search a user's messages
1702 * Returns a list of posts found using an array of search terms
1703 * eg word +word -word
1705 * @param array $searchterms an array of search terms (strings)
1706 * @param bool $fromme include messages from the user?
1707 * @param bool $tome include messages to the user?
1708 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1709 * @param int $userid the user ID of the current user
1710 * @return mixed An array of messages or false if no matching messages were found
1712 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1713 global $CFG, $USER, $DB;
1715 // If user is searching all messages check they are allowed to before doing anything else.
1716 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1717 print_error('accessdenied','admin');
1720 // If no userid sent then assume current user.
1721 if ($userid == 0) $userid = $USER->id;
1723 // Some differences in SQL syntax.
1724 if ($DB->sql_regex_supported()) {
1725 $REGEXP = $DB->sql_regex(true);
1726 $NOTREGEXP = $DB->sql_regex(false);
1729 $searchcond = array();
1730 $params = array();
1731 $i = 0;
1733 // Preprocess search terms to check whether we have at least 1 eligible search term.
1734 // If we do we can drop words around it like 'a'.
1735 $dropshortwords = false;
1736 foreach ($searchterms as $searchterm) {
1737 if (strlen($searchterm) >= 2) {
1738 $dropshortwords = true;
1742 foreach ($searchterms as $searchterm) {
1743 $i++;
1745 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1747 if ($dropshortwords && strlen($searchterm) < 2) {
1748 continue;
1750 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1751 if (!$DB->sql_regex_supported()) {
1752 if (substr($searchterm, 0, 1) == '-') {
1753 $NOT = true;
1755 $searchterm = trim($searchterm, '+-');
1758 if (substr($searchterm,0,1) == "+") {
1759 $searchterm = substr($searchterm,1);
1760 $searchterm = preg_quote($searchterm, '|');
1761 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1762 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1764 } else if (substr($searchterm,0,1) == "-") {
1765 $searchterm = substr($searchterm,1);
1766 $searchterm = preg_quote($searchterm, '|');
1767 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1768 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1770 } else {
1771 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1772 $params['ss'.$i] = "%$searchterm%";
1776 if (empty($searchcond)) {
1777 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1778 $params['ss1'] = "%";
1779 } else {
1780 $searchcond = implode(" AND ", $searchcond);
1783 // There are several possibilities
1784 // 1. courseid = SITEID : The admin is searching messages by all users
1785 // 2. courseid = ?? : A teacher is searching messages by users in
1786 // one of their courses - currently disabled
1787 // 3. courseid = none : User is searching their own messages;
1788 // a. Messages from user
1789 // b. Messages to user
1790 // c. Messages to and from user
1792 if ($courseid == SITEID) { // Admin is searching all messages.
1793 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1794 FROM {message_read} m
1795 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1796 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1797 FROM {message} m
1798 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1800 } else if ($courseid !== 'none') {
1801 // This has not been implemented due to security concerns.
1802 $m_read = array();
1803 $m_unread = array();
1805 } else {
1807 if ($fromme and $tome) {
1808 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1809 $params['userid1'] = $userid;
1810 $params['userid2'] = $userid;
1812 } else if ($fromme) {
1813 $searchcond .= " AND m.useridfrom=:userid";
1814 $params['userid'] = $userid;
1816 } else if ($tome) {
1817 $searchcond .= " AND m.useridto=:userid";
1818 $params['userid'] = $userid;
1821 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1822 FROM {message_read} m
1823 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1824 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1825 FROM {message} m
1826 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1830 /// The keys may be duplicated in $m_read and $m_unread so we can't
1831 /// do a simple concatenation
1832 $messages = array();
1833 foreach ($m_read as $m) {
1834 $messages[] = $m;
1836 foreach ($m_unread as $m) {
1837 $messages[] = $m;
1840 return (empty($messages)) ? false : $messages;
1844 * Given a message object that we already know has a long message
1845 * this function truncates the message nicely to the first
1846 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1848 * @param string $message the message
1849 * @param int $minlength the minimum length to trim the message to
1850 * @return string the shortened message
1852 function message_shorten_message($message, $minlength = 0) {
1853 $i = 0;
1854 $tag = false;
1855 $length = strlen($message);
1856 $count = 0;
1857 $stopzone = false;
1858 $truncate = 0;
1859 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1862 for ($i=0; $i<$length; $i++) {
1863 $char = $message[$i];
1865 switch ($char) {
1866 case "<":
1867 $tag = true;
1868 break;
1869 case ">":
1870 $tag = false;
1871 break;
1872 default:
1873 if (!$tag) {
1874 if ($stopzone) {
1875 if ($char == '.' or $char == ' ') {
1876 $truncate = $i+1;
1877 break 2;
1880 $count++;
1882 break;
1884 if (!$stopzone) {
1885 if ($count > $minlength) {
1886 $stopzone = true;
1891 if (!$truncate) {
1892 $truncate = $i;
1895 return substr($message, 0, $truncate);
1900 * Given a string and an array of keywords, this function looks
1901 * for the first keyword in the string, and then chops out a
1902 * small section from the text that shows that word in context.
1904 * @param string $message the text to search
1905 * @param array $keywords array of keywords to find
1907 function message_get_fragment($message, $keywords) {
1909 $fullsize = 160;
1910 $halfsize = (int)($fullsize/2);
1912 $message = strip_tags($message);
1914 foreach ($keywords as $keyword) { // Just get the first one
1915 if ($keyword !== '') {
1916 break;
1919 if (empty($keyword)) { // None found, so just return start of message
1920 return message_shorten_message($message, 30);
1923 $leadin = $leadout = '';
1925 /// Find the start of the fragment
1926 $start = 0;
1927 $length = strlen($message);
1929 $pos = strpos($message, $keyword);
1930 if ($pos > $halfsize) {
1931 $start = $pos - $halfsize;
1932 $leadin = '...';
1934 /// Find the end of the fragment
1935 $end = $start + $fullsize;
1936 if ($end > $length) {
1937 $end = $length;
1938 } else {
1939 $leadout = '...';
1942 /// Pull out the fragment and format it
1944 $fragment = substr($message, $start, $end - $start);
1945 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1946 return $fragment;
1950 * Retrieve the messages between two users
1952 * @param object $user1 the current user
1953 * @param object $user2 the other user
1954 * @param int $limitnum the maximum number of messages to retrieve
1955 * @param bool $viewingnewmessages are we currently viewing new messages?
1957 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1958 global $DB, $CFG;
1960 $messages = array();
1962 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1963 //desc to get the last $limitnum messages then flip the order in php
1964 $sort = 'asc';
1965 if ($limitnum>0) {
1966 $sort = 'desc';
1969 $notificationswhere = null;
1970 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1971 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1972 $notificationswhere = 'AND notification=0';
1975 //prevent notifications of your own actions appearing in your own message history
1976 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1978 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1979 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1980 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1981 "timecreated $sort", '*', 0, $limitnum)) {
1982 foreach ($messages_read as $message) {
1983 $messages[] = $message;
1986 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1987 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1988 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1989 "timecreated $sort", '*', 0, $limitnum)) {
1990 foreach ($messages_new as $message) {
1991 $messages[] = $message;
1995 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
1997 //if we only want the last $limitnum messages
1998 $messagecount = count($messages);
1999 if ($limitnum > 0 && $messagecount > $limitnum) {
2000 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
2003 return $messages;
2007 * Print the message history between two users
2009 * @param object $user1 the current user
2010 * @param object $user2 the other user
2011 * @param string $search search terms to highlight
2012 * @param int $messagelimit maximum number of messages to return
2013 * @param string $messagehistorylink the html for the message history link or false
2014 * @param bool $viewingnewmessages are we currently viewing new messages?
2016 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
2017 global $CFG, $OUTPUT;
2019 echo $OUTPUT->box_start('center', 'message_user_pictures');
2020 echo $OUTPUT->box_start('user');
2021 echo $OUTPUT->box_start('generalbox', 'user1');
2022 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2023 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
2024 echo $OUTPUT->box_end();
2025 echo $OUTPUT->box_end();
2027 $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16);
2028 echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between');
2030 echo $OUTPUT->box_start('user');
2031 echo $OUTPUT->box_start('generalbox', 'user2');
2032 // Show user picture with link is real user else without link.
2033 if (core_user::is_real_user($user2->id)) {
2034 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2035 } else {
2036 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2038 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2040 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2042 $script = null;
2043 $text = true;
2044 $icon = false;
2046 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2047 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2048 $useractionlinks = $strcontact.'&nbsp;|&nbsp;'.$strblock;
2050 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2052 echo $OUTPUT->box_end();
2053 echo $OUTPUT->box_end();
2054 echo $OUTPUT->box_end();
2056 if (!empty($messagehistorylink)) {
2057 echo $messagehistorylink;
2060 /// Get all the messages and print them
2061 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2062 $tablecontents = '';
2064 $current = new stdClass();
2065 $current->mday = '';
2066 $current->month = '';
2067 $current->year = '';
2068 $messagedate = get_string('strftimetime');
2069 $blockdate = get_string('strftimedaydate');
2070 foreach ($messages as $message) {
2071 if ($message->notification) {
2072 $notificationclass = ' notification';
2073 } else {
2074 $notificationclass = null;
2076 $date = usergetdate($message->timecreated);
2077 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2078 $current->mday = $date['mday'];
2079 $current->month = $date['month'];
2080 $current->year = $date['year'];
2082 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2083 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2085 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2088 $formatted_message = $side = null;
2089 if ($message->useridfrom == $user1->id) {
2090 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2091 $side = 'left';
2092 } else {
2093 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2094 $side = 'right';
2096 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2099 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2100 } else {
2101 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2106 * Format a message for display in the message history
2108 * @param object $message the message object
2109 * @param string $format optional date format
2110 * @param string $keywords keywords to highlight
2111 * @param string $class CSS class to apply to the div around the message
2112 * @return string the formatted message
2114 function message_format_message($message, $format='', $keywords='', $class='other') {
2116 static $dateformat;
2118 //if we haven't previously set the date format or they've supplied a new one
2119 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2120 if ($format) {
2121 $dateformat = $format;
2122 } else {
2123 $dateformat = get_string('strftimedatetimeshort');
2126 $time = userdate($message->timecreated, $dateformat);
2128 $messagetext = message_format_message_text($message, false);
2130 if ($keywords) {
2131 $messagetext = highlight($keywords, $messagetext);
2134 $messagetext .= message_format_contexturl($message);
2136 $messagetext = clean_text($messagetext, FORMAT_HTML);
2138 return <<<TEMPLATE
2139 <div class='message $class'>
2140 <a name="m{$message->id}"></a>
2141 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2142 </div>
2143 TEMPLATE;
2147 * Format a the context url and context url name of a message for display
2149 * @param object $message the message object
2150 * @return string the formatted string
2152 function message_format_contexturl($message) {
2153 $s = null;
2155 if (!empty($message->contexturl)) {
2156 $displaytext = null;
2157 if (!empty($message->contexturlname)) {
2158 $displaytext= $message->contexturlname;
2159 } else {
2160 $displaytext= $message->contexturl;
2162 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2163 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2164 $s .= html_writer::end_tag('div');
2167 return $s;
2171 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2173 * @param object $userfrom the message sender
2174 * @param object $userto the message recipient
2175 * @param string $message the message
2176 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2177 * @return int|false the ID of the new message or false
2179 function message_post_message($userfrom, $userto, $message, $format) {
2180 global $SITE, $CFG, $USER;
2182 $eventdata = new stdClass();
2183 $eventdata->component = 'moodle';
2184 $eventdata->name = 'instantmessage';
2185 $eventdata->userfrom = $userfrom;
2186 $eventdata->userto = $userto;
2188 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2189 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2191 if ($format == FORMAT_HTML) {
2192 $eventdata->fullmessagehtml = $message;
2193 //some message processors may revert to sending plain text even if html is supplied
2194 //so we keep both plain and html versions if we're intending to send html
2195 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2196 } else {
2197 $eventdata->fullmessage = $message;
2198 $eventdata->fullmessagehtml = '';
2201 $eventdata->fullmessageformat = $format;
2202 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2204 $s = new stdClass();
2205 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2206 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2208 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2209 if (!empty($eventdata->fullmessage)) {
2210 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2212 if (!empty($eventdata->fullmessagehtml)) {
2213 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2216 $eventdata->timecreated = time();
2217 $eventdata->notification = 0;
2218 return message_send($eventdata);
2222 * Print a row of contactlist displaying user picture, messages waiting and
2223 * block links etc
2225 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2226 * @param bool $incontactlist is the user a contact of ours?
2227 * @param bool $isblocked is the user blocked?
2228 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2229 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2230 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2231 * @return void
2233 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2234 global $OUTPUT, $USER, $COURSE;
2235 $fullname = fullname($contact);
2236 $fullnamelink = $fullname;
2237 $output = '';
2239 $linkclass = '';
2240 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2241 $linkclass = 'messageselecteduser';
2244 // Are there any unread messages for this contact?
2245 if ($contact->messagecount > 0 ){
2246 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2249 $strcontact = $strblock = $strhistory = null;
2251 if ($showactionlinks) {
2252 // Show block and delete links if user is real user.
2253 if (core_user::is_real_user($contact->id)) {
2254 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2255 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2257 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2260 $output .= html_writer::start_tag('div', array('class' => 'pix'));
2261 $output .= $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2262 $output .= html_writer::end_tag('div');
2264 $popupoptions = array(
2265 'height' => MESSAGE_DISCUSSION_HEIGHT,
2266 'width' => MESSAGE_DISCUSSION_WIDTH,
2267 'menubar' => false,
2268 'location' => false,
2269 'status' => true,
2270 'scrollbars' => true,
2271 'resizable' => true);
2273 $link = $action = null;
2274 if (!empty($selectcontacturl)) {
2275 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2276 } else {
2277 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2278 $link = new moodle_url("/message/index.php?id=$contact->id");
2279 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2283 if (strlen($strcontact . $strblock . $strhistory) > 0) {
2284 $output .= html_writer::tag('div', $strcontact . $strblock . $strhistory, array('class' => 'link'));
2286 $output .= html_writer::start_tag('div', array('class' => 'contact'));
2287 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2288 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2289 $output .= html_writer::end_tag('div');
2290 } else {
2291 $output .= html_writer::start_tag('div', array('class' => 'contact nolinks'));
2292 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2293 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2294 $output .= html_writer::end_tag('div');
2297 return $output;
2301 * Constructs the add/remove contact link to display next to other users
2303 * @param bool $incontactlist is the user a contact
2304 * @param bool $isblocked is the user blocked
2305 * @param stdClass $contact contact object
2306 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2307 * @param bool $text include text next to the icons?
2308 * @param bool $icon include a graphical icon?
2309 * @return string
2311 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2312 $strcontact = '';
2314 if($incontactlist){
2315 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2316 } else if ($isblocked) {
2317 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2318 } else{
2319 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2322 return $strcontact;
2326 * Constructs the block contact link to display next to other users
2328 * @param bool $incontactlist is the user a contact?
2329 * @param bool $isblocked is the user blocked?
2330 * @param stdClass $contact contact object
2331 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2332 * @param bool $text include text next to the icons?
2333 * @param bool $icon include a graphical icon?
2334 * @return string
2336 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2337 $strblock = '';
2339 //commented out to allow the user to block a contact without having to remove them first
2340 /*if ($incontactlist) {
2341 //$strblock = '';
2342 } else*/
2343 if ($isblocked) {
2344 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2345 } else{
2346 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2349 return $strblock;
2353 * Moves messages from a particular user from the message table (unread messages) to message_read
2354 * This is typically only used when a user is deleted
2356 * @param object $userid User id
2357 * @return boolean success
2359 function message_move_userfrom_unread2read($userid) {
2360 global $DB;
2362 // move all unread messages from message table to message_read
2363 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2364 foreach ($messages as $message) {
2365 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2368 return true;
2372 * marks ALL messages being sent from $fromuserid to $touserid as read
2374 * @param int $touserid the id of the message recipient
2375 * @param int $fromuserid the id of the message sender
2376 * @return void
2378 function message_mark_messages_read($touserid, $fromuserid) {
2379 global $DB;
2381 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2382 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2384 foreach ($messages as $message) {
2385 message_mark_message_read($message, time());
2388 $messages->close();
2392 * Mark a single message as read
2394 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2395 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2396 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2397 * @return int the ID of the message in the message_read table
2399 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2400 global $DB;
2402 $message->timeread = $timeread;
2404 $messageid = $message->id;
2405 unset($message->id);//unset because it will get a new id on insert into message_read
2407 //If any processors have pending actions abort them
2408 if (!$messageworkingempty) {
2409 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2411 $messagereadid = $DB->insert_record('message_read', $message);
2413 $DB->delete_records('message', array('id' => $messageid));
2415 // Get the context for the user who received the message.
2416 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2417 // If the user no longer exists the context value will be false, in this case use the system context.
2418 if ($context === false) {
2419 $context = context_system::instance();
2422 // Trigger event for reading a message.
2423 $event = \core\event\message_viewed::create(array(
2424 'objectid' => $messagereadid,
2425 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2426 'context' => $context,
2427 'relateduserid' => $message->useridfrom,
2428 'other' => array(
2429 'messageid' => $messageid
2432 $event->trigger();
2434 return $messagereadid;
2438 * Get all message processors, validate corresponding plugin existance and
2439 * system configuration
2441 * @param bool $ready only return ready-to-use processors
2442 * @param bool $reset Reset list of message processors (used in unit tests)
2443 * @return mixed $processors array of objects containing information on message processors
2445 function get_message_processors($ready = false, $reset = false) {
2446 global $DB, $CFG;
2448 static $processors;
2449 if ($reset) {
2450 $processors = array();
2453 if (empty($processors)) {
2454 // Get all processors, ensure the name column is the first so it will be the array key
2455 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2456 foreach ($processors as &$processor){
2457 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2458 if (is_readable($processorfile)) {
2459 include_once($processorfile);
2460 $processclass = 'message_output_' . $processor->name;
2461 if (class_exists($processclass)) {
2462 $pclass = new $processclass();
2463 $processor->object = $pclass;
2464 $processor->configured = 0;
2465 if ($pclass->is_system_configured()) {
2466 $processor->configured = 1;
2468 $processor->hassettings = 0;
2469 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2470 $processor->hassettings = 1;
2472 $processor->available = 1;
2473 } else {
2474 print_error('errorcallingprocessor', 'message');
2476 } else {
2477 $processor->available = 0;
2481 if ($ready) {
2482 // Filter out enabled and system_configured processors
2483 $readyprocessors = $processors;
2484 foreach ($readyprocessors as $readyprocessor) {
2485 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2486 unset($readyprocessors[$readyprocessor->name]);
2489 return $readyprocessors;
2492 return $processors;
2496 * Get all message providers, validate their plugin existance and
2497 * system configuration
2499 * @return mixed $processors array of objects containing information on message processors
2501 function get_message_providers() {
2502 global $CFG, $DB;
2504 $pluginman = core_plugin_manager::instance();
2506 $providers = $DB->get_records('message_providers', null, 'name');
2508 // Remove all the providers whose plugins are disabled or don't exist
2509 foreach ($providers as $providerid => $provider) {
2510 $plugin = $pluginman->get_plugin_info($provider->component);
2511 if ($plugin) {
2512 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2513 unset($providers[$providerid]); // Plugins does not exist
2514 continue;
2516 if ($plugin->is_enabled() === false) {
2517 unset($providers[$providerid]); // Plugin disabled
2518 continue;
2522 return $providers;
2526 * Get an instance of the message_output class for one of the output plugins.
2527 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2528 * @return message_output message_output the requested class.
2530 function get_message_processor($type) {
2531 global $CFG;
2533 // Note, we cannot use the get_message_processors function here, becaues this
2534 // code is called during install after installing each messaging plugin, and
2535 // get_message_processors caches the list of installed plugins.
2537 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2538 if (!is_readable($processorfile)) {
2539 throw new coding_exception('Unknown message processor type ' . $type);
2542 include_once($processorfile);
2544 $processclass = 'message_output_' . $type;
2545 if (!class_exists($processclass)) {
2546 throw new coding_exception('Message processor ' . $type .
2547 ' does not define the right class');
2550 return new $processclass();
2554 * Get messaging outputs default (site) preferences
2556 * @return object $processors object containing information on message processors
2558 function get_message_output_default_preferences() {
2559 return get_config('message');
2563 * Translate message default settings from binary value to the array of string
2564 * representing the settings to be stored. Also validate the provided value and
2565 * use default if it is malformed.
2567 * @param int $plugindefault Default setting suggested by plugin
2568 * @param string $processorname The name of processor
2569 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2571 function translate_message_default_setting($plugindefault, $processorname) {
2572 // Preset translation arrays
2573 $permittedvalues = array(
2574 0x04 => 'disallowed',
2575 0x08 => 'permitted',
2576 0x0c => 'forced',
2579 $loggedinstatusvalues = array(
2580 0x00 => null, // use null if loggedin/loggedoff is not defined
2581 0x01 => 'loggedin',
2582 0x02 => 'loggedoff',
2585 // define the default setting
2586 $processor = get_message_processor($processorname);
2587 $default = $processor->get_default_messaging_settings();
2589 // Validate the value. It should not exceed the maximum size
2590 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2591 debugging(get_string('errortranslatingdefault', 'message'));
2592 $plugindefault = $default;
2594 // Use plugin default setting of 'permitted' is 0
2595 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2596 $plugindefault = $default;
2599 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2600 $loggedin = $loggedoff = null;
2602 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2603 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2604 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2607 return array($permitted, $loggedin, $loggedoff);
2611 * Return a list of page types
2612 * @param string $pagetype current page type
2613 * @param stdClass $parentcontext Block's parent context
2614 * @param stdClass $currentcontext Current context of block
2616 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2617 return array('messages-*'=>get_string('page-message-x', 'message'));
2621 * Get messages sent or/and received by the specified users.
2623 * @param int $useridto the user id who received the message
2624 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
2625 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
2626 * @param bool $read true for retrieving read messages, false for unread
2627 * @param string $sort the column name to order by including optionally direction
2628 * @param int $limitfrom limit from
2629 * @param int $limitnum limit num
2630 * @return external_description
2631 * @since 2.8
2633 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
2634 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
2635 global $DB;
2637 $messagetable = $read ? '{message_read}' : '{message}';
2638 $params = array('deleted' => 0);
2640 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
2641 if (empty($useridto)) {
2642 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
2643 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
2644 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
2645 $params['useridfrom'] = $useridfrom;
2646 } else {
2647 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
2648 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
2649 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
2650 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
2651 $params['useridto'] = $useridto;
2652 if (!empty($useridfrom)) {
2653 $usersql .= " AND mr.useridfrom = :useridfrom";
2654 $params['useridfrom'] = $useridfrom;
2658 // Now, if retrieve notifications, conversations or both.
2659 $typesql = "";
2660 if ($notifications !== -1) {
2661 $typesql = "AND mr.notification = :notification";
2662 $params['notification'] = ($notifications) ? 1 : 0;
2665 $sql = "SELECT mr.*, $userfields
2666 FROM $messagetable mr
2667 $joinsql
2668 WHERE $usersql
2669 $typesql
2670 ORDER BY $sort";
2672 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2673 return $messages;
2677 * Requires the JS libraries to send a message using a dialog.
2679 * @return void
2681 function message_messenger_requirejs() {
2682 global $PAGE;
2684 static $done = false;
2685 if ($done) {
2686 return;
2689 $PAGE->requires->yui_module(
2690 array('moodle-core_message-messenger'),
2691 'Y.M.core_message.messenger.init',
2692 array(array())
2694 $PAGE->requires->strings_for_js(array(
2695 'errorwhilesendingmessage',
2696 'messagesent',
2697 'messagetosend',
2698 'sendingmessage',
2699 'sendmessage',
2700 'viewconversation',
2701 ), 'core_message');
2702 $PAGE->requires->string_for_js('error', 'core');
2704 $done = true;
2708 * Returns the attributes to place on a link to open the 'Send message' dialog.
2710 * @param object $user User object.
2711 * @return void
2713 function message_messenger_sendmessage_link_params($user) {
2714 return array(
2715 'data-trigger' => 'core_message-messenger::sendmessage',
2716 'data-fullname' => fullname($user),
2717 'data-userid' => $user->id,
2718 'role' => 'button'