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) {
474 if ($countunreadtotal>0) { //if there are unread messages
475 $options[MESSAGE_VIEW_UNREAD_MESSAGES
] = $strunreadmessages;
478 $str = get_string('mycontacts', 'message');
479 $options[MESSAGE_VIEW_CONTACTS
] = $str;
481 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS
] = get_string('mostrecentconversations', 'message');
482 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS
] = get_string('mostrecentnotifications', 'message');
484 if (!empty($courses)) {
485 $courses_options = array();
487 foreach($courses as $course) {
488 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id
])) {
489 //Not using short_text() as we want the end of the course name. Not the beginning.
490 $shortname = format_string($course->shortname
, true, array('context' => $coursecontexts[$course->id
]));
491 if (textlib
::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH
) {
492 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = '...'.textlib
::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH
);
494 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = $shortname;
499 if (!empty($courses_options)) {
500 $options[] = array(get_string('courses') => $courses_options);
504 if ($countblocked>0) {
505 $str = get_string('blockedusers','message', $countblocked);
506 $options[MESSAGE_VIEW_BLOCKED
] = $str;
509 echo html_writer
::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
510 echo html_writer
::start_tag('fieldset');
511 echo html_writer
::label(get_string('messagenavigation', 'message'), 'viewing');
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
] = context_course
::instance($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 by $conversation->timecreated, newest to oldest
753 // There may be multiple conversations with the same timecreated
754 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
755 $result = collatorlib
::asort_objects_by_property($conversations, 'timecreated', collatorlib
::SORT_NUMERIC
);
756 $conversations = array_reverse($conversations);
758 return $conversations;
762 * Get the users recent event notifications
764 * @param object $user the current user
765 * @param int $limitfrom can be used for paging
766 * @param int $limitto can be used for paging
769 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
772 $userfields = user_picture
::fields('u', array('lastaccess'));
773 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
774 FROM {message_read} mr
775 JOIN {user} u ON u.id=mr.useridfrom
776 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
777 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
778 $params = array('userid1' => $user->id
, 'notification' => 1);
780 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
781 return $notifications;
785 * Print the user's recent conversations
787 * @param stdClass $user the current user
788 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
790 function message_print_recent_conversations($user=null, $showicontext=false) {
793 echo html_writer
::start_tag('p', array('class' => 'heading'));
794 echo get_string('mostrecentconversations', 'message');
795 echo html_writer
::end_tag('p');
801 $conversations = message_get_recent_conversations($user);
803 // Attach context url information to create the "View this conversation" type links
804 foreach($conversations as $conversation) {
805 $conversation->contexturl
= new moodle_url("/message/index.php?user2={$conversation->id}");
806 $conversation->contexturlname
= get_string('thisconversation', 'message');
809 $showotheruser = true;
810 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
814 * Print the user's recent notifications
816 * @param stdClass $user the current user
818 function message_print_recent_notifications($user=null) {
821 echo html_writer
::start_tag('p', array('class' => 'heading'));
822 echo get_string('mostrecentnotifications', 'message');
823 echo html_writer
::end_tag('p');
829 $notifications = message_get_recent_notifications($user);
831 $showicontext = false;
832 $showotheruser = false;
833 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
837 * Print a list of recent messages
839 * @param array $messages the messages to display
840 * @param object $user the current user
841 * @param bool $showotheruser display information on the other user?
842 * @param bool $showicontext show text next to the action icons?
843 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
846 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false, $forcetexttohtml=false) {
850 if (empty($dateformat)) {
851 $dateformat = get_string('strftimedatetimeshort');
854 echo html_writer
::start_tag('div', array('class' => 'messagerecent'));
855 foreach ($messages as $message) {
856 echo html_writer
::start_tag('div', array('class' => 'singlemessage'));
858 if ($showotheruser) {
859 if ( $message->contactlistid
) {
860 if ($message->blocked
== 0) { /// not blocked
861 $strcontact = message_contact_link($message->id
, 'remove', true, null, $showicontext);
862 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
864 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
865 $strblock = message_contact_link($message->id
, 'unblock', true, null, $showicontext);
868 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
869 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
872 //should we show just the icon or icon and text?
873 $histicontext = 'icon';
875 $histicontext = 'both';
877 $strhistory = message_history_link($user->id
, $message->id
, true, '', '', $histicontext);
879 echo html_writer
::start_tag('span', array('class' => 'otheruser'));
881 echo html_writer
::start_tag('span', array('class' => 'pix'));
882 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID
));
883 echo html_writer
::end_tag('span');
885 echo html_writer
::start_tag('span', array('class' => 'contact'));
887 $link = new moodle_url("/message/index.php?id=$message->id");
889 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
891 echo html_writer
::end_tag('span');//end contact
893 echo $strcontact.$strblock.$strhistory;
894 echo html_writer
::end_tag('span');//end otheruser
896 $messagetoprint = null;
897 if (!empty($message->smallmessage
)) {
898 $messagetoprint = $message->smallmessage
;
900 $messagetoprint = $message->fullmessage
;
903 echo html_writer
::tag('span', userdate($message->timecreated
, $dateformat), array('class' => 'messagedate'));
904 echo html_writer
::tag('span', format_text($messagetoprint, $forcetexttohtml?FORMAT_MOODLE
:FORMAT_HTML
), array('class' => 'themessage'));
905 echo message_format_contexturl($message);
906 echo html_writer
::end_tag('div');//end singlemessage
908 echo html_writer
::end_tag('div');//end messagerecent
912 * Add the selected user as a contact for the current user
914 * @param int $contactid the ID of the user to add as a contact
915 * @param int $blocked 1 if you wish to block the contact
916 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
917 * Otherwise returns the result of update_record() or insert_record()
919 function message_add_contact($contactid, $blocked=0) {
922 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
926 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid))) !== false) {
927 /// record already exists - we may be changing blocking status
929 if ($contact->blocked
!== $blocked) {
930 /// change to blocking status
931 $contact->blocked
= $blocked;
932 return $DB->update_record('message_contacts', $contact);
934 /// no changes to blocking status
939 /// new contact record
940 $contact = new stdClass();
941 $contact->userid
= $USER->id
;
942 $contact->contactid
= $contactid;
943 $contact->blocked
= $blocked;
944 return $DB->insert_record('message_contacts', $contact, false);
951 * @param int $contactid the user ID of the contact to remove
952 * @return bool returns the result of delete_records()
954 function message_remove_contact($contactid) {
956 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
960 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
962 * @param int $contactid the user ID of the contact to unblock
963 * @return bool returns the result of delete_records()
965 function message_unblock_contact($contactid) {
967 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
973 * @param int $contactid the user ID of the user to block
975 function message_block_contact($contactid) {
976 return message_add_contact($contactid, 1);
980 * Load a user's contact record
982 * @param int $contactid the user ID of the user whose contact record you want
983 * @return array message contacts
985 function message_get_contact($contactid) {
987 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
991 * Print the results of a message search
993 * @param mixed $frm submitted form data
994 * @param bool $showicontext show text next to action icons?
995 * @param object $currentuser the current user
998 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
999 global $USER, $DB, $OUTPUT;
1001 if (empty($currentuser)) {
1002 $currentuser = $USER;
1005 echo html_writer
::start_tag('div', array('class' => 'mdl-left'));
1007 $personsearch = false;
1008 $personsearchstring = null;
1009 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
1010 $personsearch = true;
1011 $personsearchstring = $frm->name
;
1012 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1013 $personsearch = true;
1014 $personsearchstring = $frm->combinedsearch
;
1017 /// search for person
1018 if ($personsearch) {
1019 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
1021 $mycourses = enrol_get_my_courses();
1022 foreach ($mycourses as $mycourse) {
1023 if (is_array($susers = message_search_users($mycourse->id
, $personsearchstring))) {
1024 foreach ($susers as $suser) $users[$suser->id
] = $suser;
1028 $users = message_search_users(SITEID
, $personsearchstring);
1031 if (!empty($users)) {
1032 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1033 echo get_string('userssearchresults', 'message', count($users));
1034 echo html_writer
::end_tag('p');
1036 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults'));
1037 foreach ($users as $user) {
1039 if ( $user->contactlistid
) {
1040 if ($user->blocked
== 0) { /// not blocked
1041 $strcontact = message_contact_link($user->id
, 'remove', true, null, $showicontext);
1042 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1044 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1045 $strblock = message_contact_link($user->id
, 'unblock', true, null, $showicontext);
1048 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1049 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1052 //should we show just the icon or icon and text?
1053 $histicontext = 'icon';
1054 if ($showicontext) {
1055 $histicontext = 'both';
1057 $strhistory = message_history_link($USER->id
, $user->id
, true, '', '', $histicontext);
1059 echo html_writer
::start_tag('tr');
1061 echo html_writer
::start_tag('td', array('class' => 'pix'));
1062 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1063 echo html_writer
::end_tag('td');
1065 echo html_writer
::start_tag('td',array('class' => 'contact'));
1067 $link = new moodle_url("/message/index.php?id=$user->id");
1068 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1069 echo html_writer
::end_tag('td');
1071 echo html_writer
::tag('td', $strcontact, array('class' => 'link'));
1072 echo html_writer
::tag('td', $strblock, array('class' => 'link'));
1073 echo html_writer
::tag('td', $strhistory, array('class' => 'link'));
1075 echo html_writer
::end_tag('tr');
1077 echo html_writer
::end_tag('table');
1080 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1081 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1082 echo html_writer
::end_tag('p');
1086 // search messages for keywords
1087 $messagesearch = false;
1088 $messagesearchstring = null;
1089 if (!empty($frm->keywords
)) {
1090 $messagesearch = true;
1091 $messagesearchstring = clean_text(trim($frm->keywords
));
1092 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1093 $messagesearch = true;
1094 $messagesearchstring = clean_text(trim($frm->combinedsearch
));
1097 if ($messagesearch) {
1098 if ($messagesearchstring) {
1099 $keywords = explode(' ', $messagesearchstring);
1101 $keywords = array();
1107 if (empty($frm->keywordsoption
)) {
1108 $frm->keywordsoption
= 'allmine';
1111 switch ($frm->keywordsoption
) {
1126 $courseid = $frm->courseid
;
1133 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1135 /// get a list of contacts
1136 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id
), '', 'contactid, blocked') ) === false) {
1137 $contacts = array();
1140 /// print heading with number of results
1141 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1142 $countresults = count($messages);
1143 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS
) {
1144 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1146 echo get_string('keywordssearchresults', 'message', $countresults);
1148 echo html_writer
::end_tag('p');
1150 /// print table headings
1151 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1153 $headertdstart = html_writer
::start_tag('td', array('class' => 'messagesearchresultscol'));
1154 $headertdend = html_writer
::end_tag('td');
1155 echo html_writer
::start_tag('tr');
1156 echo $headertdstart.get_string('from').$headertdend;
1157 echo $headertdstart.get_string('to').$headertdend;
1158 echo $headertdstart.get_string('message', 'message').$headertdend;
1159 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1160 echo html_writer
::end_tag('tr');
1163 $dateformat = get_string('strftimedatetimeshort');
1164 $strcontext = get_string('context', 'message');
1165 foreach ($messages as $message) {
1167 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1168 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
1169 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
1170 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
1177 /// load up user to record
1178 if ($message->useridto
!== $USER->id
) {
1179 $userto = $DB->get_record('user', array('id' => $message->useridto
));
1180 $tocontact = (array_key_exists($message->useridto
, $contacts) and
1181 ($contacts[$message->useridto
]->blocked
== 0) );
1182 $toblocked = (array_key_exists($message->useridto
, $contacts) and
1183 ($contacts[$message->useridto
]->blocked
== 1) );
1190 /// load up user from record
1191 if ($message->useridfrom
!== $USER->id
) {
1192 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom
));
1193 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
1194 ($contacts[$message->useridfrom
]->blocked
== 0) );
1195 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
1196 ($contacts[$message->useridfrom
]->blocked
== 1) );
1199 $fromcontact = false;
1200 $fromblocked = false;
1203 /// find date string for this message
1204 $date = usergetdate($message->timecreated
);
1205 $datestring = $date['year'].$date['mon'].$date['mday'];
1207 /// print out message row
1208 echo html_writer
::start_tag('tr', array('valign' => 'top'));
1210 echo html_writer
::start_tag('td', array('class' => 'contact'));
1211 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1212 echo html_writer
::end_tag('td');
1214 echo html_writer
::start_tag('td', array('class' => 'contact'));
1215 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1216 echo html_writer
::end_tag('td');
1218 echo html_writer
::start_tag('td', array('class' => 'summary'));
1219 echo message_get_fragment($message->fullmessage
, $keywords);
1220 echo html_writer
::start_tag('div', array('class' => 'link'));
1222 //If the user clicks the context link display message sender on the left
1223 //EXCEPT if the current user is in the conversation. Current user == always on the left
1224 $leftsideuserid = $rightsideuserid = null;
1225 if ($currentuser->id
== $message->useridto
) {
1226 $leftsideuserid = $message->useridto
;
1227 $rightsideuserid = $message->useridfrom
;
1229 $leftsideuserid = $message->useridfrom
;
1230 $rightsideuserid = $message->useridto
;
1232 message_history_link($leftsideuserid, $rightsideuserid, false,
1233 $messagesearchstring, 'm'.$message->id
, $strcontext);
1234 echo html_writer
::end_tag('div');
1235 echo html_writer
::end_tag('td');
1237 echo html_writer
::tag('td', userdate($message->timecreated
, $dateformat), array('class' => 'date'));
1239 echo html_writer
::end_tag('tr');
1243 if ($blockedcount > 0) {
1244 echo html_writer
::start_tag('tr');
1245 echo html_writer
::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1246 echo html_writer
::end_tag('tr');
1248 echo html_writer
::end_tag('table');
1251 echo html_writer
::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1255 if (!$personsearch && !$messagesearch) {
1256 //they didn't enter any search terms
1257 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1260 echo html_writer
::end_tag('div');
1264 * Print information on a user. Used when printing search results.
1266 * @param object/bool $user the user to display or false if you just want $USER
1267 * @param bool $iscontact is the user being displayed a contact?
1268 * @param bool $isblocked is the user being displayed blocked?
1269 * @param bool $includeicontext include text next to the action icons?
1272 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1273 global $USER, $OUTPUT;
1275 if ($user === false) {
1276 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID
));
1278 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1284 message_contact_link($user->id
, 'remove', $return, $script, $includeicontext);
1286 message_contact_link($user->id
, 'add', $return, $script, $includeicontext);
1290 message_contact_link($user->id
, 'unblock', $return, $script, $includeicontext);
1292 message_contact_link($user->id
, 'block', $return, $script, $includeicontext);
1295 $popupoptions = array(
1296 'height' => MESSAGE_DISCUSSION_HEIGHT
,
1297 'width' => MESSAGE_DISCUSSION_WIDTH
,
1299 'location' => false,
1301 'scrollbars' => true,
1302 'resizable' => true);
1304 $link = new moodle_url("/message/index.php?id=$user->id");
1305 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1307 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1313 * Print a message contact link
1315 * @param int $userid the ID of the user to apply to action to
1316 * @param string $linktype can be add, remove, block or unblock
1317 * @param bool $return if true return the link as a string. If false echo the link.
1318 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1319 * @param bool $text include text next to the icons?
1320 * @param bool $icon include a graphical icon?
1321 * @return string if $return is true otherwise bool
1323 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1324 global $OUTPUT, $PAGE;
1326 //hold onto the strings as we're probably creating a bunch of links
1329 if (empty($script)) {
1330 //strip off previous action params like 'removecontact'
1331 $script = message_remove_url_params($PAGE->url
);
1334 if (empty($str->blockcontact
)) {
1335 $str = new stdClass();
1336 $str->blockcontact
= get_string('blockcontact', 'message');
1337 $str->unblockcontact
= get_string('unblockcontact', 'message');
1338 $str->removecontact
= get_string('removecontact', 'message');
1339 $str->addcontact
= get_string('addcontact', 'message');
1342 $command = $linktype.'contact';
1343 $string = $str->{$command};
1345 $safealttext = s($string);
1348 if (!empty($text)) {
1349 $safestring = $safealttext;
1355 switch ($linktype) {
1357 $iconpath = 't/block';
1360 $iconpath = 't/userblue';
1363 $iconpath = 'i/cross_red_big';
1367 $iconpath = 't/addgreen';
1370 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1373 $output = '<span class="'.$linktype.'contact">'.
1374 '<a href="'.$script.'&'.$command.'='.$userid.
1375 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1377 $safestring.'</a></span>';
1388 * echo or return a link to take the user to the full message history between themselves and another user
1390 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1391 * @param int $userid2 the ID of the other user
1392 * @param bool $return true to return the link as a string. False to echo the link.
1393 * @param string $keywords any keywords to highlight in the message history
1394 * @param string $position anchor name to jump to within the message history
1395 * @param string $linktext optionally specify the link text
1396 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1398 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1400 static $strmessagehistory;
1402 if (empty($strmessagehistory)) {
1403 $strmessagehistory = get_string('messagehistory', 'message');
1407 $position = "#$position";
1410 $keywords = "&search=".urlencode($keywords);
1413 if ($linktext == 'icon') { // Icon only
1414 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1415 } else if ($linktext == 'both') { // Icon and standard name
1416 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1417 $fulllink .= ' '.$strmessagehistory;
1418 } else if ($linktext) { // Custom name
1419 $fulllink = $linktext;
1420 } else { // Standard name only
1421 $fulllink = $strmessagehistory;
1424 $popupoptions = array(
1428 'location' => false,
1430 'scrollbars' => true,
1431 'resizable' => true);
1433 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL
."&user1=$userid1&user2=$userid2$keywords$position");
1435 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1437 $str = '<span class="history">'.$str.'</span>';
1449 * Search through course users
1451 * If $coursid specifies the site course then this function searches
1452 * through all undeleted and confirmed users
1453 * @param int $courseid The course in question.
1454 * @param string $searchtext the text to search for
1455 * @param string $sort the column name to order by
1456 * @param string $exceptions comma separated list of user IDs to exclude
1457 * @return array An array of {@link $USER} records.
1459 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1460 global $CFG, $USER, $DB;
1462 $fullname = $DB->sql_fullname();
1464 if (!empty($exceptions)) {
1465 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1470 if (!empty($sort)) {
1471 $order = ' ORDER BY '. $sort;
1476 $ufields = user_picture
::fields('u');
1477 if (!$courseid or $courseid == SITEID
) {
1478 $params = array($USER->id
, "%$searchtext%");
1479 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1481 LEFT JOIN {message_contacts} mc
1482 ON mc.contactid = u.id AND mc.userid = ?
1483 WHERE u.deleted = '0' AND u.confirmed = '1'
1484 AND (".$DB->sql_like($fullname, '?', false).")
1488 //TODO: add enabled enrolment join here (skodak)
1489 $context = context_course
::instance($courseid);
1490 $contextlists = get_related_contexts_string($context);
1492 // everyone who has a role assignment in this course or higher
1493 $params = array($USER->id
, "%$searchtext%");
1494 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1496 JOIN {role_assignments} ra ON ra.userid = u.id
1497 LEFT JOIN {message_contacts} mc
1498 ON mc.contactid = u.id AND mc.userid = ?
1499 WHERE u.deleted = '0' AND u.confirmed = '1'
1500 AND ra.contextid $contextlists
1501 AND (".$DB->sql_like($fullname, '?', false).")
1510 * search a user's messages
1512 * @param array $searchterms an array of search terms (strings)
1513 * @param bool $fromme include messages from the user?
1514 * @param bool $tome include messages to the user?
1515 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1516 * @param int $userid the user ID of the current user
1517 * @return mixed An array of messages or false if no matching messages were found
1519 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1520 /// Returns a list of posts found using an array of search terms
1521 /// eg word +word -word
1523 global $CFG, $USER, $DB;
1525 // If user is searching all messages check they are allowed to before doing anything else
1526 if ($courseid == SITEID
&& !has_capability('moodle/site:readallmessages', context_system
::instance())) {
1527 print_error('accessdenied','admin');
1530 /// If no userid sent then assume current user
1531 if ($userid == 0) $userid = $USER->id
;
1533 /// Some differences in SQL syntax
1534 if ($DB->sql_regex_supported()) {
1535 $REGEXP = $DB->sql_regex(true);
1536 $NOTREGEXP = $DB->sql_regex(false);
1539 $searchcond = array();
1543 //preprocess search terms to check whether we have at least 1 eligible search term
1544 //if we do we can drop words around it like 'a'
1545 $dropshortwords = false;
1546 foreach ($searchterms as $searchterm) {
1547 if (strlen($searchterm) >= 2) {
1548 $dropshortwords = true;
1552 foreach ($searchterms as $searchterm) {
1555 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1557 if ($dropshortwords && strlen($searchterm) < 2) {
1560 /// Under Oracle and MSSQL, trim the + and - operators and perform
1561 /// simpler LIKE search
1562 if (!$DB->sql_regex_supported()) {
1563 if (substr($searchterm, 0, 1) == '-') {
1566 $searchterm = trim($searchterm, '+-');
1569 if (substr($searchterm,0,1) == "+") {
1570 $searchterm = substr($searchterm,1);
1571 $searchterm = preg_quote($searchterm, '|');
1572 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1573 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1575 } else if (substr($searchterm,0,1) == "-") {
1576 $searchterm = substr($searchterm,1);
1577 $searchterm = preg_quote($searchterm, '|');
1578 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1579 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1582 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1583 $params['ss'.$i] = "%$searchterm%";
1587 if (empty($searchcond)) {
1588 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1589 $params['ss1'] = "%";
1591 $searchcond = implode(" AND ", $searchcond);
1594 /// There are several possibilities
1595 /// 1. courseid = SITEID : The admin is searching messages by all users
1596 /// 2. courseid = ?? : A teacher is searching messages by users in
1597 /// one of their courses - currently disabled
1598 /// 3. courseid = none : User is searching their own messages;
1599 /// a. Messages from user
1600 /// b. Messages to user
1601 /// c. Messages to and from user
1603 if ($courseid == SITEID
) { /// admin is searching all messages
1604 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1605 FROM {message_read} m
1606 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1607 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1609 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1611 } else if ($courseid !== 'none') {
1612 /// This has not been implemented due to security concerns
1614 $m_unread = array();
1618 if ($fromme and $tome) {
1619 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1620 $params['userid1'] = $userid;
1621 $params['userid2'] = $userid;
1623 } else if ($fromme) {
1624 $searchcond .= " AND m.useridfrom=:userid";
1625 $params['userid'] = $userid;
1628 $searchcond .= " AND m.useridto=:userid";
1629 $params['userid'] = $userid;
1632 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1633 FROM {message_read} m
1634 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1635 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1637 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1641 /// The keys may be duplicated in $m_read and $m_unread so we can't
1642 /// do a simple concatenation
1643 $messages = array();
1644 foreach ($m_read as $m) {
1647 foreach ($m_unread as $m) {
1651 return (empty($messages)) ?
false : $messages;
1655 * Given a message object that we already know has a long message
1656 * this function truncates the message nicely to the first
1657 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1659 * @param string $message the message
1660 * @param int $minlength the minimum length to trim the message to
1661 * @return string the shortened message
1663 function message_shorten_message($message, $minlength = 0) {
1666 $length = strlen($message);
1670 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
1673 for ($i=0; $i<$length; $i++
) {
1674 $char = $message[$i];
1686 if ($char == '.' or $char == ' ') {
1696 if ($count > $minlength) {
1706 return substr($message, 0, $truncate);
1711 * Given a string and an array of keywords, this function looks
1712 * for the first keyword in the string, and then chops out a
1713 * small section from the text that shows that word in context.
1715 * @param string $message the text to search
1716 * @param array $keywords array of keywords to find
1718 function message_get_fragment($message, $keywords) {
1721 $halfsize = (int)($fullsize/2);
1723 $message = strip_tags($message);
1725 foreach ($keywords as $keyword) { // Just get the first one
1726 if ($keyword !== '') {
1730 if (empty($keyword)) { // None found, so just return start of message
1731 return message_shorten_message($message, 30);
1734 $leadin = $leadout = '';
1736 /// Find the start of the fragment
1738 $length = strlen($message);
1740 $pos = strpos($message, $keyword);
1741 if ($pos > $halfsize) {
1742 $start = $pos - $halfsize;
1745 /// Find the end of the fragment
1746 $end = $start +
$fullsize;
1747 if ($end > $length) {
1753 /// Pull out the fragment and format it
1755 $fragment = substr($message, $start, $end - $start);
1756 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1761 * Retrieve the messages between two users
1763 * @param object $user1 the current user
1764 * @param object $user2 the other user
1765 * @param int $limitnum the maximum number of messages to retrieve
1766 * @param bool $viewingnewmessages are we currently viewing new messages?
1768 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1771 $messages = array();
1773 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1774 //desc to get the last $limitnum messages then flip the order in php
1780 $notificationswhere = null;
1781 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1782 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications
) {
1783 $notificationswhere = 'AND notification=0';
1786 //prevent notifications of your own actions appearing in your own message history
1787 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1789 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1790 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1791 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1792 "timecreated $sort", '*', 0, $limitnum)) {
1793 foreach ($messages_read as $message) {
1794 $messages[] = $message;
1797 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1798 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1799 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1800 "timecreated $sort", '*', 0, $limitnum)) {
1801 foreach ($messages_new as $message) {
1802 $messages[] = $message;
1806 $result = collatorlib
::asort_objects_by_property($messages, 'timecreated', collatorlib
::SORT_NUMERIC
);
1808 //if we only want the last $limitnum messages
1809 $messagecount = count($messages);
1810 if ($limitnum > 0 && $messagecount > $limitnum) {
1811 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1818 * Print the message history between two users
1820 * @param object $user1 the current user
1821 * @param object $user2 the other user
1822 * @param string $search search terms to highlight
1823 * @param int $messagelimit maximum number of messages to return
1824 * @param string $messagehistorylink the html for the message history link or false
1825 * @param bool $viewingnewmessages are we currently viewing new messages?
1827 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1828 global $CFG, $OUTPUT;
1830 echo $OUTPUT->box_start('center');
1831 echo html_writer
::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1832 echo html_writer
::start_tag('tr');
1834 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1835 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID
));
1836 echo html_writer
::tag('div', fullname($user1), array('class' => 'heading'));
1837 echo html_writer
::end_tag('td');
1839 echo html_writer
::start_tag('td', array('align' => 'center'));
1840 echo html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1841 echo html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1842 echo html_writer
::end_tag('td');
1844 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1845 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID
));
1846 echo html_writer
::tag('div', fullname($user2), array('class' => 'heading'));
1848 if (isset($user2->iscontact
) && isset($user2->isblocked
)) {
1849 $incontactlist = $user2->iscontact
;
1850 $isblocked = $user2->isblocked
;
1856 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1857 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1858 $useractionlinks = $strcontact.' |'.$strblock;
1860 echo html_writer
::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1863 echo html_writer
::end_tag('td');
1864 echo html_writer
::end_tag('tr');
1865 echo html_writer
::end_tag('table');
1866 echo $OUTPUT->box_end();
1868 if (!empty($messagehistorylink)) {
1869 echo $messagehistorylink;
1872 /// Get all the messages and print them
1873 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1874 $tablecontents = '';
1876 $current = new stdClass();
1877 $current->mday
= '';
1878 $current->month
= '';
1879 $current->year
= '';
1880 $messagedate = get_string('strftimetime');
1881 $blockdate = get_string('strftimedaydate');
1882 foreach ($messages as $message) {
1883 if ($message->notification
) {
1884 $notificationclass = ' notification';
1886 $notificationclass = null;
1888 $date = usergetdate($message->timecreated
);
1889 if ($current->mday
!= $date['mday'] |
$current->month
!= $date['month'] |
$current->year
!= $date['year']) {
1890 $current->mday
= $date['mday'];
1891 $current->month
= $date['month'];
1892 $current->year
= $date['year'];
1894 $datestring = html_writer
::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1895 $tablecontents .= html_writer
::tag('div', $datestring, array('class' => 'mdl-align heading'));
1897 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated
, $blockdate), 4, 'mdl-align');
1900 $formatted_message = $side = null;
1901 if ($message->useridfrom
== $user1->id
) {
1902 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1905 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1908 $tablecontents .= html_writer
::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1911 echo html_writer
::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1913 echo html_writer
::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1918 * Format a message for display in the message history
1920 * @param object $message the message object
1921 * @param string $format optional date format
1922 * @param string $keywords keywords to highlight
1923 * @param string $class CSS class to apply to the div around the message
1924 * @return string the formatted message
1926 function message_format_message($message, $format='', $keywords='', $class='other') {
1930 //if we haven't previously set the date format or they've supplied a new one
1931 if ( empty($dateformat) ||
(!empty($format) && $dateformat != $format) ) {
1933 $dateformat = $format;
1935 $dateformat = get_string('strftimedatetimeshort');
1938 $time = userdate($message->timecreated
, $dateformat);
1939 $options = new stdClass();
1940 $options->para
= false;
1942 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1943 if (!empty($message->smallmessage
)) {
1944 $messagetext = $message->smallmessage
;
1946 $messagetext = $message->fullmessage
;
1948 if ($message->fullmessageformat
== FORMAT_HTML
) {
1949 //dont escape html tags by calling s() if html format or they will display in the UI
1950 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat
, $options));
1952 $messagetext = format_text(s($messagetext), $message->fullmessageformat
, $options);
1955 $messagetext .= message_format_contexturl($message);
1958 $messagetext = highlight($keywords, $messagetext);
1962 <div class='message $class'>
1963 <a name="m'.{$message->id}.'"></a>
1964 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
1970 * Format a the context url and context url name of a message for display
1972 * @param object $message the message object
1973 * @return string the formatted string
1975 function message_format_contexturl($message) {
1978 if (!empty($message->contexturl
)) {
1979 $displaytext = null;
1980 if (!empty($message->contexturlname
)) {
1981 $displaytext= $message->contexturlname
;
1983 $displaytext= $message->contexturl
;
1985 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
1986 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
1987 $s .= html_writer
::end_tag('div');
1994 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1996 * @param object $userfrom the message sender
1997 * @param object $userto the message recipient
1998 * @param string $message the message
1999 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2000 * @return int|false the ID of the new message or false
2002 function message_post_message($userfrom, $userto, $message, $format) {
2003 global $SITE, $CFG, $USER;
2005 $eventdata = new stdClass();
2006 $eventdata->component
= 'moodle';
2007 $eventdata->name
= 'instantmessage';
2008 $eventdata->userfrom
= $userfrom;
2009 $eventdata->userto
= $userto;
2011 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2012 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
2014 if ($format == FORMAT_HTML
) {
2015 $eventdata->fullmessagehtml
= $message;
2016 //some message processors may revert to sending plain text even if html is supplied
2017 //so we keep both plain and html versions if we're intending to send html
2018 $eventdata->fullmessage
= html_to_text($eventdata->fullmessagehtml
);
2020 $eventdata->fullmessage
= $message;
2021 $eventdata->fullmessagehtml
= '';
2024 $eventdata->fullmessageformat
= $format;
2025 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
2027 $s = new stdClass();
2028 $s->sitename
= format_string($SITE->shortname
, true, array('context' => context_course
::instance(SITEID
)));
2029 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
2031 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
2032 if (!empty($eventdata->fullmessage
)) {
2033 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2035 if (!empty($eventdata->fullmessagehtml
)) {
2036 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2039 $eventdata->timecreated
= time();
2040 return message_send($eventdata);
2044 * Print a row of contactlist displaying user picture, messages waiting and
2047 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2048 * @param bool $incontactlist is the user a contact of ours?
2049 * @param bool $isblocked is the user blocked?
2050 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2051 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2052 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2055 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2056 global $OUTPUT, $USER;
2057 $fullname = fullname($contact);
2058 $fullnamelink = $fullname;
2061 if (!empty($selecteduser) && $contact->id
== $selecteduser->id
) {
2062 $linkclass = 'messageselecteduser';
2065 /// are there any unread messages for this contact?
2066 if ($contact->messagecount
> 0 ){
2067 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount
.')</strong>';
2070 $strcontact = $strblock = $strhistory = null;
2072 if ($showactionlinks) {
2073 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2074 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2075 $strhistory = message_history_link($USER->id
, $contact->id
, true, '', '', 'icon');
2078 echo html_writer
::start_tag('tr');
2079 echo html_writer
::start_tag('td', array('class' => 'pix'));
2080 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID
));
2081 echo html_writer
::end_tag('td');
2083 echo html_writer
::start_tag('td', array('class' => 'contact'));
2085 $popupoptions = array(
2086 'height' => MESSAGE_DISCUSSION_HEIGHT
,
2087 'width' => MESSAGE_DISCUSSION_WIDTH
,
2089 'location' => false,
2091 'scrollbars' => true,
2092 'resizable' => true);
2094 $link = $action = null;
2095 if (!empty($selectcontacturl)) {
2096 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id
);
2098 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2099 $link = new moodle_url("/message/index.php?id=$contact->id");
2100 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2102 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2104 echo html_writer
::end_tag('td');
2106 echo html_writer
::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2108 echo html_writer
::end_tag('tr');
2112 * Constructs the add/remove contact link to display next to other users
2114 * @param bool $incontactlist is the user a contact
2115 * @param bool $isblocked is the user blocked
2116 * @param stdClass $contact contact object
2117 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2118 * @param bool $text include text next to the icons?
2119 * @param bool $icon include a graphical icon?
2122 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2126 $strcontact = message_contact_link($contact->id
, 'remove', true, $script, $text, $icon);
2127 } else if ($isblocked) {
2128 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2130 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2137 * Constructs the block contact link to display next to other users
2139 * @param bool $incontactlist is the user a contact?
2140 * @param bool $isblocked is the user blocked?
2141 * @param stdClass $contact contact object
2142 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2143 * @param bool $text include text next to the icons?
2144 * @param bool $icon include a graphical icon?
2147 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2150 //commented out to allow the user to block a contact without having to remove them first
2151 /*if ($incontactlist) {
2155 $strblock = ' '.message_contact_link($contact->id
, 'unblock', true, $script, $text, $icon);
2157 $strblock = ' '.message_contact_link($contact->id
, 'block', true, $script, $text, $icon);
2164 * Moves messages from a particular user from the message table (unread messages) to message_read
2165 * This is typically only used when a user is deleted
2167 * @param object $userid User id
2168 * @return boolean success
2170 function message_move_userfrom_unread2read($userid) {
2173 // move all unread messages from message table to message_read
2174 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2175 foreach ($messages as $message) {
2176 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2183 * marks ALL messages being sent from $fromuserid to $touserid as read
2185 * @param int $touserid the id of the message recipient
2186 * @param int $fromuserid the id of the message sender
2189 function message_mark_messages_read($touserid, $fromuserid){
2192 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2193 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2195 foreach ($messages as $message) {
2196 message_mark_message_read($message, time());
2203 * Mark a single message as read
2205 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2206 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2207 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2208 * @return int the ID of the message in the message_read table
2210 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2213 $message->timeread
= $timeread;
2215 $messageid = $message->id
;
2216 unset($message->id
);//unset because it will get a new id on insert into message_read
2218 //If any processors have pending actions abort them
2219 if (!$messageworkingempty) {
2220 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2222 $messagereadid = $DB->insert_record('message_read', $message);
2223 $DB->delete_records('message', array('id' => $messageid));
2224 return $messagereadid;
2228 * A helper function that prints a formatted heading
2230 * @param string $title the heading to display
2231 * @param int $colspan
2234 function message_print_heading($title, $colspan=3) {
2235 echo html_writer
::start_tag('tr');
2236 echo html_writer
::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2237 echo html_writer
::end_tag('tr');
2241 * Get all message processors, validate corresponding plugin existance and
2242 * system configuration
2244 * @param bool $ready only return ready-to-use processors
2245 * @return mixed $processors array of objects containing information on message processors
2247 function get_message_processors($ready = false) {
2252 if (empty($processors)) {
2253 // Get all processors, ensure the name column is the first so it will be the array key
2254 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2255 foreach ($processors as &$processor){
2256 $processorfile = $CFG->dirroot
. '/message/output/'.$processor->name
.'/message_output_'.$processor->name
.'.php';
2257 if (is_readable($processorfile)) {
2258 include_once($processorfile);
2259 $processclass = 'message_output_' . $processor->name
;
2260 if (class_exists($processclass)) {
2261 $pclass = new $processclass();
2262 $processor->object = $pclass;
2263 $processor->configured
= 0;
2264 if ($pclass->is_system_configured()) {
2265 $processor->configured
= 1;
2267 $processor->hassettings
= 0;
2268 if (is_readable($CFG->dirroot
.'/message/output/'.$processor->name
.'/settings.php')) {
2269 $processor->hassettings
= 1;
2271 $processor->available
= 1;
2273 print_error('errorcallingprocessor', 'message');
2276 $processor->available
= 0;
2281 // Filter out enabled and system_configured processors
2282 $readyprocessors = $processors;
2283 foreach ($readyprocessors as $readyprocessor) {
2284 if (!($readyprocessor->enabled
&& $readyprocessor->configured
)) {
2285 unset($readyprocessors[$readyprocessor->name
]);
2288 return $readyprocessors;
2295 * Get all message providers, validate their plugin existance and
2296 * system configuration
2298 * @return mixed $processors array of objects containing information on message processors
2300 function get_message_providers() {
2302 require_once($CFG->libdir
. '/pluginlib.php');
2303 $pluginman = plugin_manager
::instance();
2305 $providers = $DB->get_records('message_providers', null, 'name');
2307 // Remove all the providers whose plugins are disabled or don't exist
2308 foreach ($providers as $providerid => $provider) {
2309 $plugin = $pluginman->get_plugin_info($provider->component
);
2311 if ($plugin->get_status() === plugin_manager
::PLUGIN_STATUS_MISSING
) {
2312 unset($providers[$providerid]); // Plugins does not exist
2315 if ($plugin->is_enabled() === false) {
2316 unset($providers[$providerid]); // Plugin disabled
2325 * Get an instance of the message_output class for one of the output plugins.
2326 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2327 * @return message_output message_output the requested class.
2329 function get_message_processor($type) {
2332 // Note, we cannot use the get_message_processors function here, becaues this
2333 // code is called during install after installing each messaging plugin, and
2334 // get_message_processors caches the list of installed plugins.
2336 $processorfile = $CFG->dirroot
. "/message/output/{$type}/message_output_{$type}.php";
2337 if (!is_readable($processorfile)) {
2338 throw new coding_exception('Unknown message processor type ' . $type);
2341 include_once($processorfile);
2343 $processclass = 'message_output_' . $type;
2344 if (!class_exists($processclass)) {
2345 throw new coding_exception('Message processor ' . $type .
2346 ' does not define the right class');
2349 return new $processclass();
2353 * Get messaging outputs default (site) preferences
2355 * @return object $processors object containing information on message processors
2357 function get_message_output_default_preferences() {
2358 return get_config('message');
2362 * Translate message default settings from binary value to the array of string
2363 * representing the settings to be stored. Also validate the provided value and
2364 * use default if it is malformed.
2366 * @param int $plugindefault Default setting suggested by plugin
2367 * @param string $processorname The name of processor
2368 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2370 function translate_message_default_setting($plugindefault, $processorname) {
2371 // Preset translation arrays
2372 $permittedvalues = array(
2373 0x04 => 'disallowed',
2374 0x08 => 'permitted',
2378 $loggedinstatusvalues = array(
2379 0x00 => null, // use null if loggedin/loggedoff is not defined
2381 0x02 => 'loggedoff',
2384 // define the default setting
2385 $processor = get_message_processor($processorname);
2386 $default = $processor->get_default_messaging_settings();
2388 // Validate the value. It should not exceed the maximum size
2389 if (!is_int($plugindefault) ||
($plugindefault > 0x0f)) {
2390 debugging(get_string('errortranslatingdefault', 'message'));
2391 $plugindefault = $default;
2393 // Use plugin default setting of 'permitted' is 0
2394 if (!($plugindefault & MESSAGE_PERMITTED_MASK
)) {
2395 $plugindefault = $default;
2398 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK
];
2399 $loggedin = $loggedoff = null;
2401 if (($plugindefault & MESSAGE_PERMITTED_MASK
) == MESSAGE_PERMITTED
) {
2402 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN
];
2403 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF
];
2406 return array($permitted, $loggedin, $loggedoff);
2410 * Return a list of page types
2411 * @param string $pagetype current page type
2412 * @param stdClass $parentcontext Block's parent context
2413 * @param stdClass $currentcontext Current context of block
2415 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2416 return array('messages-*'=>get_string('page-message-x', 'message'));
2420 * Is $USER one of the supplied users?
2422 * $user2 will be null if viewing a user's recent conversations
2424 * @param stdClass the first user
2425 * @param stdClass the second user or null
2426 * @return bool True if the current user is one of either $user1 or $user2
2428 function message_current_user_is_involved($user1, $user2) {
2431 if (empty($user1->id
) ||
(!empty($user2) && empty($user2->id
))) {
2432 throw new coding_exception('Invalid user object detected. Missing id.');
2435 if ($user1->id
!= $USER->id
&& (empty($user2) ||
$user2->id
!= $USER->id
)) {