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');
29 define ('MESSAGE_SHORTLENGTH', 300);
30 define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
32 define ('MESSAGE_DISCUSSION_WIDTH',600);
33 define ('MESSAGE_DISCUSSION_HEIGHT',500);
35 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
37 define ('CONTACT_ID','id');
39 define('MESSAGE_HISTORY_SHORT',0);
40 define('MESSAGE_HISTORY_ALL',1);
42 //some constants used as function arguments. Just to make function calls a bit more understandable
43 define('IS_CONTACT',true);
44 define('IS_NOT_CONTACT',false);
46 define('IS_BLOCKED',true);
47 define('IS_NOT_BLOCKED',false);
49 define('VIEW_UNREAD_MESSAGES','unread');
50 define('VIEW_CONTACTS','contacts');
51 define('VIEW_BLOCKED','blockedusers');
52 define('VIEW_COURSE','course_');
54 define('SHOW_ACTION_LINKS_IN_CONTACT_LIST', true);
56 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
58 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
59 $CFG->message_contacts_refresh = 60;
61 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
62 $CFG->message_chat_refresh = 5;
64 if (!isset($CFG->message_offline_time)) {
65 $CFG->message_offline_time = 300;
68 function message_print_contact_selector($countunreadtotal, $usergroup, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks) {
71 echo html_writer::start_tag('div', array('class'=>'contactselector mdl-align'));
73 //if 0 unread messages and they've requested unread messages then show contacts
74 if ($countunreadtotal==0 && $usergroup==VIEW_UNREAD_MESSAGES) {
75 $usergroup = VIEW_CONTACTS;
78 //if they have no blocked users and they've requested blocked users switch them over to contacts
79 if (count($blockedusers)==0 && $usergroup==VIEW_BLOCKED) {
80 $usergroup = VIEW_CONTACTS;
83 $onlyactivecourses = true;
84 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
85 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
87 $strunreadmessages = null;
88 if ($countunreadtotal>0) { //if there are unread messages
89 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
92 message_print_usergroup_selector($usergroup, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
96 if ($usergroup==VIEW_UNREAD_MESSAGES) {
97 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
98 } else if ($usergroup==VIEW_CONTACTS) {
99 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
100 } else if ($usergroup==VIEW_BLOCKED) {
101 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
102 } else if (substr($usergroup, 0, 7)==VIEW_COURSE) {
103 $courseidtoshow = intval(substr($usergroup, 7));
105 if (!empty($courseidtoshow)
106 && array_key_exists($courseidtoshow, $coursecontexts)
107 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
109 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks);
111 //shouldn't get here. User trying to access a course they're not in perhaps.
112 add_to_log(SITEID, 'message', 'view', 'index.php', $usergroup);
116 echo html_writer::start_tag('form', array('action'=>'contacts.php?advanced=1'));
117 echo html_writer::start_tag('fieldset');
118 $managebuttonclass = 'hiddenelement';
119 if ($usergroup == VIEW_CONTACTS) {
120 $managebuttonclass = 'visible';
122 $strmanagecontacts = get_string('search','message');
123 echo html_writer::empty_tag('input', array('type'=>'submit','value'=>$strmanagecontacts,'class'=>$managebuttonclass));
124 echo html_writer::end_tag('fieldset');
125 echo html_writer::end_tag('form');
126 echo html_writer::end_tag('div');
129 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null) {
132 $participants = get_enrolled_users($context);
134 echo '<table id="message_participants" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
136 if (!empty($titletodisplay)) {
137 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
140 if (empty($titletodisplay)) {
141 echo '<tr><td colspan="3" class="heading">';
142 echo get_string('participants');
146 //todo these need to come from somewhere if the course participants list is to show users with unread messages
149 foreach ($participants as $participant) {
150 if ($participant->id != $USER->id) {
151 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
152 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks);
155 //$participants->close();
160 function message_get_blocked_users($user1=null, &$user2=null) {
167 if (!empty($user2)) {
168 $user2->isblocked = false;
171 $userfields = user_picture::fields('u', array('lastaccess'));
172 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
173 FROM {message_contacts} mc
174 JOIN {user} u ON u.id = mc.contactid
175 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
176 WHERE mc.userid = :user1id2 AND mc.blocked = 1
178 ORDER BY u.firstname ASC";
179 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1'=>$user1->id, 'user1id2'=>$user1->id));
181 $blockedusers = array();
183 foreach($rs as $rd) {
184 $blockedusers[] = $rd;
186 if (!empty($user2) && $user2->id==$rd->id) {
187 $user2->isblocked = true;
194 return $blockedusers;
197 function message_print_blocked_users(&$blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null) {
200 $countblocked = count($blockedusers);
202 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
204 if (!empty($titletodisplay)) {
205 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
209 echo '<tr><td colspan="3" class="heading">';
210 echo get_string('blockedusers', 'message', $countblocked);
213 foreach ($blockedusers as $blockeduser) {
214 message_print_contactlist_user($blockeduser, IS_NOT_CONTACT, IS_BLOCKED, $contactselecturl, $showactionlinks);
221 function message_get_contacts($user1=null, &$user2=null) {
222 global $DB, $CFG, $USER;
228 if (!empty($user2)) {
229 $user2->iscontact = false;
232 $timetoshowusers = 300; //Seconds default
233 if (isset($CFG->block_online_users_timetosee)) {
234 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
237 // time which a user is counting as being active since
238 $timefrom = time()-$timetoshowusers;
240 // people in our contactlist who are online
241 $onlinecontacts = array();
242 // people in our contactlist who are offline
243 $offlinecontacts = array();
244 // people who are not in our contactlist but have sent us a message
245 $strangers = array();
247 $userfields = user_picture::fields('u', array('lastaccess'));
249 // get all in our contactlist who are not blocked in our contact list
250 // and count messages we have waiting from each of them
251 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
252 FROM {message_contacts} mc
253 JOIN {user} u ON u.id = mc.contactid
254 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
255 WHERE mc.userid = ? AND mc.blocked = 0
257 ORDER BY u.firstname ASC";
259 if ($rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id))){
262 if($rd->lastaccess >= $timefrom){
263 // they have been active recently, so are counted online
264 $onlinecontacts[] = $rd;
267 $offlinecontacts[] = $rd;
270 if (!empty($user2) && $user2->id==$rd->id) {
271 $user2->iscontact = true;
278 // get messages from anyone who isn't in our contact list and count the number
279 // of messages we have from each of them
280 $strangersql = "SELECT $userfields, count(m.id) as messagecount
282 JOIN {user} u ON u.id = m.useridfrom
283 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
284 WHERE mc.id IS NULL AND m.useridto = ?
286 ORDER BY u.firstname ASC";
288 if($rs = $DB->get_recordset_sql($strangersql, array($USER->id))){
296 return array($onlinecontacts, $offlinecontacts, $strangers);
299 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refresh=true, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null) {
300 global $CFG, $PAGE, $OUTPUT;
302 $countonlinecontacts = count($onlinecontacts);
303 $countofflinecontacts = count($offlinecontacts);
304 $countstrangers = count($strangers);
306 if ($countonlinecontacts + $countofflinecontacts == 0) {
307 echo '<div class="heading">';
308 print_string('contactlistempty', 'message');
310 //echo '<div class="note">';
311 //print_string('addsomecontacts', 'message', message_remove_url_params($PAGE->url).'?tab=search');
315 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
317 if (!empty($titletodisplay)) {
318 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
321 if($countonlinecontacts) {
322 /// print out list of online contacts
324 if (empty($titletodisplay)) {
325 echo '<tr><td colspan="3" class="heading">';
326 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
330 foreach ($onlinecontacts as $contact) {
331 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
332 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
337 if ($countofflinecontacts) {
338 /// print out list of offline contacts
340 if (empty($titletodisplay)) {
341 echo '<tr><td colspan="3" class="heading">';
342 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
346 foreach ($offlinecontacts as $contact) {
347 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
348 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
351 echo '<tr><td colspan="3"> </td></tr>';
354 /// print out list of incoming contacts
355 if ($countstrangers) {
356 echo '<tr><td colspan="3" class="heading">';
357 echo get_string('incomingcontacts', 'message', $countstrangers);
360 foreach ($strangers as $stranger) {
361 if ($minmessages==0 || $stranger->messagecount>=$minmessages) {
362 message_print_contactlist_user($stranger, IS_NOT_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
369 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
370 echo '<div class="note">(';
371 print_string('addsomecontactsincoming', 'message');
378 $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
380 echo $OUTPUT->container_start('messagejsautorefresh note center');
381 echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
382 echo $OUTPUT->container_end();
384 echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
385 echo $OUTPUT->single_button(message_remove_url_params($PAGE->url), get_string('refresh'));
386 echo $OUTPUT->container_end();
390 function message_print_usergroup_selector($usergroup, &$courses, &$coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
391 $strblockedusers = null;
394 if ($countunreadtotal>0) { //if there are unread messages
395 $options[VIEW_UNREAD_MESSAGES] = $strunreadmessages;
398 if ($countblocked>0) {
399 $strblockedusers = get_string('blockedusers','message', $countblocked);
400 $options[VIEW_BLOCKED] = $strblockedusers;
403 $strcontacts = get_string('mycontacts', 'message');
404 $options[VIEW_CONTACTS] = $strcontacts;
406 if (!empty($courses)) {
407 $courses_options = array();
409 foreach($courses as $course) {
410 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
411 $courses_options[VIEW_COURSE.$course->id] = $course->shortname;
415 if (!empty($courses_options)) {
416 $options[] = array(get_string('courses')=>$courses_options);
420 echo html_writer::start_tag('form', array('id'=>'usergroupform','method'=>'get','action'=>''));
421 echo html_writer::start_tag('fieldset');
422 echo html_writer::select($options, 'usergroup', $usergroup, false, array('id'=>'usergroup','onchange'=>'this.form.submit()'));
423 echo html_writer::end_tag('fieldset');
424 echo html_writer::end_tag('form');
427 function message_get_course_contexts(&$courses) {
428 $coursecontexts = array();
430 foreach($courses as $course) {
431 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
434 return $coursecontexts;
438 * strip off action parameters like 'removecontact'
440 function message_remove_url_params($moodleurl) {
441 $newurl = new moodle_url($moodleurl);
442 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
443 return $newurl->out();
447 /// $messagearray is an array of objects
448 /// $field is a valid property of object
449 /// $value is the value $field should equal to be counted
450 /// if $field is empty then return count of the whole array
451 /// if $field is non-existent then return 0;
452 function message_count_messages($messagearray, $field='', $value='') {
453 if (!is_array($messagearray)) return 0;
454 if ($field == '' or empty($messagearray)) return count($messagearray);
457 foreach ($messagearray as $message) {
458 $count += ($message->$field == $value) ? 1 : 0;
464 * Returns the count of unread messages for user. Either from a specific user or from all users.
465 * @global <type> $USER
467 * @param object $user1 the first user. Defaults to $USER
468 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
469 * @return int the count of $user1's unread messages
471 function message_count_unread_messages($user1=null, $user2=null) {
478 if (!empty($user2)) {
479 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
480 array($user1->id, $user2->id), "COUNT('id')");
482 return $DB->count_records_select('message', "useridto = ?",
483 array($user1->id), "COUNT('id')");
487 function message_count_blocked_users($user1=null) {
494 $sql = "SELECT count(mc.id)
495 FROM {message_contacts} mc
496 WHERE mc.userid = :userid AND mc.blocked = 1";
497 $params = array('userid'=>$user1->id);
499 return $DB->count_records_sql($sql, $params);
504 * @global <type> $USER
505 * @global <type> $PAGE
506 * @global <type> $OUTPUT
507 * @param boolean advancedsearch show basic or advanced search form
508 * @return boolean was a search performed?
510 function message_print_search($advancedsearch = false, $user1=null) {
511 global $USER, $PAGE, $OUTPUT;
513 $frm = data_submitted();
515 $doingsearch = false;
517 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
520 if (!empty($frm->combinedsearch)) {
521 $combinedsearchstring = $frm->combinedsearch;
523 $combinedsearchstring = get_string('searchcombined','message').'...';
526 $PAGE->requires->js_init_call('M.core_message.init_search_page', array($combinedsearchstring));
529 if ($advancedsearch) {
532 if (!empty($frm->keywords)) {
533 $messagesearch = $frm->keywords;
536 if (!empty($frm->name)) {
537 $personsearch = $frm->name;
539 include('search_advanced.html');
541 include('search.html');
544 $showicontext = false;
545 message_print_search_results($frm, $showicontext, $user1);
550 /// unfinished buggy code disabled in search.html anyway
551 // find all courses this use has readallmessages capabilities in
552 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
553 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
554 $cs = '<select name="courseselect">';
555 foreach ($teachers as $tcourse) {
556 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
562 if ($advancedsearch) {
563 $personsearch = $messagesearch = '';
564 include('search_advanced.html');
566 include('search.html');
572 function message_print_settings() {
573 global $USER, $OUTPUT, $PAGE;
575 if ($frm = data_submitted() and confirm_sesskey()) {
578 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
579 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
581 set_user_preferences($pref);
583 redirect(message_remove_url_params($PAGE->url), get_string('settingssaved', 'message'), 1);
586 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
587 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
589 include('settings.html');
594 function message_add_contact($contactid, $blocked=0) {
597 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
601 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
602 /// record already exists - we may be changing blocking status
604 if ($contact->blocked !== $blocked) {
605 /// change to blocking status
606 $contact->blocked = $blocked;
607 return $DB->update_record('message_contacts', $contact);
609 /// no changes to blocking status
614 /// new contact record
616 $contact->userid = $USER->id;
617 $contact->contactid = $contactid;
618 $contact->blocked = $blocked;
619 return $DB->insert_record('message_contacts', $contact, false);
623 function message_remove_contact($contactid) {
625 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
628 function message_unblock_contact($contactid) {
630 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
633 function message_block_contact($contactid) {
634 return message_add_contact($contactid, 1);
637 function message_get_contact($contactid) {
639 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
644 function message_print_search_results($frm, $showicontext=false, $user1=null) {
645 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
651 echo '<div class="mdl-left">';
653 $personsearch = false;
654 $personsearchstring = null;
655 if (!empty($frm->personsubmit) and !empty($frm->name)) {
656 $personsearch = true;
657 $personsearchstring = $frm->name;
658 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
659 $personsearch = true;
660 $personsearchstring = $frm->combinedsearch;
663 /// search for person
665 if (optional_param('mycourses', 0, PARAM_BOOL)) {
667 $mycourses = enrol_get_my_courses();
668 foreach ($mycourses as $mycourse) {
669 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
670 foreach ($susers as $suser) $users[$suser->id] = $suser;
674 $users = message_search_users(SITEID, $personsearchstring);
677 if (!empty($users)) {
678 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
679 echo get_string('userssearchresults', 'message', count($users));
680 echo html_writer::end_tag('p');
682 echo '<table class="messagesearchresults">';
683 foreach ($users as $user) {
685 if ( $user->contactlistid ) {
686 if ($user->blocked == 0) { /// not blocked
687 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
688 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
690 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
691 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
694 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
695 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
698 //should we show just the icon or icon and text?
699 $histicontext = 'icon';
701 $histicontext = 'both';
703 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
705 echo '<tr><td class="pix">';
706 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
708 echo '<td class="contact">';
709 $popupoptions = array(
710 'height' => MESSAGE_DISCUSSION_HEIGHT,
711 'width' => MESSAGE_DISCUSSION_WIDTH,
715 'scrollbars' => true,
716 'resizable' => true);
718 //$link = new moodle_url("/message/discussion.php?id=$user->id");
719 $link = new moodle_url("/message/index.php?id=$user->id");
720 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
722 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
726 echo '<td class="link">'.$strcontact.'</td>';
727 echo '<td class="link">'.$strblock.'</td>';
728 echo '<td class="link">'.$strhistory.'</td>';
734 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
735 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
736 echo html_writer::end_tag('p');
740 // search messages for keywords
741 $messagesearch = false;
742 $messagesearchstring = null;
743 if (!empty($frm->keywords)) {
744 $messagesearch = true;
745 $messagesearchstring = clean_text(trim($frm->keywords));
746 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
747 $messagesearch = true;
748 $messagesearchstring = clean_text(trim($frm->combinedsearch));
751 if ($messagesearch) {
752 if ($messagesearchstring) {
753 $keywords = explode(' ', $messagesearchstring);
761 if (empty($frm->keywordsoption)) {
762 $frm->keywordsoption = 'allmine';
765 switch ($frm->keywordsoption) {
780 $courseid = $frm->courseid;
787 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
789 /// get a list of contacts
790 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
794 /// print heading with number of results
795 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
796 $countresults = count($messages);
797 if ($countresults==MESSAGE_SEARCH_MAX_RESULTS) {
798 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
800 echo get_string('keywordssearchresults', 'message', $countresults).' ("'.s($messagesearchstring).'")';
802 echo html_writer::end_tag('p');
804 /// print table headings
805 echo '<table class="messagesearchresults" cellspacing="0">';
807 $headertdstart = html_writer::start_tag('td', array('class'=>'messagesearchresultscol'));
808 $headertdend = html_writer::end_tag('td');
810 echo $headertdstart.get_string('from').$headertdend;
811 echo $headertdstart.get_string('to').$headertdend;
812 echo $headertdstart.get_string('message', 'message').$headertdend;
813 echo $headertdstart.get_string('timesent', 'message').$headertdend;
817 $dateformat = get_string('strftimedatetimeshort');
818 $strcontext = get_string('context', 'message');
819 foreach ($messages as $message) {
821 /// ignore messages to and from blocked users unless $frm->includeblocked is set
822 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
823 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
824 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
831 /// load up user to record
832 if ($message->useridto !== $USER->id) {
833 $userto = $DB->get_record('user', array('id'=>$message->useridto));
834 $tocontact = (array_key_exists($message->useridto, $contacts) and
835 ($contacts[$message->useridto]->blocked == 0) );
836 $toblocked = (array_key_exists($message->useridto, $contacts) and
837 ($contacts[$message->useridto]->blocked == 1) );
844 /// load up user from record
845 if ($message->useridfrom !== $USER->id) {
846 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
847 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
848 ($contacts[$message->useridfrom]->blocked == 0) );
849 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
850 ($contacts[$message->useridfrom]->blocked == 1) );
853 $fromcontact = false;
854 $fromblocked = false;
857 /// find date string for this message
858 $date = usergetdate($message->timecreated);
859 $datestring = $date['year'].$date['mon'].$date['mday'];
861 /// print out message row
862 echo '<tr valign="top">';
863 echo '<td class="contact">';
864 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
866 echo '<td class="contact">';
867 message_print_user($userto, $tocontact, $toblocked, $showicontext);
869 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
870 echo '<br /><div class="link">';
872 //find the user involved that isn't the current user
874 if ($user1->id == $message->useridto) {
875 $user2id = $message->useridfrom;
877 $user2id = $message->useridto;
879 message_history_link($user1->id, $user2id, false,
880 $messagesearchstring, 'm'.$message->id, $strcontext);
883 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
888 if ($blockedcount > 0) {
889 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
894 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', 0).' ("'.s($messagesearchstring).'")</p>';
898 if (!$personsearch && !$messagesearch) {
899 //they didn't enter any search terms
900 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
904 echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('tab' => 'search')), get_string('newsearch', 'message'));
910 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
911 global $USER, $OUTPUT;
913 if ($user === false) {
914 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
916 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
922 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
924 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
928 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
930 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
934 $popupoptions = array(
935 'height' => MESSAGE_DISCUSSION_HEIGHT,
936 'width' => MESSAGE_DISCUSSION_WIDTH,
940 'scrollbars' => true,
941 'resizable' => true);
943 //$link = new moodle_url("/message/discussion.php?id=$user->id");
944 $link = new moodle_url("/message/index.php?id=$user->id");
945 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
947 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
953 /// linktype can be: add, remove, block, unblock
954 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
955 global $USER, $CFG, $OUTPUT, $PAGE;
957 //hold onto the strings as we're probably creating a bunch of links
960 if (empty($script)) {
961 //strip off previous action params like 'removecontact'
962 $theurl = message_remove_url_params($PAGE->url);
964 if (strpos($theurl, '?')===false) {
965 $script = $theurl.'?tab=contacts';
967 $script = $theurl.'&tab=contacts';
971 if (empty($str->blockcontact)) {
972 $str->blockcontact = get_string('blockcontact', 'message');
973 $str->unblockcontact = get_string('unblockcontact', 'message');
974 $str->removecontact = get_string('removecontact', 'message');
975 $str->addcontact = get_string('addcontact', 'message');
978 $command = $linktype.'contact';
979 $string = $str->{$command};
981 $safealttext = s($string);
985 $safestring = $safealttext;
993 $iconpath = 't/block';
996 $iconpath = 't/userblue';
999 $iconpath = 'i/cross_red_big';
1003 $iconpath = 't/addgreen';
1006 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1009 $output = '<span class="'.$linktype.'contact">'.
1010 '<a href="'.$script.'&'.$command.'='.$userid.
1011 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1013 $safestring.'</a></span>';
1023 function message_history_link($userid1, $userid2, $returnstr=false, $keywords='', $position='', $linktext='') {
1024 global $USER, $CFG, $OUTPUT;
1026 static $strmessagehistory;
1028 if (empty($strmessagehistory)) {
1029 $strmessagehistory = get_string('messagehistory', 'message');
1033 $position = "#$position";
1036 $keywords = "&search=".urlencode($keywords);
1039 if ($linktext == 'icon') { // Icon only
1040 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1041 } else if ($linktext == 'both') { // Icon and standard name
1042 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1043 $fulllink .= ' '.$strmessagehistory;
1044 } else if ($linktext) { // Custom name
1045 $fulllink = $linktext;
1046 } else { // Standard name only
1047 $fulllink = $strmessagehistory;
1050 $popupoptions = array(
1054 'location' => false,
1056 'scrollbars' => true,
1057 'resizable' => true);
1059 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
1060 //$action = new popup_action('click', $link, "message_history_$userid1", $popupoptions);
1062 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
1064 $str = '<span class="history">'.$str.'</span>';
1076 * Search through course users
1078 * If $coursid specifies the site course then this function searches
1079 * through all undeleted and confirmed users
1083 * @param int $courseid The course in question.
1084 * @param string $searchtext ?
1085 * @param string $sort ?
1086 * @param string $exceptions ?
1087 * @return array An array of {@link $USER} records.
1088 * @todo Finish documenting this function
1090 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1091 global $CFG, $USER, $DB;
1093 $fullname = $DB->sql_fullname();
1095 if (!empty($exceptions)) {
1096 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1101 if (!empty($sort)) {
1102 $order = ' ORDER BY '. $sort;
1107 $ufields = user_picture::fields('u');
1108 if (!$courseid or $courseid == SITEID) {
1109 $params = array($USER->id, "%$searchtext%");
1110 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1112 LEFT JOIN {message_contacts} mc
1113 ON mc.contactid = u.id AND mc.userid = ?
1114 WHERE u.deleted = '0' AND u.confirmed = '1'
1115 AND (".$DB->sql_like($fullname, '?', false).")
1119 //TODO: add enabled enrolment join here (skodak)
1120 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1121 $contextlists = get_related_contexts_string($context);
1123 // everyone who has a role assignment in this course or higher
1124 $params = array($USER->id, "%$searchtext%");
1125 $users = $DB->get_records_sql("SELECT $ufields,
1126 FROM {user} u, mc.id as contactlistid, mc.blocked
1127 JOIN {role_assignments} ra ON ra.userid = u.id
1128 LEFT JOIN {message_contacts} mc
1129 ON mc.contactid = u.id AND mc.userid = ?
1130 WHERE u.deleted = '0' AND u.confirmed = '1'
1131 AND ra.contextid $contextlists
1132 AND (".$DB->sql_like($fullname, '?', false).")
1143 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1144 /// Returns a list of posts found using an array of search terms
1145 /// eg word +word -word
1147 global $CFG, $USER, $DB;
1149 /// If no userid sent then assume current user
1150 if ($userid == 0) $userid = $USER->id;
1152 /// Some differences in SQL syntax
1153 if ($DB->sql_regex_supported()) {
1154 $REGEXP = $DB->sql_regex(true);
1155 $NOTREGEXP = $DB->sql_regex(false);
1158 $searchcond = array();
1162 //preprocess search terms to check whether we have at least 1 eligible search term
1163 //if we do we can drop words around it like 'a'
1164 $dropshortwords = false;
1165 foreach ($searchterms as $searchterm) {
1166 if (strlen($searchterm) >= 2) {
1167 $dropshortwords = true;
1171 foreach ($searchterms as $searchterm) {
1174 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1176 if ($dropshortwords && strlen($searchterm) < 2) {
1179 /// Under Oracle and MSSQL, trim the + and - operators and perform
1180 /// simpler LIKE search
1181 if (!$DB->sql_regex_supported()) {
1182 if (substr($searchterm, 0, 1) == '-') {
1185 $searchterm = trim($searchterm, '+-');
1188 if (substr($searchterm,0,1) == "+") {
1189 $searchterm = substr($searchterm,1);
1190 $searchterm = preg_quote($searchterm, '|');
1191 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1192 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1194 } else if (substr($searchterm,0,1) == "-") {
1195 $searchterm = substr($searchterm,1);
1196 $searchterm = preg_quote($searchterm, '|');
1197 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1198 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1201 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1202 $params['ss'.$i] = "%$searchterm%";
1206 if (empty($searchcond)) {
1207 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1208 $params['ss1'] = "%";
1210 $searchcond = implode(" AND ", $searchcond);
1213 /// There are several possibilities
1214 /// 1. courseid = SITEID : The admin is searching messages by all users
1215 /// 2. courseid = ?? : A teacher is searching messages by users in
1216 /// one of their courses - currently disabled
1217 /// 3. courseid = none : User is searching their own messages;
1218 /// a. Messages from user
1219 /// b. Messages to user
1220 /// c. Messages to and from user
1222 if ($courseid == SITEID) { /// admin is searching all messages
1223 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1224 FROM {message_read} m
1225 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1226 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1228 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1230 } else if ($courseid !== 'none') {
1231 /// This has not been implemented due to security concerns
1233 $m_unread = array();
1237 if ($fromme and $tome) {
1238 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1239 $params['userid1'] = $userid;
1240 $params['userid2'] = $userid;
1242 } else if ($fromme) {
1243 $searchcond .= " AND m.useridfrom=:userid";
1244 $params['userid'] = $userid;
1247 $searchcond .= " AND m.useridto=:userid";
1248 $params['userid'] = $userid;
1251 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1252 FROM {message_read} m
1253 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1254 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1256 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1260 /// The keys may be duplicated in $m_read and $m_unread so we can't
1261 /// do a simple concatenation
1263 foreach ($m_read as $m) {
1266 foreach ($m_unread as $m) {
1270 return (empty($messages)) ? false : $messages;
1275 /// Borrowed with changes from mod/forum/lib.php
1276 function message_shorten_message($message, $minlength=0) {
1277 // Given a post object that we already know has a long message
1278 // this function truncates the message nicely to the first
1279 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1283 $length = strlen($message);
1287 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1290 for ($i=0; $i<$length; $i++) {
1291 $char = $message[$i];
1303 if ($char == '.' or $char == ' ') {
1313 if ($count > $minlength) {
1323 return substr($message, 0, $truncate);
1328 * Given a string and an array of keywords, this function looks
1329 * for the first keyword in the string, and then chops out a
1330 * small section from the text that shows that word in context.
1332 function message_get_fragment($message, $keywords) {
1335 $halfsize = (int)($fullsize/2);
1337 $message = strip_tags($message);
1339 foreach ($keywords as $keyword) { // Just get the first one
1340 if ($keyword !== '') {
1344 if (empty($keyword)) { // None found, so just return start of message
1345 return message_shorten_message($message, 30);
1348 $leadin = $leadout = '';
1350 /// Find the start of the fragment
1352 $length = strlen($message);
1354 $pos = strpos($message, $keyword);
1355 if ($pos > $halfsize) {
1356 $start = $pos - $halfsize;
1359 /// Find the end of the fragment
1360 $end = $start + $fullsize;
1361 if ($end > $length) {
1367 /// Pull out the fragment and format it
1369 $fragment = substr($message, $start, $end - $start);
1370 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1374 //retrieve the messages between two users
1375 function message_get_history($user1, $user2, $limitnum=0) {
1378 $messages = array();
1380 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1381 //desc to get the last $limitnum messages then flip the order in php
1387 if ($messages_read = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
1388 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
1389 "timecreated $sort", '*', 0, $limitnum)) {
1390 foreach ($messages_read as $message) {
1391 $messages[$message->timecreated] = $message;
1394 if ($messages_new = $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
1395 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
1396 "timecreated $sort", '*', 0, $limitnum)) {
1397 foreach ($messages_new as $message) {
1398 $messages[$message->timecreated] = $message;
1402 //if we only want the last $limitnum messages
1405 $messages = array_slice($messages, count($messages)-$limitnum, $limitnum, true);
1411 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false) {
1412 global $CFG, $OUTPUT;
1414 echo $OUTPUT->box_start('center');
1415 echo '<table cellpadding="10" class="message_user_pictures"><tr>';
1416 echo '<td align="center" id="user1">';
1417 echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID));
1418 echo '<div class="heading">'.fullname($user1).'</div>';
1420 echo '<td align="center">';
1421 echo '<img src="'.$OUTPUT->pix_url('t/left').'" alt="'.get_string('from').'" />';
1422 echo '<img src="'.$OUTPUT->pix_url('t/right').'" alt="'.get_string('to').'" />';
1424 echo '<td align="center" id="user2">';
1425 echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID));
1426 echo '<div class="heading">'.fullname($user2).'</div>';
1428 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1429 $incontactlist = $user2->iscontact;
1430 $isblocked = $user2->isblocked;
1436 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1437 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1438 $useractionlinks = $strcontact.' |'.$strblock;
1440 echo html_writer::tag('div', $useractionlinks, array('class'=>'useractionlinks'));
1444 echo '</tr></table>';
1445 echo $OUTPUT->box_end();
1447 if (!empty($messagehistorylink)) {
1448 echo $messagehistorylink;
1451 /// Get all the messages and print them
1452 if ($messages = message_get_history($user1, $user2, $messagelimit)) {
1453 $tablecontents = '';
1455 $current = new stdClass();
1456 $current->mday = '';
1457 $current->month = '';
1458 $current->year = '';
1459 $messagedate = get_string('strftimetime');
1460 $blockdate = get_string('strftimedaydate');
1461 foreach ($messages as $message) {
1462 $date = usergetdate($message->timecreated);
1463 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1464 $current->mday = $date['mday'];
1465 $current->month = $date['month'];
1466 $current->year = $date['year'];
1468 $tablecontents .= '<div class="mdl-align heading"><a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
1469 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center').'</div>';
1471 if ($message->useridfrom == $user1->id) {
1472 $tablecontents .= '<div class="mdl-left left">'.message_format_message($message, $user1, $messagedate, $search, 'me').'</div><br />';
1474 $tablecontents .= '<div class="mdl-left right">'.message_format_message($message, $user2, $messagedate, $search, 'other').'</div><br />';
1478 echo html_writer::nonempty_tag('div', $tablecontents, array('class'=>'mdl-left messagehistory'));
1480 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class'=>'mdl-align messagehistory'));
1484 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
1488 if (empty($dateformat)) {
1490 $dateformat = $format;
1492 $format = get_string('strftimedatetimeshort');
1495 $time = userdate($message->timecreated, $dateformat);
1496 $options = new stdClass();
1497 $options->para = false;
1499 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1500 if (!empty($message->smallmessage)) {
1501 $messagetext = format_text($message->smallmessage, null, $options);
1503 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1507 $messagetext = highlight($keywords, $messagetext);
1509 //return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a><span class="author">'.s(fullname($user)).'</span> <span class="time">['.$time.']</span>: <span class="content">'.$messagetext.'</span></div>';
1510 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1514 * Inserts a message into the database, but also forwards it
1515 * via other means if appropriate.
1517 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
1518 global $SITE, $CFG, $USER;
1520 $eventdata = new stdClass();
1521 $eventdata->component = 'moodle';
1522 $eventdata->name = 'instantmessage';
1523 $eventdata->userfrom = $userfrom;
1524 $eventdata->userto = $userto;
1525 $eventdata->subject = get_string('unreadnewmessage', 'message', fullname($userfrom));
1526 $eventdata->fullmessage = $message;
1527 $eventdata->fullmessageformat = $format;
1528 $eventdata->fullmessagehtml = '';
1529 $eventdata->smallmessage = $message;
1531 $s = new stdClass();
1532 $s->sitename = $SITE->shortname;
1533 $s->url = $CFG->wwwroot.'/message/index.php?id='.$userfrom->id;//.'&user='.$userto->id;
1535 $emailtagline = get_string('emailtagline', 'message', $s);
1536 //$eventdata->footer = "\n\n---------------------------------------------------------------------\n".$emailtagline;
1537 if (!empty($eventdata->fullmessage)) {
1538 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1540 //$eventdata->footerhtml = "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1541 if (!empty($eventdata->fullmessagehtml)) {
1542 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1545 $eventdata->timecreated = time();
1546 return message_send($eventdata);
1551 * Returns a list of all user ids who have used messaging in the site
1552 * This was the simple way to code the SQL ... is it going to blow up
1553 * on large datasets?
1555 function message_get_participants() {
1558 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1559 UNION SELECT useridto as id,1 FROM {message}
1560 UNION SELECT useridfrom as id,1 FROM {message_read}
1561 UNION SELECT useridto as id,1 FROM {message_read}
1562 UNION SELECT userid as id,1 FROM {message_contacts}
1563 UNION SELECT contactid as id,1 from {message_contacts}");
1567 * Print a row of contactlist displaying user picture, messages waiting and
1569 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
1570 * @param $incontactlist is the user a contact of ours?
1571 * @param $selectcontacturl string the url to send the user to when a contact's name is clicked
1573 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true) {
1574 global $OUTPUT, $USER;
1575 $fullname = fullname($contact);
1576 $fullnamelink = $fullname;
1578 /// are there any unread messages for this contact?
1579 if ($contact->messagecount > 0 ){
1580 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1583 $strcontact = $strblock = $strhistory = null;
1585 if ($showactionlinks) {
1586 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
1587 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
1588 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
1591 echo '<tr><td class="pix">';
1592 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
1594 echo '<td class="contact">';
1596 $popupoptions = array(
1597 'height' => MESSAGE_DISCUSSION_HEIGHT,
1598 'width' => MESSAGE_DISCUSSION_WIDTH,
1600 'location' => false,
1602 'scrollbars' => true,
1603 'resizable' => true);
1605 $link = $action = null;
1606 if (!empty($selectcontacturl)) {
1607 $link = new moodle_url($selectcontacturl.'&'.CONTACT_ID.'='.$contact->id);
1609 //I suspect this else clause can be removed and maybe the $selectcontacturl arg can be removed and hardcoded
1610 $link = new moodle_url("/message/discussion.php?id=$contact->id");
1611 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1613 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
1616 echo '<td class="link"> '.$strcontact.$strblock.' '.$strhistory.'</td>';
1620 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1624 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
1625 } else if ($isblocked) {
1626 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1628 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1634 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1637 //commented out to allow the user to block a contact without having to remove them first
1638 /*if ($incontactlist) {
1642 $strblock = ' '.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
1644 $strblock = ' '.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
1651 * Moves unread messages from message table to message_read for a given from user
1652 * @param object $userid User id
1653 * @return boolean success
1655 function message_move_userfrom_unread2read($userid) {
1659 // move all unread messages from message table to message_read
1660 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1661 foreach ($messages as $message) {
1662 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
1668 function message_get_popup_messages($destuserid, $fromuserid=NULL){
1671 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1673 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1675 //for every message to process check if it's for current user and process
1676 $messages = array();
1677 foreach ($messagesproc as $msgp){
1678 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1680 $query['useridfrom'] = $fromuserid;
1682 if ($message = $DB->get_record('message', $query)){
1683 $messages[] = $message;
1684 /// Move the entry to the other table
1685 $message->timeread = time();
1686 $messageid = $message->id;
1687 unset($message->id);
1689 //delete what we've processed and check if can move message
1690 $DB->delete_records('message_working', array('id' => $msgp->id));
1691 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
1692 message_mark_message_read($message, time(), true);
1700 * marks ALL messages being sent from $fromuserid to $touserid as read
1701 * @param int $touserid the id of the message recipient
1702 * @param int $fromuserid the id of the message sender
1705 function message_mark_messages_read($touserid, $fromuserid){
1708 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
1709 $messages = $DB->get_recordset_sql($sql, array('useridto'=>$touserid,'useridfrom'=>$fromuserid));
1711 foreach ($messages as $message) {
1712 message_mark_message_read($message, time());
1717 * Mark a single message as read
1718 * @param message an object with an object property ie $message->id which is an id in the message table
1719 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
1720 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
1723 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
1726 $message->timeread = $timeread;
1728 $messageid = $message->id;
1729 unset($message->id);//unset because it will get a new id on insert into message_read
1731 //If any processors have pending actions abort them
1732 if (!$messageworkingempty) {
1733 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
1735 $DB->insert_record('message_read', $message);
1736 $DB->delete_records('message', array('id' => $messageid));