2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library functions for messaging
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir.'/eventslib.php');
27 define ('MESSAGE_SHORTLENGTH', 300);
29 define ('MESSAGE_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
75 * Print the selector that allows the user to view their contacts, course participants, their recent
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
93 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
95 //if 0 unread messages and they've requested unread messages then show contacts
96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97 $viewing = MESSAGE_VIEW_CONTACTS;
100 //if they have no blocked users and they've requested blocked users switch them over to contacts
101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102 $viewing = MESSAGE_VIEW_CONTACTS;
105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
118 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
120 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
121 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
123 $courseidtoshow = intval(substr($viewing, 7));
125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
131 //shouldn't get here. User trying to access a course they're not in perhaps.
132 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
136 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
137 echo html_writer::start_tag('fieldset');
138 $managebuttonclass = 'visible';
139 if ($viewing == MESSAGE_VIEW_SEARCH) {
140 $managebuttonclass = 'hiddenelement';
142 $strmanagecontacts = get_string('search','message');
143 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
144 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
145 echo html_writer::end_tag('fieldset');
146 echo html_writer::end_tag('form');
148 echo html_writer::end_tag('div');
152 * Print course participants. Called by message_print_contact_selector()
154 * @param object $context the course context
155 * @param int $courseid the course ID
156 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
157 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
158 * @param string $titletodisplay Optionally specify a title to display above the participants
159 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
160 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
163 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
164 global $DB, $USER, $PAGE, $OUTPUT;
166 if (empty($titletodisplay)) {
167 $titletodisplay = get_string('participants');
170 $countparticipants = count_enrolled_users($context);
172 list($esql, $params) = get_enrolled_sql($context);
173 $params['mcuserid'] = $USER->id;
174 $ufields = user_picture::fields('u');
176 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
178 JOIN ($esql) je ON je.id = u.id
179 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
180 WHERE u.deleted = 0";
182 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
184 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
185 echo $OUTPUT->render($pagingbar);
187 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
189 echo html_writer::start_tag('tr');
190 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
191 echo html_writer::end_tag('tr');
193 foreach ($participants as $participant) {
194 if ($participant->id != $USER->id) {
198 if ( $participant->contactlistid ) {
199 if ($participant->blocked == 0) {
200 // Is contact. Is not blocked.
210 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
211 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
215 echo html_writer::end_tag('table');
219 * Retrieve users blocked by $user1
221 * @param object $user1 the user whose messages are being viewed
222 * @param object $user2 the user $user1 is talking to. If they are being blocked
223 * they will have a variable called 'isblocked' added to their user object
224 * @return array the users blocked by $user1
226 function message_get_blocked_users($user1=null, $user2=null) {
233 if (!empty($user2)) {
234 $user2->isblocked = false;
237 $blockedusers = array();
239 $userfields = user_picture::fields('u', array('lastaccess'));
240 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
241 FROM {message_contacts} mc
242 JOIN {user} u ON u.id = mc.contactid
243 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
244 WHERE mc.userid = :user1id2 AND mc.blocked = 1
246 ORDER BY u.firstname ASC";
247 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
249 foreach($rs as $rd) {
250 $blockedusers[] = $rd;
252 if (!empty($user2) && $user2->id == $rd->id) {
253 $user2->isblocked = true;
258 return $blockedusers;
262 * Print users blocked by $user1. Called by message_print_contact_selector()
264 * @param array $blockedusers the users blocked by $user1
265 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
266 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
267 * @param string $titletodisplay Optionally specify a title to display above the participants
268 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
271 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
274 $countblocked = count($blockedusers);
276 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
278 if (!empty($titletodisplay)) {
279 echo html_writer::start_tag('tr');
280 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
281 echo html_writer::end_tag('tr');
285 echo html_writer::start_tag('tr');
286 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
287 echo html_writer::end_tag('tr');
289 $isuserblocked = true;
290 $isusercontact = false;
291 foreach ($blockedusers as $blockeduser) {
292 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
296 echo html_writer::end_tag('table');
300 * Retrieve $user1's contacts (online, offline and strangers)
302 * @param object $user1 the user whose messages are being viewed
303 * @param object $user2 the user $user1 is talking to. If they are a contact
304 * they will have a variable called 'iscontact' added to their user object
305 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
307 function message_get_contacts($user1=null, $user2=null) {
308 global $DB, $CFG, $USER;
314 if (!empty($user2)) {
315 $user2->iscontact = false;
318 $timetoshowusers = 300; //Seconds default
319 if (isset($CFG->block_online_users_timetosee)) {
320 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
323 // time which a user is counting as being active since
324 $timefrom = time()-$timetoshowusers;
326 // people in our contactlist who are online
327 $onlinecontacts = array();
328 // people in our contactlist who are offline
329 $offlinecontacts = array();
330 // people who are not in our contactlist but have sent us a message
331 $strangers = array();
333 $userfields = user_picture::fields('u', array('lastaccess'));
335 // get all in our contactlist who are not blocked in our contact list
336 // and count messages we have waiting from each of them
337 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
338 FROM {message_contacts} mc
339 JOIN {user} u ON u.id = mc.contactid
340 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
341 WHERE mc.userid = ? AND mc.blocked = 0
343 ORDER BY u.firstname ASC";
345 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
346 foreach ($rs as $rd) {
347 if ($rd->lastaccess >= $timefrom) {
348 // they have been active recently, so are counted online
349 $onlinecontacts[] = $rd;
352 $offlinecontacts[] = $rd;
355 if (!empty($user2) && $user2->id == $rd->id) {
356 $user2->iscontact = true;
361 // get messages from anyone who isn't in our contact list and count the number
362 // of messages we have from each of them
363 $strangersql = "SELECT $userfields, count(m.id) as messagecount
365 JOIN {user} u ON u.id = m.useridfrom
366 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
367 WHERE mc.id IS NULL AND m.useridto = ?
369 ORDER BY u.firstname ASC";
371 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
372 foreach ($rs as $rd) {
377 return array($onlinecontacts, $offlinecontacts, $strangers);
381 * Print $user1's contacts. Called by message_print_contact_selector()
383 * @param array $onlinecontacts $user1's contacts which are online
384 * @param array $offlinecontacts $user1's contacts which are offline
385 * @param array $strangers users which are not contacts but who have messaged $user1
386 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
387 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
388 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
389 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
390 * @param string $titletodisplay Optionally specify a title to display above the participants
391 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
394 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
395 global $CFG, $PAGE, $OUTPUT;
397 $countonlinecontacts = count($onlinecontacts);
398 $countofflinecontacts = count($offlinecontacts);
399 $countstrangers = count($strangers);
400 $isuserblocked = null;
402 if ($countonlinecontacts + $countofflinecontacts == 0) {
403 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
406 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
408 if (!empty($titletodisplay)) {
409 message_print_heading($titletodisplay);
412 if($countonlinecontacts) {
413 /// print out list of online contacts
415 if (empty($titletodisplay)) {
416 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
419 $isuserblocked = false;
420 $isusercontact = true;
421 foreach ($onlinecontacts as $contact) {
422 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
423 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
428 if ($countofflinecontacts) {
429 /// print out list of offline contacts
431 if (empty($titletodisplay)) {
432 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
435 $isuserblocked = false;
436 $isusercontact = true;
437 foreach ($offlinecontacts as $contact) {
438 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
439 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
445 /// print out list of incoming contacts
446 if ($countstrangers) {
447 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
449 $isuserblocked = false;
450 $isusercontact = false;
451 foreach ($strangers as $stranger) {
452 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
453 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
458 echo html_writer::end_tag('table');
460 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
461 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
466 * Print a select box allowing the user to choose to view new messages, course participants etc.
468 * Called by message_print_contact_selector()
469 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
470 * @param array $courses array of course objects. The courses the user is enrolled in.
471 * @param array $coursecontexts array of course contexts. Keyed on course id.
472 * @param int $countunreadtotal how many unread messages does the user have?
473 * @param int $countblocked how many users has the current user blocked?
474 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
477 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
480 if ($countunreadtotal>0) { //if there are unread messages
481 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
484 $str = get_string('mycontacts', 'message');
485 $options[MESSAGE_VIEW_CONTACTS] = $str;
487 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
488 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
490 if (!empty($courses)) {
491 $courses_options = array();
493 foreach($courses as $course) {
494 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
495 //Not using short_text() as we want the end of the course name. Not the beginning.
496 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
497 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
498 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
500 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
505 if (!empty($courses_options)) {
506 $options[] = array(get_string('courses') => $courses_options);
510 if ($countblocked>0) {
511 $str = get_string('blockedusers','message', $countblocked);
512 $options[MESSAGE_VIEW_BLOCKED] = $str;
515 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
516 echo html_writer::start_tag('fieldset');
517 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
518 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
519 echo html_writer::end_tag('fieldset');
520 echo html_writer::end_tag('form');
524 * Load the course contexts for all of the users courses
526 * @param array $courses array of course objects. The courses the user is enrolled in.
527 * @return array of course contexts
529 function message_get_course_contexts($courses) {
530 $coursecontexts = array();
532 foreach($courses as $course) {
533 $coursecontexts[$course->id] = context_course::instance($course->id);
536 return $coursecontexts;
540 * strip off action parameters like 'removecontact'
542 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
543 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
545 function message_remove_url_params($moodleurl) {
546 $newurl = new moodle_url($moodleurl);
547 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
548 return $newurl->out();
552 * Count the number of messages with a field having a specified value.
553 * if $field is empty then return count of the whole array
554 * if $field is non-existent then return 0
556 * @param array $messagearray array of message objects
557 * @param string $field the field to inspect on the message objects
558 * @param string $value the value to test the field against
560 function message_count_messages($messagearray, $field='', $value='') {
561 if (!is_array($messagearray)) return 0;
562 if ($field == '' or empty($messagearray)) return count($messagearray);
565 foreach ($messagearray as $message) {
566 $count += ($message->$field == $value) ? 1 : 0;
572 * Returns the count of unread messages for user. Either from a specific user or from all users.
574 * @param object $user1 the first user. Defaults to $USER
575 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
576 * @return int the count of $user1's unread messages
578 function message_count_unread_messages($user1=null, $user2=null) {
585 if (!empty($user2)) {
586 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
587 array($user1->id, $user2->id), "COUNT('id')");
589 return $DB->count_records_select('message', "useridto = ?",
590 array($user1->id), "COUNT('id')");
595 * Count the number of users blocked by $user1
597 * @param object $user1 user object
598 * @return int the number of blocked users
600 function message_count_blocked_users($user1=null) {
607 $sql = "SELECT count(mc.id)
608 FROM {message_contacts} mc
609 WHERE mc.userid = :userid AND mc.blocked = 1";
610 $params = array('userid' => $user1->id);
612 return $DB->count_records_sql($sql, $params);
616 * Print the search form and search results if a search has been performed
618 * @param boolean $advancedsearch show basic or advanced search form
619 * @param object $user1 the current user
620 * @return boolean true if a search was performed
622 function message_print_search($advancedsearch = false, $user1=null) {
623 $frm = data_submitted();
625 $doingsearch = false;
627 if (confirm_sesskey()) {
628 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
634 if (!empty($frm->combinedsearch)) {
635 $combinedsearchstring = $frm->combinedsearch;
637 //$combinedsearchstring = get_string('searchcombined','message').'...';
638 $combinedsearchstring = '';
642 if ($advancedsearch) {
645 if (!empty($frm->keywords)) {
646 $messagesearch = $frm->keywords;
649 if (!empty($frm->name)) {
650 $personsearch = $frm->name;
652 include('search_advanced.html');
654 include('search.html');
657 $showicontext = false;
658 message_print_search_results($frm, $showicontext, $user1);
663 if ($advancedsearch) {
664 $personsearch = $messagesearch = '';
665 include('search_advanced.html');
667 include('search.html');
674 * Get the users recent conversations meaning all the people they've recently
675 * sent or received a message from plus the most recent message sent to or received from each other user
677 * @param object $user the current user
678 * @param int $limitfrom can be used for paging
679 * @param int $limitto can be used for paging
682 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
685 $userfields = user_picture::fields('u', array('lastaccess'));
686 //This query retrieves the last message received from and sent to each user
687 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
688 //It then joins with some other tables to get some additional data we need
690 //message ID is used instead of timecreated as it should sort the same and will be much faster
692 //There is a separate query for read and unread queries as they are stored in different tables
693 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
694 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
695 FROM {message_read} mr
697 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
699 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
700 FROM {message_read} mr1
701 WHERE mr1.useridfrom = :userid1
702 AND mr1.notification = 0
703 GROUP BY mr1.useridto
705 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
706 FROM {message_read} mr2
707 WHERE mr2.useridto = :userid2
708 AND mr2.notification = 0
709 GROUP BY mr2.useridfrom
711 GROUP BY messages.userid
712 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
713 JOIN {user} u ON u.id = messages2.userid
714 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
715 WHERE u.deleted = '0'
716 ORDER BY mr.id DESC";
717 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
718 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
720 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
723 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
725 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
727 WHERE m1.useridfrom = :userid1
728 AND m1.notification = 0
731 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
733 WHERE m2.useridto = :userid2
734 AND m2.notification = 0
735 GROUP BY m2.useridfrom
737 GROUP BY messages.userid
738 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
739 JOIN {user} u ON u.id = messages2.userid
740 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
741 WHERE u.deleted = '0'
743 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
745 $conversations = array();
747 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
748 //$conversation->id (the array key) is the other user's ID
749 $conversation_arrays = array($unread, $read);
750 foreach ($conversation_arrays as $conversation_array) {
751 foreach ($conversation_array as $conversation) {
752 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
753 $conversations[$conversation->id] = $conversation;
758 // Sort the conversations by $conversation->timecreated, newest to oldest
759 // There may be multiple conversations with the same timecreated
760 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
761 $result = collatorlib::asort_objects_by_property($conversations, 'timecreated', collatorlib::SORT_NUMERIC);
762 $conversations = array_reverse($conversations);
764 return $conversations;
768 * Get the users recent event notifications
770 * @param object $user the current user
771 * @param int $limitfrom can be used for paging
772 * @param int $limitto can be used for paging
775 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
778 $userfields = user_picture::fields('u', array('lastaccess'));
779 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
780 FROM {message_read} mr
781 JOIN {user} u ON u.id=mr.useridfrom
782 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
783 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
784 $params = array('userid1' => $user->id, 'notification' => 1);
786 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
787 return $notifications;
791 * Print the user's recent conversations
793 * @param stdClass $user the current user
794 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
796 function message_print_recent_conversations($user=null, $showicontext=false) {
799 echo html_writer::start_tag('p', array('class' => 'heading'));
800 echo get_string('mostrecentconversations', 'message');
801 echo html_writer::end_tag('p');
807 $conversations = message_get_recent_conversations($user);
809 // Attach context url information to create the "View this conversation" type links
810 foreach($conversations as $conversation) {
811 $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
812 $conversation->contexturlname = get_string('thisconversation', 'message');
815 $showotheruser = true;
816 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
820 * Print the user's recent notifications
822 * @param stdClass $user the current user
824 function message_print_recent_notifications($user=null) {
827 echo html_writer::start_tag('p', array('class' => 'heading'));
828 echo get_string('mostrecentnotifications', 'message');
829 echo html_writer::end_tag('p');
835 $notifications = message_get_recent_notifications($user);
837 $showicontext = false;
838 $showotheruser = false;
839 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
843 * Print a list of recent messages
845 * @param array $messages the messages to display
846 * @param object $user the current user
847 * @param bool $showotheruser display information on the other user?
848 * @param bool $showicontext show text next to the action icons?
849 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
852 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false, $forcetexttohtml=false) {
856 if (empty($dateformat)) {
857 $dateformat = get_string('strftimedatetimeshort');
860 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
861 foreach ($messages as $message) {
862 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
864 if ($showotheruser) {
865 if ( $message->contactlistid ) {
866 if ($message->blocked == 0) { /// not blocked
867 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
868 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
870 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
871 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
874 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
875 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
878 //should we show just the icon or icon and text?
879 $histicontext = 'icon';
881 $histicontext = 'both';
883 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
885 echo html_writer::start_tag('span', array('class' => 'otheruser'));
887 echo html_writer::start_tag('span', array('class' => 'pix'));
888 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
889 echo html_writer::end_tag('span');
891 echo html_writer::start_tag('span', array('class' => 'contact'));
893 $link = new moodle_url("/message/index.php?id=$message->id");
895 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
897 echo html_writer::end_tag('span');//end contact
899 echo $strcontact.$strblock.$strhistory;
900 echo html_writer::end_tag('span');//end otheruser
902 $messagetoprint = null;
903 if (!empty($message->smallmessage)) {
904 $messagetoprint = $message->smallmessage;
906 $messagetoprint = $message->fullmessage;
909 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
910 echo html_writer::tag('span', format_text($messagetoprint, $forcetexttohtml?FORMAT_MOODLE:FORMAT_HTML), array('class' => 'themessage'));
911 echo message_format_contexturl($message);
912 echo html_writer::end_tag('div');//end singlemessage
914 echo html_writer::end_tag('div');//end messagerecent
918 * Add the selected user as a contact for the current user
920 * @param int $contactid the ID of the user to add as a contact
921 * @param int $blocked 1 if you wish to block the contact
922 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
923 * Otherwise returns the result of update_record() or insert_record()
925 function message_add_contact($contactid, $blocked=0) {
928 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
932 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
933 /// record already exists - we may be changing blocking status
935 if ($contact->blocked !== $blocked) {
936 /// change to blocking status
937 $contact->blocked = $blocked;
938 return $DB->update_record('message_contacts', $contact);
940 /// no changes to blocking status
945 /// new contact record
946 $contact = new stdClass();
947 $contact->userid = $USER->id;
948 $contact->contactid = $contactid;
949 $contact->blocked = $blocked;
950 return $DB->insert_record('message_contacts', $contact, false);
957 * @param int $contactid the user ID of the contact to remove
958 * @return bool returns the result of delete_records()
960 function message_remove_contact($contactid) {
962 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
966 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
968 * @param int $contactid the user ID of the contact to unblock
969 * @return bool returns the result of delete_records()
971 function message_unblock_contact($contactid) {
973 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
979 * @param int $contactid the user ID of the user to block
981 function message_block_contact($contactid) {
982 return message_add_contact($contactid, 1);
986 * Load a user's contact record
988 * @param int $contactid the user ID of the user whose contact record you want
989 * @return array message contacts
991 function message_get_contact($contactid) {
993 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
997 * Print the results of a message search
999 * @param mixed $frm submitted form data
1000 * @param bool $showicontext show text next to action icons?
1001 * @param object $currentuser the current user
1004 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1005 global $USER, $DB, $OUTPUT;
1007 if (empty($currentuser)) {
1008 $currentuser = $USER;
1011 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1013 $personsearch = false;
1014 $personsearchstring = null;
1015 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1016 $personsearch = true;
1017 $personsearchstring = $frm->name;
1018 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1019 $personsearch = true;
1020 $personsearchstring = $frm->combinedsearch;
1023 /// search for person
1024 if ($personsearch) {
1025 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1027 $mycourses = enrol_get_my_courses('id');
1028 $mycoursesids = array();
1029 foreach ($mycourses as $mycourse) {
1030 $mycoursesids[] = $mycourse->id;
1032 $susers = message_search_users($mycoursesids, $personsearchstring);
1033 foreach ($susers as $suser) {
1034 $users[$suser->id] = $suser;
1037 $users = message_search_users(SITEID, $personsearchstring);
1040 if (!empty($users)) {
1041 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1042 echo get_string('userssearchresults', 'message', count($users));
1043 echo html_writer::end_tag('p');
1045 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1046 foreach ($users as $user) {
1048 if ( $user->contactlistid ) {
1049 if ($user->blocked == 0) { /// not blocked
1050 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1051 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1053 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1054 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1057 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1058 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1061 //should we show just the icon or icon and text?
1062 $histicontext = 'icon';
1063 if ($showicontext) {
1064 $histicontext = 'both';
1066 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1068 echo html_writer::start_tag('tr');
1070 echo html_writer::start_tag('td', array('class' => 'pix'));
1071 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1072 echo html_writer::end_tag('td');
1074 echo html_writer::start_tag('td',array('class' => 'contact'));
1076 $link = new moodle_url("/message/index.php?id=$user->id");
1077 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1078 echo html_writer::end_tag('td');
1080 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1081 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1082 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1084 echo html_writer::end_tag('tr');
1086 echo html_writer::end_tag('table');
1089 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1090 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1091 echo html_writer::end_tag('p');
1095 // search messages for keywords
1096 $messagesearch = false;
1097 $messagesearchstring = null;
1098 if (!empty($frm->keywords)) {
1099 $messagesearch = true;
1100 $messagesearchstring = clean_text(trim($frm->keywords));
1101 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1102 $messagesearch = true;
1103 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1106 if ($messagesearch) {
1107 if ($messagesearchstring) {
1108 $keywords = explode(' ', $messagesearchstring);
1110 $keywords = array();
1116 if (empty($frm->keywordsoption)) {
1117 $frm->keywordsoption = 'allmine';
1120 switch ($frm->keywordsoption) {
1135 $courseid = $frm->courseid;
1142 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1144 /// get a list of contacts
1145 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1146 $contacts = array();
1149 /// print heading with number of results
1150 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1151 $countresults = count($messages);
1152 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1153 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1155 echo get_string('keywordssearchresults', 'message', $countresults);
1157 echo html_writer::end_tag('p');
1159 /// print table headings
1160 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1162 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1163 $headertdend = html_writer::end_tag('td');
1164 echo html_writer::start_tag('tr');
1165 echo $headertdstart.get_string('from').$headertdend;
1166 echo $headertdstart.get_string('to').$headertdend;
1167 echo $headertdstart.get_string('message', 'message').$headertdend;
1168 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1169 echo html_writer::end_tag('tr');
1172 $dateformat = get_string('strftimedatetimeshort');
1173 $strcontext = get_string('context', 'message');
1174 foreach ($messages as $message) {
1176 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1177 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1178 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1179 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1186 /// load up user to record
1187 if ($message->useridto !== $USER->id) {
1188 $userto = $DB->get_record('user', array('id' => $message->useridto));
1189 $tocontact = (array_key_exists($message->useridto, $contacts) and
1190 ($contacts[$message->useridto]->blocked == 0) );
1191 $toblocked = (array_key_exists($message->useridto, $contacts) and
1192 ($contacts[$message->useridto]->blocked == 1) );
1199 /// load up user from record
1200 if ($message->useridfrom !== $USER->id) {
1201 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1202 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1203 ($contacts[$message->useridfrom]->blocked == 0) );
1204 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1205 ($contacts[$message->useridfrom]->blocked == 1) );
1208 $fromcontact = false;
1209 $fromblocked = false;
1212 /// find date string for this message
1213 $date = usergetdate($message->timecreated);
1214 $datestring = $date['year'].$date['mon'].$date['mday'];
1216 /// print out message row
1217 echo html_writer::start_tag('tr', array('valign' => 'top'));
1219 echo html_writer::start_tag('td', array('class' => 'contact'));
1220 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1221 echo html_writer::end_tag('td');
1223 echo html_writer::start_tag('td', array('class' => 'contact'));
1224 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1225 echo html_writer::end_tag('td');
1227 echo html_writer::start_tag('td', array('class' => 'summary'));
1228 echo message_get_fragment($message->smallmessage, $keywords);
1229 echo html_writer::start_tag('div', array('class' => 'link'));
1231 //If the user clicks the context link display message sender on the left
1232 //EXCEPT if the current user is in the conversation. Current user == always on the left
1233 $leftsideuserid = $rightsideuserid = null;
1234 if ($currentuser->id == $message->useridto) {
1235 $leftsideuserid = $message->useridto;
1236 $rightsideuserid = $message->useridfrom;
1238 $leftsideuserid = $message->useridfrom;
1239 $rightsideuserid = $message->useridto;
1241 message_history_link($leftsideuserid, $rightsideuserid, false,
1242 $messagesearchstring, 'm'.$message->id, $strcontext);
1243 echo html_writer::end_tag('div');
1244 echo html_writer::end_tag('td');
1246 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1248 echo html_writer::end_tag('tr');
1252 if ($blockedcount > 0) {
1253 echo html_writer::start_tag('tr');
1254 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1255 echo html_writer::end_tag('tr');
1257 echo html_writer::end_tag('table');
1260 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1264 if (!$personsearch && !$messagesearch) {
1265 //they didn't enter any search terms
1266 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1269 echo html_writer::end_tag('div');
1273 * Print information on a user. Used when printing search results.
1275 * @param object/bool $user the user to display or false if you just want $USER
1276 * @param bool $iscontact is the user being displayed a contact?
1277 * @param bool $isblocked is the user being displayed blocked?
1278 * @param bool $includeicontext include text next to the action icons?
1281 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1282 global $USER, $OUTPUT;
1284 if ($user === false) {
1285 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1287 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1289 $link = new moodle_url("/message/index.php?id=$user->id");
1290 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1291 get_string('sendmessageto', 'message', fullname($user))));
1296 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1298 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1302 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1304 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1310 * Print a message contact link
1312 * @param int $userid the ID of the user to apply to action to
1313 * @param string $linktype can be add, remove, block or unblock
1314 * @param bool $return if true return the link as a string. If false echo the link.
1315 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1316 * @param bool $text include text next to the icons?
1317 * @param bool $icon include a graphical icon?
1318 * @return string if $return is true otherwise bool
1320 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1321 global $OUTPUT, $PAGE;
1323 //hold onto the strings as we're probably creating a bunch of links
1326 if (empty($script)) {
1327 //strip off previous action params like 'removecontact'
1328 $script = message_remove_url_params($PAGE->url);
1331 if (empty($str->blockcontact)) {
1332 $str = new stdClass();
1333 $str->blockcontact = get_string('blockcontact', 'message');
1334 $str->unblockcontact = get_string('unblockcontact', 'message');
1335 $str->removecontact = get_string('removecontact', 'message');
1336 $str->addcontact = get_string('addcontact', 'message');
1339 $command = $linktype.'contact';
1340 $string = $str->{$command};
1342 $safealttext = s($string);
1345 if (!empty($text)) {
1346 $safestring = $safealttext;
1352 switch ($linktype) {
1354 $iconpath = 't/block';
1357 $iconpath = 't/unblock';
1360 $iconpath = 't/removecontact';
1364 $iconpath = 't/addcontact';
1367 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1370 $output = '<span class="'.$linktype.'contact">'.
1371 '<a href="'.$script.'&'.$command.'='.$userid.
1372 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1374 $safestring.'</a></span>';
1385 * echo or return a link to take the user to the full message history between themselves and another user
1387 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1388 * @param int $userid2 the ID of the other user
1389 * @param bool $return true to return the link as a string. False to echo the link.
1390 * @param string $keywords any keywords to highlight in the message history
1391 * @param string $position anchor name to jump to within the message history
1392 * @param string $linktext optionally specify the link text
1393 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1395 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1397 static $strmessagehistory;
1399 if (empty($strmessagehistory)) {
1400 $strmessagehistory = get_string('messagehistory', 'message');
1404 $position = "#$position";
1407 $keywords = "&search=".urlencode($keywords);
1410 if ($linktext == 'icon') { // Icon only
1411 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1412 } else if ($linktext == 'both') { // Icon and standard name
1413 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1414 $fulllink .= ' '.$strmessagehistory;
1415 } else if ($linktext) { // Custom name
1416 $fulllink = $linktext;
1417 } else { // Standard name only
1418 $fulllink = $strmessagehistory;
1421 $popupoptions = array(
1425 'location' => false,
1427 'scrollbars' => true,
1428 'resizable' => true);
1430 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1432 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1434 $str = '<span class="history">'.$str.'</span>';
1446 * Search through course users.
1448 * If $courseids contains the site course then this function searches
1449 * through all undeleted and confirmed users.
1451 * @param int|array $courseids Course ID or array of course IDs.
1452 * @param string $searchtext the text to search for.
1453 * @param string $sort the column name to order by.
1454 * @param string $exceptions comma separated list of user IDs to exclude
1455 * @return array An array of {@link $USER} records.
1457 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1458 global $CFG, $USER, $DB;
1460 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1462 $courseids = array(SITEID);
1465 // Allow an integer to be passed.
1466 if (!is_array($courseids)) {
1467 $courseids = array($courseids);
1470 $fullname = $DB->sql_fullname();
1472 if (!empty($exceptions)) {
1473 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1478 if (!empty($sort)) {
1479 $order = ' ORDER BY '. $sort;
1484 $ufields = user_picture::fields('u');
1486 if (in_array(SITEID, $courseids)) {
1487 // Search on site level.
1488 $params = array($USER->id, "%$searchtext%");
1489 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1491 LEFT JOIN {message_contacts} mc
1492 ON mc.contactid = u.id AND mc.userid = ?
1493 WHERE u.deleted = '0' AND u.confirmed = '1'
1494 AND (".$DB->sql_like($fullname, '?', false).")
1498 // Search in courses.
1499 $params = array($USER->id, "%$searchtext%");
1501 // Getting the context IDs or each course.
1502 $contextids = array();
1503 foreach ($courseids as $courseid) {
1504 $context = context_course::instance($courseid);
1505 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1507 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids));
1508 $params = array_merge($params, $contextparams);
1510 // Everyone who has a role assignment in this course or higher.
1511 // TODO: add enabled enrolment join here (skodak)
1512 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1514 JOIN {role_assignments} ra ON ra.userid = u.id
1515 LEFT JOIN {message_contacts} mc
1516 ON mc.contactid = u.id AND mc.userid = ?
1517 WHERE u.deleted = '0' AND u.confirmed = '1'
1518 AND (".$DB->sql_like($fullname, '?', false).")
1519 AND ra.contextid $contextwhere
1528 * search a user's messages
1530 * @param array $searchterms an array of search terms (strings)
1531 * @param bool $fromme include messages from the user?
1532 * @param bool $tome include messages to the user?
1533 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1534 * @param int $userid the user ID of the current user
1535 * @return mixed An array of messages or false if no matching messages were found
1537 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1538 /// Returns a list of posts found using an array of search terms
1539 /// eg word +word -word
1541 global $CFG, $USER, $DB;
1543 // If user is searching all messages check they are allowed to before doing anything else
1544 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1545 print_error('accessdenied','admin');
1548 /// If no userid sent then assume current user
1549 if ($userid == 0) $userid = $USER->id;
1551 /// Some differences in SQL syntax
1552 if ($DB->sql_regex_supported()) {
1553 $REGEXP = $DB->sql_regex(true);
1554 $NOTREGEXP = $DB->sql_regex(false);
1557 $searchcond = array();
1561 //preprocess search terms to check whether we have at least 1 eligible search term
1562 //if we do we can drop words around it like 'a'
1563 $dropshortwords = false;
1564 foreach ($searchterms as $searchterm) {
1565 if (strlen($searchterm) >= 2) {
1566 $dropshortwords = true;
1570 foreach ($searchterms as $searchterm) {
1573 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1575 if ($dropshortwords && strlen($searchterm) < 2) {
1578 /// Under Oracle and MSSQL, trim the + and - operators and perform
1579 /// simpler LIKE search
1580 if (!$DB->sql_regex_supported()) {
1581 if (substr($searchterm, 0, 1) == '-') {
1584 $searchterm = trim($searchterm, '+-');
1587 if (substr($searchterm,0,1) == "+") {
1588 $searchterm = substr($searchterm,1);
1589 $searchterm = preg_quote($searchterm, '|');
1590 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1591 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1593 } else if (substr($searchterm,0,1) == "-") {
1594 $searchterm = substr($searchterm,1);
1595 $searchterm = preg_quote($searchterm, '|');
1596 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1597 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1600 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1601 $params['ss'.$i] = "%$searchterm%";
1605 if (empty($searchcond)) {
1606 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1607 $params['ss1'] = "%";
1609 $searchcond = implode(" AND ", $searchcond);
1612 /// There are several possibilities
1613 /// 1. courseid = SITEID : The admin is searching messages by all users
1614 /// 2. courseid = ?? : A teacher is searching messages by users in
1615 /// one of their courses - currently disabled
1616 /// 3. courseid = none : User is searching their own messages;
1617 /// a. Messages from user
1618 /// b. Messages to user
1619 /// c. Messages to and from user
1621 if ($courseid == SITEID) { /// admin is searching all messages
1622 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1623 FROM {message_read} m
1624 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1625 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1627 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1629 } else if ($courseid !== 'none') {
1630 /// This has not been implemented due to security concerns
1632 $m_unread = array();
1636 if ($fromme and $tome) {
1637 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1638 $params['userid1'] = $userid;
1639 $params['userid2'] = $userid;
1641 } else if ($fromme) {
1642 $searchcond .= " AND m.useridfrom=:userid";
1643 $params['userid'] = $userid;
1646 $searchcond .= " AND m.useridto=:userid";
1647 $params['userid'] = $userid;
1650 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1651 FROM {message_read} m
1652 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1653 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1655 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1659 /// The keys may be duplicated in $m_read and $m_unread so we can't
1660 /// do a simple concatenation
1661 $messages = array();
1662 foreach ($m_read as $m) {
1665 foreach ($m_unread as $m) {
1669 return (empty($messages)) ? false : $messages;
1673 * Given a message object that we already know has a long message
1674 * this function truncates the message nicely to the first
1675 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1677 * @param string $message the message
1678 * @param int $minlength the minimum length to trim the message to
1679 * @return string the shortened message
1681 function message_shorten_message($message, $minlength = 0) {
1684 $length = strlen($message);
1688 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1691 for ($i=0; $i<$length; $i++) {
1692 $char = $message[$i];
1704 if ($char == '.' or $char == ' ') {
1714 if ($count > $minlength) {
1724 return substr($message, 0, $truncate);
1729 * Given a string and an array of keywords, this function looks
1730 * for the first keyword in the string, and then chops out a
1731 * small section from the text that shows that word in context.
1733 * @param string $message the text to search
1734 * @param array $keywords array of keywords to find
1736 function message_get_fragment($message, $keywords) {
1739 $halfsize = (int)($fullsize/2);
1741 $message = strip_tags($message);
1743 foreach ($keywords as $keyword) { // Just get the first one
1744 if ($keyword !== '') {
1748 if (empty($keyword)) { // None found, so just return start of message
1749 return message_shorten_message($message, 30);
1752 $leadin = $leadout = '';
1754 /// Find the start of the fragment
1756 $length = strlen($message);
1758 $pos = strpos($message, $keyword);
1759 if ($pos > $halfsize) {
1760 $start = $pos - $halfsize;
1763 /// Find the end of the fragment
1764 $end = $start + $fullsize;
1765 if ($end > $length) {
1771 /// Pull out the fragment and format it
1773 $fragment = substr($message, $start, $end - $start);
1774 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1779 * Retrieve the messages between two users
1781 * @param object $user1 the current user
1782 * @param object $user2 the other user
1783 * @param int $limitnum the maximum number of messages to retrieve
1784 * @param bool $viewingnewmessages are we currently viewing new messages?
1786 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1789 $messages = array();
1791 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1792 //desc to get the last $limitnum messages then flip the order in php
1798 $notificationswhere = null;
1799 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1800 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1801 $notificationswhere = 'AND notification=0';
1804 //prevent notifications of your own actions appearing in your own message history
1805 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1807 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1808 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1809 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1810 "timecreated $sort", '*', 0, $limitnum)) {
1811 foreach ($messages_read as $message) {
1812 $messages[] = $message;
1815 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1816 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1817 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1818 "timecreated $sort", '*', 0, $limitnum)) {
1819 foreach ($messages_new as $message) {
1820 $messages[] = $message;
1824 $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);
1826 //if we only want the last $limitnum messages
1827 $messagecount = count($messages);
1828 if ($limitnum > 0 && $messagecount > $limitnum) {
1829 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1836 * Print the message history between two users
1838 * @param object $user1 the current user
1839 * @param object $user2 the other user
1840 * @param string $search search terms to highlight
1841 * @param int $messagelimit maximum number of messages to return
1842 * @param string $messagehistorylink the html for the message history link or false
1843 * @param bool $viewingnewmessages are we currently viewing new messages?
1845 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1846 global $CFG, $OUTPUT;
1848 echo $OUTPUT->box_start('center');
1849 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1850 echo html_writer::start_tag('tr');
1852 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1853 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1854 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1855 echo html_writer::end_tag('td');
1857 echo html_writer::start_tag('td', array('align' => 'center'));
1858 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1859 echo html_writer::end_tag('td');
1861 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1862 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1863 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1865 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1866 $incontactlist = $user2->iscontact;
1867 $isblocked = $user2->isblocked;
1873 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1874 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1875 $useractionlinks = $strcontact.' |'.$strblock;
1877 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1880 echo html_writer::end_tag('td');
1881 echo html_writer::end_tag('tr');
1882 echo html_writer::end_tag('table');
1883 echo $OUTPUT->box_end();
1885 if (!empty($messagehistorylink)) {
1886 echo $messagehistorylink;
1889 /// Get all the messages and print them
1890 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1891 $tablecontents = '';
1893 $current = new stdClass();
1894 $current->mday = '';
1895 $current->month = '';
1896 $current->year = '';
1897 $messagedate = get_string('strftimetime');
1898 $blockdate = get_string('strftimedaydate');
1899 foreach ($messages as $message) {
1900 if ($message->notification) {
1901 $notificationclass = ' notification';
1903 $notificationclass = null;
1905 $date = usergetdate($message->timecreated);
1906 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1907 $current->mday = $date['mday'];
1908 $current->month = $date['month'];
1909 $current->year = $date['year'];
1911 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1912 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1914 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1917 $formatted_message = $side = null;
1918 if ($message->useridfrom == $user1->id) {
1919 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1922 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1925 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1928 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1930 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1935 * Format a message for display in the message history
1937 * @param object $message the message object
1938 * @param string $format optional date format
1939 * @param string $keywords keywords to highlight
1940 * @param string $class CSS class to apply to the div around the message
1941 * @return string the formatted message
1943 function message_format_message($message, $format='', $keywords='', $class='other') {
1947 //if we haven't previously set the date format or they've supplied a new one
1948 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1950 $dateformat = $format;
1952 $dateformat = get_string('strftimedatetimeshort');
1955 $time = userdate($message->timecreated, $dateformat);
1956 $options = new stdClass();
1957 $options->para = false;
1959 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1960 if (!empty($message->smallmessage)) {
1961 $messagetext = $message->smallmessage;
1963 $messagetext = $message->fullmessage;
1965 if ($message->fullmessageformat == FORMAT_HTML) {
1966 //dont escape html tags by calling s() if html format or they will display in the UI
1967 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1969 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1972 $messagetext .= message_format_contexturl($message);
1975 $messagetext = highlight($keywords, $messagetext);
1979 <div class='message $class'>
1980 <a name="m'.{$message->id}.'"></a>
1981 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
1987 * Format a the context url and context url name of a message for display
1989 * @param object $message the message object
1990 * @return string the formatted string
1992 function message_format_contexturl($message) {
1995 if (!empty($message->contexturl)) {
1996 $displaytext = null;
1997 if (!empty($message->contexturlname)) {
1998 $displaytext= $message->contexturlname;
2000 $displaytext= $message->contexturl;
2002 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2003 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2004 $s .= html_writer::end_tag('div');
2011 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2013 * @param object $userfrom the message sender
2014 * @param object $userto the message recipient
2015 * @param string $message the message
2016 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2017 * @return int|false the ID of the new message or false
2019 function message_post_message($userfrom, $userto, $message, $format) {
2020 global $SITE, $CFG, $USER;
2022 $eventdata = new stdClass();
2023 $eventdata->component = 'moodle';
2024 $eventdata->name = 'instantmessage';
2025 $eventdata->userfrom = $userfrom;
2026 $eventdata->userto = $userto;
2028 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2029 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2031 if ($format == FORMAT_HTML) {
2032 $eventdata->fullmessagehtml = $message;
2033 //some message processors may revert to sending plain text even if html is supplied
2034 //so we keep both plain and html versions if we're intending to send html
2035 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2037 $eventdata->fullmessage = $message;
2038 $eventdata->fullmessagehtml = '';
2041 $eventdata->fullmessageformat = $format;
2042 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2044 $s = new stdClass();
2045 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2046 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2048 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2049 if (!empty($eventdata->fullmessage)) {
2050 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2052 if (!empty($eventdata->fullmessagehtml)) {
2053 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2056 $eventdata->timecreated = time();
2057 return message_send($eventdata);
2061 * Print a row of contactlist displaying user picture, messages waiting and
2064 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2065 * @param bool $incontactlist is the user a contact of ours?
2066 * @param bool $isblocked is the user blocked?
2067 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2068 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2069 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2072 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2073 global $OUTPUT, $USER;
2074 $fullname = fullname($contact);
2075 $fullnamelink = $fullname;
2078 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2079 $linkclass = 'messageselecteduser';
2082 /// are there any unread messages for this contact?
2083 if ($contact->messagecount > 0 ){
2084 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2087 $strcontact = $strblock = $strhistory = null;
2089 if ($showactionlinks) {
2090 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2091 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2092 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2095 echo html_writer::start_tag('tr');
2096 echo html_writer::start_tag('td', array('class' => 'pix'));
2097 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2098 echo html_writer::end_tag('td');
2100 echo html_writer::start_tag('td', array('class' => 'contact'));
2102 $popupoptions = array(
2103 'height' => MESSAGE_DISCUSSION_HEIGHT,
2104 'width' => MESSAGE_DISCUSSION_WIDTH,
2106 'location' => false,
2108 'scrollbars' => true,
2109 'resizable' => true);
2111 $link = $action = null;
2112 if (!empty($selectcontacturl)) {
2113 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2115 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2116 $link = new moodle_url("/message/index.php?id=$contact->id");
2117 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2119 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2121 echo html_writer::end_tag('td');
2123 echo html_writer::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2125 echo html_writer::end_tag('tr');
2129 * Constructs the add/remove contact link to display next to other users
2131 * @param bool $incontactlist is the user a contact
2132 * @param bool $isblocked is the user blocked
2133 * @param stdClass $contact contact object
2134 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2135 * @param bool $text include text next to the icons?
2136 * @param bool $icon include a graphical icon?
2139 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2143 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2144 } else if ($isblocked) {
2145 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2147 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2154 * Constructs the block contact link to display next to other users
2156 * @param bool $incontactlist is the user a contact?
2157 * @param bool $isblocked is the user blocked?
2158 * @param stdClass $contact contact object
2159 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2160 * @param bool $text include text next to the icons?
2161 * @param bool $icon include a graphical icon?
2164 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2167 //commented out to allow the user to block a contact without having to remove them first
2168 /*if ($incontactlist) {
2172 $strblock = ' '.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2174 $strblock = ' '.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2181 * Moves messages from a particular user from the message table (unread messages) to message_read
2182 * This is typically only used when a user is deleted
2184 * @param object $userid User id
2185 * @return boolean success
2187 function message_move_userfrom_unread2read($userid) {
2190 // move all unread messages from message table to message_read
2191 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2192 foreach ($messages as $message) {
2193 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2200 * marks ALL messages being sent from $fromuserid to $touserid as read
2202 * @param int $touserid the id of the message recipient
2203 * @param int $fromuserid the id of the message sender
2206 function message_mark_messages_read($touserid, $fromuserid){
2209 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2210 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2212 foreach ($messages as $message) {
2213 message_mark_message_read($message, time());
2220 * Mark a single message as read
2222 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2223 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2224 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2225 * @return int the ID of the message in the message_read table
2227 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2230 $message->timeread = $timeread;
2232 $messageid = $message->id;
2233 unset($message->id);//unset because it will get a new id on insert into message_read
2235 //If any processors have pending actions abort them
2236 if (!$messageworkingempty) {
2237 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2239 $messagereadid = $DB->insert_record('message_read', $message);
2240 $DB->delete_records('message', array('id' => $messageid));
2241 return $messagereadid;
2245 * A helper function that prints a formatted heading
2247 * @param string $title the heading to display
2248 * @param int $colspan
2251 function message_print_heading($title, $colspan=3) {
2252 echo html_writer::start_tag('tr');
2253 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2254 echo html_writer::end_tag('tr');
2258 * Get all message processors, validate corresponding plugin existance and
2259 * system configuration
2261 * @param bool $ready only return ready-to-use processors
2262 * @return mixed $processors array of objects containing information on message processors
2264 function get_message_processors($ready = false) {
2269 if (empty($processors)) {
2270 // Get all processors, ensure the name column is the first so it will be the array key
2271 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2272 foreach ($processors as &$processor){
2273 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2274 if (is_readable($processorfile)) {
2275 include_once($processorfile);
2276 $processclass = 'message_output_' . $processor->name;
2277 if (class_exists($processclass)) {
2278 $pclass = new $processclass();
2279 $processor->object = $pclass;
2280 $processor->configured = 0;
2281 if ($pclass->is_system_configured()) {
2282 $processor->configured = 1;
2284 $processor->hassettings = 0;
2285 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2286 $processor->hassettings = 1;
2288 $processor->available = 1;
2290 print_error('errorcallingprocessor', 'message');
2293 $processor->available = 0;
2298 // Filter out enabled and system_configured processors
2299 $readyprocessors = $processors;
2300 foreach ($readyprocessors as $readyprocessor) {
2301 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2302 unset($readyprocessors[$readyprocessor->name]);
2305 return $readyprocessors;
2312 * Get all message providers, validate their plugin existance and
2313 * system configuration
2315 * @return mixed $processors array of objects containing information on message processors
2317 function get_message_providers() {
2319 require_once($CFG->libdir . '/pluginlib.php');
2320 $pluginman = plugin_manager::instance();
2322 $providers = $DB->get_records('message_providers', null, 'name');
2324 // Remove all the providers whose plugins are disabled or don't exist
2325 foreach ($providers as $providerid => $provider) {
2326 $plugin = $pluginman->get_plugin_info($provider->component);
2328 if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2329 unset($providers[$providerid]); // Plugins does not exist
2332 if ($plugin->is_enabled() === false) {
2333 unset($providers[$providerid]); // Plugin disabled
2342 * Get an instance of the message_output class for one of the output plugins.
2343 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2344 * @return message_output message_output the requested class.
2346 function get_message_processor($type) {
2349 // Note, we cannot use the get_message_processors function here, becaues this
2350 // code is called during install after installing each messaging plugin, and
2351 // get_message_processors caches the list of installed plugins.
2353 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2354 if (!is_readable($processorfile)) {
2355 throw new coding_exception('Unknown message processor type ' . $type);
2358 include_once($processorfile);
2360 $processclass = 'message_output_' . $type;
2361 if (!class_exists($processclass)) {
2362 throw new coding_exception('Message processor ' . $type .
2363 ' does not define the right class');
2366 return new $processclass();
2370 * Get messaging outputs default (site) preferences
2372 * @return object $processors object containing information on message processors
2374 function get_message_output_default_preferences() {
2375 return get_config('message');
2379 * Translate message default settings from binary value to the array of string
2380 * representing the settings to be stored. Also validate the provided value and
2381 * use default if it is malformed.
2383 * @param int $plugindefault Default setting suggested by plugin
2384 * @param string $processorname The name of processor
2385 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2387 function translate_message_default_setting($plugindefault, $processorname) {
2388 // Preset translation arrays
2389 $permittedvalues = array(
2390 0x04 => 'disallowed',
2391 0x08 => 'permitted',
2395 $loggedinstatusvalues = array(
2396 0x00 => null, // use null if loggedin/loggedoff is not defined
2398 0x02 => 'loggedoff',
2401 // define the default setting
2402 $processor = get_message_processor($processorname);
2403 $default = $processor->get_default_messaging_settings();
2405 // Validate the value. It should not exceed the maximum size
2406 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2407 debugging(get_string('errortranslatingdefault', 'message'));
2408 $plugindefault = $default;
2410 // Use plugin default setting of 'permitted' is 0
2411 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2412 $plugindefault = $default;
2415 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2416 $loggedin = $loggedoff = null;
2418 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2419 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2420 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2423 return array($permitted, $loggedin, $loggedoff);
2427 * Return a list of page types
2428 * @param string $pagetype current page type
2429 * @param stdClass $parentcontext Block's parent context
2430 * @param stdClass $currentcontext Current context of block
2432 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2433 return array('messages-*'=>get_string('page-message-x', 'message'));
2437 * Is $USER one of the supplied users?
2439 * $user2 will be null if viewing a user's recent conversations
2441 * @param stdClass the first user
2442 * @param stdClass the second user or null
2443 * @return bool True if the current user is one of either $user1 or $user2
2445 function message_current_user_is_involved($user1, $user2) {
2448 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2449 throw new coding_exception('Invalid user object detected. Missing id.');
2452 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {