Merge branch 'MDL-30175' of git://github.com/stronk7/moodle
[moodle.git] / message / lib.php
bloba9c8fffac8bc26eb39959ce538b7cd83211c84d4
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::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
514 echo html_writer::end_tag('fieldset');
515 echo html_writer::end_tag('form');
519 * Load the course contexts for all of the users courses
521 * @param array $courses array of course objects. The courses the user is enrolled in.
522 * @return array of course contexts
524 function message_get_course_contexts($courses) {
525 $coursecontexts = array();
527 foreach($courses as $course) {
528 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
531 return $coursecontexts;
535 * strip off action parameters like 'removecontact'
537 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
538 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
540 function message_remove_url_params($moodleurl) {
541 $newurl = new moodle_url($moodleurl);
542 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
543 return $newurl->out();
547 * Count the number of messages with a field having a specified value.
548 * if $field is empty then return count of the whole array
549 * if $field is non-existent then return 0
551 * @param array $messagearray array of message objects
552 * @param string $field the field to inspect on the message objects
553 * @param string $value the value to test the field against
555 function message_count_messages($messagearray, $field='', $value='') {
556 if (!is_array($messagearray)) return 0;
557 if ($field == '' or empty($messagearray)) return count($messagearray);
559 $count = 0;
560 foreach ($messagearray as $message) {
561 $count += ($message->$field == $value) ? 1 : 0;
563 return $count;
567 * Returns the count of unread messages for user. Either from a specific user or from all users.
569 * @param object $user1 the first user. Defaults to $USER
570 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
571 * @return int the count of $user1's unread messages
573 function message_count_unread_messages($user1=null, $user2=null) {
574 global $USER, $DB;
576 if (empty($user1)) {
577 $user1 = $USER;
580 if (!empty($user2)) {
581 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
582 array($user1->id, $user2->id), "COUNT('id')");
583 } else {
584 return $DB->count_records_select('message', "useridto = ?",
585 array($user1->id), "COUNT('id')");
590 * Count the number of users blocked by $user1
592 * @param object $user1 user object
593 * @return int the number of blocked users
595 function message_count_blocked_users($user1=null) {
596 global $USER, $DB;
598 if (empty($user1)) {
599 $user1 = $USER;
602 $sql = "SELECT count(mc.id)
603 FROM {message_contacts} mc
604 WHERE mc.userid = :userid AND mc.blocked = 1";
605 $params = array('userid' => $user1->id);
607 return $DB->count_records_sql($sql, $params);
611 * Print the search form and search results if a search has been performed
613 * @param boolean $advancedsearch show basic or advanced search form
614 * @param object $user1 the current user
615 * @return boolean true if a search was performed
617 function message_print_search($advancedsearch = false, $user1=null) {
618 $frm = data_submitted();
620 $doingsearch = false;
621 if ($frm) {
622 if (confirm_sesskey()) {
623 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
624 } else {
625 $frm = false;
629 if (!empty($frm->combinedsearch)) {
630 $combinedsearchstring = $frm->combinedsearch;
631 } else {
632 //$combinedsearchstring = get_string('searchcombined','message').'...';
633 $combinedsearchstring = '';
636 if ($doingsearch) {
637 if ($advancedsearch) {
639 $messagesearch = '';
640 if (!empty($frm->keywords)) {
641 $messagesearch = $frm->keywords;
643 $personsearch = '';
644 if (!empty($frm->name)) {
645 $personsearch = $frm->name;
647 include('search_advanced.html');
648 } else {
649 include('search.html');
652 $showicontext = false;
653 message_print_search_results($frm, $showicontext, $user1);
655 return true;
656 } else {
658 if ($advancedsearch) {
659 $personsearch = $messagesearch = '';
660 include('search_advanced.html');
661 } else {
662 include('search.html');
664 return false;
669 * Get the users recent conversations meaning all the people they've recently
670 * sent or received a message from plus the most recent message sent to or received from each other user
672 * @param object $user the current user
673 * @param int $limitfrom can be used for paging
674 * @param int $limitto can be used for paging
675 * @return array
677 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
678 global $DB;
680 $userfields = user_picture::fields('u', array('lastaccess'));
681 //This query retrieves the last message received from and sent to each user
682 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
683 //It then joins with some other tables to get some additional data we need
685 //message ID is used instead of timecreated as it should sort the same and will be much faster
687 //There is a separate query for read and unread queries as they are stored in different tables
688 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
689 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
690 FROM {message_read} mr
691 JOIN (
692 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
693 FROM (
694 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
695 FROM {message_read} mr1
696 WHERE mr1.useridfrom = :userid1
697 AND mr1.notification = 0
698 GROUP BY mr1.useridto
699 UNION
700 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
701 FROM {message_read} mr2
702 WHERE mr2.useridto = :userid2
703 AND mr2.notification = 0
704 GROUP BY mr2.useridfrom
705 ) messages
706 GROUP BY messages.userid
707 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
708 JOIN {user} u ON u.id = messages2.userid
709 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
710 WHERE u.deleted = '0'
711 ORDER BY mr.id DESC";
712 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
713 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
715 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
716 FROM {message} m
717 JOIN (
718 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
719 FROM (
720 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
721 FROM {message} m1
722 WHERE m1.useridfrom = :userid1
723 AND m1.notification = 0
724 GROUP BY m1.useridto
725 UNION
726 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
727 FROM {message} m2
728 WHERE m2.useridto = :userid2
729 AND m2.notification = 0
730 GROUP BY m2.useridfrom
731 ) messages
732 GROUP BY messages.userid
733 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
734 JOIN {user} u ON u.id = messages2.userid
735 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
736 WHERE u.deleted = '0'
737 ORDER BY m.id DESC";
738 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
740 $conversations = array();
742 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
743 //$conversation->id (the array key) is the other user's ID
744 $conversation_arrays = array($unread, $read);
745 foreach ($conversation_arrays as $conversation_array) {
746 foreach ($conversation_array as $conversation) {
747 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
748 $conversations[$conversation->id] = $conversation;
753 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
754 //and there may be multiple conversations with the same timecreated value.
755 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
756 usort($conversations, "conversationsort");
758 return $conversations;
762 * Sort function used to order conversations
764 * @param object $a A conversation object
765 * @param object $b A conversation object
766 * @return integer
768 function conversationsort($a, $b)
770 if ($a->timecreated == $b->timecreated) {
771 return 0;
773 return ($a->timecreated > $b->timecreated) ? -1 : 1;
777 * Get the users recent event notifications
779 * @param object $user the current user
780 * @param int $limitfrom can be used for paging
781 * @param int $limitto can be used for paging
782 * @return array
784 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
785 global $DB;
787 $userfields = user_picture::fields('u', array('lastaccess'));
788 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
789 FROM {message_read} mr
790 JOIN {user} u ON u.id=mr.useridfrom
791 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
792 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
793 $params = array('userid1' => $user->id, 'notification' => 1);
795 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
796 return $notifications;
800 * Print the user's recent conversations
802 * @param object $user1 the current user
803 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
804 * @return void
806 function message_print_recent_conversations($user=null, $showicontext=false) {
807 global $USER;
809 echo html_writer::start_tag('p', array('class' => 'heading'));
810 echo get_string('mostrecentconversations', 'message');
811 echo html_writer::end_tag('p');
813 if (empty($user)) {
814 $user = $USER;
817 $conversations = message_get_recent_conversations($user);
819 $showotheruser = true;
820 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
824 * Print the user's recent notifications
826 * @param object $user1 the current user
827 * @return void
829 function message_print_recent_notifications($user=null) {
830 global $USER;
832 echo html_writer::start_tag('p', array('class' => 'heading'));
833 echo get_string('mostrecentnotifications', 'message');
834 echo html_writer::end_tag('p');
836 if (empty($user)) {
837 $user = $USER;
840 $notifications = message_get_recent_notifications($user);
842 $showicontext = false;
843 $showotheruser = false;
844 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
848 * Print a list of recent messages
850 * @staticvar type $dateformat
851 * @param array $messages the messages to display
852 * @param object $user the current user
853 * @param bool $showotheruser display information on the other user?
854 * @param bool $showicontext show text next to the action icons?
855 * @return void
857 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
858 global $OUTPUT;
859 static $dateformat;
861 if (empty($dateformat)) {
862 $dateformat = get_string('strftimedatetimeshort');
865 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
866 foreach ($messages as $message) {
867 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
869 if ($showotheruser) {
870 if ( $message->contactlistid ) {
871 if ($message->blocked == 0) { /// not blocked
872 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
873 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
874 } else { // blocked
875 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
876 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
878 } else {
879 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
880 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
883 //should we show just the icon or icon and text?
884 $histicontext = 'icon';
885 if ($showicontext) {
886 $histicontext = 'both';
888 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
890 echo html_writer::start_tag('span', array('class' => 'otheruser'));
892 echo html_writer::start_tag('span', array('class' => 'pix'));
893 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
894 echo html_writer::end_tag('span');
896 echo html_writer::start_tag('span', array('class' => 'contact'));
898 $link = new moodle_url("/message/index.php?id=$message->id");
899 $action = null;
900 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
902 echo html_writer::end_tag('span');//end contact
904 echo $strcontact.$strblock.$strhistory;
905 echo html_writer::end_tag('span');//end otheruser
907 $messagetoprint = null;
908 if (!empty($message->smallmessage)) {
909 $messagetoprint = $message->smallmessage;
910 } else {
911 $messagetoprint = $message->fullmessage;
914 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
915 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
916 echo message_format_contexturl($message);
917 echo html_writer::end_tag('div');//end singlemessage
919 echo html_writer::end_tag('div');//end messagerecent
923 * Add the selected user as a contact for the current user
925 * @param int $contactid the ID of the user to add as a contact
926 * @param int $blocked 1 if you wish to block the contact
927 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
928 * Otherwise returns the result of update_record() or insert_record()
930 function message_add_contact($contactid, $blocked=0) {
931 global $USER, $DB;
933 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
934 return false;
937 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
938 /// record already exists - we may be changing blocking status
940 if ($contact->blocked !== $blocked) {
941 /// change to blocking status
942 $contact->blocked = $blocked;
943 return $DB->update_record('message_contacts', $contact);
944 } else {
945 /// no changes to blocking status
946 return true;
949 } else {
950 /// new contact record
951 unset($contact);
952 $contact->userid = $USER->id;
953 $contact->contactid = $contactid;
954 $contact->blocked = $blocked;
955 return $DB->insert_record('message_contacts', $contact, false);
960 * remove a contact
962 * @param type $contactid the user ID of the contact to remove
963 * @return bool returns the result of delete_records()
965 function message_remove_contact($contactid) {
966 global $USER, $DB;
967 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
971 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
973 * @param int $contactid the user ID of the contact to unblock
974 * @return bool returns the result of delete_records()
976 function message_unblock_contact($contactid) {
977 global $USER, $DB;
978 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
982 * block a user
984 * @param int $contactid the user ID of the user to block
986 function message_block_contact($contactid) {
987 return message_add_contact($contactid, 1);
991 * Load a user's contact record
993 * @param int $contactid the user ID of the user whose contact record you want
994 * @return array message contacts
996 function message_get_contact($contactid) {
997 global $USER, $DB;
998 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1002 * Print the results of a message search
1004 * @param mixed $frm submitted form data
1005 * @param bool $showicontext show text next to action icons?
1006 * @param object $currentuser the current user
1007 * @return void
1009 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1010 global $USER, $DB, $OUTPUT;
1012 if (empty($currentuser)) {
1013 $currentuser = $USER;
1016 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1018 $personsearch = false;
1019 $personsearchstring = null;
1020 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1021 $personsearch = true;
1022 $personsearchstring = $frm->name;
1023 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1024 $personsearch = true;
1025 $personsearchstring = $frm->combinedsearch;
1028 /// search for person
1029 if ($personsearch) {
1030 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1031 $users = array();
1032 $mycourses = enrol_get_my_courses();
1033 foreach ($mycourses as $mycourse) {
1034 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1035 foreach ($susers as $suser) $users[$suser->id] = $suser;
1038 } else {
1039 $users = message_search_users(SITEID, $personsearchstring);
1042 if (!empty($users)) {
1043 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1044 echo get_string('userssearchresults', 'message', count($users));
1045 echo html_writer::end_tag('p');
1047 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1048 foreach ($users as $user) {
1050 if ( $user->contactlistid ) {
1051 if ($user->blocked == 0) { /// not blocked
1052 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1053 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1054 } else { // blocked
1055 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1056 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1058 } else {
1059 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1060 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1063 //should we show just the icon or icon and text?
1064 $histicontext = 'icon';
1065 if ($showicontext) {
1066 $histicontext = 'both';
1068 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1070 echo html_writer::start_tag('tr');
1072 echo html_writer::start_tag('td', array('class' => 'pix'));
1073 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1074 echo html_writer::end_tag('td');
1076 echo html_writer::start_tag('td',array('class' => 'contact'));
1077 $action = null;
1078 $link = new moodle_url("/message/index.php?id=$user->id");
1079 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1080 echo html_writer::end_tag('td');
1082 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1083 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1084 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1086 echo html_writer::end_tag('tr');
1088 echo html_writer::end_tag('table');
1090 } else {
1091 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1092 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1093 echo html_writer::end_tag('p');
1097 // search messages for keywords
1098 $messagesearch = false;
1099 $messagesearchstring = null;
1100 if (!empty($frm->keywords)) {
1101 $messagesearch = true;
1102 $messagesearchstring = clean_text(trim($frm->keywords));
1103 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1104 $messagesearch = true;
1105 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1108 if ($messagesearch) {
1109 if ($messagesearchstring) {
1110 $keywords = explode(' ', $messagesearchstring);
1111 } else {
1112 $keywords = array();
1114 $tome = false;
1115 $fromme = false;
1116 $courseid = 'none';
1118 if (empty($frm->keywordsoption)) {
1119 $frm->keywordsoption = 'allmine';
1122 switch ($frm->keywordsoption) {
1123 case 'tome':
1124 $tome = true;
1125 break;
1126 case 'fromme':
1127 $fromme = true;
1128 break;
1129 case 'allmine':
1130 $tome = true;
1131 $fromme = true;
1132 break;
1133 case 'allusers':
1134 $courseid = SITEID;
1135 break;
1136 case 'courseusers':
1137 $courseid = $frm->courseid;
1138 break;
1139 default:
1140 $tome = true;
1141 $fromme = true;
1144 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1146 /// get a list of contacts
1147 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1148 $contacts = array();
1151 /// print heading with number of results
1152 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1153 $countresults = count($messages);
1154 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1155 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1156 } else {
1157 echo get_string('keywordssearchresults', 'message', $countresults);
1159 echo html_writer::end_tag('p');
1161 /// print table headings
1162 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1164 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1165 $headertdend = html_writer::end_tag('td');
1166 echo html_writer::start_tag('tr');
1167 echo $headertdstart.get_string('from').$headertdend;
1168 echo $headertdstart.get_string('to').$headertdend;
1169 echo $headertdstart.get_string('message', 'message').$headertdend;
1170 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1171 echo html_writer::end_tag('tr');
1173 $blockedcount = 0;
1174 $dateformat = get_string('strftimedatetimeshort');
1175 $strcontext = get_string('context', 'message');
1176 foreach ($messages as $message) {
1178 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1179 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1180 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1181 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1184 $blockedcount ++;
1185 continue;
1188 /// load up user to record
1189 if ($message->useridto !== $USER->id) {
1190 $userto = $DB->get_record('user', array('id' => $message->useridto));
1191 $tocontact = (array_key_exists($message->useridto, $contacts) and
1192 ($contacts[$message->useridto]->blocked == 0) );
1193 $toblocked = (array_key_exists($message->useridto, $contacts) and
1194 ($contacts[$message->useridto]->blocked == 1) );
1195 } else {
1196 $userto = false;
1197 $tocontact = false;
1198 $toblocked = false;
1201 /// load up user from record
1202 if ($message->useridfrom !== $USER->id) {
1203 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1204 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1205 ($contacts[$message->useridfrom]->blocked == 0) );
1206 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1207 ($contacts[$message->useridfrom]->blocked == 1) );
1208 } else {
1209 $userfrom = false;
1210 $fromcontact = false;
1211 $fromblocked = false;
1214 /// find date string for this message
1215 $date = usergetdate($message->timecreated);
1216 $datestring = $date['year'].$date['mon'].$date['mday'];
1218 /// print out message row
1219 echo html_writer::start_tag('tr', array('valign' => 'top'));
1221 echo html_writer::start_tag('td', array('class' => 'contact'));
1222 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1223 echo html_writer::end_tag('td');
1225 echo html_writer::start_tag('td', array('class' => 'contact'));
1226 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1227 echo html_writer::end_tag('td');
1229 echo html_writer::start_tag('td', array('class' => 'summary'));
1230 echo message_get_fragment($message->fullmessage, $keywords);
1231 echo html_writer::start_tag('div', array('class' => 'link'));
1233 //If the user clicks the context link display message sender on the left
1234 //EXCEPT if the current user is in the conversation. Current user == always on the left
1235 $leftsideuserid = $rightsideuserid = null;
1236 if ($currentuser->id == $message->useridto) {
1237 $leftsideuserid = $message->useridto;
1238 $rightsideuserid = $message->useridfrom;
1239 } else {
1240 $leftsideuserid = $message->useridfrom;
1241 $rightsideuserid = $message->useridto;
1243 message_history_link($leftsideuserid, $rightsideuserid, false,
1244 $messagesearchstring, 'm'.$message->id, $strcontext);
1245 echo html_writer::end_tag('div');
1246 echo html_writer::end_tag('td');
1248 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1250 echo html_writer::end_tag('tr');
1254 if ($blockedcount > 0) {
1255 echo html_writer::start_tag('tr');
1256 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1257 echo html_writer::end_tag('tr');
1259 echo html_writer::end_tag('table');
1261 } else {
1262 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1266 if (!$personsearch && !$messagesearch) {
1267 //they didn't enter any search terms
1268 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1271 echo html_writer::end_tag('div');
1275 * Print information on a user. Used when printing search results.
1277 * @param object/bool $user the user to display or false if you just want $USER
1278 * @param bool $iscontact is the user being displayed a contact?
1279 * @param bool $isblocked is the user being displayed blocked?
1280 * @param bool $includeicontext include text next to the action icons?
1281 * @return void
1283 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1284 global $USER, $OUTPUT;
1286 if ($user === false) {
1287 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1288 } else {
1289 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1290 echo '&nbsp;';
1292 $return = false;
1293 $script = null;
1294 if ($iscontact) {
1295 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1296 } else {
1297 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1299 echo '&nbsp;';
1300 if ($isblocked) {
1301 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1302 } else {
1303 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1306 $popupoptions = array(
1307 'height' => MESSAGE_DISCUSSION_HEIGHT,
1308 'width' => MESSAGE_DISCUSSION_WIDTH,
1309 'menubar' => false,
1310 'location' => false,
1311 'status' => true,
1312 'scrollbars' => true,
1313 'resizable' => true);
1315 $link = new moodle_url("/message/index.php?id=$user->id");
1316 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1317 $action = null;
1318 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1324 * Print a message contact link
1326 * @staticvar type $str
1327 * @param int $userid the ID of the user to apply to action to
1328 * @param string $linktype can be add, remove, block or unblock
1329 * @param bool $return if true return the link as a string. If false echo the link.
1330 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1331 * @param bool $text include text next to the icons?
1332 * @param bool $icon include a graphical icon?
1333 * @return string if $return is true otherwise bool
1335 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1336 global $OUTPUT, $PAGE;
1338 //hold onto the strings as we're probably creating a bunch of links
1339 static $str;
1341 if (empty($script)) {
1342 //strip off previous action params like 'removecontact'
1343 $script = message_remove_url_params($PAGE->url);
1346 if (empty($str->blockcontact)) {
1347 $str->blockcontact = get_string('blockcontact', 'message');
1348 $str->unblockcontact = get_string('unblockcontact', 'message');
1349 $str->removecontact = get_string('removecontact', 'message');
1350 $str->addcontact = get_string('addcontact', 'message');
1353 $command = $linktype.'contact';
1354 $string = $str->{$command};
1356 $safealttext = s($string);
1358 $safestring = '';
1359 if (!empty($text)) {
1360 $safestring = $safealttext;
1363 $img = '';
1364 if ($icon) {
1365 $iconpath = null;
1366 switch ($linktype) {
1367 case 'block':
1368 $iconpath = 't/block';
1369 break;
1370 case 'unblock':
1371 $iconpath = 't/userblue';
1372 break;
1373 case 'remove':
1374 $iconpath = 'i/cross_red_big';
1375 break;
1376 case 'add':
1377 default:
1378 $iconpath = 't/addgreen';
1381 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1384 $output = '<span class="'.$linktype.'contact">'.
1385 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1386 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1387 $img.
1388 $safestring.'</a></span>';
1390 if ($return) {
1391 return $output;
1392 } else {
1393 echo $output;
1394 return true;
1399 * echo or return a link to take the user to the full message history between themselves and another user
1401 * @staticvar type $strmessagehistory
1402 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1403 * @param int $userid2 the ID of the other user
1404 * @param bool $return true to return the link as a string. False to echo the link.
1405 * @param string $keywords any keywords to highlight in the message history
1406 * @param string $position anchor name to jump to within the message history
1407 * @param string $linktext optionally specify the link text
1408 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1410 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1411 global $OUTPUT;
1412 static $strmessagehistory;
1414 if (empty($strmessagehistory)) {
1415 $strmessagehistory = get_string('messagehistory', 'message');
1418 if ($position) {
1419 $position = "#$position";
1421 if ($keywords) {
1422 $keywords = "&search=".urlencode($keywords);
1425 if ($linktext == 'icon') { // Icon only
1426 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1427 } else if ($linktext == 'both') { // Icon and standard name
1428 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1429 $fulllink .= '&nbsp;'.$strmessagehistory;
1430 } else if ($linktext) { // Custom name
1431 $fulllink = $linktext;
1432 } else { // Standard name only
1433 $fulllink = $strmessagehistory;
1436 $popupoptions = array(
1437 'height' => 500,
1438 'width' => 500,
1439 'menubar' => false,
1440 'location' => false,
1441 'status' => true,
1442 'scrollbars' => true,
1443 'resizable' => true);
1445 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1446 $action = null;
1447 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1449 $str = '<span class="history">'.$str.'</span>';
1451 if ($return) {
1452 return $str;
1453 } else {
1454 echo $str;
1455 return true;
1461 * Search through course users
1463 * If $coursid specifies the site course then this function searches
1464 * through all undeleted and confirmed users
1465 * @param int $courseid The course in question.
1466 * @param string $searchtext the text to search for
1467 * @param string $sort the column name to order by
1468 * @param string $exceptions comma separated list of user IDs to exclude
1469 * @return array An array of {@link $USER} records.
1471 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1472 global $CFG, $USER, $DB;
1474 $fullname = $DB->sql_fullname();
1476 if (!empty($exceptions)) {
1477 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1478 } else {
1479 $except = '';
1482 if (!empty($sort)) {
1483 $order = ' ORDER BY '. $sort;
1484 } else {
1485 $order = '';
1488 $ufields = user_picture::fields('u');
1489 if (!$courseid or $courseid == SITEID) {
1490 $params = array($USER->id, "%$searchtext%");
1491 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1492 FROM {user} u
1493 LEFT JOIN {message_contacts} mc
1494 ON mc.contactid = u.id AND mc.userid = ?
1495 WHERE u.deleted = '0' AND u.confirmed = '1'
1496 AND (".$DB->sql_like($fullname, '?', false).")
1497 $except
1498 $order", $params);
1499 } else {
1500 //TODO: add enabled enrolment join here (skodak)
1501 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1502 $contextlists = get_related_contexts_string($context);
1504 // everyone who has a role assignment in this course or higher
1505 $params = array($USER->id, "%$searchtext%");
1506 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1507 FROM {user} u
1508 JOIN {role_assignments} ra ON ra.userid = u.id
1509 LEFT JOIN {message_contacts} mc
1510 ON mc.contactid = u.id AND mc.userid = ?
1511 WHERE u.deleted = '0' AND u.confirmed = '1'
1512 AND ra.contextid $contextlists
1513 AND (".$DB->sql_like($fullname, '?', false).")
1514 $except
1515 $order", $params);
1517 return $users;
1522 * search a user's messages
1524 * @param array $searchterms an array of search terms (strings)
1525 * @param bool $fromme include messages from the user?
1526 * @param bool $tome include messages to the user?
1527 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1528 * @param int $userid the user ID of the current user
1529 * @return mixed An array of messages or false if no matching messages were found
1531 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1532 /// Returns a list of posts found using an array of search terms
1533 /// eg word +word -word
1535 global $CFG, $USER, $DB;
1537 /// If no userid sent then assume current user
1538 if ($userid == 0) $userid = $USER->id;
1540 /// Some differences in SQL syntax
1541 if ($DB->sql_regex_supported()) {
1542 $REGEXP = $DB->sql_regex(true);
1543 $NOTREGEXP = $DB->sql_regex(false);
1546 $searchcond = array();
1547 $params = array();
1548 $i = 0;
1550 //preprocess search terms to check whether we have at least 1 eligible search term
1551 //if we do we can drop words around it like 'a'
1552 $dropshortwords = false;
1553 foreach ($searchterms as $searchterm) {
1554 if (strlen($searchterm) >= 2) {
1555 $dropshortwords = true;
1559 foreach ($searchterms as $searchterm) {
1560 $i++;
1562 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1564 if ($dropshortwords && strlen($searchterm) < 2) {
1565 continue;
1567 /// Under Oracle and MSSQL, trim the + and - operators and perform
1568 /// simpler LIKE search
1569 if (!$DB->sql_regex_supported()) {
1570 if (substr($searchterm, 0, 1) == '-') {
1571 $NOT = true;
1573 $searchterm = trim($searchterm, '+-');
1576 if (substr($searchterm,0,1) == "+") {
1577 $searchterm = substr($searchterm,1);
1578 $searchterm = preg_quote($searchterm, '|');
1579 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1580 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1582 } else if (substr($searchterm,0,1) == "-") {
1583 $searchterm = substr($searchterm,1);
1584 $searchterm = preg_quote($searchterm, '|');
1585 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1586 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1588 } else {
1589 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1590 $params['ss'.$i] = "%$searchterm%";
1594 if (empty($searchcond)) {
1595 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1596 $params['ss1'] = "%";
1597 } else {
1598 $searchcond = implode(" AND ", $searchcond);
1601 /// There are several possibilities
1602 /// 1. courseid = SITEID : The admin is searching messages by all users
1603 /// 2. courseid = ?? : A teacher is searching messages by users in
1604 /// one of their courses - currently disabled
1605 /// 3. courseid = none : User is searching their own messages;
1606 /// a. Messages from user
1607 /// b. Messages to user
1608 /// c. Messages to and from user
1610 if ($courseid == SITEID) { /// admin is searching all messages
1611 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1612 FROM {message_read} m
1613 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1614 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1615 FROM {message} m
1616 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1618 } else if ($courseid !== 'none') {
1619 /// This has not been implemented due to security concerns
1620 $m_read = array();
1621 $m_unread = array();
1623 } else {
1625 if ($fromme and $tome) {
1626 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1627 $params['userid1'] = $userid;
1628 $params['userid2'] = $userid;
1630 } else if ($fromme) {
1631 $searchcond .= " AND m.useridfrom=:userid";
1632 $params['userid'] = $userid;
1634 } else if ($tome) {
1635 $searchcond .= " AND m.useridto=:userid";
1636 $params['userid'] = $userid;
1639 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1640 FROM {message_read} m
1641 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1642 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1643 FROM {message} m
1644 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1648 /// The keys may be duplicated in $m_read and $m_unread so we can't
1649 /// do a simple concatenation
1650 $message = array();
1651 foreach ($m_read as $m) {
1652 $messages[] = $m;
1654 foreach ($m_unread as $m) {
1655 $messages[] = $m;
1658 return (empty($messages)) ? false : $messages;
1662 * Given a message object that we already know has a long message
1663 * this function truncates the message nicely to the first
1664 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1666 * @param string $message the message
1667 * @param int $minlength the minimum length to trim the message to
1668 * @return string the shortened message
1670 function message_shorten_message($message, $minlength = 0) {
1671 $i = 0;
1672 $tag = false;
1673 $length = strlen($message);
1674 $count = 0;
1675 $stopzone = false;
1676 $truncate = 0;
1677 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1680 for ($i=0; $i<$length; $i++) {
1681 $char = $message[$i];
1683 switch ($char) {
1684 case "<":
1685 $tag = true;
1686 break;
1687 case ">":
1688 $tag = false;
1689 break;
1690 default:
1691 if (!$tag) {
1692 if ($stopzone) {
1693 if ($char == '.' or $char == ' ') {
1694 $truncate = $i+1;
1695 break 2;
1698 $count++;
1700 break;
1702 if (!$stopzone) {
1703 if ($count > $minlength) {
1704 $stopzone = true;
1709 if (!$truncate) {
1710 $truncate = $i;
1713 return substr($message, 0, $truncate);
1718 * Given a string and an array of keywords, this function looks
1719 * for the first keyword in the string, and then chops out a
1720 * small section from the text that shows that word in context.
1722 * @param string $message the text to search
1723 * @param array $keywords array of keywords to find
1725 function message_get_fragment($message, $keywords) {
1727 $fullsize = 160;
1728 $halfsize = (int)($fullsize/2);
1730 $message = strip_tags($message);
1732 foreach ($keywords as $keyword) { // Just get the first one
1733 if ($keyword !== '') {
1734 break;
1737 if (empty($keyword)) { // None found, so just return start of message
1738 return message_shorten_message($message, 30);
1741 $leadin = $leadout = '';
1743 /// Find the start of the fragment
1744 $start = 0;
1745 $length = strlen($message);
1747 $pos = strpos($message, $keyword);
1748 if ($pos > $halfsize) {
1749 $start = $pos - $halfsize;
1750 $leadin = '...';
1752 /// Find the end of the fragment
1753 $end = $start + $fullsize;
1754 if ($end > $length) {
1755 $end = $length;
1756 } else {
1757 $leadout = '...';
1760 /// Pull out the fragment and format it
1762 $fragment = substr($message, $start, $end - $start);
1763 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1764 return $fragment;
1768 * Retrieve the messages between two users
1770 * @param object $user1 the current user
1771 * @param object $user2 the other user
1772 * @param int $limitnum the maximum number of messages to retrieve
1773 * @param bool $viewingnewmessages are we currently viewing new messages?
1775 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1776 global $DB, $CFG;
1778 $messages = array();
1780 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1781 //desc to get the last $limitnum messages then flip the order in php
1782 $sort = 'asc';
1783 if ($limitnum>0) {
1784 $sort = 'desc';
1787 $notificationswhere = null;
1788 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1789 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1790 $notificationswhere = 'AND notification=0';
1793 //prevent notifications of your own actions appearing in your own message history
1794 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1796 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1797 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1798 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1799 "timecreated $sort", '*', 0, $limitnum)) {
1800 foreach ($messages_read as $message) {
1801 $messages[$message->timecreated] = $message;
1804 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1805 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1806 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1807 "timecreated $sort", '*', 0, $limitnum)) {
1808 foreach ($messages_new as $message) {
1809 $messages[$message->timecreated] = $message;
1813 //if we only want the last $limitnum messages
1814 ksort($messages);
1815 $messagecount = count($messages);
1816 if ($limitnum>0 && $messagecount>$limitnum) {
1817 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1820 return $messages;
1824 * Print the message history between two users
1826 * @param object $user1 the current user
1827 * @param object $user2 the other user
1828 * @param string $search search terms to highlight
1829 * @param int $messagelimit maximum number of messages to return
1830 * @param string $messagehistorylink the html for the message history link or false
1831 * @param bool $viewingnewmessages are we currently viewing new messages?
1833 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1834 global $CFG, $OUTPUT;
1836 echo $OUTPUT->box_start('center');
1837 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1838 echo html_writer::start_tag('tr');
1840 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1841 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1842 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1843 echo html_writer::end_tag('td');
1845 echo html_writer::start_tag('td', array('align' => 'center'));
1846 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1847 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1848 echo html_writer::end_tag('td');
1850 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1851 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1852 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1854 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1855 $incontactlist = $user2->iscontact;
1856 $isblocked = $user2->isblocked;
1858 $script = null;
1859 $text = true;
1860 $icon = false;
1862 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1863 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1864 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1866 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1869 echo html_writer::end_tag('td');
1870 echo html_writer::end_tag('tr');
1871 echo html_writer::end_tag('table');
1872 echo $OUTPUT->box_end();
1874 if (!empty($messagehistorylink)) {
1875 echo $messagehistorylink;
1878 /// Get all the messages and print them
1879 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1880 $tablecontents = '';
1882 $current = new stdClass();
1883 $current->mday = '';
1884 $current->month = '';
1885 $current->year = '';
1886 $messagedate = get_string('strftimetime');
1887 $blockdate = get_string('strftimedaydate');
1888 foreach ($messages as $message) {
1889 if ($message->notification) {
1890 $notificationclass = ' notification';
1891 } else {
1892 $notificationclass = null;
1894 $date = usergetdate($message->timecreated);
1895 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1896 $current->mday = $date['mday'];
1897 $current->month = $date['month'];
1898 $current->year = $date['year'];
1900 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1901 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1903 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1906 $formatted_message = $side = null;
1907 if ($message->useridfrom == $user1->id) {
1908 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1909 $side = 'left';
1910 } else {
1911 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1912 $side = 'right';
1914 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1917 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1918 } else {
1919 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1924 * Format a message for display in the message history
1926 * @param object $message the message object
1927 * @param string $format optional date format
1928 * @param string $keywords keywords to highlight
1929 * @param string $class CSS class to apply to the div around the message
1930 * @return string the formatted message
1932 function message_format_message($message, $format='', $keywords='', $class='other') {
1934 static $dateformat;
1936 //if we haven't previously set the date format or they've supplied a new one
1937 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1938 if ($format) {
1939 $dateformat = $format;
1940 } else {
1941 $dateformat = get_string('strftimedatetimeshort');
1944 $time = userdate($message->timecreated, $dateformat);
1945 $options = new stdClass();
1946 $options->para = false;
1948 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1949 if (!empty($message->smallmessage)) {
1950 $messagetext = $message->smallmessage;
1951 } else {
1952 $messagetext = $message->fullmessage;
1954 if ($message->fullmessageformat == FORMAT_HTML) {
1955 //dont escape html tags by calling s() if html format or they will display in the UI
1956 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1957 } else {
1958 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1961 $messagetext .= message_format_contexturl($message);
1963 if ($keywords) {
1964 $messagetext = highlight($keywords, $messagetext);
1967 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1971 * Format a the context url and context url name of a message for display
1973 * @param object $message the message object
1974 * @return string the formatted string
1976 function message_format_contexturl($message) {
1977 $s = null;
1979 if (!empty($message->contexturl)) {
1980 $displaytext = null;
1981 if (!empty($message->contexturlname)) {
1982 $displaytext= $message->contexturlname;
1983 } else {
1984 $displaytext= $message->contexturl;
1986 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1987 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1988 $s .= html_writer::end_tag('div');
1991 return $s;
1995 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1997 * @param object $userfrom the message sender
1998 * @param object $userto the message recipient
1999 * @param string $message the message
2000 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2001 * @return int|false the ID of the new message or false
2003 function message_post_message($userfrom, $userto, $message, $format) {
2004 global $SITE, $CFG, $USER;
2006 $eventdata = new stdClass();
2007 $eventdata->component = 'moodle';
2008 $eventdata->name = 'instantmessage';
2009 $eventdata->userfrom = $userfrom;
2010 $eventdata->userto = $userto;
2012 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2013 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2015 if ($format == FORMAT_HTML) {
2016 $eventdata->fullmessage = '';
2017 $eventdata->fullmessagehtml = $message;
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'));