3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library functions for messaging
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir
.'/eventslib.php');
28 define ('MESSAGE_SHORTLENGTH', 300);
30 //$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
32 $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
35 define ('MESSAGE_DISCUSSION_WIDTH',600);
36 define ('MESSAGE_DISCUSSION_HEIGHT',500);
38 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
40 define('MESSAGE_HISTORY_SHORT',0);
41 define('MESSAGE_HISTORY_ALL',1);
43 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
44 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
45 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
46 define('MESSAGE_VIEW_CONTACTS','contacts');
47 define('MESSAGE_VIEW_BLOCKED','blockedusers');
48 define('MESSAGE_VIEW_COURSE','course_');
49 define('MESSAGE_VIEW_SEARCH','search');
51 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
53 define('MESSAGE_CONTACTS_PER_PAGE',10);
54 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
56 if (!isset($CFG->message_contacts_refresh
)) { // Refresh the contacts list every 60 seconds
57 $CFG->message_contacts_refresh
= 60;
59 if (!isset($CFG->message_chat_refresh
)) { // Look for new comments every 5 seconds
60 $CFG->message_chat_refresh
= 5;
62 if (!isset($CFG->message_offline_time
)) {
63 $CFG->message_offline_time
= 300;
67 * Print the selector that allows the user to view their contacts, course participants, their recent
69 * @param int $countunreadtotal how many unread messages does the user have?
70 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
71 * @param object $user1 the user whose messages are being viewed
72 * @param object $user2 the user $user1 is talking to
73 * @param array $blockedusers an array of users blocked by $user1
74 * @param array $onlinecontacts an array of $user1's online contacts
75 * @param array $offlinecontacts an array of $user1's offline contacts
76 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
77 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
78 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
81 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
84 echo html_writer
::start_tag('div', array('class' => 'contactselector mdl-align'));
86 //if 0 unread messages and they've requested unread messages then show contacts
87 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
88 $viewing = MESSAGE_VIEW_CONTACTS
;
91 //if they have no blocked users and they've requested blocked users switch them over to contacts
92 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED
) {
93 $viewing = MESSAGE_VIEW_CONTACTS
;
96 $onlyactivecourses = true;
97 $courses = enrol_get_users_courses($user1->id
, $onlyactivecourses);
98 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
100 $strunreadmessages = null;
101 if ($countunreadtotal>0) { //if there are unread messages
102 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
105 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
107 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
108 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 1, $showcontactactionlinks,$strunreadmessages, $user2);
109 } else if ($viewing == MESSAGE_VIEW_CONTACTS ||
$viewing == MESSAGE_VIEW_SEARCH ||
$viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS ||
$viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS
) {
110 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 0, $showcontactactionlinks, $strunreadmessages, $user2);
111 } else if ($viewing == MESSAGE_VIEW_BLOCKED
) {
112 message_print_blocked_users($blockedusers, $PAGE->url
, $showcontactactionlinks, null, $user2);
113 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE
) {
114 $courseidtoshow = intval(substr($viewing, 7));
116 if (!empty($courseidtoshow)
117 && array_key_exists($courseidtoshow, $coursecontexts)
118 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
120 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url
, $showcontactactionlinks, null, $page, $user2);
122 //shouldn't get here. User trying to access a course they're not in perhaps.
123 add_to_log(SITEID
, 'message', 'view', 'index.php', $viewing);
127 echo html_writer
::start_tag('form', array('action' => 'index.php','method' => 'GET'));
128 echo html_writer
::start_tag('fieldset');
129 $managebuttonclass = 'visible';
130 if ($viewing == MESSAGE_VIEW_SEARCH
) {
131 $managebuttonclass = 'hiddenelement';
133 $strmanagecontacts = get_string('search','message');
134 echo html_writer
::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH
));
135 echo html_writer
::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
136 echo html_writer
::end_tag('fieldset');
137 echo html_writer
::end_tag('form');
139 echo html_writer
::end_tag('div');
143 * Print course participants. Called by message_print_contact_selector()
144 * @param object $context the course context
145 * @param int $courseid the course ID
146 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
147 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
148 * @param string $titletodisplay Optionally specify a title to display above the participants
149 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
150 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
153 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
154 global $DB, $USER, $PAGE, $OUTPUT;
156 if (empty($titletodisplay)) {
157 $titletodisplay = get_string('participants');
160 $countparticipants = count_enrolled_users($context);
161 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE
, MESSAGE_CONTACTS_PER_PAGE
);
163 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE
, $PAGE->url
, 'page');
164 echo $OUTPUT->render($pagingbar);
166 echo html_writer
::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
168 echo html_writer
::start_tag('tr');
169 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
170 echo html_writer
::end_tag('tr');
172 //todo these need to come from somewhere if the course participants list is to show users with unread messages
175 foreach ($participants as $participant) {
176 if ($participant->id
!= $USER->id
) {
177 $participant->messagecount
= 0;//todo it would be nice if the course participant could report new messages
178 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
182 echo html_writer
::end_tag('table');
186 * Retrieve users blocked by $user1
187 * @param object $user1 the user whose messages are being viewed
188 * @param object $user2 the user $user1 is talking to. If they are being blocked
189 * they will have a variable called 'isblocked' added to their user object
190 * @return array the users blocked by $user1
192 function message_get_blocked_users($user1=null, $user2=null) {
199 if (!empty($user2)) {
200 $user2->isblocked
= false;
203 $blockedusers = array();
205 $userfields = user_picture
::fields('u', array('lastaccess'));
206 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
207 FROM {message_contacts} mc
208 JOIN {user} u ON u.id = mc.contactid
209 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
210 WHERE mc.userid = :user1id2 AND mc.blocked = 1
212 ORDER BY u.firstname ASC";
213 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id
, 'user1id2' => $user1->id
));
215 foreach($rs as $rd) {
216 $blockedusers[] = $rd;
218 if (!empty($user2) && $user2->id
== $rd->id
) {
219 $user2->isblocked
= true;
224 return $blockedusers;
228 * Print users blocked by $user1. Called by message_print_contact_selector()
229 * @param array $blockedusers the users blocked by $user1
230 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
231 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
232 * @param string $titletodisplay Optionally specify a title to display above the participants
233 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
236 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
239 $countblocked = count($blockedusers);
241 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
243 if (!empty($titletodisplay)) {
244 echo html_writer
::start_tag('tr');
245 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
246 echo html_writer
::end_tag('tr');
250 echo html_writer
::start_tag('tr');
251 echo html_writer
::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
252 echo html_writer
::end_tag('tr');
254 $isuserblocked = true;
255 $isusercontact = false;
256 foreach ($blockedusers as $blockeduser) {
257 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
261 echo html_writer
::end_tag('table');
265 * Retrieve $user1's contacts (online, offline and strangers)
266 * @param object $user1 the user whose messages are being viewed
267 * @param object $user2 the user $user1 is talking to. If they are a contact
268 * they will have a variable called 'iscontact' added to their user object
269 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
271 function message_get_contacts($user1=null, $user2=null) {
272 global $DB, $CFG, $USER;
278 if (!empty($user2)) {
279 $user2->iscontact
= false;
282 $timetoshowusers = 300; //Seconds default
283 if (isset($CFG->block_online_users_timetosee
)) {
284 $timetoshowusers = $CFG->block_online_users_timetosee
* 60;
287 // time which a user is counting as being active since
288 $timefrom = time()-$timetoshowusers;
290 // people in our contactlist who are online
291 $onlinecontacts = array();
292 // people in our contactlist who are offline
293 $offlinecontacts = array();
294 // people who are not in our contactlist but have sent us a message
295 $strangers = array();
297 $userfields = user_picture
::fields('u', array('lastaccess'));
299 // get all in our contactlist who are not blocked in our contact list
300 // and count messages we have waiting from each of them
301 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
302 FROM {message_contacts} mc
303 JOIN {user} u ON u.id = mc.contactid
304 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
305 WHERE mc.userid = ? AND mc.blocked = 0
307 ORDER BY u.firstname ASC";
309 $rs = $DB->get_recordset_sql($contactsql, array($user1->id
, $user1->id
));
310 foreach ($rs as $rd) {
311 if ($rd->lastaccess
>= $timefrom) {
312 // they have been active recently, so are counted online
313 $onlinecontacts[] = $rd;
316 $offlinecontacts[] = $rd;
319 if (!empty($user2) && $user2->id
== $rd->id
) {
320 $user2->iscontact
= true;
325 // get messages from anyone who isn't in our contact list and count the number
326 // of messages we have from each of them
327 $strangersql = "SELECT $userfields, count(m.id) as messagecount
329 JOIN {user} u ON u.id = m.useridfrom
330 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
331 WHERE mc.id IS NULL AND m.useridto = ?
333 ORDER BY u.firstname ASC";
335 $rs = $DB->get_recordset_sql($strangersql, array($USER->id
));
336 foreach ($rs as $rd) {
341 return array($onlinecontacts, $offlinecontacts, $strangers);
345 * Print $user1's contacts. Called by message_print_contact_selector()
346 * @param array $onlinecontacts $user1's contacts which are online
347 * @param array $offlinecontacts $user1's contacts which are offline
348 * @param array $strangers users which are not contacts but who have messaged $user1
349 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
350 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
351 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
352 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
353 * @param string $titletodisplay Optionally specify a title to display above the participants
354 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
357 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
358 global $CFG, $PAGE, $OUTPUT;
360 $countonlinecontacts = count($onlinecontacts);
361 $countofflinecontacts = count($offlinecontacts);
362 $countstrangers = count($strangers);
363 $isuserblocked = null;
365 if ($countonlinecontacts +
$countofflinecontacts == 0) {
366 echo html_writer
::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
369 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
371 if (!empty($titletodisplay)) {
372 message_print_heading($titletodisplay);
375 if($countonlinecontacts) {
376 /// print out list of online contacts
378 if (empty($titletodisplay)) {
379 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
382 $isuserblocked = false;
383 $isusercontact = true;
384 foreach ($onlinecontacts as $contact) {
385 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
386 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
391 if ($countofflinecontacts) {
392 /// print out list of offline contacts
394 if (empty($titletodisplay)) {
395 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
398 $isuserblocked = false;
399 $isusercontact = true;
400 foreach ($offlinecontacts as $contact) {
401 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
402 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
408 /// print out list of incoming contacts
409 if ($countstrangers) {
410 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
412 $isuserblocked = false;
413 $isusercontact = false;
414 foreach ($strangers as $stranger) {
415 if ($minmessages == 0 ||
$stranger->messagecount
>= $minmessages) {
416 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
421 echo html_writer
::end_tag('table');
423 if ($countstrangers && ($countonlinecontacts +
$countofflinecontacts == 0)) { // Extra help
424 echo html_writer
::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
429 * Print a select box allowing the user to choose to view new messages, course participants etc.
430 * Called by message_print_contact_selector()
431 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
432 * @param array $courses array of course objects. The courses the user is enrolled in.
433 * @param array $coursecontexts array of course contexts. Keyed on course id.
434 * @param int $countunreadtotal how many unread messages does the user have?
435 * @param int $countblocked how many users has the current user blocked?
436 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
439 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
441 $textlib = textlib_get_instance(); // going to use textlib services
443 if ($countunreadtotal>0) { //if there are unread messages
444 $options[MESSAGE_VIEW_UNREAD_MESSAGES
] = $strunreadmessages;
447 $str = get_string('mycontacts', 'message');
448 $options[MESSAGE_VIEW_CONTACTS
] = $str;
450 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS
] = get_string('mostrecentconversations', 'message');
451 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS
] = get_string('mostrecentnotifications', 'message');
453 if (!empty($courses)) {
454 $courses_options = array();
456 foreach($courses as $course) {
457 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id
])) {
458 //Not using short_text() as we want the end of the course name. Not the beginning.
459 if ($textlib->strlen($course->shortname
) > MESSAGE_MAX_COURSE_NAME_LENGTH
) {
460 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = '...'.$textlib->substr($course->shortname
, -MESSAGE_MAX_COURSE_NAME_LENGTH
);
462 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = $course->shortname
;
467 if (!empty($courses_options)) {
468 $options[] = array(get_string('courses') => $courses_options);
472 if ($countblocked>0) {
473 $str = get_string('blockedusers','message', $countblocked);
474 $options[MESSAGE_VIEW_BLOCKED
] = $str;
477 echo html_writer
::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
478 echo html_writer
::start_tag('fieldset');
479 echo html_writer
::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
480 echo html_writer
::end_tag('fieldset');
481 echo html_writer
::end_tag('form');
485 * Load the course contexts for all of the users courses
486 * @param array $courses array of course objects. The courses the user is enrolled in.
487 * @return array of course contexts
489 function message_get_course_contexts($courses) {
490 $coursecontexts = array();
492 foreach($courses as $course) {
493 $coursecontexts[$course->id
] = get_context_instance(CONTEXT_COURSE
, $course->id
);
496 return $coursecontexts;
500 * strip off action parameters like 'removecontact'
501 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
502 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
504 function message_remove_url_params($moodleurl) {
505 $newurl = new moodle_url($moodleurl);
506 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
507 return $newurl->out();
511 * Count the number of messages with a field having a specified value.
512 * if $field is empty then return count of the whole array
513 * if $field is non-existent then return 0
514 * @param array $messagearray array of message objects
515 * @param string $field the field to inspect on the message objects
516 * @param string $value the value to test the field against
518 function message_count_messages($messagearray, $field='', $value='') {
519 if (!is_array($messagearray)) return 0;
520 if ($field == '' or empty($messagearray)) return count($messagearray);
523 foreach ($messagearray as $message) {
524 $count +
= ($message->$field == $value) ?
1 : 0;
530 * Returns the count of unread messages for user. Either from a specific user or from all users.
531 * @param object $user1 the first user. Defaults to $USER
532 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
533 * @return int the count of $user1's unread messages
535 function message_count_unread_messages($user1=null, $user2=null) {
542 if (!empty($user2)) {
543 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
544 array($user1->id
, $user2->id
), "COUNT('id')");
546 return $DB->count_records_select('message', "useridto = ?",
547 array($user1->id
), "COUNT('id')");
552 * Count the number of users blocked by $user1
555 function message_count_blocked_users($user1=null) {
562 $sql = "SELECT count(mc.id)
563 FROM {message_contacts} mc
564 WHERE mc.userid = :userid AND mc.blocked = 1";
565 $params = array('userid' => $user1->id
);
567 return $DB->count_records_sql($sql, $params);
571 * Print the search form and search results if a search has been performed
572 * @param boolean $advancedsearch show basic or advanced search form
573 * @param object $user1 the current user
574 * @return boolean true if a search was performed
576 function message_print_search($advancedsearch = false, $user1=null) {
577 $frm = data_submitted();
579 $doingsearch = false;
581 if (confirm_sesskey()) {
582 $doingsearch = !empty($frm->combinedsubmit
) ||
!empty($frm->keywords
) ||
(!empty($frm->personsubmit
) and !empty($frm->name
));
588 if (!empty($frm->combinedsearch
)) {
589 $combinedsearchstring = $frm->combinedsearch
;
591 //$combinedsearchstring = get_string('searchcombined','message').'...';
592 $combinedsearchstring = '';
596 if ($advancedsearch) {
599 if (!empty($frm->keywords
)) {
600 $messagesearch = $frm->keywords
;
603 if (!empty($frm->name
)) {
604 $personsearch = $frm->name
;
606 include('search_advanced.html');
608 include('search.html');
611 $showicontext = false;
612 message_print_search_results($frm, $showicontext, $user1);
617 if ($advancedsearch) {
618 $personsearch = $messagesearch = '';
619 include('search_advanced.html');
621 include('search.html');
628 * Get the users recent conversations meaning all the people they've recently
629 * sent or received a message from plus the most recent message sent to or received from each other user
630 * @param object $user the current user
631 * @param int $limitfrom can be used for paging
632 * @param int $limitto can be used for paging
635 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
638 $userfields = user_picture
::fields('u', array('lastaccess'));
639 //This query retrieves the last message received from and sent to each user
640 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
641 //It then joins with some other tables to get some additional data we need
643 //message ID is used instead of timecreated as it should sort the same and will be much faster
645 //There is a separate query for read and unread queries as they are stored in different tables
646 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
647 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
648 FROM {message_read} mr
650 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
652 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
653 FROM {message_read} mr1
654 WHERE mr1.useridfrom = :userid1
655 AND mr1.notification = 0
656 GROUP BY mr1.useridto
658 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
659 FROM {message_read} mr2
660 WHERE mr2.useridto = :userid2
661 AND mr2.notification = 0
662 GROUP BY mr2.useridfrom
664 GROUP BY messages.userid
665 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
666 JOIN {user} u ON u.id = messages2.userid
667 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
668 WHERE u.deleted = '0'
669 ORDER BY mr.id DESC";
670 $params = array('userid1' => $user->id
, 'userid2' => $user->id
, 'userid3' => $user->id
);
671 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
673 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
676 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
678 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
680 WHERE m1.useridfrom = :userid1
681 AND m1.notification = 0
684 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
686 WHERE m2.useridto = :userid2
687 AND m2.notification = 0
688 GROUP BY m2.useridfrom
690 GROUP BY messages.userid
691 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
692 JOIN {user} u ON u.id = messages2.userid
693 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
694 WHERE u.deleted = '0'
696 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
698 $conversations = array();
700 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
701 //$conversation->id (the array key) is the other user's ID
702 $conversation_arrays = array($unread, $read);
703 foreach ($conversation_arrays as $conversation_array) {
704 foreach ($conversation_array as $conversation) {
705 if (empty($conversations[$conversation->id
]) ||
$conversations[$conversation->id
]->timecreated
< $conversation->timecreated
) {
706 $conversations[$conversation->id
] = $conversation;
711 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
712 //and there may be multiple conversations with the same timecreated value.
713 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
714 usort($conversations, "conversationsort");
716 return $conversations;
720 * Sort function used to order conversations
721 * @param object $a A conversation object
722 * @param object $b A conversation object
725 function conversationsort($a, $b)
727 if ($a->timecreated
== $b->timecreated
) {
730 return ($a->timecreated
> $b->timecreated
) ?
-1 : 1;
734 * Get the users recent event notifications
735 * @param object $user the current user
736 * @param int $limitfrom can be used for paging
737 * @param int $limitto can be used for paging
740 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
743 $userfields = user_picture
::fields('u', array('lastaccess'));
744 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
745 FROM {message_read} mr
746 JOIN {user} u ON u.id=mr.useridfrom
747 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
748 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
749 $params = array('userid1' => $user->id
, 'notification' => 1);
751 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
752 return $notifications;
756 * Print the user's recent conversations
757 * @param object $user1 the current user
758 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
760 function message_print_recent_conversations($user=null, $showicontext=false) {
763 echo html_writer
::start_tag('p', array('class' => 'heading'));
764 echo get_string('mostrecentconversations', 'message');
765 echo html_writer
::end_tag('p');
771 $conversations = message_get_recent_conversations($user);
773 $showotheruser = true;
774 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
778 * Print the user's recent notifications
779 * @param object $user1 the current user
781 function message_print_recent_notifications($user=null) {
784 echo html_writer
::start_tag('p', array('class' => 'heading'));
785 echo get_string('mostrecentnotifications', 'message');
786 echo html_writer
::end_tag('p');
792 $notifications = message_get_recent_notifications($user);
794 $showicontext = false;
795 $showotheruser = false;
796 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
800 * Print a list of recent messages
801 * @staticvar type $dateformat
802 * @param array $messages the messages to display
803 * @param object $user the current user
804 * @param bool $showotheruser display information on the other user?
805 * @param bool $showicontext show text next to the action icons?
807 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
811 if (empty($dateformat)) {
812 $dateformat = get_string('strftimedatetimeshort');
815 echo html_writer
::start_tag('div', array('class' => 'messagerecent'));
816 foreach ($messages as $message) {
817 echo html_writer
::start_tag('div', array('class' => 'singlemessage'));
819 if ($showotheruser) {
820 if ( $message->contactlistid
) {
821 if ($message->blocked
== 0) { /// not blocked
822 $strcontact = message_contact_link($message->id
, 'remove', true, null, $showicontext);
823 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
825 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
826 $strblock = message_contact_link($message->id
, 'unblock', true, null, $showicontext);
829 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
830 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
833 //should we show just the icon or icon and text?
834 $histicontext = 'icon';
836 $histicontext = 'both';
838 $strhistory = message_history_link($user->id
, $message->id
, true, '', '', $histicontext);
840 echo html_writer
::start_tag('span', array('class' => 'otheruser'));
842 echo html_writer
::start_tag('span', array('class' => 'pix'));
843 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID
));
844 echo html_writer
::end_tag('span');
846 echo html_writer
::start_tag('span', array('class' => 'contact'));
848 $link = new moodle_url("/message/index.php?id=$message->id");
850 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
852 echo html_writer
::end_tag('span');//end contact
854 echo $strcontact.$strblock.$strhistory;
855 echo html_writer
::end_tag('span');//end otheruser
857 $messagetoprint = null;
858 if (!empty($message->smallmessage
)) {
859 $messagetoprint = $message->smallmessage
;
861 $messagetoprint = $message->fullmessage
;
864 echo html_writer
::tag('span', userdate($message->timecreated
, $dateformat), array('class' => 'messagedate'));
865 echo html_writer
::tag('span', format_text($messagetoprint, FORMAT_HTML
), array('class' => 'themessage'));
866 echo message_format_contexturl($message);
867 echo html_writer
::end_tag('div');//end singlemessage
869 echo html_writer
::end_tag('div');//end messagerecent
873 * Add the selected user as a contact for the current user
874 * @param int $contactid the ID of the user to add as a contact
875 * @param int $blocked 1 if you wish to block the contact
876 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
877 * Otherwise returns the result of update_record() or insert_record()
879 function message_add_contact($contactid, $blocked=0) {
882 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
886 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid))) !== false) {
887 /// record already exists - we may be changing blocking status
889 if ($contact->blocked
!== $blocked) {
890 /// change to blocking status
891 $contact->blocked
= $blocked;
892 return $DB->update_record('message_contacts', $contact);
894 /// no changes to blocking status
899 /// new contact record
901 $contact->userid
= $USER->id
;
902 $contact->contactid
= $contactid;
903 $contact->blocked
= $blocked;
904 return $DB->insert_record('message_contacts', $contact, false);
910 * @param type $contactid the user ID of the contact to remove
911 * @return bool returns the result of delete_records()
913 function message_remove_contact($contactid) {
915 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
919 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
920 * @param int $contactid the user ID of the contact to unblock
921 * @return bool returns the result of delete_records()
923 function message_unblock_contact($contactid) {
925 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
930 * @param int $contactid the user ID of the user to block
932 function message_block_contact($contactid) {
933 return message_add_contact($contactid, 1);
937 * Load a user's contact record
938 * @param int $contactid the user ID of the user whose contact record you want
940 function message_get_contact($contactid) {
942 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
946 * Print the results of a message search
947 * @param mixed $frm submitted form data
948 * @param bool $showicontext show text next to action icons?
949 * @param object $currentuser the current user
952 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
953 global $USER, $DB, $OUTPUT;
955 if (empty($currentuser)) {
956 $currentuser = $USER;
959 echo html_writer
::start_tag('div', array('class' => 'mdl-left'));
961 $personsearch = false;
962 $personsearchstring = null;
963 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
964 $personsearch = true;
965 $personsearchstring = $frm->name
;
966 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
967 $personsearch = true;
968 $personsearchstring = $frm->combinedsearch
;
971 /// search for person
973 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
975 $mycourses = enrol_get_my_courses();
976 foreach ($mycourses as $mycourse) {
977 if (is_array($susers = message_search_users($mycourse->id
, $personsearchstring))) {
978 foreach ($susers as $suser) $users[$suser->id
] = $suser;
982 $users = message_search_users(SITEID
, $personsearchstring);
985 if (!empty($users)) {
986 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
987 echo get_string('userssearchresults', 'message', count($users));
988 echo html_writer
::end_tag('p');
990 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults'));
991 foreach ($users as $user) {
993 if ( $user->contactlistid
) {
994 if ($user->blocked
== 0) { /// not blocked
995 $strcontact = message_contact_link($user->id
, 'remove', true, null, $showicontext);
996 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
998 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
999 $strblock = message_contact_link($user->id
, 'unblock', true, null, $showicontext);
1002 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1003 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1006 //should we show just the icon or icon and text?
1007 $histicontext = 'icon';
1008 if ($showicontext) {
1009 $histicontext = 'both';
1011 $strhistory = message_history_link($USER->id
, $user->id
, true, '', '', $histicontext);
1013 echo html_writer
::start_tag('tr');
1015 echo html_writer
::start_tag('td', array('class' => 'pix'));
1016 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1017 echo html_writer
::end_tag('td');
1019 echo html_writer
::start_tag('td',array('class' => 'contact'));
1021 $link = new moodle_url("/message/index.php?id=$user->id");
1022 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1023 echo html_writer
::end_tag('td');
1025 echo html_writer
::tag('td', $strcontact, array('class' => 'link'));
1026 echo html_writer
::tag('td', $strblock, array('class' => 'link'));
1027 echo html_writer
::tag('td', $strhistory, array('class' => 'link'));
1029 echo html_writer
::end_tag('tr');
1031 echo html_writer
::end_tag('table');
1034 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1035 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1036 echo html_writer
::end_tag('p');
1040 // search messages for keywords
1041 $messagesearch = false;
1042 $messagesearchstring = null;
1043 if (!empty($frm->keywords
)) {
1044 $messagesearch = true;
1045 $messagesearchstring = clean_text(trim($frm->keywords
));
1046 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1047 $messagesearch = true;
1048 $messagesearchstring = clean_text(trim($frm->combinedsearch
));
1051 if ($messagesearch) {
1052 if ($messagesearchstring) {
1053 $keywords = explode(' ', $messagesearchstring);
1055 $keywords = array();
1061 if (empty($frm->keywordsoption
)) {
1062 $frm->keywordsoption
= 'allmine';
1065 switch ($frm->keywordsoption
) {
1080 $courseid = $frm->courseid
;
1087 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1089 /// get a list of contacts
1090 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id
), '', 'contactid, blocked') ) === false) {
1091 $contacts = array();
1094 /// print heading with number of results
1095 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1096 $countresults = count($messages);
1097 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS
) {
1098 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1100 echo get_string('keywordssearchresults', 'message', $countresults);
1102 echo html_writer
::end_tag('p');
1104 /// print table headings
1105 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1107 $headertdstart = html_writer
::start_tag('td', array('class' => 'messagesearchresultscol'));
1108 $headertdend = html_writer
::end_tag('td');
1109 echo html_writer
::start_tag('tr');
1110 echo $headertdstart.get_string('from').$headertdend;
1111 echo $headertdstart.get_string('to').$headertdend;
1112 echo $headertdstart.get_string('message', 'message').$headertdend;
1113 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1114 echo html_writer
::end_tag('tr');
1117 $dateformat = get_string('strftimedatetimeshort');
1118 $strcontext = get_string('context', 'message');
1119 foreach ($messages as $message) {
1121 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1122 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
1123 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
1124 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
1131 /// load up user to record
1132 if ($message->useridto
!== $USER->id
) {
1133 $userto = $DB->get_record('user', array('id' => $message->useridto
));
1134 $tocontact = (array_key_exists($message->useridto
, $contacts) and
1135 ($contacts[$message->useridto
]->blocked
== 0) );
1136 $toblocked = (array_key_exists($message->useridto
, $contacts) and
1137 ($contacts[$message->useridto
]->blocked
== 1) );
1144 /// load up user from record
1145 if ($message->useridfrom
!== $USER->id
) {
1146 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom
));
1147 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
1148 ($contacts[$message->useridfrom
]->blocked
== 0) );
1149 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
1150 ($contacts[$message->useridfrom
]->blocked
== 1) );
1153 $fromcontact = false;
1154 $fromblocked = false;
1157 /// find date string for this message
1158 $date = usergetdate($message->timecreated
);
1159 $datestring = $date['year'].$date['mon'].$date['mday'];
1161 /// print out message row
1162 echo html_writer
::start_tag('tr', array('valign' => 'top'));
1164 echo html_writer
::start_tag('td', array('class' => 'contact'));
1165 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1166 echo html_writer
::end_tag('td');
1168 echo html_writer
::start_tag('td', array('class' => 'contact'));
1169 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1170 echo html_writer
::end_tag('td');
1172 echo html_writer
::start_tag('td', array('class' => 'summary'));
1173 echo message_get_fragment($message->fullmessage
, $keywords);
1174 echo html_writer
::start_tag('div', array('class' => 'link'));
1176 //If the user clicks the context link display message sender on the left
1177 //EXCEPT if the current user is in the conversation. Current user == always on the left
1178 $leftsideuserid = $rightsideuserid = null;
1179 if ($currentuser->id
== $message->useridto
) {
1180 $leftsideuserid = $message->useridto
;
1181 $rightsideuserid = $message->useridfrom
;
1183 $leftsideuserid = $message->useridfrom
;
1184 $rightsideuserid = $message->useridto
;
1186 message_history_link($leftsideuserid, $rightsideuserid, false,
1187 $messagesearchstring, 'm'.$message->id
, $strcontext);
1188 echo html_writer
::end_tag('div');
1189 echo html_writer
::end_tag('td');
1191 echo html_writer
::tag('td', userdate($message->timecreated
, $dateformat), array('class' => 'date'));
1193 echo html_writer
::end_tag('tr');
1197 if ($blockedcount > 0) {
1198 echo html_writer
::start_tag('tr');
1199 echo html_writer
::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1200 echo html_writer
::end_tag('tr');
1202 echo html_writer
::end_tag('table');
1205 echo html_writer
::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1209 if (!$personsearch && !$messagesearch) {
1210 //they didn't enter any search terms
1211 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1214 echo html_writer
::end_tag('div');
1218 * Print information on a user. Used when printing search results.
1219 * @param object/bool $user the user to display or false if you just want $USER
1220 * @param bool $iscontact is the user being displayed a contact?
1221 * @param bool $isblocked is the user being displayed blocked?
1222 * @param bool $includeicontext include text next to the action icons?
1224 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1225 global $USER, $OUTPUT;
1227 if ($user === false) {
1228 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID
));
1230 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1236 message_contact_link($user->id
, 'remove', $return, $script, $includeicontext);
1238 message_contact_link($user->id
, 'add', $return, $script, $includeicontext);
1242 message_contact_link($user->id
, 'unblock', $return, $script, $includeicontext);
1244 message_contact_link($user->id
, 'block', $return, $script, $includeicontext);
1247 $popupoptions = array(
1248 'height' => MESSAGE_DISCUSSION_HEIGHT
,
1249 'width' => MESSAGE_DISCUSSION_WIDTH
,
1251 'location' => false,
1253 'scrollbars' => true,
1254 'resizable' => true);
1256 $link = new moodle_url("/message/index.php?id=$user->id");
1257 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1259 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1265 * Print a message contact link
1266 * @staticvar type $str
1267 * @param int $userid the ID of the user to apply to action to
1268 * @param string $linktype can be add, remove, block or unblock
1269 * @param bool $return if true return the link as a string. If false echo the link.
1270 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1271 * @param bool $text include text next to the icons?
1272 * @param bool $icon include a graphical icon?
1273 * @return string if $return is true otherwise bool
1275 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1276 global $OUTPUT, $PAGE;
1278 //hold onto the strings as we're probably creating a bunch of links
1281 if (empty($script)) {
1282 //strip off previous action params like 'removecontact'
1283 $script = message_remove_url_params($PAGE->url
);
1286 if (empty($str->blockcontact
)) {
1287 $str->blockcontact
= get_string('blockcontact', 'message');
1288 $str->unblockcontact
= get_string('unblockcontact', 'message');
1289 $str->removecontact
= get_string('removecontact', 'message');
1290 $str->addcontact
= get_string('addcontact', 'message');
1293 $command = $linktype.'contact';
1294 $string = $str->{$command};
1296 $safealttext = s($string);
1299 if (!empty($text)) {
1300 $safestring = $safealttext;
1306 switch ($linktype) {
1308 $iconpath = 't/block';
1311 $iconpath = 't/userblue';
1314 $iconpath = 'i/cross_red_big';
1318 $iconpath = 't/addgreen';
1321 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1324 $output = '<span class="'.$linktype.'contact">'.
1325 '<a href="'.$script.'&'.$command.'='.$userid.
1326 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1328 $safestring.'</a></span>';
1339 * echo or return a link to take the user to the full message history between themselves and another user
1340 * @staticvar type $strmessagehistory
1341 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1342 * @param int $userid2 the ID of the other user
1343 * @param bool $return true to return the link as a string. False to echo the link.
1344 * @param string $keywords any keywords to highlight in the message history
1345 * @param string $position anchor name to jump to within the message history
1346 * @param string $linktext optionally specify the link text
1347 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1349 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1351 static $strmessagehistory;
1353 if (empty($strmessagehistory)) {
1354 $strmessagehistory = get_string('messagehistory', 'message');
1358 $position = "#$position";
1361 $keywords = "&search=".urlencode($keywords);
1364 if ($linktext == 'icon') { // Icon only
1365 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1366 } else if ($linktext == 'both') { // Icon and standard name
1367 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1368 $fulllink .= ' '.$strmessagehistory;
1369 } else if ($linktext) { // Custom name
1370 $fulllink = $linktext;
1371 } else { // Standard name only
1372 $fulllink = $strmessagehistory;
1375 $popupoptions = array(
1379 'location' => false,
1381 'scrollbars' => true,
1382 'resizable' => true);
1384 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL
."&user1=$userid1&user2=$userid2$keywords$position");
1386 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1388 $str = '<span class="history">'.$str.'</span>';
1400 * Search through course users
1402 * If $coursid specifies the site course then this function searches
1403 * through all undeleted and confirmed users
1404 * @param int $courseid The course in question.
1405 * @param string $searchtext the text to search for
1406 * @param string $sort the column name to order by
1407 * @param string $exceptions comma separated list of user IDs to exclude
1408 * @return array An array of {@link $USER} records.
1410 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1411 global $CFG, $USER, $DB;
1413 $fullname = $DB->sql_fullname();
1415 if (!empty($exceptions)) {
1416 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1421 if (!empty($sort)) {
1422 $order = ' ORDER BY '. $sort;
1427 $ufields = user_picture
::fields('u');
1428 if (!$courseid or $courseid == SITEID
) {
1429 $params = array($USER->id
, "%$searchtext%");
1430 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1432 LEFT JOIN {message_contacts} mc
1433 ON mc.contactid = u.id AND mc.userid = ?
1434 WHERE u.deleted = '0' AND u.confirmed = '1'
1435 AND (".$DB->sql_like($fullname, '?', false).")
1439 //TODO: add enabled enrolment join here (skodak)
1440 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
1441 $contextlists = get_related_contexts_string($context);
1443 // everyone who has a role assignment in this course or higher
1444 $params = array($USER->id
, "%$searchtext%");
1445 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1447 JOIN {role_assignments} ra ON ra.userid = u.id
1448 LEFT JOIN {message_contacts} mc
1449 ON mc.contactid = u.id AND mc.userid = ?
1450 WHERE u.deleted = '0' AND u.confirmed = '1'
1451 AND ra.contextid $contextlists
1452 AND (".$DB->sql_like($fullname, '?', false).")
1461 * search a user's messages
1462 * @param array $searchterms an array of search terms (strings)
1463 * @param bool $fromme include messages from the user?
1464 * @param bool $tome include messages to the user?
1465 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1466 * @param int $userid the user ID of the current user
1467 * @return mixed An array of messages or false if no matching messages were found
1469 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1470 /// Returns a list of posts found using an array of search terms
1471 /// eg word +word -word
1473 global $CFG, $USER, $DB;
1475 /// If no userid sent then assume current user
1476 if ($userid == 0) $userid = $USER->id
;
1478 /// Some differences in SQL syntax
1479 if ($DB->sql_regex_supported()) {
1480 $REGEXP = $DB->sql_regex(true);
1481 $NOTREGEXP = $DB->sql_regex(false);
1484 $searchcond = array();
1488 //preprocess search terms to check whether we have at least 1 eligible search term
1489 //if we do we can drop words around it like 'a'
1490 $dropshortwords = false;
1491 foreach ($searchterms as $searchterm) {
1492 if (strlen($searchterm) >= 2) {
1493 $dropshortwords = true;
1497 foreach ($searchterms as $searchterm) {
1500 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1502 if ($dropshortwords && strlen($searchterm) < 2) {
1505 /// Under Oracle and MSSQL, trim the + and - operators and perform
1506 /// simpler LIKE search
1507 if (!$DB->sql_regex_supported()) {
1508 if (substr($searchterm, 0, 1) == '-') {
1511 $searchterm = trim($searchterm, '+-');
1514 if (substr($searchterm,0,1) == "+") {
1515 $searchterm = substr($searchterm,1);
1516 $searchterm = preg_quote($searchterm, '|');
1517 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1518 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1520 } else if (substr($searchterm,0,1) == "-") {
1521 $searchterm = substr($searchterm,1);
1522 $searchterm = preg_quote($searchterm, '|');
1523 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1524 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1527 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1528 $params['ss'.$i] = "%$searchterm%";
1532 if (empty($searchcond)) {
1533 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1534 $params['ss1'] = "%";
1536 $searchcond = implode(" AND ", $searchcond);
1539 /// There are several possibilities
1540 /// 1. courseid = SITEID : The admin is searching messages by all users
1541 /// 2. courseid = ?? : A teacher is searching messages by users in
1542 /// one of their courses - currently disabled
1543 /// 3. courseid = none : User is searching their own messages;
1544 /// a. Messages from user
1545 /// b. Messages to user
1546 /// c. Messages to and from user
1548 if ($courseid == SITEID
) { /// admin is searching all messages
1549 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1550 FROM {message_read} m
1551 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1552 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1554 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1556 } else if ($courseid !== 'none') {
1557 /// This has not been implemented due to security concerns
1559 $m_unread = array();
1563 if ($fromme and $tome) {
1564 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1565 $params['userid1'] = $userid;
1566 $params['userid2'] = $userid;
1568 } else if ($fromme) {
1569 $searchcond .= " AND m.useridfrom=:userid";
1570 $params['userid'] = $userid;
1573 $searchcond .= " AND m.useridto=:userid";
1574 $params['userid'] = $userid;
1577 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1578 FROM {message_read} m
1579 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1580 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1582 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1586 /// The keys may be duplicated in $m_read and $m_unread so we can't
1587 /// do a simple concatenation
1589 foreach ($m_read as $m) {
1592 foreach ($m_unread as $m) {
1596 return (empty($messages)) ?
false : $messages;
1600 * Given a message object that we already know has a long message
1601 * this function truncates the message nicely to the first
1602 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1603 * @param string $message the message
1604 * @param int $minlength the minimum length to trim the message to
1605 * @return string the shortened message
1607 function message_shorten_message($message, $minlength = 0) {
1610 $length = strlen($message);
1614 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
1617 for ($i=0; $i<$length; $i++
) {
1618 $char = $message[$i];
1630 if ($char == '.' or $char == ' ') {
1640 if ($count > $minlength) {
1650 return substr($message, 0, $truncate);
1655 * Given a string and an array of keywords, this function looks
1656 * for the first keyword in the string, and then chops out a
1657 * small section from the text that shows that word in context.
1658 * @param string $message the text to search
1659 * @param array $keywords array of keywords to find
1661 function message_get_fragment($message, $keywords) {
1664 $halfsize = (int)($fullsize/2);
1666 $message = strip_tags($message);
1668 foreach ($keywords as $keyword) { // Just get the first one
1669 if ($keyword !== '') {
1673 if (empty($keyword)) { // None found, so just return start of message
1674 return message_shorten_message($message, 30);
1677 $leadin = $leadout = '';
1679 /// Find the start of the fragment
1681 $length = strlen($message);
1683 $pos = strpos($message, $keyword);
1684 if ($pos > $halfsize) {
1685 $start = $pos - $halfsize;
1688 /// Find the end of the fragment
1689 $end = $start +
$fullsize;
1690 if ($end > $length) {
1696 /// Pull out the fragment and format it
1698 $fragment = substr($message, $start, $end - $start);
1699 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1704 * Retrieve the messages between two users
1705 * @param object $user1 the current user
1706 * @param object $user2 the other user
1707 * @param int $limitnum the maximum number of messages to retrieve
1708 * @param bool $viewingnewmessages are we currently viewing new messages?
1710 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1713 $messages = array();
1715 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1716 //desc to get the last $limitnum messages then flip the order in php
1722 $notificationswhere = null;
1723 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1724 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications
) {
1725 $notificationswhere = 'AND notification=0';
1728 //prevent notifications of your own actions appearing in your own message history
1729 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1731 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1732 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1733 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1734 "timecreated $sort", '*', 0, $limitnum)) {
1735 foreach ($messages_read as $message) {
1736 $messages[$message->timecreated
] = $message;
1739 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1740 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1741 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1742 "timecreated $sort", '*', 0, $limitnum)) {
1743 foreach ($messages_new as $message) {
1744 $messages[$message->timecreated
] = $message;
1748 //if we only want the last $limitnum messages
1750 $messagecount = count($messages);
1751 if ($limitnum>0 && $messagecount>$limitnum) {
1752 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1759 * Print the message history between two users
1760 * @param object $user1 the current user
1761 * @param object $user2 the other user
1762 * @param string $search search terms to highlight
1763 * @param int $messagelimit maximum number of messages to return
1764 * @param string $messagehistorylink the html for the message history link or false
1765 * @param bool $viewingnewmessages are we currently viewing new messages?
1767 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1768 global $CFG, $OUTPUT;
1770 echo $OUTPUT->box_start('center');
1771 echo html_writer
::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1772 echo html_writer
::start_tag('tr');
1774 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1775 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID
));
1776 echo html_writer
::tag('div', fullname($user1), array('class' => 'heading'));
1777 echo html_writer
::end_tag('td');
1779 echo html_writer
::start_tag('td', array('align' => 'center'));
1780 echo html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1781 echo html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1782 echo html_writer
::end_tag('td');
1784 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1785 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID
));
1786 echo html_writer
::tag('div', fullname($user2), array('class' => 'heading'));
1788 if (isset($user2->iscontact
) && isset($user2->isblocked
)) {
1789 $incontactlist = $user2->iscontact
;
1790 $isblocked = $user2->isblocked
;
1796 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1797 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1798 $useractionlinks = $strcontact.' |'.$strblock;
1800 echo html_writer
::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1803 echo html_writer
::end_tag('td');
1804 echo html_writer
::end_tag('tr');
1805 echo html_writer
::end_tag('table');
1806 echo $OUTPUT->box_end();
1808 if (!empty($messagehistorylink)) {
1809 echo $messagehistorylink;
1812 /// Get all the messages and print them
1813 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1814 $tablecontents = '';
1816 $current = new stdClass();
1817 $current->mday
= '';
1818 $current->month
= '';
1819 $current->year
= '';
1820 $messagedate = get_string('strftimetime');
1821 $blockdate = get_string('strftimedaydate');
1822 foreach ($messages as $message) {
1823 if ($message->notification
) {
1824 $notificationclass = ' notification';
1826 $notificationclass = null;
1828 $date = usergetdate($message->timecreated
);
1829 if ($current->mday
!= $date['mday'] |
$current->month
!= $date['month'] |
$current->year
!= $date['year']) {
1830 $current->mday
= $date['mday'];
1831 $current->month
= $date['month'];
1832 $current->year
= $date['year'];
1834 $datestring = html_writer
::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1835 $tablecontents .= html_writer
::tag('div', $datestring, array('class' => 'mdl-align heading'));
1837 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated
, $blockdate), 4, 'mdl-align');
1840 $formatted_message = $side = null;
1841 if ($message->useridfrom
== $user1->id
) {
1842 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1845 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1848 $tablecontents .= html_writer
::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1851 echo html_writer
::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1853 echo html_writer
::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1858 * Format a message for display in the message history
1859 * @param object $message the message object
1860 * @param string $format optional date format
1861 * @param string $keywords keywords to highlight
1862 * @param string $class CSS class to apply to the div around the message
1863 * @return string the formatted message
1865 function message_format_message($message, $format='', $keywords='', $class='other') {
1869 //if we haven't previously set the date format or they've supplied a new one
1870 if ( empty($dateformat) ||
(!empty($format) && $dateformat != $format) ) {
1872 $dateformat = $format;
1874 $dateformat = get_string('strftimedatetimeshort');
1877 $time = userdate($message->timecreated
, $dateformat);
1878 $options = new stdClass();
1879 $options->para
= false;
1881 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1882 if (!empty($message->smallmessage
)) {
1883 $messagetext = $message->smallmessage
;
1885 $messagetext = $message->fullmessage
;
1887 if ($message->fullmessageformat
== FORMAT_HTML
) {
1888 //dont escape html tags by calling s() if html format or they will display in the UI
1889 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat
, $options));
1891 $messagetext = format_text(s($messagetext), $message->fullmessageformat
, $options);
1894 $messagetext .= message_format_contexturl($message);
1897 $messagetext = highlight($keywords, $messagetext);
1900 return '<div class="message '.$class.'"><a name="m'.$message->id
.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1904 * Format a the context url and context url name of a message for display
1905 * @param object $message the message object
1906 * @return string the formatted string
1908 function message_format_contexturl($message) {
1911 if (!empty($message->contexturl
)) {
1912 $displaytext = null;
1913 if (!empty($message->contexturlname
)) {
1914 $displaytext= $message->contexturlname
;
1916 $displaytext= $message->contexturl
;
1918 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
1919 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
1920 $s .= html_writer
::end_tag('div');
1927 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1928 * @param object $userfrom the message sender
1929 * @param object $userto the message recipient
1930 * @param string $message the message
1931 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1932 * @return int|false the ID of the new message or false
1934 function message_post_message($userfrom, $userto, $message, $format) {
1935 global $SITE, $CFG, $USER;
1937 $eventdata = new stdClass();
1938 $eventdata->component
= 'moodle';
1939 $eventdata->name
= 'instantmessage';
1940 $eventdata->userfrom
= $userfrom;
1941 $eventdata->userto
= $userto;
1943 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
1944 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
1946 if ($format == FORMAT_HTML
) {
1947 $eventdata->fullmessage
= '';
1948 $eventdata->fullmessagehtml
= $message;
1950 $eventdata->fullmessage
= $message;
1951 $eventdata->fullmessagehtml
= '';
1954 $eventdata->fullmessageformat
= $format;
1955 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
1957 $s = new stdClass();
1958 $s->sitename
= $SITE->shortname
;
1959 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
1961 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
1962 if (!empty($eventdata->fullmessage
)) {
1963 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1965 if (!empty($eventdata->fullmessagehtml
)) {
1966 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1969 $eventdata->timecreated
= time();
1970 return message_send($eventdata);
1975 * Returns a list of all user ids who have used messaging in the site
1976 * This was the simple way to code the SQL ... is it going to blow up
1977 * on large datasets?
1979 function message_get_participants() {
1982 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1983 UNION SELECT useridto as id,1 FROM {message}
1984 UNION SELECT useridfrom as id,1 FROM {message_read}
1985 UNION SELECT useridto as id,1 FROM {message_read}
1986 UNION SELECT userid as id,1 FROM {message_contacts}
1987 UNION SELECT contactid as id,1 from {message_contacts}");
1991 * Print a row of contactlist displaying user picture, messages waiting and
1993 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
1994 * @param bool $incontactlist is the user a contact of ours?
1995 * @param bool $isblocked is the user blocked?
1996 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
1997 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
1998 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2000 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2001 global $OUTPUT, $USER;
2002 $fullname = fullname($contact);
2003 $fullnamelink = $fullname;
2006 if (!empty($selecteduser) && $contact->id
== $selecteduser->id
) {
2007 $linkclass = 'messageselecteduser';
2010 /// are there any unread messages for this contact?
2011 if ($contact->messagecount
> 0 ){
2012 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount
.')</strong>';
2015 $strcontact = $strblock = $strhistory = null;
2017 if ($showactionlinks) {
2018 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2019 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2020 $strhistory = message_history_link($USER->id
, $contact->id
, true, '', '', 'icon');
2023 echo html_writer
::start_tag('tr');
2024 echo html_writer
::start_tag('td', array('class' => 'pix'));
2025 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID
));
2026 echo html_writer
::end_tag('td');
2028 echo html_writer
::start_tag('td', array('class' => 'contact'));
2030 $popupoptions = array(
2031 'height' => MESSAGE_DISCUSSION_HEIGHT
,
2032 'width' => MESSAGE_DISCUSSION_WIDTH
,
2034 'location' => false,
2036 'scrollbars' => true,
2037 'resizable' => true);
2039 $link = $action = null;
2040 if (!empty($selectcontacturl)) {
2041 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id
);
2043 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2044 $link = new moodle_url("/message/index.php?id=$contact->id");
2045 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2047 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2049 echo html_writer
::end_tag('td');
2051 echo html_writer
::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2053 echo html_writer
::end_tag('tr');
2057 * Constructs the add/remove contact link to display next to other users
2058 * @param bool $incontactlist is the user a contact
2059 * @param bool $isblocked is the user blocked
2060 * @param type $contact contact object
2061 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2062 * @param bool $text include text next to the icons?
2063 * @param bool $icon include a graphical icon?
2066 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2070 $strcontact = message_contact_link($contact->id
, 'remove', true, $script, $text, $icon);
2071 } else if ($isblocked) {
2072 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2074 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2081 * Constructs the block contact link to display next to other users
2082 * @param bool $incontactlist is the user a contact
2083 * @param bool $isblocked is the user blocked
2084 * @param type $contact contact object
2085 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2086 * @param bool $text include text next to the icons?
2087 * @param bool $icon include a graphical icon?
2090 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2093 //commented out to allow the user to block a contact without having to remove them first
2094 /*if ($incontactlist) {
2098 $strblock = ' '.message_contact_link($contact->id
, 'unblock', true, $script, $text, $icon);
2100 $strblock = ' '.message_contact_link($contact->id
, 'block', true, $script, $text, $icon);
2107 * Moves messages from a particular user from the message table (unread messages) to message_read
2108 * This is typically only used when a user is deleted
2109 * @param object $userid User id
2110 * @return boolean success
2112 function message_move_userfrom_unread2read($userid) {
2115 // move all unread messages from message table to message_read
2116 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2117 foreach ($messages as $message) {
2118 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2125 * marks ALL messages being sent from $fromuserid to $touserid as read
2126 * @param int $touserid the id of the message recipient
2127 * @param int $fromuserid the id of the message sender
2130 function message_mark_messages_read($touserid, $fromuserid){
2133 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2134 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2136 foreach ($messages as $message) {
2137 message_mark_message_read($message, time());
2144 * Mark a single message as read
2145 * @param message an object with an object property ie $message->id which is an id in the message table
2146 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2147 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2148 * @return int the ID of the message in the message_read table
2150 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2153 $message->timeread
= $timeread;
2155 $messageid = $message->id
;
2156 unset($message->id
);//unset because it will get a new id on insert into message_read
2158 //If any processors have pending actions abort them
2159 if (!$messageworkingempty) {
2160 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2162 $messagereadid = $DB->insert_record('message_read', $message);
2163 $DB->delete_records('message', array('id' => $messageid));
2164 return $messagereadid;
2168 * A helper function that prints a formatted heading
2169 * @param string $title the heading to display
2170 * @param int $colspan
2172 function message_print_heading($title, $colspan=3) {
2173 echo html_writer
::start_tag('tr');
2174 echo html_writer
::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2175 echo html_writer
::end_tag('tr');