MDL-24394 qtype_match: should be able to use multilang for the choices.
[moodle.git] / message / lib.php
blobb86f456c03b68a05f0a4ea636caff24d32a0217b
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 /**
57 * Define contants for messaging default settings population. For unambiguity of
58 * plugin developer intentions we use 4-bit value (LSB numbering):
59 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
60 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
61 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
63 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
66 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
67 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
69 define('MESSAGE_DISALLOWED', 0x04); // 0100
70 define('MESSAGE_PERMITTED', 0x08); // 1000
71 define('MESSAGE_FORCED', 0x0c); // 1100
73 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
75 /**
76 * Set default value for default outputs permitted setting
78 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
80 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
81 $CFG->message_contacts_refresh = 60;
83 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
84 $CFG->message_chat_refresh = 5;
86 if (!isset($CFG->message_offline_time)) {
87 $CFG->message_offline_time = 300;
90 /**
91 * Print the selector that allows the user to view their contacts, course participants, their recent
92 * conversations etc
94 * @param int $countunreadtotal how many unread messages does the user have?
95 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
96 * @param object $user1 the user whose messages are being viewed
97 * @param object $user2 the user $user1 is talking to
98 * @param array $blockedusers an array of users blocked by $user1
99 * @param array $onlinecontacts an array of $user1's online contacts
100 * @param array $offlinecontacts an array of $user1's offline contacts
101 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
102 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
103 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
104 * @return void
106 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
107 global $PAGE;
109 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
111 //if 0 unread messages and they've requested unread messages then show contacts
112 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
113 $viewing = MESSAGE_VIEW_CONTACTS;
116 //if they have no blocked users and they've requested blocked users switch them over to contacts
117 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
118 $viewing = MESSAGE_VIEW_CONTACTS;
121 $onlyactivecourses = true;
122 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
123 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
125 $strunreadmessages = null;
126 if ($countunreadtotal>0) { //if there are unread messages
127 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
130 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
132 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
133 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
134 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
135 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
136 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
137 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
138 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
139 $courseidtoshow = intval(substr($viewing, 7));
141 if (!empty($courseidtoshow)
142 && array_key_exists($courseidtoshow, $coursecontexts)
143 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
145 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
146 } else {
147 //shouldn't get here. User trying to access a course they're not in perhaps.
148 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
152 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
153 echo html_writer::start_tag('fieldset');
154 $managebuttonclass = 'visible';
155 if ($viewing == MESSAGE_VIEW_SEARCH) {
156 $managebuttonclass = 'hiddenelement';
158 $strmanagecontacts = get_string('search','message');
159 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
160 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
161 echo html_writer::end_tag('fieldset');
162 echo html_writer::end_tag('form');
164 echo html_writer::end_tag('div');
168 * Print course participants. Called by message_print_contact_selector()
170 * @param object $context the course context
171 * @param int $courseid the course ID
172 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
173 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
174 * @param string $titletodisplay Optionally specify a title to display above the participants
175 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
176 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
177 * @return void
179 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
180 global $DB, $USER, $PAGE, $OUTPUT;
182 if (empty($titletodisplay)) {
183 $titletodisplay = get_string('participants');
186 $countparticipants = count_enrolled_users($context);
187 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
189 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
190 echo $OUTPUT->render($pagingbar);
192 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
194 echo html_writer::start_tag('tr');
195 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
196 echo html_writer::end_tag('tr');
198 //todo these need to come from somewhere if the course participants list is to show users with unread messages
199 $iscontact = true;
200 $isblocked = false;
201 foreach ($participants as $participant) {
202 if ($participant->id != $USER->id) {
203 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
204 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
208 echo html_writer::end_tag('table');
212 * Retrieve users blocked by $user1
214 * @param object $user1 the user whose messages are being viewed
215 * @param object $user2 the user $user1 is talking to. If they are being blocked
216 * they will have a variable called 'isblocked' added to their user object
217 * @return array the users blocked by $user1
219 function message_get_blocked_users($user1=null, $user2=null) {
220 global $DB, $USER;
222 if (empty($user1)) {
223 $user1 = $USER;
226 if (!empty($user2)) {
227 $user2->isblocked = false;
230 $blockedusers = array();
232 $userfields = user_picture::fields('u', array('lastaccess'));
233 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
234 FROM {message_contacts} mc
235 JOIN {user} u ON u.id = mc.contactid
236 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
237 WHERE mc.userid = :user1id2 AND mc.blocked = 1
238 GROUP BY $userfields
239 ORDER BY u.firstname ASC";
240 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
242 foreach($rs as $rd) {
243 $blockedusers[] = $rd;
245 if (!empty($user2) && $user2->id == $rd->id) {
246 $user2->isblocked = true;
249 $rs->close();
251 return $blockedusers;
255 * Print users blocked by $user1. Called by message_print_contact_selector()
257 * @param array $blockedusers the users blocked by $user1
258 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
259 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
260 * @param string $titletodisplay Optionally specify a title to display above the participants
261 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
262 * @return void
264 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
265 global $DB, $USER;
267 $countblocked = count($blockedusers);
269 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
271 if (!empty($titletodisplay)) {
272 echo html_writer::start_tag('tr');
273 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
274 echo html_writer::end_tag('tr');
277 if ($countblocked) {
278 echo html_writer::start_tag('tr');
279 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
280 echo html_writer::end_tag('tr');
282 $isuserblocked = true;
283 $isusercontact = false;
284 foreach ($blockedusers as $blockeduser) {
285 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
289 echo html_writer::end_tag('table');
293 * Retrieve $user1's contacts (online, offline and strangers)
295 * @param object $user1 the user whose messages are being viewed
296 * @param object $user2 the user $user1 is talking to. If they are a contact
297 * they will have a variable called 'iscontact' added to their user object
298 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
300 function message_get_contacts($user1=null, $user2=null) {
301 global $DB, $CFG, $USER;
303 if (empty($user1)) {
304 $user1 = $USER;
307 if (!empty($user2)) {
308 $user2->iscontact = false;
311 $timetoshowusers = 300; //Seconds default
312 if (isset($CFG->block_online_users_timetosee)) {
313 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
316 // time which a user is counting as being active since
317 $timefrom = time()-$timetoshowusers;
319 // people in our contactlist who are online
320 $onlinecontacts = array();
321 // people in our contactlist who are offline
322 $offlinecontacts = array();
323 // people who are not in our contactlist but have sent us a message
324 $strangers = array();
326 $userfields = user_picture::fields('u', array('lastaccess'));
328 // get all in our contactlist who are not blocked in our contact list
329 // and count messages we have waiting from each of them
330 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
331 FROM {message_contacts} mc
332 JOIN {user} u ON u.id = mc.contactid
333 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
334 WHERE mc.userid = ? AND mc.blocked = 0
335 GROUP BY $userfields
336 ORDER BY u.firstname ASC";
338 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
339 foreach ($rs as $rd) {
340 if ($rd->lastaccess >= $timefrom) {
341 // they have been active recently, so are counted online
342 $onlinecontacts[] = $rd;
344 } else {
345 $offlinecontacts[] = $rd;
348 if (!empty($user2) && $user2->id == $rd->id) {
349 $user2->iscontact = true;
352 $rs->close();
354 // get messages from anyone who isn't in our contact list and count the number
355 // of messages we have from each of them
356 $strangersql = "SELECT $userfields, count(m.id) as messagecount
357 FROM {message} m
358 JOIN {user} u ON u.id = m.useridfrom
359 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
360 WHERE mc.id IS NULL AND m.useridto = ?
361 GROUP BY $userfields
362 ORDER BY u.firstname ASC";
364 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
365 foreach ($rs as $rd) {
366 $strangers[] = $rd;
368 $rs->close();
370 return array($onlinecontacts, $offlinecontacts, $strangers);
374 * Print $user1's contacts. Called by message_print_contact_selector()
376 * @param array $onlinecontacts $user1's contacts which are online
377 * @param array $offlinecontacts $user1's contacts which are offline
378 * @param array $strangers users which are not contacts but who have messaged $user1
379 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
380 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
381 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
382 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
383 * @param string $titletodisplay Optionally specify a title to display above the participants
384 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
385 * @return void
387 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
388 global $CFG, $PAGE, $OUTPUT;
390 $countonlinecontacts = count($onlinecontacts);
391 $countofflinecontacts = count($offlinecontacts);
392 $countstrangers = count($strangers);
393 $isuserblocked = null;
395 if ($countonlinecontacts + $countofflinecontacts == 0) {
396 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
399 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
401 if (!empty($titletodisplay)) {
402 message_print_heading($titletodisplay);
405 if($countonlinecontacts) {
406 /// print out list of online contacts
408 if (empty($titletodisplay)) {
409 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
412 $isuserblocked = false;
413 $isusercontact = true;
414 foreach ($onlinecontacts as $contact) {
415 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
416 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
421 if ($countofflinecontacts) {
422 /// print out list of offline contacts
424 if (empty($titletodisplay)) {
425 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
428 $isuserblocked = false;
429 $isusercontact = true;
430 foreach ($offlinecontacts as $contact) {
431 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
432 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
438 /// print out list of incoming contacts
439 if ($countstrangers) {
440 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
442 $isuserblocked = false;
443 $isusercontact = false;
444 foreach ($strangers as $stranger) {
445 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
446 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
451 echo html_writer::end_tag('table');
453 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
454 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
459 * Print a select box allowing the user to choose to view new messages, course participants etc.
461 * Called by message_print_contact_selector()
462 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
463 * @param array $courses array of course objects. The courses the user is enrolled in.
464 * @param array $coursecontexts array of course contexts. Keyed on course id.
465 * @param int $countunreadtotal how many unread messages does the user have?
466 * @param int $countblocked how many users has the current user blocked?
467 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
468 * @return void
470 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
471 $options = array();
472 $textlib = textlib_get_instance(); // going to use textlib services
474 if ($countunreadtotal>0) { //if there are unread messages
475 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
478 $str = get_string('mycontacts', 'message');
479 $options[MESSAGE_VIEW_CONTACTS] = $str;
481 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
482 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
484 if (!empty($courses)) {
485 $courses_options = array();
487 foreach($courses as $course) {
488 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
489 //Not using short_text() as we want the end of the course name. Not the beginning.
490 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
491 if ($textlib->strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
492 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.$textlib->substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
493 } else {
494 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
499 if (!empty($courses_options)) {
500 $options[] = array(get_string('courses') => $courses_options);
504 if ($countblocked>0) {
505 $str = get_string('blockedusers','message', $countblocked);
506 $options[MESSAGE_VIEW_BLOCKED] = $str;
509 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
510 echo html_writer::start_tag('fieldset');
511 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
512 echo html_writer::end_tag('fieldset');
513 echo html_writer::end_tag('form');
517 * Load the course contexts for all of the users courses
519 * @param array $courses array of course objects. The courses the user is enrolled in.
520 * @return array of course contexts
522 function message_get_course_contexts($courses) {
523 $coursecontexts = array();
525 foreach($courses as $course) {
526 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
529 return $coursecontexts;
533 * strip off action parameters like 'removecontact'
535 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
536 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
538 function message_remove_url_params($moodleurl) {
539 $newurl = new moodle_url($moodleurl);
540 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
541 return $newurl->out();
545 * Count the number of messages with a field having a specified value.
546 * if $field is empty then return count of the whole array
547 * if $field is non-existent then return 0
549 * @param array $messagearray array of message objects
550 * @param string $field the field to inspect on the message objects
551 * @param string $value the value to test the field against
553 function message_count_messages($messagearray, $field='', $value='') {
554 if (!is_array($messagearray)) return 0;
555 if ($field == '' or empty($messagearray)) return count($messagearray);
557 $count = 0;
558 foreach ($messagearray as $message) {
559 $count += ($message->$field == $value) ? 1 : 0;
561 return $count;
565 * Returns the count of unread messages for user. Either from a specific user or from all users.
567 * @param object $user1 the first user. Defaults to $USER
568 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
569 * @return int the count of $user1's unread messages
571 function message_count_unread_messages($user1=null, $user2=null) {
572 global $USER, $DB;
574 if (empty($user1)) {
575 $user1 = $USER;
578 if (!empty($user2)) {
579 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
580 array($user1->id, $user2->id), "COUNT('id')");
581 } else {
582 return $DB->count_records_select('message', "useridto = ?",
583 array($user1->id), "COUNT('id')");
588 * Count the number of users blocked by $user1
590 * @param object $user1 user object
591 * @return int the number of blocked users
593 function message_count_blocked_users($user1=null) {
594 global $USER, $DB;
596 if (empty($user1)) {
597 $user1 = $USER;
600 $sql = "SELECT count(mc.id)
601 FROM {message_contacts} mc
602 WHERE mc.userid = :userid AND mc.blocked = 1";
603 $params = array('userid' => $user1->id);
605 return $DB->count_records_sql($sql, $params);
609 * Print the search form and search results if a search has been performed
611 * @param boolean $advancedsearch show basic or advanced search form
612 * @param object $user1 the current user
613 * @return boolean true if a search was performed
615 function message_print_search($advancedsearch = false, $user1=null) {
616 $frm = data_submitted();
618 $doingsearch = false;
619 if ($frm) {
620 if (confirm_sesskey()) {
621 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
622 } else {
623 $frm = false;
627 if (!empty($frm->combinedsearch)) {
628 $combinedsearchstring = $frm->combinedsearch;
629 } else {
630 //$combinedsearchstring = get_string('searchcombined','message').'...';
631 $combinedsearchstring = '';
634 if ($doingsearch) {
635 if ($advancedsearch) {
637 $messagesearch = '';
638 if (!empty($frm->keywords)) {
639 $messagesearch = $frm->keywords;
641 $personsearch = '';
642 if (!empty($frm->name)) {
643 $personsearch = $frm->name;
645 include('search_advanced.html');
646 } else {
647 include('search.html');
650 $showicontext = false;
651 message_print_search_results($frm, $showicontext, $user1);
653 return true;
654 } else {
656 if ($advancedsearch) {
657 $personsearch = $messagesearch = '';
658 include('search_advanced.html');
659 } else {
660 include('search.html');
662 return false;
667 * Get the users recent conversations meaning all the people they've recently
668 * sent or received a message from plus the most recent message sent to or received from each other user
670 * @param object $user the current user
671 * @param int $limitfrom can be used for paging
672 * @param int $limitto can be used for paging
673 * @return array
675 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
676 global $DB;
678 $userfields = user_picture::fields('u', array('lastaccess'));
679 //This query retrieves the last message received from and sent to each user
680 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
681 //It then joins with some other tables to get some additional data we need
683 //message ID is used instead of timecreated as it should sort the same and will be much faster
685 //There is a separate query for read and unread queries as they are stored in different tables
686 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
687 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
688 FROM {message_read} mr
689 JOIN (
690 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
691 FROM (
692 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
693 FROM {message_read} mr1
694 WHERE mr1.useridfrom = :userid1
695 AND mr1.notification = 0
696 GROUP BY mr1.useridto
697 UNION
698 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
699 FROM {message_read} mr2
700 WHERE mr2.useridto = :userid2
701 AND mr2.notification = 0
702 GROUP BY mr2.useridfrom
703 ) messages
704 GROUP BY messages.userid
705 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
706 JOIN {user} u ON u.id = messages2.userid
707 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
708 WHERE u.deleted = '0'
709 ORDER BY mr.id DESC";
710 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
711 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
713 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
714 FROM {message} m
715 JOIN (
716 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
717 FROM (
718 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
719 FROM {message} m1
720 WHERE m1.useridfrom = :userid1
721 AND m1.notification = 0
722 GROUP BY m1.useridto
723 UNION
724 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
725 FROM {message} m2
726 WHERE m2.useridto = :userid2
727 AND m2.notification = 0
728 GROUP BY m2.useridfrom
729 ) messages
730 GROUP BY messages.userid
731 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
732 JOIN {user} u ON u.id = messages2.userid
733 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
734 WHERE u.deleted = '0'
735 ORDER BY m.id DESC";
736 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
738 $conversations = array();
740 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
741 //$conversation->id (the array key) is the other user's ID
742 $conversation_arrays = array($unread, $read);
743 foreach ($conversation_arrays as $conversation_array) {
744 foreach ($conversation_array as $conversation) {
745 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
746 $conversations[$conversation->id] = $conversation;
751 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
752 //and there may be multiple conversations with the same timecreated value.
753 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
754 usort($conversations, "conversationsort");
756 return $conversations;
760 * Sort function used to order conversations
762 * @param object $a A conversation object
763 * @param object $b A conversation object
764 * @return integer
766 function conversationsort($a, $b)
768 if ($a->timecreated == $b->timecreated) {
769 return 0;
771 return ($a->timecreated > $b->timecreated) ? -1 : 1;
775 * Get the users recent event notifications
777 * @param object $user the current user
778 * @param int $limitfrom can be used for paging
779 * @param int $limitto can be used for paging
780 * @return array
782 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
783 global $DB;
785 $userfields = user_picture::fields('u', array('lastaccess'));
786 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
787 FROM {message_read} mr
788 JOIN {user} u ON u.id=mr.useridfrom
789 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
790 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
791 $params = array('userid1' => $user->id, 'notification' => 1);
793 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
794 return $notifications;
798 * Print the user's recent conversations
800 * @param object $user1 the current user
801 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
802 * @return void
804 function message_print_recent_conversations($user=null, $showicontext=false) {
805 global $USER;
807 echo html_writer::start_tag('p', array('class' => 'heading'));
808 echo get_string('mostrecentconversations', 'message');
809 echo html_writer::end_tag('p');
811 if (empty($user)) {
812 $user = $USER;
815 $conversations = message_get_recent_conversations($user);
817 $showotheruser = true;
818 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
822 * Print the user's recent notifications
824 * @param object $user1 the current user
825 * @return void
827 function message_print_recent_notifications($user=null) {
828 global $USER;
830 echo html_writer::start_tag('p', array('class' => 'heading'));
831 echo get_string('mostrecentnotifications', 'message');
832 echo html_writer::end_tag('p');
834 if (empty($user)) {
835 $user = $USER;
838 $notifications = message_get_recent_notifications($user);
840 $showicontext = false;
841 $showotheruser = false;
842 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
846 * Print a list of recent messages
848 * @staticvar type $dateformat
849 * @param array $messages the messages to display
850 * @param object $user the current user
851 * @param bool $showotheruser display information on the other user?
852 * @param bool $showicontext show text next to the action icons?
853 * @return void
855 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
856 global $OUTPUT;
857 static $dateformat;
859 if (empty($dateformat)) {
860 $dateformat = get_string('strftimedatetimeshort');
863 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
864 foreach ($messages as $message) {
865 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
867 if ($showotheruser) {
868 if ( $message->contactlistid ) {
869 if ($message->blocked == 0) { /// not blocked
870 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
871 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
872 } else { // blocked
873 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
874 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
876 } else {
877 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
878 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
881 //should we show just the icon or icon and text?
882 $histicontext = 'icon';
883 if ($showicontext) {
884 $histicontext = 'both';
886 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
888 echo html_writer::start_tag('span', array('class' => 'otheruser'));
890 echo html_writer::start_tag('span', array('class' => 'pix'));
891 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
892 echo html_writer::end_tag('span');
894 echo html_writer::start_tag('span', array('class' => 'contact'));
896 $link = new moodle_url("/message/index.php?id=$message->id");
897 $action = null;
898 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
900 echo html_writer::end_tag('span');//end contact
902 echo $strcontact.$strblock.$strhistory;
903 echo html_writer::end_tag('span');//end otheruser
905 $messagetoprint = null;
906 if (!empty($message->smallmessage)) {
907 $messagetoprint = $message->smallmessage;
908 } else {
909 $messagetoprint = $message->fullmessage;
912 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
913 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
914 echo message_format_contexturl($message);
915 echo html_writer::end_tag('div');//end singlemessage
917 echo html_writer::end_tag('div');//end messagerecent
921 * Add the selected user as a contact for the current user
923 * @param int $contactid the ID of the user to add as a contact
924 * @param int $blocked 1 if you wish to block the contact
925 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
926 * Otherwise returns the result of update_record() or insert_record()
928 function message_add_contact($contactid, $blocked=0) {
929 global $USER, $DB;
931 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
932 return false;
935 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
936 /// record already exists - we may be changing blocking status
938 if ($contact->blocked !== $blocked) {
939 /// change to blocking status
940 $contact->blocked = $blocked;
941 return $DB->update_record('message_contacts', $contact);
942 } else {
943 /// no changes to blocking status
944 return true;
947 } else {
948 /// new contact record
949 unset($contact);
950 $contact->userid = $USER->id;
951 $contact->contactid = $contactid;
952 $contact->blocked = $blocked;
953 return $DB->insert_record('message_contacts', $contact, false);
958 * remove a contact
960 * @param type $contactid the user ID of the contact to remove
961 * @return bool returns the result of delete_records()
963 function message_remove_contact($contactid) {
964 global $USER, $DB;
965 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
969 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
971 * @param int $contactid the user ID of the contact to unblock
972 * @return bool returns the result of delete_records()
974 function message_unblock_contact($contactid) {
975 global $USER, $DB;
976 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
980 * block a user
982 * @param int $contactid the user ID of the user to block
984 function message_block_contact($contactid) {
985 return message_add_contact($contactid, 1);
989 * Load a user's contact record
991 * @param int $contactid the user ID of the user whose contact record you want
992 * @return array message contacts
994 function message_get_contact($contactid) {
995 global $USER, $DB;
996 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1000 * Print the results of a message search
1002 * @param mixed $frm submitted form data
1003 * @param bool $showicontext show text next to action icons?
1004 * @param object $currentuser the current user
1005 * @return void
1007 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1008 global $USER, $DB, $OUTPUT;
1010 if (empty($currentuser)) {
1011 $currentuser = $USER;
1014 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1016 $personsearch = false;
1017 $personsearchstring = null;
1018 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1019 $personsearch = true;
1020 $personsearchstring = $frm->name;
1021 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1022 $personsearch = true;
1023 $personsearchstring = $frm->combinedsearch;
1026 /// search for person
1027 if ($personsearch) {
1028 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1029 $users = array();
1030 $mycourses = enrol_get_my_courses();
1031 foreach ($mycourses as $mycourse) {
1032 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1033 foreach ($susers as $suser) $users[$suser->id] = $suser;
1036 } else {
1037 $users = message_search_users(SITEID, $personsearchstring);
1040 if (!empty($users)) {
1041 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1042 echo get_string('userssearchresults', 'message', count($users));
1043 echo html_writer::end_tag('p');
1045 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1046 foreach ($users as $user) {
1048 if ( $user->contactlistid ) {
1049 if ($user->blocked == 0) { /// not blocked
1050 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1051 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1052 } else { // blocked
1053 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1054 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1056 } else {
1057 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1058 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1061 //should we show just the icon or icon and text?
1062 $histicontext = 'icon';
1063 if ($showicontext) {
1064 $histicontext = 'both';
1066 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1068 echo html_writer::start_tag('tr');
1070 echo html_writer::start_tag('td', array('class' => 'pix'));
1071 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1072 echo html_writer::end_tag('td');
1074 echo html_writer::start_tag('td',array('class' => 'contact'));
1075 $action = null;
1076 $link = new moodle_url("/message/index.php?id=$user->id");
1077 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1078 echo html_writer::end_tag('td');
1080 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1081 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1082 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1084 echo html_writer::end_tag('tr');
1086 echo html_writer::end_tag('table');
1088 } else {
1089 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1090 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1091 echo html_writer::end_tag('p');
1095 // search messages for keywords
1096 $messagesearch = false;
1097 $messagesearchstring = null;
1098 if (!empty($frm->keywords)) {
1099 $messagesearch = true;
1100 $messagesearchstring = clean_text(trim($frm->keywords));
1101 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1102 $messagesearch = true;
1103 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1106 if ($messagesearch) {
1107 if ($messagesearchstring) {
1108 $keywords = explode(' ', $messagesearchstring);
1109 } else {
1110 $keywords = array();
1112 $tome = false;
1113 $fromme = false;
1114 $courseid = 'none';
1116 if (empty($frm->keywordsoption)) {
1117 $frm->keywordsoption = 'allmine';
1120 switch ($frm->keywordsoption) {
1121 case 'tome':
1122 $tome = true;
1123 break;
1124 case 'fromme':
1125 $fromme = true;
1126 break;
1127 case 'allmine':
1128 $tome = true;
1129 $fromme = true;
1130 break;
1131 case 'allusers':
1132 $courseid = SITEID;
1133 break;
1134 case 'courseusers':
1135 $courseid = $frm->courseid;
1136 break;
1137 default:
1138 $tome = true;
1139 $fromme = true;
1142 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1144 /// get a list of contacts
1145 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1146 $contacts = array();
1149 /// print heading with number of results
1150 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1151 $countresults = count($messages);
1152 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1153 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1154 } else {
1155 echo get_string('keywordssearchresults', 'message', $countresults);
1157 echo html_writer::end_tag('p');
1159 /// print table headings
1160 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1162 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1163 $headertdend = html_writer::end_tag('td');
1164 echo html_writer::start_tag('tr');
1165 echo $headertdstart.get_string('from').$headertdend;
1166 echo $headertdstart.get_string('to').$headertdend;
1167 echo $headertdstart.get_string('message', 'message').$headertdend;
1168 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1169 echo html_writer::end_tag('tr');
1171 $blockedcount = 0;
1172 $dateformat = get_string('strftimedatetimeshort');
1173 $strcontext = get_string('context', 'message');
1174 foreach ($messages as $message) {
1176 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1177 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1178 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1179 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1182 $blockedcount ++;
1183 continue;
1186 /// load up user to record
1187 if ($message->useridto !== $USER->id) {
1188 $userto = $DB->get_record('user', array('id' => $message->useridto));
1189 $tocontact = (array_key_exists($message->useridto, $contacts) and
1190 ($contacts[$message->useridto]->blocked == 0) );
1191 $toblocked = (array_key_exists($message->useridto, $contacts) and
1192 ($contacts[$message->useridto]->blocked == 1) );
1193 } else {
1194 $userto = false;
1195 $tocontact = false;
1196 $toblocked = false;
1199 /// load up user from record
1200 if ($message->useridfrom !== $USER->id) {
1201 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1202 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1203 ($contacts[$message->useridfrom]->blocked == 0) );
1204 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1205 ($contacts[$message->useridfrom]->blocked == 1) );
1206 } else {
1207 $userfrom = false;
1208 $fromcontact = false;
1209 $fromblocked = false;
1212 /// find date string for this message
1213 $date = usergetdate($message->timecreated);
1214 $datestring = $date['year'].$date['mon'].$date['mday'];
1216 /// print out message row
1217 echo html_writer::start_tag('tr', array('valign' => 'top'));
1219 echo html_writer::start_tag('td', array('class' => 'contact'));
1220 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1221 echo html_writer::end_tag('td');
1223 echo html_writer::start_tag('td', array('class' => 'contact'));
1224 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1225 echo html_writer::end_tag('td');
1227 echo html_writer::start_tag('td', array('class' => 'summary'));
1228 echo message_get_fragment($message->fullmessage, $keywords);
1229 echo html_writer::start_tag('div', array('class' => 'link'));
1231 //If the user clicks the context link display message sender on the left
1232 //EXCEPT if the current user is in the conversation. Current user == always on the left
1233 $leftsideuserid = $rightsideuserid = null;
1234 if ($currentuser->id == $message->useridto) {
1235 $leftsideuserid = $message->useridto;
1236 $rightsideuserid = $message->useridfrom;
1237 } else {
1238 $leftsideuserid = $message->useridfrom;
1239 $rightsideuserid = $message->useridto;
1241 message_history_link($leftsideuserid, $rightsideuserid, false,
1242 $messagesearchstring, 'm'.$message->id, $strcontext);
1243 echo html_writer::end_tag('div');
1244 echo html_writer::end_tag('td');
1246 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1248 echo html_writer::end_tag('tr');
1252 if ($blockedcount > 0) {
1253 echo html_writer::start_tag('tr');
1254 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1255 echo html_writer::end_tag('tr');
1257 echo html_writer::end_tag('table');
1259 } else {
1260 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1264 if (!$personsearch && !$messagesearch) {
1265 //they didn't enter any search terms
1266 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1269 echo html_writer::end_tag('div');
1273 * Print information on a user. Used when printing search results.
1275 * @param object/bool $user the user to display or false if you just want $USER
1276 * @param bool $iscontact is the user being displayed a contact?
1277 * @param bool $isblocked is the user being displayed blocked?
1278 * @param bool $includeicontext include text next to the action icons?
1279 * @return void
1281 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1282 global $USER, $OUTPUT;
1284 if ($user === false) {
1285 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1286 } else {
1287 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1288 echo '&nbsp;';
1290 $return = false;
1291 $script = null;
1292 if ($iscontact) {
1293 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1294 } else {
1295 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1297 echo '&nbsp;';
1298 if ($isblocked) {
1299 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1300 } else {
1301 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1304 $popupoptions = array(
1305 'height' => MESSAGE_DISCUSSION_HEIGHT,
1306 'width' => MESSAGE_DISCUSSION_WIDTH,
1307 'menubar' => false,
1308 'location' => false,
1309 'status' => true,
1310 'scrollbars' => true,
1311 'resizable' => true);
1313 $link = new moodle_url("/message/index.php?id=$user->id");
1314 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1315 $action = null;
1316 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1322 * Print a message contact link
1324 * @staticvar type $str
1325 * @param int $userid the ID of the user to apply to action to
1326 * @param string $linktype can be add, remove, block or unblock
1327 * @param bool $return if true return the link as a string. If false echo the link.
1328 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1329 * @param bool $text include text next to the icons?
1330 * @param bool $icon include a graphical icon?
1331 * @return string if $return is true otherwise bool
1333 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1334 global $OUTPUT, $PAGE;
1336 //hold onto the strings as we're probably creating a bunch of links
1337 static $str;
1339 if (empty($script)) {
1340 //strip off previous action params like 'removecontact'
1341 $script = message_remove_url_params($PAGE->url);
1344 if (empty($str->blockcontact)) {
1345 $str->blockcontact = get_string('blockcontact', 'message');
1346 $str->unblockcontact = get_string('unblockcontact', 'message');
1347 $str->removecontact = get_string('removecontact', 'message');
1348 $str->addcontact = get_string('addcontact', 'message');
1351 $command = $linktype.'contact';
1352 $string = $str->{$command};
1354 $safealttext = s($string);
1356 $safestring = '';
1357 if (!empty($text)) {
1358 $safestring = $safealttext;
1361 $img = '';
1362 if ($icon) {
1363 $iconpath = null;
1364 switch ($linktype) {
1365 case 'block':
1366 $iconpath = 't/block';
1367 break;
1368 case 'unblock':
1369 $iconpath = 't/userblue';
1370 break;
1371 case 'remove':
1372 $iconpath = 'i/cross_red_big';
1373 break;
1374 case 'add':
1375 default:
1376 $iconpath = 't/addgreen';
1379 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1382 $output = '<span class="'.$linktype.'contact">'.
1383 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1384 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1385 $img.
1386 $safestring.'</a></span>';
1388 if ($return) {
1389 return $output;
1390 } else {
1391 echo $output;
1392 return true;
1397 * echo or return a link to take the user to the full message history between themselves and another user
1399 * @staticvar type $strmessagehistory
1400 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1401 * @param int $userid2 the ID of the other user
1402 * @param bool $return true to return the link as a string. False to echo the link.
1403 * @param string $keywords any keywords to highlight in the message history
1404 * @param string $position anchor name to jump to within the message history
1405 * @param string $linktext optionally specify the link text
1406 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1408 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1409 global $OUTPUT;
1410 static $strmessagehistory;
1412 if (empty($strmessagehistory)) {
1413 $strmessagehistory = get_string('messagehistory', 'message');
1416 if ($position) {
1417 $position = "#$position";
1419 if ($keywords) {
1420 $keywords = "&search=".urlencode($keywords);
1423 if ($linktext == 'icon') { // Icon only
1424 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1425 } else if ($linktext == 'both') { // Icon and standard name
1426 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1427 $fulllink .= '&nbsp;'.$strmessagehistory;
1428 } else if ($linktext) { // Custom name
1429 $fulllink = $linktext;
1430 } else { // Standard name only
1431 $fulllink = $strmessagehistory;
1434 $popupoptions = array(
1435 'height' => 500,
1436 'width' => 500,
1437 'menubar' => false,
1438 'location' => false,
1439 'status' => true,
1440 'scrollbars' => true,
1441 'resizable' => true);
1443 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1444 $action = null;
1445 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1447 $str = '<span class="history">'.$str.'</span>';
1449 if ($return) {
1450 return $str;
1451 } else {
1452 echo $str;
1453 return true;
1459 * Search through course users
1461 * If $coursid specifies the site course then this function searches
1462 * through all undeleted and confirmed users
1463 * @param int $courseid The course in question.
1464 * @param string $searchtext the text to search for
1465 * @param string $sort the column name to order by
1466 * @param string $exceptions comma separated list of user IDs to exclude
1467 * @return array An array of {@link $USER} records.
1469 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1470 global $CFG, $USER, $DB;
1472 $fullname = $DB->sql_fullname();
1474 if (!empty($exceptions)) {
1475 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1476 } else {
1477 $except = '';
1480 if (!empty($sort)) {
1481 $order = ' ORDER BY '. $sort;
1482 } else {
1483 $order = '';
1486 $ufields = user_picture::fields('u');
1487 if (!$courseid or $courseid == SITEID) {
1488 $params = array($USER->id, "%$searchtext%");
1489 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1490 FROM {user} u
1491 LEFT JOIN {message_contacts} mc
1492 ON mc.contactid = u.id AND mc.userid = ?
1493 WHERE u.deleted = '0' AND u.confirmed = '1'
1494 AND (".$DB->sql_like($fullname, '?', false).")
1495 $except
1496 $order", $params);
1497 } else {
1498 //TODO: add enabled enrolment join here (skodak)
1499 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1500 $contextlists = get_related_contexts_string($context);
1502 // everyone who has a role assignment in this course or higher
1503 $params = array($USER->id, "%$searchtext%");
1504 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1505 FROM {user} u
1506 JOIN {role_assignments} ra ON ra.userid = u.id
1507 LEFT JOIN {message_contacts} mc
1508 ON mc.contactid = u.id AND mc.userid = ?
1509 WHERE u.deleted = '0' AND u.confirmed = '1'
1510 AND ra.contextid $contextlists
1511 AND (".$DB->sql_like($fullname, '?', false).")
1512 $except
1513 $order", $params);
1515 return $users;
1520 * search a user's messages
1522 * @param array $searchterms an array of search terms (strings)
1523 * @param bool $fromme include messages from the user?
1524 * @param bool $tome include messages to the user?
1525 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1526 * @param int $userid the user ID of the current user
1527 * @return mixed An array of messages or false if no matching messages were found
1529 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1530 /// Returns a list of posts found using an array of search terms
1531 /// eg word +word -word
1533 global $CFG, $USER, $DB;
1535 /// If no userid sent then assume current user
1536 if ($userid == 0) $userid = $USER->id;
1538 /// Some differences in SQL syntax
1539 if ($DB->sql_regex_supported()) {
1540 $REGEXP = $DB->sql_regex(true);
1541 $NOTREGEXP = $DB->sql_regex(false);
1544 $searchcond = array();
1545 $params = array();
1546 $i = 0;
1548 //preprocess search terms to check whether we have at least 1 eligible search term
1549 //if we do we can drop words around it like 'a'
1550 $dropshortwords = false;
1551 foreach ($searchterms as $searchterm) {
1552 if (strlen($searchterm) >= 2) {
1553 $dropshortwords = true;
1557 foreach ($searchterms as $searchterm) {
1558 $i++;
1560 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1562 if ($dropshortwords && strlen($searchterm) < 2) {
1563 continue;
1565 /// Under Oracle and MSSQL, trim the + and - operators and perform
1566 /// simpler LIKE search
1567 if (!$DB->sql_regex_supported()) {
1568 if (substr($searchterm, 0, 1) == '-') {
1569 $NOT = true;
1571 $searchterm = trim($searchterm, '+-');
1574 if (substr($searchterm,0,1) == "+") {
1575 $searchterm = substr($searchterm,1);
1576 $searchterm = preg_quote($searchterm, '|');
1577 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1578 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1580 } else if (substr($searchterm,0,1) == "-") {
1581 $searchterm = substr($searchterm,1);
1582 $searchterm = preg_quote($searchterm, '|');
1583 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1584 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1586 } else {
1587 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1588 $params['ss'.$i] = "%$searchterm%";
1592 if (empty($searchcond)) {
1593 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1594 $params['ss1'] = "%";
1595 } else {
1596 $searchcond = implode(" AND ", $searchcond);
1599 /// There are several possibilities
1600 /// 1. courseid = SITEID : The admin is searching messages by all users
1601 /// 2. courseid = ?? : A teacher is searching messages by users in
1602 /// one of their courses - currently disabled
1603 /// 3. courseid = none : User is searching their own messages;
1604 /// a. Messages from user
1605 /// b. Messages to user
1606 /// c. Messages to and from user
1608 if ($courseid == SITEID) { /// admin is searching all messages
1609 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1610 FROM {message_read} m
1611 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1612 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1613 FROM {message} m
1614 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1616 } else if ($courseid !== 'none') {
1617 /// This has not been implemented due to security concerns
1618 $m_read = array();
1619 $m_unread = array();
1621 } else {
1623 if ($fromme and $tome) {
1624 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1625 $params['userid1'] = $userid;
1626 $params['userid2'] = $userid;
1628 } else if ($fromme) {
1629 $searchcond .= " AND m.useridfrom=:userid";
1630 $params['userid'] = $userid;
1632 } else if ($tome) {
1633 $searchcond .= " AND m.useridto=:userid";
1634 $params['userid'] = $userid;
1637 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1638 FROM {message_read} m
1639 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1640 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1641 FROM {message} m
1642 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1646 /// The keys may be duplicated in $m_read and $m_unread so we can't
1647 /// do a simple concatenation
1648 $message = array();
1649 foreach ($m_read as $m) {
1650 $messages[] = $m;
1652 foreach ($m_unread as $m) {
1653 $messages[] = $m;
1656 return (empty($messages)) ? false : $messages;
1660 * Given a message object that we already know has a long message
1661 * this function truncates the message nicely to the first
1662 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1664 * @param string $message the message
1665 * @param int $minlength the minimum length to trim the message to
1666 * @return string the shortened message
1668 function message_shorten_message($message, $minlength = 0) {
1669 $i = 0;
1670 $tag = false;
1671 $length = strlen($message);
1672 $count = 0;
1673 $stopzone = false;
1674 $truncate = 0;
1675 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1678 for ($i=0; $i<$length; $i++) {
1679 $char = $message[$i];
1681 switch ($char) {
1682 case "<":
1683 $tag = true;
1684 break;
1685 case ">":
1686 $tag = false;
1687 break;
1688 default:
1689 if (!$tag) {
1690 if ($stopzone) {
1691 if ($char == '.' or $char == ' ') {
1692 $truncate = $i+1;
1693 break 2;
1696 $count++;
1698 break;
1700 if (!$stopzone) {
1701 if ($count > $minlength) {
1702 $stopzone = true;
1707 if (!$truncate) {
1708 $truncate = $i;
1711 return substr($message, 0, $truncate);
1716 * Given a string and an array of keywords, this function looks
1717 * for the first keyword in the string, and then chops out a
1718 * small section from the text that shows that word in context.
1720 * @param string $message the text to search
1721 * @param array $keywords array of keywords to find
1723 function message_get_fragment($message, $keywords) {
1725 $fullsize = 160;
1726 $halfsize = (int)($fullsize/2);
1728 $message = strip_tags($message);
1730 foreach ($keywords as $keyword) { // Just get the first one
1731 if ($keyword !== '') {
1732 break;
1735 if (empty($keyword)) { // None found, so just return start of message
1736 return message_shorten_message($message, 30);
1739 $leadin = $leadout = '';
1741 /// Find the start of the fragment
1742 $start = 0;
1743 $length = strlen($message);
1745 $pos = strpos($message, $keyword);
1746 if ($pos > $halfsize) {
1747 $start = $pos - $halfsize;
1748 $leadin = '...';
1750 /// Find the end of the fragment
1751 $end = $start + $fullsize;
1752 if ($end > $length) {
1753 $end = $length;
1754 } else {
1755 $leadout = '...';
1758 /// Pull out the fragment and format it
1760 $fragment = substr($message, $start, $end - $start);
1761 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1762 return $fragment;
1766 * Retrieve the messages between two users
1768 * @param object $user1 the current user
1769 * @param object $user2 the other user
1770 * @param int $limitnum the maximum number of messages to retrieve
1771 * @param bool $viewingnewmessages are we currently viewing new messages?
1773 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1774 global $DB, $CFG;
1776 $messages = array();
1778 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1779 //desc to get the last $limitnum messages then flip the order in php
1780 $sort = 'asc';
1781 if ($limitnum>0) {
1782 $sort = 'desc';
1785 $notificationswhere = null;
1786 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1787 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1788 $notificationswhere = 'AND notification=0';
1791 //prevent notifications of your own actions appearing in your own message history
1792 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1794 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1795 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1796 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1797 "timecreated $sort", '*', 0, $limitnum)) {
1798 foreach ($messages_read as $message) {
1799 $messages[$message->timecreated] = $message;
1802 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1803 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1804 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1805 "timecreated $sort", '*', 0, $limitnum)) {
1806 foreach ($messages_new as $message) {
1807 $messages[$message->timecreated] = $message;
1811 //if we only want the last $limitnum messages
1812 ksort($messages);
1813 $messagecount = count($messages);
1814 if ($limitnum>0 && $messagecount>$limitnum) {
1815 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1818 return $messages;
1822 * Print the message history between two users
1824 * @param object $user1 the current user
1825 * @param object $user2 the other user
1826 * @param string $search search terms to highlight
1827 * @param int $messagelimit maximum number of messages to return
1828 * @param string $messagehistorylink the html for the message history link or false
1829 * @param bool $viewingnewmessages are we currently viewing new messages?
1831 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1832 global $CFG, $OUTPUT;
1834 echo $OUTPUT->box_start('center');
1835 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1836 echo html_writer::start_tag('tr');
1838 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1839 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1840 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1841 echo html_writer::end_tag('td');
1843 echo html_writer::start_tag('td', array('align' => 'center'));
1844 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1845 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1846 echo html_writer::end_tag('td');
1848 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1849 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1850 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1852 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1853 $incontactlist = $user2->iscontact;
1854 $isblocked = $user2->isblocked;
1856 $script = null;
1857 $text = true;
1858 $icon = false;
1860 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1861 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1862 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1864 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1867 echo html_writer::end_tag('td');
1868 echo html_writer::end_tag('tr');
1869 echo html_writer::end_tag('table');
1870 echo $OUTPUT->box_end();
1872 if (!empty($messagehistorylink)) {
1873 echo $messagehistorylink;
1876 /// Get all the messages and print them
1877 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1878 $tablecontents = '';
1880 $current = new stdClass();
1881 $current->mday = '';
1882 $current->month = '';
1883 $current->year = '';
1884 $messagedate = get_string('strftimetime');
1885 $blockdate = get_string('strftimedaydate');
1886 foreach ($messages as $message) {
1887 if ($message->notification) {
1888 $notificationclass = ' notification';
1889 } else {
1890 $notificationclass = null;
1892 $date = usergetdate($message->timecreated);
1893 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1894 $current->mday = $date['mday'];
1895 $current->month = $date['month'];
1896 $current->year = $date['year'];
1898 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1899 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1901 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1904 $formatted_message = $side = null;
1905 if ($message->useridfrom == $user1->id) {
1906 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1907 $side = 'left';
1908 } else {
1909 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1910 $side = 'right';
1912 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1915 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1916 } else {
1917 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1922 * Format a message for display in the message history
1924 * @param object $message the message object
1925 * @param string $format optional date format
1926 * @param string $keywords keywords to highlight
1927 * @param string $class CSS class to apply to the div around the message
1928 * @return string the formatted message
1930 function message_format_message($message, $format='', $keywords='', $class='other') {
1932 static $dateformat;
1934 //if we haven't previously set the date format or they've supplied a new one
1935 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1936 if ($format) {
1937 $dateformat = $format;
1938 } else {
1939 $dateformat = get_string('strftimedatetimeshort');
1942 $time = userdate($message->timecreated, $dateformat);
1943 $options = new stdClass();
1944 $options->para = false;
1946 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1947 if (!empty($message->smallmessage)) {
1948 $messagetext = $message->smallmessage;
1949 } else {
1950 $messagetext = $message->fullmessage;
1952 if ($message->fullmessageformat == FORMAT_HTML) {
1953 //dont escape html tags by calling s() if html format or they will display in the UI
1954 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1955 } else {
1956 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1959 $messagetext .= message_format_contexturl($message);
1961 if ($keywords) {
1962 $messagetext = highlight($keywords, $messagetext);
1965 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1969 * Format a the context url and context url name of a message for display
1971 * @param object $message the message object
1972 * @return string the formatted string
1974 function message_format_contexturl($message) {
1975 $s = null;
1977 if (!empty($message->contexturl)) {
1978 $displaytext = null;
1979 if (!empty($message->contexturlname)) {
1980 $displaytext= $message->contexturlname;
1981 } else {
1982 $displaytext= $message->contexturl;
1984 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1985 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1986 $s .= html_writer::end_tag('div');
1989 return $s;
1993 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1995 * @param object $userfrom the message sender
1996 * @param object $userto the message recipient
1997 * @param string $message the message
1998 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1999 * @return int|false the ID of the new message or false
2001 function message_post_message($userfrom, $userto, $message, $format) {
2002 global $SITE, $CFG, $USER;
2004 $eventdata = new stdClass();
2005 $eventdata->component = 'moodle';
2006 $eventdata->name = 'instantmessage';
2007 $eventdata->userfrom = $userfrom;
2008 $eventdata->userto = $userto;
2010 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2011 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2013 if ($format == FORMAT_HTML) {
2014 $eventdata->fullmessagehtml = $message;
2015 //some message processors may revert to sending plain text even if html is supplied
2016 //so we keep both plain and html versions if we're intending to send html
2017 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2018 } else {
2019 $eventdata->fullmessage = $message;
2020 $eventdata->fullmessagehtml = '';
2023 $eventdata->fullmessageformat = $format;
2024 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2026 $s = new stdClass();
2027 $s->sitename = format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
2028 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2030 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2031 if (!empty($eventdata->fullmessage)) {
2032 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2034 if (!empty($eventdata->fullmessagehtml)) {
2035 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2038 $eventdata->timecreated = time();
2039 return message_send($eventdata);
2044 * Returns a list of all user ids who have used messaging in the site
2045 * This was the simple way to code the SQL ... is it going to blow up
2046 * on large datasets?
2048 * @todo: deprecated - to be deleted in 2.2
2049 * @return array
2051 function message_get_participants() {
2052 global $CFG, $DB;
2054 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
2055 UNION SELECT useridto as id,1 FROM {message}
2056 UNION SELECT useridfrom as id,1 FROM {message_read}
2057 UNION SELECT useridto as id,1 FROM {message_read}
2058 UNION SELECT userid as id,1 FROM {message_contacts}
2059 UNION SELECT contactid as id,1 from {message_contacts}");
2063 * Print a row of contactlist displaying user picture, messages waiting and
2064 * block links etc
2066 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2067 * @param bool $incontactlist is the user a contact of ours?
2068 * @param bool $isblocked is the user blocked?
2069 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2070 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2071 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2072 * @return void
2074 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2075 global $OUTPUT, $USER;
2076 $fullname = fullname($contact);
2077 $fullnamelink = $fullname;
2079 $linkclass = '';
2080 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2081 $linkclass = 'messageselecteduser';
2084 /// are there any unread messages for this contact?
2085 if ($contact->messagecount > 0 ){
2086 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2089 $strcontact = $strblock = $strhistory = null;
2091 if ($showactionlinks) {
2092 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2093 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2094 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2097 echo html_writer::start_tag('tr');
2098 echo html_writer::start_tag('td', array('class' => 'pix'));
2099 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2100 echo html_writer::end_tag('td');
2102 echo html_writer::start_tag('td', array('class' => 'contact'));
2104 $popupoptions = array(
2105 'height' => MESSAGE_DISCUSSION_HEIGHT,
2106 'width' => MESSAGE_DISCUSSION_WIDTH,
2107 'menubar' => false,
2108 'location' => false,
2109 'status' => true,
2110 'scrollbars' => true,
2111 'resizable' => true);
2113 $link = $action = null;
2114 if (!empty($selectcontacturl)) {
2115 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2116 } else {
2117 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2118 $link = new moodle_url("/message/index.php?id=$contact->id");
2119 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2121 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2123 echo html_writer::end_tag('td');
2125 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2127 echo html_writer::end_tag('tr');
2131 * Constructs the add/remove contact link to display next to other users
2133 * @param bool $incontactlist is the user a contact
2134 * @param bool $isblocked is the user blocked
2135 * @param type $contact contact object
2136 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2137 * @param bool $text include text next to the icons?
2138 * @param bool $icon include a graphical icon?
2139 * @return string
2141 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2142 $strcontact = '';
2144 if($incontactlist){
2145 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2146 } else if ($isblocked) {
2147 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2148 } else{
2149 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2152 return $strcontact;
2156 * Constructs the block contact link to display next to other users
2158 * @param bool $incontactlist is the user a contact
2159 * @param bool $isblocked is the user blocked
2160 * @param type $contact contact object
2161 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2162 * @param bool $text include text next to the icons?
2163 * @param bool $icon include a graphical icon?
2164 * @return string
2166 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2167 $strblock = '';
2169 //commented out to allow the user to block a contact without having to remove them first
2170 /*if ($incontactlist) {
2171 //$strblock = '';
2172 } else*/
2173 if ($isblocked) {
2174 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2175 } else{
2176 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2179 return $strblock;
2183 * Moves messages from a particular user from the message table (unread messages) to message_read
2184 * This is typically only used when a user is deleted
2186 * @param object $userid User id
2187 * @return boolean success
2189 function message_move_userfrom_unread2read($userid) {
2190 global $DB;
2192 // move all unread messages from message table to message_read
2193 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2194 foreach ($messages as $message) {
2195 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2198 return true;
2202 * marks ALL messages being sent from $fromuserid to $touserid as read
2204 * @param int $touserid the id of the message recipient
2205 * @param int $fromuserid the id of the message sender
2206 * @return void
2208 function message_mark_messages_read($touserid, $fromuserid){
2209 global $DB;
2211 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2212 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2214 foreach ($messages as $message) {
2215 message_mark_message_read($message, time());
2218 $messages->close();
2222 * Mark a single message as read
2224 * @param message an object with an object property ie $message->id which is an id in the message table
2225 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2226 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2227 * @return int the ID of the message in the message_read table
2229 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2230 global $DB;
2232 $message->timeread = $timeread;
2234 $messageid = $message->id;
2235 unset($message->id);//unset because it will get a new id on insert into message_read
2237 //If any processors have pending actions abort them
2238 if (!$messageworkingempty) {
2239 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2241 $messagereadid = $DB->insert_record('message_read', $message);
2242 $DB->delete_records('message', array('id' => $messageid));
2243 return $messagereadid;
2247 * A helper function that prints a formatted heading
2249 * @param string $title the heading to display
2250 * @param int $colspan
2251 * @return void
2253 function message_print_heading($title, $colspan=3) {
2254 echo html_writer::start_tag('tr');
2255 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2256 echo html_writer::end_tag('tr');
2260 * Get all message processors, validate corresponding plugin existance and
2261 * system configuration
2263 * @param bool $ready only return ready-to-use processors
2264 * @return mixed $processors array of objects containing information on message processors
2266 function get_message_processors($ready = false) {
2267 global $DB, $CFG;
2269 static $processors;
2271 if (empty($processors)) {
2272 // Get all processors, ensure the name column is the first so it will be the array key
2273 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2274 foreach ($processors as &$processor){
2275 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2276 if (is_readable($processorfile)) {
2277 include_once($processorfile);
2278 $processclass = 'message_output_' . $processor->name;
2279 if (class_exists($processclass)) {
2280 $pclass = new $processclass();
2281 $processor->object = $pclass;
2282 $processor->configured = 0;
2283 if ($pclass->is_system_configured()) {
2284 $processor->configured = 1;
2286 $processor->hassettings = 0;
2287 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2288 $processor->hassettings = 1;
2290 $processor->available = 1;
2291 } else {
2292 print_error('errorcallingprocessor', 'message');
2294 } else {
2295 $processor->available = 0;
2299 if ($ready) {
2300 // Filter out enabled and system_configured processors
2301 $readyprocessors = $processors;
2302 foreach ($readyprocessors as $readyprocessor) {
2303 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2304 unset($readyprocessors[$readyprocessor->name]);
2307 return $readyprocessors;
2310 return $processors;
2314 * Get an instance of the message_output class for one of the output plugins.
2315 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2316 * @return message_output message_output the requested class.
2318 function get_message_processor($type) {
2319 global $CFG;
2321 // Note, we cannot use the get_message_processors function here, becaues this
2322 // code is called during install after installing each messaging plugin, and
2323 // get_message_processors caches the list of installed plugins.
2325 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2326 if (!is_readable($processorfile)) {
2327 throw new coding_exception('Unknown message processor type ' . $type);
2330 include_once($processorfile);
2332 $processclass = 'message_output_' . $type;
2333 if (!class_exists($processclass)) {
2334 throw new coding_exception('Message processor ' . $type .
2335 ' does not define the right class');
2338 return new $processclass();
2342 * Get messaging outputs default (site) preferences
2344 * @return object $processors object containing information on message processors
2346 function get_message_output_default_preferences() {
2347 $preferences = get_config('message');
2348 if (!$preferences) {
2349 $preferences = new stdClass();
2351 return $preferences;
2355 * Translate message default settings from binary value to the array of string
2356 * representing the settings to be stored. Also validate the provided value and
2357 * use default if it is malformed.
2359 * @param int $plugindefault Default setting suggested by plugin
2360 * @param string $processorname The name of processor
2361 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2363 function translate_message_default_setting($plugindefault, $processorname) {
2364 // Preset translation arrays
2365 $permittedvalues = array(
2366 0x04 => 'disallowed',
2367 0x08 => 'permitted',
2368 0x0c => 'forced',
2371 $loggedinstatusvalues = array(
2372 0x00 => null, // use null if loggedin/loggedoff is not defined
2373 0x01 => 'loggedin',
2374 0x02 => 'loggedoff',
2377 // define the default setting
2378 $processor = get_message_processor($processorname);
2379 $default = $processor->get_default_messaging_settings();
2381 // Validate the value. It should not exceed the maximum size
2382 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2383 $OUTPUT->notification(get_string('errortranslatingdefault', 'message'), 'notifyproblem');
2384 $plugindefault = $default;
2386 // Use plugin default setting of 'permitted' is 0
2387 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2388 $plugindefault = $default;
2391 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2392 $loggedin = $loggedoff = null;
2394 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2395 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2396 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2399 return array($permitted, $loggedin, $loggedoff);
2403 * Return a list of page types
2404 * @param string $pagetype current page type
2405 * @param stdClass $parentcontext Block's parent context
2406 * @param stdClass $currentcontext Current context of block
2408 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2409 return array('messages-*'=>get_string('page-message-x', 'message'));