MDL-42796 ActionMenu: Move event handlers to showMenu
[moodle.git] / message / lib.php
blob98e5775b0d001e01ff42310ff77a0c5dfc34f218
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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);
50 /**
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
69 /**
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 /**
75 * Print the selector that allows the user to view their contacts, course participants, their recent
76 * conversations etc
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
88 * @return void
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
91 global $PAGE;
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);
130 } else {
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
165 * @return void
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
181 FROM {user} u
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) {
200 $iscontact = false;
201 $isblocked = false;
202 if ( $participant->contactlistid ) {
203 if ($participant->blocked == 0) {
204 // Is contact. Is not blocked.
205 $iscontact = true;
206 $isblocked = false;
207 } else {
208 // Is blocked.
209 $iscontact = false;
210 $isblocked = true;
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) {
231 global $DB, $USER;
233 if (empty($user1)) {
234 $user1 = $USER;
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
249 GROUP BY $userfields
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;
260 $rs->close();
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
273 * @return void
275 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
276 global $DB, $USER;
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');
288 if ($countblocked) {
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;
314 if (empty($user1)) {
315 $user1 = $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
346 GROUP BY $userfields
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;
355 } else {
356 $offlinecontacts[] = $rd;
359 if (!empty($user2) && $user2->id == $rd->id) {
360 $user2->iscontact = true;
363 $rs->close();
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
368 FROM {message} m
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 = ?
372 GROUP BY $userfields
373 ORDER BY u.firstname ASC";
375 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
376 foreach ($rs as $rd) {
377 $strangers[] = $rd;
379 $rs->close();
381 // Add noreply user and support user to the list.
382 $supportuser = core_user::get_support_user();
383 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
384 if ($supportuser->messagecount > 0) {
385 $strangers[] = $supportuser;
387 $noreplyuser = core_user::get_noreply_user();
388 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
389 if ($noreplyuser->messagecount > 0) {
390 $strangers[] = $noreplyuser;
392 return array($onlinecontacts, $offlinecontacts, $strangers);
396 * Print $user1's contacts. Called by message_print_contact_selector()
398 * @param array $onlinecontacts $user1's contacts which are online
399 * @param array $offlinecontacts $user1's contacts which are offline
400 * @param array $strangers users which are not contacts but who have messaged $user1
401 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
402 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
403 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
404 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
405 * @param string $titletodisplay Optionally specify a title to display above the participants
406 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
407 * @return void
409 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
410 global $CFG, $PAGE, $OUTPUT;
412 $countonlinecontacts = count($onlinecontacts);
413 $countofflinecontacts = count($offlinecontacts);
414 $countstrangers = count($strangers);
415 $isuserblocked = null;
417 if ($countonlinecontacts + $countofflinecontacts == 0) {
418 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
421 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
423 if (!empty($titletodisplay)) {
424 message_print_heading($titletodisplay);
427 if($countonlinecontacts) {
428 // Print out list of online contacts.
430 if (empty($titletodisplay)) {
431 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
434 $isuserblocked = false;
435 $isusercontact = true;
436 foreach ($onlinecontacts as $contact) {
437 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
438 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
443 if ($countofflinecontacts) {
444 // Print out list of offline contacts.
446 if (empty($titletodisplay)) {
447 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
450 $isuserblocked = false;
451 $isusercontact = true;
452 foreach ($offlinecontacts as $contact) {
453 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
454 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
460 // Print out list of incoming contacts.
461 if ($countstrangers) {
462 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
464 $isuserblocked = false;
465 $isusercontact = false;
466 foreach ($strangers as $stranger) {
467 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
468 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
473 echo html_writer::end_tag('table');
475 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
476 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
481 * Print a select box allowing the user to choose to view new messages, course participants etc.
483 * Called by message_print_contact_selector()
484 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
485 * @param array $courses array of course objects. The courses the user is enrolled in.
486 * @param array $coursecontexts array of course contexts. Keyed on course id.
487 * @param int $countunreadtotal how many unread messages does the user have?
488 * @param int $countblocked how many users has the current user blocked?
489 * @param stdClass $user1 The user whose messages we are viewing.
490 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
491 * @return void
493 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
494 $options = array();
496 if ($countunreadtotal>0) { //if there are unread messages
497 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
500 $str = get_string('contacts', 'message');
501 $options[MESSAGE_VIEW_CONTACTS] = $str;
503 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
504 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
506 if (!empty($courses)) {
507 $courses_options = array();
509 foreach($courses as $course) {
510 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
511 //Not using short_text() as we want the end of the course name. Not the beginning.
512 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
513 if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
514 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
515 } else {
516 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
521 if (!empty($courses_options)) {
522 $options[] = array(get_string('courses') => $courses_options);
526 if ($countblocked>0) {
527 $str = get_string('blockedusers','message', $countblocked);
528 $options[MESSAGE_VIEW_BLOCKED] = $str;
531 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
532 echo html_writer::start_tag('fieldset');
533 if ( !empty($user1) && !empty($user1->id) ) {
534 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id));
536 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
537 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
538 echo html_writer::end_tag('fieldset');
539 echo html_writer::end_tag('form');
543 * Load the course contexts for all of the users courses
545 * @param array $courses array of course objects. The courses the user is enrolled in.
546 * @return array of course contexts
548 function message_get_course_contexts($courses) {
549 $coursecontexts = array();
551 foreach($courses as $course) {
552 $coursecontexts[$course->id] = context_course::instance($course->id);
555 return $coursecontexts;
559 * strip off action parameters like 'removecontact'
561 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
562 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
564 function message_remove_url_params($moodleurl) {
565 $newurl = new moodle_url($moodleurl);
566 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
567 return $newurl->out();
571 * Count the number of messages with a field having a specified value.
572 * if $field is empty then return count of the whole array
573 * if $field is non-existent then return 0
575 * @param array $messagearray array of message objects
576 * @param string $field the field to inspect on the message objects
577 * @param string $value the value to test the field against
579 function message_count_messages($messagearray, $field='', $value='') {
580 if (!is_array($messagearray)) return 0;
581 if ($field == '' or empty($messagearray)) return count($messagearray);
583 $count = 0;
584 foreach ($messagearray as $message) {
585 $count += ($message->$field == $value) ? 1 : 0;
587 return $count;
591 * Returns the count of unread messages for user. Either from a specific user or from all users.
593 * @param object $user1 the first user. Defaults to $USER
594 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
595 * @return int the count of $user1's unread messages
597 function message_count_unread_messages($user1=null, $user2=null) {
598 global $USER, $DB;
600 if (empty($user1)) {
601 $user1 = $USER;
604 if (!empty($user2)) {
605 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
606 array($user1->id, $user2->id), "COUNT('id')");
607 } else {
608 return $DB->count_records_select('message', "useridto = ?",
609 array($user1->id), "COUNT('id')");
614 * Count the number of users blocked by $user1
616 * @param object $user1 user object
617 * @return int the number of blocked users
619 function message_count_blocked_users($user1=null) {
620 global $USER, $DB;
622 if (empty($user1)) {
623 $user1 = $USER;
626 $sql = "SELECT count(mc.id)
627 FROM {message_contacts} mc
628 WHERE mc.userid = :userid AND mc.blocked = 1";
629 $params = array('userid' => $user1->id);
631 return $DB->count_records_sql($sql, $params);
635 * Print the search form and search results if a search has been performed
637 * @param boolean $advancedsearch show basic or advanced search form
638 * @param object $user1 the current user
639 * @return boolean true if a search was performed
641 function message_print_search($advancedsearch = false, $user1=null) {
642 $frm = data_submitted();
644 $doingsearch = false;
645 if ($frm) {
646 if (confirm_sesskey()) {
647 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
648 } else {
649 $frm = false;
653 if (!empty($frm->combinedsearch)) {
654 $combinedsearchstring = $frm->combinedsearch;
655 } else {
656 //$combinedsearchstring = get_string('searchcombined','message').'...';
657 $combinedsearchstring = '';
660 if ($doingsearch) {
661 if ($advancedsearch) {
663 $messagesearch = '';
664 if (!empty($frm->keywords)) {
665 $messagesearch = $frm->keywords;
667 $personsearch = '';
668 if (!empty($frm->name)) {
669 $personsearch = $frm->name;
671 include('search_advanced.html');
672 } else {
673 include('search.html');
676 $showicontext = false;
677 message_print_search_results($frm, $showicontext, $user1);
679 return true;
680 } else {
682 if ($advancedsearch) {
683 $personsearch = $messagesearch = '';
684 include('search_advanced.html');
685 } else {
686 include('search.html');
688 return false;
693 * Get the users recent conversations meaning all the people they've recently
694 * sent or received a message from plus the most recent message sent to or received from each other user
696 * @param object $user the current user
697 * @param int $limitfrom can be used for paging
698 * @param int $limitto can be used for paging
699 * @return array
701 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
702 global $DB;
704 $userfields = user_picture::fields('u', array('lastaccess'));
705 //This query retrieves the last message received from and sent to each user
706 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
707 //It then joins with some other tables to get some additional data we need
709 //message ID is used instead of timecreated as it should sort the same and will be much faster
711 //There is a separate query for read and unread queries as they are stored in different tables
712 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
713 $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
714 FROM {message_read} mr
715 JOIN (
716 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
717 FROM (
718 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
719 FROM {message_read} mr1
720 WHERE mr1.useridfrom = :userid1
721 AND mr1.notification = 0
722 GROUP BY mr1.useridto
723 UNION
724 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
725 FROM {message_read} mr2
726 WHERE mr2.useridto = :userid2
727 AND mr2.notification = 0
728 GROUP BY mr2.useridfrom
729 ) messages
730 GROUP BY messages.userid
731 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
732 JOIN {user} u ON u.id = messages2.userid
733 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
734 WHERE u.deleted = '0'
735 ORDER BY mr.id DESC";
736 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
737 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
739 $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
740 FROM {message} m
741 JOIN (
742 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
743 FROM (
744 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
745 FROM {message} m1
746 WHERE m1.useridfrom = :userid1
747 AND m1.notification = 0
748 GROUP BY m1.useridto
749 UNION
750 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
751 FROM {message} m2
752 WHERE m2.useridto = :userid2
753 AND m2.notification = 0
754 GROUP BY m2.useridfrom
755 ) messages
756 GROUP BY messages.userid
757 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
758 JOIN {user} u ON u.id = messages2.userid
759 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
760 WHERE u.deleted = '0'
761 ORDER BY m.id DESC";
762 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
764 $conversations = array();
766 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
767 //$conversation->id (the array key) is the other user's ID
768 $conversation_arrays = array($unread, $read);
769 foreach ($conversation_arrays as $conversation_array) {
770 foreach ($conversation_array as $conversation) {
771 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
772 $conversations[$conversation->id] = $conversation;
777 // Sort the conversations by $conversation->timecreated, newest to oldest
778 // There may be multiple conversations with the same timecreated
779 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
780 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
781 $conversations = array_reverse($conversations);
783 return $conversations;
787 * Get the users recent event notifications
789 * @param object $user the current user
790 * @param int $limitfrom can be used for paging
791 * @param int $limitto can be used for paging
792 * @return array
794 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
795 global $DB;
797 $userfields = user_picture::fields('u', array('lastaccess'));
798 $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
799 FROM {message_read} mr
800 JOIN {user} u ON u.id=mr.useridfrom
801 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
802 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
803 $params = array('userid1' => $user->id, 'notification' => 1);
805 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
806 return $notifications;
810 * Print the user's recent conversations
812 * @param stdClass $user the current user
813 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
815 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
816 global $USER;
818 echo html_writer::start_tag('p', array('class' => 'heading'));
819 echo get_string('mostrecentconversations', 'message');
820 echo html_writer::end_tag('p');
822 if (empty($user1)) {
823 $user1 = $USER;
826 $conversations = message_get_recent_conversations($user1);
828 // Attach context url information to create the "View this conversation" type links
829 foreach($conversations as $conversation) {
830 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
831 $conversation->contexturlname = get_string('thisconversation', 'message');
834 $showotheruser = true;
835 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
839 * Print the user's recent notifications
841 * @param stdClass $user the current user
843 function message_print_recent_notifications($user=null) {
844 global $USER;
846 echo html_writer::start_tag('p', array('class' => 'heading'));
847 echo get_string('mostrecentnotifications', 'message');
848 echo html_writer::end_tag('p');
850 if (empty($user)) {
851 $user = $USER;
854 $notifications = message_get_recent_notifications($user);
856 $showicontext = false;
857 $showotheruser = false;
858 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
862 * Print a list of recent messages
864 * @access private
866 * @param array $messages the messages to display
867 * @param stdClass $user the current user
868 * @param bool $showotheruser display information on the other user?
869 * @param bool $showicontext show text next to the action icons?
870 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
871 * @param bool $showactionlinks
872 * @return void
874 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
875 global $OUTPUT;
876 static $dateformat;
878 if (empty($dateformat)) {
879 $dateformat = get_string('strftimedatetimeshort');
882 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
883 foreach ($messages as $message) {
884 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
886 if ($showotheruser) {
887 $strcontact = $strblock = $strhistory = null;
889 if ($showactionlinks) {
890 if ( $message->contactlistid ) {
891 if ($message->blocked == 0) { // The other user isn't blocked.
892 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
893 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
894 } else { // The other user is blocked.
895 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
896 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
898 } else {
899 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
900 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
903 //should we show just the icon or icon and text?
904 $histicontext = 'icon';
905 if ($showicontext) {
906 $histicontext = 'both';
908 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
910 echo html_writer::start_tag('span', array('class' => 'otheruser'));
912 echo html_writer::start_tag('span', array('class' => 'pix'));
913 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
914 echo html_writer::end_tag('span');
916 echo html_writer::start_tag('span', array('class' => 'contact'));
918 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
919 $action = null;
920 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
922 echo html_writer::end_tag('span');//end contact
924 if ($showactionlinks) {
925 echo $strcontact.$strblock.$strhistory;
927 echo html_writer::end_tag('span');//end otheruser
930 $messagetext = message_format_message_text($message, $forcetexttohtml);
932 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
933 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
934 echo message_format_contexturl($message);
935 echo html_writer::end_tag('div');//end singlemessage
937 echo html_writer::end_tag('div');//end messagerecent
941 * Try to guess how to convert the message to html.
943 * @access private
945 * @param stdClass $message
946 * @param bool $forcetexttohtml
947 * @return string html fragment
949 function message_format_message_text($message, $forcetexttohtml = false) {
950 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
952 $options = new stdClass();
953 $options->para = false;
955 $format = $message->fullmessageformat;
957 if ($message->smallmessage !== '') {
958 if ($message->notification == 1) {
959 if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
960 $format = FORMAT_PLAIN;
963 $messagetext = $message->smallmessage;
965 } else if ($message->fullmessageformat == FORMAT_HTML) {
966 if ($message->fullmessagehtml !== '') {
967 $messagetext = $message->fullmessagehtml;
968 } else {
969 $messagetext = $message->fullmessage;
970 $format = FORMAT_MOODLE;
973 } else {
974 if ($message->fullmessage !== '') {
975 $messagetext = $message->fullmessage;
976 } else {
977 $messagetext = $message->fullmessagehtml;
978 $format = FORMAT_HTML;
982 if ($forcetexttohtml) {
983 // This is a crazy hack, why not set proper format when creating the notifications?
984 if ($format === FORMAT_PLAIN) {
985 $format = FORMAT_MOODLE;
988 return format_text($messagetext, $format, $options);
992 * Add the selected user as a contact for the current user
994 * @param int $contactid the ID of the user to add as a contact
995 * @param int $blocked 1 if you wish to block the contact
996 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
997 * Otherwise returns the result of update_record() or insert_record()
999 function message_add_contact($contactid, $blocked=0) {
1000 global $USER, $DB;
1002 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
1003 return false;
1006 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
1007 // A record already exists. We may be changing blocking status.
1009 if ($contact->blocked !== $blocked) {
1010 // Blocking status has been changed.
1011 $contact->blocked = $blocked;
1012 return $DB->update_record('message_contacts', $contact);
1013 } else {
1014 // No change to blocking status.
1015 return true;
1018 } else {
1019 // New contact record.
1020 $contact = new stdClass();
1021 $contact->userid = $USER->id;
1022 $contact->contactid = $contactid;
1023 $contact->blocked = $blocked;
1024 return $DB->insert_record('message_contacts', $contact, false);
1029 * remove a contact
1031 * @param int $contactid the user ID of the contact to remove
1032 * @return bool returns the result of delete_records()
1034 function message_remove_contact($contactid) {
1035 global $USER, $DB;
1036 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1040 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1042 * @param int $contactid the user ID of the contact to unblock
1043 * @return bool returns the result of delete_records()
1045 function message_unblock_contact($contactid) {
1046 global $USER, $DB;
1047 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1051 * block a user
1053 * @param int $contactid the user ID of the user to block
1055 function message_block_contact($contactid) {
1056 return message_add_contact($contactid, 1);
1060 * Load a user's contact record
1062 * @param int $contactid the user ID of the user whose contact record you want
1063 * @return array message contacts
1065 function message_get_contact($contactid) {
1066 global $USER, $DB;
1067 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1071 * Print the results of a message search
1073 * @param mixed $frm submitted form data
1074 * @param bool $showicontext show text next to action icons?
1075 * @param object $currentuser the current user
1076 * @return void
1078 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1079 global $USER, $DB, $OUTPUT;
1081 if (empty($currentuser)) {
1082 $currentuser = $USER;
1085 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1087 $personsearch = false;
1088 $personsearchstring = null;
1089 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1090 $personsearch = true;
1091 $personsearchstring = $frm->name;
1092 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1093 $personsearch = true;
1094 $personsearchstring = $frm->combinedsearch;
1097 // Search for person.
1098 if ($personsearch) {
1099 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1100 $users = array();
1101 $mycourses = enrol_get_my_courses('id');
1102 $mycoursesids = array();
1103 foreach ($mycourses as $mycourse) {
1104 $mycoursesids[] = $mycourse->id;
1106 $susers = message_search_users($mycoursesids, $personsearchstring);
1107 foreach ($susers as $suser) {
1108 $users[$suser->id] = $suser;
1110 } else {
1111 $users = message_search_users(SITEID, $personsearchstring);
1114 if (!empty($users)) {
1115 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1116 echo get_string('userssearchresults', 'message', count($users));
1117 echo html_writer::end_tag('p');
1119 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1120 foreach ($users as $user) {
1122 if ( $user->contactlistid ) {
1123 if ($user->blocked == 0) { // User is not blocked.
1124 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1125 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1126 } else { // blocked
1127 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1128 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1130 } else {
1131 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1132 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1135 // Should we show just the icon or icon and text?
1136 $histicontext = 'icon';
1137 if ($showicontext) {
1138 $histicontext = 'both';
1140 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1142 echo html_writer::start_tag('tr');
1144 echo html_writer::start_tag('td', array('class' => 'pix'));
1145 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1146 echo html_writer::end_tag('td');
1148 echo html_writer::start_tag('td',array('class' => 'contact'));
1149 $action = null;
1150 $link = new moodle_url("/message/index.php?id=$user->id");
1151 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1152 echo html_writer::end_tag('td');
1154 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1155 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1156 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1158 echo html_writer::end_tag('tr');
1160 echo html_writer::end_tag('table');
1162 } else {
1163 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1164 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1165 echo html_writer::end_tag('p');
1169 // search messages for keywords
1170 $messagesearch = false;
1171 $messagesearchstring = null;
1172 if (!empty($frm->keywords)) {
1173 $messagesearch = true;
1174 $messagesearchstring = clean_text(trim($frm->keywords));
1175 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1176 $messagesearch = true;
1177 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1180 if ($messagesearch) {
1181 if ($messagesearchstring) {
1182 $keywords = explode(' ', $messagesearchstring);
1183 } else {
1184 $keywords = array();
1186 $tome = false;
1187 $fromme = false;
1188 $courseid = 'none';
1190 if (empty($frm->keywordsoption)) {
1191 $frm->keywordsoption = 'allmine';
1194 switch ($frm->keywordsoption) {
1195 case 'tome':
1196 $tome = true;
1197 break;
1198 case 'fromme':
1199 $fromme = true;
1200 break;
1201 case 'allmine':
1202 $tome = true;
1203 $fromme = true;
1204 break;
1205 case 'allusers':
1206 $courseid = SITEID;
1207 break;
1208 case 'courseusers':
1209 $courseid = $frm->courseid;
1210 break;
1211 default:
1212 $tome = true;
1213 $fromme = true;
1216 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1218 // Get a list of contacts.
1219 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1220 $contacts = array();
1223 // Print heading with number of results.
1224 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1225 $countresults = count($messages);
1226 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1227 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1228 } else {
1229 echo get_string('keywordssearchresults', 'message', $countresults);
1231 echo html_writer::end_tag('p');
1233 // Print table headings.
1234 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1236 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1237 $headertdend = html_writer::end_tag('td');
1238 echo html_writer::start_tag('tr');
1239 echo $headertdstart.get_string('from').$headertdend;
1240 echo $headertdstart.get_string('to').$headertdend;
1241 echo $headertdstart.get_string('message', 'message').$headertdend;
1242 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1243 echo html_writer::end_tag('tr');
1245 $blockedcount = 0;
1246 $dateformat = get_string('strftimedatetimeshort');
1247 $strcontext = get_string('context', 'message');
1248 foreach ($messages as $message) {
1250 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1251 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1252 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1253 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1256 $blockedcount ++;
1257 continue;
1260 // Load user-to record.
1261 if ($message->useridto !== $USER->id) {
1262 $userto = core_user::get_user($message->useridto);
1263 $tocontact = (array_key_exists($message->useridto, $contacts) and
1264 ($contacts[$message->useridto]->blocked == 0) );
1265 $toblocked = (array_key_exists($message->useridto, $contacts) and
1266 ($contacts[$message->useridto]->blocked == 1) );
1267 } else {
1268 $userto = false;
1269 $tocontact = false;
1270 $toblocked = false;
1273 // Load user-from record.
1274 if ($message->useridfrom !== $USER->id) {
1275 $userfrom = core_user::get_user($message->useridfrom);
1276 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1277 ($contacts[$message->useridfrom]->blocked == 0) );
1278 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1279 ($contacts[$message->useridfrom]->blocked == 1) );
1280 } else {
1281 $userfrom = false;
1282 $fromcontact = false;
1283 $fromblocked = false;
1286 // Find date string for this message.
1287 $date = usergetdate($message->timecreated);
1288 $datestring = $date['year'].$date['mon'].$date['mday'];
1290 // Print out message row.
1291 echo html_writer::start_tag('tr', array('valign' => 'top'));
1293 echo html_writer::start_tag('td', array('class' => 'contact'));
1294 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1295 echo html_writer::end_tag('td');
1297 echo html_writer::start_tag('td', array('class' => 'contact'));
1298 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1299 echo html_writer::end_tag('td');
1301 echo html_writer::start_tag('td', array('class' => 'summary'));
1302 echo message_get_fragment($message->smallmessage, $keywords);
1303 echo html_writer::start_tag('div', array('class' => 'link'));
1305 // If the user clicks the context link display message sender on the left.
1306 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1307 $leftsideuserid = $rightsideuserid = null;
1308 if ($currentuser->id == $message->useridto) {
1309 $leftsideuserid = $message->useridto;
1310 $rightsideuserid = $message->useridfrom;
1311 } else {
1312 $leftsideuserid = $message->useridfrom;
1313 $rightsideuserid = $message->useridto;
1315 message_history_link($leftsideuserid, $rightsideuserid, false,
1316 $messagesearchstring, 'm'.$message->id, $strcontext);
1317 echo html_writer::end_tag('div');
1318 echo html_writer::end_tag('td');
1320 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1322 echo html_writer::end_tag('tr');
1326 if ($blockedcount > 0) {
1327 echo html_writer::start_tag('tr');
1328 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1329 echo html_writer::end_tag('tr');
1331 echo html_writer::end_tag('table');
1333 } else {
1334 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1338 if (!$personsearch && !$messagesearch) {
1339 //they didn't enter any search terms
1340 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1343 echo html_writer::end_tag('div');
1347 * Print information on a user. Used when printing search results.
1349 * @param object/bool $user the user to display or false if you just want $USER
1350 * @param bool $iscontact is the user being displayed a contact?
1351 * @param bool $isblocked is the user being displayed blocked?
1352 * @param bool $includeicontext include text next to the action icons?
1353 * @return void
1355 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1356 global $USER, $OUTPUT;
1358 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1360 if ($user === false) {
1361 echo $OUTPUT->user_picture($USER, $userpictureparams);
1362 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1363 $userpictureparams['link'] = false;
1364 echo $OUTPUT->user_picture($USER, $userpictureparams);
1365 echo fullname($user);
1366 } else {
1367 echo $OUTPUT->user_picture($user, $userpictureparams);
1369 $link = new moodle_url("/message/index.php?id=$user->id");
1370 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1371 get_string('sendmessageto', 'message', fullname($user))));
1373 $return = false;
1374 $script = null;
1375 if ($iscontact) {
1376 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1377 } else {
1378 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1381 if ($isblocked) {
1382 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1383 } else {
1384 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1390 * Print a message contact link
1392 * @param int $userid the ID of the user to apply to action to
1393 * @param string $linktype can be add, remove, block or unblock
1394 * @param bool $return if true return the link as a string. If false echo the link.
1395 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1396 * @param bool $text include text next to the icons?
1397 * @param bool $icon include a graphical icon?
1398 * @return string if $return is true otherwise bool
1400 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1401 global $OUTPUT, $PAGE;
1403 //hold onto the strings as we're probably creating a bunch of links
1404 static $str;
1406 if (empty($script)) {
1407 //strip off previous action params like 'removecontact'
1408 $script = message_remove_url_params($PAGE->url);
1411 if (empty($str->blockcontact)) {
1412 $str = new stdClass();
1413 $str->blockcontact = get_string('blockcontact', 'message');
1414 $str->unblockcontact = get_string('unblockcontact', 'message');
1415 $str->removecontact = get_string('removecontact', 'message');
1416 $str->addcontact = get_string('addcontact', 'message');
1419 $command = $linktype.'contact';
1420 $string = $str->{$command};
1422 $safealttext = s($string);
1424 $safestring = '';
1425 if (!empty($text)) {
1426 $safestring = $safealttext;
1429 $img = '';
1430 if ($icon) {
1431 $iconpath = null;
1432 switch ($linktype) {
1433 case 'block':
1434 $iconpath = 't/block';
1435 break;
1436 case 'unblock':
1437 $iconpath = 't/unblock';
1438 break;
1439 case 'remove':
1440 $iconpath = 't/removecontact';
1441 break;
1442 case 'add':
1443 default:
1444 $iconpath = 't/addcontact';
1447 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1450 $output = '<span class="'.$linktype.'contact">'.
1451 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1452 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1453 $img.
1454 $safestring.'</a></span>';
1456 if ($return) {
1457 return $output;
1458 } else {
1459 echo $output;
1460 return true;
1465 * echo or return a link to take the user to the full message history between themselves and another user
1467 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1468 * @param int $userid2 the ID of the other user
1469 * @param bool $return true to return the link as a string. False to echo the link.
1470 * @param string $keywords any keywords to highlight in the message history
1471 * @param string $position anchor name to jump to within the message history
1472 * @param string $linktext optionally specify the link text
1473 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1475 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1476 global $OUTPUT, $PAGE;
1477 static $strmessagehistory;
1479 if (empty($strmessagehistory)) {
1480 $strmessagehistory = get_string('messagehistory', 'message');
1483 if ($position) {
1484 $position = "#$position";
1486 if ($keywords) {
1487 $keywords = "&search=".urlencode($keywords);
1490 if ($linktext == 'icon') { // Icon only
1491 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1492 } else if ($linktext == 'both') { // Icon and standard name
1493 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1494 $fulllink .= '&nbsp;'.$strmessagehistory;
1495 } else if ($linktext) { // Custom name
1496 $fulllink = $linktext;
1497 } else { // Standard name only
1498 $fulllink = $strmessagehistory;
1501 $popupoptions = array(
1502 'height' => 500,
1503 'width' => 500,
1504 'menubar' => false,
1505 'location' => false,
1506 'status' => true,
1507 'scrollbars' => true,
1508 'resizable' => true);
1510 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1511 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1512 $link->param('viewing', $PAGE->url->get_param('viewing'));
1514 $action = null;
1515 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1517 $str = '<span class="history">'.$str.'</span>';
1519 if ($return) {
1520 return $str;
1521 } else {
1522 echo $str;
1523 return true;
1529 * Search through course users.
1531 * If $courseids contains the site course then this function searches
1532 * through all undeleted and confirmed users.
1534 * @param int|array $courseids Course ID or array of course IDs.
1535 * @param string $searchtext the text to search for.
1536 * @param string $sort the column name to order by.
1537 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1538 * @return array An array of {@link $USER} records.
1540 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1541 global $CFG, $USER, $DB;
1543 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1544 if (!$courseids) {
1545 $courseids = array(SITEID);
1548 // Allow an integer to be passed.
1549 if (!is_array($courseids)) {
1550 $courseids = array($courseids);
1553 $fullname = $DB->sql_fullname();
1554 $ufields = user_picture::fields('u');
1556 if (!empty($sort)) {
1557 $order = ' ORDER BY '. $sort;
1558 } else {
1559 $order = '';
1562 $params = array(
1563 'userid' => $USER->id,
1564 'query' => "%$searchtext%"
1567 if (empty($exceptions)) {
1568 $exceptions = array();
1569 } else if (!empty($exceptions) && is_string($exceptions)) {
1570 $exceptions = explode(',', $exceptions);
1573 // Ignore self and guest account.
1574 $exceptions[] = $USER->id;
1575 $exceptions[] = $CFG->siteguest;
1577 // Exclude exceptions from the search result.
1578 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1579 $except = ' AND u.id ' . $except;
1580 $params = array_merge($params_except, $params);
1582 if (in_array(SITEID, $courseids)) {
1583 // Search on site level.
1584 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1585 FROM {user} u
1586 LEFT JOIN {message_contacts} mc
1587 ON mc.contactid = u.id AND mc.userid = :userid
1588 WHERE u.deleted = '0' AND u.confirmed = '1'
1589 AND (".$DB->sql_like($fullname, ':query', false).")
1590 $except
1591 $order", $params);
1592 } else {
1593 // Search in courses.
1595 // Getting the context IDs or each course.
1596 $contextids = array();
1597 foreach ($courseids as $courseid) {
1598 $context = context_course::instance($courseid);
1599 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1601 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1602 $params = array_merge($params, $contextparams);
1604 // Everyone who has a role assignment in this course or higher.
1605 // TODO: add enabled enrolment join here (skodak)
1606 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1607 FROM {user} u
1608 JOIN {role_assignments} ra ON ra.userid = u.id
1609 LEFT JOIN {message_contacts} mc
1610 ON mc.contactid = u.id AND mc.userid = :userid
1611 WHERE u.deleted = '0' AND u.confirmed = '1'
1612 AND (".$DB->sql_like($fullname, ':query', false).")
1613 AND ra.contextid $contextwhere
1614 $except
1615 $order", $params);
1617 return $users;
1622 * Search a user's messages
1624 * Returns a list of posts found using an array of search terms
1625 * eg word +word -word
1627 * @param array $searchterms an array of search terms (strings)
1628 * @param bool $fromme include messages from the user?
1629 * @param bool $tome include messages to the user?
1630 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1631 * @param int $userid the user ID of the current user
1632 * @return mixed An array of messages or false if no matching messages were found
1634 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1635 global $CFG, $USER, $DB;
1637 // If user is searching all messages check they are allowed to before doing anything else.
1638 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1639 print_error('accessdenied','admin');
1642 // If no userid sent then assume current user.
1643 if ($userid == 0) $userid = $USER->id;
1645 // Some differences in SQL syntax.
1646 if ($DB->sql_regex_supported()) {
1647 $REGEXP = $DB->sql_regex(true);
1648 $NOTREGEXP = $DB->sql_regex(false);
1651 $searchcond = array();
1652 $params = array();
1653 $i = 0;
1655 // Preprocess search terms to check whether we have at least 1 eligible search term.
1656 // If we do we can drop words around it like 'a'.
1657 $dropshortwords = false;
1658 foreach ($searchterms as $searchterm) {
1659 if (strlen($searchterm) >= 2) {
1660 $dropshortwords = true;
1664 foreach ($searchterms as $searchterm) {
1665 $i++;
1667 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1669 if ($dropshortwords && strlen($searchterm) < 2) {
1670 continue;
1672 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1673 if (!$DB->sql_regex_supported()) {
1674 if (substr($searchterm, 0, 1) == '-') {
1675 $NOT = true;
1677 $searchterm = trim($searchterm, '+-');
1680 if (substr($searchterm,0,1) == "+") {
1681 $searchterm = substr($searchterm,1);
1682 $searchterm = preg_quote($searchterm, '|');
1683 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1684 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1686 } else if (substr($searchterm,0,1) == "-") {
1687 $searchterm = substr($searchterm,1);
1688 $searchterm = preg_quote($searchterm, '|');
1689 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1690 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1692 } else {
1693 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1694 $params['ss'.$i] = "%$searchterm%";
1698 if (empty($searchcond)) {
1699 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1700 $params['ss1'] = "%";
1701 } else {
1702 $searchcond = implode(" AND ", $searchcond);
1705 // There are several possibilities
1706 // 1. courseid = SITEID : The admin is searching messages by all users
1707 // 2. courseid = ?? : A teacher is searching messages by users in
1708 // one of their courses - currently disabled
1709 // 3. courseid = none : User is searching their own messages;
1710 // a. Messages from user
1711 // b. Messages to user
1712 // c. Messages to and from user
1714 if ($courseid == SITEID) { // Admin is searching all messages.
1715 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1716 FROM {message_read} m
1717 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1718 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1719 FROM {message} m
1720 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1722 } else if ($courseid !== 'none') {
1723 // This has not been implemented due to security concerns.
1724 $m_read = array();
1725 $m_unread = array();
1727 } else {
1729 if ($fromme and $tome) {
1730 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1731 $params['userid1'] = $userid;
1732 $params['userid2'] = $userid;
1734 } else if ($fromme) {
1735 $searchcond .= " AND m.useridfrom=:userid";
1736 $params['userid'] = $userid;
1738 } else if ($tome) {
1739 $searchcond .= " AND m.useridto=:userid";
1740 $params['userid'] = $userid;
1743 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1744 FROM {message_read} m
1745 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1746 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1747 FROM {message} m
1748 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1752 /// The keys may be duplicated in $m_read and $m_unread so we can't
1753 /// do a simple concatenation
1754 $messages = array();
1755 foreach ($m_read as $m) {
1756 $messages[] = $m;
1758 foreach ($m_unread as $m) {
1759 $messages[] = $m;
1762 return (empty($messages)) ? false : $messages;
1766 * Given a message object that we already know has a long message
1767 * this function truncates the message nicely to the first
1768 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1770 * @param string $message the message
1771 * @param int $minlength the minimum length to trim the message to
1772 * @return string the shortened message
1774 function message_shorten_message($message, $minlength = 0) {
1775 $i = 0;
1776 $tag = false;
1777 $length = strlen($message);
1778 $count = 0;
1779 $stopzone = false;
1780 $truncate = 0;
1781 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1784 for ($i=0; $i<$length; $i++) {
1785 $char = $message[$i];
1787 switch ($char) {
1788 case "<":
1789 $tag = true;
1790 break;
1791 case ">":
1792 $tag = false;
1793 break;
1794 default:
1795 if (!$tag) {
1796 if ($stopzone) {
1797 if ($char == '.' or $char == ' ') {
1798 $truncate = $i+1;
1799 break 2;
1802 $count++;
1804 break;
1806 if (!$stopzone) {
1807 if ($count > $minlength) {
1808 $stopzone = true;
1813 if (!$truncate) {
1814 $truncate = $i;
1817 return substr($message, 0, $truncate);
1822 * Given a string and an array of keywords, this function looks
1823 * for the first keyword in the string, and then chops out a
1824 * small section from the text that shows that word in context.
1826 * @param string $message the text to search
1827 * @param array $keywords array of keywords to find
1829 function message_get_fragment($message, $keywords) {
1831 $fullsize = 160;
1832 $halfsize = (int)($fullsize/2);
1834 $message = strip_tags($message);
1836 foreach ($keywords as $keyword) { // Just get the first one
1837 if ($keyword !== '') {
1838 break;
1841 if (empty($keyword)) { // None found, so just return start of message
1842 return message_shorten_message($message, 30);
1845 $leadin = $leadout = '';
1847 /// Find the start of the fragment
1848 $start = 0;
1849 $length = strlen($message);
1851 $pos = strpos($message, $keyword);
1852 if ($pos > $halfsize) {
1853 $start = $pos - $halfsize;
1854 $leadin = '...';
1856 /// Find the end of the fragment
1857 $end = $start + $fullsize;
1858 if ($end > $length) {
1859 $end = $length;
1860 } else {
1861 $leadout = '...';
1864 /// Pull out the fragment and format it
1866 $fragment = substr($message, $start, $end - $start);
1867 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1868 return $fragment;
1872 * Retrieve the messages between two users
1874 * @param object $user1 the current user
1875 * @param object $user2 the other user
1876 * @param int $limitnum the maximum number of messages to retrieve
1877 * @param bool $viewingnewmessages are we currently viewing new messages?
1879 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1880 global $DB, $CFG;
1882 $messages = array();
1884 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1885 //desc to get the last $limitnum messages then flip the order in php
1886 $sort = 'asc';
1887 if ($limitnum>0) {
1888 $sort = 'desc';
1891 $notificationswhere = null;
1892 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1893 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1894 $notificationswhere = 'AND notification=0';
1897 //prevent notifications of your own actions appearing in your own message history
1898 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1900 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1901 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1902 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1903 "timecreated $sort", '*', 0, $limitnum)) {
1904 foreach ($messages_read as $message) {
1905 $messages[] = $message;
1908 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1909 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1910 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1911 "timecreated $sort", '*', 0, $limitnum)) {
1912 foreach ($messages_new as $message) {
1913 $messages[] = $message;
1917 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
1919 //if we only want the last $limitnum messages
1920 $messagecount = count($messages);
1921 if ($limitnum > 0 && $messagecount > $limitnum) {
1922 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1925 return $messages;
1929 * Print the message history between two users
1931 * @param object $user1 the current user
1932 * @param object $user2 the other user
1933 * @param string $search search terms to highlight
1934 * @param int $messagelimit maximum number of messages to return
1935 * @param string $messagehistorylink the html for the message history link or false
1936 * @param bool $viewingnewmessages are we currently viewing new messages?
1938 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1939 global $CFG, $OUTPUT;
1941 echo $OUTPUT->box_start('center');
1942 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1943 echo html_writer::start_tag('tr');
1945 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1946 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1947 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1948 echo html_writer::end_tag('td');
1950 echo html_writer::start_tag('td', array('align' => 'center'));
1951 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1952 echo html_writer::end_tag('td');
1954 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1955 // Show user picture with link is real user else without link.
1956 if (core_user::is_real_user($user2->id)) {
1957 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1958 } else {
1959 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
1961 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1963 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
1965 $script = null;
1966 $text = true;
1967 $icon = false;
1969 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1970 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1971 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1973 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1976 echo html_writer::end_tag('td');
1977 echo html_writer::end_tag('tr');
1978 echo html_writer::end_tag('table');
1979 echo $OUTPUT->box_end();
1981 if (!empty($messagehistorylink)) {
1982 echo $messagehistorylink;
1985 /// Get all the messages and print them
1986 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1987 $tablecontents = '';
1989 $current = new stdClass();
1990 $current->mday = '';
1991 $current->month = '';
1992 $current->year = '';
1993 $messagedate = get_string('strftimetime');
1994 $blockdate = get_string('strftimedaydate');
1995 foreach ($messages as $message) {
1996 if ($message->notification) {
1997 $notificationclass = ' notification';
1998 } else {
1999 $notificationclass = null;
2001 $date = usergetdate($message->timecreated);
2002 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2003 $current->mday = $date['mday'];
2004 $current->month = $date['month'];
2005 $current->year = $date['year'];
2007 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2008 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2010 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2013 $formatted_message = $side = null;
2014 if ($message->useridfrom == $user1->id) {
2015 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2016 $side = 'left';
2017 } else {
2018 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2019 $side = 'right';
2021 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2024 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2025 } else {
2026 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2031 * Format a message for display in the message history
2033 * @param object $message the message object
2034 * @param string $format optional date format
2035 * @param string $keywords keywords to highlight
2036 * @param string $class CSS class to apply to the div around the message
2037 * @return string the formatted message
2039 function message_format_message($message, $format='', $keywords='', $class='other') {
2041 static $dateformat;
2043 //if we haven't previously set the date format or they've supplied a new one
2044 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2045 if ($format) {
2046 $dateformat = $format;
2047 } else {
2048 $dateformat = get_string('strftimedatetimeshort');
2051 $time = userdate($message->timecreated, $dateformat);
2053 $messagetext = message_format_message_text($message, false);
2055 if ($keywords) {
2056 $messagetext = highlight($keywords, $messagetext);
2059 $messagetext .= message_format_contexturl($message);
2061 $messagetext = clean_text($messagetext, FORMAT_HTML);
2063 return <<<TEMPLATE
2064 <div class='message $class'>
2065 <a name="m'.{$message->id}.'"></a>
2066 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2067 </div>
2068 TEMPLATE;
2072 * Format a the context url and context url name of a message for display
2074 * @param object $message the message object
2075 * @return string the formatted string
2077 function message_format_contexturl($message) {
2078 $s = null;
2080 if (!empty($message->contexturl)) {
2081 $displaytext = null;
2082 if (!empty($message->contexturlname)) {
2083 $displaytext= $message->contexturlname;
2084 } else {
2085 $displaytext= $message->contexturl;
2087 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2088 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2089 $s .= html_writer::end_tag('div');
2092 return $s;
2096 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2098 * @param object $userfrom the message sender
2099 * @param object $userto the message recipient
2100 * @param string $message the message
2101 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2102 * @return int|false the ID of the new message or false
2104 function message_post_message($userfrom, $userto, $message, $format) {
2105 global $SITE, $CFG, $USER;
2107 $eventdata = new stdClass();
2108 $eventdata->component = 'moodle';
2109 $eventdata->name = 'instantmessage';
2110 $eventdata->userfrom = $userfrom;
2111 $eventdata->userto = $userto;
2113 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2114 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2116 if ($format == FORMAT_HTML) {
2117 $eventdata->fullmessagehtml = $message;
2118 //some message processors may revert to sending plain text even if html is supplied
2119 //so we keep both plain and html versions if we're intending to send html
2120 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2121 } else {
2122 $eventdata->fullmessage = $message;
2123 $eventdata->fullmessagehtml = '';
2126 $eventdata->fullmessageformat = $format;
2127 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2129 $s = new stdClass();
2130 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2131 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2133 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2134 if (!empty($eventdata->fullmessage)) {
2135 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2137 if (!empty($eventdata->fullmessagehtml)) {
2138 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2141 $eventdata->timecreated = time();
2142 return message_send($eventdata);
2146 * Print a row of contactlist displaying user picture, messages waiting and
2147 * block links etc
2149 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2150 * @param bool $incontactlist is the user a contact of ours?
2151 * @param bool $isblocked is the user blocked?
2152 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2153 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2154 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2155 * @return void
2157 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2158 global $OUTPUT, $USER, $COURSE;
2159 $fullname = fullname($contact);
2160 $fullnamelink = $fullname;
2162 $linkclass = '';
2163 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2164 $linkclass = 'messageselecteduser';
2167 // Are there any unread messages for this contact?
2168 if ($contact->messagecount > 0 ){
2169 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2172 $strcontact = $strblock = $strhistory = null;
2174 if ($showactionlinks) {
2175 // Show block and delete links if user is real user.
2176 if (core_user::is_real_user($contact->id)) {
2177 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2178 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2180 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2183 echo html_writer::start_tag('tr');
2184 echo html_writer::start_tag('td', array('class' => 'pix'));
2185 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2186 echo html_writer::end_tag('td');
2188 echo html_writer::start_tag('td', array('class' => 'contact'));
2190 $popupoptions = array(
2191 'height' => MESSAGE_DISCUSSION_HEIGHT,
2192 'width' => MESSAGE_DISCUSSION_WIDTH,
2193 'menubar' => false,
2194 'location' => false,
2195 'status' => true,
2196 'scrollbars' => true,
2197 'resizable' => true);
2199 $link = $action = null;
2200 if (!empty($selectcontacturl)) {
2201 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2202 } else {
2203 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2204 $link = new moodle_url("/message/index.php?id=$contact->id");
2205 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2207 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2209 echo html_writer::end_tag('td');
2211 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2213 echo html_writer::end_tag('tr');
2217 * Constructs the add/remove contact link to display next to other users
2219 * @param bool $incontactlist is the user a contact
2220 * @param bool $isblocked is the user blocked
2221 * @param stdClass $contact contact object
2222 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2223 * @param bool $text include text next to the icons?
2224 * @param bool $icon include a graphical icon?
2225 * @return string
2227 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2228 $strcontact = '';
2230 if($incontactlist){
2231 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2232 } else if ($isblocked) {
2233 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2234 } else{
2235 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2238 return $strcontact;
2242 * Constructs the block contact link to display next to other users
2244 * @param bool $incontactlist is the user a contact?
2245 * @param bool $isblocked is the user blocked?
2246 * @param stdClass $contact contact object
2247 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2248 * @param bool $text include text next to the icons?
2249 * @param bool $icon include a graphical icon?
2250 * @return string
2252 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2253 $strblock = '';
2255 //commented out to allow the user to block a contact without having to remove them first
2256 /*if ($incontactlist) {
2257 //$strblock = '';
2258 } else*/
2259 if ($isblocked) {
2260 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2261 } else{
2262 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2265 return $strblock;
2269 * Moves messages from a particular user from the message table (unread messages) to message_read
2270 * This is typically only used when a user is deleted
2272 * @param object $userid User id
2273 * @return boolean success
2275 function message_move_userfrom_unread2read($userid) {
2276 global $DB;
2278 // move all unread messages from message table to message_read
2279 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2280 foreach ($messages as $message) {
2281 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2284 return true;
2288 * marks ALL messages being sent from $fromuserid to $touserid as read
2290 * @param int $touserid the id of the message recipient
2291 * @param int $fromuserid the id of the message sender
2292 * @return void
2294 function message_mark_messages_read($touserid, $fromuserid){
2295 global $DB;
2297 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2298 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2300 foreach ($messages as $message) {
2301 message_mark_message_read($message, time());
2304 $messages->close();
2308 * Mark a single message as read
2310 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2311 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2312 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2313 * @return int the ID of the message in the message_read table
2315 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2316 global $DB;
2318 $message->timeread = $timeread;
2320 $messageid = $message->id;
2321 unset($message->id);//unset because it will get a new id on insert into message_read
2323 //If any processors have pending actions abort them
2324 if (!$messageworkingempty) {
2325 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2327 $messagereadid = $DB->insert_record('message_read', $message);
2328 $DB->delete_records('message', array('id' => $messageid));
2329 return $messagereadid;
2333 * A helper function that prints a formatted heading
2335 * @param string $title the heading to display
2336 * @param int $colspan
2337 * @return void
2339 function message_print_heading($title, $colspan=3) {
2340 echo html_writer::start_tag('tr');
2341 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2342 echo html_writer::end_tag('tr');
2346 * Get all message processors, validate corresponding plugin existance and
2347 * system configuration
2349 * @param bool $ready only return ready-to-use processors
2350 * @param bool $reset Reset list of message processors (used in unit tests)
2351 * @return mixed $processors array of objects containing information on message processors
2353 function get_message_processors($ready = false, $reset = false) {
2354 global $DB, $CFG;
2356 static $processors;
2357 if ($reset) {
2358 $processors = array();
2361 if (empty($processors)) {
2362 // Get all processors, ensure the name column is the first so it will be the array key
2363 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2364 foreach ($processors as &$processor){
2365 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2366 if (is_readable($processorfile)) {
2367 include_once($processorfile);
2368 $processclass = 'message_output_' . $processor->name;
2369 if (class_exists($processclass)) {
2370 $pclass = new $processclass();
2371 $processor->object = $pclass;
2372 $processor->configured = 0;
2373 if ($pclass->is_system_configured()) {
2374 $processor->configured = 1;
2376 $processor->hassettings = 0;
2377 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2378 $processor->hassettings = 1;
2380 $processor->available = 1;
2381 } else {
2382 print_error('errorcallingprocessor', 'message');
2384 } else {
2385 $processor->available = 0;
2389 if ($ready) {
2390 // Filter out enabled and system_configured processors
2391 $readyprocessors = $processors;
2392 foreach ($readyprocessors as $readyprocessor) {
2393 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2394 unset($readyprocessors[$readyprocessor->name]);
2397 return $readyprocessors;
2400 return $processors;
2404 * Get all message providers, validate their plugin existance and
2405 * system configuration
2407 * @return mixed $processors array of objects containing information on message processors
2409 function get_message_providers() {
2410 global $CFG, $DB;
2412 $pluginman = core_plugin_manager::instance();
2414 $providers = $DB->get_records('message_providers', null, 'name');
2416 // Remove all the providers whose plugins are disabled or don't exist
2417 foreach ($providers as $providerid => $provider) {
2418 $plugin = $pluginman->get_plugin_info($provider->component);
2419 if ($plugin) {
2420 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2421 unset($providers[$providerid]); // Plugins does not exist
2422 continue;
2424 if ($plugin->is_enabled() === false) {
2425 unset($providers[$providerid]); // Plugin disabled
2426 continue;
2430 return $providers;
2434 * Get an instance of the message_output class for one of the output plugins.
2435 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2436 * @return message_output message_output the requested class.
2438 function get_message_processor($type) {
2439 global $CFG;
2441 // Note, we cannot use the get_message_processors function here, becaues this
2442 // code is called during install after installing each messaging plugin, and
2443 // get_message_processors caches the list of installed plugins.
2445 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2446 if (!is_readable($processorfile)) {
2447 throw new coding_exception('Unknown message processor type ' . $type);
2450 include_once($processorfile);
2452 $processclass = 'message_output_' . $type;
2453 if (!class_exists($processclass)) {
2454 throw new coding_exception('Message processor ' . $type .
2455 ' does not define the right class');
2458 return new $processclass();
2462 * Get messaging outputs default (site) preferences
2464 * @return object $processors object containing information on message processors
2466 function get_message_output_default_preferences() {
2467 return get_config('message');
2471 * Translate message default settings from binary value to the array of string
2472 * representing the settings to be stored. Also validate the provided value and
2473 * use default if it is malformed.
2475 * @param int $plugindefault Default setting suggested by plugin
2476 * @param string $processorname The name of processor
2477 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2479 function translate_message_default_setting($plugindefault, $processorname) {
2480 // Preset translation arrays
2481 $permittedvalues = array(
2482 0x04 => 'disallowed',
2483 0x08 => 'permitted',
2484 0x0c => 'forced',
2487 $loggedinstatusvalues = array(
2488 0x00 => null, // use null if loggedin/loggedoff is not defined
2489 0x01 => 'loggedin',
2490 0x02 => 'loggedoff',
2493 // define the default setting
2494 $processor = get_message_processor($processorname);
2495 $default = $processor->get_default_messaging_settings();
2497 // Validate the value. It should not exceed the maximum size
2498 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2499 debugging(get_string('errortranslatingdefault', 'message'));
2500 $plugindefault = $default;
2502 // Use plugin default setting of 'permitted' is 0
2503 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2504 $plugindefault = $default;
2507 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2508 $loggedin = $loggedoff = null;
2510 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2511 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2512 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2515 return array($permitted, $loggedin, $loggedoff);
2519 * Return a list of page types
2520 * @param string $pagetype current page type
2521 * @param stdClass $parentcontext Block's parent context
2522 * @param stdClass $currentcontext Current context of block
2524 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2525 return array('messages-*'=>get_string('page-message-x', 'message'));
2529 * Is $USER one of the supplied users?
2531 * $user2 will be null if viewing a user's recent conversations
2533 * @param stdClass the first user
2534 * @param stdClass the second user or null
2535 * @return bool True if the current user is one of either $user1 or $user2
2537 function message_current_user_is_involved($user1, $user2) {
2538 global $USER;
2540 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2541 throw new coding_exception('Invalid user object detected. Missing id.');
2544 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2545 return false;
2547 return true;