Merge branch 'install_27_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / message / lib.php
bloba3bb7cb69d361a205b24f0a4c7f26b487ba9346b
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);
133 // Only show the search button if we're viewing our own messages.
134 // Search isn't currently able to deal with user A wanting to search user B's messages.
135 if ($showactionlinks) {
136 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
137 echo html_writer::start_tag('fieldset');
138 $managebuttonclass = 'visible';
139 if ($viewing == MESSAGE_VIEW_SEARCH) {
140 $managebuttonclass = 'hiddenelement';
142 $strmanagecontacts = get_string('search','message');
143 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
144 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
145 echo html_writer::end_tag('fieldset');
146 echo html_writer::end_tag('form');
149 echo html_writer::end_tag('div');
153 * Print course participants. Called by message_print_contact_selector()
155 * @param object $context the course context
156 * @param int $courseid the course ID
157 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
158 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
159 * @param string $titletodisplay Optionally specify a title to display above the participants
160 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
161 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
162 * @return void
164 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
165 global $DB, $USER, $PAGE, $OUTPUT;
167 if (empty($titletodisplay)) {
168 $titletodisplay = get_string('participants');
171 $countparticipants = count_enrolled_users($context);
173 list($esql, $params) = get_enrolled_sql($context);
174 $params['mcuserid'] = $USER->id;
175 $ufields = user_picture::fields('u');
177 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
178 FROM {user} u
179 JOIN ($esql) je ON je.id = u.id
180 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
181 WHERE u.deleted = 0";
183 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
185 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
186 echo $OUTPUT->render($pagingbar);
188 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
190 echo html_writer::start_tag('tr');
191 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
192 echo html_writer::end_tag('tr');
194 foreach ($participants as $participant) {
195 if ($participant->id != $USER->id) {
197 $iscontact = false;
198 $isblocked = false;
199 if ( $participant->contactlistid ) {
200 if ($participant->blocked == 0) {
201 // Is contact. Is not blocked.
202 $iscontact = true;
203 $isblocked = false;
204 } else {
205 // Is blocked.
206 $iscontact = false;
207 $isblocked = true;
211 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
212 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
216 echo html_writer::end_tag('table');
220 * Retrieve users blocked by $user1
222 * @param object $user1 the user whose messages are being viewed
223 * @param object $user2 the user $user1 is talking to. If they are being blocked
224 * they will have a variable called 'isblocked' added to their user object
225 * @return array the users blocked by $user1
227 function message_get_blocked_users($user1=null, $user2=null) {
228 global $DB, $USER;
230 if (empty($user1)) {
231 $user1 = $USER;
234 if (!empty($user2)) {
235 $user2->isblocked = false;
238 $blockedusers = array();
240 $userfields = user_picture::fields('u', array('lastaccess'));
241 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
242 FROM {message_contacts} mc
243 JOIN {user} u ON u.id = mc.contactid
244 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
245 WHERE mc.userid = :user1id2 AND mc.blocked = 1
246 GROUP BY $userfields
247 ORDER BY u.firstname ASC";
248 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
250 foreach($rs as $rd) {
251 $blockedusers[] = $rd;
253 if (!empty($user2) && $user2->id == $rd->id) {
254 $user2->isblocked = true;
257 $rs->close();
259 return $blockedusers;
263 * Print users blocked by $user1. Called by message_print_contact_selector()
265 * @param array $blockedusers the users blocked by $user1
266 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
267 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
268 * @param string $titletodisplay Optionally specify a title to display above the participants
269 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
270 * @return void
272 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
273 global $DB, $USER;
275 $countblocked = count($blockedusers);
277 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
279 if (!empty($titletodisplay)) {
280 echo html_writer::start_tag('tr');
281 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
282 echo html_writer::end_tag('tr');
285 if ($countblocked) {
286 echo html_writer::start_tag('tr');
287 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
288 echo html_writer::end_tag('tr');
290 $isuserblocked = true;
291 $isusercontact = false;
292 foreach ($blockedusers as $blockeduser) {
293 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
297 echo html_writer::end_tag('table');
301 * Retrieve $user1's contacts (online, offline and strangers)
303 * @param object $user1 the user whose messages are being viewed
304 * @param object $user2 the user $user1 is talking to. If they are a contact
305 * they will have a variable called 'iscontact' added to their user object
306 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
308 function message_get_contacts($user1=null, $user2=null) {
309 global $DB, $CFG, $USER;
311 if (empty($user1)) {
312 $user1 = $USER;
315 if (!empty($user2)) {
316 $user2->iscontact = false;
319 $timetoshowusers = 300; //Seconds default
320 if (isset($CFG->block_online_users_timetosee)) {
321 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
324 // time which a user is counting as being active since
325 $timefrom = time()-$timetoshowusers;
327 // people in our contactlist who are online
328 $onlinecontacts = array();
329 // people in our contactlist who are offline
330 $offlinecontacts = array();
331 // people who are not in our contactlist but have sent us a message
332 $strangers = array();
334 $userfields = user_picture::fields('u', array('lastaccess'));
336 // get all in our contactlist who are not blocked in our contact list
337 // and count messages we have waiting from each of them
338 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
339 FROM {message_contacts} mc
340 JOIN {user} u ON u.id = mc.contactid
341 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
342 WHERE mc.userid = ? AND mc.blocked = 0
343 GROUP BY $userfields
344 ORDER BY u.firstname ASC";
346 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
347 foreach ($rs as $rd) {
348 if ($rd->lastaccess >= $timefrom) {
349 // they have been active recently, so are counted online
350 $onlinecontacts[] = $rd;
352 } else {
353 $offlinecontacts[] = $rd;
356 if (!empty($user2) && $user2->id == $rd->id) {
357 $user2->iscontact = true;
360 $rs->close();
362 // get messages from anyone who isn't in our contact list and count the number
363 // of messages we have from each of them
364 $strangersql = "SELECT $userfields, count(m.id) as messagecount
365 FROM {message} m
366 JOIN {user} u ON u.id = m.useridfrom
367 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
368 WHERE mc.id IS NULL AND m.useridto = ?
369 GROUP BY $userfields
370 ORDER BY u.firstname ASC";
372 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
373 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
374 foreach ($rs as $rd) {
375 $strangers[$rd->id] = $rd;
377 $rs->close();
379 // Add noreply user and support user to the list, if they don't exist.
380 $supportuser = core_user::get_support_user();
381 if (!isset($strangers[$supportuser->id])) {
382 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
383 if ($supportuser->messagecount > 0) {
384 $strangers[$supportuser->id] = $supportuser;
388 $noreplyuser = core_user::get_noreply_user();
389 if (!isset($strangers[$noreplyuser->id])) {
390 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
391 if ($noreplyuser->messagecount > 0) {
392 $strangers[$noreplyuser->id] = $noreplyuser;
395 return array($onlinecontacts, $offlinecontacts, $strangers);
399 * Print $user1's contacts. Called by message_print_contact_selector()
401 * @param array $onlinecontacts $user1's contacts which are online
402 * @param array $offlinecontacts $user1's contacts which are offline
403 * @param array $strangers users which are not contacts but who have messaged $user1
404 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
405 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
406 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
407 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
408 * @param string $titletodisplay Optionally specify a title to display above the participants
409 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
410 * @return void
412 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
413 global $CFG, $PAGE, $OUTPUT;
415 $countonlinecontacts = count($onlinecontacts);
416 $countofflinecontacts = count($offlinecontacts);
417 $countstrangers = count($strangers);
418 $isuserblocked = null;
420 if ($countonlinecontacts + $countofflinecontacts == 0) {
421 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
424 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
426 if (!empty($titletodisplay)) {
427 message_print_heading($titletodisplay);
430 if($countonlinecontacts) {
431 // Print out list of online contacts.
433 if (empty($titletodisplay)) {
434 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
437 $isuserblocked = false;
438 $isusercontact = true;
439 foreach ($onlinecontacts as $contact) {
440 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
441 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
446 if ($countofflinecontacts) {
447 // Print out list of offline contacts.
449 if (empty($titletodisplay)) {
450 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
453 $isuserblocked = false;
454 $isusercontact = true;
455 foreach ($offlinecontacts as $contact) {
456 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
457 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
463 // Print out list of incoming contacts.
464 if ($countstrangers) {
465 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
467 $isuserblocked = false;
468 $isusercontact = false;
469 foreach ($strangers as $stranger) {
470 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
471 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
476 echo html_writer::end_tag('table');
478 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
479 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
484 * Print a select box allowing the user to choose to view new messages, course participants etc.
486 * Called by message_print_contact_selector()
487 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
488 * @param array $courses array of course objects. The courses the user is enrolled in.
489 * @param array $coursecontexts array of course contexts. Keyed on course id.
490 * @param int $countunreadtotal how many unread messages does the user have?
491 * @param int $countblocked how many users has the current user blocked?
492 * @param stdClass $user1 The user whose messages we are viewing.
493 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
494 * @return void
496 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
497 $options = array();
499 if ($countunreadtotal>0) { //if there are unread messages
500 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
503 $str = get_string('contacts', 'message');
504 $options[MESSAGE_VIEW_CONTACTS] = $str;
506 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
507 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
509 if (!empty($courses)) {
510 $courses_options = array();
512 foreach($courses as $course) {
513 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
514 //Not using short_text() as we want the end of the course name. Not the beginning.
515 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
516 if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
517 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
518 } else {
519 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
524 if (!empty($courses_options)) {
525 $options[] = array(get_string('courses') => $courses_options);
529 if ($countblocked>0) {
530 $str = get_string('blockedusers','message', $countblocked);
531 $options[MESSAGE_VIEW_BLOCKED] = $str;
534 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
535 echo html_writer::start_tag('fieldset');
536 if ( !empty($user1) && !empty($user1->id) ) {
537 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id));
539 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
540 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
541 echo html_writer::end_tag('fieldset');
542 echo html_writer::end_tag('form');
546 * Load the course contexts for all of the users courses
548 * @param array $courses array of course objects. The courses the user is enrolled in.
549 * @return array of course contexts
551 function message_get_course_contexts($courses) {
552 $coursecontexts = array();
554 foreach($courses as $course) {
555 $coursecontexts[$course->id] = context_course::instance($course->id);
558 return $coursecontexts;
562 * strip off action parameters like 'removecontact'
564 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
565 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
567 function message_remove_url_params($moodleurl) {
568 $newurl = new moodle_url($moodleurl);
569 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
570 return $newurl->out();
574 * Count the number of messages with a field having a specified value.
575 * if $field is empty then return count of the whole array
576 * if $field is non-existent then return 0
578 * @param array $messagearray array of message objects
579 * @param string $field the field to inspect on the message objects
580 * @param string $value the value to test the field against
582 function message_count_messages($messagearray, $field='', $value='') {
583 if (!is_array($messagearray)) return 0;
584 if ($field == '' or empty($messagearray)) return count($messagearray);
586 $count = 0;
587 foreach ($messagearray as $message) {
588 $count += ($message->$field == $value) ? 1 : 0;
590 return $count;
594 * Returns the count of unread messages for user. Either from a specific user or from all users.
596 * @param object $user1 the first user. Defaults to $USER
597 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
598 * @return int the count of $user1's unread messages
600 function message_count_unread_messages($user1=null, $user2=null) {
601 global $USER, $DB;
603 if (empty($user1)) {
604 $user1 = $USER;
607 if (!empty($user2)) {
608 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
609 array($user1->id, $user2->id), "COUNT('id')");
610 } else {
611 return $DB->count_records_select('message', "useridto = ?",
612 array($user1->id), "COUNT('id')");
617 * Count the number of users blocked by $user1
619 * @param object $user1 user object
620 * @return int the number of blocked users
622 function message_count_blocked_users($user1=null) {
623 global $USER, $DB;
625 if (empty($user1)) {
626 $user1 = $USER;
629 $sql = "SELECT count(mc.id)
630 FROM {message_contacts} mc
631 WHERE mc.userid = :userid AND mc.blocked = 1";
632 $params = array('userid' => $user1->id);
634 return $DB->count_records_sql($sql, $params);
638 * Print the search form and search results if a search has been performed
640 * @param boolean $advancedsearch show basic or advanced search form
641 * @param object $user1 the current user
642 * @return boolean true if a search was performed
644 function message_print_search($advancedsearch = false, $user1=null) {
645 $frm = data_submitted();
647 $doingsearch = false;
648 if ($frm) {
649 if (confirm_sesskey()) {
650 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
651 } else {
652 $frm = false;
656 if (!empty($frm->combinedsearch)) {
657 $combinedsearchstring = $frm->combinedsearch;
658 } else {
659 //$combinedsearchstring = get_string('searchcombined','message').'...';
660 $combinedsearchstring = '';
663 if ($doingsearch) {
664 if ($advancedsearch) {
666 $messagesearch = '';
667 if (!empty($frm->keywords)) {
668 $messagesearch = $frm->keywords;
670 $personsearch = '';
671 if (!empty($frm->name)) {
672 $personsearch = $frm->name;
674 include('search_advanced.html');
675 } else {
676 include('search.html');
679 $showicontext = false;
680 message_print_search_results($frm, $showicontext, $user1);
682 return true;
683 } else {
685 if ($advancedsearch) {
686 $personsearch = $messagesearch = '';
687 include('search_advanced.html');
688 } else {
689 include('search.html');
691 return false;
696 * Get the users recent conversations meaning all the people they've recently
697 * sent or received a message from plus the most recent message sent to or received from each other user
699 * @param object $user the current user
700 * @param int $limitfrom can be used for paging
701 * @param int $limitto can be used for paging
702 * @return array
704 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
705 global $DB;
707 $userfields = user_picture::fields('u', array('lastaccess'));
708 //This query retrieves the last message received from and sent to each user
709 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
710 //It then joins with some other tables to get some additional data we need
712 //message ID is used instead of timecreated as it should sort the same and will be much faster
714 //There is a separate query for read and unread queries as they are stored in different tables
715 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
716 $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
717 FROM {message_read} mr
718 JOIN (
719 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
720 FROM (
721 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
722 FROM {message_read} mr1
723 WHERE mr1.useridfrom = :userid1
724 AND mr1.notification = 0
725 GROUP BY mr1.useridto
726 UNION
727 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
728 FROM {message_read} mr2
729 WHERE mr2.useridto = :userid2
730 AND mr2.notification = 0
731 GROUP BY mr2.useridfrom
732 ) messages
733 GROUP BY messages.userid
734 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
735 JOIN {user} u ON u.id = messages2.userid
736 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
737 WHERE u.deleted = '0'
738 ORDER BY mr.id DESC";
739 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
740 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
742 $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
743 FROM {message} m
744 JOIN (
745 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
746 FROM (
747 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
748 FROM {message} m1
749 WHERE m1.useridfrom = :userid1
750 AND m1.notification = 0
751 GROUP BY m1.useridto
752 UNION
753 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
754 FROM {message} m2
755 WHERE m2.useridto = :userid2
756 AND m2.notification = 0
757 GROUP BY m2.useridfrom
758 ) messages
759 GROUP BY messages.userid
760 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
761 JOIN {user} u ON u.id = messages2.userid
762 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
763 WHERE u.deleted = '0'
764 ORDER BY m.id DESC";
765 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
767 $conversations = array();
769 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
770 //$conversation->id (the array key) is the other user's ID
771 $conversation_arrays = array($unread, $read);
772 foreach ($conversation_arrays as $conversation_array) {
773 foreach ($conversation_array as $conversation) {
774 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
775 $conversations[$conversation->id] = $conversation;
780 // Sort the conversations by $conversation->timecreated, newest to oldest
781 // There may be multiple conversations with the same timecreated
782 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
783 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
784 $conversations = array_reverse($conversations);
786 return $conversations;
790 * Get the users recent event notifications
792 * @param object $user the current user
793 * @param int $limitfrom can be used for paging
794 * @param int $limitto can be used for paging
795 * @return array
797 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
798 global $DB;
800 $userfields = user_picture::fields('u', array('lastaccess'));
801 $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
802 FROM {message_read} mr
803 JOIN {user} u ON u.id=mr.useridfrom
804 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
805 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
806 $params = array('userid1' => $user->id, 'notification' => 1);
808 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
809 return $notifications;
813 * Print the user's recent conversations
815 * @param stdClass $user the current user
816 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
818 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
819 global $USER;
821 echo html_writer::start_tag('p', array('class' => 'heading'));
822 echo get_string('mostrecentconversations', 'message');
823 echo html_writer::end_tag('p');
825 if (empty($user1)) {
826 $user1 = $USER;
829 $conversations = message_get_recent_conversations($user1);
831 // Attach context url information to create the "View this conversation" type links
832 foreach($conversations as $conversation) {
833 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
834 $conversation->contexturlname = get_string('thisconversation', 'message');
837 $showotheruser = true;
838 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
842 * Print the user's recent notifications
844 * @param stdClass $user the current user
846 function message_print_recent_notifications($user=null) {
847 global $USER;
849 echo html_writer::start_tag('p', array('class' => 'heading'));
850 echo get_string('mostrecentnotifications', 'message');
851 echo html_writer::end_tag('p');
853 if (empty($user)) {
854 $user = $USER;
857 $notifications = message_get_recent_notifications($user);
859 $showicontext = false;
860 $showotheruser = false;
861 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
865 * Print a list of recent messages
867 * @access private
869 * @param array $messages the messages to display
870 * @param stdClass $user the current user
871 * @param bool $showotheruser display information on the other user?
872 * @param bool $showicontext show text next to the action icons?
873 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
874 * @param bool $showactionlinks
875 * @return void
877 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
878 global $OUTPUT;
879 static $dateformat;
881 if (empty($dateformat)) {
882 $dateformat = get_string('strftimedatetimeshort');
885 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
886 foreach ($messages as $message) {
887 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
889 if ($showotheruser) {
890 $strcontact = $strblock = $strhistory = null;
892 if ($showactionlinks) {
893 if ( $message->contactlistid ) {
894 if ($message->blocked == 0) { // The other user isn't blocked.
895 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
896 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
897 } else { // The other user is blocked.
898 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
899 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
901 } else {
902 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
903 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
906 //should we show just the icon or icon and text?
907 $histicontext = 'icon';
908 if ($showicontext) {
909 $histicontext = 'both';
911 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
913 echo html_writer::start_tag('span', array('class' => 'otheruser'));
915 echo html_writer::start_tag('span', array('class' => 'pix'));
916 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
917 echo html_writer::end_tag('span');
919 echo html_writer::start_tag('span', array('class' => 'contact'));
921 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
922 $action = null;
923 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
925 echo html_writer::end_tag('span');//end contact
927 if ($showactionlinks) {
928 echo $strcontact.$strblock.$strhistory;
930 echo html_writer::end_tag('span');//end otheruser
933 $messagetext = message_format_message_text($message, $forcetexttohtml);
935 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
936 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
937 echo message_format_contexturl($message);
938 echo html_writer::end_tag('div');//end singlemessage
940 echo html_writer::end_tag('div');//end messagerecent
944 * Try to guess how to convert the message to html.
946 * @access private
948 * @param stdClass $message
949 * @param bool $forcetexttohtml
950 * @return string html fragment
952 function message_format_message_text($message, $forcetexttohtml = false) {
953 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
955 $options = new stdClass();
956 $options->para = false;
958 $format = $message->fullmessageformat;
960 if ($message->smallmessage !== '') {
961 if ($message->notification == 1) {
962 if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
963 $format = FORMAT_PLAIN;
966 $messagetext = $message->smallmessage;
968 } else if ($message->fullmessageformat == FORMAT_HTML) {
969 if ($message->fullmessagehtml !== '') {
970 $messagetext = $message->fullmessagehtml;
971 } else {
972 $messagetext = $message->fullmessage;
973 $format = FORMAT_MOODLE;
976 } else {
977 if ($message->fullmessage !== '') {
978 $messagetext = $message->fullmessage;
979 } else {
980 $messagetext = $message->fullmessagehtml;
981 $format = FORMAT_HTML;
985 if ($forcetexttohtml) {
986 // This is a crazy hack, why not set proper format when creating the notifications?
987 if ($format === FORMAT_PLAIN) {
988 $format = FORMAT_MOODLE;
991 return format_text($messagetext, $format, $options);
995 * Add the selected user as a contact for the current user
997 * @param int $contactid the ID of the user to add as a contact
998 * @param int $blocked 1 if you wish to block the contact
999 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
1000 * Otherwise returns the result of update_record() or insert_record()
1002 function message_add_contact($contactid, $blocked=0) {
1003 global $USER, $DB;
1005 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
1006 return false;
1009 // Check if a record already exists as we may be changing blocking status.
1010 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
1011 // Check if blocking status has been changed.
1012 if ($contact->blocked !== $blocked) {
1013 $contact->blocked = $blocked;
1014 $DB->update_record('message_contacts', $contact);
1016 if ($blocked == 1) {
1017 // Trigger event for blocking a contact.
1018 $event = \core\event\message_contact_blocked::create(array(
1019 'objectid' => $contact->id,
1020 'userid' => $contact->userid,
1021 'relateduserid' => $contact->contactid,
1022 'context' => context_user::instance($contact->userid)
1024 $event->add_record_snapshot('message_contacts', $contact);
1025 $event->trigger();
1026 } else {
1027 // Trigger event for unblocking a contact.
1028 $event = \core\event\message_contact_unblocked::create(array(
1029 'objectid' => $contact->id,
1030 'userid' => $contact->userid,
1031 'relateduserid' => $contact->contactid,
1032 'context' => context_user::instance($contact->userid)
1034 $event->add_record_snapshot('message_contacts', $contact);
1035 $event->trigger();
1038 return true;
1039 } else {
1040 // No change to blocking status.
1041 return true;
1044 } else {
1045 // New contact record.
1046 $contact = new stdClass();
1047 $contact->userid = $USER->id;
1048 $contact->contactid = $contactid;
1049 $contact->blocked = $blocked;
1050 $contact->id = $DB->insert_record('message_contacts', $contact);
1052 $eventparams = array(
1053 'objectid' => $contact->id,
1054 'userid' => $contact->userid,
1055 'relateduserid' => $contact->contactid,
1056 'context' => context_user::instance($contact->userid)
1059 if ($blocked) {
1060 $event = \core\event\message_contact_blocked::create($eventparams);
1061 } else {
1062 $event = \core\event\message_contact_added::create($eventparams);
1064 // Trigger event.
1065 $event->trigger();
1067 return true;
1072 * remove a contact
1074 * @param int $contactid the user ID of the contact to remove
1075 * @return bool returns the result of delete_records()
1077 function message_remove_contact($contactid) {
1078 global $USER, $DB;
1080 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1081 $DB->delete_records('message_contacts', array('id' => $contact->id));
1083 // Trigger event for removing a contact.
1084 $event = \core\event\message_contact_removed::create(array(
1085 'objectid' => $contact->id,
1086 'userid' => $contact->userid,
1087 'relateduserid' => $contact->contactid,
1088 'context' => context_user::instance($contact->userid)
1090 $event->add_record_snapshot('message_contacts', $contact);
1091 $event->trigger();
1093 return true;
1096 return false;
1100 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1102 * @param int $contactid the user ID of the contact to unblock
1103 * @return bool returns the result of delete_records()
1105 function message_unblock_contact($contactid) {
1106 return message_add_contact($contactid, 0);
1110 * Block a user.
1112 * @param int $contactid the user ID of the user to block
1113 * @return bool
1115 function message_block_contact($contactid) {
1116 return message_add_contact($contactid, 1);
1120 * Load a user's contact record
1122 * @param int $contactid the user ID of the user whose contact record you want
1123 * @return array message contacts
1125 function message_get_contact($contactid) {
1126 global $USER, $DB;
1127 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1131 * Print the results of a message search
1133 * @param mixed $frm submitted form data
1134 * @param bool $showicontext show text next to action icons?
1135 * @param object $currentuser the current user
1136 * @return void
1138 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1139 global $USER, $DB, $OUTPUT;
1141 if (empty($currentuser)) {
1142 $currentuser = $USER;
1145 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1147 $personsearch = false;
1148 $personsearchstring = null;
1149 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1150 $personsearch = true;
1151 $personsearchstring = $frm->name;
1152 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1153 $personsearch = true;
1154 $personsearchstring = $frm->combinedsearch;
1157 // Search for person.
1158 if ($personsearch) {
1159 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1160 $users = array();
1161 $mycourses = enrol_get_my_courses('id');
1162 $mycoursesids = array();
1163 foreach ($mycourses as $mycourse) {
1164 $mycoursesids[] = $mycourse->id;
1166 $susers = message_search_users($mycoursesids, $personsearchstring);
1167 foreach ($susers as $suser) {
1168 $users[$suser->id] = $suser;
1170 } else {
1171 $users = message_search_users(SITEID, $personsearchstring);
1174 if (!empty($users)) {
1175 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1176 echo get_string('userssearchresults', 'message', count($users));
1177 echo html_writer::end_tag('p');
1179 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1180 foreach ($users as $user) {
1182 if ( $user->contactlistid ) {
1183 if ($user->blocked == 0) { // User is not blocked.
1184 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1185 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1186 } else { // blocked
1187 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1188 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1190 } else {
1191 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1192 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1195 // Should we show just the icon or icon and text?
1196 $histicontext = 'icon';
1197 if ($showicontext) {
1198 $histicontext = 'both';
1200 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1202 echo html_writer::start_tag('tr');
1204 echo html_writer::start_tag('td', array('class' => 'pix'));
1205 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1206 echo html_writer::end_tag('td');
1208 echo html_writer::start_tag('td',array('class' => 'contact'));
1209 $action = null;
1210 $link = new moodle_url("/message/index.php?id=$user->id");
1211 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1212 echo html_writer::end_tag('td');
1214 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1215 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1216 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1218 echo html_writer::end_tag('tr');
1220 echo html_writer::end_tag('table');
1222 } else {
1223 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1224 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1225 echo html_writer::end_tag('p');
1229 // search messages for keywords
1230 $messagesearch = false;
1231 $messagesearchstring = null;
1232 if (!empty($frm->keywords)) {
1233 $messagesearch = true;
1234 $messagesearchstring = clean_text(trim($frm->keywords));
1235 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1236 $messagesearch = true;
1237 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1240 if ($messagesearch) {
1241 if ($messagesearchstring) {
1242 $keywords = explode(' ', $messagesearchstring);
1243 } else {
1244 $keywords = array();
1246 $tome = false;
1247 $fromme = false;
1248 $courseid = 'none';
1250 if (empty($frm->keywordsoption)) {
1251 $frm->keywordsoption = 'allmine';
1254 switch ($frm->keywordsoption) {
1255 case 'tome':
1256 $tome = true;
1257 break;
1258 case 'fromme':
1259 $fromme = true;
1260 break;
1261 case 'allmine':
1262 $tome = true;
1263 $fromme = true;
1264 break;
1265 case 'allusers':
1266 $courseid = SITEID;
1267 break;
1268 case 'courseusers':
1269 $courseid = $frm->courseid;
1270 break;
1271 default:
1272 $tome = true;
1273 $fromme = true;
1276 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1278 // Get a list of contacts.
1279 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1280 $contacts = array();
1283 // Print heading with number of results.
1284 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1285 $countresults = count($messages);
1286 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1287 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1288 } else {
1289 echo get_string('keywordssearchresults', 'message', $countresults);
1291 echo html_writer::end_tag('p');
1293 // Print table headings.
1294 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1296 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1297 $headertdend = html_writer::end_tag('td');
1298 echo html_writer::start_tag('tr');
1299 echo $headertdstart.get_string('from').$headertdend;
1300 echo $headertdstart.get_string('to').$headertdend;
1301 echo $headertdstart.get_string('message', 'message').$headertdend;
1302 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1303 echo html_writer::end_tag('tr');
1305 $blockedcount = 0;
1306 $dateformat = get_string('strftimedatetimeshort');
1307 $strcontext = get_string('context', 'message');
1308 foreach ($messages as $message) {
1310 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1311 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1312 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1313 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1316 $blockedcount ++;
1317 continue;
1320 // Load user-to record.
1321 if ($message->useridto !== $USER->id) {
1322 $userto = core_user::get_user($message->useridto);
1323 $tocontact = (array_key_exists($message->useridto, $contacts) and
1324 ($contacts[$message->useridto]->blocked == 0) );
1325 $toblocked = (array_key_exists($message->useridto, $contacts) and
1326 ($contacts[$message->useridto]->blocked == 1) );
1327 } else {
1328 $userto = false;
1329 $tocontact = false;
1330 $toblocked = false;
1333 // Load user-from record.
1334 if ($message->useridfrom !== $USER->id) {
1335 $userfrom = core_user::get_user($message->useridfrom);
1336 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1337 ($contacts[$message->useridfrom]->blocked == 0) );
1338 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1339 ($contacts[$message->useridfrom]->blocked == 1) );
1340 } else {
1341 $userfrom = false;
1342 $fromcontact = false;
1343 $fromblocked = false;
1346 // Find date string for this message.
1347 $date = usergetdate($message->timecreated);
1348 $datestring = $date['year'].$date['mon'].$date['mday'];
1350 // Print out message row.
1351 echo html_writer::start_tag('tr', array('valign' => 'top'));
1353 echo html_writer::start_tag('td', array('class' => 'contact'));
1354 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1355 echo html_writer::end_tag('td');
1357 echo html_writer::start_tag('td', array('class' => 'contact'));
1358 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1359 echo html_writer::end_tag('td');
1361 echo html_writer::start_tag('td', array('class' => 'summary'));
1362 echo message_get_fragment($message->smallmessage, $keywords);
1363 echo html_writer::start_tag('div', array('class' => 'link'));
1365 // If the user clicks the context link display message sender on the left.
1366 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1367 $leftsideuserid = $rightsideuserid = null;
1368 if ($currentuser->id == $message->useridto) {
1369 $leftsideuserid = $message->useridto;
1370 $rightsideuserid = $message->useridfrom;
1371 } else {
1372 $leftsideuserid = $message->useridfrom;
1373 $rightsideuserid = $message->useridto;
1375 message_history_link($leftsideuserid, $rightsideuserid, false,
1376 $messagesearchstring, 'm'.$message->id, $strcontext);
1377 echo html_writer::end_tag('div');
1378 echo html_writer::end_tag('td');
1380 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1382 echo html_writer::end_tag('tr');
1386 if ($blockedcount > 0) {
1387 echo html_writer::start_tag('tr');
1388 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1389 echo html_writer::end_tag('tr');
1391 echo html_writer::end_tag('table');
1393 } else {
1394 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1398 if (!$personsearch && !$messagesearch) {
1399 //they didn't enter any search terms
1400 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1403 echo html_writer::end_tag('div');
1407 * Print information on a user. Used when printing search results.
1409 * @param object/bool $user the user to display or false if you just want $USER
1410 * @param bool $iscontact is the user being displayed a contact?
1411 * @param bool $isblocked is the user being displayed blocked?
1412 * @param bool $includeicontext include text next to the action icons?
1413 * @return void
1415 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1416 global $USER, $OUTPUT;
1418 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1420 if ($user === false) {
1421 echo $OUTPUT->user_picture($USER, $userpictureparams);
1422 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1423 $userpictureparams['link'] = false;
1424 echo $OUTPUT->user_picture($USER, $userpictureparams);
1425 echo fullname($user);
1426 } else {
1427 echo $OUTPUT->user_picture($user, $userpictureparams);
1429 $link = new moodle_url("/message/index.php?id=$user->id");
1430 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1431 get_string('sendmessageto', 'message', fullname($user))));
1433 $return = false;
1434 $script = null;
1435 if ($iscontact) {
1436 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1437 } else {
1438 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1441 if ($isblocked) {
1442 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1443 } else {
1444 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1450 * Print a message contact link
1452 * @param int $userid the ID of the user to apply to action to
1453 * @param string $linktype can be add, remove, block or unblock
1454 * @param bool $return if true return the link as a string. If false echo the link.
1455 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1456 * @param bool $text include text next to the icons?
1457 * @param bool $icon include a graphical icon?
1458 * @return string if $return is true otherwise bool
1460 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1461 global $OUTPUT, $PAGE;
1463 //hold onto the strings as we're probably creating a bunch of links
1464 static $str;
1466 if (empty($script)) {
1467 //strip off previous action params like 'removecontact'
1468 $script = message_remove_url_params($PAGE->url);
1471 if (empty($str->blockcontact)) {
1472 $str = new stdClass();
1473 $str->blockcontact = get_string('blockcontact', 'message');
1474 $str->unblockcontact = get_string('unblockcontact', 'message');
1475 $str->removecontact = get_string('removecontact', 'message');
1476 $str->addcontact = get_string('addcontact', 'message');
1479 $command = $linktype.'contact';
1480 $string = $str->{$command};
1482 $safealttext = s($string);
1484 $safestring = '';
1485 if (!empty($text)) {
1486 $safestring = $safealttext;
1489 $img = '';
1490 if ($icon) {
1491 $iconpath = null;
1492 switch ($linktype) {
1493 case 'block':
1494 $iconpath = 't/block';
1495 break;
1496 case 'unblock':
1497 $iconpath = 't/unblock';
1498 break;
1499 case 'remove':
1500 $iconpath = 't/removecontact';
1501 break;
1502 case 'add':
1503 default:
1504 $iconpath = 't/addcontact';
1507 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1510 $output = '<span class="'.$linktype.'contact">'.
1511 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1512 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1513 $img.
1514 $safestring.'</a></span>';
1516 if ($return) {
1517 return $output;
1518 } else {
1519 echo $output;
1520 return true;
1525 * echo or return a link to take the user to the full message history between themselves and another user
1527 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1528 * @param int $userid2 the ID of the other user
1529 * @param bool $return true to return the link as a string. False to echo the link.
1530 * @param string $keywords any keywords to highlight in the message history
1531 * @param string $position anchor name to jump to within the message history
1532 * @param string $linktext optionally specify the link text
1533 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1535 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1536 global $OUTPUT, $PAGE;
1537 static $strmessagehistory;
1539 if (empty($strmessagehistory)) {
1540 $strmessagehistory = get_string('messagehistory', 'message');
1543 if ($position) {
1544 $position = "#$position";
1546 if ($keywords) {
1547 $keywords = "&search=".urlencode($keywords);
1550 if ($linktext == 'icon') { // Icon only
1551 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1552 } else if ($linktext == 'both') { // Icon and standard name
1553 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1554 $fulllink .= '&nbsp;'.$strmessagehistory;
1555 } else if ($linktext) { // Custom name
1556 $fulllink = $linktext;
1557 } else { // Standard name only
1558 $fulllink = $strmessagehistory;
1561 $popupoptions = array(
1562 'height' => 500,
1563 'width' => 500,
1564 'menubar' => false,
1565 'location' => false,
1566 'status' => true,
1567 'scrollbars' => true,
1568 'resizable' => true);
1570 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1571 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1572 $link->param('viewing', $PAGE->url->get_param('viewing'));
1574 $action = null;
1575 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1577 $str = '<span class="history">'.$str.'</span>';
1579 if ($return) {
1580 return $str;
1581 } else {
1582 echo $str;
1583 return true;
1589 * Search through course users.
1591 * If $courseids contains the site course then this function searches
1592 * through all undeleted and confirmed users.
1594 * @param int|array $courseids Course ID or array of course IDs.
1595 * @param string $searchtext the text to search for.
1596 * @param string $sort the column name to order by.
1597 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1598 * @return array An array of {@link $USER} records.
1600 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1601 global $CFG, $USER, $DB;
1603 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1604 if (!$courseids) {
1605 $courseids = array(SITEID);
1608 // Allow an integer to be passed.
1609 if (!is_array($courseids)) {
1610 $courseids = array($courseids);
1613 $fullname = $DB->sql_fullname();
1614 $ufields = user_picture::fields('u');
1616 if (!empty($sort)) {
1617 $order = ' ORDER BY '. $sort;
1618 } else {
1619 $order = '';
1622 $params = array(
1623 'userid' => $USER->id,
1624 'query' => "%$searchtext%"
1627 if (empty($exceptions)) {
1628 $exceptions = array();
1629 } else if (!empty($exceptions) && is_string($exceptions)) {
1630 $exceptions = explode(',', $exceptions);
1633 // Ignore self and guest account.
1634 $exceptions[] = $USER->id;
1635 $exceptions[] = $CFG->siteguest;
1637 // Exclude exceptions from the search result.
1638 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1639 $except = ' AND u.id ' . $except;
1640 $params = array_merge($params_except, $params);
1642 if (in_array(SITEID, $courseids)) {
1643 // Search on site level.
1644 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1645 FROM {user} u
1646 LEFT JOIN {message_contacts} mc
1647 ON mc.contactid = u.id AND mc.userid = :userid
1648 WHERE u.deleted = '0' AND u.confirmed = '1'
1649 AND (".$DB->sql_like($fullname, ':query', false).")
1650 $except
1651 $order", $params);
1652 } else {
1653 // Search in courses.
1655 // Getting the context IDs or each course.
1656 $contextids = array();
1657 foreach ($courseids as $courseid) {
1658 $context = context_course::instance($courseid);
1659 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1661 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1662 $params = array_merge($params, $contextparams);
1664 // Everyone who has a role assignment in this course or higher.
1665 // TODO: add enabled enrolment join here (skodak)
1666 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1667 FROM {user} u
1668 JOIN {role_assignments} ra ON ra.userid = u.id
1669 LEFT JOIN {message_contacts} mc
1670 ON mc.contactid = u.id AND mc.userid = :userid
1671 WHERE u.deleted = '0' AND u.confirmed = '1'
1672 AND (".$DB->sql_like($fullname, ':query', false).")
1673 AND ra.contextid $contextwhere
1674 $except
1675 $order", $params);
1677 return $users;
1682 * Search a user's messages
1684 * Returns a list of posts found using an array of search terms
1685 * eg word +word -word
1687 * @param array $searchterms an array of search terms (strings)
1688 * @param bool $fromme include messages from the user?
1689 * @param bool $tome include messages to the user?
1690 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1691 * @param int $userid the user ID of the current user
1692 * @return mixed An array of messages or false if no matching messages were found
1694 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1695 global $CFG, $USER, $DB;
1697 // If user is searching all messages check they are allowed to before doing anything else.
1698 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1699 print_error('accessdenied','admin');
1702 // If no userid sent then assume current user.
1703 if ($userid == 0) $userid = $USER->id;
1705 // Some differences in SQL syntax.
1706 if ($DB->sql_regex_supported()) {
1707 $REGEXP = $DB->sql_regex(true);
1708 $NOTREGEXP = $DB->sql_regex(false);
1711 $searchcond = array();
1712 $params = array();
1713 $i = 0;
1715 // Preprocess search terms to check whether we have at least 1 eligible search term.
1716 // If we do we can drop words around it like 'a'.
1717 $dropshortwords = false;
1718 foreach ($searchterms as $searchterm) {
1719 if (strlen($searchterm) >= 2) {
1720 $dropshortwords = true;
1724 foreach ($searchterms as $searchterm) {
1725 $i++;
1727 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1729 if ($dropshortwords && strlen($searchterm) < 2) {
1730 continue;
1732 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1733 if (!$DB->sql_regex_supported()) {
1734 if (substr($searchterm, 0, 1) == '-') {
1735 $NOT = true;
1737 $searchterm = trim($searchterm, '+-');
1740 if (substr($searchterm,0,1) == "+") {
1741 $searchterm = substr($searchterm,1);
1742 $searchterm = preg_quote($searchterm, '|');
1743 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1744 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1746 } else if (substr($searchterm,0,1) == "-") {
1747 $searchterm = substr($searchterm,1);
1748 $searchterm = preg_quote($searchterm, '|');
1749 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1750 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1752 } else {
1753 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1754 $params['ss'.$i] = "%$searchterm%";
1758 if (empty($searchcond)) {
1759 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1760 $params['ss1'] = "%";
1761 } else {
1762 $searchcond = implode(" AND ", $searchcond);
1765 // There are several possibilities
1766 // 1. courseid = SITEID : The admin is searching messages by all users
1767 // 2. courseid = ?? : A teacher is searching messages by users in
1768 // one of their courses - currently disabled
1769 // 3. courseid = none : User is searching their own messages;
1770 // a. Messages from user
1771 // b. Messages to user
1772 // c. Messages to and from user
1774 if ($courseid == SITEID) { // Admin is searching all messages.
1775 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1776 FROM {message_read} m
1777 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1778 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1779 FROM {message} m
1780 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1782 } else if ($courseid !== 'none') {
1783 // This has not been implemented due to security concerns.
1784 $m_read = array();
1785 $m_unread = array();
1787 } else {
1789 if ($fromme and $tome) {
1790 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1791 $params['userid1'] = $userid;
1792 $params['userid2'] = $userid;
1794 } else if ($fromme) {
1795 $searchcond .= " AND m.useridfrom=:userid";
1796 $params['userid'] = $userid;
1798 } else if ($tome) {
1799 $searchcond .= " AND m.useridto=:userid";
1800 $params['userid'] = $userid;
1803 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1804 FROM {message_read} m
1805 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1806 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1807 FROM {message} m
1808 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1812 /// The keys may be duplicated in $m_read and $m_unread so we can't
1813 /// do a simple concatenation
1814 $messages = array();
1815 foreach ($m_read as $m) {
1816 $messages[] = $m;
1818 foreach ($m_unread as $m) {
1819 $messages[] = $m;
1822 return (empty($messages)) ? false : $messages;
1826 * Given a message object that we already know has a long message
1827 * this function truncates the message nicely to the first
1828 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1830 * @param string $message the message
1831 * @param int $minlength the minimum length to trim the message to
1832 * @return string the shortened message
1834 function message_shorten_message($message, $minlength = 0) {
1835 $i = 0;
1836 $tag = false;
1837 $length = strlen($message);
1838 $count = 0;
1839 $stopzone = false;
1840 $truncate = 0;
1841 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1844 for ($i=0; $i<$length; $i++) {
1845 $char = $message[$i];
1847 switch ($char) {
1848 case "<":
1849 $tag = true;
1850 break;
1851 case ">":
1852 $tag = false;
1853 break;
1854 default:
1855 if (!$tag) {
1856 if ($stopzone) {
1857 if ($char == '.' or $char == ' ') {
1858 $truncate = $i+1;
1859 break 2;
1862 $count++;
1864 break;
1866 if (!$stopzone) {
1867 if ($count > $minlength) {
1868 $stopzone = true;
1873 if (!$truncate) {
1874 $truncate = $i;
1877 return substr($message, 0, $truncate);
1882 * Given a string and an array of keywords, this function looks
1883 * for the first keyword in the string, and then chops out a
1884 * small section from the text that shows that word in context.
1886 * @param string $message the text to search
1887 * @param array $keywords array of keywords to find
1889 function message_get_fragment($message, $keywords) {
1891 $fullsize = 160;
1892 $halfsize = (int)($fullsize/2);
1894 $message = strip_tags($message);
1896 foreach ($keywords as $keyword) { // Just get the first one
1897 if ($keyword !== '') {
1898 break;
1901 if (empty($keyword)) { // None found, so just return start of message
1902 return message_shorten_message($message, 30);
1905 $leadin = $leadout = '';
1907 /// Find the start of the fragment
1908 $start = 0;
1909 $length = strlen($message);
1911 $pos = strpos($message, $keyword);
1912 if ($pos > $halfsize) {
1913 $start = $pos - $halfsize;
1914 $leadin = '...';
1916 /// Find the end of the fragment
1917 $end = $start + $fullsize;
1918 if ($end > $length) {
1919 $end = $length;
1920 } else {
1921 $leadout = '...';
1924 /// Pull out the fragment and format it
1926 $fragment = substr($message, $start, $end - $start);
1927 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1928 return $fragment;
1932 * Retrieve the messages between two users
1934 * @param object $user1 the current user
1935 * @param object $user2 the other user
1936 * @param int $limitnum the maximum number of messages to retrieve
1937 * @param bool $viewingnewmessages are we currently viewing new messages?
1939 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1940 global $DB, $CFG;
1942 $messages = array();
1944 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1945 //desc to get the last $limitnum messages then flip the order in php
1946 $sort = 'asc';
1947 if ($limitnum>0) {
1948 $sort = 'desc';
1951 $notificationswhere = null;
1952 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1953 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1954 $notificationswhere = 'AND notification=0';
1957 //prevent notifications of your own actions appearing in your own message history
1958 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1960 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1961 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1962 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1963 "timecreated $sort", '*', 0, $limitnum)) {
1964 foreach ($messages_read as $message) {
1965 $messages[] = $message;
1968 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1969 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1970 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1971 "timecreated $sort", '*', 0, $limitnum)) {
1972 foreach ($messages_new as $message) {
1973 $messages[] = $message;
1977 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
1979 //if we only want the last $limitnum messages
1980 $messagecount = count($messages);
1981 if ($limitnum > 0 && $messagecount > $limitnum) {
1982 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1985 return $messages;
1989 * Print the message history between two users
1991 * @param object $user1 the current user
1992 * @param object $user2 the other user
1993 * @param string $search search terms to highlight
1994 * @param int $messagelimit maximum number of messages to return
1995 * @param string $messagehistorylink the html for the message history link or false
1996 * @param bool $viewingnewmessages are we currently viewing new messages?
1998 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1999 global $CFG, $OUTPUT;
2001 echo $OUTPUT->box_start('center');
2002 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
2003 echo html_writer::start_tag('tr');
2005 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
2006 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2007 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
2008 echo html_writer::end_tag('td');
2010 echo html_writer::start_tag('td', array('align' => 'center'));
2011 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
2012 echo html_writer::end_tag('td');
2014 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
2015 // Show user picture with link is real user else without link.
2016 if (core_user::is_real_user($user2->id)) {
2017 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2018 } else {
2019 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2021 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2023 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2025 $script = null;
2026 $text = true;
2027 $icon = false;
2029 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2030 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2031 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
2033 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2036 echo html_writer::end_tag('td');
2037 echo html_writer::end_tag('tr');
2038 echo html_writer::end_tag('table');
2039 echo $OUTPUT->box_end();
2041 if (!empty($messagehistorylink)) {
2042 echo $messagehistorylink;
2045 /// Get all the messages and print them
2046 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2047 $tablecontents = '';
2049 $current = new stdClass();
2050 $current->mday = '';
2051 $current->month = '';
2052 $current->year = '';
2053 $messagedate = get_string('strftimetime');
2054 $blockdate = get_string('strftimedaydate');
2055 foreach ($messages as $message) {
2056 if ($message->notification) {
2057 $notificationclass = ' notification';
2058 } else {
2059 $notificationclass = null;
2061 $date = usergetdate($message->timecreated);
2062 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2063 $current->mday = $date['mday'];
2064 $current->month = $date['month'];
2065 $current->year = $date['year'];
2067 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2068 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2070 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2073 $formatted_message = $side = null;
2074 if ($message->useridfrom == $user1->id) {
2075 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2076 $side = 'left';
2077 } else {
2078 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2079 $side = 'right';
2081 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2084 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2085 } else {
2086 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2091 * Format a message for display in the message history
2093 * @param object $message the message object
2094 * @param string $format optional date format
2095 * @param string $keywords keywords to highlight
2096 * @param string $class CSS class to apply to the div around the message
2097 * @return string the formatted message
2099 function message_format_message($message, $format='', $keywords='', $class='other') {
2101 static $dateformat;
2103 //if we haven't previously set the date format or they've supplied a new one
2104 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2105 if ($format) {
2106 $dateformat = $format;
2107 } else {
2108 $dateformat = get_string('strftimedatetimeshort');
2111 $time = userdate($message->timecreated, $dateformat);
2113 $messagetext = message_format_message_text($message, false);
2115 if ($keywords) {
2116 $messagetext = highlight($keywords, $messagetext);
2119 $messagetext .= message_format_contexturl($message);
2121 $messagetext = clean_text($messagetext, FORMAT_HTML);
2123 return <<<TEMPLATE
2124 <div class='message $class'>
2125 <a name="m{$message->id}"></a>
2126 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2127 </div>
2128 TEMPLATE;
2132 * Format a the context url and context url name of a message for display
2134 * @param object $message the message object
2135 * @return string the formatted string
2137 function message_format_contexturl($message) {
2138 $s = null;
2140 if (!empty($message->contexturl)) {
2141 $displaytext = null;
2142 if (!empty($message->contexturlname)) {
2143 $displaytext= $message->contexturlname;
2144 } else {
2145 $displaytext= $message->contexturl;
2147 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2148 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2149 $s .= html_writer::end_tag('div');
2152 return $s;
2156 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2158 * @param object $userfrom the message sender
2159 * @param object $userto the message recipient
2160 * @param string $message the message
2161 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2162 * @return int|false the ID of the new message or false
2164 function message_post_message($userfrom, $userto, $message, $format) {
2165 global $SITE, $CFG, $USER;
2167 $eventdata = new stdClass();
2168 $eventdata->component = 'moodle';
2169 $eventdata->name = 'instantmessage';
2170 $eventdata->userfrom = $userfrom;
2171 $eventdata->userto = $userto;
2173 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2174 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2176 if ($format == FORMAT_HTML) {
2177 $eventdata->fullmessagehtml = $message;
2178 //some message processors may revert to sending plain text even if html is supplied
2179 //so we keep both plain and html versions if we're intending to send html
2180 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2181 } else {
2182 $eventdata->fullmessage = $message;
2183 $eventdata->fullmessagehtml = '';
2186 $eventdata->fullmessageformat = $format;
2187 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2189 $s = new stdClass();
2190 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2191 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2193 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2194 if (!empty($eventdata->fullmessage)) {
2195 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2197 if (!empty($eventdata->fullmessagehtml)) {
2198 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2201 $eventdata->timecreated = time();
2202 $eventdata->notification = 0;
2203 return message_send($eventdata);
2207 * Print a row of contactlist displaying user picture, messages waiting and
2208 * block links etc
2210 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2211 * @param bool $incontactlist is the user a contact of ours?
2212 * @param bool $isblocked is the user blocked?
2213 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2214 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2215 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2216 * @return void
2218 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2219 global $OUTPUT, $USER, $COURSE;
2220 $fullname = fullname($contact);
2221 $fullnamelink = $fullname;
2223 $linkclass = '';
2224 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2225 $linkclass = 'messageselecteduser';
2228 // Are there any unread messages for this contact?
2229 if ($contact->messagecount > 0 ){
2230 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2233 $strcontact = $strblock = $strhistory = null;
2235 if ($showactionlinks) {
2236 // Show block and delete links if user is real user.
2237 if (core_user::is_real_user($contact->id)) {
2238 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2239 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2241 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2244 echo html_writer::start_tag('tr');
2245 echo html_writer::start_tag('td', array('class' => 'pix'));
2246 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2247 echo html_writer::end_tag('td');
2249 echo html_writer::start_tag('td', array('class' => 'contact'));
2251 $popupoptions = array(
2252 'height' => MESSAGE_DISCUSSION_HEIGHT,
2253 'width' => MESSAGE_DISCUSSION_WIDTH,
2254 'menubar' => false,
2255 'location' => false,
2256 'status' => true,
2257 'scrollbars' => true,
2258 'resizable' => true);
2260 $link = $action = null;
2261 if (!empty($selectcontacturl)) {
2262 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2263 } else {
2264 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2265 $link = new moodle_url("/message/index.php?id=$contact->id");
2266 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2268 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2270 echo html_writer::end_tag('td');
2272 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2274 echo html_writer::end_tag('tr');
2278 * Constructs the add/remove contact link to display next to other users
2280 * @param bool $incontactlist is the user a contact
2281 * @param bool $isblocked is the user blocked
2282 * @param stdClass $contact contact object
2283 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2284 * @param bool $text include text next to the icons?
2285 * @param bool $icon include a graphical icon?
2286 * @return string
2288 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2289 $strcontact = '';
2291 if($incontactlist){
2292 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2293 } else if ($isblocked) {
2294 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2295 } else{
2296 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2299 return $strcontact;
2303 * Constructs the block contact link to display next to other users
2305 * @param bool $incontactlist is the user a contact?
2306 * @param bool $isblocked is the user blocked?
2307 * @param stdClass $contact contact object
2308 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2309 * @param bool $text include text next to the icons?
2310 * @param bool $icon include a graphical icon?
2311 * @return string
2313 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2314 $strblock = '';
2316 //commented out to allow the user to block a contact without having to remove them first
2317 /*if ($incontactlist) {
2318 //$strblock = '';
2319 } else*/
2320 if ($isblocked) {
2321 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2322 } else{
2323 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2326 return $strblock;
2330 * Moves messages from a particular user from the message table (unread messages) to message_read
2331 * This is typically only used when a user is deleted
2333 * @param object $userid User id
2334 * @return boolean success
2336 function message_move_userfrom_unread2read($userid) {
2337 global $DB;
2339 // move all unread messages from message table to message_read
2340 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2341 foreach ($messages as $message) {
2342 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2345 return true;
2349 * marks ALL messages being sent from $fromuserid to $touserid as read
2351 * @param int $touserid the id of the message recipient
2352 * @param int $fromuserid the id of the message sender
2353 * @return void
2355 function message_mark_messages_read($touserid, $fromuserid){
2356 global $DB;
2358 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2359 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2361 foreach ($messages as $message) {
2362 message_mark_message_read($message, time());
2365 $messages->close();
2369 * Mark a single message as read
2371 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2372 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2373 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2374 * @return int the ID of the message in the message_read table
2376 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2377 global $DB;
2379 $message->timeread = $timeread;
2381 $messageid = $message->id;
2382 unset($message->id);//unset because it will get a new id on insert into message_read
2384 //If any processors have pending actions abort them
2385 if (!$messageworkingempty) {
2386 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2388 $messagereadid = $DB->insert_record('message_read', $message);
2390 $DB->delete_records('message', array('id' => $messageid));
2392 // Trigger event for reading a message.
2393 $event = \core\event\message_viewed::create(array(
2394 'objectid' => $messagereadid,
2395 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2396 'context' => context_user::instance($message->useridto),
2397 'relateduserid' => $message->useridfrom,
2398 'other' => array(
2399 'messageid' => $messageid
2402 $event->trigger();
2404 return $messagereadid;
2408 * A helper function that prints a formatted heading
2410 * @param string $title the heading to display
2411 * @param int $colspan
2412 * @return void
2414 function message_print_heading($title, $colspan=3) {
2415 echo html_writer::start_tag('tr');
2416 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2417 echo html_writer::end_tag('tr');
2421 * Get all message processors, validate corresponding plugin existance and
2422 * system configuration
2424 * @param bool $ready only return ready-to-use processors
2425 * @param bool $reset Reset list of message processors (used in unit tests)
2426 * @return mixed $processors array of objects containing information on message processors
2428 function get_message_processors($ready = false, $reset = false) {
2429 global $DB, $CFG;
2431 static $processors;
2432 if ($reset) {
2433 $processors = array();
2436 if (empty($processors)) {
2437 // Get all processors, ensure the name column is the first so it will be the array key
2438 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2439 foreach ($processors as &$processor){
2440 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2441 if (is_readable($processorfile)) {
2442 include_once($processorfile);
2443 $processclass = 'message_output_' . $processor->name;
2444 if (class_exists($processclass)) {
2445 $pclass = new $processclass();
2446 $processor->object = $pclass;
2447 $processor->configured = 0;
2448 if ($pclass->is_system_configured()) {
2449 $processor->configured = 1;
2451 $processor->hassettings = 0;
2452 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2453 $processor->hassettings = 1;
2455 $processor->available = 1;
2456 } else {
2457 print_error('errorcallingprocessor', 'message');
2459 } else {
2460 $processor->available = 0;
2464 if ($ready) {
2465 // Filter out enabled and system_configured processors
2466 $readyprocessors = $processors;
2467 foreach ($readyprocessors as $readyprocessor) {
2468 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2469 unset($readyprocessors[$readyprocessor->name]);
2472 return $readyprocessors;
2475 return $processors;
2479 * Get all message providers, validate their plugin existance and
2480 * system configuration
2482 * @return mixed $processors array of objects containing information on message processors
2484 function get_message_providers() {
2485 global $CFG, $DB;
2487 $pluginman = core_plugin_manager::instance();
2489 $providers = $DB->get_records('message_providers', null, 'name');
2491 // Remove all the providers whose plugins are disabled or don't exist
2492 foreach ($providers as $providerid => $provider) {
2493 $plugin = $pluginman->get_plugin_info($provider->component);
2494 if ($plugin) {
2495 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2496 unset($providers[$providerid]); // Plugins does not exist
2497 continue;
2499 if ($plugin->is_enabled() === false) {
2500 unset($providers[$providerid]); // Plugin disabled
2501 continue;
2505 return $providers;
2509 * Get an instance of the message_output class for one of the output plugins.
2510 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2511 * @return message_output message_output the requested class.
2513 function get_message_processor($type) {
2514 global $CFG;
2516 // Note, we cannot use the get_message_processors function here, becaues this
2517 // code is called during install after installing each messaging plugin, and
2518 // get_message_processors caches the list of installed plugins.
2520 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2521 if (!is_readable($processorfile)) {
2522 throw new coding_exception('Unknown message processor type ' . $type);
2525 include_once($processorfile);
2527 $processclass = 'message_output_' . $type;
2528 if (!class_exists($processclass)) {
2529 throw new coding_exception('Message processor ' . $type .
2530 ' does not define the right class');
2533 return new $processclass();
2537 * Get messaging outputs default (site) preferences
2539 * @return object $processors object containing information on message processors
2541 function get_message_output_default_preferences() {
2542 return get_config('message');
2546 * Translate message default settings from binary value to the array of string
2547 * representing the settings to be stored. Also validate the provided value and
2548 * use default if it is malformed.
2550 * @param int $plugindefault Default setting suggested by plugin
2551 * @param string $processorname The name of processor
2552 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2554 function translate_message_default_setting($plugindefault, $processorname) {
2555 // Preset translation arrays
2556 $permittedvalues = array(
2557 0x04 => 'disallowed',
2558 0x08 => 'permitted',
2559 0x0c => 'forced',
2562 $loggedinstatusvalues = array(
2563 0x00 => null, // use null if loggedin/loggedoff is not defined
2564 0x01 => 'loggedin',
2565 0x02 => 'loggedoff',
2568 // define the default setting
2569 $processor = get_message_processor($processorname);
2570 $default = $processor->get_default_messaging_settings();
2572 // Validate the value. It should not exceed the maximum size
2573 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2574 debugging(get_string('errortranslatingdefault', 'message'));
2575 $plugindefault = $default;
2577 // Use plugin default setting of 'permitted' is 0
2578 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2579 $plugindefault = $default;
2582 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2583 $loggedin = $loggedoff = null;
2585 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2586 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2587 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2590 return array($permitted, $loggedin, $loggedoff);
2594 * Return a list of page types
2595 * @param string $pagetype current page type
2596 * @param stdClass $parentcontext Block's parent context
2597 * @param stdClass $currentcontext Current context of block
2599 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2600 return array('messages-*'=>get_string('page-message-x', 'message'));
2604 * Is $USER one of the supplied users?
2606 * $user2 will be null if viewing a user's recent conversations
2608 * @param stdClass the first user
2609 * @param stdClass the second user or null
2610 * @return bool True if the current user is one of either $user1 or $user2
2612 function message_current_user_is_involved($user1, $user2) {
2613 global $USER;
2615 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2616 throw new coding_exception('Invalid user object detected. Missing id.');
2619 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2620 return false;
2622 return true;