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 //$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
31 //TODO: this is a mega crazy hack - it is not acceptable to call anything when including lib!!! (skodak)
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);
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
76 * Set default value for default outputs permitted setting
78 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
80 //TODO: defaults must be initialised via settings - this is a bad hack! (skodak)
81 if (!isset($CFG->message_contacts_refresh
)) { // Refresh the contacts list every 60 seconds
82 $CFG->message_contacts_refresh
= 60;
84 if (!isset($CFG->message_chat_refresh
)) { // Look for new comments every 5 seconds
85 $CFG->message_chat_refresh
= 5;
87 if (!isset($CFG->message_offline_time
)) {
88 $CFG->message_offline_time
= 300;
92 * Print the selector that allows the user to view their contacts, course participants, their recent
95 * @param int $countunreadtotal how many unread messages does the user have?
96 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
97 * @param object $user1 the user whose messages are being viewed
98 * @param object $user2 the user $user1 is talking to
99 * @param array $blockedusers an array of users blocked by $user1
100 * @param array $onlinecontacts an array of $user1's online contacts
101 * @param array $offlinecontacts an array of $user1's offline contacts
102 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
103 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
104 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
107 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
110 echo html_writer
::start_tag('div', array('class' => 'contactselector mdl-align'));
112 //if 0 unread messages and they've requested unread messages then show contacts
113 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
114 $viewing = MESSAGE_VIEW_CONTACTS
;
117 //if they have no blocked users and they've requested blocked users switch them over to contacts
118 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED
) {
119 $viewing = MESSAGE_VIEW_CONTACTS
;
122 $onlyactivecourses = true;
123 $courses = enrol_get_users_courses($user1->id
, $onlyactivecourses);
124 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
126 $strunreadmessages = null;
127 if ($countunreadtotal>0) { //if there are unread messages
128 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
131 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
133 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
134 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 1, $showcontactactionlinks,$strunreadmessages, $user2);
135 } else if ($viewing == MESSAGE_VIEW_CONTACTS ||
$viewing == MESSAGE_VIEW_SEARCH ||
$viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS ||
$viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS
) {
136 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 0, $showcontactactionlinks, $strunreadmessages, $user2);
137 } else if ($viewing == MESSAGE_VIEW_BLOCKED
) {
138 message_print_blocked_users($blockedusers, $PAGE->url
, $showcontactactionlinks, null, $user2);
139 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE
) {
140 $courseidtoshow = intval(substr($viewing, 7));
142 if (!empty($courseidtoshow)
143 && array_key_exists($courseidtoshow, $coursecontexts)
144 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
146 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url
, $showcontactactionlinks, null, $page, $user2);
148 //shouldn't get here. User trying to access a course they're not in perhaps.
149 add_to_log(SITEID
, 'message', 'view', 'index.php', $viewing);
153 echo html_writer
::start_tag('form', array('action' => 'index.php','method' => 'GET'));
154 echo html_writer
::start_tag('fieldset');
155 $managebuttonclass = 'visible';
156 if ($viewing == MESSAGE_VIEW_SEARCH
) {
157 $managebuttonclass = 'hiddenelement';
159 $strmanagecontacts = get_string('search','message');
160 echo html_writer
::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH
));
161 echo html_writer
::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
162 echo html_writer
::end_tag('fieldset');
163 echo html_writer
::end_tag('form');
165 echo html_writer
::end_tag('div');
169 * Print course participants. Called by message_print_contact_selector()
171 * @param object $context the course context
172 * @param int $courseid the course ID
173 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
174 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
175 * @param string $titletodisplay Optionally specify a title to display above the participants
176 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
177 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
180 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
181 global $DB, $USER, $PAGE, $OUTPUT;
183 if (empty($titletodisplay)) {
184 $titletodisplay = get_string('participants');
187 $countparticipants = count_enrolled_users($context);
188 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE
, MESSAGE_CONTACTS_PER_PAGE
);
190 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE
, $PAGE->url
, 'page');
191 echo $OUTPUT->render($pagingbar);
193 echo html_writer
::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
195 echo html_writer
::start_tag('tr');
196 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
197 echo html_writer
::end_tag('tr');
199 //todo these need to come from somewhere if the course participants list is to show users with unread messages
202 foreach ($participants as $participant) {
203 if ($participant->id
!= $USER->id
) {
204 $participant->messagecount
= 0;//todo it would be nice if the course participant could report new messages
205 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
209 echo html_writer
::end_tag('table');
213 * Retrieve users blocked by $user1
215 * @param object $user1 the user whose messages are being viewed
216 * @param object $user2 the user $user1 is talking to. If they are being blocked
217 * they will have a variable called 'isblocked' added to their user object
218 * @return array the users blocked by $user1
220 function message_get_blocked_users($user1=null, $user2=null) {
227 if (!empty($user2)) {
228 $user2->isblocked
= false;
231 $blockedusers = array();
233 $userfields = user_picture
::fields('u', array('lastaccess'));
234 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
235 FROM {message_contacts} mc
236 JOIN {user} u ON u.id = mc.contactid
237 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
238 WHERE mc.userid = :user1id2 AND mc.blocked = 1
240 ORDER BY u.firstname ASC";
241 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id
, 'user1id2' => $user1->id
));
243 foreach($rs as $rd) {
244 $blockedusers[] = $rd;
246 if (!empty($user2) && $user2->id
== $rd->id
) {
247 $user2->isblocked
= true;
252 return $blockedusers;
256 * Print users blocked by $user1. Called by message_print_contact_selector()
258 * @param array $blockedusers the users blocked by $user1
259 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
260 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
261 * @param string $titletodisplay Optionally specify a title to display above the participants
262 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
265 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
268 $countblocked = count($blockedusers);
270 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
272 if (!empty($titletodisplay)) {
273 echo html_writer
::start_tag('tr');
274 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
275 echo html_writer
::end_tag('tr');
279 echo html_writer
::start_tag('tr');
280 echo html_writer
::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
281 echo html_writer
::end_tag('tr');
283 $isuserblocked = true;
284 $isusercontact = false;
285 foreach ($blockedusers as $blockeduser) {
286 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
290 echo html_writer
::end_tag('table');
294 * Retrieve $user1's contacts (online, offline and strangers)
296 * @param object $user1 the user whose messages are being viewed
297 * @param object $user2 the user $user1 is talking to. If they are a contact
298 * they will have a variable called 'iscontact' added to their user object
299 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
301 function message_get_contacts($user1=null, $user2=null) {
302 global $DB, $CFG, $USER;
308 if (!empty($user2)) {
309 $user2->iscontact
= false;
312 $timetoshowusers = 300; //Seconds default
313 if (isset($CFG->block_online_users_timetosee
)) {
314 $timetoshowusers = $CFG->block_online_users_timetosee
* 60;
317 // time which a user is counting as being active since
318 $timefrom = time()-$timetoshowusers;
320 // people in our contactlist who are online
321 $onlinecontacts = array();
322 // people in our contactlist who are offline
323 $offlinecontacts = array();
324 // people who are not in our contactlist but have sent us a message
325 $strangers = array();
327 $userfields = user_picture
::fields('u', array('lastaccess'));
329 // get all in our contactlist who are not blocked in our contact list
330 // and count messages we have waiting from each of them
331 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
332 FROM {message_contacts} mc
333 JOIN {user} u ON u.id = mc.contactid
334 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
335 WHERE mc.userid = ? AND mc.blocked = 0
337 ORDER BY u.firstname ASC";
339 $rs = $DB->get_recordset_sql($contactsql, array($user1->id
, $user1->id
));
340 foreach ($rs as $rd) {
341 if ($rd->lastaccess
>= $timefrom) {
342 // they have been active recently, so are counted online
343 $onlinecontacts[] = $rd;
346 $offlinecontacts[] = $rd;
349 if (!empty($user2) && $user2->id
== $rd->id
) {
350 $user2->iscontact
= true;
355 // get messages from anyone who isn't in our contact list and count the number
356 // of messages we have from each of them
357 $strangersql = "SELECT $userfields, count(m.id) as messagecount
359 JOIN {user} u ON u.id = m.useridfrom
360 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
361 WHERE mc.id IS NULL AND m.useridto = ?
363 ORDER BY u.firstname ASC";
365 $rs = $DB->get_recordset_sql($strangersql, array($USER->id
));
366 foreach ($rs as $rd) {
371 return array($onlinecontacts, $offlinecontacts, $strangers);
375 * Print $user1's contacts. Called by message_print_contact_selector()
377 * @param array $onlinecontacts $user1's contacts which are online
378 * @param array $offlinecontacts $user1's contacts which are offline
379 * @param array $strangers users which are not contacts but who have messaged $user1
380 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
381 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
382 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
383 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
384 * @param string $titletodisplay Optionally specify a title to display above the participants
385 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
388 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
389 global $CFG, $PAGE, $OUTPUT;
391 $countonlinecontacts = count($onlinecontacts);
392 $countofflinecontacts = count($offlinecontacts);
393 $countstrangers = count($strangers);
394 $isuserblocked = null;
396 if ($countonlinecontacts +
$countofflinecontacts == 0) {
397 echo html_writer
::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
400 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
402 if (!empty($titletodisplay)) {
403 message_print_heading($titletodisplay);
406 if($countonlinecontacts) {
407 /// print out list of online contacts
409 if (empty($titletodisplay)) {
410 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
413 $isuserblocked = false;
414 $isusercontact = true;
415 foreach ($onlinecontacts as $contact) {
416 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
417 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
422 if ($countofflinecontacts) {
423 /// print out list of offline contacts
425 if (empty($titletodisplay)) {
426 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
429 $isuserblocked = false;
430 $isusercontact = true;
431 foreach ($offlinecontacts as $contact) {
432 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
433 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
439 /// print out list of incoming contacts
440 if ($countstrangers) {
441 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
443 $isuserblocked = false;
444 $isusercontact = false;
445 foreach ($strangers as $stranger) {
446 if ($minmessages == 0 ||
$stranger->messagecount
>= $minmessages) {
447 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
452 echo html_writer
::end_tag('table');
454 if ($countstrangers && ($countonlinecontacts +
$countofflinecontacts == 0)) { // Extra help
455 echo html_writer
::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
460 * Print a select box allowing the user to choose to view new messages, course participants etc.
462 * Called by message_print_contact_selector()
463 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
464 * @param array $courses array of course objects. The courses the user is enrolled in.
465 * @param array $coursecontexts array of course contexts. Keyed on course id.
466 * @param int $countunreadtotal how many unread messages does the user have?
467 * @param int $countblocked how many users has the current user blocked?
468 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
471 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
473 $textlib = textlib_get_instance(); // going to use textlib services
475 if ($countunreadtotal>0) { //if there are unread messages
476 $options[MESSAGE_VIEW_UNREAD_MESSAGES
] = $strunreadmessages;
479 $str = get_string('mycontacts', 'message');
480 $options[MESSAGE_VIEW_CONTACTS
] = $str;
482 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS
] = get_string('mostrecentconversations', 'message');
483 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS
] = get_string('mostrecentnotifications', 'message');
485 if (!empty($courses)) {
486 $courses_options = array();
488 foreach($courses as $course) {
489 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id
])) {
490 //Not using short_text() as we want the end of the course name. Not the beginning.
491 $shortname = format_string($course->shortname
, true, array('context' => $coursecontexts[$course->id
]));
492 if ($textlib->strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH
) {
493 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = '...'.$textlib->substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH
);
495 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = $shortname;
500 if (!empty($courses_options)) {
501 $options[] = array(get_string('courses') => $courses_options);
505 if ($countblocked>0) {
506 $str = get_string('blockedusers','message', $countblocked);
507 $options[MESSAGE_VIEW_BLOCKED
] = $str;
510 echo html_writer
::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
511 echo html_writer
::start_tag('fieldset');
512 echo html_writer
::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
513 echo html_writer
::end_tag('fieldset');
514 echo html_writer
::end_tag('form');
518 * Load the course contexts for all of the users courses
520 * @param array $courses array of course objects. The courses the user is enrolled in.
521 * @return array of course contexts
523 function message_get_course_contexts($courses) {
524 $coursecontexts = array();
526 foreach($courses as $course) {
527 $coursecontexts[$course->id
] = get_context_instance(CONTEXT_COURSE
, $course->id
);
530 return $coursecontexts;
534 * strip off action parameters like 'removecontact'
536 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
537 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
539 function message_remove_url_params($moodleurl) {
540 $newurl = new moodle_url($moodleurl);
541 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
542 return $newurl->out();
546 * Count the number of messages with a field having a specified value.
547 * if $field is empty then return count of the whole array
548 * if $field is non-existent then return 0
550 * @param array $messagearray array of message objects
551 * @param string $field the field to inspect on the message objects
552 * @param string $value the value to test the field against
554 function message_count_messages($messagearray, $field='', $value='') {
555 if (!is_array($messagearray)) return 0;
556 if ($field == '' or empty($messagearray)) return count($messagearray);
559 foreach ($messagearray as $message) {
560 $count +
= ($message->$field == $value) ?
1 : 0;
566 * Returns the count of unread messages for user. Either from a specific user or from all users.
568 * @param object $user1 the first user. Defaults to $USER
569 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
570 * @return int the count of $user1's unread messages
572 function message_count_unread_messages($user1=null, $user2=null) {
579 if (!empty($user2)) {
580 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
581 array($user1->id
, $user2->id
), "COUNT('id')");
583 return $DB->count_records_select('message', "useridto = ?",
584 array($user1->id
), "COUNT('id')");
589 * Count the number of users blocked by $user1
591 * @param object $user1 user object
592 * @return int the number of blocked users
594 function message_count_blocked_users($user1=null) {
601 $sql = "SELECT count(mc.id)
602 FROM {message_contacts} mc
603 WHERE mc.userid = :userid AND mc.blocked = 1";
604 $params = array('userid' => $user1->id
);
606 return $DB->count_records_sql($sql, $params);
610 * Print the search form and search results if a search has been performed
612 * @param boolean $advancedsearch show basic or advanced search form
613 * @param object $user1 the current user
614 * @return boolean true if a search was performed
616 function message_print_search($advancedsearch = false, $user1=null) {
617 $frm = data_submitted();
619 $doingsearch = false;
621 if (confirm_sesskey()) {
622 $doingsearch = !empty($frm->combinedsubmit
) ||
!empty($frm->keywords
) ||
(!empty($frm->personsubmit
) and !empty($frm->name
));
628 if (!empty($frm->combinedsearch
)) {
629 $combinedsearchstring = $frm->combinedsearch
;
631 //$combinedsearchstring = get_string('searchcombined','message').'...';
632 $combinedsearchstring = '';
636 if ($advancedsearch) {
639 if (!empty($frm->keywords
)) {
640 $messagesearch = $frm->keywords
;
643 if (!empty($frm->name
)) {
644 $personsearch = $frm->name
;
646 include('search_advanced.html');
648 include('search.html');
651 $showicontext = false;
652 message_print_search_results($frm, $showicontext, $user1);
657 if ($advancedsearch) {
658 $personsearch = $messagesearch = '';
659 include('search_advanced.html');
661 include('search.html');
668 * Get the users recent conversations meaning all the people they've recently
669 * sent or received a message from plus the most recent message sent to or received from each other user
671 * @param object $user the current user
672 * @param int $limitfrom can be used for paging
673 * @param int $limitto can be used for paging
676 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
679 $userfields = user_picture
::fields('u', array('lastaccess'));
680 //This query retrieves the last message received from and sent to each user
681 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
682 //It then joins with some other tables to get some additional data we need
684 //message ID is used instead of timecreated as it should sort the same and will be much faster
686 //There is a separate query for read and unread queries as they are stored in different tables
687 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
688 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
689 FROM {message_read} mr
691 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
693 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
694 FROM {message_read} mr1
695 WHERE mr1.useridfrom = :userid1
696 AND mr1.notification = 0
697 GROUP BY mr1.useridto
699 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
700 FROM {message_read} mr2
701 WHERE mr2.useridto = :userid2
702 AND mr2.notification = 0
703 GROUP BY mr2.useridfrom
705 GROUP BY messages.userid
706 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
707 JOIN {user} u ON u.id = messages2.userid
708 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
709 WHERE u.deleted = '0'
710 ORDER BY mr.id DESC";
711 $params = array('userid1' => $user->id
, 'userid2' => $user->id
, 'userid3' => $user->id
);
712 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
714 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
717 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
719 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
721 WHERE m1.useridfrom = :userid1
722 AND m1.notification = 0
725 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
727 WHERE m2.useridto = :userid2
728 AND m2.notification = 0
729 GROUP BY m2.useridfrom
731 GROUP BY messages.userid
732 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
733 JOIN {user} u ON u.id = messages2.userid
734 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
735 WHERE u.deleted = '0'
737 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
739 $conversations = array();
741 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
742 //$conversation->id (the array key) is the other user's ID
743 $conversation_arrays = array($unread, $read);
744 foreach ($conversation_arrays as $conversation_array) {
745 foreach ($conversation_array as $conversation) {
746 if (empty($conversations[$conversation->id
]) ||
$conversations[$conversation->id
]->timecreated
< $conversation->timecreated
) {
747 $conversations[$conversation->id
] = $conversation;
752 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
753 //and there may be multiple conversations with the same timecreated value.
754 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
755 usort($conversations, "conversationsort");
757 return $conversations;
761 * Sort function used to order conversations
763 * @param object $a A conversation object
764 * @param object $b A conversation object
767 function conversationsort($a, $b)
769 if ($a->timecreated
== $b->timecreated
) {
772 return ($a->timecreated
> $b->timecreated
) ?
-1 : 1;
776 * Get the users recent event notifications
778 * @param object $user the current user
779 * @param int $limitfrom can be used for paging
780 * @param int $limitto can be used for paging
783 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
786 $userfields = user_picture
::fields('u', array('lastaccess'));
787 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
788 FROM {message_read} mr
789 JOIN {user} u ON u.id=mr.useridfrom
790 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
791 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
792 $params = array('userid1' => $user->id
, 'notification' => 1);
794 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
795 return $notifications;
799 * Print the user's recent conversations
801 * @param stdClass $user the current user
802 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
804 function message_print_recent_conversations($user=null, $showicontext=false) {
807 echo html_writer
::start_tag('p', array('class' => 'heading'));
808 echo get_string('mostrecentconversations', 'message');
809 echo html_writer
::end_tag('p');
815 $conversations = message_get_recent_conversations($user);
817 $showotheruser = true;
818 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
822 * Print the user's recent notifications
824 * @param stdClass $user the current user
826 function message_print_recent_notifications($user=null) {
829 echo html_writer
::start_tag('p', array('class' => 'heading'));
830 echo get_string('mostrecentnotifications', 'message');
831 echo html_writer
::end_tag('p');
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 * @param array $messages the messages to display
848 * @param object $user the current user
849 * @param bool $showotheruser display information on the other user?
850 * @param bool $showicontext show text next to the action icons?
853 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
857 if (empty($dateformat)) {
858 $dateformat = get_string('strftimedatetimeshort');
861 echo html_writer
::start_tag('div', array('class' => 'messagerecent'));
862 foreach ($messages as $message) {
863 echo html_writer
::start_tag('div', array('class' => 'singlemessage'));
865 if ($showotheruser) {
866 if ( $message->contactlistid
) {
867 if ($message->blocked
== 0) { /// not blocked
868 $strcontact = message_contact_link($message->id
, 'remove', true, null, $showicontext);
869 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
871 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
872 $strblock = message_contact_link($message->id
, 'unblock', true, null, $showicontext);
875 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
876 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
879 //should we show just the icon or icon and text?
880 $histicontext = 'icon';
882 $histicontext = 'both';
884 $strhistory = message_history_link($user->id
, $message->id
, true, '', '', $histicontext);
886 echo html_writer
::start_tag('span', array('class' => 'otheruser'));
888 echo html_writer
::start_tag('span', array('class' => 'pix'));
889 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID
));
890 echo html_writer
::end_tag('span');
892 echo html_writer
::start_tag('span', array('class' => 'contact'));
894 $link = new moodle_url("/message/index.php?id=$message->id");
896 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
898 echo html_writer
::end_tag('span');//end contact
900 echo $strcontact.$strblock.$strhistory;
901 echo html_writer
::end_tag('span');//end otheruser
903 $messagetoprint = null;
904 if (!empty($message->smallmessage
)) {
905 $messagetoprint = $message->smallmessage
;
907 $messagetoprint = $message->fullmessage
;
910 echo html_writer
::tag('span', userdate($message->timecreated
, $dateformat), array('class' => 'messagedate'));
911 echo html_writer
::tag('span', format_text($messagetoprint, FORMAT_HTML
), array('class' => 'themessage'));
912 echo message_format_contexturl($message);
913 echo html_writer
::end_tag('div');//end singlemessage
915 echo html_writer
::end_tag('div');//end messagerecent
919 * Add the selected user as a contact for the current user
921 * @param int $contactid the ID of the user to add as a contact
922 * @param int $blocked 1 if you wish to block the contact
923 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
924 * Otherwise returns the result of update_record() or insert_record()
926 function message_add_contact($contactid, $blocked=0) {
929 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
933 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid))) !== false) {
934 /// record already exists - we may be changing blocking status
936 if ($contact->blocked
!== $blocked) {
937 /// change to blocking status
938 $contact->blocked
= $blocked;
939 return $DB->update_record('message_contacts', $contact);
941 /// no changes to blocking status
946 /// new contact record
947 $contact = new stdClass();
948 $contact->userid
= $USER->id
;
949 $contact->contactid
= $contactid;
950 $contact->blocked
= $blocked;
951 return $DB->insert_record('message_contacts', $contact, false);
958 * @param int $contactid the user ID of the contact to remove
959 * @return bool returns the result of delete_records()
961 function message_remove_contact($contactid) {
963 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
967 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
969 * @param int $contactid the user ID of the contact to unblock
970 * @return bool returns the result of delete_records()
972 function message_unblock_contact($contactid) {
974 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
980 * @param int $contactid the user ID of the user to block
982 function message_block_contact($contactid) {
983 return message_add_contact($contactid, 1);
987 * Load a user's contact record
989 * @param int $contactid the user ID of the user whose contact record you want
990 * @return array message contacts
992 function message_get_contact($contactid) {
994 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
998 * Print the results of a message search
1000 * @param mixed $frm submitted form data
1001 * @param bool $showicontext show text next to action icons?
1002 * @param object $currentuser the current user
1005 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1006 global $USER, $DB, $OUTPUT;
1008 if (empty($currentuser)) {
1009 $currentuser = $USER;
1012 echo html_writer
::start_tag('div', array('class' => 'mdl-left'));
1014 $personsearch = false;
1015 $personsearchstring = null;
1016 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
1017 $personsearch = true;
1018 $personsearchstring = $frm->name
;
1019 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1020 $personsearch = true;
1021 $personsearchstring = $frm->combinedsearch
;
1024 /// search for person
1025 if ($personsearch) {
1026 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
1028 $mycourses = enrol_get_my_courses();
1029 foreach ($mycourses as $mycourse) {
1030 if (is_array($susers = message_search_users($mycourse->id
, $personsearchstring))) {
1031 foreach ($susers as $suser) $users[$suser->id
] = $suser;
1035 $users = message_search_users(SITEID
, $personsearchstring);
1038 if (!empty($users)) {
1039 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1040 echo get_string('userssearchresults', 'message', count($users));
1041 echo html_writer
::end_tag('p');
1043 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults'));
1044 foreach ($users as $user) {
1046 if ( $user->contactlistid
) {
1047 if ($user->blocked
== 0) { /// not blocked
1048 $strcontact = message_contact_link($user->id
, 'remove', true, null, $showicontext);
1049 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1051 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1052 $strblock = message_contact_link($user->id
, 'unblock', true, null, $showicontext);
1055 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1056 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1059 //should we show just the icon or icon and text?
1060 $histicontext = 'icon';
1061 if ($showicontext) {
1062 $histicontext = 'both';
1064 $strhistory = message_history_link($USER->id
, $user->id
, true, '', '', $histicontext);
1066 echo html_writer
::start_tag('tr');
1068 echo html_writer
::start_tag('td', array('class' => 'pix'));
1069 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1070 echo html_writer
::end_tag('td');
1072 echo html_writer
::start_tag('td',array('class' => 'contact'));
1074 $link = new moodle_url("/message/index.php?id=$user->id");
1075 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1076 echo html_writer
::end_tag('td');
1078 echo html_writer
::tag('td', $strcontact, array('class' => 'link'));
1079 echo html_writer
::tag('td', $strblock, array('class' => 'link'));
1080 echo html_writer
::tag('td', $strhistory, array('class' => 'link'));
1082 echo html_writer
::end_tag('tr');
1084 echo html_writer
::end_tag('table');
1087 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1088 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1089 echo html_writer
::end_tag('p');
1093 // search messages for keywords
1094 $messagesearch = false;
1095 $messagesearchstring = null;
1096 if (!empty($frm->keywords
)) {
1097 $messagesearch = true;
1098 $messagesearchstring = clean_text(trim($frm->keywords
));
1099 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1100 $messagesearch = true;
1101 $messagesearchstring = clean_text(trim($frm->combinedsearch
));
1104 if ($messagesearch) {
1105 if ($messagesearchstring) {
1106 $keywords = explode(' ', $messagesearchstring);
1108 $keywords = array();
1114 if (empty($frm->keywordsoption
)) {
1115 $frm->keywordsoption
= 'allmine';
1118 switch ($frm->keywordsoption
) {
1133 $courseid = $frm->courseid
;
1140 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1142 /// get a list of contacts
1143 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id
), '', 'contactid, blocked') ) === false) {
1144 $contacts = array();
1147 /// print heading with number of results
1148 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1149 $countresults = count($messages);
1150 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS
) {
1151 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1153 echo get_string('keywordssearchresults', 'message', $countresults);
1155 echo html_writer
::end_tag('p');
1157 /// print table headings
1158 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1160 $headertdstart = html_writer
::start_tag('td', array('class' => 'messagesearchresultscol'));
1161 $headertdend = html_writer
::end_tag('td');
1162 echo html_writer
::start_tag('tr');
1163 echo $headertdstart.get_string('from').$headertdend;
1164 echo $headertdstart.get_string('to').$headertdend;
1165 echo $headertdstart.get_string('message', 'message').$headertdend;
1166 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1167 echo html_writer
::end_tag('tr');
1170 $dateformat = get_string('strftimedatetimeshort');
1171 $strcontext = get_string('context', 'message');
1172 foreach ($messages as $message) {
1174 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1175 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
1176 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
1177 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
1184 /// load up user to record
1185 if ($message->useridto
!== $USER->id
) {
1186 $userto = $DB->get_record('user', array('id' => $message->useridto
));
1187 $tocontact = (array_key_exists($message->useridto
, $contacts) and
1188 ($contacts[$message->useridto
]->blocked
== 0) );
1189 $toblocked = (array_key_exists($message->useridto
, $contacts) and
1190 ($contacts[$message->useridto
]->blocked
== 1) );
1197 /// load up user from record
1198 if ($message->useridfrom
!== $USER->id
) {
1199 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom
));
1200 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
1201 ($contacts[$message->useridfrom
]->blocked
== 0) );
1202 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
1203 ($contacts[$message->useridfrom
]->blocked
== 1) );
1206 $fromcontact = false;
1207 $fromblocked = false;
1210 /// find date string for this message
1211 $date = usergetdate($message->timecreated
);
1212 $datestring = $date['year'].$date['mon'].$date['mday'];
1214 /// print out message row
1215 echo html_writer
::start_tag('tr', array('valign' => 'top'));
1217 echo html_writer
::start_tag('td', array('class' => 'contact'));
1218 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1219 echo html_writer
::end_tag('td');
1221 echo html_writer
::start_tag('td', array('class' => 'contact'));
1222 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1223 echo html_writer
::end_tag('td');
1225 echo html_writer
::start_tag('td', array('class' => 'summary'));
1226 echo message_get_fragment($message->fullmessage
, $keywords);
1227 echo html_writer
::start_tag('div', array('class' => 'link'));
1229 //If the user clicks the context link display message sender on the left
1230 //EXCEPT if the current user is in the conversation. Current user == always on the left
1231 $leftsideuserid = $rightsideuserid = null;
1232 if ($currentuser->id
== $message->useridto
) {
1233 $leftsideuserid = $message->useridto
;
1234 $rightsideuserid = $message->useridfrom
;
1236 $leftsideuserid = $message->useridfrom
;
1237 $rightsideuserid = $message->useridto
;
1239 message_history_link($leftsideuserid, $rightsideuserid, false,
1240 $messagesearchstring, 'm'.$message->id
, $strcontext);
1241 echo html_writer
::end_tag('div');
1242 echo html_writer
::end_tag('td');
1244 echo html_writer
::tag('td', userdate($message->timecreated
, $dateformat), array('class' => 'date'));
1246 echo html_writer
::end_tag('tr');
1250 if ($blockedcount > 0) {
1251 echo html_writer
::start_tag('tr');
1252 echo html_writer
::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1253 echo html_writer
::end_tag('tr');
1255 echo html_writer
::end_tag('table');
1258 echo html_writer
::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1262 if (!$personsearch && !$messagesearch) {
1263 //they didn't enter any search terms
1264 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1267 echo html_writer
::end_tag('div');
1271 * Print information on a user. Used when printing search results.
1273 * @param object/bool $user the user to display or false if you just want $USER
1274 * @param bool $iscontact is the user being displayed a contact?
1275 * @param bool $isblocked is the user being displayed blocked?
1276 * @param bool $includeicontext include text next to the action icons?
1279 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1280 global $USER, $OUTPUT;
1282 if ($user === false) {
1283 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID
));
1285 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1291 message_contact_link($user->id
, 'remove', $return, $script, $includeicontext);
1293 message_contact_link($user->id
, 'add', $return, $script, $includeicontext);
1297 message_contact_link($user->id
, 'unblock', $return, $script, $includeicontext);
1299 message_contact_link($user->id
, 'block', $return, $script, $includeicontext);
1302 $popupoptions = array(
1303 'height' => MESSAGE_DISCUSSION_HEIGHT
,
1304 'width' => MESSAGE_DISCUSSION_WIDTH
,
1306 'location' => false,
1308 'scrollbars' => true,
1309 'resizable' => true);
1311 $link = new moodle_url("/message/index.php?id=$user->id");
1312 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1314 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1320 * Print a message contact link
1322 * @param int $userid the ID of the user to apply to action to
1323 * @param string $linktype can be add, remove, block or unblock
1324 * @param bool $return if true return the link as a string. If false echo the link.
1325 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1326 * @param bool $text include text next to the icons?
1327 * @param bool $icon include a graphical icon?
1328 * @return string if $return is true otherwise bool
1330 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1331 global $OUTPUT, $PAGE;
1333 //hold onto the strings as we're probably creating a bunch of links
1336 if (empty($script)) {
1337 //strip off previous action params like 'removecontact'
1338 $script = message_remove_url_params($PAGE->url
);
1341 if (empty($str->blockcontact
)) {
1342 $str = new stdClass();
1343 $str->blockcontact
= get_string('blockcontact', 'message');
1344 $str->unblockcontact
= get_string('unblockcontact', 'message');
1345 $str->removecontact
= get_string('removecontact', 'message');
1346 $str->addcontact
= get_string('addcontact', 'message');
1349 $command = $linktype.'contact';
1350 $string = $str->{$command};
1352 $safealttext = s($string);
1355 if (!empty($text)) {
1356 $safestring = $safealttext;
1362 switch ($linktype) {
1364 $iconpath = 't/block';
1367 $iconpath = 't/userblue';
1370 $iconpath = 'i/cross_red_big';
1374 $iconpath = 't/addgreen';
1377 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1380 $output = '<span class="'.$linktype.'contact">'.
1381 '<a href="'.$script.'&'.$command.'='.$userid.
1382 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1384 $safestring.'</a></span>';
1395 * echo or return a link to take the user to the full message history between themselves and another user
1397 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1398 * @param int $userid2 the ID of the other user
1399 * @param bool $return true to return the link as a string. False to echo the link.
1400 * @param string $keywords any keywords to highlight in the message history
1401 * @param string $position anchor name to jump to within the message history
1402 * @param string $linktext optionally specify the link text
1403 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1405 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1407 static $strmessagehistory;
1409 if (empty($strmessagehistory)) {
1410 $strmessagehistory = get_string('messagehistory', 'message');
1414 $position = "#$position";
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 .= ' '.$strmessagehistory;
1425 } else if ($linktext) { // Custom name
1426 $fulllink = $linktext;
1427 } else { // Standard name only
1428 $fulllink = $strmessagehistory;
1431 $popupoptions = array(
1435 'location' => false,
1437 'scrollbars' => true,
1438 'resizable' => true);
1440 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL
."&user1=$userid1&user2=$userid2$keywords$position");
1442 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1444 $str = '<span class="history">'.$str.'</span>';
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 .') ';
1477 if (!empty($sort)) {
1478 $order = ' ORDER BY '. $sort;
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
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).")
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
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).")
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();
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) {
1557 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1559 if ($dropshortwords && strlen($searchterm) < 2) {
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) == '-') {
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]|$)";
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'] = "%";
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
1611 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1613 } else if ($courseid !== 'none') {
1614 /// This has not been implemented due to security concerns
1616 $m_unread = array();
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;
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
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 $messages = array();
1646 foreach ($m_read as $m) {
1649 foreach ($m_unread as $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) {
1668 $length = strlen($message);
1672 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
1675 for ($i=0; $i<$length; $i++
) {
1676 $char = $message[$i];
1688 if ($char == '.' or $char == ' ') {
1698 if ($count > $minlength) {
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) {
1723 $halfsize = (int)($fullsize/2);
1725 $message = strip_tags($message);
1727 foreach ($keywords as $keyword) { // Just get the first one
1728 if ($keyword !== '') {
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
1740 $length = strlen($message);
1742 $pos = strpos($message, $keyword);
1743 if ($pos > $halfsize) {
1744 $start = $pos - $halfsize;
1747 /// Find the end of the fragment
1748 $end = $start +
$fullsize;
1749 if ($end > $length) {
1755 /// Pull out the fragment and format it
1757 $fragment = substr($message, $start, $end - $start);
1758 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
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) {
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
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
1810 $messagecount = count($messages);
1811 if ($limitnum>0 && $messagecount>$limitnum) {
1812 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
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
;
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.' |'.$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';
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');
1906 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
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'));
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') {
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) ) {
1934 $dateformat = $format;
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 = $message->smallmessage
;
1947 $messagetext = $message->fullmessage
;
1949 if ($message->fullmessageformat
== FORMAT_HTML
) {
1950 //dont escape html tags by calling s() if html format or they will display in the UI
1951 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat
, $options));
1953 $messagetext = format_text(s($messagetext), $message->fullmessageformat
, $options);
1956 $messagetext .= message_format_contexturl($message);
1959 $messagetext = highlight($keywords, $messagetext);
1962 return '<div class="message '.$class.'"><a name="m'.$message->id
.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1966 * Format a the context url and context url name of a message for display
1968 * @param object $message the message object
1969 * @return string the formatted string
1971 function message_format_contexturl($message) {
1974 if (!empty($message->contexturl
)) {
1975 $displaytext = null;
1976 if (!empty($message->contexturlname
)) {
1977 $displaytext= $message->contexturlname
;
1979 $displaytext= $message->contexturl
;
1981 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
1982 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
1983 $s .= html_writer
::end_tag('div');
1990 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1992 * @param object $userfrom the message sender
1993 * @param object $userto the message recipient
1994 * @param string $message the message
1995 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1996 * @return int|false the ID of the new message or false
1998 function message_post_message($userfrom, $userto, $message, $format) {
1999 global $SITE, $CFG, $USER;
2001 $eventdata = new stdClass();
2002 $eventdata->component
= 'moodle';
2003 $eventdata->name
= 'instantmessage';
2004 $eventdata->userfrom
= $userfrom;
2005 $eventdata->userto
= $userto;
2007 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2008 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
2010 if ($format == FORMAT_HTML
) {
2011 $eventdata->fullmessagehtml
= $message;
2012 //some message processors may revert to sending plain text even if html is supplied
2013 //so we keep both plain and html versions if we're intending to send html
2014 $eventdata->fullmessage
= html_to_text($eventdata->fullmessagehtml
);
2016 $eventdata->fullmessage
= $message;
2017 $eventdata->fullmessagehtml
= '';
2020 $eventdata->fullmessageformat
= $format;
2021 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
2023 $s = new stdClass();
2024 $s->sitename
= format_string($SITE->shortname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, SITEID
)));
2025 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
2027 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
2028 if (!empty($eventdata->fullmessage
)) {
2029 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2031 if (!empty($eventdata->fullmessagehtml
)) {
2032 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2035 $eventdata->timecreated
= time();
2036 return message_send($eventdata);
2041 * Returns a list of all user ids who have used messaging in the site
2042 * This was the simple way to code the SQL ... is it going to blow up
2043 * on large datasets?
2045 * @deprecated To be deleted in 2.2 MDL-31709
2048 function message_get_participants() {
2051 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
2052 UNION SELECT useridto as id,1 FROM {message}
2053 UNION SELECT useridfrom as id,1 FROM {message_read}
2054 UNION SELECT useridto as id,1 FROM {message_read}
2055 UNION SELECT userid as id,1 FROM {message_contacts}
2056 UNION SELECT contactid as id,1 from {message_contacts}");
2060 * Print a row of contactlist displaying user picture, messages waiting and
2063 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2064 * @param bool $incontactlist is the user a contact of ours?
2065 * @param bool $isblocked is the user blocked?
2066 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2067 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2068 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2071 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2072 global $OUTPUT, $USER;
2073 $fullname = fullname($contact);
2074 $fullnamelink = $fullname;
2077 if (!empty($selecteduser) && $contact->id
== $selecteduser->id
) {
2078 $linkclass = 'messageselecteduser';
2081 /// are there any unread messages for this contact?
2082 if ($contact->messagecount
> 0 ){
2083 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount
.')</strong>';
2086 $strcontact = $strblock = $strhistory = null;
2088 if ($showactionlinks) {
2089 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2090 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2091 $strhistory = message_history_link($USER->id
, $contact->id
, true, '', '', 'icon');
2094 echo html_writer
::start_tag('tr');
2095 echo html_writer
::start_tag('td', array('class' => 'pix'));
2096 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID
));
2097 echo html_writer
::end_tag('td');
2099 echo html_writer
::start_tag('td', array('class' => 'contact'));
2101 $popupoptions = array(
2102 'height' => MESSAGE_DISCUSSION_HEIGHT
,
2103 'width' => MESSAGE_DISCUSSION_WIDTH
,
2105 'location' => false,
2107 'scrollbars' => true,
2108 'resizable' => true);
2110 $link = $action = null;
2111 if (!empty($selectcontacturl)) {
2112 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id
);
2114 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2115 $link = new moodle_url("/message/index.php?id=$contact->id");
2116 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2118 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2120 echo html_writer
::end_tag('td');
2122 echo html_writer
::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2124 echo html_writer
::end_tag('tr');
2128 * Constructs the add/remove contact link to display next to other users
2130 * @param bool $incontactlist is the user a contact
2131 * @param bool $isblocked is the user blocked
2132 * @param stdClass $contact contact object
2133 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2134 * @param bool $text include text next to the icons?
2135 * @param bool $icon include a graphical icon?
2138 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2142 $strcontact = message_contact_link($contact->id
, 'remove', true, $script, $text, $icon);
2143 } else if ($isblocked) {
2144 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2146 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2153 * Constructs the block contact link to display next to other users
2155 * @param bool $incontactlist is the user a contact?
2156 * @param bool $isblocked is the user blocked?
2157 * @param stdClass $contact contact object
2158 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2159 * @param bool $text include text next to the icons?
2160 * @param bool $icon include a graphical icon?
2163 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2166 //commented out to allow the user to block a contact without having to remove them first
2167 /*if ($incontactlist) {
2171 $strblock = ' '.message_contact_link($contact->id
, 'unblock', true, $script, $text, $icon);
2173 $strblock = ' '.message_contact_link($contact->id
, 'block', true, $script, $text, $icon);
2180 * Moves messages from a particular user from the message table (unread messages) to message_read
2181 * This is typically only used when a user is deleted
2183 * @param object $userid User id
2184 * @return boolean success
2186 function message_move_userfrom_unread2read($userid) {
2189 // move all unread messages from message table to message_read
2190 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2191 foreach ($messages as $message) {
2192 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2199 * marks ALL messages being sent from $fromuserid to $touserid as read
2201 * @param int $touserid the id of the message recipient
2202 * @param int $fromuserid the id of the message sender
2205 function message_mark_messages_read($touserid, $fromuserid){
2208 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2209 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2211 foreach ($messages as $message) {
2212 message_mark_message_read($message, time());
2219 * Mark a single message as read
2221 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2222 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2223 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2224 * @return int the ID of the message in the message_read table
2226 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2229 $message->timeread
= $timeread;
2231 $messageid = $message->id
;
2232 unset($message->id
);//unset because it will get a new id on insert into message_read
2234 //If any processors have pending actions abort them
2235 if (!$messageworkingempty) {
2236 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2238 $messagereadid = $DB->insert_record('message_read', $message);
2239 $DB->delete_records('message', array('id' => $messageid));
2240 return $messagereadid;
2244 * A helper function that prints a formatted heading
2246 * @param string $title the heading to display
2247 * @param int $colspan
2250 function message_print_heading($title, $colspan=3) {
2251 echo html_writer
::start_tag('tr');
2252 echo html_writer
::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2253 echo html_writer
::end_tag('tr');
2257 * Get all message processors, validate corresponding plugin existance and
2258 * system configuration
2260 * @param bool $ready only return ready-to-use processors
2261 * @return mixed $processors array of objects containing information on message processors
2263 function get_message_processors($ready = false) {
2268 if (empty($processors)) {
2269 // Get all processors, ensure the name column is the first so it will be the array key
2270 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2271 foreach ($processors as &$processor){
2272 $processorfile = $CFG->dirroot
. '/message/output/'.$processor->name
.'/message_output_'.$processor->name
.'.php';
2273 if (is_readable($processorfile)) {
2274 include_once($processorfile);
2275 $processclass = 'message_output_' . $processor->name
;
2276 if (class_exists($processclass)) {
2277 $pclass = new $processclass();
2278 $processor->object = $pclass;
2279 $processor->configured
= 0;
2280 if ($pclass->is_system_configured()) {
2281 $processor->configured
= 1;
2283 $processor->hassettings
= 0;
2284 if (is_readable($CFG->dirroot
.'/message/output/'.$processor->name
.'/settings.php')) {
2285 $processor->hassettings
= 1;
2287 $processor->available
= 1;
2289 print_error('errorcallingprocessor', 'message');
2292 $processor->available
= 0;
2297 // Filter out enabled and system_configured processors
2298 $readyprocessors = $processors;
2299 foreach ($readyprocessors as $readyprocessor) {
2300 if (!($readyprocessor->enabled
&& $readyprocessor->configured
)) {
2301 unset($readyprocessors[$readyprocessor->name
]);
2304 return $readyprocessors;
2311 * Get an instance of the message_output class for one of the output plugins.
2312 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2313 * @return message_output message_output the requested class.
2315 function get_message_processor($type) {
2318 // Note, we cannot use the get_message_processors function here, becaues this
2319 // code is called during install after installing each messaging plugin, and
2320 // get_message_processors caches the list of installed plugins.
2322 $processorfile = $CFG->dirroot
. "/message/output/{$type}/message_output_{$type}.php";
2323 if (!is_readable($processorfile)) {
2324 throw new coding_exception('Unknown message processor type ' . $type);
2327 include_once($processorfile);
2329 $processclass = 'message_output_' . $type;
2330 if (!class_exists($processclass)) {
2331 throw new coding_exception('Message processor ' . $type .
2332 ' does not define the right class');
2335 return new $processclass();
2339 * Get messaging outputs default (site) preferences
2341 * @return object $processors object containing information on message processors
2343 function get_message_output_default_preferences() {
2344 return get_config('message');
2348 * Translate message default settings from binary value to the array of string
2349 * representing the settings to be stored. Also validate the provided value and
2350 * use default if it is malformed.
2352 * @param int $plugindefault Default setting suggested by plugin
2353 * @param string $processorname The name of processor
2354 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2356 function translate_message_default_setting($plugindefault, $processorname) {
2357 // Preset translation arrays
2358 $permittedvalues = array(
2359 0x04 => 'disallowed',
2360 0x08 => 'permitted',
2364 $loggedinstatusvalues = array(
2365 0x00 => null, // use null if loggedin/loggedoff is not defined
2367 0x02 => 'loggedoff',
2370 // define the default setting
2371 $processor = get_message_processor($processorname);
2372 $default = $processor->get_default_messaging_settings();
2374 // Validate the value. It should not exceed the maximum size
2375 if (!is_int($plugindefault) ||
($plugindefault > 0x0f)) {
2376 debugging(get_string('errortranslatingdefault', 'message'));
2377 $plugindefault = $default;
2379 // Use plugin default setting of 'permitted' is 0
2380 if (!($plugindefault & MESSAGE_PERMITTED_MASK
)) {
2381 $plugindefault = $default;
2384 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK
];
2385 $loggedin = $loggedoff = null;
2387 if (($plugindefault & MESSAGE_PERMITTED_MASK
) == MESSAGE_PERMITTED
) {
2388 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN
];
2389 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF
];
2392 return array($permitted, $loggedin, $loggedoff);
2396 * Return a list of page types
2397 * @param string $pagetype current page type
2398 * @param stdClass $parentcontext Block's parent context
2399 * @param stdClass $currentcontext Current context of block
2401 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2402 return array('messages-*'=>get_string('page-message-x', 'message'));