2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library functions for messaging
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir
.'/eventslib.php');
27 define ('MESSAGE_SHORTLENGTH', 300);
29 define ('MESSAGE_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
75 * Print the selector that allows the user to view their contacts, course participants, their recent
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86 * @param bool $showactionlinks show action links (add/remove contact etc)
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
93 echo html_writer
::start_tag('div', array('class' => 'contactselector mdl-align'));
95 //if 0 unread messages and they've requested unread messages then show contacts
96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
97 $viewing = MESSAGE_VIEW_CONTACTS
;
100 //if they have no blocked users and they've requested blocked users switch them over to contacts
101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED
) {
102 $viewing = MESSAGE_VIEW_CONTACTS
;
105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id
, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES
) {
117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 1, $showactionlinks,$strunreadmessages, $user2);
118 } else if ($viewing == MESSAGE_VIEW_CONTACTS ||
$viewing == MESSAGE_VIEW_SEARCH ||
$viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS ||
$viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS
) {
119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url
, 0, $showactionlinks, $strunreadmessages, $user2);
120 } else if ($viewing == MESSAGE_VIEW_BLOCKED
) {
121 message_print_blocked_users($blockedusers, $PAGE->url
, $showactionlinks, null, $user2);
122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE
) {
123 $courseidtoshow = intval(substr($viewing, 7));
125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url
, $showactionlinks, null, $page, $user2);
131 //shouldn't get here. User trying to access a course they're not in perhaps.
132 add_to_log(SITEID
, 'message', 'view', 'index.php', $viewing);
136 // Only show the search button if we're viewing our own messages.
137 // Search isn't currently able to deal with user A wanting to search user B's messages.
138 if ($showactionlinks) {
139 echo html_writer
::start_tag('form', array('action' => 'index.php','method' => 'GET'));
140 echo html_writer
::start_tag('fieldset');
141 $managebuttonclass = 'visible';
142 if ($viewing == MESSAGE_VIEW_SEARCH
) {
143 $managebuttonclass = 'hiddenelement';
145 $strmanagecontacts = get_string('search','message');
146 echo html_writer
::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH
));
147 echo html_writer
::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
148 echo html_writer
::end_tag('fieldset');
149 echo html_writer
::end_tag('form');
152 echo html_writer
::end_tag('div');
156 * Print course participants. Called by message_print_contact_selector()
158 * @param object $context the course context
159 * @param int $courseid the course ID
160 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
161 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
162 * @param string $titletodisplay Optionally specify a title to display above the participants
163 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
164 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
167 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
168 global $DB, $USER, $PAGE, $OUTPUT;
170 if (empty($titletodisplay)) {
171 $titletodisplay = get_string('participants');
174 $countparticipants = count_enrolled_users($context);
176 list($esql, $params) = get_enrolled_sql($context);
177 $params['mcuserid'] = $USER->id
;
178 $ufields = user_picture
::fields('u');
180 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
182 JOIN ($esql) je ON je.id = u.id
183 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
184 WHERE u.deleted = 0";
186 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE
, MESSAGE_CONTACTS_PER_PAGE
);
188 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE
, $PAGE->url
, 'page');
189 echo $OUTPUT->render($pagingbar);
191 echo html_writer
::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
193 echo html_writer
::start_tag('tr');
194 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
195 echo html_writer
::end_tag('tr');
197 foreach ($participants as $participant) {
198 if ($participant->id
!= $USER->id
) {
202 if ( $participant->contactlistid
) {
203 if ($participant->blocked
== 0) {
204 // Is contact. Is not blocked.
214 $participant->messagecount
= 0;//todo it would be nice if the course participant could report new messages
215 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
219 echo html_writer
::end_tag('table');
223 * Retrieve users blocked by $user1
225 * @param object $user1 the user whose messages are being viewed
226 * @param object $user2 the user $user1 is talking to. If they are being blocked
227 * they will have a variable called 'isblocked' added to their user object
228 * @return array the users blocked by $user1
230 function message_get_blocked_users($user1=null, $user2=null) {
237 if (!empty($user2)) {
238 $user2->isblocked
= false;
241 $blockedusers = array();
243 $userfields = user_picture
::fields('u', array('lastaccess'));
244 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
245 FROM {message_contacts} mc
246 JOIN {user} u ON u.id = mc.contactid
247 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
248 WHERE mc.userid = :user1id2 AND mc.blocked = 1
250 ORDER BY u.firstname ASC";
251 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id
, 'user1id2' => $user1->id
));
253 foreach($rs as $rd) {
254 $blockedusers[] = $rd;
256 if (!empty($user2) && $user2->id
== $rd->id
) {
257 $user2->isblocked
= true;
262 return $blockedusers;
266 * Print users blocked by $user1. Called by message_print_contact_selector()
268 * @param array $blockedusers the users blocked by $user1
269 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
270 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
271 * @param string $titletodisplay Optionally specify a title to display above the participants
272 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
275 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
278 $countblocked = count($blockedusers);
280 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
282 if (!empty($titletodisplay)) {
283 echo html_writer
::start_tag('tr');
284 echo html_writer
::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
285 echo html_writer
::end_tag('tr');
289 echo html_writer
::start_tag('tr');
290 echo html_writer
::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
291 echo html_writer
::end_tag('tr');
293 $isuserblocked = true;
294 $isusercontact = false;
295 foreach ($blockedusers as $blockeduser) {
296 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
300 echo html_writer
::end_tag('table');
304 * Retrieve $user1's contacts (online, offline and strangers)
306 * @param object $user1 the user whose messages are being viewed
307 * @param object $user2 the user $user1 is talking to. If they are a contact
308 * they will have a variable called 'iscontact' added to their user object
309 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
311 function message_get_contacts($user1=null, $user2=null) {
312 global $DB, $CFG, $USER;
318 if (!empty($user2)) {
319 $user2->iscontact
= false;
322 $timetoshowusers = 300; //Seconds default
323 if (isset($CFG->block_online_users_timetosee
)) {
324 $timetoshowusers = $CFG->block_online_users_timetosee
* 60;
327 // time which a user is counting as being active since
328 $timefrom = time()-$timetoshowusers;
330 // people in our contactlist who are online
331 $onlinecontacts = array();
332 // people in our contactlist who are offline
333 $offlinecontacts = array();
334 // people who are not in our contactlist but have sent us a message
335 $strangers = array();
337 $userfields = user_picture
::fields('u', array('lastaccess'));
339 // get all in our contactlist who are not blocked in our contact list
340 // and count messages we have waiting from each of them
341 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
342 FROM {message_contacts} mc
343 JOIN {user} u ON u.id = mc.contactid
344 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
345 WHERE mc.userid = ? AND mc.blocked = 0
347 ORDER BY u.firstname ASC";
349 $rs = $DB->get_recordset_sql($contactsql, array($user1->id
, $user1->id
));
350 foreach ($rs as $rd) {
351 if ($rd->lastaccess
>= $timefrom) {
352 // they have been active recently, so are counted online
353 $onlinecontacts[] = $rd;
356 $offlinecontacts[] = $rd;
359 if (!empty($user2) && $user2->id
== $rd->id
) {
360 $user2->iscontact
= true;
365 // get messages from anyone who isn't in our contact list and count the number
366 // of messages we have from each of them
367 $strangersql = "SELECT $userfields, count(m.id) as messagecount
369 JOIN {user} u ON u.id = m.useridfrom
370 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
371 WHERE mc.id IS NULL AND m.useridto = ?
373 ORDER BY u.firstname ASC";
375 $rs = $DB->get_recordset_sql($strangersql, array($USER->id
));
376 foreach ($rs as $rd) {
381 return array($onlinecontacts, $offlinecontacts, $strangers);
385 * Print $user1's contacts. Called by message_print_contact_selector()
387 * @param array $onlinecontacts $user1's contacts which are online
388 * @param array $offlinecontacts $user1's contacts which are offline
389 * @param array $strangers users which are not contacts but who have messaged $user1
390 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
391 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
392 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
393 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
394 * @param string $titletodisplay Optionally specify a title to display above the participants
395 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
398 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
399 global $CFG, $PAGE, $OUTPUT;
401 $countonlinecontacts = count($onlinecontacts);
402 $countofflinecontacts = count($offlinecontacts);
403 $countstrangers = count($strangers);
404 $isuserblocked = null;
406 if ($countonlinecontacts +
$countofflinecontacts == 0) {
407 echo html_writer
::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
410 echo html_writer
::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
412 if (!empty($titletodisplay)) {
413 message_print_heading($titletodisplay);
416 if($countonlinecontacts) {
417 // Print out list of online contacts.
419 if (empty($titletodisplay)) {
420 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
423 $isuserblocked = false;
424 $isusercontact = true;
425 foreach ($onlinecontacts as $contact) {
426 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
427 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
432 if ($countofflinecontacts) {
433 // Print out list of offline contacts.
435 if (empty($titletodisplay)) {
436 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
439 $isuserblocked = false;
440 $isusercontact = true;
441 foreach ($offlinecontacts as $contact) {
442 if ($minmessages == 0 ||
$contact->messagecount
>= $minmessages) {
443 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
449 // Print out list of incoming contacts.
450 if ($countstrangers) {
451 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
453 $isuserblocked = false;
454 $isusercontact = false;
455 foreach ($strangers as $stranger) {
456 if ($minmessages == 0 ||
$stranger->messagecount
>= $minmessages) {
457 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
462 echo html_writer
::end_tag('table');
464 if ($countstrangers && ($countonlinecontacts +
$countofflinecontacts == 0)) { // Extra help
465 echo html_writer
::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
470 * Print a select box allowing the user to choose to view new messages, course participants etc.
472 * Called by message_print_contact_selector()
473 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
474 * @param array $courses array of course objects. The courses the user is enrolled in.
475 * @param array $coursecontexts array of course contexts. Keyed on course id.
476 * @param int $countunreadtotal how many unread messages does the user have?
477 * @param int $countblocked how many users has the current user blocked?
478 * @param stdClass $user1 The user whose messages we are viewing.
479 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
482 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
485 if ($countunreadtotal>0) { //if there are unread messages
486 $options[MESSAGE_VIEW_UNREAD_MESSAGES
] = $strunreadmessages;
489 $str = get_string('contacts', 'message');
490 $options[MESSAGE_VIEW_CONTACTS
] = $str;
492 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS
] = get_string('mostrecentconversations', 'message');
493 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS
] = get_string('mostrecentnotifications', 'message');
495 if (!empty($courses)) {
496 $courses_options = array();
498 foreach($courses as $course) {
499 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id
])) {
500 //Not using short_text() as we want the end of the course name. Not the beginning.
501 $shortname = format_string($course->shortname
, true, array('context' => $coursecontexts[$course->id
]));
502 if (core_text
::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH
) {
503 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = '...'.core_text
::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH
);
505 $courses_options[MESSAGE_VIEW_COURSE
.$course->id
] = $shortname;
510 if (!empty($courses_options)) {
511 $options[] = array(get_string('courses') => $courses_options);
515 if ($countblocked>0) {
516 $str = get_string('blockedusers','message', $countblocked);
517 $options[MESSAGE_VIEW_BLOCKED
] = $str;
520 echo html_writer
::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
521 echo html_writer
::start_tag('fieldset');
522 if ( !empty($user1) && !empty($user1->id
) ) {
523 echo html_writer
::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id
));
525 echo html_writer
::label(get_string('messagenavigation', 'message'), 'viewing');
526 echo html_writer
::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
527 echo html_writer
::end_tag('fieldset');
528 echo html_writer
::end_tag('form');
532 * Load the course contexts for all of the users courses
534 * @param array $courses array of course objects. The courses the user is enrolled in.
535 * @return array of course contexts
537 function message_get_course_contexts($courses) {
538 $coursecontexts = array();
540 foreach($courses as $course) {
541 $coursecontexts[$course->id
] = context_course
::instance($course->id
);
544 return $coursecontexts;
548 * strip off action parameters like 'removecontact'
550 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
551 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
553 function message_remove_url_params($moodleurl) {
554 $newurl = new moodle_url($moodleurl);
555 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
556 return $newurl->out();
560 * Count the number of messages with a field having a specified value.
561 * if $field is empty then return count of the whole array
562 * if $field is non-existent then return 0
564 * @param array $messagearray array of message objects
565 * @param string $field the field to inspect on the message objects
566 * @param string $value the value to test the field against
568 function message_count_messages($messagearray, $field='', $value='') {
569 if (!is_array($messagearray)) return 0;
570 if ($field == '' or empty($messagearray)) return count($messagearray);
573 foreach ($messagearray as $message) {
574 $count +
= ($message->$field == $value) ?
1 : 0;
580 * Returns the count of unread messages for user. Either from a specific user or from all users.
582 * @param object $user1 the first user. Defaults to $USER
583 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
584 * @return int the count of $user1's unread messages
586 function message_count_unread_messages($user1=null, $user2=null) {
593 if (!empty($user2)) {
594 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
595 array($user1->id
, $user2->id
), "COUNT('id')");
597 return $DB->count_records_select('message', "useridto = ?",
598 array($user1->id
), "COUNT('id')");
603 * Count the number of users blocked by $user1
605 * @param object $user1 user object
606 * @return int the number of blocked users
608 function message_count_blocked_users($user1=null) {
615 $sql = "SELECT count(mc.id)
616 FROM {message_contacts} mc
617 WHERE mc.userid = :userid AND mc.blocked = 1";
618 $params = array('userid' => $user1->id
);
620 return $DB->count_records_sql($sql, $params);
624 * Print the search form and search results if a search has been performed
626 * @param boolean $advancedsearch show basic or advanced search form
627 * @param object $user1 the current user
628 * @return boolean true if a search was performed
630 function message_print_search($advancedsearch = false, $user1=null) {
631 $frm = data_submitted();
633 $doingsearch = false;
635 if (confirm_sesskey()) {
636 $doingsearch = !empty($frm->combinedsubmit
) ||
!empty($frm->keywords
) ||
(!empty($frm->personsubmit
) and !empty($frm->name
));
642 if (!empty($frm->combinedsearch
)) {
643 $combinedsearchstring = $frm->combinedsearch
;
645 //$combinedsearchstring = get_string('searchcombined','message').'...';
646 $combinedsearchstring = '';
650 if ($advancedsearch) {
653 if (!empty($frm->keywords
)) {
654 $messagesearch = $frm->keywords
;
657 if (!empty($frm->name
)) {
658 $personsearch = $frm->name
;
660 include('search_advanced.html');
662 include('search.html');
665 $showicontext = false;
666 message_print_search_results($frm, $showicontext, $user1);
671 if ($advancedsearch) {
672 $personsearch = $messagesearch = '';
673 include('search_advanced.html');
675 include('search.html');
682 * Get the users recent conversations meaning all the people they've recently
683 * sent or received a message from plus the most recent message sent to or received from each other user
685 * @param object $user the current user
686 * @param int $limitfrom can be used for paging
687 * @param int $limitto can be used for paging
690 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
693 $userfields = user_picture
::fields('u', array('lastaccess'));
694 //This query retrieves the last message received from and sent to each user
695 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
696 //It then joins with some other tables to get some additional data we need
698 //message ID is used instead of timecreated as it should sort the same and will be much faster
700 //There is a separate query for read and unread queries as they are stored in different tables
701 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
702 $sql = "SELECT $userfields, mr.id as mid, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated, mc.id as contactlistid, mc.blocked
703 FROM {message_read} mr
705 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
707 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
708 FROM {message_read} mr1
709 WHERE mr1.useridfrom = :userid1
710 AND mr1.notification = 0
711 GROUP BY mr1.useridto
713 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
714 FROM {message_read} mr2
715 WHERE mr2.useridto = :userid2
716 AND mr2.notification = 0
717 GROUP BY mr2.useridfrom
719 GROUP BY messages.userid
720 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
721 JOIN {user} u ON u.id = messages2.userid
722 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
723 WHERE u.deleted = '0'
724 ORDER BY mr.id DESC";
725 $params = array('userid1' => $user->id
, 'userid2' => $user->id
, 'userid3' => $user->id
);
726 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
728 $sql = "SELECT $userfields, m.id as mid, m.notification, m.smallmessage, m.fullmessage, m.fullmessagehtml, m.fullmessageformat, m.timecreated, mc.id as contactlistid, mc.blocked
731 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
733 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
735 WHERE m1.useridfrom = :userid1
736 AND m1.notification = 0
739 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
741 WHERE m2.useridto = :userid2
742 AND m2.notification = 0
743 GROUP BY m2.useridfrom
745 GROUP BY messages.userid
746 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
747 JOIN {user} u ON u.id = messages2.userid
748 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
749 WHERE u.deleted = '0'
751 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
753 $conversations = array();
755 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
756 //$conversation->id (the array key) is the other user's ID
757 $conversation_arrays = array($unread, $read);
758 foreach ($conversation_arrays as $conversation_array) {
759 foreach ($conversation_array as $conversation) {
760 if (empty($conversations[$conversation->id
]) ||
$conversations[$conversation->id
]->timecreated
< $conversation->timecreated
) {
761 $conversations[$conversation->id
] = $conversation;
766 // Sort the conversations by $conversation->timecreated, newest to oldest
767 // There may be multiple conversations with the same timecreated
768 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
769 $result = core_collator
::asort_objects_by_property($conversations, 'timecreated', core_collator
::SORT_NUMERIC
);
770 $conversations = array_reverse($conversations);
772 return $conversations;
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.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, 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($user1 = null, $showicontext = false, $showactionlinks = true) {
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($user1);
817 // Attach context url information to create the "View this conversation" type links
818 foreach($conversations as $conversation) {
819 $conversation->contexturl
= new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
820 $conversation->contexturlname
= get_string('thisconversation', 'message');
823 $showotheruser = true;
824 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
828 * Print the user's recent notifications
830 * @param stdClass $user the current user
832 function message_print_recent_notifications($user=null) {
835 echo html_writer
::start_tag('p', array('class' => 'heading'));
836 echo get_string('mostrecentnotifications', 'message');
837 echo html_writer
::end_tag('p');
843 $notifications = message_get_recent_notifications($user);
845 $showicontext = false;
846 $showotheruser = false;
847 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
851 * Print a list of recent messages
855 * @param array $messages the messages to display
856 * @param stdClass $user the current user
857 * @param bool $showotheruser display information on the other user?
858 * @param bool $showicontext show text next to the action icons?
859 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
860 * @param bool $showactionlinks
863 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
867 if (empty($dateformat)) {
868 $dateformat = get_string('strftimedatetimeshort');
871 echo html_writer
::start_tag('div', array('class' => 'messagerecent'));
872 foreach ($messages as $message) {
873 echo html_writer
::start_tag('div', array('class' => 'singlemessage'));
875 if ($showotheruser) {
876 $strcontact = $strblock = $strhistory = null;
878 if ($showactionlinks) {
879 if ( $message->contactlistid
) {
880 if ($message->blocked
== 0) { // The other user isn't blocked.
881 $strcontact = message_contact_link($message->id
, 'remove', true, null, $showicontext);
882 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
883 } else { // The other user is blocked.
884 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
885 $strblock = message_contact_link($message->id
, 'unblock', true, null, $showicontext);
888 $strcontact = message_contact_link($message->id
, 'add', true, null, $showicontext);
889 $strblock = message_contact_link($message->id
, 'block', true, null, $showicontext);
892 //should we show just the icon or icon and text?
893 $histicontext = 'icon';
895 $histicontext = 'both';
897 $strhistory = message_history_link($user->id
, $message->id
, true, '', '', $histicontext);
899 echo html_writer
::start_tag('span', array('class' => 'otheruser'));
901 echo html_writer
::start_tag('span', array('class' => 'pix'));
902 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID
));
903 echo html_writer
::end_tag('span');
905 echo html_writer
::start_tag('span', array('class' => 'contact'));
907 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
909 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
911 echo html_writer
::end_tag('span');//end contact
913 if ($showactionlinks) {
914 echo $strcontact.$strblock.$strhistory;
916 echo html_writer
::end_tag('span');//end otheruser
919 $messagetext = message_format_message_text($message, $forcetexttohtml);
921 echo html_writer
::tag('span', userdate($message->timecreated
, $dateformat), array('class' => 'messagedate'));
922 echo html_writer
::tag('span', $messagetext, array('class' => 'themessage'));
923 echo message_format_contexturl($message);
924 echo html_writer
::end_tag('div');//end singlemessage
926 echo html_writer
::end_tag('div');//end messagerecent
930 * Try to guess how to convert the message to html.
934 * @param stdClass $message
935 * @param bool $forcetexttohtml
936 * @return string html fragment
938 function message_format_message_text($message, $forcetexttohtml = false) {
939 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
941 $options = new stdClass();
942 $options->para
= false;
944 $format = $message->fullmessageformat
;
946 if ($message->smallmessage
!== '') {
947 if ($message->notification
== 1) {
948 if ($message->fullmessagehtml
!== '' or $message->fullmessage
!== '') {
949 $format = FORMAT_PLAIN
;
952 $messagetext = $message->smallmessage
;
954 } else if ($message->fullmessageformat
== FORMAT_HTML
) {
955 if ($message->fullmessagehtml
!== '') {
956 $messagetext = $message->fullmessagehtml
;
958 $messagetext = $message->fullmessage
;
959 $format = FORMAT_MOODLE
;
963 if ($message->fullmessage
!== '') {
964 $messagetext = $message->fullmessage
;
966 $messagetext = $message->fullmessagehtml
;
967 $format = FORMAT_HTML
;
971 if ($forcetexttohtml) {
972 // This is a crazy hack, why not set proper format when creating the notifications?
973 if ($format === FORMAT_PLAIN
) {
974 $format = FORMAT_MOODLE
;
977 return format_text($messagetext, $format, $options);
981 * Add the selected user as a contact for the current user
983 * @param int $contactid the ID of the user to add as a contact
984 * @param int $blocked 1 if you wish to block the contact
985 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
986 * Otherwise returns the result of update_record() or insert_record()
988 function message_add_contact($contactid, $blocked=0) {
991 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
995 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid))) !== false) {
996 // A record already exists. We may be changing blocking status.
998 if ($contact->blocked
!== $blocked) {
999 // Blocking status has been changed.
1000 $contact->blocked
= $blocked;
1001 return $DB->update_record('message_contacts', $contact);
1003 // No change to blocking status.
1008 // New contact record.
1009 $contact = new stdClass();
1010 $contact->userid
= $USER->id
;
1011 $contact->contactid
= $contactid;
1012 $contact->blocked
= $blocked;
1013 return $DB->insert_record('message_contacts', $contact, false);
1020 * @param int $contactid the user ID of the contact to remove
1021 * @return bool returns the result of delete_records()
1023 function message_remove_contact($contactid) {
1025 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
1029 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1031 * @param int $contactid the user ID of the contact to unblock
1032 * @return bool returns the result of delete_records()
1034 function message_unblock_contact($contactid) {
1036 return $DB->delete_records('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
1042 * @param int $contactid the user ID of the user to block
1044 function message_block_contact($contactid) {
1045 return message_add_contact($contactid, 1);
1049 * Load a user's contact record
1051 * @param int $contactid the user ID of the user whose contact record you want
1052 * @return array message contacts
1054 function message_get_contact($contactid) {
1056 return $DB->get_record('message_contacts', array('userid' => $USER->id
, 'contactid' => $contactid));
1060 * Print the results of a message search
1062 * @param mixed $frm submitted form data
1063 * @param bool $showicontext show text next to action icons?
1064 * @param object $currentuser the current user
1067 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1068 global $USER, $DB, $OUTPUT;
1070 if (empty($currentuser)) {
1071 $currentuser = $USER;
1074 echo html_writer
::start_tag('div', array('class' => 'mdl-left'));
1076 $personsearch = false;
1077 $personsearchstring = null;
1078 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
1079 $personsearch = true;
1080 $personsearchstring = $frm->name
;
1081 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1082 $personsearch = true;
1083 $personsearchstring = $frm->combinedsearch
;
1086 // Search for person.
1087 if ($personsearch) {
1088 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
1090 $mycourses = enrol_get_my_courses('id');
1091 $mycoursesids = array();
1092 foreach ($mycourses as $mycourse) {
1093 $mycoursesids[] = $mycourse->id
;
1095 $susers = message_search_users($mycoursesids, $personsearchstring);
1096 foreach ($susers as $suser) {
1097 $users[$suser->id
] = $suser;
1100 $users = message_search_users(SITEID
, $personsearchstring);
1103 if (!empty($users)) {
1104 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1105 echo get_string('userssearchresults', 'message', count($users));
1106 echo html_writer
::end_tag('p');
1108 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults'));
1109 foreach ($users as $user) {
1111 if ( $user->contactlistid
) {
1112 if ($user->blocked
== 0) { // User is not blocked.
1113 $strcontact = message_contact_link($user->id
, 'remove', true, null, $showicontext);
1114 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1116 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1117 $strblock = message_contact_link($user->id
, 'unblock', true, null, $showicontext);
1120 $strcontact = message_contact_link($user->id
, 'add', true, null, $showicontext);
1121 $strblock = message_contact_link($user->id
, 'block', true, null, $showicontext);
1124 // Should we show just the icon or icon and text?
1125 $histicontext = 'icon';
1126 if ($showicontext) {
1127 $histicontext = 'both';
1129 $strhistory = message_history_link($USER->id
, $user->id
, true, '', '', $histicontext);
1131 echo html_writer
::start_tag('tr');
1133 echo html_writer
::start_tag('td', array('class' => 'pix'));
1134 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID
));
1135 echo html_writer
::end_tag('td');
1137 echo html_writer
::start_tag('td',array('class' => 'contact'));
1139 $link = new moodle_url("/message/index.php?id=$user->id");
1140 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1141 echo html_writer
::end_tag('td');
1143 echo html_writer
::tag('td', $strcontact, array('class' => 'link'));
1144 echo html_writer
::tag('td', $strblock, array('class' => 'link'));
1145 echo html_writer
::tag('td', $strhistory, array('class' => 'link'));
1147 echo html_writer
::end_tag('tr');
1149 echo html_writer
::end_tag('table');
1152 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1153 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1154 echo html_writer
::end_tag('p');
1158 // search messages for keywords
1159 $messagesearch = false;
1160 $messagesearchstring = null;
1161 if (!empty($frm->keywords
)) {
1162 $messagesearch = true;
1163 $messagesearchstring = clean_text(trim($frm->keywords
));
1164 } else if (!empty($frm->combinedsubmit
) and !empty($frm->combinedsearch
)) {
1165 $messagesearch = true;
1166 $messagesearchstring = clean_text(trim($frm->combinedsearch
));
1169 if ($messagesearch) {
1170 if ($messagesearchstring) {
1171 $keywords = explode(' ', $messagesearchstring);
1173 $keywords = array();
1179 if (empty($frm->keywordsoption
)) {
1180 $frm->keywordsoption
= 'allmine';
1183 switch ($frm->keywordsoption
) {
1198 $courseid = $frm->courseid
;
1205 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1207 // Get a list of contacts.
1208 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id
), '', 'contactid, blocked') ) === false) {
1209 $contacts = array();
1212 // Print heading with number of results.
1213 echo html_writer
::start_tag('p', array('class' => 'heading searchresultcount'));
1214 $countresults = count($messages);
1215 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS
) {
1216 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1218 echo get_string('keywordssearchresults', 'message', $countresults);
1220 echo html_writer
::end_tag('p');
1222 // Print table headings.
1223 echo html_writer
::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1225 $headertdstart = html_writer
::start_tag('td', array('class' => 'messagesearchresultscol'));
1226 $headertdend = html_writer
::end_tag('td');
1227 echo html_writer
::start_tag('tr');
1228 echo $headertdstart.get_string('from').$headertdend;
1229 echo $headertdstart.get_string('to').$headertdend;
1230 echo $headertdstart.get_string('message', 'message').$headertdend;
1231 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1232 echo html_writer
::end_tag('tr');
1235 $dateformat = get_string('strftimedatetimeshort');
1236 $strcontext = get_string('context', 'message');
1237 foreach ($messages as $message) {
1239 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1240 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
1241 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
1242 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
1249 // Load user-to record.
1250 if ($message->useridto
!== $USER->id
) {
1251 $userto = core_user
::get_user($message->useridto
);
1252 $tocontact = (array_key_exists($message->useridto
, $contacts) and
1253 ($contacts[$message->useridto
]->blocked
== 0) );
1254 $toblocked = (array_key_exists($message->useridto
, $contacts) and
1255 ($contacts[$message->useridto
]->blocked
== 1) );
1262 // Load user-from record.
1263 if ($message->useridfrom
!== $USER->id
) {
1264 $userfrom = core_user
::get_user($message->useridfrom
);
1265 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
1266 ($contacts[$message->useridfrom
]->blocked
== 0) );
1267 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
1268 ($contacts[$message->useridfrom
]->blocked
== 1) );
1271 $fromcontact = false;
1272 $fromblocked = false;
1275 // Find date string for this message.
1276 $date = usergetdate($message->timecreated
);
1277 $datestring = $date['year'].$date['mon'].$date['mday'];
1279 // Print out message row.
1280 echo html_writer
::start_tag('tr', array('valign' => 'top'));
1282 echo html_writer
::start_tag('td', array('class' => 'contact'));
1283 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1284 echo html_writer
::end_tag('td');
1286 echo html_writer
::start_tag('td', array('class' => 'contact'));
1287 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1288 echo html_writer
::end_tag('td');
1290 echo html_writer
::start_tag('td', array('class' => 'summary'));
1291 echo message_get_fragment($message->smallmessage
, $keywords);
1292 echo html_writer
::start_tag('div', array('class' => 'link'));
1294 // If the user clicks the context link display message sender on the left.
1295 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1296 $leftsideuserid = $rightsideuserid = null;
1297 if ($currentuser->id
== $message->useridto
) {
1298 $leftsideuserid = $message->useridto
;
1299 $rightsideuserid = $message->useridfrom
;
1301 $leftsideuserid = $message->useridfrom
;
1302 $rightsideuserid = $message->useridto
;
1304 message_history_link($leftsideuserid, $rightsideuserid, false,
1305 $messagesearchstring, 'm'.$message->id
, $strcontext);
1306 echo html_writer
::end_tag('div');
1307 echo html_writer
::end_tag('td');
1309 echo html_writer
::tag('td', userdate($message->timecreated
, $dateformat), array('class' => 'date'));
1311 echo html_writer
::end_tag('tr');
1315 if ($blockedcount > 0) {
1316 echo html_writer
::start_tag('tr');
1317 echo html_writer
::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1318 echo html_writer
::end_tag('tr');
1320 echo html_writer
::end_tag('table');
1323 echo html_writer
::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1327 if (!$personsearch && !$messagesearch) {
1328 //they didn't enter any search terms
1329 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1332 echo html_writer
::end_tag('div');
1336 * Print information on a user. Used when printing search results.
1338 * @param object/bool $user the user to display or false if you just want $USER
1339 * @param bool $iscontact is the user being displayed a contact?
1340 * @param bool $isblocked is the user being displayed blocked?
1341 * @param bool $includeicontext include text next to the action icons?
1344 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1345 global $USER, $OUTPUT;
1347 $userpictureparams = array('size' => 20, 'courseid' => SITEID
);
1349 if ($user === false) {
1350 echo $OUTPUT->user_picture($USER, $userpictureparams);
1351 } else if (core_user
::is_real_user($user->id
)) { // If not real user, then don't show any links.
1352 $userpictureparams['link'] = false;
1353 echo $OUTPUT->user_picture($USER, $userpictureparams);
1354 echo fullname($user);
1356 echo $OUTPUT->user_picture($user, $userpictureparams);
1358 $link = new moodle_url("/message/index.php?id=$user->id");
1359 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1360 get_string('sendmessageto', 'message', fullname($user))));
1365 message_contact_link($user->id
, 'remove', $return, $script, $includeicontext);
1367 message_contact_link($user->id
, 'add', $return, $script, $includeicontext);
1371 message_contact_link($user->id
, 'unblock', $return, $script, $includeicontext);
1373 message_contact_link($user->id
, 'block', $return, $script, $includeicontext);
1379 * Print a message contact link
1381 * @param int $userid the ID of the user to apply to action to
1382 * @param string $linktype can be add, remove, block or unblock
1383 * @param bool $return if true return the link as a string. If false echo the link.
1384 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1385 * @param bool $text include text next to the icons?
1386 * @param bool $icon include a graphical icon?
1387 * @return string if $return is true otherwise bool
1389 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1390 global $OUTPUT, $PAGE;
1392 //hold onto the strings as we're probably creating a bunch of links
1395 if (empty($script)) {
1396 //strip off previous action params like 'removecontact'
1397 $script = message_remove_url_params($PAGE->url
);
1400 if (empty($str->blockcontact
)) {
1401 $str = new stdClass();
1402 $str->blockcontact
= get_string('blockcontact', 'message');
1403 $str->unblockcontact
= get_string('unblockcontact', 'message');
1404 $str->removecontact
= get_string('removecontact', 'message');
1405 $str->addcontact
= get_string('addcontact', 'message');
1408 $command = $linktype.'contact';
1409 $string = $str->{$command};
1411 $safealttext = s($string);
1414 if (!empty($text)) {
1415 $safestring = $safealttext;
1421 switch ($linktype) {
1423 $iconpath = 't/block';
1426 $iconpath = 't/unblock';
1429 $iconpath = 't/removecontact';
1433 $iconpath = 't/addcontact';
1436 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1439 $output = '<span class="'.$linktype.'contact">'.
1440 '<a href="'.$script.'&'.$command.'='.$userid.
1441 '&sesskey='.sesskey().'" title="'.$safealttext.'">'.
1443 $safestring.'</a></span>';
1454 * echo or return a link to take the user to the full message history between themselves and another user
1456 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1457 * @param int $userid2 the ID of the other user
1458 * @param bool $return true to return the link as a string. False to echo the link.
1459 * @param string $keywords any keywords to highlight in the message history
1460 * @param string $position anchor name to jump to within the message history
1461 * @param string $linktext optionally specify the link text
1462 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1464 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1465 global $OUTPUT, $PAGE;
1466 static $strmessagehistory;
1468 if (empty($strmessagehistory)) {
1469 $strmessagehistory = get_string('messagehistory', 'message');
1473 $position = "#$position";
1476 $keywords = "&search=".urlencode($keywords);
1479 if ($linktext == 'icon') { // Icon only
1480 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1481 } else if ($linktext == 'both') { // Icon and standard name
1482 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1483 $fulllink .= ' '.$strmessagehistory;
1484 } else if ($linktext) { // Custom name
1485 $fulllink = $linktext;
1486 } else { // Standard name only
1487 $fulllink = $strmessagehistory;
1490 $popupoptions = array(
1494 'location' => false,
1496 'scrollbars' => true,
1497 'resizable' => true);
1499 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL
."&user1=$userid1&user2=$userid2$keywords$position");
1500 if ($PAGE->url
&& $PAGE->url
->get_param('viewing')) {
1501 $link->param('viewing', $PAGE->url
->get_param('viewing'));
1504 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1506 $str = '<span class="history">'.$str.'</span>';
1518 * Search through course users.
1520 * If $courseids contains the site course then this function searches
1521 * through all undeleted and confirmed users.
1523 * @param int|array $courseids Course ID or array of course IDs.
1524 * @param string $searchtext the text to search for.
1525 * @param string $sort the column name to order by.
1526 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1527 * @return array An array of {@link $USER} records.
1529 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1530 global $CFG, $USER, $DB;
1532 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1534 $courseids = array(SITEID
);
1537 // Allow an integer to be passed.
1538 if (!is_array($courseids)) {
1539 $courseids = array($courseids);
1542 $fullname = $DB->sql_fullname();
1543 $ufields = user_picture
::fields('u');
1545 if (!empty($sort)) {
1546 $order = ' ORDER BY '. $sort;
1552 'userid' => $USER->id
,
1553 'query' => "%$searchtext%"
1556 if (empty($exceptions)) {
1557 $exceptions = array();
1558 } else if (!empty($exceptions) && is_string($exceptions)) {
1559 $exceptions = explode(',', $exceptions);
1562 // Ignore self and guest account.
1563 $exceptions[] = $USER->id
;
1564 $exceptions[] = $CFG->siteguest
;
1566 // Exclude exceptions from the search result.
1567 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'param', false);
1568 $except = ' AND u.id ' . $except;
1569 $params = array_merge($params_except, $params);
1571 if (in_array(SITEID
, $courseids)) {
1572 // Search on site level.
1573 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1575 LEFT JOIN {message_contacts} mc
1576 ON mc.contactid = u.id AND mc.userid = :userid
1577 WHERE u.deleted = '0' AND u.confirmed = '1'
1578 AND (".$DB->sql_like($fullname, ':query', false).")
1582 // Search in courses.
1584 // Getting the context IDs or each course.
1585 $contextids = array();
1586 foreach ($courseids as $courseid) {
1587 $context = context_course
::instance($courseid);
1588 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1590 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED
, 'context');
1591 $params = array_merge($params, $contextparams);
1593 // Everyone who has a role assignment in this course or higher.
1594 // TODO: add enabled enrolment join here (skodak)
1595 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1597 JOIN {role_assignments} ra ON ra.userid = u.id
1598 LEFT JOIN {message_contacts} mc
1599 ON mc.contactid = u.id AND mc.userid = :userid
1600 WHERE u.deleted = '0' AND u.confirmed = '1'
1601 AND (".$DB->sql_like($fullname, ':query', false).")
1602 AND ra.contextid $contextwhere
1611 * Search a user's messages
1613 * Returns a list of posts found using an array of search terms
1614 * eg word +word -word
1616 * @param array $searchterms an array of search terms (strings)
1617 * @param bool $fromme include messages from the user?
1618 * @param bool $tome include messages to the user?
1619 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1620 * @param int $userid the user ID of the current user
1621 * @return mixed An array of messages or false if no matching messages were found
1623 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1624 global $CFG, $USER, $DB;
1626 // If user is searching all messages check they are allowed to before doing anything else.
1627 if ($courseid == SITEID
&& !has_capability('moodle/site:readallmessages', context_system
::instance())) {
1628 print_error('accessdenied','admin');
1631 // If no userid sent then assume current user.
1632 if ($userid == 0) $userid = $USER->id
;
1634 // Some differences in SQL syntax.
1635 if ($DB->sql_regex_supported()) {
1636 $REGEXP = $DB->sql_regex(true);
1637 $NOTREGEXP = $DB->sql_regex(false);
1640 $searchcond = array();
1644 // Preprocess search terms to check whether we have at least 1 eligible search term.
1645 // If we do we can drop words around it like 'a'.
1646 $dropshortwords = false;
1647 foreach ($searchterms as $searchterm) {
1648 if (strlen($searchterm) >= 2) {
1649 $dropshortwords = true;
1653 foreach ($searchterms as $searchterm) {
1656 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1658 if ($dropshortwords && strlen($searchterm) < 2) {
1661 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1662 if (!$DB->sql_regex_supported()) {
1663 if (substr($searchterm, 0, 1) == '-') {
1666 $searchterm = trim($searchterm, '+-');
1669 if (substr($searchterm,0,1) == "+") {
1670 $searchterm = substr($searchterm,1);
1671 $searchterm = preg_quote($searchterm, '|');
1672 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1673 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1675 } else if (substr($searchterm,0,1) == "-") {
1676 $searchterm = substr($searchterm,1);
1677 $searchterm = preg_quote($searchterm, '|');
1678 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1679 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1682 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1683 $params['ss'.$i] = "%$searchterm%";
1687 if (empty($searchcond)) {
1688 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1689 $params['ss1'] = "%";
1691 $searchcond = implode(" AND ", $searchcond);
1694 // There are several possibilities
1695 // 1. courseid = SITEID : The admin is searching messages by all users
1696 // 2. courseid = ?? : A teacher is searching messages by users in
1697 // one of their courses - currently disabled
1698 // 3. courseid = none : User is searching their own messages;
1699 // a. Messages from user
1700 // b. Messages to user
1701 // c. Messages to and from user
1703 if ($courseid == SITEID
) { // Admin is searching all messages.
1704 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1705 FROM {message_read} m
1706 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1707 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1709 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1711 } else if ($courseid !== 'none') {
1712 // This has not been implemented due to security concerns.
1714 $m_unread = array();
1718 if ($fromme and $tome) {
1719 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1720 $params['userid1'] = $userid;
1721 $params['userid2'] = $userid;
1723 } else if ($fromme) {
1724 $searchcond .= " AND m.useridfrom=:userid";
1725 $params['userid'] = $userid;
1728 $searchcond .= " AND m.useridto=:userid";
1729 $params['userid'] = $userid;
1732 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1733 FROM {message_read} m
1734 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1735 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1737 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS
);
1741 /// The keys may be duplicated in $m_read and $m_unread so we can't
1742 /// do a simple concatenation
1743 $messages = array();
1744 foreach ($m_read as $m) {
1747 foreach ($m_unread as $m) {
1751 return (empty($messages)) ?
false : $messages;
1755 * Given a message object that we already know has a long message
1756 * this function truncates the message nicely to the first
1757 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1759 * @param string $message the message
1760 * @param int $minlength the minimum length to trim the message to
1761 * @return string the shortened message
1763 function message_shorten_message($message, $minlength = 0) {
1766 $length = strlen($message);
1770 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
1773 for ($i=0; $i<$length; $i++
) {
1774 $char = $message[$i];
1786 if ($char == '.' or $char == ' ') {
1796 if ($count > $minlength) {
1806 return substr($message, 0, $truncate);
1811 * Given a string and an array of keywords, this function looks
1812 * for the first keyword in the string, and then chops out a
1813 * small section from the text that shows that word in context.
1815 * @param string $message the text to search
1816 * @param array $keywords array of keywords to find
1818 function message_get_fragment($message, $keywords) {
1821 $halfsize = (int)($fullsize/2);
1823 $message = strip_tags($message);
1825 foreach ($keywords as $keyword) { // Just get the first one
1826 if ($keyword !== '') {
1830 if (empty($keyword)) { // None found, so just return start of message
1831 return message_shorten_message($message, 30);
1834 $leadin = $leadout = '';
1836 /// Find the start of the fragment
1838 $length = strlen($message);
1840 $pos = strpos($message, $keyword);
1841 if ($pos > $halfsize) {
1842 $start = $pos - $halfsize;
1845 /// Find the end of the fragment
1846 $end = $start +
$fullsize;
1847 if ($end > $length) {
1853 /// Pull out the fragment and format it
1855 $fragment = substr($message, $start, $end - $start);
1856 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1861 * Retrieve the messages between two users
1863 * @param object $user1 the current user
1864 * @param object $user2 the other user
1865 * @param int $limitnum the maximum number of messages to retrieve
1866 * @param bool $viewingnewmessages are we currently viewing new messages?
1868 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1871 $messages = array();
1873 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1874 //desc to get the last $limitnum messages then flip the order in php
1880 $notificationswhere = null;
1881 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1882 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications
) {
1883 $notificationswhere = 'AND notification=0';
1886 //prevent notifications of your own actions appearing in your own message history
1887 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1889 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1890 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1891 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1892 "timecreated $sort", '*', 0, $limitnum)) {
1893 foreach ($messages_read as $message) {
1894 $messages[] = $message;
1897 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1898 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1899 array($user1->id
, $user2->id
, $user2->id
, $user1->id
, $user1->id
),
1900 "timecreated $sort", '*', 0, $limitnum)) {
1901 foreach ($messages_new as $message) {
1902 $messages[] = $message;
1906 $result = core_collator
::asort_objects_by_property($messages, 'timecreated', core_collator
::SORT_NUMERIC
);
1908 //if we only want the last $limitnum messages
1909 $messagecount = count($messages);
1910 if ($limitnum > 0 && $messagecount > $limitnum) {
1911 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1918 * Print the message history between two users
1920 * @param object $user1 the current user
1921 * @param object $user2 the other user
1922 * @param string $search search terms to highlight
1923 * @param int $messagelimit maximum number of messages to return
1924 * @param string $messagehistorylink the html for the message history link or false
1925 * @param bool $viewingnewmessages are we currently viewing new messages?
1927 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1928 global $CFG, $OUTPUT;
1930 echo $OUTPUT->box_start('center');
1931 echo html_writer
::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1932 echo html_writer
::start_tag('tr');
1934 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1935 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID
));
1936 echo html_writer
::tag('div', fullname($user1), array('class' => 'heading'));
1937 echo html_writer
::end_tag('td');
1939 echo html_writer
::start_tag('td', array('align' => 'center'));
1940 echo html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1941 echo html_writer
::end_tag('td');
1943 echo html_writer
::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1944 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID
));
1945 echo html_writer
::tag('div', fullname($user2), array('class' => 'heading'));
1947 if ($showactionlinks && isset($user2->iscontact
) && isset($user2->isblocked
)) {
1953 $strcontact = message_get_contact_add_remove_link($user2->iscontact
, $user2->isblocked
, $user2, $script, $text, $icon);
1954 $strblock = message_get_contact_block_link($user2->iscontact
, $user2->isblocked
, $user2, $script, $text, $icon);
1955 $useractionlinks = $strcontact.' |'.$strblock;
1957 echo html_writer
::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1960 echo html_writer
::end_tag('td');
1961 echo html_writer
::end_tag('tr');
1962 echo html_writer
::end_tag('table');
1963 echo $OUTPUT->box_end();
1965 if (!empty($messagehistorylink)) {
1966 echo $messagehistorylink;
1969 /// Get all the messages and print them
1970 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1971 $tablecontents = '';
1973 $current = new stdClass();
1974 $current->mday
= '';
1975 $current->month
= '';
1976 $current->year
= '';
1977 $messagedate = get_string('strftimetime');
1978 $blockdate = get_string('strftimedaydate');
1979 foreach ($messages as $message) {
1980 if ($message->notification
) {
1981 $notificationclass = ' notification';
1983 $notificationclass = null;
1985 $date = usergetdate($message->timecreated
);
1986 if ($current->mday
!= $date['mday'] |
$current->month
!= $date['month'] |
$current->year
!= $date['year']) {
1987 $current->mday
= $date['mday'];
1988 $current->month
= $date['month'];
1989 $current->year
= $date['year'];
1991 $datestring = html_writer
::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1992 $tablecontents .= html_writer
::tag('div', $datestring, array('class' => 'mdl-align heading'));
1994 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated
, $blockdate), 4, 'mdl-align');
1997 $formatted_message = $side = null;
1998 if ($message->useridfrom
== $user1->id
) {
1999 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2002 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2005 $tablecontents .= html_writer
::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2008 echo html_writer
::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2010 echo html_writer
::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2015 * Format a message for display in the message history
2017 * @param object $message the message object
2018 * @param string $format optional date format
2019 * @param string $keywords keywords to highlight
2020 * @param string $class CSS class to apply to the div around the message
2021 * @return string the formatted message
2023 function message_format_message($message, $format='', $keywords='', $class='other') {
2027 //if we haven't previously set the date format or they've supplied a new one
2028 if ( empty($dateformat) ||
(!empty($format) && $dateformat != $format) ) {
2030 $dateformat = $format;
2032 $dateformat = get_string('strftimedatetimeshort');
2035 $time = userdate($message->timecreated
, $dateformat);
2037 $messagetext = message_format_message_text($message, false);
2040 $messagetext = highlight($keywords, $messagetext);
2043 $messagetext .= message_format_contexturl($message);
2046 <div class='message $class'>
2047 <a name="m'.{$message->id}.'"></a>
2048 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2054 * Format a the context url and context url name of a message for display
2056 * @param object $message the message object
2057 * @return string the formatted string
2059 function message_format_contexturl($message) {
2062 if (!empty($message->contexturl
)) {
2063 $displaytext = null;
2064 if (!empty($message->contexturlname
)) {
2065 $displaytext= $message->contexturlname
;
2067 $displaytext= $message->contexturl
;
2069 $s .= html_writer
::start_tag('div',array('class' => 'messagecontext'));
2070 $s .= get_string('view').': '.html_writer
::tag('a', $displaytext, array('href' => $message->contexturl
));
2071 $s .= html_writer
::end_tag('div');
2078 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2080 * @param object $userfrom the message sender
2081 * @param object $userto the message recipient
2082 * @param string $message the message
2083 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2084 * @return int|false the ID of the new message or false
2086 function message_post_message($userfrom, $userto, $message, $format) {
2087 global $SITE, $CFG, $USER;
2089 $eventdata = new stdClass();
2090 $eventdata->component
= 'moodle';
2091 $eventdata->name
= 'instantmessage';
2092 $eventdata->userfrom
= $userfrom;
2093 $eventdata->userto
= $userto;
2095 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2096 $eventdata->subject
= get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang
);
2098 if ($format == FORMAT_HTML
) {
2099 $eventdata->fullmessagehtml
= $message;
2100 //some message processors may revert to sending plain text even if html is supplied
2101 //so we keep both plain and html versions if we're intending to send html
2102 $eventdata->fullmessage
= html_to_text($eventdata->fullmessagehtml
);
2104 $eventdata->fullmessage
= $message;
2105 $eventdata->fullmessagehtml
= '';
2108 $eventdata->fullmessageformat
= $format;
2109 $eventdata->smallmessage
= $message;//store the message unfiltered. Clean up on output.
2111 $s = new stdClass();
2112 $s->sitename
= format_string($SITE->shortname
, true, array('context' => context_course
::instance(SITEID
)));
2113 $s->url
= $CFG->wwwroot
.'/message/index.php?user='.$userto->id
.'&id='.$userfrom->id
;
2115 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang
);
2116 if (!empty($eventdata->fullmessage
)) {
2117 $eventdata->fullmessage
.= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2119 if (!empty($eventdata->fullmessagehtml
)) {
2120 $eventdata->fullmessagehtml
.= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2123 $eventdata->timecreated
= time();
2124 return message_send($eventdata);
2128 * Print a row of contactlist displaying user picture, messages waiting and
2131 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2132 * @param bool $incontactlist is the user a contact of ours?
2133 * @param bool $isblocked is the user blocked?
2134 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2135 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2136 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2139 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2140 global $OUTPUT, $USER, $COURSE;
2141 $fullname = fullname($contact);
2142 $fullnamelink = $fullname;
2145 if (!empty($selecteduser) && $contact->id
== $selecteduser->id
) {
2146 $linkclass = 'messageselecteduser';
2149 // Are there any unread messages for this contact?
2150 if ($contact->messagecount
> 0 ){
2151 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount
.')</strong>';
2154 $strcontact = $strblock = $strhistory = null;
2156 if ($showactionlinks) {
2157 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2158 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2159 $strhistory = message_history_link($USER->id
, $contact->id
, true, '', '', 'icon');
2162 echo html_writer
::start_tag('tr');
2163 echo html_writer
::start_tag('td', array('class' => 'pix'));
2164 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id
));
2165 echo html_writer
::end_tag('td');
2167 echo html_writer
::start_tag('td', array('class' => 'contact'));
2169 $popupoptions = array(
2170 'height' => MESSAGE_DISCUSSION_HEIGHT
,
2171 'width' => MESSAGE_DISCUSSION_WIDTH
,
2173 'location' => false,
2175 'scrollbars' => true,
2176 'resizable' => true);
2178 $link = $action = null;
2179 if (!empty($selectcontacturl)) {
2180 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id
);
2182 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2183 $link = new moodle_url("/message/index.php?id=$contact->id");
2184 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2186 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2188 echo html_writer
::end_tag('td');
2190 echo html_writer
::tag('td', ' '.$strcontact.$strblock.' '.$strhistory, array('class' => 'link'));
2192 echo html_writer
::end_tag('tr');
2196 * Constructs the add/remove contact link to display next to other users
2198 * @param bool $incontactlist is the user a contact
2199 * @param bool $isblocked is the user blocked
2200 * @param stdClass $contact contact object
2201 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2202 * @param bool $text include text next to the icons?
2203 * @param bool $icon include a graphical icon?
2206 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2210 $strcontact = message_contact_link($contact->id
, 'remove', true, $script, $text, $icon);
2211 } else if ($isblocked) {
2212 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2214 $strcontact = message_contact_link($contact->id
, 'add', true, $script, $text, $icon);
2221 * Constructs the block contact link to display next to other users
2223 * @param bool $incontactlist is the user a contact?
2224 * @param bool $isblocked is the user blocked?
2225 * @param stdClass $contact contact object
2226 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2227 * @param bool $text include text next to the icons?
2228 * @param bool $icon include a graphical icon?
2231 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2234 //commented out to allow the user to block a contact without having to remove them first
2235 /*if ($incontactlist) {
2239 $strblock = ' '.message_contact_link($contact->id
, 'unblock', true, $script, $text, $icon);
2241 $strblock = ' '.message_contact_link($contact->id
, 'block', true, $script, $text, $icon);
2248 * Moves messages from a particular user from the message table (unread messages) to message_read
2249 * This is typically only used when a user is deleted
2251 * @param object $userid User id
2252 * @return boolean success
2254 function message_move_userfrom_unread2read($userid) {
2257 // move all unread messages from message table to message_read
2258 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2259 foreach ($messages as $message) {
2260 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2267 * marks ALL messages being sent from $fromuserid to $touserid as read
2269 * @param int $touserid the id of the message recipient
2270 * @param int $fromuserid the id of the message sender
2273 function message_mark_messages_read($touserid, $fromuserid){
2276 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2277 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2279 foreach ($messages as $message) {
2280 message_mark_message_read($message, time());
2287 * Mark a single message as read
2289 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2290 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2291 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2292 * @return int the ID of the message in the message_read table
2294 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2297 $message->timeread
= $timeread;
2299 $messageid = $message->id
;
2300 unset($message->id
);//unset because it will get a new id on insert into message_read
2302 //If any processors have pending actions abort them
2303 if (!$messageworkingempty) {
2304 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2306 $messagereadid = $DB->insert_record('message_read', $message);
2307 $DB->delete_records('message', array('id' => $messageid));
2308 return $messagereadid;
2312 * A helper function that prints a formatted heading
2314 * @param string $title the heading to display
2315 * @param int $colspan
2318 function message_print_heading($title, $colspan=3) {
2319 echo html_writer
::start_tag('tr');
2320 echo html_writer
::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2321 echo html_writer
::end_tag('tr');
2325 * Get all message processors, validate corresponding plugin existance and
2326 * system configuration
2328 * @param bool $ready only return ready-to-use processors
2329 * @param bool $reset Reset list of message processors (used in unit tests)
2330 * @return mixed $processors array of objects containing information on message processors
2332 function get_message_processors($ready = false, $reset = false) {
2337 $processors = array();
2340 if (empty($processors)) {
2341 // Get all processors, ensure the name column is the first so it will be the array key
2342 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2343 foreach ($processors as &$processor){
2344 $processorfile = $CFG->dirroot
. '/message/output/'.$processor->name
.'/message_output_'.$processor->name
.'.php';
2345 if (is_readable($processorfile)) {
2346 include_once($processorfile);
2347 $processclass = 'message_output_' . $processor->name
;
2348 if (class_exists($processclass)) {
2349 $pclass = new $processclass();
2350 $processor->object = $pclass;
2351 $processor->configured
= 0;
2352 if ($pclass->is_system_configured()) {
2353 $processor->configured
= 1;
2355 $processor->hassettings
= 0;
2356 if (is_readable($CFG->dirroot
.'/message/output/'.$processor->name
.'/settings.php')) {
2357 $processor->hassettings
= 1;
2359 $processor->available
= 1;
2361 print_error('errorcallingprocessor', 'message');
2364 $processor->available
= 0;
2369 // Filter out enabled and system_configured processors
2370 $readyprocessors = $processors;
2371 foreach ($readyprocessors as $readyprocessor) {
2372 if (!($readyprocessor->enabled
&& $readyprocessor->configured
)) {
2373 unset($readyprocessors[$readyprocessor->name
]);
2376 return $readyprocessors;
2383 * Get all message providers, validate their plugin existance and
2384 * system configuration
2386 * @return mixed $processors array of objects containing information on message processors
2388 function get_message_providers() {
2391 $pluginman = core_plugin_manager
::instance();
2393 $providers = $DB->get_records('message_providers', null, 'name');
2395 // Remove all the providers whose plugins are disabled or don't exist
2396 foreach ($providers as $providerid => $provider) {
2397 $plugin = $pluginman->get_plugin_info($provider->component
);
2399 if ($plugin->get_status() === core_plugin_manager
::PLUGIN_STATUS_MISSING
) {
2400 unset($providers[$providerid]); // Plugins does not exist
2403 if ($plugin->is_enabled() === false) {
2404 unset($providers[$providerid]); // Plugin disabled
2413 * Get an instance of the message_output class for one of the output plugins.
2414 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2415 * @return message_output message_output the requested class.
2417 function get_message_processor($type) {
2420 // Note, we cannot use the get_message_processors function here, becaues this
2421 // code is called during install after installing each messaging plugin, and
2422 // get_message_processors caches the list of installed plugins.
2424 $processorfile = $CFG->dirroot
. "/message/output/{$type}/message_output_{$type}.php";
2425 if (!is_readable($processorfile)) {
2426 throw new coding_exception('Unknown message processor type ' . $type);
2429 include_once($processorfile);
2431 $processclass = 'message_output_' . $type;
2432 if (!class_exists($processclass)) {
2433 throw new coding_exception('Message processor ' . $type .
2434 ' does not define the right class');
2437 return new $processclass();
2441 * Get messaging outputs default (site) preferences
2443 * @return object $processors object containing information on message processors
2445 function get_message_output_default_preferences() {
2446 return get_config('message');
2450 * Translate message default settings from binary value to the array of string
2451 * representing the settings to be stored. Also validate the provided value and
2452 * use default if it is malformed.
2454 * @param int $plugindefault Default setting suggested by plugin
2455 * @param string $processorname The name of processor
2456 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2458 function translate_message_default_setting($plugindefault, $processorname) {
2459 // Preset translation arrays
2460 $permittedvalues = array(
2461 0x04 => 'disallowed',
2462 0x08 => 'permitted',
2466 $loggedinstatusvalues = array(
2467 0x00 => null, // use null if loggedin/loggedoff is not defined
2469 0x02 => 'loggedoff',
2472 // define the default setting
2473 $processor = get_message_processor($processorname);
2474 $default = $processor->get_default_messaging_settings();
2476 // Validate the value. It should not exceed the maximum size
2477 if (!is_int($plugindefault) ||
($plugindefault > 0x0f)) {
2478 debugging(get_string('errortranslatingdefault', 'message'));
2479 $plugindefault = $default;
2481 // Use plugin default setting of 'permitted' is 0
2482 if (!($plugindefault & MESSAGE_PERMITTED_MASK
)) {
2483 $plugindefault = $default;
2486 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK
];
2487 $loggedin = $loggedoff = null;
2489 if (($plugindefault & MESSAGE_PERMITTED_MASK
) == MESSAGE_PERMITTED
) {
2490 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN
];
2491 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF
];
2494 return array($permitted, $loggedin, $loggedoff);
2498 * Return a list of page types
2499 * @param string $pagetype current page type
2500 * @param stdClass $parentcontext Block's parent context
2501 * @param stdClass $currentcontext Current context of block
2503 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2504 return array('messages-*'=>get_string('page-message-x', 'message'));
2508 * Is $USER one of the supplied users?
2510 * $user2 will be null if viewing a user's recent conversations
2512 * @param stdClass the first user
2513 * @param stdClass the second user or null
2514 * @return bool True if the current user is one of either $user1 or $user2
2516 function message_current_user_is_involved($user1, $user2) {
2519 if (empty($user1->id
) ||
(!empty($user2) && empty($user2->id
))) {
2520 throw new coding_exception('Invalid user object detected. Missing id.');
2523 if ($user1->id
!= $USER->id
&& (empty($user2) ||
$user2->id
!= $USER->id
)) {