Merge branch 'wip-mdl-50259' of https://github.com/rajeshtaneja/moodle
[moodle.git] / message / lib.php
bloba8342fb94f8526f62dcb8d77daf1a6e9ee94388f
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 $conversations = array();
781 $conversation_arrays = array($unread, $read);
782 foreach ($conversation_arrays as $conversation_array) {
783 foreach ($conversation_array as $conversation) {
784 if (!isset($conversations[$conversation->id])) {
785 $conversations[$conversation->id] = $conversation;
786 } else {
787 $current = $conversations[$conversation->id];
788 if ($current->timecreated < $conversation->timecreated) {
789 $conversations[$conversation->id] = $conversation;
790 } else if ($current->timecreated == $conversation->timecreated) {
791 if ($current->mid < $conversation->mid) {
792 $conversations[$conversation->id] = $conversation;
799 // Sort the conversations by $conversation->timecreated, newest to oldest
800 // There may be multiple conversations with the same timecreated
801 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
802 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
803 $conversations = array_reverse($conversations);
805 return $conversations;
809 * Get the users recent event notifications
811 * @param object $user the current user
812 * @param int $limitfrom can be used for paging
813 * @param int $limitto can be used for paging
814 * @return array
816 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
817 global $DB;
819 $userfields = user_picture::fields('u', array('lastaccess'));
820 $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
821 FROM {message_read} mr
822 JOIN {user} u ON u.id=mr.useridfrom
823 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
824 ORDER BY mr.timecreated DESC";
825 $params = array('userid1' => $user->id, 'notification' => 1);
827 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
828 return $notifications;
832 * Print the user's recent conversations
834 * @param stdClass $user the current user
835 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
837 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
838 global $USER;
840 echo html_writer::start_tag('p', array('class' => 'heading'));
841 echo get_string('mostrecentconversations', 'message');
842 echo html_writer::end_tag('p');
844 if (empty($user1)) {
845 $user1 = $USER;
848 $conversations = message_get_recent_conversations($user1);
850 // Attach context url information to create the "View this conversation" type links
851 foreach($conversations as $conversation) {
852 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
853 $conversation->contexturlname = get_string('thisconversation', 'message');
856 $showotheruser = true;
857 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
861 * Print the user's recent notifications
863 * @param stdClass $user the current user
865 function message_print_recent_notifications($user=null) {
866 global $USER;
868 echo html_writer::start_tag('p', array('class' => 'heading'));
869 echo get_string('mostrecentnotifications', 'message');
870 echo html_writer::end_tag('p');
872 if (empty($user)) {
873 $user = $USER;
876 $notifications = message_get_recent_notifications($user);
878 $showicontext = false;
879 $showotheruser = false;
880 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
884 * Print a list of recent messages
886 * @access private
888 * @param array $messages the messages to display
889 * @param stdClass $user the current user
890 * @param bool $showotheruser display information on the other user?
891 * @param bool $showicontext show text next to the action icons?
892 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
893 * @param bool $showactionlinks
894 * @return void
896 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
897 global $OUTPUT;
898 static $dateformat;
900 if (empty($dateformat)) {
901 $dateformat = get_string('strftimedatetimeshort');
904 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
905 foreach ($messages as $message) {
906 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
908 if ($showotheruser) {
909 $strcontact = $strblock = $strhistory = null;
911 if ($showactionlinks) {
912 if ( $message->contactlistid ) {
913 if ($message->blocked == 0) { // The other user isn't blocked.
914 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
915 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
916 } else { // The other user is blocked.
917 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
918 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
920 } else {
921 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
922 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
925 //should we show just the icon or icon and text?
926 $histicontext = 'icon';
927 if ($showicontext) {
928 $histicontext = 'both';
930 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
932 echo html_writer::start_tag('span', array('class' => 'otheruser'));
934 echo html_writer::start_tag('span', array('class' => 'pix'));
935 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
936 echo html_writer::end_tag('span');
938 echo html_writer::start_tag('span', array('class' => 'contact'));
940 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
941 $action = null;
942 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
944 echo html_writer::end_tag('span');//end contact
946 if ($showactionlinks) {
947 echo $strcontact.$strblock.$strhistory;
949 echo html_writer::end_tag('span');//end otheruser
952 $messagetext = message_format_message_text($message, $forcetexttohtml);
954 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
955 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
956 echo message_format_contexturl($message);
957 echo html_writer::end_tag('div');//end singlemessage
959 echo html_writer::end_tag('div');//end messagerecent
963 * Try to guess how to convert the message to html.
965 * @access private
967 * @param stdClass $message
968 * @param bool $forcetexttohtml
969 * @return string html fragment
971 function message_format_message_text($message, $forcetexttohtml = false) {
972 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
974 $options = new stdClass();
975 $options->para = false;
977 $format = $message->fullmessageformat;
979 if ($message->smallmessage !== '') {
980 if ($message->notification == 1) {
981 if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
982 $format = FORMAT_PLAIN;
985 $messagetext = $message->smallmessage;
987 } else if ($message->fullmessageformat == FORMAT_HTML) {
988 if ($message->fullmessagehtml !== '') {
989 $messagetext = $message->fullmessagehtml;
990 } else {
991 $messagetext = $message->fullmessage;
992 $format = FORMAT_MOODLE;
995 } else {
996 if ($message->fullmessage !== '') {
997 $messagetext = $message->fullmessage;
998 } else {
999 $messagetext = $message->fullmessagehtml;
1000 $format = FORMAT_HTML;
1004 if ($forcetexttohtml) {
1005 // This is a crazy hack, why not set proper format when creating the notifications?
1006 if ($format === FORMAT_PLAIN) {
1007 $format = FORMAT_MOODLE;
1010 return format_text($messagetext, $format, $options);
1014 * Add the selected user as a contact for the current user
1016 * @param int $contactid the ID of the user to add as a contact
1017 * @param int $blocked 1 if you wish to block the contact
1018 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
1019 * Otherwise returns the result of update_record() or insert_record()
1021 function message_add_contact($contactid, $blocked=0) {
1022 global $USER, $DB;
1024 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
1025 return false;
1028 // Check if a record already exists as we may be changing blocking status.
1029 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
1030 // Check if blocking status has been changed.
1031 if ($contact->blocked !== $blocked) {
1032 $contact->blocked = $blocked;
1033 $DB->update_record('message_contacts', $contact);
1035 if ($blocked == 1) {
1036 // Trigger event for blocking a contact.
1037 $event = \core\event\message_contact_blocked::create(array(
1038 'objectid' => $contact->id,
1039 'userid' => $contact->userid,
1040 'relateduserid' => $contact->contactid,
1041 'context' => context_user::instance($contact->userid)
1043 $event->add_record_snapshot('message_contacts', $contact);
1044 $event->trigger();
1045 } else {
1046 // Trigger event for unblocking a contact.
1047 $event = \core\event\message_contact_unblocked::create(array(
1048 'objectid' => $contact->id,
1049 'userid' => $contact->userid,
1050 'relateduserid' => $contact->contactid,
1051 'context' => context_user::instance($contact->userid)
1053 $event->add_record_snapshot('message_contacts', $contact);
1054 $event->trigger();
1057 return true;
1058 } else {
1059 // No change to blocking status.
1060 return true;
1063 } else {
1064 // New contact record.
1065 $contact = new stdClass();
1066 $contact->userid = $USER->id;
1067 $contact->contactid = $contactid;
1068 $contact->blocked = $blocked;
1069 $contact->id = $DB->insert_record('message_contacts', $contact);
1071 $eventparams = array(
1072 'objectid' => $contact->id,
1073 'userid' => $contact->userid,
1074 'relateduserid' => $contact->contactid,
1075 'context' => context_user::instance($contact->userid)
1078 if ($blocked) {
1079 $event = \core\event\message_contact_blocked::create($eventparams);
1080 } else {
1081 $event = \core\event\message_contact_added::create($eventparams);
1083 // Trigger event.
1084 $event->trigger();
1086 return true;
1091 * remove a contact
1093 * @param int $contactid the user ID of the contact to remove
1094 * @return bool returns the result of delete_records()
1096 function message_remove_contact($contactid) {
1097 global $USER, $DB;
1099 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1100 $DB->delete_records('message_contacts', array('id' => $contact->id));
1102 // Trigger event for removing a contact.
1103 $event = \core\event\message_contact_removed::create(array(
1104 'objectid' => $contact->id,
1105 'userid' => $contact->userid,
1106 'relateduserid' => $contact->contactid,
1107 'context' => context_user::instance($contact->userid)
1109 $event->add_record_snapshot('message_contacts', $contact);
1110 $event->trigger();
1112 return true;
1115 return false;
1119 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1121 * @param int $contactid the user ID of the contact to unblock
1122 * @return bool returns the result of delete_records()
1124 function message_unblock_contact($contactid) {
1125 return message_add_contact($contactid, 0);
1129 * Block a user.
1131 * @param int $contactid the user ID of the user to block
1132 * @return bool
1134 function message_block_contact($contactid) {
1135 return message_add_contact($contactid, 1);
1139 * Load a user's contact record
1141 * @param int $contactid the user ID of the user whose contact record you want
1142 * @return array message contacts
1144 function message_get_contact($contactid) {
1145 global $USER, $DB;
1146 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1150 * Print the results of a message search
1152 * @param mixed $frm submitted form data
1153 * @param bool $showicontext show text next to action icons?
1154 * @param object $currentuser the current user
1155 * @return void
1157 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1158 global $USER, $DB, $OUTPUT;
1160 if (empty($currentuser)) {
1161 $currentuser = $USER;
1164 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1166 $personsearch = false;
1167 $personsearchstring = null;
1168 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1169 $personsearch = true;
1170 $personsearchstring = $frm->name;
1171 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1172 $personsearch = true;
1173 $personsearchstring = $frm->combinedsearch;
1176 // Search for person.
1177 if ($personsearch) {
1178 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1179 $users = array();
1180 $mycourses = enrol_get_my_courses('id');
1181 $mycoursesids = array();
1182 foreach ($mycourses as $mycourse) {
1183 $mycoursesids[] = $mycourse->id;
1185 $susers = message_search_users($mycoursesids, $personsearchstring);
1186 foreach ($susers as $suser) {
1187 $users[$suser->id] = $suser;
1189 } else {
1190 $users = message_search_users(SITEID, $personsearchstring);
1193 if (!empty($users)) {
1194 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1195 echo get_string('userssearchresults', 'message', count($users));
1196 echo html_writer::end_tag('p');
1198 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1199 foreach ($users as $user) {
1201 if ( $user->contactlistid ) {
1202 if ($user->blocked == 0) { // User is not blocked.
1203 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1204 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1205 } else { // blocked
1206 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1207 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1209 } else {
1210 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1211 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1214 // Should we show just the icon or icon and text?
1215 $histicontext = 'icon';
1216 if ($showicontext) {
1217 $histicontext = 'both';
1219 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1221 echo html_writer::start_tag('tr');
1223 echo html_writer::start_tag('td', array('class' => 'pix'));
1224 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1225 echo html_writer::end_tag('td');
1227 echo html_writer::start_tag('td',array('class' => 'contact'));
1228 $action = null;
1229 $link = new moodle_url("/message/index.php?id=$user->id");
1230 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1231 echo html_writer::end_tag('td');
1233 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1234 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1235 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1237 echo html_writer::end_tag('tr');
1239 echo html_writer::end_tag('table');
1241 } else {
1242 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1243 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1244 echo html_writer::end_tag('p');
1248 // search messages for keywords
1249 $messagesearch = false;
1250 $messagesearchstring = null;
1251 if (!empty($frm->keywords)) {
1252 $messagesearch = true;
1253 $messagesearchstring = clean_text(trim($frm->keywords));
1254 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1255 $messagesearch = true;
1256 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1259 if ($messagesearch) {
1260 if ($messagesearchstring) {
1261 $keywords = explode(' ', $messagesearchstring);
1262 } else {
1263 $keywords = array();
1265 $tome = false;
1266 $fromme = false;
1267 $courseid = 'none';
1269 if (empty($frm->keywordsoption)) {
1270 $frm->keywordsoption = 'allmine';
1273 switch ($frm->keywordsoption) {
1274 case 'tome':
1275 $tome = true;
1276 break;
1277 case 'fromme':
1278 $fromme = true;
1279 break;
1280 case 'allmine':
1281 $tome = true;
1282 $fromme = true;
1283 break;
1284 case 'allusers':
1285 $courseid = SITEID;
1286 break;
1287 case 'courseusers':
1288 $courseid = $frm->courseid;
1289 break;
1290 default:
1291 $tome = true;
1292 $fromme = true;
1295 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1297 // Get a list of contacts.
1298 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1299 $contacts = array();
1302 // Print heading with number of results.
1303 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1304 $countresults = count($messages);
1305 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1306 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1307 } else {
1308 echo get_string('keywordssearchresults', 'message', $countresults);
1310 echo html_writer::end_tag('p');
1312 // Print table headings.
1313 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1315 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1316 $headertdend = html_writer::end_tag('td');
1317 echo html_writer::start_tag('tr');
1318 echo $headertdstart.get_string('from').$headertdend;
1319 echo $headertdstart.get_string('to').$headertdend;
1320 echo $headertdstart.get_string('message', 'message').$headertdend;
1321 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1322 echo html_writer::end_tag('tr');
1324 $blockedcount = 0;
1325 $dateformat = get_string('strftimedatetimeshort');
1326 $strcontext = get_string('context', 'message');
1327 foreach ($messages as $message) {
1329 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1330 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1331 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1332 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1335 $blockedcount ++;
1336 continue;
1339 // Load user-to record.
1340 if ($message->useridto !== $USER->id) {
1341 $userto = core_user::get_user($message->useridto);
1342 $tocontact = (array_key_exists($message->useridto, $contacts) and
1343 ($contacts[$message->useridto]->blocked == 0) );
1344 $toblocked = (array_key_exists($message->useridto, $contacts) and
1345 ($contacts[$message->useridto]->blocked == 1) );
1346 } else {
1347 $userto = false;
1348 $tocontact = false;
1349 $toblocked = false;
1352 // Load user-from record.
1353 if ($message->useridfrom !== $USER->id) {
1354 $userfrom = core_user::get_user($message->useridfrom);
1355 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1356 ($contacts[$message->useridfrom]->blocked == 0) );
1357 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1358 ($contacts[$message->useridfrom]->blocked == 1) );
1359 } else {
1360 $userfrom = false;
1361 $fromcontact = false;
1362 $fromblocked = false;
1365 // Find date string for this message.
1366 $date = usergetdate($message->timecreated);
1367 $datestring = $date['year'].$date['mon'].$date['mday'];
1369 // Print out message row.
1370 echo html_writer::start_tag('tr', array('valign' => 'top'));
1372 echo html_writer::start_tag('td', array('class' => 'contact'));
1373 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1374 echo html_writer::end_tag('td');
1376 echo html_writer::start_tag('td', array('class' => 'contact'));
1377 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1378 echo html_writer::end_tag('td');
1380 echo html_writer::start_tag('td', array('class' => 'summary'));
1381 echo message_get_fragment($message->smallmessage, $keywords);
1382 echo html_writer::start_tag('div', array('class' => 'link'));
1384 // If the user clicks the context link display message sender on the left.
1385 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1386 $leftsideuserid = $rightsideuserid = null;
1387 if ($currentuser->id == $message->useridto) {
1388 $leftsideuserid = $message->useridto;
1389 $rightsideuserid = $message->useridfrom;
1390 } else {
1391 $leftsideuserid = $message->useridfrom;
1392 $rightsideuserid = $message->useridto;
1394 message_history_link($leftsideuserid, $rightsideuserid, false,
1395 $messagesearchstring, 'm'.$message->id, $strcontext);
1396 echo html_writer::end_tag('div');
1397 echo html_writer::end_tag('td');
1399 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1401 echo html_writer::end_tag('tr');
1405 if ($blockedcount > 0) {
1406 echo html_writer::start_tag('tr');
1407 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1408 echo html_writer::end_tag('tr');
1410 echo html_writer::end_tag('table');
1412 } else {
1413 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1417 if (!$personsearch && !$messagesearch) {
1418 //they didn't enter any search terms
1419 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1422 echo html_writer::end_tag('div');
1426 * Print information on a user. Used when printing search results.
1428 * @param object/bool $user the user to display or false if you just want $USER
1429 * @param bool $iscontact is the user being displayed a contact?
1430 * @param bool $isblocked is the user being displayed blocked?
1431 * @param bool $includeicontext include text next to the action icons?
1432 * @return void
1434 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1435 global $USER, $OUTPUT;
1437 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1439 if ($user === false) {
1440 echo $OUTPUT->user_picture($USER, $userpictureparams);
1441 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1442 $userpictureparams['link'] = false;
1443 echo $OUTPUT->user_picture($USER, $userpictureparams);
1444 echo fullname($user);
1445 } else {
1446 echo $OUTPUT->user_picture($user, $userpictureparams);
1448 $link = new moodle_url("/message/index.php?id=$user->id");
1449 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1450 get_string('sendmessageto', 'message', fullname($user))));
1452 $return = false;
1453 $script = null;
1454 if ($iscontact) {
1455 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1456 } else {
1457 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1460 if ($isblocked) {
1461 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1462 } else {
1463 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1469 * Print a message contact link
1471 * @param int $userid the ID of the user to apply to action to
1472 * @param string $linktype can be add, remove, block or unblock
1473 * @param bool $return if true return the link as a string. If false echo the link.
1474 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1475 * @param bool $text include text next to the icons?
1476 * @param bool $icon include a graphical icon?
1477 * @return string if $return is true otherwise bool
1479 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1480 global $OUTPUT, $PAGE;
1482 //hold onto the strings as we're probably creating a bunch of links
1483 static $str;
1485 if (empty($script)) {
1486 //strip off previous action params like 'removecontact'
1487 $script = message_remove_url_params($PAGE->url);
1490 if (empty($str->blockcontact)) {
1491 $str = new stdClass();
1492 $str->blockcontact = get_string('blockcontact', 'message');
1493 $str->unblockcontact = get_string('unblockcontact', 'message');
1494 $str->removecontact = get_string('removecontact', 'message');
1495 $str->addcontact = get_string('addcontact', 'message');
1498 $command = $linktype.'contact';
1499 $string = $str->{$command};
1501 $safealttext = s($string);
1503 $safestring = '';
1504 if (!empty($text)) {
1505 $safestring = $safealttext;
1508 $img = '';
1509 if ($icon) {
1510 $iconpath = null;
1511 switch ($linktype) {
1512 case 'block':
1513 $iconpath = 't/block';
1514 break;
1515 case 'unblock':
1516 $iconpath = 't/unblock';
1517 break;
1518 case 'remove':
1519 $iconpath = 't/removecontact';
1520 break;
1521 case 'add':
1522 default:
1523 $iconpath = 't/addcontact';
1526 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1529 $output = '<span class="'.$linktype.'contact">'.
1530 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1531 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1532 $img.
1533 $safestring.'</a></span>';
1535 if ($return) {
1536 return $output;
1537 } else {
1538 echo $output;
1539 return true;
1544 * echo or return a link to take the user to the full message history between themselves and another user
1546 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1547 * @param int $userid2 the ID of the other user
1548 * @param bool $return true to return the link as a string. False to echo the link.
1549 * @param string $keywords any keywords to highlight in the message history
1550 * @param string $position anchor name to jump to within the message history
1551 * @param string $linktext optionally specify the link text
1552 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1554 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1555 global $OUTPUT, $PAGE;
1556 static $strmessagehistory;
1558 if (empty($strmessagehistory)) {
1559 $strmessagehistory = get_string('messagehistory', 'message');
1562 if ($position) {
1563 $position = "#$position";
1565 if ($keywords) {
1566 $keywords = "&search=".urlencode($keywords);
1569 if ($linktext == 'icon') { // Icon only
1570 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1571 } else if ($linktext == 'both') { // Icon and standard name
1572 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1573 $fulllink .= '&nbsp;'.$strmessagehistory;
1574 } else if ($linktext) { // Custom name
1575 $fulllink = $linktext;
1576 } else { // Standard name only
1577 $fulllink = $strmessagehistory;
1580 $popupoptions = array(
1581 'height' => 500,
1582 'width' => 500,
1583 'menubar' => false,
1584 'location' => false,
1585 'status' => true,
1586 'scrollbars' => true,
1587 'resizable' => true);
1589 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1590 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1591 $link->param('viewing', $PAGE->url->get_param('viewing'));
1593 $action = null;
1594 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1596 $str = '<span class="history">'.$str.'</span>';
1598 if ($return) {
1599 return $str;
1600 } else {
1601 echo $str;
1602 return true;
1608 * Search through course users.
1610 * If $courseids contains the site course then this function searches
1611 * through all undeleted and confirmed users.
1613 * @param int|array $courseids Course ID or array of course IDs.
1614 * @param string $searchtext the text to search for.
1615 * @param string $sort the column name to order by.
1616 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1617 * @return array An array of {@link $USER} records.
1619 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1620 global $CFG, $USER, $DB;
1622 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1623 if (!$courseids) {
1624 $courseids = array(SITEID);
1627 // Allow an integer to be passed.
1628 if (!is_array($courseids)) {
1629 $courseids = array($courseids);
1632 $fullname = $DB->sql_fullname();
1633 $ufields = user_picture::fields('u');
1635 if (!empty($sort)) {
1636 $order = ' ORDER BY '. $sort;
1637 } else {
1638 $order = '';
1641 $params = array(
1642 'userid' => $USER->id,
1643 'query' => "%$searchtext%"
1646 if (empty($exceptions)) {
1647 $exceptions = array();
1648 } else if (!empty($exceptions) && is_string($exceptions)) {
1649 $exceptions = explode(',', $exceptions);
1652 // Ignore self and guest account.
1653 $exceptions[] = $USER->id;
1654 $exceptions[] = $CFG->siteguest;
1656 // Exclude exceptions from the search result.
1657 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1658 $except = ' AND u.id ' . $except;
1659 $params = array_merge($params_except, $params);
1661 if (in_array(SITEID, $courseids)) {
1662 // Search on site level.
1663 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1664 FROM {user} u
1665 LEFT JOIN {message_contacts} mc
1666 ON mc.contactid = u.id AND mc.userid = :userid
1667 WHERE u.deleted = '0' AND u.confirmed = '1'
1668 AND (".$DB->sql_like($fullname, ':query', false).")
1669 $except
1670 $order", $params);
1671 } else {
1672 // Search in courses.
1674 // Getting the context IDs or each course.
1675 $contextids = array();
1676 foreach ($courseids as $courseid) {
1677 $context = context_course::instance($courseid);
1678 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1680 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1681 $params = array_merge($params, $contextparams);
1683 // Everyone who has a role assignment in this course or higher.
1684 // TODO: add enabled enrolment join here (skodak)
1685 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1686 FROM {user} u
1687 JOIN {role_assignments} ra ON ra.userid = u.id
1688 LEFT JOIN {message_contacts} mc
1689 ON mc.contactid = u.id AND mc.userid = :userid
1690 WHERE u.deleted = '0' AND u.confirmed = '1'
1691 AND (".$DB->sql_like($fullname, ':query', false).")
1692 AND ra.contextid $contextwhere
1693 $except
1694 $order", $params);
1696 return $users;
1701 * Search a user's messages
1703 * Returns a list of posts found using an array of search terms
1704 * eg word +word -word
1706 * @param array $searchterms an array of search terms (strings)
1707 * @param bool $fromme include messages from the user?
1708 * @param bool $tome include messages to the user?
1709 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1710 * @param int $userid the user ID of the current user
1711 * @return mixed An array of messages or false if no matching messages were found
1713 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1714 global $CFG, $USER, $DB;
1716 // If user is searching all messages check they are allowed to before doing anything else.
1717 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1718 print_error('accessdenied','admin');
1721 // If no userid sent then assume current user.
1722 if ($userid == 0) $userid = $USER->id;
1724 // Some differences in SQL syntax.
1725 if ($DB->sql_regex_supported()) {
1726 $REGEXP = $DB->sql_regex(true);
1727 $NOTREGEXP = $DB->sql_regex(false);
1730 $searchcond = array();
1731 $params = array();
1732 $i = 0;
1734 // Preprocess search terms to check whether we have at least 1 eligible search term.
1735 // If we do we can drop words around it like 'a'.
1736 $dropshortwords = false;
1737 foreach ($searchterms as $searchterm) {
1738 if (strlen($searchterm) >= 2) {
1739 $dropshortwords = true;
1743 foreach ($searchterms as $searchterm) {
1744 $i++;
1746 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1748 if ($dropshortwords && strlen($searchterm) < 2) {
1749 continue;
1751 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1752 if (!$DB->sql_regex_supported()) {
1753 if (substr($searchterm, 0, 1) == '-') {
1754 $NOT = true;
1756 $searchterm = trim($searchterm, '+-');
1759 if (substr($searchterm,0,1) == "+") {
1760 $searchterm = substr($searchterm,1);
1761 $searchterm = preg_quote($searchterm, '|');
1762 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1763 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1765 } else if (substr($searchterm,0,1) == "-") {
1766 $searchterm = substr($searchterm,1);
1767 $searchterm = preg_quote($searchterm, '|');
1768 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1769 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1771 } else {
1772 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1773 $params['ss'.$i] = "%$searchterm%";
1777 if (empty($searchcond)) {
1778 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1779 $params['ss1'] = "%";
1780 } else {
1781 $searchcond = implode(" AND ", $searchcond);
1784 // There are several possibilities
1785 // 1. courseid = SITEID : The admin is searching messages by all users
1786 // 2. courseid = ?? : A teacher is searching messages by users in
1787 // one of their courses - currently disabled
1788 // 3. courseid = none : User is searching their own messages;
1789 // a. Messages from user
1790 // b. Messages to user
1791 // c. Messages to and from user
1793 if ($courseid == SITEID) { // Admin is searching all messages.
1794 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1795 FROM {message_read} m
1796 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1797 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1798 FROM {message} m
1799 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1801 } else if ($courseid !== 'none') {
1802 // This has not been implemented due to security concerns.
1803 $m_read = array();
1804 $m_unread = array();
1806 } else {
1808 if ($fromme and $tome) {
1809 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1810 $params['userid1'] = $userid;
1811 $params['userid2'] = $userid;
1813 } else if ($fromme) {
1814 $searchcond .= " AND m.useridfrom=:userid";
1815 $params['userid'] = $userid;
1817 } else if ($tome) {
1818 $searchcond .= " AND m.useridto=:userid";
1819 $params['userid'] = $userid;
1822 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1823 FROM {message_read} m
1824 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1825 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1826 FROM {message} m
1827 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1831 /// The keys may be duplicated in $m_read and $m_unread so we can't
1832 /// do a simple concatenation
1833 $messages = array();
1834 foreach ($m_read as $m) {
1835 $messages[] = $m;
1837 foreach ($m_unread as $m) {
1838 $messages[] = $m;
1841 return (empty($messages)) ? false : $messages;
1845 * Given a message object that we already know has a long message
1846 * this function truncates the message nicely to the first
1847 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1849 * @param string $message the message
1850 * @param int $minlength the minimum length to trim the message to
1851 * @return string the shortened message
1853 function message_shorten_message($message, $minlength = 0) {
1854 $i = 0;
1855 $tag = false;
1856 $length = strlen($message);
1857 $count = 0;
1858 $stopzone = false;
1859 $truncate = 0;
1860 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1863 for ($i=0; $i<$length; $i++) {
1864 $char = $message[$i];
1866 switch ($char) {
1867 case "<":
1868 $tag = true;
1869 break;
1870 case ">":
1871 $tag = false;
1872 break;
1873 default:
1874 if (!$tag) {
1875 if ($stopzone) {
1876 if ($char == '.' or $char == ' ') {
1877 $truncate = $i+1;
1878 break 2;
1881 $count++;
1883 break;
1885 if (!$stopzone) {
1886 if ($count > $minlength) {
1887 $stopzone = true;
1892 if (!$truncate) {
1893 $truncate = $i;
1896 return substr($message, 0, $truncate);
1901 * Given a string and an array of keywords, this function looks
1902 * for the first keyword in the string, and then chops out a
1903 * small section from the text that shows that word in context.
1905 * @param string $message the text to search
1906 * @param array $keywords array of keywords to find
1908 function message_get_fragment($message, $keywords) {
1910 $fullsize = 160;
1911 $halfsize = (int)($fullsize/2);
1913 $message = strip_tags($message);
1915 foreach ($keywords as $keyword) { // Just get the first one
1916 if ($keyword !== '') {
1917 break;
1920 if (empty($keyword)) { // None found, so just return start of message
1921 return message_shorten_message($message, 30);
1924 $leadin = $leadout = '';
1926 /// Find the start of the fragment
1927 $start = 0;
1928 $length = strlen($message);
1930 $pos = strpos($message, $keyword);
1931 if ($pos > $halfsize) {
1932 $start = $pos - $halfsize;
1933 $leadin = '...';
1935 /// Find the end of the fragment
1936 $end = $start + $fullsize;
1937 if ($end > $length) {
1938 $end = $length;
1939 } else {
1940 $leadout = '...';
1943 /// Pull out the fragment and format it
1945 $fragment = substr($message, $start, $end - $start);
1946 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1947 return $fragment;
1951 * Retrieve the messages between two users
1953 * @param object $user1 the current user
1954 * @param object $user2 the other user
1955 * @param int $limitnum the maximum number of messages to retrieve
1956 * @param bool $viewingnewmessages are we currently viewing new messages?
1958 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1959 global $DB, $CFG;
1961 $messages = array();
1963 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1964 //desc to get the last $limitnum messages then flip the order in php
1965 $sort = 'asc';
1966 if ($limitnum>0) {
1967 $sort = 'desc';
1970 $notificationswhere = null;
1971 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1972 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1973 $notificationswhere = 'AND notification=0';
1976 //prevent notifications of your own actions appearing in your own message history
1977 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1979 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1980 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1981 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1982 "timecreated $sort", '*', 0, $limitnum)) {
1983 foreach ($messages_read as $message) {
1984 $messages[] = $message;
1987 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1988 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1989 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1990 "timecreated $sort", '*', 0, $limitnum)) {
1991 foreach ($messages_new as $message) {
1992 $messages[] = $message;
1996 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
1998 //if we only want the last $limitnum messages
1999 $messagecount = count($messages);
2000 if ($limitnum > 0 && $messagecount > $limitnum) {
2001 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
2004 return $messages;
2008 * Print the message history between two users
2010 * @param object $user1 the current user
2011 * @param object $user2 the other user
2012 * @param string $search search terms to highlight
2013 * @param int $messagelimit maximum number of messages to return
2014 * @param string $messagehistorylink the html for the message history link or false
2015 * @param bool $viewingnewmessages are we currently viewing new messages?
2017 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
2018 global $CFG, $OUTPUT;
2020 echo $OUTPUT->box_start('center', 'message_user_pictures');
2021 echo $OUTPUT->box_start('user');
2022 echo $OUTPUT->box_start('generalbox', 'user1');
2023 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2024 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
2025 echo $OUTPUT->box_end();
2026 echo $OUTPUT->box_end();
2028 $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16);
2029 echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between');
2031 echo $OUTPUT->box_start('user');
2032 echo $OUTPUT->box_start('generalbox', 'user2');
2033 // Show user picture with link is real user else without link.
2034 if (core_user::is_real_user($user2->id)) {
2035 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2036 } else {
2037 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2039 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2041 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2043 $script = null;
2044 $text = true;
2045 $icon = false;
2047 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2048 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2049 $useractionlinks = $strcontact.'&nbsp;|&nbsp;'.$strblock;
2051 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2053 echo $OUTPUT->box_end();
2054 echo $OUTPUT->box_end();
2055 echo $OUTPUT->box_end();
2057 if (!empty($messagehistorylink)) {
2058 echo $messagehistorylink;
2061 /// Get all the messages and print them
2062 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2063 $tablecontents = '';
2065 $current = new stdClass();
2066 $current->mday = '';
2067 $current->month = '';
2068 $current->year = '';
2069 $messagedate = get_string('strftimetime');
2070 $blockdate = get_string('strftimedaydate');
2071 foreach ($messages as $message) {
2072 if ($message->notification) {
2073 $notificationclass = ' notification';
2074 } else {
2075 $notificationclass = null;
2077 $date = usergetdate($message->timecreated);
2078 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2079 $current->mday = $date['mday'];
2080 $current->month = $date['month'];
2081 $current->year = $date['year'];
2083 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2084 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2086 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2089 $formatted_message = $side = null;
2090 if ($message->useridfrom == $user1->id) {
2091 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2092 $side = 'left';
2093 } else {
2094 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2095 $side = 'right';
2097 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2100 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2101 } else {
2102 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2107 * Format a message for display in the message history
2109 * @param object $message the message object
2110 * @param string $format optional date format
2111 * @param string $keywords keywords to highlight
2112 * @param string $class CSS class to apply to the div around the message
2113 * @return string the formatted message
2115 function message_format_message($message, $format='', $keywords='', $class='other') {
2117 static $dateformat;
2119 //if we haven't previously set the date format or they've supplied a new one
2120 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2121 if ($format) {
2122 $dateformat = $format;
2123 } else {
2124 $dateformat = get_string('strftimedatetimeshort');
2127 $time = userdate($message->timecreated, $dateformat);
2129 $messagetext = message_format_message_text($message, false);
2131 if ($keywords) {
2132 $messagetext = highlight($keywords, $messagetext);
2135 $messagetext .= message_format_contexturl($message);
2137 $messagetext = clean_text($messagetext, FORMAT_HTML);
2139 return <<<TEMPLATE
2140 <div class='message $class'>
2141 <a name="m{$message->id}"></a>
2142 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2143 </div>
2144 TEMPLATE;
2148 * Format a the context url and context url name of a message for display
2150 * @param object $message the message object
2151 * @return string the formatted string
2153 function message_format_contexturl($message) {
2154 $s = null;
2156 if (!empty($message->contexturl)) {
2157 $displaytext = null;
2158 if (!empty($message->contexturlname)) {
2159 $displaytext= $message->contexturlname;
2160 } else {
2161 $displaytext= $message->contexturl;
2163 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2164 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2165 $s .= html_writer::end_tag('div');
2168 return $s;
2172 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2174 * @param object $userfrom the message sender
2175 * @param object $userto the message recipient
2176 * @param string $message the message
2177 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2178 * @return int|false the ID of the new message or false
2180 function message_post_message($userfrom, $userto, $message, $format) {
2181 global $SITE, $CFG, $USER;
2183 $eventdata = new stdClass();
2184 $eventdata->component = 'moodle';
2185 $eventdata->name = 'instantmessage';
2186 $eventdata->userfrom = $userfrom;
2187 $eventdata->userto = $userto;
2189 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2190 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2192 if ($format == FORMAT_HTML) {
2193 $eventdata->fullmessagehtml = $message;
2194 //some message processors may revert to sending plain text even if html is supplied
2195 //so we keep both plain and html versions if we're intending to send html
2196 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2197 } else {
2198 $eventdata->fullmessage = $message;
2199 $eventdata->fullmessagehtml = '';
2202 $eventdata->fullmessageformat = $format;
2203 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2205 $s = new stdClass();
2206 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2207 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2209 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2210 if (!empty($eventdata->fullmessage)) {
2211 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2213 if (!empty($eventdata->fullmessagehtml)) {
2214 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2217 $eventdata->timecreated = time();
2218 $eventdata->notification = 0;
2219 return message_send($eventdata);
2223 * Print a row of contactlist displaying user picture, messages waiting and
2224 * block links etc
2226 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2227 * @param bool $incontactlist is the user a contact of ours?
2228 * @param bool $isblocked is the user blocked?
2229 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2230 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2231 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2232 * @return void
2234 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2235 global $OUTPUT, $USER, $COURSE;
2236 $fullname = fullname($contact);
2237 $fullnamelink = $fullname;
2238 $output = '';
2240 $linkclass = '';
2241 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2242 $linkclass = 'messageselecteduser';
2245 // Are there any unread messages for this contact?
2246 if ($contact->messagecount > 0 ){
2247 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2250 $strcontact = $strblock = $strhistory = null;
2252 if ($showactionlinks) {
2253 // Show block and delete links if user is real user.
2254 if (core_user::is_real_user($contact->id)) {
2255 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2256 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2258 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2261 $output .= html_writer::start_tag('div', array('class' => 'pix'));
2262 $output .= $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2263 $output .= html_writer::end_tag('div');
2265 $popupoptions = array(
2266 'height' => MESSAGE_DISCUSSION_HEIGHT,
2267 'width' => MESSAGE_DISCUSSION_WIDTH,
2268 'menubar' => false,
2269 'location' => false,
2270 'status' => true,
2271 'scrollbars' => true,
2272 'resizable' => true);
2274 $link = $action = null;
2275 if (!empty($selectcontacturl)) {
2276 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2277 } else {
2278 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2279 $link = new moodle_url("/message/index.php?id=$contact->id");
2280 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2284 if (strlen($strcontact . $strblock . $strhistory) > 0) {
2285 $output .= html_writer::tag('div', $strcontact . $strblock . $strhistory, array('class' => 'link'));
2287 $output .= html_writer::start_tag('div', array('class' => 'contact'));
2288 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2289 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2290 $output .= html_writer::end_tag('div');
2291 } else {
2292 $output .= html_writer::start_tag('div', array('class' => 'contact nolinks'));
2293 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2294 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2295 $output .= html_writer::end_tag('div');
2298 return $output;
2302 * Constructs the add/remove contact link to display next to other users
2304 * @param bool $incontactlist is the user a contact
2305 * @param bool $isblocked is the user blocked
2306 * @param stdClass $contact contact object
2307 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2308 * @param bool $text include text next to the icons?
2309 * @param bool $icon include a graphical icon?
2310 * @return string
2312 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2313 $strcontact = '';
2315 if($incontactlist){
2316 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2317 } else if ($isblocked) {
2318 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2319 } else{
2320 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2323 return $strcontact;
2327 * Constructs the block contact link to display next to other users
2329 * @param bool $incontactlist is the user a contact?
2330 * @param bool $isblocked is the user blocked?
2331 * @param stdClass $contact contact object
2332 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2333 * @param bool $text include text next to the icons?
2334 * @param bool $icon include a graphical icon?
2335 * @return string
2337 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2338 $strblock = '';
2340 //commented out to allow the user to block a contact without having to remove them first
2341 /*if ($incontactlist) {
2342 //$strblock = '';
2343 } else*/
2344 if ($isblocked) {
2345 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2346 } else{
2347 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2350 return $strblock;
2354 * Moves messages from a particular user from the message table (unread messages) to message_read
2355 * This is typically only used when a user is deleted
2357 * @param object $userid User id
2358 * @return boolean success
2360 function message_move_userfrom_unread2read($userid) {
2361 global $DB;
2363 // move all unread messages from message table to message_read
2364 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2365 foreach ($messages as $message) {
2366 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2369 return true;
2373 * marks ALL messages being sent from $fromuserid to $touserid as read
2375 * @param int $touserid the id of the message recipient
2376 * @param int $fromuserid the id of the message sender
2377 * @return void
2379 function message_mark_messages_read($touserid, $fromuserid) {
2380 global $DB;
2382 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2383 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2385 foreach ($messages as $message) {
2386 message_mark_message_read($message, time());
2389 $messages->close();
2393 * Mark a single message as read
2395 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2396 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2397 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2398 * @return int the ID of the message in the message_read table
2400 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2401 global $DB;
2403 $message->timeread = $timeread;
2405 $messageid = $message->id;
2406 unset($message->id);//unset because it will get a new id on insert into message_read
2408 //If any processors have pending actions abort them
2409 if (!$messageworkingempty) {
2410 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2412 $messagereadid = $DB->insert_record('message_read', $message);
2414 $DB->delete_records('message', array('id' => $messageid));
2416 // Get the context for the user who received the message.
2417 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2418 // If the user no longer exists the context value will be false, in this case use the system context.
2419 if ($context === false) {
2420 $context = context_system::instance();
2423 // Trigger event for reading a message.
2424 $event = \core\event\message_viewed::create(array(
2425 'objectid' => $messagereadid,
2426 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2427 'context' => $context,
2428 'relateduserid' => $message->useridfrom,
2429 'other' => array(
2430 'messageid' => $messageid
2433 $event->trigger();
2435 return $messagereadid;
2439 * Get all message processors, validate corresponding plugin existance and
2440 * system configuration
2442 * @param bool $ready only return ready-to-use processors
2443 * @param bool $reset Reset list of message processors (used in unit tests)
2444 * @return mixed $processors array of objects containing information on message processors
2446 function get_message_processors($ready = false, $reset = false) {
2447 global $DB, $CFG;
2449 static $processors;
2450 if ($reset) {
2451 $processors = array();
2454 if (empty($processors)) {
2455 // Get all processors, ensure the name column is the first so it will be the array key
2456 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2457 foreach ($processors as &$processor){
2458 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2459 if (is_readable($processorfile)) {
2460 include_once($processorfile);
2461 $processclass = 'message_output_' . $processor->name;
2462 if (class_exists($processclass)) {
2463 $pclass = new $processclass();
2464 $processor->object = $pclass;
2465 $processor->configured = 0;
2466 if ($pclass->is_system_configured()) {
2467 $processor->configured = 1;
2469 $processor->hassettings = 0;
2470 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2471 $processor->hassettings = 1;
2473 $processor->available = 1;
2474 } else {
2475 print_error('errorcallingprocessor', 'message');
2477 } else {
2478 $processor->available = 0;
2482 if ($ready) {
2483 // Filter out enabled and system_configured processors
2484 $readyprocessors = $processors;
2485 foreach ($readyprocessors as $readyprocessor) {
2486 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2487 unset($readyprocessors[$readyprocessor->name]);
2490 return $readyprocessors;
2493 return $processors;
2497 * Get all message providers, validate their plugin existance and
2498 * system configuration
2500 * @return mixed $processors array of objects containing information on message processors
2502 function get_message_providers() {
2503 global $CFG, $DB;
2505 $pluginman = core_plugin_manager::instance();
2507 $providers = $DB->get_records('message_providers', null, 'name');
2509 // Remove all the providers whose plugins are disabled or don't exist
2510 foreach ($providers as $providerid => $provider) {
2511 $plugin = $pluginman->get_plugin_info($provider->component);
2512 if ($plugin) {
2513 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2514 unset($providers[$providerid]); // Plugins does not exist
2515 continue;
2517 if ($plugin->is_enabled() === false) {
2518 unset($providers[$providerid]); // Plugin disabled
2519 continue;
2523 return $providers;
2527 * Get an instance of the message_output class for one of the output plugins.
2528 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2529 * @return message_output message_output the requested class.
2531 function get_message_processor($type) {
2532 global $CFG;
2534 // Note, we cannot use the get_message_processors function here, becaues this
2535 // code is called during install after installing each messaging plugin, and
2536 // get_message_processors caches the list of installed plugins.
2538 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2539 if (!is_readable($processorfile)) {
2540 throw new coding_exception('Unknown message processor type ' . $type);
2543 include_once($processorfile);
2545 $processclass = 'message_output_' . $type;
2546 if (!class_exists($processclass)) {
2547 throw new coding_exception('Message processor ' . $type .
2548 ' does not define the right class');
2551 return new $processclass();
2555 * Get messaging outputs default (site) preferences
2557 * @return object $processors object containing information on message processors
2559 function get_message_output_default_preferences() {
2560 return get_config('message');
2564 * Translate message default settings from binary value to the array of string
2565 * representing the settings to be stored. Also validate the provided value and
2566 * use default if it is malformed.
2568 * @param int $plugindefault Default setting suggested by plugin
2569 * @param string $processorname The name of processor
2570 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2572 function translate_message_default_setting($plugindefault, $processorname) {
2573 // Preset translation arrays
2574 $permittedvalues = array(
2575 0x04 => 'disallowed',
2576 0x08 => 'permitted',
2577 0x0c => 'forced',
2580 $loggedinstatusvalues = array(
2581 0x00 => null, // use null if loggedin/loggedoff is not defined
2582 0x01 => 'loggedin',
2583 0x02 => 'loggedoff',
2586 // define the default setting
2587 $processor = get_message_processor($processorname);
2588 $default = $processor->get_default_messaging_settings();
2590 // Validate the value. It should not exceed the maximum size
2591 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2592 debugging(get_string('errortranslatingdefault', 'message'));
2593 $plugindefault = $default;
2595 // Use plugin default setting of 'permitted' is 0
2596 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2597 $plugindefault = $default;
2600 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2601 $loggedin = $loggedoff = null;
2603 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2604 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2605 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2608 return array($permitted, $loggedin, $loggedoff);
2612 * Return a list of page types
2613 * @param string $pagetype current page type
2614 * @param stdClass $parentcontext Block's parent context
2615 * @param stdClass $currentcontext Current context of block
2617 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2618 return array('messages-*'=>get_string('page-message-x', 'message'));
2622 * Get messages sent or/and received by the specified users.
2624 * @param int $useridto the user id who received the message
2625 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
2626 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
2627 * @param bool $read true for retrieving read messages, false for unread
2628 * @param string $sort the column name to order by including optionally direction
2629 * @param int $limitfrom limit from
2630 * @param int $limitnum limit num
2631 * @return external_description
2632 * @since 2.8
2634 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
2635 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
2636 global $DB;
2638 $messagetable = $read ? '{message_read}' : '{message}';
2639 $params = array('deleted' => 0);
2641 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
2642 if (empty($useridto)) {
2643 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
2644 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
2645 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
2646 $params['useridfrom'] = $useridfrom;
2647 } else {
2648 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
2649 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
2650 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
2651 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
2652 $params['useridto'] = $useridto;
2653 if (!empty($useridfrom)) {
2654 $usersql .= " AND mr.useridfrom = :useridfrom";
2655 $params['useridfrom'] = $useridfrom;
2659 // Now, if retrieve notifications, conversations or both.
2660 $typesql = "";
2661 if ($notifications !== -1) {
2662 $typesql = "AND mr.notification = :notification";
2663 $params['notification'] = ($notifications) ? 1 : 0;
2666 $sql = "SELECT mr.*, $userfields
2667 FROM $messagetable mr
2668 $joinsql
2669 WHERE $usersql
2670 $typesql
2671 ORDER BY $sort";
2673 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2674 return $messages;
2678 * Requires the JS libraries to send a message using a dialog.
2680 * @return void
2682 function message_messenger_requirejs() {
2683 global $PAGE;
2685 static $done = false;
2686 if ($done) {
2687 return;
2690 $PAGE->requires->yui_module(
2691 array('moodle-core_message-messenger'),
2692 'Y.M.core_message.messenger.init',
2693 array(array())
2695 $PAGE->requires->strings_for_js(array(
2696 'errorwhilesendingmessage',
2697 'messagesent',
2698 'messagetosend',
2699 'sendingmessage',
2700 'sendmessage',
2701 'viewconversation',
2702 ), 'core_message');
2703 $PAGE->requires->string_for_js('error', 'core');
2705 $done = true;
2709 * Returns the attributes to place on a link to open the 'Send message' dialog.
2711 * @param object $user User object.
2712 * @return void
2714 function message_messenger_sendmessage_link_params($user) {
2715 return array(
2716 'data-trigger' => 'core_message-messenger::sendmessage',
2717 'data-fullname' => fullname($user),
2718 'data-userid' => $user->id,
2719 'role' => 'button'