2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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);
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
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 //TODO: defaults must be initialised via settings - this is a bad hack! (skodak)
75 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
76 $CFG->message_contacts_refresh = 60;
78 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
79 $CFG->message_chat_refresh = 5;
81 if (!isset($CFG->message_offline_time)) {
82 $CFG->message_offline_time = 300;
86 * Print the selector that allows the user to view their contacts, course participants, their recent
89 * @param int $countunreadtotal how many unread messages does the user have?
90 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
91 * @param object $user1 the user whose messages are being viewed
92 * @param object $user2 the user $user1 is talking to
93 * @param array $blockedusers an array of users blocked by $user1
94 * @param array $onlinecontacts an array of $user1's online contacts
95 * @param array $offlinecontacts an array of $user1's offline contacts
96 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
97 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
98 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
101 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
104 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
106 //if 0 unread messages and they've requested unread messages then show contacts
107 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
108 $viewing = MESSAGE_VIEW_CONTACTS;
111 //if they have no blocked users and they've requested blocked users switch them over to contacts
112 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
113 $viewing = MESSAGE_VIEW_CONTACTS;
116 $onlyactivecourses = true;
117 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
118 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
120 $strunreadmessages = null;
121 if ($countunreadtotal>0) { //if there are unread messages
122 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
125 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
127 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
128 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
129 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
130 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
131 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
132 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
133 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
134 $courseidtoshow = intval(substr($viewing, 7));
136 if (!empty($courseidtoshow)
137 && array_key_exists($courseidtoshow, $coursecontexts)
138 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
140 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
142 //shouldn't get here. User trying to access a course they're not in perhaps.
143 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
147 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
148 echo html_writer::start_tag('fieldset');
149 $managebuttonclass = 'visible';
150 if ($viewing == MESSAGE_VIEW_SEARCH) {
151 $managebuttonclass = 'hiddenelement';
153 $strmanagecontacts = get_string('search','message');
154 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
155 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
156 echo html_writer::end_tag('fieldset');
157 echo html_writer::end_tag('form');
159 echo html_writer::end_tag('div');
163 * Print course participants. Called by message_print_contact_selector()
165 * @param object $context the course context
166 * @param int $courseid the course ID
167 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
168 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
169 * @param string $titletodisplay Optionally specify a title to display above the participants
170 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
171 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
174 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
175 global $DB, $USER, $PAGE, $OUTPUT;
177 if (empty($titletodisplay)) {
178 $titletodisplay = get_string('participants');
181 $countparticipants = count_enrolled_users($context);
182 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
184 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
185 echo $OUTPUT->render($pagingbar);
187 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
189 echo html_writer::start_tag('tr');
190 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
191 echo html_writer::end_tag('tr');
193 //todo these need to come from somewhere if the course participants list is to show users with unread messages
196 foreach ($participants as $participant) {
197 if ($participant->id != $USER->id) {
198 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
199 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
203 echo html_writer::end_tag('table');
207 * Retrieve users blocked by $user1
209 * @param object $user1 the user whose messages are being viewed
210 * @param object $user2 the user $user1 is talking to. If they are being blocked
211 * they will have a variable called 'isblocked' added to their user object
212 * @return array the users blocked by $user1
214 function message_get_blocked_users($user1=null, $user2=null) {
221 if (!empty($user2)) {
222 $user2->isblocked = false;
225 $blockedusers = array();
227 $userfields = user_picture::fields('u', array('lastaccess'));
228 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
229 FROM {message_contacts} mc
230 JOIN {user} u ON u.id = mc.contactid
231 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
232 WHERE mc.userid = :user1id2 AND mc.blocked = 1
234 ORDER BY u.firstname ASC";
235 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
237 foreach($rs as $rd) {
238 $blockedusers[] = $rd;
240 if (!empty($user2) && $user2->id == $rd->id) {
241 $user2->isblocked = true;
246 return $blockedusers;
250 * Print users blocked by $user1. Called by message_print_contact_selector()
252 * @param array $blockedusers the users blocked by $user1
253 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
254 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
255 * @param string $titletodisplay Optionally specify a title to display above the participants
256 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
259 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
262 $countblocked = count($blockedusers);
264 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
266 if (!empty($titletodisplay)) {
267 echo html_writer::start_tag('tr');
268 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
269 echo html_writer::end_tag('tr');
273 echo html_writer::start_tag('tr');
274 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
275 echo html_writer::end_tag('tr');
277 $isuserblocked = true;
278 $isusercontact = false;
279 foreach ($blockedusers as $blockeduser) {
280 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
284 echo html_writer::end_tag('table');
288 * Retrieve $user1's contacts (online, offline and strangers)
290 * @param object $user1 the user whose messages are being viewed
291 * @param object $user2 the user $user1 is talking to. If they are a contact
292 * they will have a variable called 'iscontact' added to their user object
293 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
295 function message_get_contacts($user1=null, $user2=null) {
296 global $DB, $CFG, $USER;
302 if (!empty($user2)) {
303 $user2->iscontact = false;
306 $timetoshowusers = 300; //Seconds default
307 if (isset($CFG->block_online_users_timetosee)) {
308 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
311 // time which a user is counting as being active since
312 $timefrom = time()-$timetoshowusers;
314 // people in our contactlist who are online
315 $onlinecontacts = array();
316 // people in our contactlist who are offline
317 $offlinecontacts = array();
318 // people who are not in our contactlist but have sent us a message
319 $strangers = array();
321 $userfields = user_picture::fields('u', array('lastaccess'));
323 // get all in our contactlist who are not blocked in our contact list
324 // and count messages we have waiting from each of them
325 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
326 FROM {message_contacts} mc
327 JOIN {user} u ON u.id = mc.contactid
328 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
329 WHERE mc.userid = ? AND mc.blocked = 0
331 ORDER BY u.firstname ASC";
333 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
334 foreach ($rs as $rd) {
335 if ($rd->lastaccess >= $timefrom) {
336 // they have been active recently, so are counted online
337 $onlinecontacts[] = $rd;
340 $offlinecontacts[] = $rd;
343 if (!empty($user2) && $user2->id == $rd->id) {
344 $user2->iscontact = true;
349 // get messages from anyone who isn't in our contact list and count the number
350 // of messages we have from each of them
351 $strangersql = "SELECT $userfields, count(m.id) as messagecount
353 JOIN {user} u ON u.id = m.useridfrom
354 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
355 WHERE mc.id IS NULL AND m.useridto = ?
357 ORDER BY u.firstname ASC";
359 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
360 foreach ($rs as $rd) {
365 return array($onlinecontacts, $offlinecontacts, $strangers);
369 * Print $user1's contacts. Called by message_print_contact_selector()
371 * @param array $onlinecontacts $user1's contacts which are online
372 * @param array $offlinecontacts $user1's contacts which are offline
373 * @param array $strangers users which are not contacts but who have messaged $user1
374 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
375 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
376 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
377 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
378 * @param string $titletodisplay Optionally specify a title to display above the participants
379 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
382 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
383 global $CFG, $PAGE, $OUTPUT;
385 $countonlinecontacts = count($onlinecontacts);
386 $countofflinecontacts = count($offlinecontacts);
387 $countstrangers = count($strangers);
388 $isuserblocked = null;
390 if ($countonlinecontacts + $countofflinecontacts == 0) {
391 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
394 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
396 if (!empty($titletodisplay)) {
397 message_print_heading($titletodisplay);
400 if($countonlinecontacts) {
401 /// print out list of online contacts
403 if (empty($titletodisplay)) {
404 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
407 $isuserblocked = false;
408 $isusercontact = true;
409 foreach ($onlinecontacts as $contact) {
410 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
411 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
416 if ($countofflinecontacts) {
417 /// print out list of offline contacts
419 if (empty($titletodisplay)) {
420 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
423 $isuserblocked = false;
424 $isusercontact = true;
425 foreach ($offlinecontacts as $contact) {
426 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
427 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
433 /// print out list of incoming contacts
434 if ($countstrangers) {
435 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
437 $isuserblocked = false;
438 $isusercontact = false;
439 foreach ($strangers as $stranger) {
440 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
441 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
446 echo html_writer::end_tag('table');
448 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
449 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
454 * Print a select box allowing the user to choose to view new messages, course participants etc.
456 * Called by message_print_contact_selector()
457 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
458 * @param array $courses array of course objects. The courses the user is enrolled in.
459 * @param array $coursecontexts array of course contexts. Keyed on course id.
460 * @param int $countunreadtotal how many unread messages does the user have?
461 * @param int $countblocked how many users has the current user blocked?
462 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
465 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
468 if ($countunreadtotal>0) { //if there are unread messages
469 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
472 $str = get_string('mycontacts', 'message');
473 $options[MESSAGE_VIEW_CONTACTS] = $str;
475 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
476 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
478 if (!empty($courses)) {
479 $courses_options = array();
481 foreach($courses as $course) {
482 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
483 //Not using short_text() as we want the end of the course name. Not the beginning.
484 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
485 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
486 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
488 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
493 if (!empty($courses_options)) {
494 $options[] = array(get_string('courses') => $courses_options);
498 if ($countblocked>0) {
499 $str = get_string('blockedusers','message', $countblocked);
500 $options[MESSAGE_VIEW_BLOCKED] = $str;
503 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
504 echo html_writer::start_tag('fieldset');
505 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
506 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
507 echo html_writer::end_tag('fieldset');
508 echo html_writer::end_tag('form');
512 * Load the course contexts for all of the users courses
514 * @param array $courses array of course objects. The courses the user is enrolled in.
515 * @return array of course contexts
517 function message_get_course_contexts($courses) {
518 $coursecontexts = array();
520 foreach($courses as $course) {
521 $coursecontexts[$course->id] = context_course::instance($course->id);
524 return $coursecontexts;
528 * strip off action parameters like 'removecontact'
530 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
531 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
533 function message_remove_url_params($moodleurl) {
534 $newurl = new moodle_url($moodleurl);
535 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
536 return $newurl->out();
540 * Count the number of messages with a field having a specified value.
541 * if $field is empty then return count of the whole array
542 * if $field is non-existent then return 0
544 * @param array $messagearray array of message objects
545 * @param string $field the field to inspect on the message objects
546 * @param string $value the value to test the field against
548 function message_count_messages($messagearray, $field='', $value='') {
549 if (!is_array($messagearray)) return 0;
550 if ($field == '' or empty($messagearray)) return count($messagearray);
553 foreach ($messagearray as $message) {
554 $count += ($message->$field == $value) ? 1 : 0;
560 * Returns the count of unread messages for user. Either from a specific user or from all users.
562 * @param object $user1 the first user. Defaults to $USER
563 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
564 * @return int the count of $user1's unread messages
566 function message_count_unread_messages($user1=null, $user2=null) {
573 if (!empty($user2)) {
574 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
575 array($user1->id, $user2->id), "COUNT('id')");
577 return $DB->count_records_select('message', "useridto = ?",
578 array($user1->id), "COUNT('id')");
583 * Count the number of users blocked by $user1
585 * @param object $user1 user object
586 * @return int the number of blocked users
588 function message_count_blocked_users($user1=null) {
595 $sql = "SELECT count(mc.id)
596 FROM {message_contacts} mc
597 WHERE mc.userid = :userid AND mc.blocked = 1";
598 $params = array('userid' => $user1->id);
600 return $DB->count_records_sql($sql, $params);
604 * Print the search form and search results if a search has been performed
606 * @param boolean $advancedsearch show basic or advanced search form
607 * @param object $user1 the current user
608 * @return boolean true if a search was performed
610 function message_print_search($advancedsearch = false, $user1=null) {
611 $frm = data_submitted();
613 $doingsearch = false;
615 if (confirm_sesskey()) {
616 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
622 if (!empty($frm->combinedsearch)) {
623 $combinedsearchstring = $frm->combinedsearch;
625 //$combinedsearchstring = get_string('searchcombined','message').'...';
626 $combinedsearchstring = '';
630 if ($advancedsearch) {
633 if (!empty($frm->keywords)) {
634 $messagesearch = $frm->keywords;
637 if (!empty($frm->name)) {
638 $personsearch = $frm->name;
640 include('search_advanced.html');
642 include('search.html');
645 $showicontext = false;
646 message_print_search_results($frm, $showicontext, $user1);
651 if ($advancedsearch) {
652 $personsearch = $messagesearch = '';
653 include('search_advanced.html');
655 include('search.html');
662 * Get the users recent conversations meaning all the people they've recently
663 * sent or received a message from plus the most recent message sent to or received from each other user
665 * @param object $user the current user
666 * @param int $limitfrom can be used for paging
667 * @param int $limitto can be used for paging
670 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
673 $userfields = user_picture::fields('u', array('lastaccess'));
674 //This query retrieves the last message received from and sent to each user
675 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
676 //It then joins with some other tables to get some additional data we need
678 //message ID is used instead of timecreated as it should sort the same and will be much faster
680 //There is a separate query for read and unread queries as they are stored in different tables
681 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
682 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
683 FROM {message_read} mr
685 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
687 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
688 FROM {message_read} mr1
689 WHERE mr1.useridfrom = :userid1
690 AND mr1.notification = 0
691 GROUP BY mr1.useridto
693 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
694 FROM {message_read} mr2
695 WHERE mr2.useridto = :userid2
696 AND mr2.notification = 0
697 GROUP BY mr2.useridfrom
699 GROUP BY messages.userid
700 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
701 JOIN {user} u ON u.id = messages2.userid
702 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
703 WHERE u.deleted = '0'
704 ORDER BY mr.id DESC";
705 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
706 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
708 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
711 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
713 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
715 WHERE m1.useridfrom = :userid1
716 AND m1.notification = 0
719 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
721 WHERE m2.useridto = :userid2
722 AND m2.notification = 0
723 GROUP BY m2.useridfrom
725 GROUP BY messages.userid
726 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
727 JOIN {user} u ON u.id = messages2.userid
728 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
729 WHERE u.deleted = '0'
731 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
733 $conversations = array();
735 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
736 //$conversation->id (the array key) is the other user's ID
737 $conversation_arrays = array($unread, $read);
738 foreach ($conversation_arrays as $conversation_array) {
739 foreach ($conversation_array as $conversation) {
740 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
741 $conversations[$conversation->id] = $conversation;
746 // Sort the conversations by $conversation->timecreated, newest to oldest
747 // There may be multiple conversations with the same timecreated
748 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
749 $result = collatorlib::asort_objects_by_property($conversations, 'timecreated', collatorlib::SORT_NUMERIC);
750 $conversations = array_reverse($conversations);
752 return $conversations;
756 * Get the users recent event notifications
758 * @param object $user the current user
759 * @param int $limitfrom can be used for paging
760 * @param int $limitto can be used for paging
763 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
766 $userfields = user_picture::fields('u', array('lastaccess'));
767 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
768 FROM {message_read} mr
769 JOIN {user} u ON u.id=mr.useridfrom
770 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
771 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
772 $params = array('userid1' => $user->id, 'notification' => 1);
774 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
775 return $notifications;
779 * Print the user's recent conversations
781 * @param stdClass $user the current user
782 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
784 function message_print_recent_conversations($user=null, $showicontext=false) {
787 echo html_writer::start_tag('p', array('class' => 'heading'));
788 echo get_string('mostrecentconversations', 'message');
789 echo html_writer::end_tag('p');
795 $conversations = message_get_recent_conversations($user);
797 // Attach context url information to create the "View this conversation" type links
798 foreach($conversations as $conversation) {
799 $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
800 $conversation->contexturlname = get_string('thisconversation', 'message');
803 $showotheruser = true;
804 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
808 * Print the user's recent notifications
810 * @param stdClass $user the current user
812 function message_print_recent_notifications($user=null) {
815 echo html_writer::start_tag('p', array('class' => 'heading'));
816 echo get_string('mostrecentnotifications', 'message');
817 echo html_writer::end_tag('p');
823 $notifications = message_get_recent_notifications($user);
825 $showicontext = false;
826 $showotheruser = false;
827 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
831 * Print a list of recent messages
833 * @param array $messages the messages to display
834 * @param object $user the current user
835 * @param bool $showotheruser display information on the other user?
836 * @param bool $showicontext show text next to the action icons?
837 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
840 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false, $forcetexttohtml=false) {
844 if (empty($dateformat)) {
845 $dateformat = get_string('strftimedatetimeshort');
848 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
849 foreach ($messages as $message) {
850 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
852 if ($showotheruser) {
853 if ( $message->contactlistid ) {
854 if ($message->blocked == 0) { /// not blocked
855 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
856 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
858 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
859 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
862 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
863 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
866 //should we show just the icon or icon and text?
867 $histicontext = 'icon';
869 $histicontext = 'both';
871 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
873 echo html_writer::start_tag('span', array('class' => 'otheruser'));
875 echo html_writer::start_tag('span', array('class' => 'pix'));
876 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
877 echo html_writer::end_tag('span');
879 echo html_writer::start_tag('span', array('class' => 'contact'));
881 $link = new moodle_url("/message/index.php?id=$message->id");
883 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
885 echo html_writer::end_tag('span');//end contact
887 echo $strcontact.$strblock.$strhistory;
888 echo html_writer::end_tag('span');//end otheruser
890 $messagetoprint = null;
891 if (!empty($message->smallmessage)) {
892 $messagetoprint = $message->smallmessage;
894 $messagetoprint = $message->fullmessage;
897 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
898 echo html_writer::tag('span', format_text($messagetoprint, $forcetexttohtml?FORMAT_MOODLE:FORMAT_HTML), array('class' => 'themessage'));
899 echo message_format_contexturl($message);
900 echo html_writer::end_tag('div');//end singlemessage
902 echo html_writer::end_tag('div');//end messagerecent
906 * Add the selected user as a contact for the current user
908 * @param int $contactid the ID of the user to add as a contact
909 * @param int $blocked 1 if you wish to block the contact
910 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
911 * Otherwise returns the result of update_record() or insert_record()
913 function message_add_contact($contactid, $blocked=0) {
916 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
920 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
921 /// record already exists - we may be changing blocking status
923 if ($contact->blocked !== $blocked) {
924 /// change to blocking status
925 $contact->blocked = $blocked;
926 return $DB->update_record('message_contacts', $contact);
928 /// no changes to blocking status
933 /// new contact record
934 $contact = new stdClass();
935 $contact->userid = $USER->id;
936 $contact->contactid = $contactid;
937 $contact->blocked = $blocked;
938 return $DB->insert_record('message_contacts', $contact, false);
945 * @param int $contactid the user ID of the contact to remove
946 * @return bool returns the result of delete_records()
948 function message_remove_contact($contactid) {
950 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
954 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
956 * @param int $contactid the user ID of the contact to unblock
957 * @return bool returns the result of delete_records()
959 function message_unblock_contact($contactid) {
961 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
967 * @param int $contactid the user ID of the user to block
969 function message_block_contact($contactid) {
970 return message_add_contact($contactid, 1);
974 * Load a user's contact record
976 * @param int $contactid the user ID of the user whose contact record you want
977 * @return array message contacts
979 function message_get_contact($contactid) {
981 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
985 * Print the results of a message search
987 * @param mixed $frm submitted form data
988 * @param bool $showicontext show text next to action icons?
989 * @param object $currentuser the current user
992 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
993 global $USER, $DB, $OUTPUT;
995 if (empty($currentuser)) {
996 $currentuser = $USER;
999 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1001 $personsearch = false;
1002 $personsearchstring = null;
1003 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1004 $personsearch = true;
1005 $personsearchstring = $frm->name;
1006 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1007 $personsearch = true;
1008 $personsearchstring = $frm->combinedsearch;
1011 /// search for person
1012 if ($personsearch) {
1013 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1015 $mycourses = enrol_get_my_courses();
1016 foreach ($mycourses as $mycourse) {
1017 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1018 foreach ($susers as $suser) $users[$suser->id] = $suser;
1022 $users = message_search_users(SITEID, $personsearchstring);
1025 if (!empty($users)) {
1026 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1027 echo get_string('userssearchresults', 'message', count($users));
1028 echo html_writer::end_tag('p');
1030 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1031 foreach ($users as $user) {
1033 if ( $user->contactlistid ) {
1034 if ($user->blocked == 0) { /// not blocked
1035 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1036 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1038 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1039 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1042 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1043 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1046 //should we show just the icon or icon and text?
1047 $histicontext = 'icon';
1048 if ($showicontext) {
1049 $histicontext = 'both';
1051 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1053 echo html_writer::start_tag('tr');
1055 echo html_writer::start_tag('td', array('class' => 'pix'));
1056 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1057 echo html_writer::end_tag('td');
1059 echo html_writer::start_tag('td',array('class' => 'contact'));
1061 $link = new moodle_url("/message/index.php?id=$user->id");
1062 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1063 echo html_writer::end_tag('td');
1065 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1066 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1067 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1069 echo html_writer::end_tag('tr');
1071 echo html_writer::end_tag('table');
1074 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1075 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1076 echo html_writer::end_tag('p');
1080 // search messages for keywords
1081 $messagesearch = false;
1082 $messagesearchstring = null;
1083 if (!empty($frm->keywords)) {
1084 $messagesearch = true;
1085 $messagesearchstring = clean_text(trim($frm->keywords));
1086 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1087 $messagesearch = true;
1088 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1091 if ($messagesearch) {
1092 if ($messagesearchstring) {
1093 $keywords = explode(' ', $messagesearchstring);
1095 $keywords = array();
1101 if (empty($frm->keywordsoption)) {
1102 $frm->keywordsoption = 'allmine';
1105 switch ($frm->keywordsoption) {
1120 $courseid = $frm->courseid;
1127 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1129 /// get a list of contacts
1130 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1131 $contacts = array();
1134 /// print heading with number of results
1135 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1136 $countresults = count($messages);
1137 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1138 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1140 echo get_string('keywordssearchresults', 'message', $countresults);
1142 echo html_writer::end_tag('p');
1144 /// print table headings
1145 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1147 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1148 $headertdend = html_writer::end_tag('td');
1149 echo html_writer::start_tag('tr');
1150 echo $headertdstart.get_string('from').$headertdend;
1151 echo $headertdstart.get_string('to').$headertdend;
1152 echo $headertdstart.get_string('message', 'message').$headertdend;
1153 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1154 echo html_writer::end_tag('tr');
1157 $dateformat = get_string('strftimedatetimeshort');
1158 $strcontext = get_string('context', 'message');
1159 foreach ($messages as $message) {
1161 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1162 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1163 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1164 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1171 /// load up user to record
1172 if ($message->useridto !== $USER->id) {
1173 $userto = $DB->get_record('user', array('id' => $message->useridto));
1174 $tocontact = (array_key_exists($message->useridto, $contacts) and
1175 ($contacts[$message->useridto]->blocked == 0) );
1176 $toblocked = (array_key_exists($message->useridto, $contacts) and
1177 ($contacts[$message->useridto]->blocked == 1) );
1184 /// load up user from record
1185 if ($message->useridfrom !== $USER->id) {
1186 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1187 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1188 ($contacts[$message->useridfrom]->blocked == 0) );
1189 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1190 ($contacts[$message->useridfrom]->blocked == 1) );
1193 $fromcontact = false;
1194 $fromblocked = false;
1197 /// find date string for this message
1198 $date = usergetdate($message->timecreated);
1199 $datestring = $date['year'].$date['mon'].$date['mday'];
1201 /// print out message row
1202 echo html_writer::start_tag('tr', array('valign' => 'top'));
1204 echo html_writer::start_tag('td', array('class' => 'contact'));
1205 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1206 echo html_writer::end_tag('td');
1208 echo html_writer::start_tag('td', array('class' => 'contact'));
1209 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1210 echo html_writer::end_tag('td');
1212 echo html_writer::start_tag('td', array('class' => 'summary'));
1213 echo message_get_fragment($message->smallmessage, $keywords);
1214 echo html_writer::start_tag('div', array('class' => 'link'));
1216 //If the user clicks the context link display message sender on the left
1217 //EXCEPT if the current user is in the conversation. Current user == always on the left
1218 $leftsideuserid = $rightsideuserid = null;
1219 if ($currentuser->id == $message->useridto) {
1220 $leftsideuserid = $message->useridto;
1221 $rightsideuserid = $message->useridfrom;
1223 $leftsideuserid = $message->useridfrom;
1224 $rightsideuserid = $message->useridto;
1226 message_history_link($leftsideuserid, $rightsideuserid, false,
1227 $messagesearchstring, 'm'.$message->id, $strcontext);
1228 echo html_writer::end_tag('div');
1229 echo html_writer::end_tag('td');
1231 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1233 echo html_writer::end_tag('tr');
1237 if ($blockedcount > 0) {
1238 echo html_writer::start_tag('tr');
1239 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1240 echo html_writer::end_tag('tr');
1242 echo html_writer::end_tag('table');
1245 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1249 if (!$personsearch && !$messagesearch) {
1250 //they didn't enter any search terms
1251 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1254 echo html_writer::end_tag('div');
1258 * Print information on a user. Used when printing search results.
1260 * @param object/bool $user the user to display or false if you just want $USER
1261 * @param bool $iscontact is the user being displayed a contact?
1262 * @param bool $isblocked is the user being displayed blocked?
1263 * @param bool $includeicontext include text next to the action icons?
1266 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1267 global $USER, $OUTPUT;
1269 if ($user === false) {
1270 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1272 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1274 $link = new moodle_url("/message/index.php?id=$user->id");
1275 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1276 get_string('sendmessageto', 'message', fullname($user))));
1281 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1283 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1287 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1289 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1295 * Print a message contact link
1297 * @param int $userid the ID of the user to apply to action to
1298 * @param string $linktype can be add, remove, block or unblock
1299 * @param bool $return if true return the link as a string. If false echo the link.
1300 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1301 * @param bool $text include text next to the icons?
1302 * @param bool $icon include a graphical icon?
1303 * @return string if $return is true otherwise bool
1305 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1306 global $OUTPUT, $PAGE;
1308 //hold onto the strings as we're probably creating a bunch of links
1311 if (empty($script)) {
1312 //strip off previous action params like 'removecontact'
1313 $script = message_remove_url_params($PAGE->url);
1316 if (empty($str->blockcontact)) {
1317 $str = new stdClass();
1318 $str->blockcontact = get_string('blockcontact', 'message');
1319 $str->unblockcontact = get_string('unblockcontact', 'message');
1320 $str->removecontact = get_string('removecontact', 'message');
1321 $str->addcontact = get_string('addcontact', 'message');
1324 $command = $linktype.'contact';
1325 $string = $str->{$command};
1327 $safealttext = s($string);
1330 if (!empty($text)) {
1331 $safestring = $safealttext;
1337 switch ($linktype) {
1339 $iconpath = 't/block';
1342 $iconpath = 't/unblock';
1345 $iconpath = 't/removecontact';
1349 $iconpath = 't/addcontact';
1352 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1355 $output = '<span class="'.$linktype.'contact">'.
1356 '<a href="'.$script.'&'.$command.'='.$userid.
1357 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1359 $safestring.'</a></span>';
1370 * echo or return a link to take the user to the full message history between themselves and another user
1372 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1373 * @param int $userid2 the ID of the other user
1374 * @param bool $return true to return the link as a string. False to echo the link.
1375 * @param string $keywords any keywords to highlight in the message history
1376 * @param string $position anchor name to jump to within the message history
1377 * @param string $linktext optionally specify the link text
1378 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1380 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1382 static $strmessagehistory;
1384 if (empty($strmessagehistory)) {
1385 $strmessagehistory = get_string('messagehistory', 'message');
1389 $position = "#$position";
1392 $keywords = "&search=".urlencode($keywords);
1395 if ($linktext == 'icon') { // Icon only
1396 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1397 } else if ($linktext == 'both') { // Icon and standard name
1398 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1399 $fulllink .= ' '.$strmessagehistory;
1400 } else if ($linktext) { // Custom name
1401 $fulllink = $linktext;
1402 } else { // Standard name only
1403 $fulllink = $strmessagehistory;
1406 $popupoptions = array(
1410 'location' => false,
1412 'scrollbars' => true,
1413 'resizable' => true);
1415 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1417 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1419 $str = '<span class="history">'.$str.'</span>';
1431 * Search through course users
1433 * If $coursid specifies the site course then this function searches
1434 * through all undeleted and confirmed users
1435 * @param int $courseid The course in question.
1436 * @param string $searchtext the text to search for
1437 * @param string $sort the column name to order by
1438 * @param string $exceptions comma separated list of user IDs to exclude
1439 * @return array An array of {@link $USER} records.
1441 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1442 global $CFG, $USER, $DB;
1444 $fullname = $DB->sql_fullname();
1446 if (!empty($exceptions)) {
1447 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1452 if (!empty($sort)) {
1453 $order = ' ORDER BY '. $sort;
1458 $ufields = user_picture::fields('u');
1459 if (!$courseid or $courseid == SITEID) {
1460 $params = array($USER->id, "%$searchtext%");
1461 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1463 LEFT JOIN {message_contacts} mc
1464 ON mc.contactid = u.id AND mc.userid = ?
1465 WHERE u.deleted = '0' AND u.confirmed = '1'
1466 AND (".$DB->sql_like($fullname, '?', false).")
1470 //TODO: add enabled enrolment join here (skodak)
1471 $context = context_course::instance($courseid);
1472 $contextlists = get_related_contexts_string($context);
1474 // everyone who has a role assignment in this course or higher
1475 $params = array($USER->id, "%$searchtext%");
1476 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1478 JOIN {role_assignments} ra ON ra.userid = u.id
1479 LEFT JOIN {message_contacts} mc
1480 ON mc.contactid = u.id AND mc.userid = ?
1481 WHERE u.deleted = '0' AND u.confirmed = '1'
1482 AND ra.contextid $contextlists
1483 AND (".$DB->sql_like($fullname, '?', false).")
1492 * search a user's messages
1494 * @param array $searchterms an array of search terms (strings)
1495 * @param bool $fromme include messages from the user?
1496 * @param bool $tome include messages to the user?
1497 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1498 * @param int $userid the user ID of the current user
1499 * @return mixed An array of messages or false if no matching messages were found
1501 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1502 /// Returns a list of posts found using an array of search terms
1503 /// eg word +word -word
1505 global $CFG, $USER, $DB;
1507 // If user is searching all messages check they are allowed to before doing anything else
1508 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1509 print_error('accessdenied','admin');
1512 /// If no userid sent then assume current user
1513 if ($userid == 0) $userid = $USER->id;
1515 /// Some differences in SQL syntax
1516 if ($DB->sql_regex_supported()) {
1517 $REGEXP = $DB->sql_regex(true);
1518 $NOTREGEXP = $DB->sql_regex(false);
1521 $searchcond = array();
1525 //preprocess search terms to check whether we have at least 1 eligible search term
1526 //if we do we can drop words around it like 'a'
1527 $dropshortwords = false;
1528 foreach ($searchterms as $searchterm) {
1529 if (strlen($searchterm) >= 2) {
1530 $dropshortwords = true;
1534 foreach ($searchterms as $searchterm) {
1537 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1539 if ($dropshortwords && strlen($searchterm) < 2) {
1542 /// Under Oracle and MSSQL, trim the + and - operators and perform
1543 /// simpler LIKE search
1544 if (!$DB->sql_regex_supported()) {
1545 if (substr($searchterm, 0, 1) == '-') {
1548 $searchterm = trim($searchterm, '+-');
1551 if (substr($searchterm,0,1) == "+") {
1552 $searchterm = substr($searchterm,1);
1553 $searchterm = preg_quote($searchterm, '|');
1554 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1555 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1557 } else if (substr($searchterm,0,1) == "-") {
1558 $searchterm = substr($searchterm,1);
1559 $searchterm = preg_quote($searchterm, '|');
1560 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1561 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1564 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1565 $params['ss'.$i] = "%$searchterm%";
1569 if (empty($searchcond)) {
1570 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1571 $params['ss1'] = "%";
1573 $searchcond = implode(" AND ", $searchcond);
1576 /// There are several possibilities
1577 /// 1. courseid = SITEID : The admin is searching messages by all users
1578 /// 2. courseid = ?? : A teacher is searching messages by users in
1579 /// one of their courses - currently disabled
1580 /// 3. courseid = none : User is searching their own messages;
1581 /// a. Messages from user
1582 /// b. Messages to user
1583 /// c. Messages to and from user
1585 if ($courseid == SITEID) { /// admin is searching all messages
1586 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1587 FROM {message_read} m
1588 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1589 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1591 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1593 } else if ($courseid !== 'none') {
1594 /// This has not been implemented due to security concerns
1596 $m_unread = array();
1600 if ($fromme and $tome) {
1601 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1602 $params['userid1'] = $userid;
1603 $params['userid2'] = $userid;
1605 } else if ($fromme) {
1606 $searchcond .= " AND m.useridfrom=:userid";
1607 $params['userid'] = $userid;
1610 $searchcond .= " AND m.useridto=:userid";
1611 $params['userid'] = $userid;
1614 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1615 FROM {message_read} m
1616 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1617 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1619 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1623 /// The keys may be duplicated in $m_read and $m_unread so we can't
1624 /// do a simple concatenation
1625 $messages = array();
1626 foreach ($m_read as $m) {
1629 foreach ($m_unread as $m) {
1633 return (empty($messages)) ? false : $messages;
1637 * Given a message object that we already know has a long message
1638 * this function truncates the message nicely to the first
1639 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1641 * @param string $message the message
1642 * @param int $minlength the minimum length to trim the message to
1643 * @return string the shortened message
1645 function message_shorten_message($message, $minlength = 0) {
1648 $length = strlen($message);
1652 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1655 for ($i=0; $i<$length; $i++) {
1656 $char = $message[$i];
1668 if ($char == '.' or $char == ' ') {
1678 if ($count > $minlength) {
1688 return substr($message, 0, $truncate);
1693 * Given a string and an array of keywords, this function looks
1694 * for the first keyword in the string, and then chops out a
1695 * small section from the text that shows that word in context.
1697 * @param string $message the text to search
1698 * @param array $keywords array of keywords to find
1700 function message_get_fragment($message, $keywords) {
1703 $halfsize = (int)($fullsize/2);
1705 $message = strip_tags($message);
1707 foreach ($keywords as $keyword) { // Just get the first one
1708 if ($keyword !== '') {
1712 if (empty($keyword)) { // None found, so just return start of message
1713 return message_shorten_message($message, 30);
1716 $leadin = $leadout = '';
1718 /// Find the start of the fragment
1720 $length = strlen($message);
1722 $pos = strpos($message, $keyword);
1723 if ($pos > $halfsize) {
1724 $start = $pos - $halfsize;
1727 /// Find the end of the fragment
1728 $end = $start + $fullsize;
1729 if ($end > $length) {
1735 /// Pull out the fragment and format it
1737 $fragment = substr($message, $start, $end - $start);
1738 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1743 * Retrieve the messages between two users
1745 * @param object $user1 the current user
1746 * @param object $user2 the other user
1747 * @param int $limitnum the maximum number of messages to retrieve
1748 * @param bool $viewingnewmessages are we currently viewing new messages?
1750 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1753 $messages = array();
1755 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1756 //desc to get the last $limitnum messages then flip the order in php
1762 $notificationswhere = null;
1763 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1764 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1765 $notificationswhere = 'AND notification=0';
1768 //prevent notifications of your own actions appearing in your own message history
1769 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1771 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1772 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1773 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1774 "timecreated $sort", '*', 0, $limitnum)) {
1775 foreach ($messages_read as $message) {
1776 $messages[] = $message;
1779 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1780 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1781 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1782 "timecreated $sort", '*', 0, $limitnum)) {
1783 foreach ($messages_new as $message) {
1784 $messages[] = $message;
1788 $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);
1790 //if we only want the last $limitnum messages
1791 $messagecount = count($messages);
1792 if ($limitnum > 0 && $messagecount > $limitnum) {
1793 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1800 * Print the message history between two users
1802 * @param object $user1 the current user
1803 * @param object $user2 the other user
1804 * @param string $search search terms to highlight
1805 * @param int $messagelimit maximum number of messages to return
1806 * @param string $messagehistorylink the html for the message history link or false
1807 * @param bool $viewingnewmessages are we currently viewing new messages?
1809 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1810 global $CFG, $OUTPUT;
1812 echo $OUTPUT->box_start('center');
1813 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1814 echo html_writer::start_tag('tr');
1816 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1817 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1818 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1819 echo html_writer::end_tag('td');
1821 echo html_writer::start_tag('td', array('align' => 'center'));
1822 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1823 echo html_writer::end_tag('td');
1825 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1826 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1827 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1829 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1830 $incontactlist = $user2->iscontact;
1831 $isblocked = $user2->isblocked;
1837 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1838 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1839 $useractionlinks = $strcontact.' |'.$strblock;
1841 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1844 echo html_writer::end_tag('td');
1845 echo html_writer::end_tag('tr');
1846 echo html_writer::end_tag('table');
1847 echo $OUTPUT->box_end();
1849 if (!empty($messagehistorylink)) {
1850 echo $messagehistorylink;
1853 /// Get all the messages and print them
1854 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1855 $tablecontents = '';
1857 $current = new stdClass();
1858 $current->mday = '';
1859 $current->month = '';
1860 $current->year = '';
1861 $messagedate = get_string('strftimetime');
1862 $blockdate = get_string('strftimedaydate');
1863 foreach ($messages as $message) {
1864 if ($message->notification) {
1865 $notificationclass = ' notification';
1867 $notificationclass = null;
1869 $date = usergetdate($message->timecreated);
1870 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1871 $current->mday = $date['mday'];
1872 $current->month = $date['month'];
1873 $current->year = $date['year'];
1875 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1876 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1878 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1881 $formatted_message = $side = null;
1882 if ($message->useridfrom == $user1->id) {
1883 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1886 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1889 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1892 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1894 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1899 * Format a message for display in the message history
1901 * @param object $message the message object
1902 * @param string $format optional date format
1903 * @param string $keywords keywords to highlight
1904 * @param string $class CSS class to apply to the div around the message
1905 * @return string the formatted message
1907 function message_format_message($message, $format='', $keywords='', $class='other') {
1911 //if we haven't previously set the date format or they've supplied a new one
1912 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1914 $dateformat = $format;
1916 $dateformat = get_string('strftimedatetimeshort');
1919 $time = userdate($message->timecreated, $dateformat);
1920 $options = new stdClass();
1921 $options->para = false;
1923 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1924 if (!empty($message->smallmessage)) {
1925 $messagetext = $message->smallmessage;
1927 $messagetext = $message->fullmessage;
1929 if ($message->fullmessageformat == FORMAT_HTML) {
1930 //dont escape html tags by calling s() if html format or they will display in the UI
1931 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1933 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1936 $messagetext .= message_format_contexturl($message);
1939 $messagetext = highlight($keywords, $messagetext);
1943 <div class='message $class'>
1944 <a name="m'.{$message->id}.'"></a>
1945 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
1951 * Format a the context url and context url name of a message for display
1953 * @param object $message the message object
1954 * @return string the formatted string
1956 function message_format_contexturl($message) {
1959 if (!empty($message->contexturl)) {
1960 $displaytext = null;
1961 if (!empty($message->contexturlname)) {
1962 $displaytext= $message->contexturlname;
1964 $displaytext= $message->contexturl;
1966 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1967 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1968 $s .= html_writer::end_tag('div');
1975 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1977 * @param object $userfrom the message sender
1978 * @param object $userto the message recipient
1979 * @param string $message the message
1980 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1981 * @return int|false the ID of the new message or false
1983 function message_post_message($userfrom, $userto, $message, $format) {
1984 global $SITE, $CFG, $USER;
1986 $eventdata = new stdClass();
1987 $eventdata->component = 'moodle';
1988 $eventdata->name = 'instantmessage';
1989 $eventdata->userfrom = $userfrom;
1990 $eventdata->userto = $userto;
1992 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
1993 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
1995 if ($format == FORMAT_HTML) {
1996 $eventdata->fullmessagehtml = $message;
1997 //some message processors may revert to sending plain text even if html is supplied
1998 //so we keep both plain and html versions if we're intending to send html
1999 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2001 $eventdata->fullmessage = $message;
2002 $eventdata->fullmessagehtml = '';
2005 $eventdata->fullmessageformat = $format;
2006 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2008 $s = new stdClass();
2009 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2010 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2012 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2013 if (!empty($eventdata->fullmessage)) {
2014 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2016 if (!empty($eventdata->fullmessagehtml)) {
2017 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2020 $eventdata->timecreated = time();
2021 return message_send($eventdata);
2025 * Print a row of contactlist displaying user picture, messages waiting and
2028 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2029 * @param bool $incontactlist is the user a contact of ours?
2030 * @param bool $isblocked is the user blocked?
2031 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2032 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2033 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2036 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2037 global $OUTPUT, $USER;
2038 $fullname = fullname($contact);
2039 $fullnamelink = $fullname;
2042 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2043 $linkclass = 'messageselecteduser';
2046 /// are there any unread messages for this contact?
2047 if ($contact->messagecount > 0 ){
2048 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2051 $strcontact = $strblock = $strhistory = null;
2053 if ($showactionlinks) {
2054 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2055 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2056 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2059 echo html_writer::start_tag('tr');
2060 echo html_writer::start_tag('td', array('class' => 'pix'));
2061 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2062 echo html_writer::end_tag('td');
2064 echo html_writer::start_tag('td', array('class' => 'contact'));
2066 $popupoptions = array(
2067 'height' => MESSAGE_DISCUSSION_HEIGHT,
2068 'width' => MESSAGE_DISCUSSION_WIDTH,
2070 'location' => false,
2072 'scrollbars' => true,
2073 'resizable' => true);
2075 $link = $action = null;
2076 if (!empty($selectcontacturl)) {
2077 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2079 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2080 $link = new moodle_url("/message/index.php?id=$contact->id");
2081 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2083 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2085 echo html_writer::end_tag('td');
2087 echo html_writer::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2089 echo html_writer::end_tag('tr');
2093 * Constructs the add/remove contact link to display next to other users
2095 * @param bool $incontactlist is the user a contact
2096 * @param bool $isblocked is the user blocked
2097 * @param stdClass $contact contact object
2098 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2099 * @param bool $text include text next to the icons?
2100 * @param bool $icon include a graphical icon?
2103 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2107 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2108 } else if ($isblocked) {
2109 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2111 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2118 * Constructs the block contact link to display next to other users
2120 * @param bool $incontactlist is the user a contact?
2121 * @param bool $isblocked is the user blocked?
2122 * @param stdClass $contact contact object
2123 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2124 * @param bool $text include text next to the icons?
2125 * @param bool $icon include a graphical icon?
2128 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2131 //commented out to allow the user to block a contact without having to remove them first
2132 /*if ($incontactlist) {
2136 $strblock = ' '.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2138 $strblock = ' '.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2145 * Moves messages from a particular user from the message table (unread messages) to message_read
2146 * This is typically only used when a user is deleted
2148 * @param object $userid User id
2149 * @return boolean success
2151 function message_move_userfrom_unread2read($userid) {
2154 // move all unread messages from message table to message_read
2155 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2156 foreach ($messages as $message) {
2157 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2164 * marks ALL messages being sent from $fromuserid to $touserid as read
2166 * @param int $touserid the id of the message recipient
2167 * @param int $fromuserid the id of the message sender
2170 function message_mark_messages_read($touserid, $fromuserid){
2173 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2174 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2176 foreach ($messages as $message) {
2177 message_mark_message_read($message, time());
2184 * Mark a single message as read
2186 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2187 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2188 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2189 * @return int the ID of the message in the message_read table
2191 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2194 $message->timeread = $timeread;
2196 $messageid = $message->id;
2197 unset($message->id);//unset because it will get a new id on insert into message_read
2199 //If any processors have pending actions abort them
2200 if (!$messageworkingempty) {
2201 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2203 $messagereadid = $DB->insert_record('message_read', $message);
2204 $DB->delete_records('message', array('id' => $messageid));
2205 return $messagereadid;
2209 * A helper function that prints a formatted heading
2211 * @param string $title the heading to display
2212 * @param int $colspan
2215 function message_print_heading($title, $colspan=3) {
2216 echo html_writer::start_tag('tr');
2217 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2218 echo html_writer::end_tag('tr');
2222 * Get all message processors, validate corresponding plugin existance and
2223 * system configuration
2225 * @param bool $ready only return ready-to-use processors
2226 * @return mixed $processors array of objects containing information on message processors
2228 function get_message_processors($ready = false) {
2233 if (empty($processors)) {
2234 // Get all processors, ensure the name column is the first so it will be the array key
2235 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2236 foreach ($processors as &$processor){
2237 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2238 if (is_readable($processorfile)) {
2239 include_once($processorfile);
2240 $processclass = 'message_output_' . $processor->name;
2241 if (class_exists($processclass)) {
2242 $pclass = new $processclass();
2243 $processor->object = $pclass;
2244 $processor->configured = 0;
2245 if ($pclass->is_system_configured()) {
2246 $processor->configured = 1;
2248 $processor->hassettings = 0;
2249 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2250 $processor->hassettings = 1;
2252 $processor->available = 1;
2254 print_error('errorcallingprocessor', 'message');
2257 $processor->available = 0;
2262 // Filter out enabled and system_configured processors
2263 $readyprocessors = $processors;
2264 foreach ($readyprocessors as $readyprocessor) {
2265 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2266 unset($readyprocessors[$readyprocessor->name]);
2269 return $readyprocessors;
2276 * Get all message providers, validate their plugin existance and
2277 * system configuration
2279 * @return mixed $processors array of objects containing information on message processors
2281 function get_message_providers() {
2283 require_once($CFG->libdir . '/pluginlib.php');
2284 $pluginman = plugin_manager::instance();
2286 $providers = $DB->get_records('message_providers', null, 'name');
2288 // Remove all the providers whose plugins are disabled or don't exist
2289 foreach ($providers as $providerid => $provider) {
2290 $plugin = $pluginman->get_plugin_info($provider->component);
2292 if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2293 unset($providers[$providerid]); // Plugins does not exist
2296 if ($plugin->is_enabled() === false) {
2297 unset($providers[$providerid]); // Plugin disabled
2306 * Get an instance of the message_output class for one of the output plugins.
2307 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2308 * @return message_output message_output the requested class.
2310 function get_message_processor($type) {
2313 // Note, we cannot use the get_message_processors function here, becaues this
2314 // code is called during install after installing each messaging plugin, and
2315 // get_message_processors caches the list of installed plugins.
2317 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2318 if (!is_readable($processorfile)) {
2319 throw new coding_exception('Unknown message processor type ' . $type);
2322 include_once($processorfile);
2324 $processclass = 'message_output_' . $type;
2325 if (!class_exists($processclass)) {
2326 throw new coding_exception('Message processor ' . $type .
2327 ' does not define the right class');
2330 return new $processclass();
2334 * Get messaging outputs default (site) preferences
2336 * @return object $processors object containing information on message processors
2338 function get_message_output_default_preferences() {
2339 return get_config('message');
2343 * Translate message default settings from binary value to the array of string
2344 * representing the settings to be stored. Also validate the provided value and
2345 * use default if it is malformed.
2347 * @param int $plugindefault Default setting suggested by plugin
2348 * @param string $processorname The name of processor
2349 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2351 function translate_message_default_setting($plugindefault, $processorname) {
2352 // Preset translation arrays
2353 $permittedvalues = array(
2354 0x04 => 'disallowed',
2355 0x08 => 'permitted',
2359 $loggedinstatusvalues = array(
2360 0x00 => null, // use null if loggedin/loggedoff is not defined
2362 0x02 => 'loggedoff',
2365 // define the default setting
2366 $processor = get_message_processor($processorname);
2367 $default = $processor->get_default_messaging_settings();
2369 // Validate the value. It should not exceed the maximum size
2370 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2371 debugging(get_string('errortranslatingdefault', 'message'));
2372 $plugindefault = $default;
2374 // Use plugin default setting of 'permitted' is 0
2375 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2376 $plugindefault = $default;
2379 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2380 $loggedin = $loggedoff = null;
2382 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2383 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2384 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2387 return array($permitted, $loggedin, $loggedoff);
2391 * Return a list of page types
2392 * @param string $pagetype current page type
2393 * @param stdClass $parentcontext Block's parent context
2394 * @param stdClass $currentcontext Current context of block
2396 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2397 return array('messages-*'=>get_string('page-message-x', 'message'));
2401 * Is $USER one of the supplied users?
2403 * $user2 will be null if viewing a user's recent conversations
2405 * @param stdClass the first user
2406 * @param stdClass the second user or null
2407 * @return bool True if the current user is one of either $user1 or $user2
2409 function message_current_user_is_involved($user1, $user2) {
2412 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2413 throw new coding_exception('Invalid user object detected. Missing id.');
2416 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {