MDL-31244, MDL-25063 there is no phpuni support in 22_STABLE
[moodle.git] / message / lib.php
blob478bad81956d050a1b24c47a3177da913a870ec2
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 //TODO: this is a mega crazy hack - it is not acceptable to call anything when including lib!!! (skodak)
33 $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
36 define ('MESSAGE_DISCUSSION_WIDTH',600);
37 define ('MESSAGE_DISCUSSION_HEIGHT',500);
39 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
41 define('MESSAGE_HISTORY_SHORT',0);
42 define('MESSAGE_HISTORY_ALL',1);
44 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
45 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
46 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
47 define('MESSAGE_VIEW_CONTACTS','contacts');
48 define('MESSAGE_VIEW_BLOCKED','blockedusers');
49 define('MESSAGE_VIEW_COURSE','course_');
50 define('MESSAGE_VIEW_SEARCH','search');
52 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
54 define('MESSAGE_CONTACTS_PER_PAGE',10);
55 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
57 /**
58 * Define contants for messaging default settings population. For unambiguity of
59 * plugin developer intentions we use 4-bit value (LSB numbering):
60 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
61 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
62 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
64 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
67 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
68 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
70 define('MESSAGE_DISALLOWED', 0x04); // 0100
71 define('MESSAGE_PERMITTED', 0x08); // 1000
72 define('MESSAGE_FORCED', 0x0c); // 1100
74 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
76 /**
77 * Set default value for default outputs permitted setting
79 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
81 //TODO: defaults must be initialised via settings - this is a bad hack! (skodak)
82 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
83 $CFG->message_contacts_refresh = 60;
85 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
86 $CFG->message_chat_refresh = 5;
88 if (!isset($CFG->message_offline_time)) {
89 $CFG->message_offline_time = 300;
92 /**
93 * Print the selector that allows the user to view their contacts, course participants, their recent
94 * conversations etc
96 * @param int $countunreadtotal how many unread messages does the user have?
97 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
98 * @param object $user1 the user whose messages are being viewed
99 * @param object $user2 the user $user1 is talking to
100 * @param array $blockedusers an array of users blocked by $user1
101 * @param array $onlinecontacts an array of $user1's online contacts
102 * @param array $offlinecontacts an array of $user1's offline contacts
103 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
104 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
105 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
106 * @return void
108 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
109 global $PAGE;
111 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
113 //if 0 unread messages and they've requested unread messages then show contacts
114 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
115 $viewing = MESSAGE_VIEW_CONTACTS;
118 //if they have no blocked users and they've requested blocked users switch them over to contacts
119 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
120 $viewing = MESSAGE_VIEW_CONTACTS;
123 $onlyactivecourses = true;
124 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
125 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
127 $strunreadmessages = null;
128 if ($countunreadtotal>0) { //if there are unread messages
129 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
132 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
134 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
135 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
136 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
137 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
138 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
139 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
140 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
141 $courseidtoshow = intval(substr($viewing, 7));
143 if (!empty($courseidtoshow)
144 && array_key_exists($courseidtoshow, $coursecontexts)
145 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
147 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
148 } else {
149 //shouldn't get here. User trying to access a course they're not in perhaps.
150 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
154 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
155 echo html_writer::start_tag('fieldset');
156 $managebuttonclass = 'visible';
157 if ($viewing == MESSAGE_VIEW_SEARCH) {
158 $managebuttonclass = 'hiddenelement';
160 $strmanagecontacts = get_string('search','message');
161 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
162 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
163 echo html_writer::end_tag('fieldset');
164 echo html_writer::end_tag('form');
166 echo html_writer::end_tag('div');
170 * Print course participants. Called by message_print_contact_selector()
172 * @param object $context the course context
173 * @param int $courseid the course ID
174 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
175 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
176 * @param string $titletodisplay Optionally specify a title to display above the participants
177 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
178 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
179 * @return void
181 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
182 global $DB, $USER, $PAGE, $OUTPUT;
184 if (empty($titletodisplay)) {
185 $titletodisplay = get_string('participants');
188 $countparticipants = count_enrolled_users($context);
189 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
191 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
192 echo $OUTPUT->render($pagingbar);
194 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
196 echo html_writer::start_tag('tr');
197 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
198 echo html_writer::end_tag('tr');
200 //todo these need to come from somewhere if the course participants list is to show users with unread messages
201 $iscontact = true;
202 $isblocked = false;
203 foreach ($participants as $participant) {
204 if ($participant->id != $USER->id) {
205 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
206 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
210 echo html_writer::end_tag('table');
214 * Retrieve users blocked by $user1
216 * @param object $user1 the user whose messages are being viewed
217 * @param object $user2 the user $user1 is talking to. If they are being blocked
218 * they will have a variable called 'isblocked' added to their user object
219 * @return array the users blocked by $user1
221 function message_get_blocked_users($user1=null, $user2=null) {
222 global $DB, $USER;
224 if (empty($user1)) {
225 $user1 = $USER;
228 if (!empty($user2)) {
229 $user2->isblocked = false;
232 $blockedusers = array();
234 $userfields = user_picture::fields('u', array('lastaccess'));
235 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
236 FROM {message_contacts} mc
237 JOIN {user} u ON u.id = mc.contactid
238 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
239 WHERE mc.userid = :user1id2 AND mc.blocked = 1
240 GROUP BY $userfields
241 ORDER BY u.firstname ASC";
242 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
244 foreach($rs as $rd) {
245 $blockedusers[] = $rd;
247 if (!empty($user2) && $user2->id == $rd->id) {
248 $user2->isblocked = true;
251 $rs->close();
253 return $blockedusers;
257 * Print users blocked by $user1. Called by message_print_contact_selector()
259 * @param array $blockedusers the users blocked by $user1
260 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
261 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
262 * @param string $titletodisplay Optionally specify a title to display above the participants
263 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
264 * @return void
266 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
267 global $DB, $USER;
269 $countblocked = count($blockedusers);
271 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
273 if (!empty($titletodisplay)) {
274 echo html_writer::start_tag('tr');
275 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
276 echo html_writer::end_tag('tr');
279 if ($countblocked) {
280 echo html_writer::start_tag('tr');
281 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
282 echo html_writer::end_tag('tr');
284 $isuserblocked = true;
285 $isusercontact = false;
286 foreach ($blockedusers as $blockeduser) {
287 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
291 echo html_writer::end_tag('table');
295 * Retrieve $user1's contacts (online, offline and strangers)
297 * @param object $user1 the user whose messages are being viewed
298 * @param object $user2 the user $user1 is talking to. If they are a contact
299 * they will have a variable called 'iscontact' added to their user object
300 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
302 function message_get_contacts($user1=null, $user2=null) {
303 global $DB, $CFG, $USER;
305 if (empty($user1)) {
306 $user1 = $USER;
309 if (!empty($user2)) {
310 $user2->iscontact = false;
313 $timetoshowusers = 300; //Seconds default
314 if (isset($CFG->block_online_users_timetosee)) {
315 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
318 // time which a user is counting as being active since
319 $timefrom = time()-$timetoshowusers;
321 // people in our contactlist who are online
322 $onlinecontacts = array();
323 // people in our contactlist who are offline
324 $offlinecontacts = array();
325 // people who are not in our contactlist but have sent us a message
326 $strangers = array();
328 $userfields = user_picture::fields('u', array('lastaccess'));
330 // get all in our contactlist who are not blocked in our contact list
331 // and count messages we have waiting from each of them
332 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
333 FROM {message_contacts} mc
334 JOIN {user} u ON u.id = mc.contactid
335 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
336 WHERE mc.userid = ? AND mc.blocked = 0
337 GROUP BY $userfields
338 ORDER BY u.firstname ASC";
340 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
341 foreach ($rs as $rd) {
342 if ($rd->lastaccess >= $timefrom) {
343 // they have been active recently, so are counted online
344 $onlinecontacts[] = $rd;
346 } else {
347 $offlinecontacts[] = $rd;
350 if (!empty($user2) && $user2->id == $rd->id) {
351 $user2->iscontact = true;
354 $rs->close();
356 // get messages from anyone who isn't in our contact list and count the number
357 // of messages we have from each of them
358 $strangersql = "SELECT $userfields, count(m.id) as messagecount
359 FROM {message} m
360 JOIN {user} u ON u.id = m.useridfrom
361 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
362 WHERE mc.id IS NULL AND m.useridto = ?
363 GROUP BY $userfields
364 ORDER BY u.firstname ASC";
366 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
367 foreach ($rs as $rd) {
368 $strangers[] = $rd;
370 $rs->close();
372 return array($onlinecontacts, $offlinecontacts, $strangers);
376 * Print $user1's contacts. Called by message_print_contact_selector()
378 * @param array $onlinecontacts $user1's contacts which are online
379 * @param array $offlinecontacts $user1's contacts which are offline
380 * @param array $strangers users which are not contacts but who have messaged $user1
381 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
382 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
383 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
384 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
385 * @param string $titletodisplay Optionally specify a title to display above the participants
386 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
387 * @return void
389 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
390 global $CFG, $PAGE, $OUTPUT;
392 $countonlinecontacts = count($onlinecontacts);
393 $countofflinecontacts = count($offlinecontacts);
394 $countstrangers = count($strangers);
395 $isuserblocked = null;
397 if ($countonlinecontacts + $countofflinecontacts == 0) {
398 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
401 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
403 if (!empty($titletodisplay)) {
404 message_print_heading($titletodisplay);
407 if($countonlinecontacts) {
408 /// print out list of online contacts
410 if (empty($titletodisplay)) {
411 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
414 $isuserblocked = false;
415 $isusercontact = true;
416 foreach ($onlinecontacts as $contact) {
417 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
418 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
423 if ($countofflinecontacts) {
424 /// print out list of offline contacts
426 if (empty($titletodisplay)) {
427 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
430 $isuserblocked = false;
431 $isusercontact = true;
432 foreach ($offlinecontacts as $contact) {
433 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
434 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
440 /// print out list of incoming contacts
441 if ($countstrangers) {
442 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
444 $isuserblocked = false;
445 $isusercontact = false;
446 foreach ($strangers as $stranger) {
447 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
448 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
453 echo html_writer::end_tag('table');
455 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
456 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
461 * Print a select box allowing the user to choose to view new messages, course participants etc.
463 * Called by message_print_contact_selector()
464 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
465 * @param array $courses array of course objects. The courses the user is enrolled in.
466 * @param array $coursecontexts array of course contexts. Keyed on course id.
467 * @param int $countunreadtotal how many unread messages does the user have?
468 * @param int $countblocked how many users has the current user blocked?
469 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
470 * @return void
472 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
473 $options = array();
474 $textlib = textlib_get_instance(); // going to use textlib services
476 if ($countunreadtotal>0) { //if there are unread messages
477 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
480 $str = get_string('mycontacts', 'message');
481 $options[MESSAGE_VIEW_CONTACTS] = $str;
483 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
484 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
486 if (!empty($courses)) {
487 $courses_options = array();
489 foreach($courses as $course) {
490 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
491 //Not using short_text() as we want the end of the course name. Not the beginning.
492 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
493 if ($textlib->strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
494 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.$textlib->substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
495 } else {
496 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
501 if (!empty($courses_options)) {
502 $options[] = array(get_string('courses') => $courses_options);
506 if ($countblocked>0) {
507 $str = get_string('blockedusers','message', $countblocked);
508 $options[MESSAGE_VIEW_BLOCKED] = $str;
511 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
512 echo html_writer::start_tag('fieldset');
513 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
514 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
515 echo html_writer::end_tag('fieldset');
516 echo html_writer::end_tag('form');
520 * Load the course contexts for all of the users courses
522 * @param array $courses array of course objects. The courses the user is enrolled in.
523 * @return array of course contexts
525 function message_get_course_contexts($courses) {
526 $coursecontexts = array();
528 foreach($courses as $course) {
529 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
532 return $coursecontexts;
536 * strip off action parameters like 'removecontact'
538 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
539 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
541 function message_remove_url_params($moodleurl) {
542 $newurl = new moodle_url($moodleurl);
543 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
544 return $newurl->out();
548 * Count the number of messages with a field having a specified value.
549 * if $field is empty then return count of the whole array
550 * if $field is non-existent then return 0
552 * @param array $messagearray array of message objects
553 * @param string $field the field to inspect on the message objects
554 * @param string $value the value to test the field against
556 function message_count_messages($messagearray, $field='', $value='') {
557 if (!is_array($messagearray)) return 0;
558 if ($field == '' or empty($messagearray)) return count($messagearray);
560 $count = 0;
561 foreach ($messagearray as $message) {
562 $count += ($message->$field == $value) ? 1 : 0;
564 return $count;
568 * Returns the count of unread messages for user. Either from a specific user or from all users.
570 * @param object $user1 the first user. Defaults to $USER
571 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
572 * @return int the count of $user1's unread messages
574 function message_count_unread_messages($user1=null, $user2=null) {
575 global $USER, $DB;
577 if (empty($user1)) {
578 $user1 = $USER;
581 if (!empty($user2)) {
582 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
583 array($user1->id, $user2->id), "COUNT('id')");
584 } else {
585 return $DB->count_records_select('message', "useridto = ?",
586 array($user1->id), "COUNT('id')");
591 * Count the number of users blocked by $user1
593 * @param object $user1 user object
594 * @return int the number of blocked users
596 function message_count_blocked_users($user1=null) {
597 global $USER, $DB;
599 if (empty($user1)) {
600 $user1 = $USER;
603 $sql = "SELECT count(mc.id)
604 FROM {message_contacts} mc
605 WHERE mc.userid = :userid AND mc.blocked = 1";
606 $params = array('userid' => $user1->id);
608 return $DB->count_records_sql($sql, $params);
612 * Print the search form and search results if a search has been performed
614 * @param boolean $advancedsearch show basic or advanced search form
615 * @param object $user1 the current user
616 * @return boolean true if a search was performed
618 function message_print_search($advancedsearch = false, $user1=null) {
619 $frm = data_submitted();
621 $doingsearch = false;
622 if ($frm) {
623 if (confirm_sesskey()) {
624 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
625 } else {
626 $frm = false;
630 if (!empty($frm->combinedsearch)) {
631 $combinedsearchstring = $frm->combinedsearch;
632 } else {
633 //$combinedsearchstring = get_string('searchcombined','message').'...';
634 $combinedsearchstring = '';
637 if ($doingsearch) {
638 if ($advancedsearch) {
640 $messagesearch = '';
641 if (!empty($frm->keywords)) {
642 $messagesearch = $frm->keywords;
644 $personsearch = '';
645 if (!empty($frm->name)) {
646 $personsearch = $frm->name;
648 include('search_advanced.html');
649 } else {
650 include('search.html');
653 $showicontext = false;
654 message_print_search_results($frm, $showicontext, $user1);
656 return true;
657 } else {
659 if ($advancedsearch) {
660 $personsearch = $messagesearch = '';
661 include('search_advanced.html');
662 } else {
663 include('search.html');
665 return false;
670 * Get the users recent conversations meaning all the people they've recently
671 * sent or received a message from plus the most recent message sent to or received from each other user
673 * @param object $user the current user
674 * @param int $limitfrom can be used for paging
675 * @param int $limitto can be used for paging
676 * @return array
678 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
679 global $DB;
681 $userfields = user_picture::fields('u', array('lastaccess'));
682 //This query retrieves the last message received from and sent to each user
683 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
684 //It then joins with some other tables to get some additional data we need
686 //message ID is used instead of timecreated as it should sort the same and will be much faster
688 //There is a separate query for read and unread queries as they are stored in different tables
689 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
690 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
691 FROM {message_read} mr
692 JOIN (
693 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
694 FROM (
695 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
696 FROM {message_read} mr1
697 WHERE mr1.useridfrom = :userid1
698 AND mr1.notification = 0
699 GROUP BY mr1.useridto
700 UNION
701 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
702 FROM {message_read} mr2
703 WHERE mr2.useridto = :userid2
704 AND mr2.notification = 0
705 GROUP BY mr2.useridfrom
706 ) messages
707 GROUP BY messages.userid
708 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
709 JOIN {user} u ON u.id = messages2.userid
710 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
711 WHERE u.deleted = '0'
712 ORDER BY mr.id DESC";
713 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
714 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
716 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
717 FROM {message} m
718 JOIN (
719 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
720 FROM (
721 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
722 FROM {message} m1
723 WHERE m1.useridfrom = :userid1
724 AND m1.notification = 0
725 GROUP BY m1.useridto
726 UNION
727 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
728 FROM {message} m2
729 WHERE m2.useridto = :userid2
730 AND m2.notification = 0
731 GROUP BY m2.useridfrom
732 ) messages
733 GROUP BY messages.userid
734 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
735 JOIN {user} u ON u.id = messages2.userid
736 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
737 WHERE u.deleted = '0'
738 ORDER BY m.id DESC";
739 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
741 $conversations = array();
743 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
744 //$conversation->id (the array key) is the other user's ID
745 $conversation_arrays = array($unread, $read);
746 foreach ($conversation_arrays as $conversation_array) {
747 foreach ($conversation_array as $conversation) {
748 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
749 $conversations[$conversation->id] = $conversation;
754 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
755 //and there may be multiple conversations with the same timecreated value.
756 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
757 usort($conversations, "conversationsort");
759 return $conversations;
763 * Sort function used to order conversations
765 * @param object $a A conversation object
766 * @param object $b A conversation object
767 * @return integer
769 function conversationsort($a, $b)
771 if ($a->timecreated == $b->timecreated) {
772 return 0;
774 return ($a->timecreated > $b->timecreated) ? -1 : 1;
778 * Get the users recent event notifications
780 * @param object $user the current user
781 * @param int $limitfrom can be used for paging
782 * @param int $limitto can be used for paging
783 * @return array
785 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
786 global $DB;
788 $userfields = user_picture::fields('u', array('lastaccess'));
789 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
790 FROM {message_read} mr
791 JOIN {user} u ON u.id=mr.useridfrom
792 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
793 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
794 $params = array('userid1' => $user->id, 'notification' => 1);
796 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
797 return $notifications;
801 * Print the user's recent conversations
803 * @param object $user1 the current user
804 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
805 * @return void
807 function message_print_recent_conversations($user=null, $showicontext=false) {
808 global $USER;
810 echo html_writer::start_tag('p', array('class' => 'heading'));
811 echo get_string('mostrecentconversations', 'message');
812 echo html_writer::end_tag('p');
814 if (empty($user)) {
815 $user = $USER;
818 $conversations = message_get_recent_conversations($user);
820 // Attach context url information to create the "View this conversation" type links
821 foreach($conversations as $conversation) {
822 $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
823 $conversation->contexturlname = get_string('thisconversation', 'message');
826 $showotheruser = true;
827 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
831 * Print the user's recent notifications
833 * @param object $user1 the current user
834 * @return void
836 function message_print_recent_notifications($user=null) {
837 global $USER;
839 echo html_writer::start_tag('p', array('class' => 'heading'));
840 echo get_string('mostrecentnotifications', 'message');
841 echo html_writer::end_tag('p');
843 if (empty($user)) {
844 $user = $USER;
847 $notifications = message_get_recent_notifications($user);
849 $showicontext = false;
850 $showotheruser = false;
851 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
855 * Print a list of recent messages
857 * @staticvar type $dateformat
858 * @param array $messages the messages to display
859 * @param object $user the current user
860 * @param bool $showotheruser display information on the other user?
861 * @param bool $showicontext show text next to the action icons?
862 * @return void
864 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
865 global $OUTPUT;
866 static $dateformat;
868 if (empty($dateformat)) {
869 $dateformat = get_string('strftimedatetimeshort');
872 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
873 foreach ($messages as $message) {
874 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
876 if ($showotheruser) {
877 if ( $message->contactlistid ) {
878 if ($message->blocked == 0) { /// not blocked
879 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
880 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
881 } else { // blocked
882 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
883 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
885 } else {
886 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
887 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
890 //should we show just the icon or icon and text?
891 $histicontext = 'icon';
892 if ($showicontext) {
893 $histicontext = 'both';
895 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
897 echo html_writer::start_tag('span', array('class' => 'otheruser'));
899 echo html_writer::start_tag('span', array('class' => 'pix'));
900 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
901 echo html_writer::end_tag('span');
903 echo html_writer::start_tag('span', array('class' => 'contact'));
905 $link = new moodle_url("/message/index.php?id=$message->id");
906 $action = null;
907 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
909 echo html_writer::end_tag('span');//end contact
911 echo $strcontact.$strblock.$strhistory;
912 echo html_writer::end_tag('span');//end otheruser
914 $messagetoprint = null;
915 if (!empty($message->smallmessage)) {
916 $messagetoprint = $message->smallmessage;
917 } else {
918 $messagetoprint = $message->fullmessage;
921 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
922 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
923 echo message_format_contexturl($message);
924 echo html_writer::end_tag('div');//end singlemessage
926 echo html_writer::end_tag('div');//end messagerecent
930 * Add the selected user as a contact for the current user
932 * @param int $contactid the ID of the user to add as a contact
933 * @param int $blocked 1 if you wish to block the contact
934 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
935 * Otherwise returns the result of update_record() or insert_record()
937 function message_add_contact($contactid, $blocked=0) {
938 global $USER, $DB;
940 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
941 return false;
944 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
945 /// record already exists - we may be changing blocking status
947 if ($contact->blocked !== $blocked) {
948 /// change to blocking status
949 $contact->blocked = $blocked;
950 return $DB->update_record('message_contacts', $contact);
951 } else {
952 /// no changes to blocking status
953 return true;
956 } else {
957 /// new contact record
958 $contact = new stdClass();
959 $contact->userid = $USER->id;
960 $contact->contactid = $contactid;
961 $contact->blocked = $blocked;
962 return $DB->insert_record('message_contacts', $contact, false);
967 * remove a contact
969 * @param type $contactid the user ID of the contact to remove
970 * @return bool returns the result of delete_records()
972 function message_remove_contact($contactid) {
973 global $USER, $DB;
974 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
978 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
980 * @param int $contactid the user ID of the contact to unblock
981 * @return bool returns the result of delete_records()
983 function message_unblock_contact($contactid) {
984 global $USER, $DB;
985 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
989 * block a user
991 * @param int $contactid the user ID of the user to block
993 function message_block_contact($contactid) {
994 return message_add_contact($contactid, 1);
998 * Load a user's contact record
1000 * @param int $contactid the user ID of the user whose contact record you want
1001 * @return array message contacts
1003 function message_get_contact($contactid) {
1004 global $USER, $DB;
1005 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1009 * Print the results of a message search
1011 * @param mixed $frm submitted form data
1012 * @param bool $showicontext show text next to action icons?
1013 * @param object $currentuser the current user
1014 * @return void
1016 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1017 global $USER, $DB, $OUTPUT;
1019 if (empty($currentuser)) {
1020 $currentuser = $USER;
1023 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1025 $personsearch = false;
1026 $personsearchstring = null;
1027 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1028 $personsearch = true;
1029 $personsearchstring = $frm->name;
1030 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1031 $personsearch = true;
1032 $personsearchstring = $frm->combinedsearch;
1035 /// search for person
1036 if ($personsearch) {
1037 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1038 $users = array();
1039 $mycourses = enrol_get_my_courses();
1040 foreach ($mycourses as $mycourse) {
1041 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1042 foreach ($susers as $suser) $users[$suser->id] = $suser;
1045 } else {
1046 $users = message_search_users(SITEID, $personsearchstring);
1049 if (!empty($users)) {
1050 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1051 echo get_string('userssearchresults', 'message', count($users));
1052 echo html_writer::end_tag('p');
1054 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1055 foreach ($users as $user) {
1057 if ( $user->contactlistid ) {
1058 if ($user->blocked == 0) { /// not blocked
1059 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1060 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1061 } else { // blocked
1062 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1063 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1065 } else {
1066 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1067 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1070 //should we show just the icon or icon and text?
1071 $histicontext = 'icon';
1072 if ($showicontext) {
1073 $histicontext = 'both';
1075 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1077 echo html_writer::start_tag('tr');
1079 echo html_writer::start_tag('td', array('class' => 'pix'));
1080 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1081 echo html_writer::end_tag('td');
1083 echo html_writer::start_tag('td',array('class' => 'contact'));
1084 $action = null;
1085 $link = new moodle_url("/message/index.php?id=$user->id");
1086 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1087 echo html_writer::end_tag('td');
1089 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1090 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1091 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1093 echo html_writer::end_tag('tr');
1095 echo html_writer::end_tag('table');
1097 } else {
1098 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1099 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1100 echo html_writer::end_tag('p');
1104 // search messages for keywords
1105 $messagesearch = false;
1106 $messagesearchstring = null;
1107 if (!empty($frm->keywords)) {
1108 $messagesearch = true;
1109 $messagesearchstring = clean_text(trim($frm->keywords));
1110 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1111 $messagesearch = true;
1112 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1115 if ($messagesearch) {
1116 if ($messagesearchstring) {
1117 $keywords = explode(' ', $messagesearchstring);
1118 } else {
1119 $keywords = array();
1121 $tome = false;
1122 $fromme = false;
1123 $courseid = 'none';
1125 if (empty($frm->keywordsoption)) {
1126 $frm->keywordsoption = 'allmine';
1129 switch ($frm->keywordsoption) {
1130 case 'tome':
1131 $tome = true;
1132 break;
1133 case 'fromme':
1134 $fromme = true;
1135 break;
1136 case 'allmine':
1137 $tome = true;
1138 $fromme = true;
1139 break;
1140 case 'allusers':
1141 $courseid = SITEID;
1142 break;
1143 case 'courseusers':
1144 $courseid = $frm->courseid;
1145 break;
1146 default:
1147 $tome = true;
1148 $fromme = true;
1151 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1153 /// get a list of contacts
1154 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1155 $contacts = array();
1158 /// print heading with number of results
1159 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1160 $countresults = count($messages);
1161 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1162 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1163 } else {
1164 echo get_string('keywordssearchresults', 'message', $countresults);
1166 echo html_writer::end_tag('p');
1168 /// print table headings
1169 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1171 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1172 $headertdend = html_writer::end_tag('td');
1173 echo html_writer::start_tag('tr');
1174 echo $headertdstart.get_string('from').$headertdend;
1175 echo $headertdstart.get_string('to').$headertdend;
1176 echo $headertdstart.get_string('message', 'message').$headertdend;
1177 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1178 echo html_writer::end_tag('tr');
1180 $blockedcount = 0;
1181 $dateformat = get_string('strftimedatetimeshort');
1182 $strcontext = get_string('context', 'message');
1183 foreach ($messages as $message) {
1185 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1186 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1187 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1188 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1191 $blockedcount ++;
1192 continue;
1195 /// load up user to record
1196 if ($message->useridto !== $USER->id) {
1197 $userto = $DB->get_record('user', array('id' => $message->useridto));
1198 $tocontact = (array_key_exists($message->useridto, $contacts) and
1199 ($contacts[$message->useridto]->blocked == 0) );
1200 $toblocked = (array_key_exists($message->useridto, $contacts) and
1201 ($contacts[$message->useridto]->blocked == 1) );
1202 } else {
1203 $userto = false;
1204 $tocontact = false;
1205 $toblocked = false;
1208 /// load up user from record
1209 if ($message->useridfrom !== $USER->id) {
1210 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1211 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1212 ($contacts[$message->useridfrom]->blocked == 0) );
1213 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1214 ($contacts[$message->useridfrom]->blocked == 1) );
1215 } else {
1216 $userfrom = false;
1217 $fromcontact = false;
1218 $fromblocked = false;
1221 /// find date string for this message
1222 $date = usergetdate($message->timecreated);
1223 $datestring = $date['year'].$date['mon'].$date['mday'];
1225 /// print out message row
1226 echo html_writer::start_tag('tr', array('valign' => 'top'));
1228 echo html_writer::start_tag('td', array('class' => 'contact'));
1229 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1230 echo html_writer::end_tag('td');
1232 echo html_writer::start_tag('td', array('class' => 'contact'));
1233 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1234 echo html_writer::end_tag('td');
1236 echo html_writer::start_tag('td', array('class' => 'summary'));
1237 echo message_get_fragment($message->fullmessage, $keywords);
1238 echo html_writer::start_tag('div', array('class' => 'link'));
1240 //If the user clicks the context link display message sender on the left
1241 //EXCEPT if the current user is in the conversation. Current user == always on the left
1242 $leftsideuserid = $rightsideuserid = null;
1243 if ($currentuser->id == $message->useridto) {
1244 $leftsideuserid = $message->useridto;
1245 $rightsideuserid = $message->useridfrom;
1246 } else {
1247 $leftsideuserid = $message->useridfrom;
1248 $rightsideuserid = $message->useridto;
1250 message_history_link($leftsideuserid, $rightsideuserid, false,
1251 $messagesearchstring, 'm'.$message->id, $strcontext);
1252 echo html_writer::end_tag('div');
1253 echo html_writer::end_tag('td');
1255 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1257 echo html_writer::end_tag('tr');
1261 if ($blockedcount > 0) {
1262 echo html_writer::start_tag('tr');
1263 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1264 echo html_writer::end_tag('tr');
1266 echo html_writer::end_tag('table');
1268 } else {
1269 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1273 if (!$personsearch && !$messagesearch) {
1274 //they didn't enter any search terms
1275 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1278 echo html_writer::end_tag('div');
1282 * Print information on a user. Used when printing search results.
1284 * @param object/bool $user the user to display or false if you just want $USER
1285 * @param bool $iscontact is the user being displayed a contact?
1286 * @param bool $isblocked is the user being displayed blocked?
1287 * @param bool $includeicontext include text next to the action icons?
1288 * @return void
1290 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1291 global $USER, $OUTPUT;
1293 if ($user === false) {
1294 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1295 } else {
1296 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1297 echo '&nbsp;';
1299 $return = false;
1300 $script = null;
1301 if ($iscontact) {
1302 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1303 } else {
1304 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1306 echo '&nbsp;';
1307 if ($isblocked) {
1308 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1309 } else {
1310 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1313 $popupoptions = array(
1314 'height' => MESSAGE_DISCUSSION_HEIGHT,
1315 'width' => MESSAGE_DISCUSSION_WIDTH,
1316 'menubar' => false,
1317 'location' => false,
1318 'status' => true,
1319 'scrollbars' => true,
1320 'resizable' => true);
1322 $link = new moodle_url("/message/index.php?id=$user->id");
1323 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1324 $action = null;
1325 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1331 * Print a message contact link
1333 * @staticvar type $str
1334 * @param int $userid the ID of the user to apply to action to
1335 * @param string $linktype can be add, remove, block or unblock
1336 * @param bool $return if true return the link as a string. If false echo the link.
1337 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1338 * @param bool $text include text next to the icons?
1339 * @param bool $icon include a graphical icon?
1340 * @return string if $return is true otherwise bool
1342 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1343 global $OUTPUT, $PAGE;
1345 //hold onto the strings as we're probably creating a bunch of links
1346 static $str;
1348 if (empty($script)) {
1349 //strip off previous action params like 'removecontact'
1350 $script = message_remove_url_params($PAGE->url);
1353 if (empty($str->blockcontact)) {
1354 $str = new stdClass();
1355 $str->blockcontact = get_string('blockcontact', 'message');
1356 $str->unblockcontact = get_string('unblockcontact', 'message');
1357 $str->removecontact = get_string('removecontact', 'message');
1358 $str->addcontact = get_string('addcontact', 'message');
1361 $command = $linktype.'contact';
1362 $string = $str->{$command};
1364 $safealttext = s($string);
1366 $safestring = '';
1367 if (!empty($text)) {
1368 $safestring = $safealttext;
1371 $img = '';
1372 if ($icon) {
1373 $iconpath = null;
1374 switch ($linktype) {
1375 case 'block':
1376 $iconpath = 't/block';
1377 break;
1378 case 'unblock':
1379 $iconpath = 't/userblue';
1380 break;
1381 case 'remove':
1382 $iconpath = 'i/cross_red_big';
1383 break;
1384 case 'add':
1385 default:
1386 $iconpath = 't/addgreen';
1389 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1392 $output = '<span class="'.$linktype.'contact">'.
1393 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1394 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1395 $img.
1396 $safestring.'</a></span>';
1398 if ($return) {
1399 return $output;
1400 } else {
1401 echo $output;
1402 return true;
1407 * echo or return a link to take the user to the full message history between themselves and another user
1409 * @staticvar type $strmessagehistory
1410 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1411 * @param int $userid2 the ID of the other user
1412 * @param bool $return true to return the link as a string. False to echo the link.
1413 * @param string $keywords any keywords to highlight in the message history
1414 * @param string $position anchor name to jump to within the message history
1415 * @param string $linktext optionally specify the link text
1416 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1418 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1419 global $OUTPUT;
1420 static $strmessagehistory;
1422 if (empty($strmessagehistory)) {
1423 $strmessagehistory = get_string('messagehistory', 'message');
1426 if ($position) {
1427 $position = "#$position";
1429 if ($keywords) {
1430 $keywords = "&search=".urlencode($keywords);
1433 if ($linktext == 'icon') { // Icon only
1434 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1435 } else if ($linktext == 'both') { // Icon and standard name
1436 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1437 $fulllink .= '&nbsp;'.$strmessagehistory;
1438 } else if ($linktext) { // Custom name
1439 $fulllink = $linktext;
1440 } else { // Standard name only
1441 $fulllink = $strmessagehistory;
1444 $popupoptions = array(
1445 'height' => 500,
1446 'width' => 500,
1447 'menubar' => false,
1448 'location' => false,
1449 'status' => true,
1450 'scrollbars' => true,
1451 'resizable' => true);
1453 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1454 $action = null;
1455 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1457 $str = '<span class="history">'.$str.'</span>';
1459 if ($return) {
1460 return $str;
1461 } else {
1462 echo $str;
1463 return true;
1469 * Search through course users
1471 * If $coursid specifies the site course then this function searches
1472 * through all undeleted and confirmed users
1473 * @param int $courseid The course in question.
1474 * @param string $searchtext the text to search for
1475 * @param string $sort the column name to order by
1476 * @param string $exceptions comma separated list of user IDs to exclude
1477 * @return array An array of {@link $USER} records.
1479 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1480 global $CFG, $USER, $DB;
1482 $fullname = $DB->sql_fullname();
1484 if (!empty($exceptions)) {
1485 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1486 } else {
1487 $except = '';
1490 if (!empty($sort)) {
1491 $order = ' ORDER BY '. $sort;
1492 } else {
1493 $order = '';
1496 $ufields = user_picture::fields('u');
1497 if (!$courseid or $courseid == SITEID) {
1498 $params = array($USER->id, "%$searchtext%");
1499 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1500 FROM {user} u
1501 LEFT JOIN {message_contacts} mc
1502 ON mc.contactid = u.id AND mc.userid = ?
1503 WHERE u.deleted = '0' AND u.confirmed = '1'
1504 AND (".$DB->sql_like($fullname, '?', false).")
1505 $except
1506 $order", $params);
1507 } else {
1508 //TODO: add enabled enrolment join here (skodak)
1509 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1510 $contextlists = get_related_contexts_string($context);
1512 // everyone who has a role assignment in this course or higher
1513 $params = array($USER->id, "%$searchtext%");
1514 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1515 FROM {user} u
1516 JOIN {role_assignments} ra ON ra.userid = u.id
1517 LEFT JOIN {message_contacts} mc
1518 ON mc.contactid = u.id AND mc.userid = ?
1519 WHERE u.deleted = '0' AND u.confirmed = '1'
1520 AND ra.contextid $contextlists
1521 AND (".$DB->sql_like($fullname, '?', false).")
1522 $except
1523 $order", $params);
1525 return $users;
1530 * search a user's messages
1532 * @param array $searchterms an array of search terms (strings)
1533 * @param bool $fromme include messages from the user?
1534 * @param bool $tome include messages to the user?
1535 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1536 * @param int $userid the user ID of the current user
1537 * @return mixed An array of messages or false if no matching messages were found
1539 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1540 /// Returns a list of posts found using an array of search terms
1541 /// eg word +word -word
1543 global $CFG, $USER, $DB;
1545 // If user is searching all messages check they are allowed to before doing anything else
1546 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) {
1547 print_error('accessdenied','admin');
1550 /// If no userid sent then assume current user
1551 if ($userid == 0) $userid = $USER->id;
1553 /// Some differences in SQL syntax
1554 if ($DB->sql_regex_supported()) {
1555 $REGEXP = $DB->sql_regex(true);
1556 $NOTREGEXP = $DB->sql_regex(false);
1559 $searchcond = array();
1560 $params = array();
1561 $i = 0;
1563 //preprocess search terms to check whether we have at least 1 eligible search term
1564 //if we do we can drop words around it like 'a'
1565 $dropshortwords = false;
1566 foreach ($searchterms as $searchterm) {
1567 if (strlen($searchterm) >= 2) {
1568 $dropshortwords = true;
1572 foreach ($searchterms as $searchterm) {
1573 $i++;
1575 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1577 if ($dropshortwords && strlen($searchterm) < 2) {
1578 continue;
1580 /// Under Oracle and MSSQL, trim the + and - operators and perform
1581 /// simpler LIKE search
1582 if (!$DB->sql_regex_supported()) {
1583 if (substr($searchterm, 0, 1) == '-') {
1584 $NOT = true;
1586 $searchterm = trim($searchterm, '+-');
1589 if (substr($searchterm,0,1) == "+") {
1590 $searchterm = substr($searchterm,1);
1591 $searchterm = preg_quote($searchterm, '|');
1592 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1593 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1595 } else if (substr($searchterm,0,1) == "-") {
1596 $searchterm = substr($searchterm,1);
1597 $searchterm = preg_quote($searchterm, '|');
1598 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1599 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1601 } else {
1602 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1603 $params['ss'.$i] = "%$searchterm%";
1607 if (empty($searchcond)) {
1608 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1609 $params['ss1'] = "%";
1610 } else {
1611 $searchcond = implode(" AND ", $searchcond);
1614 /// There are several possibilities
1615 /// 1. courseid = SITEID : The admin is searching messages by all users
1616 /// 2. courseid = ?? : A teacher is searching messages by users in
1617 /// one of their courses - currently disabled
1618 /// 3. courseid = none : User is searching their own messages;
1619 /// a. Messages from user
1620 /// b. Messages to user
1621 /// c. Messages to and from user
1623 if ($courseid == SITEID) { /// admin is searching all messages
1624 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1625 FROM {message_read} m
1626 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1627 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1628 FROM {message} m
1629 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1631 } else if ($courseid !== 'none') {
1632 /// This has not been implemented due to security concerns
1633 $m_read = array();
1634 $m_unread = array();
1636 } else {
1638 if ($fromme and $tome) {
1639 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1640 $params['userid1'] = $userid;
1641 $params['userid2'] = $userid;
1643 } else if ($fromme) {
1644 $searchcond .= " AND m.useridfrom=:userid";
1645 $params['userid'] = $userid;
1647 } else if ($tome) {
1648 $searchcond .= " AND m.useridto=:userid";
1649 $params['userid'] = $userid;
1652 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1653 FROM {message_read} m
1654 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1655 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1656 FROM {message} m
1657 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1661 /// The keys may be duplicated in $m_read and $m_unread so we can't
1662 /// do a simple concatenation
1663 $messages = array();
1664 foreach ($m_read as $m) {
1665 $messages[] = $m;
1667 foreach ($m_unread as $m) {
1668 $messages[] = $m;
1671 return (empty($messages)) ? false : $messages;
1675 * Given a message object that we already know has a long message
1676 * this function truncates the message nicely to the first
1677 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1679 * @param string $message the message
1680 * @param int $minlength the minimum length to trim the message to
1681 * @return string the shortened message
1683 function message_shorten_message($message, $minlength = 0) {
1684 $i = 0;
1685 $tag = false;
1686 $length = strlen($message);
1687 $count = 0;
1688 $stopzone = false;
1689 $truncate = 0;
1690 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1693 for ($i=0; $i<$length; $i++) {
1694 $char = $message[$i];
1696 switch ($char) {
1697 case "<":
1698 $tag = true;
1699 break;
1700 case ">":
1701 $tag = false;
1702 break;
1703 default:
1704 if (!$tag) {
1705 if ($stopzone) {
1706 if ($char == '.' or $char == ' ') {
1707 $truncate = $i+1;
1708 break 2;
1711 $count++;
1713 break;
1715 if (!$stopzone) {
1716 if ($count > $minlength) {
1717 $stopzone = true;
1722 if (!$truncate) {
1723 $truncate = $i;
1726 return substr($message, 0, $truncate);
1731 * Given a string and an array of keywords, this function looks
1732 * for the first keyword in the string, and then chops out a
1733 * small section from the text that shows that word in context.
1735 * @param string $message the text to search
1736 * @param array $keywords array of keywords to find
1738 function message_get_fragment($message, $keywords) {
1740 $fullsize = 160;
1741 $halfsize = (int)($fullsize/2);
1743 $message = strip_tags($message);
1745 foreach ($keywords as $keyword) { // Just get the first one
1746 if ($keyword !== '') {
1747 break;
1750 if (empty($keyword)) { // None found, so just return start of message
1751 return message_shorten_message($message, 30);
1754 $leadin = $leadout = '';
1756 /// Find the start of the fragment
1757 $start = 0;
1758 $length = strlen($message);
1760 $pos = strpos($message, $keyword);
1761 if ($pos > $halfsize) {
1762 $start = $pos - $halfsize;
1763 $leadin = '...';
1765 /// Find the end of the fragment
1766 $end = $start + $fullsize;
1767 if ($end > $length) {
1768 $end = $length;
1769 } else {
1770 $leadout = '...';
1773 /// Pull out the fragment and format it
1775 $fragment = substr($message, $start, $end - $start);
1776 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1777 return $fragment;
1781 * Retrieve the messages between two users
1783 * @param object $user1 the current user
1784 * @param object $user2 the other user
1785 * @param int $limitnum the maximum number of messages to retrieve
1786 * @param bool $viewingnewmessages are we currently viewing new messages?
1788 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1789 global $DB, $CFG;
1791 $messages = array();
1793 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1794 //desc to get the last $limitnum messages then flip the order in php
1795 $sort = 'asc';
1796 if ($limitnum>0) {
1797 $sort = 'desc';
1800 $notificationswhere = null;
1801 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1802 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1803 $notificationswhere = 'AND notification=0';
1806 //prevent notifications of your own actions appearing in your own message history
1807 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1809 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1810 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1811 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1812 "timecreated $sort", '*', 0, $limitnum)) {
1813 foreach ($messages_read as $message) {
1814 $messages[$message->timecreated] = $message;
1817 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1818 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1819 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1820 "timecreated $sort", '*', 0, $limitnum)) {
1821 foreach ($messages_new as $message) {
1822 $messages[$message->timecreated] = $message;
1826 //if we only want the last $limitnum messages
1827 ksort($messages);
1828 $messagecount = count($messages);
1829 if ($limitnum>0 && $messagecount>$limitnum) {
1830 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1833 return $messages;
1837 * Print the message history between two users
1839 * @param object $user1 the current user
1840 * @param object $user2 the other user
1841 * @param string $search search terms to highlight
1842 * @param int $messagelimit maximum number of messages to return
1843 * @param string $messagehistorylink the html for the message history link or false
1844 * @param bool $viewingnewmessages are we currently viewing new messages?
1846 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1847 global $CFG, $OUTPUT;
1849 echo $OUTPUT->box_start('center');
1850 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1851 echo html_writer::start_tag('tr');
1853 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1854 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1855 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1856 echo html_writer::end_tag('td');
1858 echo html_writer::start_tag('td', array('align' => 'center'));
1859 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1860 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1861 echo html_writer::end_tag('td');
1863 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1864 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1865 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1867 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1868 $incontactlist = $user2->iscontact;
1869 $isblocked = $user2->isblocked;
1871 $script = null;
1872 $text = true;
1873 $icon = false;
1875 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1876 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1877 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1879 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1882 echo html_writer::end_tag('td');
1883 echo html_writer::end_tag('tr');
1884 echo html_writer::end_tag('table');
1885 echo $OUTPUT->box_end();
1887 if (!empty($messagehistorylink)) {
1888 echo $messagehistorylink;
1891 /// Get all the messages and print them
1892 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1893 $tablecontents = '';
1895 $current = new stdClass();
1896 $current->mday = '';
1897 $current->month = '';
1898 $current->year = '';
1899 $messagedate = get_string('strftimetime');
1900 $blockdate = get_string('strftimedaydate');
1901 foreach ($messages as $message) {
1902 if ($message->notification) {
1903 $notificationclass = ' notification';
1904 } else {
1905 $notificationclass = null;
1907 $date = usergetdate($message->timecreated);
1908 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1909 $current->mday = $date['mday'];
1910 $current->month = $date['month'];
1911 $current->year = $date['year'];
1913 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1914 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1916 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1919 $formatted_message = $side = null;
1920 if ($message->useridfrom == $user1->id) {
1921 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1922 $side = 'left';
1923 } else {
1924 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1925 $side = 'right';
1927 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1930 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1931 } else {
1932 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1937 * Format a message for display in the message history
1939 * @param object $message the message object
1940 * @param string $format optional date format
1941 * @param string $keywords keywords to highlight
1942 * @param string $class CSS class to apply to the div around the message
1943 * @return string the formatted message
1945 function message_format_message($message, $format='', $keywords='', $class='other') {
1947 static $dateformat;
1949 //if we haven't previously set the date format or they've supplied a new one
1950 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1951 if ($format) {
1952 $dateformat = $format;
1953 } else {
1954 $dateformat = get_string('strftimedatetimeshort');
1957 $time = userdate($message->timecreated, $dateformat);
1958 $options = new stdClass();
1959 $options->para = false;
1961 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1962 if (!empty($message->smallmessage)) {
1963 $messagetext = $message->smallmessage;
1964 } else {
1965 $messagetext = $message->fullmessage;
1967 if ($message->fullmessageformat == FORMAT_HTML) {
1968 //dont escape html tags by calling s() if html format or they will display in the UI
1969 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1970 } else {
1971 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1974 $messagetext .= message_format_contexturl($message);
1976 if ($keywords) {
1977 $messagetext = highlight($keywords, $messagetext);
1980 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1984 * Format a the context url and context url name of a message for display
1986 * @param object $message the message object
1987 * @return string the formatted string
1989 function message_format_contexturl($message) {
1990 $s = null;
1992 if (!empty($message->contexturl)) {
1993 $displaytext = null;
1994 if (!empty($message->contexturlname)) {
1995 $displaytext= $message->contexturlname;
1996 } else {
1997 $displaytext= $message->contexturl;
1999 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2000 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2001 $s .= html_writer::end_tag('div');
2004 return $s;
2008 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2010 * @param object $userfrom the message sender
2011 * @param object $userto the message recipient
2012 * @param string $message the message
2013 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2014 * @return int|false the ID of the new message or false
2016 function message_post_message($userfrom, $userto, $message, $format) {
2017 global $SITE, $CFG, $USER;
2019 $eventdata = new stdClass();
2020 $eventdata->component = 'moodle';
2021 $eventdata->name = 'instantmessage';
2022 $eventdata->userfrom = $userfrom;
2023 $eventdata->userto = $userto;
2025 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2026 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2028 if ($format == FORMAT_HTML) {
2029 $eventdata->fullmessagehtml = $message;
2030 //some message processors may revert to sending plain text even if html is supplied
2031 //so we keep both plain and html versions if we're intending to send html
2032 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2033 } else {
2034 $eventdata->fullmessage = $message;
2035 $eventdata->fullmessagehtml = '';
2038 $eventdata->fullmessageformat = $format;
2039 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2041 $s = new stdClass();
2042 $s->sitename = format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
2043 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2045 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2046 if (!empty($eventdata->fullmessage)) {
2047 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2049 if (!empty($eventdata->fullmessagehtml)) {
2050 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2053 $eventdata->timecreated = time();
2054 return message_send($eventdata);
2059 * Returns a list of all user ids who have used messaging in the site
2060 * This was the simple way to code the SQL ... is it going to blow up
2061 * on large datasets?
2063 * @todo: deprecated - to be deleted in 2.2
2064 * @return array
2066 function message_get_participants() {
2067 global $CFG, $DB;
2069 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
2070 UNION SELECT useridto as id,1 FROM {message}
2071 UNION SELECT useridfrom as id,1 FROM {message_read}
2072 UNION SELECT useridto as id,1 FROM {message_read}
2073 UNION SELECT userid as id,1 FROM {message_contacts}
2074 UNION SELECT contactid as id,1 from {message_contacts}");
2078 * Print a row of contactlist displaying user picture, messages waiting and
2079 * block links etc
2081 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2082 * @param bool $incontactlist is the user a contact of ours?
2083 * @param bool $isblocked is the user blocked?
2084 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2085 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2086 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2087 * @return void
2089 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2090 global $OUTPUT, $USER;
2091 $fullname = fullname($contact);
2092 $fullnamelink = $fullname;
2094 $linkclass = '';
2095 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2096 $linkclass = 'messageselecteduser';
2099 /// are there any unread messages for this contact?
2100 if ($contact->messagecount > 0 ){
2101 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2104 $strcontact = $strblock = $strhistory = null;
2106 if ($showactionlinks) {
2107 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2108 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2109 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2112 echo html_writer::start_tag('tr');
2113 echo html_writer::start_tag('td', array('class' => 'pix'));
2114 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2115 echo html_writer::end_tag('td');
2117 echo html_writer::start_tag('td', array('class' => 'contact'));
2119 $popupoptions = array(
2120 'height' => MESSAGE_DISCUSSION_HEIGHT,
2121 'width' => MESSAGE_DISCUSSION_WIDTH,
2122 'menubar' => false,
2123 'location' => false,
2124 'status' => true,
2125 'scrollbars' => true,
2126 'resizable' => true);
2128 $link = $action = null;
2129 if (!empty($selectcontacturl)) {
2130 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2131 } else {
2132 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2133 $link = new moodle_url("/message/index.php?id=$contact->id");
2134 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2136 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2138 echo html_writer::end_tag('td');
2140 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2142 echo html_writer::end_tag('tr');
2146 * Constructs the add/remove contact link to display next to other users
2148 * @param bool $incontactlist is the user a contact
2149 * @param bool $isblocked is the user blocked
2150 * @param type $contact contact object
2151 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2152 * @param bool $text include text next to the icons?
2153 * @param bool $icon include a graphical icon?
2154 * @return string
2156 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2157 $strcontact = '';
2159 if($incontactlist){
2160 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2161 } else if ($isblocked) {
2162 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2163 } else{
2164 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2167 return $strcontact;
2171 * Constructs the block contact link to display next to other users
2173 * @param bool $incontactlist is the user a contact
2174 * @param bool $isblocked is the user blocked
2175 * @param type $contact contact object
2176 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2177 * @param bool $text include text next to the icons?
2178 * @param bool $icon include a graphical icon?
2179 * @return string
2181 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2182 $strblock = '';
2184 //commented out to allow the user to block a contact without having to remove them first
2185 /*if ($incontactlist) {
2186 //$strblock = '';
2187 } else*/
2188 if ($isblocked) {
2189 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2190 } else{
2191 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2194 return $strblock;
2198 * Moves messages from a particular user from the message table (unread messages) to message_read
2199 * This is typically only used when a user is deleted
2201 * @param object $userid User id
2202 * @return boolean success
2204 function message_move_userfrom_unread2read($userid) {
2205 global $DB;
2207 // move all unread messages from message table to message_read
2208 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2209 foreach ($messages as $message) {
2210 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2213 return true;
2217 * marks ALL messages being sent from $fromuserid to $touserid as read
2219 * @param int $touserid the id of the message recipient
2220 * @param int $fromuserid the id of the message sender
2221 * @return void
2223 function message_mark_messages_read($touserid, $fromuserid){
2224 global $DB;
2226 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2227 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2229 foreach ($messages as $message) {
2230 message_mark_message_read($message, time());
2233 $messages->close();
2237 * Mark a single message as read
2239 * @param message an object with an object property ie $message->id which is an id in the message table
2240 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2241 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2242 * @return int the ID of the message in the message_read table
2244 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2245 global $DB;
2247 $message->timeread = $timeread;
2249 $messageid = $message->id;
2250 unset($message->id);//unset because it will get a new id on insert into message_read
2252 //If any processors have pending actions abort them
2253 if (!$messageworkingempty) {
2254 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2256 $messagereadid = $DB->insert_record('message_read', $message);
2257 $DB->delete_records('message', array('id' => $messageid));
2258 return $messagereadid;
2262 * A helper function that prints a formatted heading
2264 * @param string $title the heading to display
2265 * @param int $colspan
2266 * @return void
2268 function message_print_heading($title, $colspan=3) {
2269 echo html_writer::start_tag('tr');
2270 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2271 echo html_writer::end_tag('tr');
2275 * Get all message processors, validate corresponding plugin existance and
2276 * system configuration
2278 * @param bool $ready only return ready-to-use processors
2279 * @return mixed $processors array of objects containing information on message processors
2281 function get_message_processors($ready = false) {
2282 global $DB, $CFG;
2284 static $processors;
2286 if (empty($processors)) {
2287 // Get all processors, ensure the name column is the first so it will be the array key
2288 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2289 foreach ($processors as &$processor){
2290 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2291 if (is_readable($processorfile)) {
2292 include_once($processorfile);
2293 $processclass = 'message_output_' . $processor->name;
2294 if (class_exists($processclass)) {
2295 $pclass = new $processclass();
2296 $processor->object = $pclass;
2297 $processor->configured = 0;
2298 if ($pclass->is_system_configured()) {
2299 $processor->configured = 1;
2301 $processor->hassettings = 0;
2302 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2303 $processor->hassettings = 1;
2305 $processor->available = 1;
2306 } else {
2307 print_error('errorcallingprocessor', 'message');
2309 } else {
2310 $processor->available = 0;
2314 if ($ready) {
2315 // Filter out enabled and system_configured processors
2316 $readyprocessors = $processors;
2317 foreach ($readyprocessors as $readyprocessor) {
2318 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2319 unset($readyprocessors[$readyprocessor->name]);
2322 return $readyprocessors;
2325 return $processors;
2329 * Get an instance of the message_output class for one of the output plugins.
2330 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2331 * @return message_output message_output the requested class.
2333 function get_message_processor($type) {
2334 global $CFG;
2336 // Note, we cannot use the get_message_processors function here, becaues this
2337 // code is called during install after installing each messaging plugin, and
2338 // get_message_processors caches the list of installed plugins.
2340 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2341 if (!is_readable($processorfile)) {
2342 throw new coding_exception('Unknown message processor type ' . $type);
2345 include_once($processorfile);
2347 $processclass = 'message_output_' . $type;
2348 if (!class_exists($processclass)) {
2349 throw new coding_exception('Message processor ' . $type .
2350 ' does not define the right class');
2353 return new $processclass();
2357 * Get messaging outputs default (site) preferences
2359 * @return object $processors object containing information on message processors
2361 function get_message_output_default_preferences() {
2362 return get_config('message');
2366 * Translate message default settings from binary value to the array of string
2367 * representing the settings to be stored. Also validate the provided value and
2368 * use default if it is malformed.
2370 * @param int $plugindefault Default setting suggested by plugin
2371 * @param string $processorname The name of processor
2372 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2374 function translate_message_default_setting($plugindefault, $processorname) {
2375 // Preset translation arrays
2376 $permittedvalues = array(
2377 0x04 => 'disallowed',
2378 0x08 => 'permitted',
2379 0x0c => 'forced',
2382 $loggedinstatusvalues = array(
2383 0x00 => null, // use null if loggedin/loggedoff is not defined
2384 0x01 => 'loggedin',
2385 0x02 => 'loggedoff',
2388 // define the default setting
2389 $processor = get_message_processor($processorname);
2390 $default = $processor->get_default_messaging_settings();
2392 // Validate the value. It should not exceed the maximum size
2393 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2394 debugging(get_string('errortranslatingdefault', 'message'));
2395 $plugindefault = $default;
2397 // Use plugin default setting of 'permitted' is 0
2398 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2399 $plugindefault = $default;
2402 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2403 $loggedin = $loggedoff = null;
2405 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2406 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2407 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2410 return array($permitted, $loggedin, $loggedoff);
2414 * Return a list of page types
2415 * @param string $pagetype current page type
2416 * @param stdClass $parentcontext Block's parent context
2417 * @param stdClass $currentcontext Current context of block
2419 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2420 return array('messages-*'=>get_string('page-message-x', 'message'));
2424 * Is $USER one of the supplied users?
2426 * $user2 will be null if viewing a user's recent conversations
2428 * @param stdClass the first user
2429 * @param stdClass the second user or null
2430 * @return bool True if the current user is one of either $user1 or $user2
2432 function message_current_user_is_involved($user1, $user2) {
2433 global $USER;
2435 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2436 throw new coding_exception('Invalid user object detected. Missing id.');
2439 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2440 return false;
2442 return true;