MDL-28186 messaging: Fix "Enable messagning setting" infuence on the menus
[moodle.git] / message / lib.php
blob9de50e00417c5e25adc92419da5fc52d326e95e1
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library functions for messaging
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package message
26 require_once($CFG->libdir.'/eventslib.php');
28 define ('MESSAGE_SHORTLENGTH', 300);
30 //$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
31 if (isset($PAGE)) {
32 $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
35 define ('MESSAGE_DISCUSSION_WIDTH',600);
36 define ('MESSAGE_DISCUSSION_HEIGHT',500);
38 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
40 define('MESSAGE_HISTORY_SHORT',0);
41 define('MESSAGE_HISTORY_ALL',1);
43 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
44 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
45 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
46 define('MESSAGE_VIEW_CONTACTS','contacts');
47 define('MESSAGE_VIEW_BLOCKED','blockedusers');
48 define('MESSAGE_VIEW_COURSE','course_');
49 define('MESSAGE_VIEW_SEARCH','search');
51 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
53 define('MESSAGE_CONTACTS_PER_PAGE',10);
54 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
56 /**
57 * Define contants for messaging default settings population. For unambiguity of
58 * plugin developer intentions we use 4-bit value (LSB numbering):
59 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
60 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
61 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
63 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
66 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
67 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
69 define('MESSAGE_DISALLOWED', 0x04); // 0100
70 define('MESSAGE_PERMITTED', 0x08); // 1000
71 define('MESSAGE_FORCED', 0x0c); // 1100
73 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
75 /**
76 * Set default value for default outputs permitted setting
78 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
80 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
81 $CFG->message_contacts_refresh = 60;
83 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
84 $CFG->message_chat_refresh = 5;
86 if (!isset($CFG->message_offline_time)) {
87 $CFG->message_offline_time = 300;
90 /**
91 * Print the selector that allows the user to view their contacts, course participants, their recent
92 * conversations etc
94 * @param int $countunreadtotal how many unread messages does the user have?
95 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
96 * @param object $user1 the user whose messages are being viewed
97 * @param object $user2 the user $user1 is talking to
98 * @param array $blockedusers an array of users blocked by $user1
99 * @param array $onlinecontacts an array of $user1's online contacts
100 * @param array $offlinecontacts an array of $user1's offline contacts
101 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
102 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
103 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
104 * @return void
106 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
107 global $PAGE;
109 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
111 //if 0 unread messages and they've requested unread messages then show contacts
112 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
113 $viewing = MESSAGE_VIEW_CONTACTS;
116 //if they have no blocked users and they've requested blocked users switch them over to contacts
117 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
118 $viewing = MESSAGE_VIEW_CONTACTS;
121 $onlyactivecourses = true;
122 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
123 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
125 $strunreadmessages = null;
126 if ($countunreadtotal>0) { //if there are unread messages
127 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
130 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
132 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
133 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
134 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
135 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
136 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
137 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
138 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
139 $courseidtoshow = intval(substr($viewing, 7));
141 if (!empty($courseidtoshow)
142 && array_key_exists($courseidtoshow, $coursecontexts)
143 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
145 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
146 } else {
147 //shouldn't get here. User trying to access a course they're not in perhaps.
148 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
152 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
153 echo html_writer::start_tag('fieldset');
154 $managebuttonclass = 'visible';
155 if ($viewing == MESSAGE_VIEW_SEARCH) {
156 $managebuttonclass = 'hiddenelement';
158 $strmanagecontacts = get_string('search','message');
159 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
160 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
161 echo html_writer::end_tag('fieldset');
162 echo html_writer::end_tag('form');
164 echo html_writer::end_tag('div');
168 * Print course participants. Called by message_print_contact_selector()
170 * @param object $context the course context
171 * @param int $courseid the course ID
172 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
173 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
174 * @param string $titletodisplay Optionally specify a title to display above the participants
175 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
176 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
177 * @return void
179 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
180 global $DB, $USER, $PAGE, $OUTPUT;
182 if (empty($titletodisplay)) {
183 $titletodisplay = get_string('participants');
186 $countparticipants = count_enrolled_users($context);
187 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
189 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
190 echo $OUTPUT->render($pagingbar);
192 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
194 echo html_writer::start_tag('tr');
195 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
196 echo html_writer::end_tag('tr');
198 //todo these need to come from somewhere if the course participants list is to show users with unread messages
199 $iscontact = true;
200 $isblocked = false;
201 foreach ($participants as $participant) {
202 if ($participant->id != $USER->id) {
203 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
204 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
208 echo html_writer::end_tag('table');
212 * Retrieve users blocked by $user1
214 * @param object $user1 the user whose messages are being viewed
215 * @param object $user2 the user $user1 is talking to. If they are being blocked
216 * they will have a variable called 'isblocked' added to their user object
217 * @return array the users blocked by $user1
219 function message_get_blocked_users($user1=null, $user2=null) {
220 global $DB, $USER;
222 if (empty($user1)) {
223 $user1 = $USER;
226 if (!empty($user2)) {
227 $user2->isblocked = false;
230 $blockedusers = array();
232 $userfields = user_picture::fields('u', array('lastaccess'));
233 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
234 FROM {message_contacts} mc
235 JOIN {user} u ON u.id = mc.contactid
236 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
237 WHERE mc.userid = :user1id2 AND mc.blocked = 1
238 GROUP BY $userfields
239 ORDER BY u.firstname ASC";
240 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
242 foreach($rs as $rd) {
243 $blockedusers[] = $rd;
245 if (!empty($user2) && $user2->id == $rd->id) {
246 $user2->isblocked = true;
249 $rs->close();
251 return $blockedusers;
255 * Print users blocked by $user1. Called by message_print_contact_selector()
257 * @param array $blockedusers the users blocked by $user1
258 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
259 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
260 * @param string $titletodisplay Optionally specify a title to display above the participants
261 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
262 * @return void
264 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
265 global $DB, $USER;
267 $countblocked = count($blockedusers);
269 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
271 if (!empty($titletodisplay)) {
272 echo html_writer::start_tag('tr');
273 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
274 echo html_writer::end_tag('tr');
277 if ($countblocked) {
278 echo html_writer::start_tag('tr');
279 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
280 echo html_writer::end_tag('tr');
282 $isuserblocked = true;
283 $isusercontact = false;
284 foreach ($blockedusers as $blockeduser) {
285 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
289 echo html_writer::end_tag('table');
293 * Retrieve $user1's contacts (online, offline and strangers)
295 * @param object $user1 the user whose messages are being viewed
296 * @param object $user2 the user $user1 is talking to. If they are a contact
297 * they will have a variable called 'iscontact' added to their user object
298 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
300 function message_get_contacts($user1=null, $user2=null) {
301 global $DB, $CFG, $USER;
303 if (empty($user1)) {
304 $user1 = $USER;
307 if (!empty($user2)) {
308 $user2->iscontact = false;
311 $timetoshowusers = 300; //Seconds default
312 if (isset($CFG->block_online_users_timetosee)) {
313 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
316 // time which a user is counting as being active since
317 $timefrom = time()-$timetoshowusers;
319 // people in our contactlist who are online
320 $onlinecontacts = array();
321 // people in our contactlist who are offline
322 $offlinecontacts = array();
323 // people who are not in our contactlist but have sent us a message
324 $strangers = array();
326 $userfields = user_picture::fields('u', array('lastaccess'));
328 // get all in our contactlist who are not blocked in our contact list
329 // and count messages we have waiting from each of them
330 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
331 FROM {message_contacts} mc
332 JOIN {user} u ON u.id = mc.contactid
333 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
334 WHERE mc.userid = ? AND mc.blocked = 0
335 GROUP BY $userfields
336 ORDER BY u.firstname ASC";
338 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
339 foreach ($rs as $rd) {
340 if ($rd->lastaccess >= $timefrom) {
341 // they have been active recently, so are counted online
342 $onlinecontacts[] = $rd;
344 } else {
345 $offlinecontacts[] = $rd;
348 if (!empty($user2) && $user2->id == $rd->id) {
349 $user2->iscontact = true;
352 $rs->close();
354 // get messages from anyone who isn't in our contact list and count the number
355 // of messages we have from each of them
356 $strangersql = "SELECT $userfields, count(m.id) as messagecount
357 FROM {message} m
358 JOIN {user} u ON u.id = m.useridfrom
359 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
360 WHERE mc.id IS NULL AND m.useridto = ?
361 GROUP BY $userfields
362 ORDER BY u.firstname ASC";
364 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
365 foreach ($rs as $rd) {
366 $strangers[] = $rd;
368 $rs->close();
370 return array($onlinecontacts, $offlinecontacts, $strangers);
374 * Print $user1's contacts. Called by message_print_contact_selector()
376 * @param array $onlinecontacts $user1's contacts which are online
377 * @param array $offlinecontacts $user1's contacts which are offline
378 * @param array $strangers users which are not contacts but who have messaged $user1
379 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
380 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
381 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
382 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
383 * @param string $titletodisplay Optionally specify a title to display above the participants
384 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
385 * @return void
387 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
388 global $CFG, $PAGE, $OUTPUT;
390 $countonlinecontacts = count($onlinecontacts);
391 $countofflinecontacts = count($offlinecontacts);
392 $countstrangers = count($strangers);
393 $isuserblocked = null;
395 if ($countonlinecontacts + $countofflinecontacts == 0) {
396 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
399 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
401 if (!empty($titletodisplay)) {
402 message_print_heading($titletodisplay);
405 if($countonlinecontacts) {
406 /// print out list of online contacts
408 if (empty($titletodisplay)) {
409 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
412 $isuserblocked = false;
413 $isusercontact = true;
414 foreach ($onlinecontacts as $contact) {
415 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
416 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
421 if ($countofflinecontacts) {
422 /// print out list of offline contacts
424 if (empty($titletodisplay)) {
425 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
428 $isuserblocked = false;
429 $isusercontact = true;
430 foreach ($offlinecontacts as $contact) {
431 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
432 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
438 /// print out list of incoming contacts
439 if ($countstrangers) {
440 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
442 $isuserblocked = false;
443 $isusercontact = false;
444 foreach ($strangers as $stranger) {
445 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
446 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
451 echo html_writer::end_tag('table');
453 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
454 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
459 * Print a select box allowing the user to choose to view new messages, course participants etc.
461 * Called by message_print_contact_selector()
462 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
463 * @param array $courses array of course objects. The courses the user is enrolled in.
464 * @param array $coursecontexts array of course contexts. Keyed on course id.
465 * @param int $countunreadtotal how many unread messages does the user have?
466 * @param int $countblocked how many users has the current user blocked?
467 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
468 * @return void
470 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
471 $options = array();
472 $textlib = textlib_get_instance(); // going to use textlib services
474 if ($countunreadtotal>0) { //if there are unread messages
475 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
478 $str = get_string('mycontacts', 'message');
479 $options[MESSAGE_VIEW_CONTACTS] = $str;
481 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
482 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
484 if (!empty($courses)) {
485 $courses_options = array();
487 foreach($courses as $course) {
488 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
489 //Not using short_text() as we want the end of the course name. Not the beginning.
490 if ($textlib->strlen($course->shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
491 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.$textlib->substr($course->shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
492 } else {
493 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $course->shortname;
498 if (!empty($courses_options)) {
499 $options[] = array(get_string('courses') => $courses_options);
503 if ($countblocked>0) {
504 $str = get_string('blockedusers','message', $countblocked);
505 $options[MESSAGE_VIEW_BLOCKED] = $str;
508 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
509 echo html_writer::start_tag('fieldset');
510 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
511 echo html_writer::end_tag('fieldset');
512 echo html_writer::end_tag('form');
516 * Load the course contexts for all of the users courses
518 * @param array $courses array of course objects. The courses the user is enrolled in.
519 * @return array of course contexts
521 function message_get_course_contexts($courses) {
522 $coursecontexts = array();
524 foreach($courses as $course) {
525 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
528 return $coursecontexts;
532 * strip off action parameters like 'removecontact'
534 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
535 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
537 function message_remove_url_params($moodleurl) {
538 $newurl = new moodle_url($moodleurl);
539 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
540 return $newurl->out();
544 * Count the number of messages with a field having a specified value.
545 * if $field is empty then return count of the whole array
546 * if $field is non-existent then return 0
548 * @param array $messagearray array of message objects
549 * @param string $field the field to inspect on the message objects
550 * @param string $value the value to test the field against
552 function message_count_messages($messagearray, $field='', $value='') {
553 if (!is_array($messagearray)) return 0;
554 if ($field == '' or empty($messagearray)) return count($messagearray);
556 $count = 0;
557 foreach ($messagearray as $message) {
558 $count += ($message->$field == $value) ? 1 : 0;
560 return $count;
564 * Returns the count of unread messages for user. Either from a specific user or from all users.
566 * @param object $user1 the first user. Defaults to $USER
567 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
568 * @return int the count of $user1's unread messages
570 function message_count_unread_messages($user1=null, $user2=null) {
571 global $USER, $DB;
573 if (empty($user1)) {
574 $user1 = $USER;
577 if (!empty($user2)) {
578 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
579 array($user1->id, $user2->id), "COUNT('id')");
580 } else {
581 return $DB->count_records_select('message', "useridto = ?",
582 array($user1->id), "COUNT('id')");
587 * Count the number of users blocked by $user1
589 * @param object $user1 user object
590 * @return int the number of blocked users
592 function message_count_blocked_users($user1=null) {
593 global $USER, $DB;
595 if (empty($user1)) {
596 $user1 = $USER;
599 $sql = "SELECT count(mc.id)
600 FROM {message_contacts} mc
601 WHERE mc.userid = :userid AND mc.blocked = 1";
602 $params = array('userid' => $user1->id);
604 return $DB->count_records_sql($sql, $params);
608 * Print the search form and search results if a search has been performed
610 * @param boolean $advancedsearch show basic or advanced search form
611 * @param object $user1 the current user
612 * @return boolean true if a search was performed
614 function message_print_search($advancedsearch = false, $user1=null) {
615 $frm = data_submitted();
617 $doingsearch = false;
618 if ($frm) {
619 if (confirm_sesskey()) {
620 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
621 } else {
622 $frm = false;
626 if (!empty($frm->combinedsearch)) {
627 $combinedsearchstring = $frm->combinedsearch;
628 } else {
629 //$combinedsearchstring = get_string('searchcombined','message').'...';
630 $combinedsearchstring = '';
633 if ($doingsearch) {
634 if ($advancedsearch) {
636 $messagesearch = '';
637 if (!empty($frm->keywords)) {
638 $messagesearch = $frm->keywords;
640 $personsearch = '';
641 if (!empty($frm->name)) {
642 $personsearch = $frm->name;
644 include('search_advanced.html');
645 } else {
646 include('search.html');
649 $showicontext = false;
650 message_print_search_results($frm, $showicontext, $user1);
652 return true;
653 } else {
655 if ($advancedsearch) {
656 $personsearch = $messagesearch = '';
657 include('search_advanced.html');
658 } else {
659 include('search.html');
661 return false;
666 * Get the users recent conversations meaning all the people they've recently
667 * sent or received a message from plus the most recent message sent to or received from each other user
669 * @param object $user the current user
670 * @param int $limitfrom can be used for paging
671 * @param int $limitto can be used for paging
672 * @return array
674 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
675 global $DB;
677 $userfields = user_picture::fields('u', array('lastaccess'));
678 //This query retrieves the last message received from and sent to each user
679 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
680 //It then joins with some other tables to get some additional data we need
682 //message ID is used instead of timecreated as it should sort the same and will be much faster
684 //There is a separate query for read and unread queries as they are stored in different tables
685 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
686 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
687 FROM {message_read} mr
688 JOIN (
689 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
690 FROM (
691 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
692 FROM {message_read} mr1
693 WHERE mr1.useridfrom = :userid1
694 AND mr1.notification = 0
695 GROUP BY mr1.useridto
696 UNION
697 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
698 FROM {message_read} mr2
699 WHERE mr2.useridto = :userid2
700 AND mr2.notification = 0
701 GROUP BY mr2.useridfrom
702 ) messages
703 GROUP BY messages.userid
704 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
705 JOIN {user} u ON u.id = messages2.userid
706 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
707 WHERE u.deleted = '0'
708 ORDER BY mr.id DESC";
709 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
710 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
712 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
713 FROM {message} m
714 JOIN (
715 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
716 FROM (
717 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
718 FROM {message} m1
719 WHERE m1.useridfrom = :userid1
720 AND m1.notification = 0
721 GROUP BY m1.useridto
722 UNION
723 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
724 FROM {message} m2
725 WHERE m2.useridto = :userid2
726 AND m2.notification = 0
727 GROUP BY m2.useridfrom
728 ) messages
729 GROUP BY messages.userid
730 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
731 JOIN {user} u ON u.id = messages2.userid
732 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
733 WHERE u.deleted = '0'
734 ORDER BY m.id DESC";
735 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
737 $conversations = array();
739 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
740 //$conversation->id (the array key) is the other user's ID
741 $conversation_arrays = array($unread, $read);
742 foreach ($conversation_arrays as $conversation_array) {
743 foreach ($conversation_array as $conversation) {
744 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
745 $conversations[$conversation->id] = $conversation;
750 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
751 //and there may be multiple conversations with the same timecreated value.
752 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
753 usort($conversations, "conversationsort");
755 return $conversations;
759 * Sort function used to order conversations
761 * @param object $a A conversation object
762 * @param object $b A conversation object
763 * @return integer
765 function conversationsort($a, $b)
767 if ($a->timecreated == $b->timecreated) {
768 return 0;
770 return ($a->timecreated > $b->timecreated) ? -1 : 1;
774 * Get the users recent event notifications
776 * @param object $user the current user
777 * @param int $limitfrom can be used for paging
778 * @param int $limitto can be used for paging
779 * @return array
781 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
782 global $DB;
784 $userfields = user_picture::fields('u', array('lastaccess'));
785 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
786 FROM {message_read} mr
787 JOIN {user} u ON u.id=mr.useridfrom
788 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
789 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
790 $params = array('userid1' => $user->id, 'notification' => 1);
792 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
793 return $notifications;
797 * Print the user's recent conversations
799 * @param object $user1 the current user
800 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
801 * @return void
803 function message_print_recent_conversations($user=null, $showicontext=false) {
804 global $USER;
806 echo html_writer::start_tag('p', array('class' => 'heading'));
807 echo get_string('mostrecentconversations', 'message');
808 echo html_writer::end_tag('p');
810 if (empty($user)) {
811 $user = $USER;
814 $conversations = message_get_recent_conversations($user);
816 $showotheruser = true;
817 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
821 * Print the user's recent notifications
823 * @param object $user1 the current user
824 * @return void
826 function message_print_recent_notifications($user=null) {
827 global $USER;
829 echo html_writer::start_tag('p', array('class' => 'heading'));
830 echo get_string('mostrecentnotifications', 'message');
831 echo html_writer::end_tag('p');
833 if (empty($user)) {
834 $user = $USER;
837 $notifications = message_get_recent_notifications($user);
839 $showicontext = false;
840 $showotheruser = false;
841 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
845 * Print a list of recent messages
847 * @staticvar type $dateformat
848 * @param array $messages the messages to display
849 * @param object $user the current user
850 * @param bool $showotheruser display information on the other user?
851 * @param bool $showicontext show text next to the action icons?
852 * @return void
854 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
855 global $OUTPUT;
856 static $dateformat;
858 if (empty($dateformat)) {
859 $dateformat = get_string('strftimedatetimeshort');
862 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
863 foreach ($messages as $message) {
864 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
866 if ($showotheruser) {
867 if ( $message->contactlistid ) {
868 if ($message->blocked == 0) { /// not blocked
869 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
870 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
871 } else { // blocked
872 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
873 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
875 } else {
876 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
877 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
880 //should we show just the icon or icon and text?
881 $histicontext = 'icon';
882 if ($showicontext) {
883 $histicontext = 'both';
885 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
887 echo html_writer::start_tag('span', array('class' => 'otheruser'));
889 echo html_writer::start_tag('span', array('class' => 'pix'));
890 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
891 echo html_writer::end_tag('span');
893 echo html_writer::start_tag('span', array('class' => 'contact'));
895 $link = new moodle_url("/message/index.php?id=$message->id");
896 $action = null;
897 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
899 echo html_writer::end_tag('span');//end contact
901 echo $strcontact.$strblock.$strhistory;
902 echo html_writer::end_tag('span');//end otheruser
904 $messagetoprint = null;
905 if (!empty($message->smallmessage)) {
906 $messagetoprint = $message->smallmessage;
907 } else {
908 $messagetoprint = $message->fullmessage;
911 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
912 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
913 echo message_format_contexturl($message);
914 echo html_writer::end_tag('div');//end singlemessage
916 echo html_writer::end_tag('div');//end messagerecent
920 * Add the selected user as a contact for the current user
922 * @param int $contactid the ID of the user to add as a contact
923 * @param int $blocked 1 if you wish to block the contact
924 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
925 * Otherwise returns the result of update_record() or insert_record()
927 function message_add_contact($contactid, $blocked=0) {
928 global $USER, $DB;
930 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
931 return false;
934 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
935 /// record already exists - we may be changing blocking status
937 if ($contact->blocked !== $blocked) {
938 /// change to blocking status
939 $contact->blocked = $blocked;
940 return $DB->update_record('message_contacts', $contact);
941 } else {
942 /// no changes to blocking status
943 return true;
946 } else {
947 /// new contact record
948 unset($contact);
949 $contact->userid = $USER->id;
950 $contact->contactid = $contactid;
951 $contact->blocked = $blocked;
952 return $DB->insert_record('message_contacts', $contact, false);
957 * remove a contact
959 * @param type $contactid the user ID of the contact to remove
960 * @return bool returns the result of delete_records()
962 function message_remove_contact($contactid) {
963 global $USER, $DB;
964 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
968 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
970 * @param int $contactid the user ID of the contact to unblock
971 * @return bool returns the result of delete_records()
973 function message_unblock_contact($contactid) {
974 global $USER, $DB;
975 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
979 * block a user
981 * @param int $contactid the user ID of the user to block
983 function message_block_contact($contactid) {
984 return message_add_contact($contactid, 1);
988 * Load a user's contact record
990 * @param int $contactid the user ID of the user whose contact record you want
991 * @return array message contacts
993 function message_get_contact($contactid) {
994 global $USER, $DB;
995 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
999 * Print the results of a message search
1001 * @param mixed $frm submitted form data
1002 * @param bool $showicontext show text next to action icons?
1003 * @param object $user1 the current user
1004 * @return void
1006 function message_print_search_results($frm, $showicontext=false, $user1=null) {
1007 global $USER, $DB, $OUTPUT;
1009 if (empty($user1)) {
1010 $user1 = $USER;
1013 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1015 $personsearch = false;
1016 $personsearchstring = null;
1017 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1018 $personsearch = true;
1019 $personsearchstring = $frm->name;
1020 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1021 $personsearch = true;
1022 $personsearchstring = $frm->combinedsearch;
1025 /// search for person
1026 if ($personsearch) {
1027 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1028 $users = array();
1029 $mycourses = enrol_get_my_courses();
1030 foreach ($mycourses as $mycourse) {
1031 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1032 foreach ($susers as $suser) $users[$suser->id] = $suser;
1035 } else {
1036 $users = message_search_users(SITEID, $personsearchstring);
1039 if (!empty($users)) {
1040 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1041 echo get_string('userssearchresults', 'message', count($users));
1042 echo html_writer::end_tag('p');
1044 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1045 foreach ($users as $user) {
1047 if ( $user->contactlistid ) {
1048 if ($user->blocked == 0) { /// not blocked
1049 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1050 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1051 } else { // blocked
1052 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1053 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1055 } else {
1056 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1057 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1060 //should we show just the icon or icon and text?
1061 $histicontext = 'icon';
1062 if ($showicontext) {
1063 $histicontext = 'both';
1065 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1067 echo html_writer::start_tag('tr');
1069 echo html_writer::start_tag('td', array('class' => 'pix'));
1070 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1071 echo html_writer::end_tag('td');
1073 echo html_writer::start_tag('td',array('class' => 'contact'));
1074 $action = null;
1075 $link = new moodle_url("/message/index.php?id=$user->id");
1076 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1077 echo html_writer::end_tag('td');
1079 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1080 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1081 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1083 echo html_writer::end_tag('tr');
1085 echo html_writer::end_tag('table');
1087 } else {
1088 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1089 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1090 echo html_writer::end_tag('p');
1094 // search messages for keywords
1095 $messagesearch = false;
1096 $messagesearchstring = null;
1097 if (!empty($frm->keywords)) {
1098 $messagesearch = true;
1099 $messagesearchstring = clean_text(trim($frm->keywords));
1100 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1101 $messagesearch = true;
1102 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1105 if ($messagesearch) {
1106 if ($messagesearchstring) {
1107 $keywords = explode(' ', $messagesearchstring);
1108 } else {
1109 $keywords = array();
1111 $tome = false;
1112 $fromme = false;
1113 $courseid = 'none';
1115 if (empty($frm->keywordsoption)) {
1116 $frm->keywordsoption = 'allmine';
1119 switch ($frm->keywordsoption) {
1120 case 'tome':
1121 $tome = true;
1122 break;
1123 case 'fromme':
1124 $fromme = true;
1125 break;
1126 case 'allmine':
1127 $tome = true;
1128 $fromme = true;
1129 break;
1130 case 'allusers':
1131 $courseid = SITEID;
1132 break;
1133 case 'courseusers':
1134 $courseid = $frm->courseid;
1135 break;
1136 default:
1137 $tome = true;
1138 $fromme = true;
1141 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1143 /// get a list of contacts
1144 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1145 $contacts = array();
1148 /// print heading with number of results
1149 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1150 $countresults = count($messages);
1151 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1152 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1153 } else {
1154 echo get_string('keywordssearchresults', 'message', $countresults);
1156 echo html_writer::end_tag('p');
1158 /// print table headings
1159 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1161 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1162 $headertdend = html_writer::end_tag('td');
1163 echo html_writer::start_tag('tr');
1164 echo $headertdstart.get_string('from').$headertdend;
1165 echo $headertdstart.get_string('to').$headertdend;
1166 echo $headertdstart.get_string('message', 'message').$headertdend;
1167 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1168 echo html_writer::end_tag('tr');
1170 $blockedcount = 0;
1171 $dateformat = get_string('strftimedatetimeshort');
1172 $strcontext = get_string('context', 'message');
1173 foreach ($messages as $message) {
1175 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1176 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1177 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1178 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1181 $blockedcount ++;
1182 continue;
1185 /// load up user to record
1186 if ($message->useridto !== $USER->id) {
1187 $userto = $DB->get_record('user', array('id' => $message->useridto));
1188 $tocontact = (array_key_exists($message->useridto, $contacts) and
1189 ($contacts[$message->useridto]->blocked == 0) );
1190 $toblocked = (array_key_exists($message->useridto, $contacts) and
1191 ($contacts[$message->useridto]->blocked == 1) );
1192 } else {
1193 $userto = false;
1194 $tocontact = false;
1195 $toblocked = false;
1198 /// load up user from record
1199 if ($message->useridfrom !== $USER->id) {
1200 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1201 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1202 ($contacts[$message->useridfrom]->blocked == 0) );
1203 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1204 ($contacts[$message->useridfrom]->blocked == 1) );
1205 } else {
1206 $userfrom = false;
1207 $fromcontact = false;
1208 $fromblocked = false;
1211 /// find date string for this message
1212 $date = usergetdate($message->timecreated);
1213 $datestring = $date['year'].$date['mon'].$date['mday'];
1215 /// print out message row
1216 echo html_writer::start_tag('tr', array('valign' => 'top'));
1218 echo html_writer::start_tag('td', array('class' => 'contact'));
1219 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1220 echo html_writer::end_tag('td');
1222 echo html_writer::start_tag('td', array('class' => 'contact'));
1223 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1224 echo html_writer::end_tag('td');
1226 echo html_writer::start_tag('td', array('class' => 'summary'));
1227 echo message_get_fragment($message->fullmessage, $keywords);
1228 echo html_writer::start_tag('div', array('class' => 'link'));
1230 //find the user involved that isn't the current user
1231 $user2id = null;
1232 if ($user1->id == $message->useridto) {
1233 $user2id = $message->useridfrom;
1234 } else {
1235 $user2id = $message->useridto;
1237 message_history_link($user1->id, $user2id, false,
1238 $messagesearchstring, 'm'.$message->id, $strcontext);
1239 echo html_writer::end_tag('div');
1240 echo html_writer::end_tag('td');
1242 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1244 echo html_writer::end_tag('tr');
1248 if ($blockedcount > 0) {
1249 echo html_writer::start_tag('tr');
1250 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1251 echo html_writer::end_tag('tr');
1253 echo html_writer::end_tag('table');
1255 } else {
1256 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1260 if (!$personsearch && !$messagesearch) {
1261 //they didn't enter any search terms
1262 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1265 echo html_writer::end_tag('div');
1269 * Print information on a user. Used when printing search results.
1271 * @param object/bool $user the user to display or false if you just want $USER
1272 * @param bool $iscontact is the user being displayed a contact?
1273 * @param bool $isblocked is the user being displayed blocked?
1274 * @param bool $includeicontext include text next to the action icons?
1275 * @return void
1277 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1278 global $USER, $OUTPUT;
1280 if ($user === false) {
1281 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1282 } else {
1283 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1284 echo '&nbsp;';
1286 $return = false;
1287 $script = null;
1288 if ($iscontact) {
1289 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1290 } else {
1291 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1293 echo '&nbsp;';
1294 if ($isblocked) {
1295 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1296 } else {
1297 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1300 $popupoptions = array(
1301 'height' => MESSAGE_DISCUSSION_HEIGHT,
1302 'width' => MESSAGE_DISCUSSION_WIDTH,
1303 'menubar' => false,
1304 'location' => false,
1305 'status' => true,
1306 'scrollbars' => true,
1307 'resizable' => true);
1309 $link = new moodle_url("/message/index.php?id=$user->id");
1310 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1311 $action = null;
1312 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1318 * Print a message contact link
1320 * @staticvar type $str
1321 * @param int $userid the ID of the user to apply to action to
1322 * @param string $linktype can be add, remove, block or unblock
1323 * @param bool $return if true return the link as a string. If false echo the link.
1324 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1325 * @param bool $text include text next to the icons?
1326 * @param bool $icon include a graphical icon?
1327 * @return string if $return is true otherwise bool
1329 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1330 global $OUTPUT, $PAGE;
1332 //hold onto the strings as we're probably creating a bunch of links
1333 static $str;
1335 if (empty($script)) {
1336 //strip off previous action params like 'removecontact'
1337 $script = message_remove_url_params($PAGE->url);
1340 if (empty($str->blockcontact)) {
1341 $str->blockcontact = get_string('blockcontact', 'message');
1342 $str->unblockcontact = get_string('unblockcontact', 'message');
1343 $str->removecontact = get_string('removecontact', 'message');
1344 $str->addcontact = get_string('addcontact', 'message');
1347 $command = $linktype.'contact';
1348 $string = $str->{$command};
1350 $safealttext = s($string);
1352 $safestring = '';
1353 if (!empty($text)) {
1354 $safestring = $safealttext;
1357 $img = '';
1358 if ($icon) {
1359 $iconpath = null;
1360 switch ($linktype) {
1361 case 'block':
1362 $iconpath = 't/block';
1363 break;
1364 case 'unblock':
1365 $iconpath = 't/userblue';
1366 break;
1367 case 'remove':
1368 $iconpath = 'i/cross_red_big';
1369 break;
1370 case 'add':
1371 default:
1372 $iconpath = 't/addgreen';
1375 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1378 $output = '<span class="'.$linktype.'contact">'.
1379 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1380 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1381 $img.
1382 $safestring.'</a></span>';
1384 if ($return) {
1385 return $output;
1386 } else {
1387 echo $output;
1388 return true;
1393 * echo or return a link to take the user to the full message history between themselves and another user
1395 * @staticvar type $strmessagehistory
1396 * @param int $userid1 the ID of the current user
1397 * @param int $userid2 the ID of the other user
1398 * @param bool $return true to return the link as a string. False to echo the link.
1399 * @param string $keywords any keywords to highlight in the message history
1400 * @param string $position anchor name to jump to within the message history
1401 * @param string $linktext optionally specify the link text
1402 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1404 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1405 global $OUTPUT;
1407 static $strmessagehistory;
1409 if (empty($strmessagehistory)) {
1410 $strmessagehistory = get_string('messagehistory', 'message');
1413 if ($position) {
1414 $position = "#$position";
1416 if ($keywords) {
1417 $keywords = "&search=".urlencode($keywords);
1420 if ($linktext == 'icon') { // Icon only
1421 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1422 } else if ($linktext == 'both') { // Icon and standard name
1423 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1424 $fulllink .= '&nbsp;'.$strmessagehistory;
1425 } else if ($linktext) { // Custom name
1426 $fulllink = $linktext;
1427 } else { // Standard name only
1428 $fulllink = $strmessagehistory;
1431 $popupoptions = array(
1432 'height' => 500,
1433 'width' => 500,
1434 'menubar' => false,
1435 'location' => false,
1436 'status' => true,
1437 'scrollbars' => true,
1438 'resizable' => true);
1440 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
1441 $action = null;
1442 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1444 $str = '<span class="history">'.$str.'</span>';
1446 if ($return) {
1447 return $str;
1448 } else {
1449 echo $str;
1450 return true;
1456 * Search through course users
1458 * If $coursid specifies the site course then this function searches
1459 * through all undeleted and confirmed users
1460 * @param int $courseid The course in question.
1461 * @param string $searchtext the text to search for
1462 * @param string $sort the column name to order by
1463 * @param string $exceptions comma separated list of user IDs to exclude
1464 * @return array An array of {@link $USER} records.
1466 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1467 global $CFG, $USER, $DB;
1469 $fullname = $DB->sql_fullname();
1471 if (!empty($exceptions)) {
1472 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1473 } else {
1474 $except = '';
1477 if (!empty($sort)) {
1478 $order = ' ORDER BY '. $sort;
1479 } else {
1480 $order = '';
1483 $ufields = user_picture::fields('u');
1484 if (!$courseid or $courseid == SITEID) {
1485 $params = array($USER->id, "%$searchtext%");
1486 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1487 FROM {user} u
1488 LEFT JOIN {message_contacts} mc
1489 ON mc.contactid = u.id AND mc.userid = ?
1490 WHERE u.deleted = '0' AND u.confirmed = '1'
1491 AND (".$DB->sql_like($fullname, '?', false).")
1492 $except
1493 $order", $params);
1494 } else {
1495 //TODO: add enabled enrolment join here (skodak)
1496 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1497 $contextlists = get_related_contexts_string($context);
1499 // everyone who has a role assignment in this course or higher
1500 $params = array($USER->id, "%$searchtext%");
1501 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1502 FROM {user} u
1503 JOIN {role_assignments} ra ON ra.userid = u.id
1504 LEFT JOIN {message_contacts} mc
1505 ON mc.contactid = u.id AND mc.userid = ?
1506 WHERE u.deleted = '0' AND u.confirmed = '1'
1507 AND ra.contextid $contextlists
1508 AND (".$DB->sql_like($fullname, '?', false).")
1509 $except
1510 $order", $params);
1512 return $users;
1517 * search a user's messages
1519 * @param array $searchterms an array of search terms (strings)
1520 * @param bool $fromme include messages from the user?
1521 * @param bool $tome include messages to the user?
1522 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1523 * @param int $userid the user ID of the current user
1524 * @return mixed An array of messages or false if no matching messages were found
1526 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1527 /// Returns a list of posts found using an array of search terms
1528 /// eg word +word -word
1530 global $CFG, $USER, $DB;
1532 /// If no userid sent then assume current user
1533 if ($userid == 0) $userid = $USER->id;
1535 /// Some differences in SQL syntax
1536 if ($DB->sql_regex_supported()) {
1537 $REGEXP = $DB->sql_regex(true);
1538 $NOTREGEXP = $DB->sql_regex(false);
1541 $searchcond = array();
1542 $params = array();
1543 $i = 0;
1545 //preprocess search terms to check whether we have at least 1 eligible search term
1546 //if we do we can drop words around it like 'a'
1547 $dropshortwords = false;
1548 foreach ($searchterms as $searchterm) {
1549 if (strlen($searchterm) >= 2) {
1550 $dropshortwords = true;
1554 foreach ($searchterms as $searchterm) {
1555 $i++;
1557 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1559 if ($dropshortwords && strlen($searchterm) < 2) {
1560 continue;
1562 /// Under Oracle and MSSQL, trim the + and - operators and perform
1563 /// simpler LIKE search
1564 if (!$DB->sql_regex_supported()) {
1565 if (substr($searchterm, 0, 1) == '-') {
1566 $NOT = true;
1568 $searchterm = trim($searchterm, '+-');
1571 if (substr($searchterm,0,1) == "+") {
1572 $searchterm = substr($searchterm,1);
1573 $searchterm = preg_quote($searchterm, '|');
1574 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1575 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1577 } else if (substr($searchterm,0,1) == "-") {
1578 $searchterm = substr($searchterm,1);
1579 $searchterm = preg_quote($searchterm, '|');
1580 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1581 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1583 } else {
1584 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1585 $params['ss'.$i] = "%$searchterm%";
1589 if (empty($searchcond)) {
1590 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1591 $params['ss1'] = "%";
1592 } else {
1593 $searchcond = implode(" AND ", $searchcond);
1596 /// There are several possibilities
1597 /// 1. courseid = SITEID : The admin is searching messages by all users
1598 /// 2. courseid = ?? : A teacher is searching messages by users in
1599 /// one of their courses - currently disabled
1600 /// 3. courseid = none : User is searching their own messages;
1601 /// a. Messages from user
1602 /// b. Messages to user
1603 /// c. Messages to and from user
1605 if ($courseid == SITEID) { /// admin is searching all messages
1606 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1607 FROM {message_read} m
1608 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1609 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1610 FROM {message} m
1611 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1613 } else if ($courseid !== 'none') {
1614 /// This has not been implemented due to security concerns
1615 $m_read = array();
1616 $m_unread = array();
1618 } else {
1620 if ($fromme and $tome) {
1621 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1622 $params['userid1'] = $userid;
1623 $params['userid2'] = $userid;
1625 } else if ($fromme) {
1626 $searchcond .= " AND m.useridfrom=:userid";
1627 $params['userid'] = $userid;
1629 } else if ($tome) {
1630 $searchcond .= " AND m.useridto=:userid";
1631 $params['userid'] = $userid;
1634 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1635 FROM {message_read} m
1636 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1637 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1638 FROM {message} m
1639 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1643 /// The keys may be duplicated in $m_read and $m_unread so we can't
1644 /// do a simple concatenation
1645 $message = array();
1646 foreach ($m_read as $m) {
1647 $messages[] = $m;
1649 foreach ($m_unread as $m) {
1650 $messages[] = $m;
1653 return (empty($messages)) ? false : $messages;
1657 * Given a message object that we already know has a long message
1658 * this function truncates the message nicely to the first
1659 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1661 * @param string $message the message
1662 * @param int $minlength the minimum length to trim the message to
1663 * @return string the shortened message
1665 function message_shorten_message($message, $minlength = 0) {
1666 $i = 0;
1667 $tag = false;
1668 $length = strlen($message);
1669 $count = 0;
1670 $stopzone = false;
1671 $truncate = 0;
1672 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1675 for ($i=0; $i<$length; $i++) {
1676 $char = $message[$i];
1678 switch ($char) {
1679 case "<":
1680 $tag = true;
1681 break;
1682 case ">":
1683 $tag = false;
1684 break;
1685 default:
1686 if (!$tag) {
1687 if ($stopzone) {
1688 if ($char == '.' or $char == ' ') {
1689 $truncate = $i+1;
1690 break 2;
1693 $count++;
1695 break;
1697 if (!$stopzone) {
1698 if ($count > $minlength) {
1699 $stopzone = true;
1704 if (!$truncate) {
1705 $truncate = $i;
1708 return substr($message, 0, $truncate);
1713 * Given a string and an array of keywords, this function looks
1714 * for the first keyword in the string, and then chops out a
1715 * small section from the text that shows that word in context.
1717 * @param string $message the text to search
1718 * @param array $keywords array of keywords to find
1720 function message_get_fragment($message, $keywords) {
1722 $fullsize = 160;
1723 $halfsize = (int)($fullsize/2);
1725 $message = strip_tags($message);
1727 foreach ($keywords as $keyword) { // Just get the first one
1728 if ($keyword !== '') {
1729 break;
1732 if (empty($keyword)) { // None found, so just return start of message
1733 return message_shorten_message($message, 30);
1736 $leadin = $leadout = '';
1738 /// Find the start of the fragment
1739 $start = 0;
1740 $length = strlen($message);
1742 $pos = strpos($message, $keyword);
1743 if ($pos > $halfsize) {
1744 $start = $pos - $halfsize;
1745 $leadin = '...';
1747 /// Find the end of the fragment
1748 $end = $start + $fullsize;
1749 if ($end > $length) {
1750 $end = $length;
1751 } else {
1752 $leadout = '...';
1755 /// Pull out the fragment and format it
1757 $fragment = substr($message, $start, $end - $start);
1758 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1759 return $fragment;
1763 * Retrieve the messages between two users
1765 * @param object $user1 the current user
1766 * @param object $user2 the other user
1767 * @param int $limitnum the maximum number of messages to retrieve
1768 * @param bool $viewingnewmessages are we currently viewing new messages?
1770 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1771 global $DB, $CFG;
1773 $messages = array();
1775 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1776 //desc to get the last $limitnum messages then flip the order in php
1777 $sort = 'asc';
1778 if ($limitnum>0) {
1779 $sort = 'desc';
1782 $notificationswhere = null;
1783 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1784 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1785 $notificationswhere = 'AND notification=0';
1788 //prevent notifications of your own actions appearing in your own message history
1789 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1791 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1792 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1793 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1794 "timecreated $sort", '*', 0, $limitnum)) {
1795 foreach ($messages_read as $message) {
1796 $messages[$message->timecreated] = $message;
1799 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1800 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1801 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1802 "timecreated $sort", '*', 0, $limitnum)) {
1803 foreach ($messages_new as $message) {
1804 $messages[$message->timecreated] = $message;
1808 //if we only want the last $limitnum messages
1809 ksort($messages);
1810 $messagecount = count($messages);
1811 if ($limitnum>0 && $messagecount>$limitnum) {
1812 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1815 return $messages;
1819 * Print the message history between two users
1821 * @param object $user1 the current user
1822 * @param object $user2 the other user
1823 * @param string $search search terms to highlight
1824 * @param int $messagelimit maximum number of messages to return
1825 * @param string $messagehistorylink the html for the message history link or false
1826 * @param bool $viewingnewmessages are we currently viewing new messages?
1828 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1829 global $CFG, $OUTPUT;
1831 echo $OUTPUT->box_start('center');
1832 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1833 echo html_writer::start_tag('tr');
1835 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1836 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1837 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1838 echo html_writer::end_tag('td');
1840 echo html_writer::start_tag('td', array('align' => 'center'));
1841 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1842 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1843 echo html_writer::end_tag('td');
1845 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1846 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1847 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1849 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1850 $incontactlist = $user2->iscontact;
1851 $isblocked = $user2->isblocked;
1853 $script = null;
1854 $text = true;
1855 $icon = false;
1857 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1858 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1859 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1861 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1864 echo html_writer::end_tag('td');
1865 echo html_writer::end_tag('tr');
1866 echo html_writer::end_tag('table');
1867 echo $OUTPUT->box_end();
1869 if (!empty($messagehistorylink)) {
1870 echo $messagehistorylink;
1873 /// Get all the messages and print them
1874 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1875 $tablecontents = '';
1877 $current = new stdClass();
1878 $current->mday = '';
1879 $current->month = '';
1880 $current->year = '';
1881 $messagedate = get_string('strftimetime');
1882 $blockdate = get_string('strftimedaydate');
1883 foreach ($messages as $message) {
1884 if ($message->notification) {
1885 $notificationclass = ' notification';
1886 } else {
1887 $notificationclass = null;
1889 $date = usergetdate($message->timecreated);
1890 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1891 $current->mday = $date['mday'];
1892 $current->month = $date['month'];
1893 $current->year = $date['year'];
1895 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1896 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1898 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1901 $formatted_message = $side = null;
1902 if ($message->useridfrom == $user1->id) {
1903 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1904 $side = 'left';
1905 } else {
1906 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1907 $side = 'right';
1909 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1912 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1913 } else {
1914 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1919 * Format a message for display in the message history
1921 * @param object $message the message object
1922 * @param string $format optional date format
1923 * @param string $keywords keywords to highlight
1924 * @param string $class CSS class to apply to the div around the message
1925 * @return string the formatted message
1927 function message_format_message($message, $format='', $keywords='', $class='other') {
1929 static $dateformat;
1931 //if we haven't previously set the date format or they've supplied a new one
1932 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1933 if ($format) {
1934 $dateformat = $format;
1935 } else {
1936 $dateformat = get_string('strftimedatetimeshort');
1939 $time = userdate($message->timecreated, $dateformat);
1940 $options = new stdClass();
1941 $options->para = false;
1943 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1944 if (!empty($message->smallmessage)) {
1945 $messagetext = format_text(s($message->smallmessage), FORMAT_MOODLE, $options);
1946 } else {
1947 $messagetext = format_text(s($message->fullmessage), $message->fullmessageformat, $options);
1950 $messagetext .= message_format_contexturl($message);
1952 if ($keywords) {
1953 $messagetext = highlight($keywords, $messagetext);
1956 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1960 * Format a the context url and context url name of a message for display
1962 * @param object $message the message object
1963 * @return string the formatted string
1965 function message_format_contexturl($message) {
1966 $s = null;
1968 if (!empty($message->contexturl)) {
1969 $displaytext = null;
1970 if (!empty($message->contexturlname)) {
1971 $displaytext= $message->contexturlname;
1972 } else {
1973 $displaytext= $message->contexturl;
1975 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1976 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1977 $s .= html_writer::end_tag('div');
1980 return $s;
1984 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1986 * @param object $userfrom the message sender
1987 * @param object $userto the message recipient
1988 * @param string $message the message
1989 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1990 * @return int|false the ID of the new message or false
1992 function message_post_message($userfrom, $userto, $message, $format) {
1993 global $SITE, $CFG, $USER;
1995 $eventdata = new stdClass();
1996 $eventdata->component = 'moodle';
1997 $eventdata->name = 'instantmessage';
1998 $eventdata->userfrom = $userfrom;
1999 $eventdata->userto = $userto;
2001 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2002 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2004 if ($format == FORMAT_HTML) {
2005 $eventdata->fullmessage = '';
2006 $eventdata->fullmessagehtml = $message;
2007 } else {
2008 $eventdata->fullmessage = $message;
2009 $eventdata->fullmessagehtml = '';
2012 $eventdata->fullmessageformat = $format;
2013 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2015 $s = new stdClass();
2016 $s->sitename = $SITE->shortname;
2017 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2019 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2020 if (!empty($eventdata->fullmessage)) {
2021 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2023 if (!empty($eventdata->fullmessagehtml)) {
2024 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2027 $eventdata->timecreated = time();
2028 return message_send($eventdata);
2033 * Returns a list of all user ids who have used messaging in the site
2034 * This was the simple way to code the SQL ... is it going to blow up
2035 * on large datasets?
2037 * @todo: deprecated - to be deleted in 2.2
2038 * @return array
2040 function message_get_participants() {
2041 global $CFG, $DB;
2043 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
2044 UNION SELECT useridto as id,1 FROM {message}
2045 UNION SELECT useridfrom as id,1 FROM {message_read}
2046 UNION SELECT useridto as id,1 FROM {message_read}
2047 UNION SELECT userid as id,1 FROM {message_contacts}
2048 UNION SELECT contactid as id,1 from {message_contacts}");
2052 * Print a row of contactlist displaying user picture, messages waiting and
2053 * block links etc
2055 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2056 * @param bool $incontactlist is the user a contact of ours?
2057 * @param bool $isblocked is the user blocked?
2058 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2059 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2060 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2061 * @return void
2063 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2064 global $OUTPUT, $USER;
2065 $fullname = fullname($contact);
2066 $fullnamelink = $fullname;
2068 $linkclass = '';
2069 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2070 $linkclass = 'messageselecteduser';
2073 /// are there any unread messages for this contact?
2074 if ($contact->messagecount > 0 ){
2075 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2078 $strcontact = $strblock = $strhistory = null;
2080 if ($showactionlinks) {
2081 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2082 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2083 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2086 echo html_writer::start_tag('tr');
2087 echo html_writer::start_tag('td', array('class' => 'pix'));
2088 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2089 echo html_writer::end_tag('td');
2091 echo html_writer::start_tag('td', array('class' => 'contact'));
2093 $popupoptions = array(
2094 'height' => MESSAGE_DISCUSSION_HEIGHT,
2095 'width' => MESSAGE_DISCUSSION_WIDTH,
2096 'menubar' => false,
2097 'location' => false,
2098 'status' => true,
2099 'scrollbars' => true,
2100 'resizable' => true);
2102 $link = $action = null;
2103 if (!empty($selectcontacturl)) {
2104 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2105 } else {
2106 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2107 $link = new moodle_url("/message/index.php?id=$contact->id");
2108 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2110 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2112 echo html_writer::end_tag('td');
2114 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2116 echo html_writer::end_tag('tr');
2120 * Constructs the add/remove contact link to display next to other users
2122 * @param bool $incontactlist is the user a contact
2123 * @param bool $isblocked is the user blocked
2124 * @param type $contact contact object
2125 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2126 * @param bool $text include text next to the icons?
2127 * @param bool $icon include a graphical icon?
2128 * @return string
2130 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2131 $strcontact = '';
2133 if($incontactlist){
2134 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2135 } else if ($isblocked) {
2136 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2137 } else{
2138 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2141 return $strcontact;
2145 * Constructs the block contact link to display next to other users
2147 * @param bool $incontactlist is the user a contact
2148 * @param bool $isblocked is the user blocked
2149 * @param type $contact contact object
2150 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2151 * @param bool $text include text next to the icons?
2152 * @param bool $icon include a graphical icon?
2153 * @return string
2155 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2156 $strblock = '';
2158 //commented out to allow the user to block a contact without having to remove them first
2159 /*if ($incontactlist) {
2160 //$strblock = '';
2161 } else*/
2162 if ($isblocked) {
2163 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2164 } else{
2165 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2168 return $strblock;
2172 * Moves messages from a particular user from the message table (unread messages) to message_read
2173 * This is typically only used when a user is deleted
2175 * @param object $userid User id
2176 * @return boolean success
2178 function message_move_userfrom_unread2read($userid) {
2179 global $DB;
2181 // move all unread messages from message table to message_read
2182 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2183 foreach ($messages as $message) {
2184 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2187 return true;
2191 * marks ALL messages being sent from $fromuserid to $touserid as read
2193 * @param int $touserid the id of the message recipient
2194 * @param int $fromuserid the id of the message sender
2195 * @return void
2197 function message_mark_messages_read($touserid, $fromuserid){
2198 global $DB;
2200 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2201 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2203 foreach ($messages as $message) {
2204 message_mark_message_read($message, time());
2207 $messages->close();
2211 * Mark a single message as read
2213 * @param message an object with an object property ie $message->id which is an id in the message table
2214 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2215 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2216 * @return int the ID of the message in the message_read table
2218 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2219 global $DB;
2221 $message->timeread = $timeread;
2223 $messageid = $message->id;
2224 unset($message->id);//unset because it will get a new id on insert into message_read
2226 //If any processors have pending actions abort them
2227 if (!$messageworkingempty) {
2228 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2230 $messagereadid = $DB->insert_record('message_read', $message);
2231 $DB->delete_records('message', array('id' => $messageid));
2232 return $messagereadid;
2236 * A helper function that prints a formatted heading
2238 * @param string $title the heading to display
2239 * @param int $colspan
2240 * @return void
2242 function message_print_heading($title, $colspan=3) {
2243 echo html_writer::start_tag('tr');
2244 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2245 echo html_writer::end_tag('tr');
2249 * Get all message processors, validate corresponding plugin existance and
2250 * system configuration
2252 * @param bool $ready only return ready-to-use processors
2253 * @return mixed $processors array of objects containing information on message processors
2255 function get_message_processors($ready = false) {
2256 global $DB, $CFG;
2258 static $processors;
2260 if (empty($processors)) {
2261 // Get all processors, ensure the name column is the first so it will be the array key
2262 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2263 foreach ($processors as &$processor){
2264 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2265 if (is_readable($processorfile)) {
2266 include_once($processorfile);
2267 $processclass = 'message_output_' . $processor->name;
2268 if (class_exists($processclass)) {
2269 $pclass = new $processclass();
2270 $processor->object = $pclass;
2271 $processor->configured = 0;
2272 if ($pclass->is_system_configured()) {
2273 $processor->configured = 1;
2275 $processor->hassettings = 0;
2276 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2277 $processor->hassettings = 1;
2279 $processor->available = 1;
2280 } else {
2281 print_error('errorcallingprocessor', 'message');
2283 } else {
2284 $processor->available = 0;
2288 if ($ready) {
2289 // Filter out enabled and system_configured processors
2290 $readyprocessors = $processors;
2291 foreach ($readyprocessors as $readyprocessor) {
2292 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2293 unset($readyprocessors[$readyprocessor->name]);
2296 return $readyprocessors;
2299 return $processors;
2303 * Get messaging outputs default (site) preferences
2305 * @return object $processors object containing information on message processors
2307 function get_message_output_default_preferences() {
2308 $preferences = get_config('message');
2309 if (!$preferences) {
2310 $preferences = new stdClass();
2312 return $preferences;
2316 * Translate message default settings from binary value to the array of string
2317 * representing the settings to be stored. Also validate the provided value and
2318 * use default if it is malformed.
2320 * @param int $plugindefault Default setting suggested by plugin
2321 * @param string $processorname The name of processor
2322 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2324 function translate_message_default_setting($plugindefault, $processorname) {
2325 // Preset translation arrays
2326 $permittedvalues = array(
2327 0x04 => 'disallowed',
2328 0x08 => 'permitted',
2329 0x0c => 'forced',
2332 $loggedinstatusvalues = array(
2333 0x00 => null, // use null if loggedin/loggedoff is not defined
2334 0x01 => 'loggedin',
2335 0x02 => 'loggedoff',
2338 // define the default setting
2339 if ($processorname == 'email') {
2340 $default = MESSAGE_PERMITTED + MESSAGE_DEFAULT_LOGGEDIN + MESSAGE_DEFAULT_LOGGEDOFF;
2341 } else {
2342 $default = MESSAGE_PERMITTED;
2345 // Validate the value. It should not exceed the maximum size
2346 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2347 $OUTPUT->notification(get_string('errortranslatingdefault', 'message'), 'notifyproblem');
2348 $plugindefault = $default;
2350 // Use plugin default setting of 'permitted' is 0
2351 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2352 $plugindefault = $default;
2355 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2356 $loggedin = $loggedoff = null;
2358 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2359 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2360 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2363 return array($permitted, $loggedin, $loggedoff);
2367 * Return a list of page types
2368 * @param string $pagetype current page type
2369 * @param stdClass $parentcontext Block's parent context
2370 * @param stdClass $currentcontext Current context of block
2372 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2373 return array('messages-*'=>get_string('page-message-x', 'message'));