Merge branch 'w12_MDL-26842_20_ociparams' of git://github.com/skodak/moodle
[moodle.git] / message / lib.php
blobe034c4128368ea45ed843b40ab589d828ce72578
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Library functions for messaging
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package message
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
31 if (isset($PAGE)) {
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;
66 /**
67 * Print the selector that allows the user to view their contacts, course participants, their recent
68 * conversations etc
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
79 * @return void
81 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
82 global $PAGE;
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);
121 } else {
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
151 * @return void
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
173 $iscontact = true;
174 $isblocked = false;
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) {
193 global $DB, $USER;
195 if (empty($user1)) {
196 $user1 = $USER;
199 if (!empty($user2)) {
200 $user2->isblocked = false;
203 $userfields = user_picture::fields('u', array('lastaccess'));
204 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
205 FROM {message_contacts} mc
206 JOIN {user} u ON u.id = mc.contactid
207 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
208 WHERE mc.userid = :user1id2 AND mc.blocked = 1
209 GROUP BY $userfields
210 ORDER BY u.firstname ASC";
211 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
213 $blockedusers = array();
214 if (!empty($rs)) {
215 foreach($rs as $rd) {
216 $blockedusers[] = $rd;
218 if (!empty($user2) && $user2->id == $rd->id) {
219 $user2->isblocked = true;
222 unset($rd);
223 $rs->close();
226 return $blockedusers;
230 * Print users blocked by $user1. Called by message_print_contact_selector()
231 * @param array $blockedusers the users blocked by $user1
232 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
233 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
234 * @param string $titletodisplay Optionally specify a title to display above the participants
235 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
236 * @return void
238 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
239 global $DB, $USER;
241 $countblocked = count($blockedusers);
243 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
245 if (!empty($titletodisplay)) {
246 echo html_writer::start_tag('tr');
247 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
248 echo html_writer::end_tag('tr');
251 if ($countblocked) {
252 echo html_writer::start_tag('tr');
253 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
254 echo html_writer::end_tag('tr');
256 $isuserblocked = true;
257 $isusercontact = false;
258 foreach ($blockedusers as $blockeduser) {
259 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
263 echo html_writer::end_tag('table');
267 * Retrieve $user1's contacts (online, offline and strangers)
268 * @param object $user1 the user whose messages are being viewed
269 * @param object $user2 the user $user1 is talking to. If they are a contact
270 * they will have a variable called 'iscontact' added to their user object
271 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
273 function message_get_contacts($user1=null, $user2=null) {
274 global $DB, $CFG, $USER;
276 if (empty($user1)) {
277 $user1 = $USER;
280 if (!empty($user2)) {
281 $user2->iscontact = false;
284 $timetoshowusers = 300; //Seconds default
285 if (isset($CFG->block_online_users_timetosee)) {
286 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
289 // time which a user is counting as being active since
290 $timefrom = time()-$timetoshowusers;
292 // people in our contactlist who are online
293 $onlinecontacts = array();
294 // people in our contactlist who are offline
295 $offlinecontacts = array();
296 // people who are not in our contactlist but have sent us a message
297 $strangers = array();
299 $userfields = user_picture::fields('u', array('lastaccess'));
301 // get all in our contactlist who are not blocked in our contact list
302 // and count messages we have waiting from each of them
303 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
304 FROM {message_contacts} mc
305 JOIN {user} u ON u.id = mc.contactid
306 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
307 WHERE mc.userid = ? AND mc.blocked = 0
308 GROUP BY $userfields
309 ORDER BY u.firstname ASC";
311 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
312 foreach ($rs as $rd) {
313 if ($rd->lastaccess >= $timefrom) {
314 // they have been active recently, so are counted online
315 $onlinecontacts[] = $rd;
317 } else {
318 $offlinecontacts[] = $rd;
321 if (!empty($user2) && $user2->id == $rd->id) {
322 $user2->iscontact = true;
325 $rs->close();
327 // get messages from anyone who isn't in our contact list and count the number
328 // of messages we have from each of them
329 $strangersql = "SELECT $userfields, count(m.id) as messagecount
330 FROM {message} m
331 JOIN {user} u ON u.id = m.useridfrom
332 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
333 WHERE mc.id IS NULL AND m.useridto = ?
334 GROUP BY $userfields
335 ORDER BY u.firstname ASC";
337 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
338 foreach ($rs as $rd) {
339 $strangers[] = $rd;
341 $rs->close();
343 return array($onlinecontacts, $offlinecontacts, $strangers);
347 * Print $user1's contacts. Called by message_print_contact_selector()
348 * @param array $onlinecontacts $user1's contacts which are online
349 * @param array $offlinecontacts $user1's contacts which are offline
350 * @param array $strangers users which are not contacts but who have messaged $user1
351 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
352 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
353 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
354 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
355 * @param string $titletodisplay Optionally specify a title to display above the participants
356 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
357 * @return void
359 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
360 global $CFG, $PAGE, $OUTPUT;
362 $countonlinecontacts = count($onlinecontacts);
363 $countofflinecontacts = count($offlinecontacts);
364 $countstrangers = count($strangers);
365 $isuserblocked = null;
367 if ($countonlinecontacts + $countofflinecontacts == 0) {
368 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
371 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
373 if (!empty($titletodisplay)) {
374 message_print_heading($titletodisplay);
377 if($countonlinecontacts) {
378 /// print out list of online contacts
380 if (empty($titletodisplay)) {
381 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
384 $isuserblocked = false;
385 $isusercontact = true;
386 foreach ($onlinecontacts as $contact) {
387 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
388 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
393 if ($countofflinecontacts) {
394 /// print out list of offline contacts
396 if (empty($titletodisplay)) {
397 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
400 $isuserblocked = false;
401 $isusercontact = true;
402 foreach ($offlinecontacts as $contact) {
403 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
404 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
410 /// print out list of incoming contacts
411 if ($countstrangers) {
412 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
414 $isuserblocked = false;
415 $isusercontact = false;
416 foreach ($strangers as $stranger) {
417 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
418 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
423 echo html_writer::end_tag('table');
425 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
426 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
431 * Print a select box allowing the user to choose to view new messages, course participants etc.
432 * Called by message_print_contact_selector()
433 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
434 * @param array $courses array of course objects. The courses the user is enrolled in.
435 * @param array $coursecontexts array of course contexts. Keyed on course id.
436 * @param int $countunreadtotal how many unread messages does the user have?
437 * @param int $countblocked how many users has the current user blocked?
438 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
439 * @return void
441 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
442 $options = array();
443 $textlib = textlib_get_instance(); // going to use textlib services
445 if ($countunreadtotal>0) { //if there are unread messages
446 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
449 $str = get_string('mycontacts', 'message');
450 $options[MESSAGE_VIEW_CONTACTS] = $str;
452 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
453 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
455 if (!empty($courses)) {
456 $courses_options = array();
458 foreach($courses as $course) {
459 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
460 //Not using short_text() as we want the end of the course name. Not the beginning.
461 if ($textlib->strlen($course->shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
462 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.$textlib->substr($course->shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
463 } else {
464 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $course->shortname;
469 if (!empty($courses_options)) {
470 $options[] = array(get_string('courses') => $courses_options);
474 if ($countblocked>0) {
475 $str = get_string('blockedusers','message', $countblocked);
476 $options[MESSAGE_VIEW_BLOCKED] = $str;
479 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
480 echo html_writer::start_tag('fieldset');
481 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
482 echo html_writer::end_tag('fieldset');
483 echo html_writer::end_tag('form');
487 * Load the course contexts for all of the users courses
488 * @param array $courses array of course objects. The courses the user is enrolled in.
489 * @return array of course contexts
491 function message_get_course_contexts($courses) {
492 $coursecontexts = array();
494 foreach($courses as $course) {
495 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
498 return $coursecontexts;
502 * strip off action parameters like 'removecontact'
503 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
504 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
506 function message_remove_url_params($moodleurl) {
507 $newurl = new moodle_url($moodleurl);
508 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
509 return $newurl->out();
513 * Count the number of messages with a field having a specified value.
514 * if $field is empty then return count of the whole array
515 * if $field is non-existent then return 0
516 * @param array $messagearray array of message objects
517 * @param string $field the field to inspect on the message objects
518 * @param string $value the value to test the field against
520 function message_count_messages($messagearray, $field='', $value='') {
521 if (!is_array($messagearray)) return 0;
522 if ($field == '' or empty($messagearray)) return count($messagearray);
524 $count = 0;
525 foreach ($messagearray as $message) {
526 $count += ($message->$field == $value) ? 1 : 0;
528 return $count;
532 * Returns the count of unread messages for user. Either from a specific user or from all users.
533 * @param object $user1 the first user. Defaults to $USER
534 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
535 * @return int the count of $user1's unread messages
537 function message_count_unread_messages($user1=null, $user2=null) {
538 global $USER, $DB;
540 if (empty($user1)) {
541 $user1 = $USER;
544 if (!empty($user2)) {
545 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
546 array($user1->id, $user2->id), "COUNT('id')");
547 } else {
548 return $DB->count_records_select('message', "useridto = ?",
549 array($user1->id), "COUNT('id')");
554 * Count the number of users blocked by $user1
555 * @param $user1
557 function message_count_blocked_users($user1=null) {
558 global $USER, $DB;
560 if (empty($user1)) {
561 $user1 = $USER;
564 $sql = "SELECT count(mc.id)
565 FROM {message_contacts} mc
566 WHERE mc.userid = :userid AND mc.blocked = 1";
567 $params = array('userid' => $user1->id);
569 return $DB->count_records_sql($sql, $params);
573 * Print the search form and search results if a search has been performed
574 * @param boolean $advancedsearch show basic or advanced search form
575 * @param object $user1 the current user
576 * @return boolean true if a search was performed
578 function message_print_search($advancedsearch = false, $user1=null) {
579 $frm = data_submitted();
581 $doingsearch = false;
582 if ($frm) {
583 if (confirm_sesskey()) {
584 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
585 } else {
586 $frm = false;
590 if (!empty($frm->combinedsearch)) {
591 $combinedsearchstring = $frm->combinedsearch;
592 } else {
593 //$combinedsearchstring = get_string('searchcombined','message').'...';
594 $combinedsearchstring = '';
597 if ($doingsearch) {
598 if ($advancedsearch) {
600 $messagesearch = '';
601 if (!empty($frm->keywords)) {
602 $messagesearch = $frm->keywords;
604 $personsearch = '';
605 if (!empty($frm->name)) {
606 $personsearch = $frm->name;
608 include('search_advanced.html');
609 } else {
610 include('search.html');
613 $showicontext = false;
614 message_print_search_results($frm, $showicontext, $user1);
616 return true;
617 } else {
619 if ($advancedsearch) {
620 $personsearch = $messagesearch = '';
621 include('search_advanced.html');
622 } else {
623 include('search.html');
625 return false;
630 * Get the users recent conversations meaning all the people they've recently
631 * sent or received a message from plus the most recent message sent to or received from each other user
632 * @param object $user the current user
633 * @param int $limitfrom can be used for paging
634 * @param int $limitto can be used for paging
635 * @return array
637 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
638 global $DB;
640 $userfields = user_picture::fields('u', array('lastaccess'));
641 //This query retrieves the last message received from and sent to each user
642 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
643 //It then joins with some other tables to get some additional data we need
645 //message ID is used instead of timecreated as it should sort the same and will be much faster
647 //There is a separate query for read and unread queries as they are stored in different tables
648 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
649 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
650 FROM {message_read} mr
651 JOIN (
652 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
653 FROM (
654 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
655 FROM {message_read} mr1
656 WHERE mr1.useridfrom = :userid1
657 AND mr1.notification = 0
658 GROUP BY mr1.useridto
659 UNION
660 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
661 FROM {message_read} mr2
662 WHERE mr2.useridto = :userid2
663 AND mr2.notification = 0
664 GROUP BY mr2.useridfrom
665 ) messages
666 GROUP BY messages.userid
667 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
668 JOIN {user} u ON u.id = messages2.userid
669 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
670 WHERE u.deleted = '0'
671 ORDER BY mr.id DESC";
672 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
673 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
675 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
676 FROM {message} m
677 JOIN (
678 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
679 FROM (
680 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
681 FROM {message} m1
682 WHERE m1.useridfrom = :userid1
683 AND m1.notification = 0
684 GROUP BY m1.useridto
685 UNION
686 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
687 FROM {message} m2
688 WHERE m2.useridto = :userid2
689 AND m2.notification = 0
690 GROUP BY m2.useridfrom
691 ) messages
692 GROUP BY messages.userid
693 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
694 JOIN {user} u ON u.id = messages2.userid
695 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
696 WHERE u.deleted = '0'
697 ORDER BY m.id DESC";
698 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
700 $conversations = array();
702 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
703 //$conversation->id (the array key) is the other user's ID
704 $conversation_arrays = array($unread, $read);
705 foreach ($conversation_arrays as $conversation_array) {
706 foreach ($conversation_array as $conversation) {
707 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
708 $conversations[$conversation->id] = $conversation;
713 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
714 //and there may be multiple conversations with the same timecreated value.
715 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
716 usort($conversations, "conversationsort");
718 return $conversations;
722 * Sort function used to order conversations
723 * @param object $a A conversation object
724 * @param object $b A conversation object
725 * @return integer
727 function conversationsort($a, $b)
729 if ($a->timecreated == $b->timecreated) {
730 return 0;
732 return ($a->timecreated > $b->timecreated) ? -1 : 1;
736 * Get the users recent event notifications
737 * @param object $user the current user
738 * @param int $limitfrom can be used for paging
739 * @param int $limitto can be used for paging
740 * @return array
742 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
743 global $DB;
745 $userfields = user_picture::fields('u', array('lastaccess'));
746 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
747 FROM {message_read} mr
748 JOIN {user} u ON u.id=mr.useridfrom
749 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
750 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
751 $params = array('userid1' => $user->id, 'notification' => 1);
753 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
754 return $notifications;
758 * Print the user's recent conversations
759 * @param object $user1 the current user
760 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
762 function message_print_recent_conversations($user=null, $showicontext=false) {
763 global $USER;
765 echo html_writer::start_tag('p', array('class' => 'heading'));
766 echo get_string('mostrecentconversations', 'message');
767 echo html_writer::end_tag('p');
769 if (empty($user)) {
770 $user = $USER;
773 $conversations = message_get_recent_conversations($user);
775 $showotheruser = true;
776 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
780 * Print the user's recent notifications
781 * @param object $user1 the current user
783 function message_print_recent_notifications($user=null) {
784 global $USER;
786 echo html_writer::start_tag('p', array('class' => 'heading'));
787 echo get_string('mostrecentnotifications', 'message');
788 echo html_writer::end_tag('p');
790 if (empty($user)) {
791 $user = $USER;
794 $notifications = message_get_recent_notifications($user);
796 $showicontext = false;
797 $showotheruser = false;
798 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
802 * Print a list of recent messages
803 * @staticvar type $dateformat
804 * @param array $messages the messages to display
805 * @param object $user the current user
806 * @param bool $showotheruser display information on the other user?
807 * @param bool $showicontext show text next to the action icons?
809 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
810 global $OUTPUT;
811 static $dateformat;
813 if (empty($dateformat)) {
814 $dateformat = get_string('strftimedatetimeshort');
817 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
818 foreach ($messages as $message) {
819 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
821 if ($showotheruser) {
822 if ( $message->contactlistid ) {
823 if ($message->blocked == 0) { /// not blocked
824 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
825 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
826 } else { // blocked
827 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
828 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
830 } else {
831 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
832 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
835 //should we show just the icon or icon and text?
836 $histicontext = 'icon';
837 if ($showicontext) {
838 $histicontext = 'both';
840 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
842 echo html_writer::start_tag('span', array('class' => 'otheruser'));
844 echo html_writer::start_tag('span', array('class' => 'pix'));
845 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
846 echo html_writer::end_tag('span');
848 echo html_writer::start_tag('span', array('class' => 'contact'));
850 $link = new moodle_url("/message/index.php?id=$message->id");
851 $action = null;
852 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
854 echo html_writer::end_tag('span');//end contact
856 echo $strcontact.$strblock.$strhistory;
857 echo html_writer::end_tag('span');//end otheruser
859 $messagetoprint = null;
860 if (!empty($message->smallmessage)) {
861 $messagetoprint = $message->smallmessage;
862 } else {
863 $messagetoprint = $message->fullmessage;
866 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
867 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
868 echo message_format_contexturl($message);
869 echo html_writer::end_tag('div');//end singlemessage
871 echo html_writer::end_tag('div');//end messagerecent
875 * Add the selected user as a contact for the current user
876 * @param int $contactid the ID of the user to add as a contact
877 * @param int $blocked 1 if you wish to block the contact
878 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
879 * Otherwise returns the result of update_record() or insert_record()
881 function message_add_contact($contactid, $blocked=0) {
882 global $USER, $DB;
884 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
885 return false;
888 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
889 /// record already exists - we may be changing blocking status
891 if ($contact->blocked !== $blocked) {
892 /// change to blocking status
893 $contact->blocked = $blocked;
894 return $DB->update_record('message_contacts', $contact);
895 } else {
896 /// no changes to blocking status
897 return true;
900 } else {
901 /// new contact record
902 unset($contact);
903 $contact->userid = $USER->id;
904 $contact->contactid = $contactid;
905 $contact->blocked = $blocked;
906 return $DB->insert_record('message_contacts', $contact, false);
911 * remove a contact
912 * @param type $contactid the user ID of the contact to remove
913 * @return bool returns the result of delete_records()
915 function message_remove_contact($contactid) {
916 global $USER, $DB;
917 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
921 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
922 * @param int $contactid the user ID of the contact to unblock
923 * @return bool returns the result of delete_records()
925 function message_unblock_contact($contactid) {
926 global $USER, $DB;
927 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
931 * block a user
932 * @param int $contactid the user ID of the user to block
934 function message_block_contact($contactid) {
935 return message_add_contact($contactid, 1);
939 * Load a user's contact record
940 * @param int $contactid the user ID of the user whose contact record you want
942 function message_get_contact($contactid) {
943 global $USER, $DB;
944 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
948 * Print the results of a message search
949 * @param mixed $frm submitted form data
950 * @param bool $showicontext show text next to action icons?
951 * @param object $user1 the current user
953 function message_print_search_results($frm, $showicontext=false, $user1=null) {
954 global $USER, $DB, $OUTPUT;
956 if (empty($user1)) {
957 $user1 = $USER;
960 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
962 $personsearch = false;
963 $personsearchstring = null;
964 if (!empty($frm->personsubmit) and !empty($frm->name)) {
965 $personsearch = true;
966 $personsearchstring = $frm->name;
967 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
968 $personsearch = true;
969 $personsearchstring = $frm->combinedsearch;
972 /// search for person
973 if ($personsearch) {
974 if (optional_param('mycourses', 0, PARAM_BOOL)) {
975 $users = array();
976 $mycourses = enrol_get_my_courses();
977 foreach ($mycourses as $mycourse) {
978 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
979 foreach ($susers as $suser) $users[$suser->id] = $suser;
982 } else {
983 $users = message_search_users(SITEID, $personsearchstring);
986 if (!empty($users)) {
987 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
988 echo get_string('userssearchresults', 'message', count($users));
989 echo html_writer::end_tag('p');
991 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
992 foreach ($users as $user) {
994 if ( $user->contactlistid ) {
995 if ($user->blocked == 0) { /// not blocked
996 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
997 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
998 } else { // blocked
999 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1000 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1002 } else {
1003 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1004 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1007 //should we show just the icon or icon and text?
1008 $histicontext = 'icon';
1009 if ($showicontext) {
1010 $histicontext = 'both';
1012 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1014 echo html_writer::start_tag('tr');
1016 echo html_writer::start_tag('td', array('class' => 'pix'));
1017 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1018 echo html_writer::end_tag('td');
1020 echo html_writer::start_tag('td',array('class' => 'contact'));
1021 $action = null;
1022 $link = new moodle_url("/message/index.php?id=$user->id");
1023 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1024 echo html_writer::end_tag('td');
1026 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1027 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1028 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1030 echo html_writer::end_tag('tr');
1032 echo html_writer::end_tag('table');
1034 } else {
1035 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1036 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1037 echo html_writer::end_tag('p');
1041 // search messages for keywords
1042 $messagesearch = false;
1043 $messagesearchstring = null;
1044 if (!empty($frm->keywords)) {
1045 $messagesearch = true;
1046 $messagesearchstring = clean_text(trim($frm->keywords));
1047 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1048 $messagesearch = true;
1049 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1052 if ($messagesearch) {
1053 if ($messagesearchstring) {
1054 $keywords = explode(' ', $messagesearchstring);
1055 } else {
1056 $keywords = array();
1058 $tome = false;
1059 $fromme = false;
1060 $courseid = 'none';
1062 if (empty($frm->keywordsoption)) {
1063 $frm->keywordsoption = 'allmine';
1066 switch ($frm->keywordsoption) {
1067 case 'tome':
1068 $tome = true;
1069 break;
1070 case 'fromme':
1071 $fromme = true;
1072 break;
1073 case 'allmine':
1074 $tome = true;
1075 $fromme = true;
1076 break;
1077 case 'allusers':
1078 $courseid = SITEID;
1079 break;
1080 case 'courseusers':
1081 $courseid = $frm->courseid;
1082 break;
1083 default:
1084 $tome = true;
1085 $fromme = true;
1088 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1090 /// get a list of contacts
1091 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1092 $contacts = array();
1095 /// print heading with number of results
1096 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1097 $countresults = count($messages);
1098 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1099 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1100 } else {
1101 echo get_string('keywordssearchresults', 'message', $countresults);
1103 echo html_writer::end_tag('p');
1105 /// print table headings
1106 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1108 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1109 $headertdend = html_writer::end_tag('td');
1110 echo html_writer::start_tag('tr');
1111 echo $headertdstart.get_string('from').$headertdend;
1112 echo $headertdstart.get_string('to').$headertdend;
1113 echo $headertdstart.get_string('message', 'message').$headertdend;
1114 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1115 echo html_writer::end_tag('tr');
1117 $blockedcount = 0;
1118 $dateformat = get_string('strftimedatetimeshort');
1119 $strcontext = get_string('context', 'message');
1120 foreach ($messages as $message) {
1122 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1123 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1124 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1125 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1128 $blockedcount ++;
1129 continue;
1132 /// load up user to record
1133 if ($message->useridto !== $USER->id) {
1134 $userto = $DB->get_record('user', array('id' => $message->useridto));
1135 $tocontact = (array_key_exists($message->useridto, $contacts) and
1136 ($contacts[$message->useridto]->blocked == 0) );
1137 $toblocked = (array_key_exists($message->useridto, $contacts) and
1138 ($contacts[$message->useridto]->blocked == 1) );
1139 } else {
1140 $userto = false;
1141 $tocontact = false;
1142 $toblocked = false;
1145 /// load up user from record
1146 if ($message->useridfrom !== $USER->id) {
1147 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1148 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1149 ($contacts[$message->useridfrom]->blocked == 0) );
1150 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1151 ($contacts[$message->useridfrom]->blocked == 1) );
1152 } else {
1153 $userfrom = false;
1154 $fromcontact = false;
1155 $fromblocked = false;
1158 /// find date string for this message
1159 $date = usergetdate($message->timecreated);
1160 $datestring = $date['year'].$date['mon'].$date['mday'];
1162 /// print out message row
1163 echo html_writer::start_tag('tr', array('valign' => 'top'));
1165 echo html_writer::start_tag('td', array('class' => 'contact'));
1166 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1167 echo html_writer::end_tag('td');
1169 echo html_writer::start_tag('td', array('class' => 'contact'));
1170 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1171 echo html_writer::end_tag('td');
1173 echo html_writer::start_tag('td', array('class' => 'summary'));
1174 echo message_get_fragment($message->fullmessage, $keywords);
1175 echo html_writer::start_tag('div', array('class' => 'link'));
1177 //find the user involved that isn't the current user
1178 $user2id = null;
1179 if ($user1->id == $message->useridto) {
1180 $user2id = $message->useridfrom;
1181 } else {
1182 $user2id = $message->useridto;
1184 message_history_link($user1->id, $user2id, false,
1185 $messagesearchstring, 'm'.$message->id, $strcontext);
1186 echo html_writer::end_tag('div');
1187 echo html_writer::end_tag('td');
1189 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1191 echo html_writer::end_tag('tr');
1195 if ($blockedcount > 0) {
1196 echo html_writer::start_tag('tr');
1197 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1198 echo html_writer::end_tag('tr');
1200 echo html_writer::end_tag('table');
1202 } else {
1203 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1207 if (!$personsearch && !$messagesearch) {
1208 //they didn't enter any search terms
1209 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1212 echo html_writer::end_tag('div');
1216 * Print information on a user. Used when printing search results.
1217 * @param object/bool $user the user to display or false if you just want $USER
1218 * @param bool $iscontact is the user being displayed a contact?
1219 * @param bool $isblocked is the user being displayed blocked?
1220 * @param bool $includeicontext include text next to the action icons?
1222 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1223 global $USER, $OUTPUT;
1225 if ($user === false) {
1226 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1227 } else {
1228 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1229 echo '&nbsp;';
1231 $return = false;
1232 $script = null;
1233 if ($iscontact) {
1234 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1235 } else {
1236 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1238 echo '&nbsp;';
1239 if ($isblocked) {
1240 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1241 } else {
1242 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1245 $popupoptions = array(
1246 'height' => MESSAGE_DISCUSSION_HEIGHT,
1247 'width' => MESSAGE_DISCUSSION_WIDTH,
1248 'menubar' => false,
1249 'location' => false,
1250 'status' => true,
1251 'scrollbars' => true,
1252 'resizable' => true);
1254 $link = new moodle_url("/message/index.php?id=$user->id");
1255 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1256 $action = null;
1257 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1263 * Print a message contact link
1264 * @staticvar type $str
1265 * @param int $userid the ID of the user to apply to action to
1266 * @param string $linktype can be add, remove, block or unblock
1267 * @param bool $return if true return the link as a string. If false echo the link.
1268 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1269 * @param bool $text include text next to the icons?
1270 * @param bool $icon include a graphical icon?
1271 * @return string if $return is true otherwise bool
1273 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1274 global $OUTPUT, $PAGE;
1276 //hold onto the strings as we're probably creating a bunch of links
1277 static $str;
1279 if (empty($script)) {
1280 //strip off previous action params like 'removecontact'
1281 $script = message_remove_url_params($PAGE->url);
1284 if (empty($str->blockcontact)) {
1285 $str->blockcontact = get_string('blockcontact', 'message');
1286 $str->unblockcontact = get_string('unblockcontact', 'message');
1287 $str->removecontact = get_string('removecontact', 'message');
1288 $str->addcontact = get_string('addcontact', 'message');
1291 $command = $linktype.'contact';
1292 $string = $str->{$command};
1294 $safealttext = s($string);
1296 $safestring = '';
1297 if (!empty($text)) {
1298 $safestring = $safealttext;
1301 $img = '';
1302 if ($icon) {
1303 $iconpath = null;
1304 switch ($linktype) {
1305 case 'block':
1306 $iconpath = 't/block';
1307 break;
1308 case 'unblock':
1309 $iconpath = 't/userblue';
1310 break;
1311 case 'remove':
1312 $iconpath = 'i/cross_red_big';
1313 break;
1314 case 'add':
1315 default:
1316 $iconpath = 't/addgreen';
1319 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1322 $output = '<span class="'.$linktype.'contact">'.
1323 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1324 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1325 $img.
1326 $safestring.'</a></span>';
1328 if ($return) {
1329 return $output;
1330 } else {
1331 echo $output;
1332 return true;
1337 * echo or return a link to take the user to the full message history between themselves and another user
1338 * @staticvar type $strmessagehistory
1339 * @param int $userid1 the ID of the current user
1340 * @param int $userid2 the ID of the other user
1341 * @param bool $return true to return the link as a string. False to echo the link.
1342 * @param string $keywords any keywords to highlight in the message history
1343 * @param string $position anchor name to jump to within the message history
1344 * @param string $linktext optionally specify the link text
1345 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1347 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1348 global $OUTPUT;
1350 static $strmessagehistory;
1352 if (empty($strmessagehistory)) {
1353 $strmessagehistory = get_string('messagehistory', 'message');
1356 if ($position) {
1357 $position = "#$position";
1359 if ($keywords) {
1360 $keywords = "&search=".urlencode($keywords);
1363 if ($linktext == 'icon') { // Icon only
1364 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1365 } else if ($linktext == 'both') { // Icon and standard name
1366 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1367 $fulllink .= '&nbsp;'.$strmessagehistory;
1368 } else if ($linktext) { // Custom name
1369 $fulllink = $linktext;
1370 } else { // Standard name only
1371 $fulllink = $strmessagehistory;
1374 $popupoptions = array(
1375 'height' => 500,
1376 'width' => 500,
1377 'menubar' => false,
1378 'location' => false,
1379 'status' => true,
1380 'scrollbars' => true,
1381 'resizable' => true);
1383 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
1384 $action = null;
1385 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1387 $str = '<span class="history">'.$str.'</span>';
1389 if ($return) {
1390 return $str;
1391 } else {
1392 echo $str;
1393 return true;
1399 * Search through course users
1401 * If $coursid specifies the site course then this function searches
1402 * through all undeleted and confirmed users
1403 * @param int $courseid The course in question.
1404 * @param string $searchtext the text to search for
1405 * @param string $sort the column name to order by
1406 * @param string $exceptions comma separated list of user IDs to exclude
1407 * @return array An array of {@link $USER} records.
1409 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1410 global $CFG, $USER, $DB;
1412 $fullname = $DB->sql_fullname();
1414 if (!empty($exceptions)) {
1415 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1416 } else {
1417 $except = '';
1420 if (!empty($sort)) {
1421 $order = ' ORDER BY '. $sort;
1422 } else {
1423 $order = '';
1426 $ufields = user_picture::fields('u');
1427 if (!$courseid or $courseid == SITEID) {
1428 $params = array($USER->id, "%$searchtext%");
1429 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1430 FROM {user} u
1431 LEFT JOIN {message_contacts} mc
1432 ON mc.contactid = u.id AND mc.userid = ?
1433 WHERE u.deleted = '0' AND u.confirmed = '1'
1434 AND (".$DB->sql_like($fullname, '?', false).")
1435 $except
1436 $order", $params);
1437 } else {
1438 //TODO: add enabled enrolment join here (skodak)
1439 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1440 $contextlists = get_related_contexts_string($context);
1442 // everyone who has a role assignment in this course or higher
1443 $params = array($USER->id, "%$searchtext%");
1444 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1445 FROM {user} u
1446 JOIN {role_assignments} ra ON ra.userid = u.id
1447 LEFT JOIN {message_contacts} mc
1448 ON mc.contactid = u.id AND mc.userid = ?
1449 WHERE u.deleted = '0' AND u.confirmed = '1'
1450 AND ra.contextid $contextlists
1451 AND (".$DB->sql_like($fullname, '?', false).")
1452 $except
1453 $order", $params);
1455 return $users;
1460 * search a user's messages
1461 * @param array $searchterms an array of search terms (strings)
1462 * @param bool $fromme include messages from the user?
1463 * @param bool $tome include messages to the user?
1464 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1465 * @param int $userid the user ID of the current user
1466 * @return mixed An array of messages or false if no matching messages were found
1468 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1469 /// Returns a list of posts found using an array of search terms
1470 /// eg word +word -word
1472 global $CFG, $USER, $DB;
1474 /// If no userid sent then assume current user
1475 if ($userid == 0) $userid = $USER->id;
1477 /// Some differences in SQL syntax
1478 if ($DB->sql_regex_supported()) {
1479 $REGEXP = $DB->sql_regex(true);
1480 $NOTREGEXP = $DB->sql_regex(false);
1483 $searchcond = array();
1484 $params = array();
1485 $i = 0;
1487 //preprocess search terms to check whether we have at least 1 eligible search term
1488 //if we do we can drop words around it like 'a'
1489 $dropshortwords = false;
1490 foreach ($searchterms as $searchterm) {
1491 if (strlen($searchterm) >= 2) {
1492 $dropshortwords = true;
1496 foreach ($searchterms as $searchterm) {
1497 $i++;
1499 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1501 if ($dropshortwords && strlen($searchterm) < 2) {
1502 continue;
1504 /// Under Oracle and MSSQL, trim the + and - operators and perform
1505 /// simpler LIKE search
1506 if (!$DB->sql_regex_supported()) {
1507 if (substr($searchterm, 0, 1) == '-') {
1508 $NOT = true;
1510 $searchterm = trim($searchterm, '+-');
1513 if (substr($searchterm,0,1) == "+") {
1514 $searchterm = substr($searchterm,1);
1515 $searchterm = preg_quote($searchterm, '|');
1516 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1517 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1519 } else if (substr($searchterm,0,1) == "-") {
1520 $searchterm = substr($searchterm,1);
1521 $searchterm = preg_quote($searchterm, '|');
1522 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1523 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1525 } else {
1526 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1527 $params['ss'.$i] = "%$searchterm%";
1531 if (empty($searchcond)) {
1532 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1533 $params['ss1'] = "%";
1534 } else {
1535 $searchcond = implode(" AND ", $searchcond);
1538 /// There are several possibilities
1539 /// 1. courseid = SITEID : The admin is searching messages by all users
1540 /// 2. courseid = ?? : A teacher is searching messages by users in
1541 /// one of their courses - currently disabled
1542 /// 3. courseid = none : User is searching their own messages;
1543 /// a. Messages from user
1544 /// b. Messages to user
1545 /// c. Messages to and from user
1547 if ($courseid == SITEID) { /// admin is searching all messages
1548 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1549 FROM {message_read} m
1550 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1551 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1552 FROM {message} m
1553 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1555 } else if ($courseid !== 'none') {
1556 /// This has not been implemented due to security concerns
1557 $m_read = array();
1558 $m_unread = array();
1560 } else {
1562 if ($fromme and $tome) {
1563 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1564 $params['userid1'] = $userid;
1565 $params['userid2'] = $userid;
1567 } else if ($fromme) {
1568 $searchcond .= " AND m.useridfrom=:userid";
1569 $params['userid'] = $userid;
1571 } else if ($tome) {
1572 $searchcond .= " AND m.useridto=:userid";
1573 $params['userid'] = $userid;
1576 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1577 FROM {message_read} m
1578 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1579 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1580 FROM {message} m
1581 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1585 /// The keys may be duplicated in $m_read and $m_unread so we can't
1586 /// do a simple concatenation
1587 $message = array();
1588 foreach ($m_read as $m) {
1589 $messages[] = $m;
1591 foreach ($m_unread as $m) {
1592 $messages[] = $m;
1595 return (empty($messages)) ? false : $messages;
1599 * Given a message object that we already know has a long message
1600 * this function truncates the message nicely to the first
1601 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1602 * @param string $message the message
1603 * @param int $minlength the minimum length to trim the message to
1604 * @return string the shortened message
1606 function message_shorten_message($message, $minlength = 0) {
1607 $i = 0;
1608 $tag = false;
1609 $length = strlen($message);
1610 $count = 0;
1611 $stopzone = false;
1612 $truncate = 0;
1613 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1616 for ($i=0; $i<$length; $i++) {
1617 $char = $message[$i];
1619 switch ($char) {
1620 case "<":
1621 $tag = true;
1622 break;
1623 case ">":
1624 $tag = false;
1625 break;
1626 default:
1627 if (!$tag) {
1628 if ($stopzone) {
1629 if ($char == '.' or $char == ' ') {
1630 $truncate = $i+1;
1631 break 2;
1634 $count++;
1636 break;
1638 if (!$stopzone) {
1639 if ($count > $minlength) {
1640 $stopzone = true;
1645 if (!$truncate) {
1646 $truncate = $i;
1649 return substr($message, 0, $truncate);
1654 * Given a string and an array of keywords, this function looks
1655 * for the first keyword in the string, and then chops out a
1656 * small section from the text that shows that word in context.
1657 * @param string $message the text to search
1658 * @param array $keywords array of keywords to find
1660 function message_get_fragment($message, $keywords) {
1662 $fullsize = 160;
1663 $halfsize = (int)($fullsize/2);
1665 $message = strip_tags($message);
1667 foreach ($keywords as $keyword) { // Just get the first one
1668 if ($keyword !== '') {
1669 break;
1672 if (empty($keyword)) { // None found, so just return start of message
1673 return message_shorten_message($message, 30);
1676 $leadin = $leadout = '';
1678 /// Find the start of the fragment
1679 $start = 0;
1680 $length = strlen($message);
1682 $pos = strpos($message, $keyword);
1683 if ($pos > $halfsize) {
1684 $start = $pos - $halfsize;
1685 $leadin = '...';
1687 /// Find the end of the fragment
1688 $end = $start + $fullsize;
1689 if ($end > $length) {
1690 $end = $length;
1691 } else {
1692 $leadout = '...';
1695 /// Pull out the fragment and format it
1697 $fragment = substr($message, $start, $end - $start);
1698 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1699 return $fragment;
1703 * Retrieve the messages between two users
1704 * @param object $user1 the current user
1705 * @param object $user2 the other user
1706 * @param int $limitnum the maximum number of messages to retrieve
1707 * @param bool $viewingnewmessages are we currently viewing new messages?
1709 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1710 global $DB, $CFG;
1712 $messages = array();
1714 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1715 //desc to get the last $limitnum messages then flip the order in php
1716 $sort = 'asc';
1717 if ($limitnum>0) {
1718 $sort = 'desc';
1721 $notificationswhere = null;
1722 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1723 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1724 $notificationswhere = 'AND notification=0';
1727 //prevent notifications of your own actions appearing in your own message history
1728 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1730 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1731 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1732 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1733 "timecreated $sort", '*', 0, $limitnum)) {
1734 foreach ($messages_read as $message) {
1735 $messages[$message->timecreated] = $message;
1738 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1739 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1740 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1741 "timecreated $sort", '*', 0, $limitnum)) {
1742 foreach ($messages_new as $message) {
1743 $messages[$message->timecreated] = $message;
1747 //if we only want the last $limitnum messages
1748 ksort($messages);
1749 $messagecount = count($messages);
1750 if ($limitnum>0 && $messagecount>$limitnum) {
1751 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1754 return $messages;
1758 * Print the message history between two users
1759 * @param object $user1 the current user
1760 * @param object $user2 the other user
1761 * @param string $search search terms to highlight
1762 * @param int $messagelimit maximum number of messages to return
1763 * @param string $messagehistorylink the html for the message history link or false
1764 * @param bool $viewingnewmessages are we currently viewing new messages?
1766 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1767 global $CFG, $OUTPUT;
1769 echo $OUTPUT->box_start('center');
1770 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1771 echo html_writer::start_tag('tr');
1773 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1774 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1775 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1776 echo html_writer::end_tag('td');
1778 echo html_writer::start_tag('td', array('align' => 'center'));
1779 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1780 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1781 echo html_writer::end_tag('td');
1783 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1784 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1785 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1787 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1788 $incontactlist = $user2->iscontact;
1789 $isblocked = $user2->isblocked;
1791 $script = null;
1792 $text = true;
1793 $icon = false;
1795 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1796 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1797 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1799 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1802 echo html_writer::end_tag('td');
1803 echo html_writer::end_tag('tr');
1804 echo html_writer::end_tag('table');
1805 echo $OUTPUT->box_end();
1807 if (!empty($messagehistorylink)) {
1808 echo $messagehistorylink;
1811 /// Get all the messages and print them
1812 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1813 $tablecontents = '';
1815 $current = new stdClass();
1816 $current->mday = '';
1817 $current->month = '';
1818 $current->year = '';
1819 $messagedate = get_string('strftimetime');
1820 $blockdate = get_string('strftimedaydate');
1821 foreach ($messages as $message) {
1822 if ($message->notification) {
1823 $notificationclass = ' notification';
1824 } else {
1825 $notificationclass = null;
1827 $date = usergetdate($message->timecreated);
1828 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1829 $current->mday = $date['mday'];
1830 $current->month = $date['month'];
1831 $current->year = $date['year'];
1833 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1834 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1836 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1839 $formatted_message = $side = null;
1840 if ($message->useridfrom == $user1->id) {
1841 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1842 $side = 'left';
1843 } else {
1844 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1845 $side = 'right';
1847 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1850 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1851 } else {
1852 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1857 * Format a message for display in the message history
1858 * @param object $message the message object
1859 * @param string $format optional date format
1860 * @param string $keywords keywords to highlight
1861 * @param string $class CSS class to apply to the div around the message
1862 * @return string the formatted message
1864 function message_format_message($message, $format='', $keywords='', $class='other') {
1866 static $dateformat;
1868 //if we haven't previously set the date format or they've supplied a new one
1869 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1870 if ($format) {
1871 $dateformat = $format;
1872 } else {
1873 $dateformat = get_string('strftimedatetimeshort');
1876 $time = userdate($message->timecreated, $dateformat);
1877 $options = new stdClass();
1878 $options->para = false;
1880 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1881 if (!empty($message->smallmessage)) {
1882 $messagetext = format_text($message->smallmessage, FORMAT_MOODLE, $options);
1883 } else {
1884 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1887 $messagetext .= message_format_contexturl($message);
1889 if ($keywords) {
1890 $messagetext = highlight($keywords, $messagetext);
1893 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1897 * Format a the context url and context url name of a message for display
1898 * @param object $message the message object
1899 * @return string the formatted string
1901 function message_format_contexturl($message) {
1902 $s = null;
1904 if (!empty($message->contexturl)) {
1905 $displaytext = null;
1906 if (!empty($message->contexturlname)) {
1907 $displaytext= $message->contexturlname;
1908 } else {
1909 $displaytext= $message->contexturl;
1911 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1912 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1913 $s .= html_writer::end_tag('div');
1916 return $s;
1920 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1921 * @param object $userfrom the message sender
1922 * @param object $userto the message recipient
1923 * @param string $message the message
1924 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1925 * @return int|false the ID of the new message or false
1927 function message_post_message($userfrom, $userto, $message, $format) {
1928 global $SITE, $CFG, $USER;
1930 $eventdata = new stdClass();
1931 $eventdata->component = 'moodle';
1932 $eventdata->name = 'instantmessage';
1933 $eventdata->userfrom = $userfrom;
1934 $eventdata->userto = $userto;
1936 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
1937 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
1939 if ($format == FORMAT_HTML) {
1940 $eventdata->fullmessage = '';
1941 $eventdata->fullmessagehtml = $message;
1942 } else {
1943 $eventdata->fullmessage = $message;
1944 $eventdata->fullmessagehtml = '';
1947 $eventdata->fullmessageformat = $format;
1948 $eventdata->smallmessage = strip_tags($message);//strip just in case there are is any html that would break the popup notification
1950 $s = new stdClass();
1951 $s->sitename = $SITE->shortname;
1952 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
1954 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
1955 if (!empty($eventdata->fullmessage)) {
1956 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1958 if (!empty($eventdata->fullmessagehtml)) {
1959 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1962 $eventdata->timecreated = time();
1963 return message_send($eventdata);
1968 * Returns a list of all user ids who have used messaging in the site
1969 * This was the simple way to code the SQL ... is it going to blow up
1970 * on large datasets?
1972 function message_get_participants() {
1973 global $CFG, $DB;
1975 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1976 UNION SELECT useridto as id,1 FROM {message}
1977 UNION SELECT useridfrom as id,1 FROM {message_read}
1978 UNION SELECT useridto as id,1 FROM {message_read}
1979 UNION SELECT userid as id,1 FROM {message_contacts}
1980 UNION SELECT contactid as id,1 from {message_contacts}");
1984 * Print a row of contactlist displaying user picture, messages waiting and
1985 * block links etc
1986 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
1987 * @param bool $incontactlist is the user a contact of ours?
1988 * @param bool $isblocked is the user blocked?
1989 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
1990 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
1991 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
1993 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
1994 global $OUTPUT, $USER;
1995 $fullname = fullname($contact);
1996 $fullnamelink = $fullname;
1998 $linkclass = '';
1999 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2000 $linkclass = 'messageselecteduser';
2003 /// are there any unread messages for this contact?
2004 if ($contact->messagecount > 0 ){
2005 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2008 $strcontact = $strblock = $strhistory = null;
2010 if ($showactionlinks) {
2011 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2012 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2013 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2016 echo html_writer::start_tag('tr');
2017 echo html_writer::start_tag('td', array('class' => 'pix'));
2018 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2019 echo html_writer::end_tag('td');
2021 echo html_writer::start_tag('td', array('class' => 'contact'));
2023 $popupoptions = array(
2024 'height' => MESSAGE_DISCUSSION_HEIGHT,
2025 'width' => MESSAGE_DISCUSSION_WIDTH,
2026 'menubar' => false,
2027 'location' => false,
2028 'status' => true,
2029 'scrollbars' => true,
2030 'resizable' => true);
2032 $link = $action = null;
2033 if (!empty($selectcontacturl)) {
2034 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2035 } else {
2036 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2037 $link = new moodle_url("/message/index.php?id=$contact->id");
2038 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2040 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2042 echo html_writer::end_tag('td');
2044 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2046 echo html_writer::end_tag('tr');
2050 * Constructs the add/remove contact link to display next to other users
2051 * @param bool $incontactlist is the user a contact
2052 * @param bool $isblocked is the user blocked
2053 * @param type $contact contact object
2054 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2055 * @param bool $text include text next to the icons?
2056 * @param bool $icon include a graphical icon?
2057 * @return string
2059 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2060 $strcontact = '';
2062 if($incontactlist){
2063 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2064 } else if ($isblocked) {
2065 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2066 } else{
2067 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2070 return $strcontact;
2074 * Constructs the block contact link to display next to other users
2075 * @param bool $incontactlist is the user a contact
2076 * @param bool $isblocked is the user blocked
2077 * @param type $contact contact object
2078 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2079 * @param bool $text include text next to the icons?
2080 * @param bool $icon include a graphical icon?
2081 * @return string
2083 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2084 $strblock = '';
2086 //commented out to allow the user to block a contact without having to remove them first
2087 /*if ($incontactlist) {
2088 //$strblock = '';
2089 } else*/
2090 if ($isblocked) {
2091 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2092 } else{
2093 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2096 return $strblock;
2100 * Moves messages from a particular user from the message table (unread messages) to message_read
2101 * This is typically only used when a user is deleted
2102 * @param object $userid User id
2103 * @return boolean success
2105 function message_move_userfrom_unread2read($userid) {
2106 global $DB;
2108 // move all unread messages from message table to message_read
2109 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2110 foreach ($messages as $message) {
2111 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2114 return true;
2118 * marks ALL messages being sent from $fromuserid to $touserid as read
2119 * @param int $touserid the id of the message recipient
2120 * @param int $fromuserid the id of the message sender
2121 * @return void
2123 function message_mark_messages_read($touserid, $fromuserid){
2124 global $DB;
2126 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2127 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2129 foreach ($messages as $message) {
2130 message_mark_message_read($message, time());
2135 * Mark a single message as read
2136 * @param message an object with an object property ie $message->id which is an id in the message table
2137 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2138 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2139 * @return int the ID of the message in the message_read table
2141 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2142 global $DB;
2144 $message->timeread = $timeread;
2146 $messageid = $message->id;
2147 unset($message->id);//unset because it will get a new id on insert into message_read
2149 //If any processors have pending actions abort them
2150 if (!$messageworkingempty) {
2151 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2153 $messagereadid = $DB->insert_record('message_read', $message);
2154 $DB->delete_records('message', array('id' => $messageid));
2155 return $messagereadid;
2159 * A helper function that prints a formatted heading
2160 * @param string $title the heading to display
2161 * @param int $colspan
2163 function message_print_heading($title, $colspan=3) {
2164 echo html_writer::start_tag('tr');
2165 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2166 echo html_writer::end_tag('tr');