Merge branch 'MDL-48660-m27' of https://github.com/sammarshallou/moodle into MOODLE_2...
[moodle.git] / message / lib.php
blob426cdaed9ba340906499d1ac888122b6191341ad
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 contacts.
134 if ($viewing == MESSAGE_VIEW_CONTACTS && $user2 == null) {
135 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
136 echo html_writer::start_tag('fieldset');
137 $managebuttonclass = 'visible';
138 if ($viewing == MESSAGE_VIEW_SEARCH) {
139 $managebuttonclass = 'hiddenelement';
141 $strmanagecontacts = get_string('search','message');
142 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
143 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
144 echo html_writer::end_tag('fieldset');
145 echo html_writer::end_tag('form');
148 echo html_writer::end_tag('div');
152 * Print course participants. Called by message_print_contact_selector()
154 * @param object $context the course context
155 * @param int $courseid the course ID
156 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
157 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
158 * @param string $titletodisplay Optionally specify a title to display above the participants
159 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
160 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
161 * @return void
163 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
164 global $DB, $USER, $PAGE, $OUTPUT;
166 if (empty($titletodisplay)) {
167 $titletodisplay = get_string('participants');
170 $countparticipants = count_enrolled_users($context);
172 list($esql, $params) = get_enrolled_sql($context);
173 $params['mcuserid'] = $USER->id;
174 $ufields = user_picture::fields('u');
176 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
177 FROM {user} u
178 JOIN ($esql) je ON je.id = u.id
179 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
180 WHERE u.deleted = 0";
182 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
184 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
185 echo $OUTPUT->render($pagingbar);
187 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
189 echo html_writer::start_tag('tr');
190 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
191 echo html_writer::end_tag('tr');
193 foreach ($participants as $participant) {
194 if ($participant->id != $USER->id) {
196 $iscontact = false;
197 $isblocked = false;
198 if ( $participant->contactlistid ) {
199 if ($participant->blocked == 0) {
200 // Is contact. Is not blocked.
201 $iscontact = true;
202 $isblocked = false;
203 } else {
204 // Is blocked.
205 $iscontact = false;
206 $isblocked = true;
210 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
211 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
215 echo html_writer::end_tag('table');
219 * Retrieve users blocked by $user1
221 * @param object $user1 the user whose messages are being viewed
222 * @param object $user2 the user $user1 is talking to. If they are being blocked
223 * they will have a variable called 'isblocked' added to their user object
224 * @return array the users blocked by $user1
226 function message_get_blocked_users($user1=null, $user2=null) {
227 global $DB, $USER;
229 if (empty($user1)) {
230 $user1 = $USER;
233 if (!empty($user2)) {
234 $user2->isblocked = false;
237 $blockedusers = array();
239 $userfields = user_picture::fields('u', array('lastaccess'));
240 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
241 FROM {message_contacts} mc
242 JOIN {user} u ON u.id = mc.contactid
243 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
244 WHERE mc.userid = :user1id2 AND mc.blocked = 1
245 GROUP BY $userfields
246 ORDER BY u.firstname ASC";
247 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
249 foreach($rs as $rd) {
250 $blockedusers[] = $rd;
252 if (!empty($user2) && $user2->id == $rd->id) {
253 $user2->isblocked = true;
256 $rs->close();
258 return $blockedusers;
262 * Print users blocked by $user1. Called by message_print_contact_selector()
264 * @param array $blockedusers the users blocked by $user1
265 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
266 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
267 * @param string $titletodisplay Optionally specify a title to display above the participants
268 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
269 * @return void
271 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
272 global $DB, $USER;
274 $countblocked = count($blockedusers);
276 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
278 if (!empty($titletodisplay)) {
279 echo html_writer::start_tag('tr');
280 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
281 echo html_writer::end_tag('tr');
284 if ($countblocked) {
285 echo html_writer::start_tag('tr');
286 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
287 echo html_writer::end_tag('tr');
289 $isuserblocked = true;
290 $isusercontact = false;
291 foreach ($blockedusers as $blockeduser) {
292 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
296 echo html_writer::end_tag('table');
300 * Retrieve $user1's contacts (online, offline and strangers)
302 * @param object $user1 the user whose messages are being viewed
303 * @param object $user2 the user $user1 is talking to. If they are a contact
304 * they will have a variable called 'iscontact' added to their user object
305 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
307 function message_get_contacts($user1=null, $user2=null) {
308 global $DB, $CFG, $USER;
310 if (empty($user1)) {
311 $user1 = $USER;
314 if (!empty($user2)) {
315 $user2->iscontact = false;
318 $timetoshowusers = 300; //Seconds default
319 if (isset($CFG->block_online_users_timetosee)) {
320 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
323 // time which a user is counting as being active since
324 $timefrom = time()-$timetoshowusers;
326 // people in our contactlist who are online
327 $onlinecontacts = array();
328 // people in our contactlist who are offline
329 $offlinecontacts = array();
330 // people who are not in our contactlist but have sent us a message
331 $strangers = array();
333 $userfields = user_picture::fields('u', array('lastaccess'));
335 // get all in our contactlist who are not blocked in our contact list
336 // and count messages we have waiting from each of them
337 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
338 FROM {message_contacts} mc
339 JOIN {user} u ON u.id = mc.contactid
340 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
341 WHERE mc.userid = ? AND mc.blocked = 0
342 GROUP BY $userfields
343 ORDER BY u.firstname ASC";
345 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
346 foreach ($rs as $rd) {
347 if ($rd->lastaccess >= $timefrom) {
348 // they have been active recently, so are counted online
349 $onlinecontacts[] = $rd;
351 } else {
352 $offlinecontacts[] = $rd;
355 if (!empty($user2) && $user2->id == $rd->id) {
356 $user2->iscontact = true;
359 $rs->close();
361 // get messages from anyone who isn't in our contact list and count the number
362 // of messages we have from each of them
363 $strangersql = "SELECT $userfields, count(m.id) as messagecount
364 FROM {message} m
365 JOIN {user} u ON u.id = m.useridfrom
366 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
367 WHERE mc.id IS NULL AND m.useridto = ?
368 GROUP BY $userfields
369 ORDER BY u.firstname ASC";
371 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
372 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
373 foreach ($rs as $rd) {
374 $strangers[$rd->id] = $rd;
376 $rs->close();
378 // Add noreply user and support user to the list, if they don't exist.
379 $supportuser = core_user::get_support_user();
380 if (!isset($strangers[$supportuser->id])) {
381 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
382 if ($supportuser->messagecount > 0) {
383 $strangers[$supportuser->id] = $supportuser;
387 $noreplyuser = core_user::get_noreply_user();
388 if (!isset($strangers[$noreplyuser->id])) {
389 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
390 if ($noreplyuser->messagecount > 0) {
391 $strangers[$noreplyuser->id] = $noreplyuser;
394 return array($onlinecontacts, $offlinecontacts, $strangers);
398 * Print $user1's contacts. Called by message_print_contact_selector()
400 * @param array $onlinecontacts $user1's contacts which are online
401 * @param array $offlinecontacts $user1's contacts which are offline
402 * @param array $strangers users which are not contacts but who have messaged $user1
403 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
404 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
405 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
406 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
407 * @param string $titletodisplay Optionally specify a title to display above the participants
408 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
409 * @return void
411 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
412 global $CFG, $PAGE, $OUTPUT;
414 $countonlinecontacts = count($onlinecontacts);
415 $countofflinecontacts = count($offlinecontacts);
416 $countstrangers = count($strangers);
417 $isuserblocked = null;
419 if ($countonlinecontacts + $countofflinecontacts == 0) {
420 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
423 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
425 if (!empty($titletodisplay)) {
426 message_print_heading($titletodisplay);
429 if($countonlinecontacts) {
430 // Print out list of online contacts.
432 if (empty($titletodisplay)) {
433 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
436 $isuserblocked = false;
437 $isusercontact = true;
438 foreach ($onlinecontacts as $contact) {
439 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
440 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
445 if ($countofflinecontacts) {
446 // Print out list of offline contacts.
448 if (empty($titletodisplay)) {
449 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
452 $isuserblocked = false;
453 $isusercontact = true;
454 foreach ($offlinecontacts as $contact) {
455 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
456 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
462 // Print out list of incoming contacts.
463 if ($countstrangers) {
464 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
466 $isuserblocked = false;
467 $isusercontact = false;
468 foreach ($strangers as $stranger) {
469 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
470 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
475 echo html_writer::end_tag('table');
477 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
478 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
483 * Print a select box allowing the user to choose to view new messages, course participants etc.
485 * Called by message_print_contact_selector()
486 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
487 * @param array $courses array of course objects. The courses the user is enrolled in.
488 * @param array $coursecontexts array of course contexts. Keyed on course id.
489 * @param int $countunreadtotal how many unread messages does the user have?
490 * @param int $countblocked how many users has the current user blocked?
491 * @param stdClass $user1 The user whose messages we are viewing.
492 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
493 * @return void
495 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
496 global $PAGE;
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 $select = new single_select($PAGE->url, 'viewing', $options, $viewing, false);
535 $select->set_label(get_string('messagenavigation', 'message'));
537 $renderer = $PAGE->get_renderer('core');
538 echo $renderer->render($select);
542 * Load the course contexts for all of the users courses
544 * @param array $courses array of course objects. The courses the user is enrolled in.
545 * @return array of course contexts
547 function message_get_course_contexts($courses) {
548 $coursecontexts = array();
550 foreach($courses as $course) {
551 $coursecontexts[$course->id] = context_course::instance($course->id);
554 return $coursecontexts;
558 * strip off action parameters like 'removecontact'
560 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
561 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
563 function message_remove_url_params($moodleurl) {
564 $newurl = new moodle_url($moodleurl);
565 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
566 return $newurl->out();
570 * Count the number of messages with a field having a specified value.
571 * if $field is empty then return count of the whole array
572 * if $field is non-existent then return 0
574 * @param array $messagearray array of message objects
575 * @param string $field the field to inspect on the message objects
576 * @param string $value the value to test the field against
578 function message_count_messages($messagearray, $field='', $value='') {
579 if (!is_array($messagearray)) return 0;
580 if ($field == '' or empty($messagearray)) return count($messagearray);
582 $count = 0;
583 foreach ($messagearray as $message) {
584 $count += ($message->$field == $value) ? 1 : 0;
586 return $count;
590 * Returns the count of unread messages for user. Either from a specific user or from all users.
592 * @param object $user1 the first user. Defaults to $USER
593 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
594 * @return int the count of $user1's unread messages
596 function message_count_unread_messages($user1=null, $user2=null) {
597 global $USER, $DB;
599 if (empty($user1)) {
600 $user1 = $USER;
603 if (!empty($user2)) {
604 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
605 array($user1->id, $user2->id), "COUNT('id')");
606 } else {
607 return $DB->count_records_select('message', "useridto = ?",
608 array($user1->id), "COUNT('id')");
613 * Count the number of users blocked by $user1
615 * @param object $user1 user object
616 * @return int the number of blocked users
618 function message_count_blocked_users($user1=null) {
619 global $USER, $DB;
621 if (empty($user1)) {
622 $user1 = $USER;
625 $sql = "SELECT count(mc.id)
626 FROM {message_contacts} mc
627 WHERE mc.userid = :userid AND mc.blocked = 1";
628 $params = array('userid' => $user1->id);
630 return $DB->count_records_sql($sql, $params);
634 * Print the search form and search results if a search has been performed
636 * @param boolean $advancedsearch show basic or advanced search form
637 * @param object $user1 the current user
638 * @return boolean true if a search was performed
640 function message_print_search($advancedsearch = false, $user1=null) {
641 $frm = data_submitted();
643 $doingsearch = false;
644 if ($frm) {
645 if (confirm_sesskey()) {
646 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
647 } else {
648 $frm = false;
652 if (!empty($frm->combinedsearch)) {
653 $combinedsearchstring = $frm->combinedsearch;
654 } else {
655 //$combinedsearchstring = get_string('searchcombined','message').'...';
656 $combinedsearchstring = '';
659 if ($doingsearch) {
660 if ($advancedsearch) {
662 $messagesearch = '';
663 if (!empty($frm->keywords)) {
664 $messagesearch = $frm->keywords;
666 $personsearch = '';
667 if (!empty($frm->name)) {
668 $personsearch = $frm->name;
670 include('search_advanced.html');
671 } else {
672 include('search.html');
675 $showicontext = false;
676 message_print_search_results($frm, $showicontext, $user1);
678 return true;
679 } else {
681 if ($advancedsearch) {
682 $personsearch = $messagesearch = '';
683 include('search_advanced.html');
684 } else {
685 include('search.html');
687 return false;
692 * Get the users recent conversations meaning all the people they've recently
693 * sent or received a message from plus the most recent message sent to or received from each other user
695 * @param object $user the current user
696 * @param int $limitfrom can be used for paging
697 * @param int $limitto can be used for paging
698 * @return array
700 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
701 global $DB;
703 $userfields = user_picture::fields('otheruser', array('lastaccess'));
705 // This query retrieves the most recent message received from or sent to
706 // seach other user.
708 // If two messages have the same timecreated, we take the one with the
709 // larger id.
711 // There is a separate query for read and unread messages as they are stored
712 // in different tables. They were originally retrieved in one query but it
713 // was so large that it was difficult to be confident in its correctness.
714 $sql = "SELECT $userfields,
715 message.id as mid, message.notification, message.smallmessage, message.fullmessage,
716 message.fullmessagehtml, message.fullmessageformat, message.timecreated,
717 contact.id as contactlistid, contact.blocked
719 FROM {message_read} message
720 JOIN {user} otheruser ON otheruser.id = CASE
721 WHEN message.useridto = :userid1 THEN message.useridfrom
722 ELSE message.useridto END
723 LEFT JOIN {message_contacts} contact ON contact.userid = :userid2 AND contact.contactid = otheruser.id
725 WHERE otheruser.deleted = 0
726 AND (message.useridto = :userid3 OR message.useridfrom = :userid4)
727 AND message.notification = 0
728 AND NOT EXISTS (
729 SELECT 1
730 FROM {message_read} othermessage
731 WHERE ((othermessage.useridto = :userid5 AND othermessage.useridfrom = otheruser.id) OR
732 (othermessage.useridfrom = :userid6 AND othermessage.useridto = otheruser.id))
733 AND (othermessage.timecreated > message.timecreated OR (
734 othermessage.timecreated = message.timecreated AND othermessage.id > message.id))
737 ORDER BY message.timecreated DESC";
738 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id,
739 'userid4' => $user->id, 'userid5' => $user->id, 'userid6' => $user->id);
740 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
742 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
743 // exact same query as the one above, except for the table we are querying. So, simply replace references to
744 // the 'message_read' table with the 'message' table.
745 $sql = str_replace('{message_read}', '{message}', $sql);
746 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
748 $conversations = array();
750 // Union the 2 result sets together looking for the message with the most
751 // recent timecreated for each other user.
752 // $conversation->id (the array key) is the other user's ID.
753 $conversation_arrays = array($unread, $read);
754 foreach ($conversation_arrays as $conversation_array) {
755 foreach ($conversation_array as $conversation) {
756 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
757 $conversations[$conversation->id] = $conversation;
762 // Sort the conversations by $conversation->timecreated, newest to oldest
763 // There may be multiple conversations with the same timecreated
764 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
765 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
766 $conversations = array_reverse($conversations);
768 return $conversations;
772 * Get the users recent event notifications
774 * @param object $user the current user
775 * @param int $limitfrom can be used for paging
776 * @param int $limitto can be used for paging
777 * @return array
779 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
780 global $DB;
782 $userfields = user_picture::fields('u', array('lastaccess'));
783 $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
784 FROM {message_read} mr
785 JOIN {user} u ON u.id=mr.useridfrom
786 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
787 ORDER BY mr.timecreated DESC";
788 $params = array('userid1' => $user->id, 'notification' => 1);
790 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
791 return $notifications;
795 * Print the user's recent conversations
797 * @param stdClass $user the current user
798 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
800 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
801 global $USER;
803 echo html_writer::start_tag('p', array('class' => 'heading'));
804 echo get_string('mostrecentconversations', 'message');
805 echo html_writer::end_tag('p');
807 if (empty($user1)) {
808 $user1 = $USER;
811 $conversations = message_get_recent_conversations($user1);
813 // Attach context url information to create the "View this conversation" type links
814 foreach($conversations as $conversation) {
815 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
816 $conversation->contexturlname = get_string('thisconversation', 'message');
819 $showotheruser = true;
820 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
824 * Print the user's recent notifications
826 * @param stdClass $user the current user
828 function message_print_recent_notifications($user=null) {
829 global $USER;
831 echo html_writer::start_tag('p', array('class' => 'heading'));
832 echo get_string('mostrecentnotifications', 'message');
833 echo html_writer::end_tag('p');
835 if (empty($user)) {
836 $user = $USER;
839 $notifications = message_get_recent_notifications($user);
841 $showicontext = false;
842 $showotheruser = false;
843 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
847 * Print a list of recent messages
849 * @access private
851 * @param array $messages the messages to display
852 * @param stdClass $user the current user
853 * @param bool $showotheruser display information on the other user?
854 * @param bool $showicontext show text next to the action icons?
855 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
856 * @param bool $showactionlinks
857 * @return void
859 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
860 global $OUTPUT;
861 static $dateformat;
863 if (empty($dateformat)) {
864 $dateformat = get_string('strftimedatetimeshort');
867 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
868 foreach ($messages as $message) {
869 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
871 if ($showotheruser) {
872 $strcontact = $strblock = $strhistory = null;
874 if ($showactionlinks) {
875 if ( $message->contactlistid ) {
876 if ($message->blocked == 0) { // The other user isn't blocked.
877 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
878 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
879 } else { // The other user is blocked.
880 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
881 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
883 } else {
884 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
885 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
888 //should we show just the icon or icon and text?
889 $histicontext = 'icon';
890 if ($showicontext) {
891 $histicontext = 'both';
893 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
895 echo html_writer::start_tag('span', array('class' => 'otheruser'));
897 echo html_writer::start_tag('span', array('class' => 'pix'));
898 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
899 echo html_writer::end_tag('span');
901 echo html_writer::start_tag('span', array('class' => 'contact'));
903 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
904 $action = null;
905 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
907 echo html_writer::end_tag('span');//end contact
909 if ($showactionlinks) {
910 echo $strcontact.$strblock.$strhistory;
912 echo html_writer::end_tag('span');//end otheruser
915 $messagetext = message_format_message_text($message, $forcetexttohtml);
917 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
918 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
919 echo message_format_contexturl($message);
920 echo html_writer::end_tag('div');//end singlemessage
922 echo html_writer::end_tag('div');//end messagerecent
926 * Try to guess how to convert the message to html.
928 * @access private
930 * @param stdClass $message
931 * @param bool $forcetexttohtml
932 * @return string html fragment
934 function message_format_message_text($message, $forcetexttohtml = false) {
935 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
937 $options = new stdClass();
938 $options->para = false;
940 $format = $message->fullmessageformat;
942 if ($message->smallmessage !== '') {
943 if ($message->notification == 1) {
944 if ($message->fullmessagehtml !== '' or $message->fullmessage !== '') {
945 $format = FORMAT_PLAIN;
948 $messagetext = $message->smallmessage;
950 } else if ($message->fullmessageformat == FORMAT_HTML) {
951 if ($message->fullmessagehtml !== '') {
952 $messagetext = $message->fullmessagehtml;
953 } else {
954 $messagetext = $message->fullmessage;
955 $format = FORMAT_MOODLE;
958 } else {
959 if ($message->fullmessage !== '') {
960 $messagetext = $message->fullmessage;
961 } else {
962 $messagetext = $message->fullmessagehtml;
963 $format = FORMAT_HTML;
967 if ($forcetexttohtml) {
968 // This is a crazy hack, why not set proper format when creating the notifications?
969 if ($format === FORMAT_PLAIN) {
970 $format = FORMAT_MOODLE;
973 return format_text($messagetext, $format, $options);
977 * Add the selected user as a contact for the current user
979 * @param int $contactid the ID of the user to add as a contact
980 * @param int $blocked 1 if you wish to block the contact
981 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
982 * Otherwise returns the result of update_record() or insert_record()
984 function message_add_contact($contactid, $blocked=0) {
985 global $USER, $DB;
987 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
988 return false;
991 // Check if a record already exists as we may be changing blocking status.
992 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
993 // Check if blocking status has been changed.
994 if ($contact->blocked !== $blocked) {
995 $contact->blocked = $blocked;
996 $DB->update_record('message_contacts', $contact);
998 if ($blocked == 1) {
999 // Trigger event for blocking a contact.
1000 $event = \core\event\message_contact_blocked::create(array(
1001 'objectid' => $contact->id,
1002 'userid' => $contact->userid,
1003 'relateduserid' => $contact->contactid,
1004 'context' => context_user::instance($contact->userid)
1006 $event->add_record_snapshot('message_contacts', $contact);
1007 $event->trigger();
1008 } else {
1009 // Trigger event for unblocking a contact.
1010 $event = \core\event\message_contact_unblocked::create(array(
1011 'objectid' => $contact->id,
1012 'userid' => $contact->userid,
1013 'relateduserid' => $contact->contactid,
1014 'context' => context_user::instance($contact->userid)
1016 $event->add_record_snapshot('message_contacts', $contact);
1017 $event->trigger();
1020 return true;
1021 } else {
1022 // No change to blocking status.
1023 return true;
1026 } else {
1027 // New contact record.
1028 $contact = new stdClass();
1029 $contact->userid = $USER->id;
1030 $contact->contactid = $contactid;
1031 $contact->blocked = $blocked;
1032 $contact->id = $DB->insert_record('message_contacts', $contact);
1034 $eventparams = array(
1035 'objectid' => $contact->id,
1036 'userid' => $contact->userid,
1037 'relateduserid' => $contact->contactid,
1038 'context' => context_user::instance($contact->userid)
1041 if ($blocked) {
1042 $event = \core\event\message_contact_blocked::create($eventparams);
1043 } else {
1044 $event = \core\event\message_contact_added::create($eventparams);
1046 // Trigger event.
1047 $event->trigger();
1049 return true;
1054 * remove a contact
1056 * @param int $contactid the user ID of the contact to remove
1057 * @return bool returns the result of delete_records()
1059 function message_remove_contact($contactid) {
1060 global $USER, $DB;
1062 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1063 $DB->delete_records('message_contacts', array('id' => $contact->id));
1065 // Trigger event for removing a contact.
1066 $event = \core\event\message_contact_removed::create(array(
1067 'objectid' => $contact->id,
1068 'userid' => $contact->userid,
1069 'relateduserid' => $contact->contactid,
1070 'context' => context_user::instance($contact->userid)
1072 $event->add_record_snapshot('message_contacts', $contact);
1073 $event->trigger();
1075 return true;
1078 return false;
1082 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1084 * @param int $contactid the user ID of the contact to unblock
1085 * @return bool returns the result of delete_records()
1087 function message_unblock_contact($contactid) {
1088 return message_add_contact($contactid, 0);
1092 * Block a user.
1094 * @param int $contactid the user ID of the user to block
1095 * @return bool
1097 function message_block_contact($contactid) {
1098 return message_add_contact($contactid, 1);
1102 * Load a user's contact record
1104 * @param int $contactid the user ID of the user whose contact record you want
1105 * @return array message contacts
1107 function message_get_contact($contactid) {
1108 global $USER, $DB;
1109 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1113 * Print the results of a message search
1115 * @param mixed $frm submitted form data
1116 * @param bool $showicontext show text next to action icons?
1117 * @param object $currentuser the current user
1118 * @return void
1120 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1121 global $USER, $DB, $OUTPUT;
1123 if (empty($currentuser)) {
1124 $currentuser = $USER;
1127 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1129 $personsearch = false;
1130 $personsearchstring = null;
1131 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1132 $personsearch = true;
1133 $personsearchstring = $frm->name;
1134 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1135 $personsearch = true;
1136 $personsearchstring = $frm->combinedsearch;
1139 // Search for person.
1140 if ($personsearch) {
1141 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1142 $users = array();
1143 $mycourses = enrol_get_my_courses('id');
1144 $mycoursesids = array();
1145 foreach ($mycourses as $mycourse) {
1146 $mycoursesids[] = $mycourse->id;
1148 $susers = message_search_users($mycoursesids, $personsearchstring);
1149 foreach ($susers as $suser) {
1150 $users[$suser->id] = $suser;
1152 } else {
1153 $users = message_search_users(SITEID, $personsearchstring);
1156 if (!empty($users)) {
1157 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1158 echo get_string('userssearchresults', 'message', count($users));
1159 echo html_writer::end_tag('p');
1161 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1162 foreach ($users as $user) {
1164 if ( $user->contactlistid ) {
1165 if ($user->blocked == 0) { // User is not blocked.
1166 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1167 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1168 } else { // blocked
1169 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1170 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1172 } else {
1173 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1174 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1177 // Should we show just the icon or icon and text?
1178 $histicontext = 'icon';
1179 if ($showicontext) {
1180 $histicontext = 'both';
1182 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1184 echo html_writer::start_tag('tr');
1186 echo html_writer::start_tag('td', array('class' => 'pix'));
1187 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1188 echo html_writer::end_tag('td');
1190 echo html_writer::start_tag('td',array('class' => 'contact'));
1191 $action = null;
1192 $link = new moodle_url("/message/index.php?id=$user->id");
1193 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1194 echo html_writer::end_tag('td');
1196 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1197 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1198 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1200 echo html_writer::end_tag('tr');
1202 echo html_writer::end_tag('table');
1204 } else {
1205 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1206 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1207 echo html_writer::end_tag('p');
1211 // search messages for keywords
1212 $messagesearch = false;
1213 $messagesearchstring = null;
1214 if (!empty($frm->keywords)) {
1215 $messagesearch = true;
1216 $messagesearchstring = clean_text(trim($frm->keywords));
1217 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1218 $messagesearch = true;
1219 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1222 if ($messagesearch) {
1223 if ($messagesearchstring) {
1224 $keywords = explode(' ', $messagesearchstring);
1225 } else {
1226 $keywords = array();
1228 $tome = false;
1229 $fromme = false;
1230 $courseid = 'none';
1232 if (empty($frm->keywordsoption)) {
1233 $frm->keywordsoption = 'allmine';
1236 switch ($frm->keywordsoption) {
1237 case 'tome':
1238 $tome = true;
1239 break;
1240 case 'fromme':
1241 $fromme = true;
1242 break;
1243 case 'allmine':
1244 $tome = true;
1245 $fromme = true;
1246 break;
1247 case 'allusers':
1248 $courseid = SITEID;
1249 break;
1250 case 'courseusers':
1251 $courseid = $frm->courseid;
1252 break;
1253 default:
1254 $tome = true;
1255 $fromme = true;
1258 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1260 // Get a list of contacts.
1261 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1262 $contacts = array();
1265 // Print heading with number of results.
1266 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1267 $countresults = count($messages);
1268 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1269 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1270 } else {
1271 echo get_string('keywordssearchresults', 'message', $countresults);
1273 echo html_writer::end_tag('p');
1275 // Print table headings.
1276 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1278 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1279 $headertdend = html_writer::end_tag('td');
1280 echo html_writer::start_tag('tr');
1281 echo $headertdstart.get_string('from').$headertdend;
1282 echo $headertdstart.get_string('to').$headertdend;
1283 echo $headertdstart.get_string('message', 'message').$headertdend;
1284 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1285 echo html_writer::end_tag('tr');
1287 $blockedcount = 0;
1288 $dateformat = get_string('strftimedatetimeshort');
1289 $strcontext = get_string('context', 'message');
1290 foreach ($messages as $message) {
1292 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1293 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1294 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1295 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1298 $blockedcount ++;
1299 continue;
1302 // Load user-to record.
1303 if ($message->useridto !== $USER->id) {
1304 $userto = core_user::get_user($message->useridto);
1305 $tocontact = (array_key_exists($message->useridto, $contacts) and
1306 ($contacts[$message->useridto]->blocked == 0) );
1307 $toblocked = (array_key_exists($message->useridto, $contacts) and
1308 ($contacts[$message->useridto]->blocked == 1) );
1309 } else {
1310 $userto = false;
1311 $tocontact = false;
1312 $toblocked = false;
1315 // Load user-from record.
1316 if ($message->useridfrom !== $USER->id) {
1317 $userfrom = core_user::get_user($message->useridfrom);
1318 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1319 ($contacts[$message->useridfrom]->blocked == 0) );
1320 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1321 ($contacts[$message->useridfrom]->blocked == 1) );
1322 } else {
1323 $userfrom = false;
1324 $fromcontact = false;
1325 $fromblocked = false;
1328 // Find date string for this message.
1329 $date = usergetdate($message->timecreated);
1330 $datestring = $date['year'].$date['mon'].$date['mday'];
1332 // Print out message row.
1333 echo html_writer::start_tag('tr', array('valign' => 'top'));
1335 echo html_writer::start_tag('td', array('class' => 'contact'));
1336 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1337 echo html_writer::end_tag('td');
1339 echo html_writer::start_tag('td', array('class' => 'contact'));
1340 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1341 echo html_writer::end_tag('td');
1343 echo html_writer::start_tag('td', array('class' => 'summary'));
1344 echo message_get_fragment($message->smallmessage, $keywords);
1345 echo html_writer::start_tag('div', array('class' => 'link'));
1347 // If the user clicks the context link display message sender on the left.
1348 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1349 $leftsideuserid = $rightsideuserid = null;
1350 if ($currentuser->id == $message->useridto) {
1351 $leftsideuserid = $message->useridto;
1352 $rightsideuserid = $message->useridfrom;
1353 } else {
1354 $leftsideuserid = $message->useridfrom;
1355 $rightsideuserid = $message->useridto;
1357 message_history_link($leftsideuserid, $rightsideuserid, false,
1358 $messagesearchstring, 'm'.$message->id, $strcontext);
1359 echo html_writer::end_tag('div');
1360 echo html_writer::end_tag('td');
1362 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1364 echo html_writer::end_tag('tr');
1368 if ($blockedcount > 0) {
1369 echo html_writer::start_tag('tr');
1370 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1371 echo html_writer::end_tag('tr');
1373 echo html_writer::end_tag('table');
1375 } else {
1376 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1380 if (!$personsearch && !$messagesearch) {
1381 //they didn't enter any search terms
1382 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1385 echo html_writer::end_tag('div');
1389 * Print information on a user. Used when printing search results.
1391 * @param object/bool $user the user to display or false if you just want $USER
1392 * @param bool $iscontact is the user being displayed a contact?
1393 * @param bool $isblocked is the user being displayed blocked?
1394 * @param bool $includeicontext include text next to the action icons?
1395 * @return void
1397 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1398 global $USER, $OUTPUT;
1400 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1402 if ($user === false) {
1403 echo $OUTPUT->user_picture($USER, $userpictureparams);
1404 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1405 $userpictureparams['link'] = false;
1406 echo $OUTPUT->user_picture($USER, $userpictureparams);
1407 echo fullname($user);
1408 } else {
1409 echo $OUTPUT->user_picture($user, $userpictureparams);
1411 $link = new moodle_url("/message/index.php?id=$user->id");
1412 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1413 get_string('sendmessageto', 'message', fullname($user))));
1415 $return = false;
1416 $script = null;
1417 if ($iscontact) {
1418 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1419 } else {
1420 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1423 if ($isblocked) {
1424 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1425 } else {
1426 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1432 * Print a message contact link
1434 * @param int $userid the ID of the user to apply to action to
1435 * @param string $linktype can be add, remove, block or unblock
1436 * @param bool $return if true return the link as a string. If false echo the link.
1437 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1438 * @param bool $text include text next to the icons?
1439 * @param bool $icon include a graphical icon?
1440 * @return string if $return is true otherwise bool
1442 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1443 global $OUTPUT, $PAGE;
1445 //hold onto the strings as we're probably creating a bunch of links
1446 static $str;
1448 if (empty($script)) {
1449 //strip off previous action params like 'removecontact'
1450 $script = message_remove_url_params($PAGE->url);
1453 if (empty($str->blockcontact)) {
1454 $str = new stdClass();
1455 $str->blockcontact = get_string('blockcontact', 'message');
1456 $str->unblockcontact = get_string('unblockcontact', 'message');
1457 $str->removecontact = get_string('removecontact', 'message');
1458 $str->addcontact = get_string('addcontact', 'message');
1461 $command = $linktype.'contact';
1462 $string = $str->{$command};
1464 $safealttext = s($string);
1466 $safestring = '';
1467 if (!empty($text)) {
1468 $safestring = $safealttext;
1471 $img = '';
1472 if ($icon) {
1473 $iconpath = null;
1474 switch ($linktype) {
1475 case 'block':
1476 $iconpath = 't/block';
1477 break;
1478 case 'unblock':
1479 $iconpath = 't/unblock';
1480 break;
1481 case 'remove':
1482 $iconpath = 't/removecontact';
1483 break;
1484 case 'add':
1485 default:
1486 $iconpath = 't/addcontact';
1489 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1492 $output = '<span class="'.$linktype.'contact">'.
1493 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1494 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1495 $img.
1496 $safestring.'</a></span>';
1498 if ($return) {
1499 return $output;
1500 } else {
1501 echo $output;
1502 return true;
1507 * echo or return a link to take the user to the full message history between themselves and another user
1509 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1510 * @param int $userid2 the ID of the other user
1511 * @param bool $return true to return the link as a string. False to echo the link.
1512 * @param string $keywords any keywords to highlight in the message history
1513 * @param string $position anchor name to jump to within the message history
1514 * @param string $linktext optionally specify the link text
1515 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1517 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1518 global $OUTPUT, $PAGE;
1519 static $strmessagehistory;
1521 if (empty($strmessagehistory)) {
1522 $strmessagehistory = get_string('messagehistory', 'message');
1525 if ($position) {
1526 $position = "#$position";
1528 if ($keywords) {
1529 $keywords = "&search=".urlencode($keywords);
1532 if ($linktext == 'icon') { // Icon only
1533 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1534 } else if ($linktext == 'both') { // Icon and standard name
1535 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1536 $fulllink .= '&nbsp;'.$strmessagehistory;
1537 } else if ($linktext) { // Custom name
1538 $fulllink = $linktext;
1539 } else { // Standard name only
1540 $fulllink = $strmessagehistory;
1543 $popupoptions = array(
1544 'height' => 500,
1545 'width' => 500,
1546 'menubar' => false,
1547 'location' => false,
1548 'status' => true,
1549 'scrollbars' => true,
1550 'resizable' => true);
1552 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1553 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1554 $link->param('viewing', $PAGE->url->get_param('viewing'));
1556 $action = null;
1557 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1559 $str = '<span class="history">'.$str.'</span>';
1561 if ($return) {
1562 return $str;
1563 } else {
1564 echo $str;
1565 return true;
1571 * Search through course users.
1573 * If $courseids contains the site course then this function searches
1574 * through all undeleted and confirmed users.
1576 * @param int|array $courseids Course ID or array of course IDs.
1577 * @param string $searchtext the text to search for.
1578 * @param string $sort the column name to order by.
1579 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1580 * @return array An array of {@link $USER} records.
1582 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1583 global $CFG, $USER, $DB;
1585 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1586 if (!$courseids) {
1587 $courseids = array(SITEID);
1590 // Allow an integer to be passed.
1591 if (!is_array($courseids)) {
1592 $courseids = array($courseids);
1595 $fullname = $DB->sql_fullname();
1596 $ufields = user_picture::fields('u');
1598 if (!empty($sort)) {
1599 $order = ' ORDER BY '. $sort;
1600 } else {
1601 $order = '';
1604 $params = array(
1605 'userid' => $USER->id,
1606 'query' => "%$searchtext%"
1609 if (empty($exceptions)) {
1610 $exceptions = array();
1611 } else if (!empty($exceptions) && is_string($exceptions)) {
1612 $exceptions = explode(',', $exceptions);
1615 // Ignore self and guest account.
1616 $exceptions[] = $USER->id;
1617 $exceptions[] = $CFG->siteguest;
1619 // Exclude exceptions from the search result.
1620 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1621 $except = ' AND u.id ' . $except;
1622 $params = array_merge($params_except, $params);
1624 if (in_array(SITEID, $courseids)) {
1625 // Search on site level.
1626 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1627 FROM {user} u
1628 LEFT JOIN {message_contacts} mc
1629 ON mc.contactid = u.id AND mc.userid = :userid
1630 WHERE u.deleted = '0' AND u.confirmed = '1'
1631 AND (".$DB->sql_like($fullname, ':query', false).")
1632 $except
1633 $order", $params);
1634 } else {
1635 // Search in courses.
1637 // Getting the context IDs or each course.
1638 $contextids = array();
1639 foreach ($courseids as $courseid) {
1640 $context = context_course::instance($courseid);
1641 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1643 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1644 $params = array_merge($params, $contextparams);
1646 // Everyone who has a role assignment in this course or higher.
1647 // TODO: add enabled enrolment join here (skodak)
1648 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1649 FROM {user} u
1650 JOIN {role_assignments} ra ON ra.userid = u.id
1651 LEFT JOIN {message_contacts} mc
1652 ON mc.contactid = u.id AND mc.userid = :userid
1653 WHERE u.deleted = '0' AND u.confirmed = '1'
1654 AND (".$DB->sql_like($fullname, ':query', false).")
1655 AND ra.contextid $contextwhere
1656 $except
1657 $order", $params);
1659 return $users;
1664 * Search a user's messages
1666 * Returns a list of posts found using an array of search terms
1667 * eg word +word -word
1669 * @param array $searchterms an array of search terms (strings)
1670 * @param bool $fromme include messages from the user?
1671 * @param bool $tome include messages to the user?
1672 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1673 * @param int $userid the user ID of the current user
1674 * @return mixed An array of messages or false if no matching messages were found
1676 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1677 global $CFG, $USER, $DB;
1679 // If user is searching all messages check they are allowed to before doing anything else.
1680 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1681 print_error('accessdenied','admin');
1684 // If no userid sent then assume current user.
1685 if ($userid == 0) $userid = $USER->id;
1687 // Some differences in SQL syntax.
1688 if ($DB->sql_regex_supported()) {
1689 $REGEXP = $DB->sql_regex(true);
1690 $NOTREGEXP = $DB->sql_regex(false);
1693 $searchcond = array();
1694 $params = array();
1695 $i = 0;
1697 // Preprocess search terms to check whether we have at least 1 eligible search term.
1698 // If we do we can drop words around it like 'a'.
1699 $dropshortwords = false;
1700 foreach ($searchterms as $searchterm) {
1701 if (strlen($searchterm) >= 2) {
1702 $dropshortwords = true;
1706 foreach ($searchterms as $searchterm) {
1707 $i++;
1709 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1711 if ($dropshortwords && strlen($searchterm) < 2) {
1712 continue;
1714 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1715 if (!$DB->sql_regex_supported()) {
1716 if (substr($searchterm, 0, 1) == '-') {
1717 $NOT = true;
1719 $searchterm = trim($searchterm, '+-');
1722 if (substr($searchterm,0,1) == "+") {
1723 $searchterm = substr($searchterm,1);
1724 $searchterm = preg_quote($searchterm, '|');
1725 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1726 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1728 } else if (substr($searchterm,0,1) == "-") {
1729 $searchterm = substr($searchterm,1);
1730 $searchterm = preg_quote($searchterm, '|');
1731 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1732 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1734 } else {
1735 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1736 $params['ss'.$i] = "%$searchterm%";
1740 if (empty($searchcond)) {
1741 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1742 $params['ss1'] = "%";
1743 } else {
1744 $searchcond = implode(" AND ", $searchcond);
1747 // There are several possibilities
1748 // 1. courseid = SITEID : The admin is searching messages by all users
1749 // 2. courseid = ?? : A teacher is searching messages by users in
1750 // one of their courses - currently disabled
1751 // 3. courseid = none : User is searching their own messages;
1752 // a. Messages from user
1753 // b. Messages to user
1754 // c. Messages to and from user
1756 if ($courseid == SITEID) { // Admin is searching all messages.
1757 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1758 FROM {message_read} m
1759 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1760 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1761 FROM {message} m
1762 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1764 } else if ($courseid !== 'none') {
1765 // This has not been implemented due to security concerns.
1766 $m_read = array();
1767 $m_unread = array();
1769 } else {
1771 if ($fromme and $tome) {
1772 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1773 $params['userid1'] = $userid;
1774 $params['userid2'] = $userid;
1776 } else if ($fromme) {
1777 $searchcond .= " AND m.useridfrom=:userid";
1778 $params['userid'] = $userid;
1780 } else if ($tome) {
1781 $searchcond .= " AND m.useridto=:userid";
1782 $params['userid'] = $userid;
1785 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1786 FROM {message_read} m
1787 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1788 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1789 FROM {message} m
1790 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1794 /// The keys may be duplicated in $m_read and $m_unread so we can't
1795 /// do a simple concatenation
1796 $messages = array();
1797 foreach ($m_read as $m) {
1798 $messages[] = $m;
1800 foreach ($m_unread as $m) {
1801 $messages[] = $m;
1804 return (empty($messages)) ? false : $messages;
1808 * Given a message object that we already know has a long message
1809 * this function truncates the message nicely to the first
1810 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1812 * @param string $message the message
1813 * @param int $minlength the minimum length to trim the message to
1814 * @return string the shortened message
1816 function message_shorten_message($message, $minlength = 0) {
1817 $i = 0;
1818 $tag = false;
1819 $length = strlen($message);
1820 $count = 0;
1821 $stopzone = false;
1822 $truncate = 0;
1823 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1826 for ($i=0; $i<$length; $i++) {
1827 $char = $message[$i];
1829 switch ($char) {
1830 case "<":
1831 $tag = true;
1832 break;
1833 case ">":
1834 $tag = false;
1835 break;
1836 default:
1837 if (!$tag) {
1838 if ($stopzone) {
1839 if ($char == '.' or $char == ' ') {
1840 $truncate = $i+1;
1841 break 2;
1844 $count++;
1846 break;
1848 if (!$stopzone) {
1849 if ($count > $minlength) {
1850 $stopzone = true;
1855 if (!$truncate) {
1856 $truncate = $i;
1859 return substr($message, 0, $truncate);
1864 * Given a string and an array of keywords, this function looks
1865 * for the first keyword in the string, and then chops out a
1866 * small section from the text that shows that word in context.
1868 * @param string $message the text to search
1869 * @param array $keywords array of keywords to find
1871 function message_get_fragment($message, $keywords) {
1873 $fullsize = 160;
1874 $halfsize = (int)($fullsize/2);
1876 $message = strip_tags($message);
1878 foreach ($keywords as $keyword) { // Just get the first one
1879 if ($keyword !== '') {
1880 break;
1883 if (empty($keyword)) { // None found, so just return start of message
1884 return message_shorten_message($message, 30);
1887 $leadin = $leadout = '';
1889 /// Find the start of the fragment
1890 $start = 0;
1891 $length = strlen($message);
1893 $pos = strpos($message, $keyword);
1894 if ($pos > $halfsize) {
1895 $start = $pos - $halfsize;
1896 $leadin = '...';
1898 /// Find the end of the fragment
1899 $end = $start + $fullsize;
1900 if ($end > $length) {
1901 $end = $length;
1902 } else {
1903 $leadout = '...';
1906 /// Pull out the fragment and format it
1908 $fragment = substr($message, $start, $end - $start);
1909 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1910 return $fragment;
1914 * Retrieve the messages between two users
1916 * @param object $user1 the current user
1917 * @param object $user2 the other user
1918 * @param int $limitnum the maximum number of messages to retrieve
1919 * @param bool $viewingnewmessages are we currently viewing new messages?
1921 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1922 global $DB, $CFG;
1924 $messages = array();
1926 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1927 //desc to get the last $limitnum messages then flip the order in php
1928 $sort = 'asc';
1929 if ($limitnum>0) {
1930 $sort = 'desc';
1933 $notificationswhere = null;
1934 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1935 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1936 $notificationswhere = 'AND notification=0';
1939 //prevent notifications of your own actions appearing in your own message history
1940 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1942 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1943 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1944 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1945 "timecreated $sort", '*', 0, $limitnum)) {
1946 foreach ($messages_read as $message) {
1947 $messages[] = $message;
1950 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1951 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1952 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1953 "timecreated $sort", '*', 0, $limitnum)) {
1954 foreach ($messages_new as $message) {
1955 $messages[] = $message;
1959 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
1961 //if we only want the last $limitnum messages
1962 $messagecount = count($messages);
1963 if ($limitnum > 0 && $messagecount > $limitnum) {
1964 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1967 return $messages;
1971 * Print the message history between two users
1973 * @param object $user1 the current user
1974 * @param object $user2 the other user
1975 * @param string $search search terms to highlight
1976 * @param int $messagelimit maximum number of messages to return
1977 * @param string $messagehistorylink the html for the message history link or false
1978 * @param bool $viewingnewmessages are we currently viewing new messages?
1980 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1981 global $CFG, $OUTPUT;
1983 echo $OUTPUT->box_start('center');
1984 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1985 echo html_writer::start_tag('tr');
1987 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1988 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1989 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1990 echo html_writer::end_tag('td');
1992 echo html_writer::start_tag('td', array('align' => 'center'));
1993 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1994 echo html_writer::end_tag('td');
1996 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1997 // Show user picture with link is real user else without link.
1998 if (core_user::is_real_user($user2->id)) {
1999 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2000 } else {
2001 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2003 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2005 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2007 $script = null;
2008 $text = true;
2009 $icon = false;
2011 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2012 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2013 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
2015 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2018 echo html_writer::end_tag('td');
2019 echo html_writer::end_tag('tr');
2020 echo html_writer::end_tag('table');
2021 echo $OUTPUT->box_end();
2023 if (!empty($messagehistorylink)) {
2024 echo $messagehistorylink;
2027 /// Get all the messages and print them
2028 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2029 $tablecontents = '';
2031 $current = new stdClass();
2032 $current->mday = '';
2033 $current->month = '';
2034 $current->year = '';
2035 $messagedate = get_string('strftimetime');
2036 $blockdate = get_string('strftimedaydate');
2037 foreach ($messages as $message) {
2038 if ($message->notification) {
2039 $notificationclass = ' notification';
2040 } else {
2041 $notificationclass = null;
2043 $date = usergetdate($message->timecreated);
2044 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2045 $current->mday = $date['mday'];
2046 $current->month = $date['month'];
2047 $current->year = $date['year'];
2049 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2050 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2052 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2055 $formatted_message = $side = null;
2056 if ($message->useridfrom == $user1->id) {
2057 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2058 $side = 'left';
2059 } else {
2060 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2061 $side = 'right';
2063 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
2066 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2067 } else {
2068 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2073 * Format a message for display in the message history
2075 * @param object $message the message object
2076 * @param string $format optional date format
2077 * @param string $keywords keywords to highlight
2078 * @param string $class CSS class to apply to the div around the message
2079 * @return string the formatted message
2081 function message_format_message($message, $format='', $keywords='', $class='other') {
2083 static $dateformat;
2085 //if we haven't previously set the date format or they've supplied a new one
2086 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2087 if ($format) {
2088 $dateformat = $format;
2089 } else {
2090 $dateformat = get_string('strftimedatetimeshort');
2093 $time = userdate($message->timecreated, $dateformat);
2095 $messagetext = message_format_message_text($message, false);
2097 if ($keywords) {
2098 $messagetext = highlight($keywords, $messagetext);
2101 $messagetext .= message_format_contexturl($message);
2103 $messagetext = clean_text($messagetext, FORMAT_HTML);
2105 return <<<TEMPLATE
2106 <div class='message $class'>
2107 <a name="m{$message->id}"></a>
2108 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2109 </div>
2110 TEMPLATE;
2114 * Format a the context url and context url name of a message for display
2116 * @param object $message the message object
2117 * @return string the formatted string
2119 function message_format_contexturl($message) {
2120 $s = null;
2122 if (!empty($message->contexturl)) {
2123 $displaytext = null;
2124 if (!empty($message->contexturlname)) {
2125 $displaytext= $message->contexturlname;
2126 } else {
2127 $displaytext= $message->contexturl;
2129 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2130 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2131 $s .= html_writer::end_tag('div');
2134 return $s;
2138 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2140 * @param object $userfrom the message sender
2141 * @param object $userto the message recipient
2142 * @param string $message the message
2143 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2144 * @return int|false the ID of the new message or false
2146 function message_post_message($userfrom, $userto, $message, $format) {
2147 global $SITE, $CFG, $USER;
2149 $eventdata = new stdClass();
2150 $eventdata->component = 'moodle';
2151 $eventdata->name = 'instantmessage';
2152 $eventdata->userfrom = $userfrom;
2153 $eventdata->userto = $userto;
2155 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2156 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2158 if ($format == FORMAT_HTML) {
2159 $eventdata->fullmessagehtml = $message;
2160 //some message processors may revert to sending plain text even if html is supplied
2161 //so we keep both plain and html versions if we're intending to send html
2162 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2163 } else {
2164 $eventdata->fullmessage = $message;
2165 $eventdata->fullmessagehtml = '';
2168 $eventdata->fullmessageformat = $format;
2169 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2171 $s = new stdClass();
2172 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2173 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2175 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2176 if (!empty($eventdata->fullmessage)) {
2177 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2179 if (!empty($eventdata->fullmessagehtml)) {
2180 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2183 $eventdata->timecreated = time();
2184 $eventdata->notification = 0;
2185 return message_send($eventdata);
2189 * Print a row of contactlist displaying user picture, messages waiting and
2190 * block links etc
2192 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2193 * @param bool $incontactlist is the user a contact of ours?
2194 * @param bool $isblocked is the user blocked?
2195 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2196 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2197 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2198 * @return void
2200 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2201 global $OUTPUT, $USER, $COURSE;
2202 $fullname = fullname($contact);
2203 $fullnamelink = $fullname;
2205 $linkclass = '';
2206 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2207 $linkclass = 'messageselecteduser';
2210 // Are there any unread messages for this contact?
2211 if ($contact->messagecount > 0 ){
2212 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2215 $strcontact = $strblock = $strhistory = null;
2217 if ($showactionlinks) {
2218 // Show block and delete links if user is real user.
2219 if (core_user::is_real_user($contact->id)) {
2220 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2221 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2223 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2226 echo html_writer::start_tag('tr');
2227 echo html_writer::start_tag('td', array('class' => 'pix'));
2228 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2229 echo html_writer::end_tag('td');
2231 echo html_writer::start_tag('td', array('class' => 'contact'));
2233 $popupoptions = array(
2234 'height' => MESSAGE_DISCUSSION_HEIGHT,
2235 'width' => MESSAGE_DISCUSSION_WIDTH,
2236 'menubar' => false,
2237 'location' => false,
2238 'status' => true,
2239 'scrollbars' => true,
2240 'resizable' => true);
2242 $link = $action = null;
2243 if (!empty($selectcontacturl)) {
2244 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2245 } else {
2246 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2247 $link = new moodle_url("/message/index.php?id=$contact->id");
2248 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2250 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2252 echo html_writer::end_tag('td');
2254 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2256 echo html_writer::end_tag('tr');
2260 * Constructs the add/remove contact link to display next to other users
2262 * @param bool $incontactlist is the user a contact
2263 * @param bool $isblocked is the user blocked
2264 * @param stdClass $contact contact object
2265 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2266 * @param bool $text include text next to the icons?
2267 * @param bool $icon include a graphical icon?
2268 * @return string
2270 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2271 $strcontact = '';
2273 if($incontactlist){
2274 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2275 } else if ($isblocked) {
2276 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2277 } else{
2278 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2281 return $strcontact;
2285 * Constructs the block contact link to display next to other users
2287 * @param bool $incontactlist is the user a contact?
2288 * @param bool $isblocked is the user blocked?
2289 * @param stdClass $contact contact object
2290 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2291 * @param bool $text include text next to the icons?
2292 * @param bool $icon include a graphical icon?
2293 * @return string
2295 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2296 $strblock = '';
2298 //commented out to allow the user to block a contact without having to remove them first
2299 /*if ($incontactlist) {
2300 //$strblock = '';
2301 } else*/
2302 if ($isblocked) {
2303 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2304 } else{
2305 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2308 return $strblock;
2312 * Moves messages from a particular user from the message table (unread messages) to message_read
2313 * This is typically only used when a user is deleted
2315 * @param object $userid User id
2316 * @return boolean success
2318 function message_move_userfrom_unread2read($userid) {
2319 global $DB;
2321 // move all unread messages from message table to message_read
2322 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2323 foreach ($messages as $message) {
2324 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2327 return true;
2331 * marks ALL messages being sent from $fromuserid to $touserid as read
2333 * @param int $touserid the id of the message recipient
2334 * @param int $fromuserid the id of the message sender
2335 * @return void
2337 function message_mark_messages_read($touserid, $fromuserid){
2338 global $DB;
2340 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2341 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2343 foreach ($messages as $message) {
2344 message_mark_message_read($message, time());
2347 $messages->close();
2351 * Mark a single message as read
2353 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2354 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2355 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2356 * @return int the ID of the message in the message_read table
2358 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2359 global $DB;
2361 $message->timeread = $timeread;
2363 $messageid = $message->id;
2364 unset($message->id);//unset because it will get a new id on insert into message_read
2366 //If any processors have pending actions abort them
2367 if (!$messageworkingempty) {
2368 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2370 $messagereadid = $DB->insert_record('message_read', $message);
2372 $DB->delete_records('message', array('id' => $messageid));
2374 // Get the context for the user who received the message.
2375 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2376 // If the user no longer exists the context value will be false, in this case use the system context.
2377 if ($context === false) {
2378 $context = context_system::instance();
2381 // Trigger event for reading a message.
2382 $event = \core\event\message_viewed::create(array(
2383 'objectid' => $messagereadid,
2384 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2385 'context' => $context,
2386 'relateduserid' => $message->useridfrom,
2387 'other' => array(
2388 'messageid' => $messageid
2391 $event->trigger();
2393 return $messagereadid;
2397 * A helper function that prints a formatted heading
2399 * @param string $title the heading to display
2400 * @param int $colspan
2401 * @return void
2403 function message_print_heading($title, $colspan=3) {
2404 echo html_writer::start_tag('tr');
2405 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2406 echo html_writer::end_tag('tr');
2410 * Get all message processors, validate corresponding plugin existance and
2411 * system configuration
2413 * @param bool $ready only return ready-to-use processors
2414 * @param bool $reset Reset list of message processors (used in unit tests)
2415 * @return mixed $processors array of objects containing information on message processors
2417 function get_message_processors($ready = false, $reset = false) {
2418 global $DB, $CFG;
2420 static $processors;
2421 if ($reset) {
2422 $processors = array();
2425 if (empty($processors)) {
2426 // Get all processors, ensure the name column is the first so it will be the array key
2427 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2428 foreach ($processors as &$processor){
2429 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2430 if (is_readable($processorfile)) {
2431 include_once($processorfile);
2432 $processclass = 'message_output_' . $processor->name;
2433 if (class_exists($processclass)) {
2434 $pclass = new $processclass();
2435 $processor->object = $pclass;
2436 $processor->configured = 0;
2437 if ($pclass->is_system_configured()) {
2438 $processor->configured = 1;
2440 $processor->hassettings = 0;
2441 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2442 $processor->hassettings = 1;
2444 $processor->available = 1;
2445 } else {
2446 print_error('errorcallingprocessor', 'message');
2448 } else {
2449 $processor->available = 0;
2453 if ($ready) {
2454 // Filter out enabled and system_configured processors
2455 $readyprocessors = $processors;
2456 foreach ($readyprocessors as $readyprocessor) {
2457 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2458 unset($readyprocessors[$readyprocessor->name]);
2461 return $readyprocessors;
2464 return $processors;
2468 * Get all message providers, validate their plugin existance and
2469 * system configuration
2471 * @return mixed $processors array of objects containing information on message processors
2473 function get_message_providers() {
2474 global $CFG, $DB;
2476 $pluginman = core_plugin_manager::instance();
2478 $providers = $DB->get_records('message_providers', null, 'name');
2480 // Remove all the providers whose plugins are disabled or don't exist
2481 foreach ($providers as $providerid => $provider) {
2482 $plugin = $pluginman->get_plugin_info($provider->component);
2483 if ($plugin) {
2484 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2485 unset($providers[$providerid]); // Plugins does not exist
2486 continue;
2488 if ($plugin->is_enabled() === false) {
2489 unset($providers[$providerid]); // Plugin disabled
2490 continue;
2494 return $providers;
2498 * Get an instance of the message_output class for one of the output plugins.
2499 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2500 * @return message_output message_output the requested class.
2502 function get_message_processor($type) {
2503 global $CFG;
2505 // Note, we cannot use the get_message_processors function here, becaues this
2506 // code is called during install after installing each messaging plugin, and
2507 // get_message_processors caches the list of installed plugins.
2509 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2510 if (!is_readable($processorfile)) {
2511 throw new coding_exception('Unknown message processor type ' . $type);
2514 include_once($processorfile);
2516 $processclass = 'message_output_' . $type;
2517 if (!class_exists($processclass)) {
2518 throw new coding_exception('Message processor ' . $type .
2519 ' does not define the right class');
2522 return new $processclass();
2526 * Get messaging outputs default (site) preferences
2528 * @return object $processors object containing information on message processors
2530 function get_message_output_default_preferences() {
2531 return get_config('message');
2535 * Translate message default settings from binary value to the array of string
2536 * representing the settings to be stored. Also validate the provided value and
2537 * use default if it is malformed.
2539 * @param int $plugindefault Default setting suggested by plugin
2540 * @param string $processorname The name of processor
2541 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2543 function translate_message_default_setting($plugindefault, $processorname) {
2544 // Preset translation arrays
2545 $permittedvalues = array(
2546 0x04 => 'disallowed',
2547 0x08 => 'permitted',
2548 0x0c => 'forced',
2551 $loggedinstatusvalues = array(
2552 0x00 => null, // use null if loggedin/loggedoff is not defined
2553 0x01 => 'loggedin',
2554 0x02 => 'loggedoff',
2557 // define the default setting
2558 $processor = get_message_processor($processorname);
2559 $default = $processor->get_default_messaging_settings();
2561 // Validate the value. It should not exceed the maximum size
2562 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2563 debugging(get_string('errortranslatingdefault', 'message'));
2564 $plugindefault = $default;
2566 // Use plugin default setting of 'permitted' is 0
2567 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2568 $plugindefault = $default;
2571 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2572 $loggedin = $loggedoff = null;
2574 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2575 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2576 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2579 return array($permitted, $loggedin, $loggedoff);
2583 * Return a list of page types
2584 * @param string $pagetype current page type
2585 * @param stdClass $parentcontext Block's parent context
2586 * @param stdClass $currentcontext Current context of block
2588 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2589 return array('messages-*'=>get_string('page-message-x', 'message'));
2593 * Is $USER one of the supplied users?
2595 * $user2 will be null if viewing a user's recent conversations
2597 * @param stdClass the first user
2598 * @param stdClass the second user or null
2599 * @return bool True if the current user is one of either $user1 or $user2
2601 function message_current_user_is_involved($user1, $user2) {
2602 global $USER;
2604 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2605 throw new coding_exception('Invalid user object detected. Missing id.');
2608 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2609 return false;
2611 return true;