MDL-39528 behat: Avoid modal window suite failure
[moodle.git] / message / lib.php
blobbd642ce697dfc601e9547972a514337b9b9368a5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions for messaging
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir.'/eventslib.php');
27 define ('MESSAGE_SHORTLENGTH', 300);
29 define ('MESSAGE_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
50 /**
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
69 /**
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 /**
75 * Print the selector that allows the user to view their contacts, course participants, their recent
76 * conversations etc
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86 * @param bool $showactionlinks show action links (add/remove contact etc)
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
88 * @return void
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
91 global $PAGE;
93 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
95 //if 0 unread messages and they've requested unread messages then show contacts
96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97 $viewing = MESSAGE_VIEW_CONTACTS;
100 //if they have no blocked users and they've requested blocked users switch them over to contacts
101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102 $viewing = MESSAGE_VIEW_CONTACTS;
105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
118 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
120 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
121 message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
123 $courseidtoshow = intval(substr($viewing, 7));
125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
130 } else {
131 //shouldn't get here. User trying to access a course they're not in perhaps.
132 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
136 // Only show the search button if we're viewing our own messages.
137 // Search isn't currently able to deal with user A wanting to search user B's messages.
138 if ($showactionlinks) {
139 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
140 echo html_writer::start_tag('fieldset');
141 $managebuttonclass = 'visible';
142 if ($viewing == MESSAGE_VIEW_SEARCH) {
143 $managebuttonclass = 'hiddenelement';
145 $strmanagecontacts = get_string('search','message');
146 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
147 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
148 echo html_writer::end_tag('fieldset');
149 echo html_writer::end_tag('form');
152 echo html_writer::end_tag('div');
156 * Print course participants. Called by message_print_contact_selector()
158 * @param object $context the course context
159 * @param int $courseid the course ID
160 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
161 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
162 * @param string $titletodisplay Optionally specify a title to display above the participants
163 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
164 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
165 * @return void
167 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
168 global $DB, $USER, $PAGE, $OUTPUT;
170 if (empty($titletodisplay)) {
171 $titletodisplay = get_string('participants');
174 $countparticipants = count_enrolled_users($context);
176 list($esql, $params) = get_enrolled_sql($context);
177 $params['mcuserid'] = $USER->id;
178 $ufields = user_picture::fields('u');
180 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
181 FROM {user} u
182 JOIN ($esql) je ON je.id = u.id
183 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
184 WHERE u.deleted = 0";
186 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
188 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
189 echo $OUTPUT->render($pagingbar);
191 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
193 echo html_writer::start_tag('tr');
194 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
195 echo html_writer::end_tag('tr');
197 foreach ($participants as $participant) {
198 if ($participant->id != $USER->id) {
200 $iscontact = false;
201 $isblocked = false;
202 if ( $participant->contactlistid ) {
203 if ($participant->blocked == 0) {
204 // Is contact. Is not blocked.
205 $iscontact = true;
206 $isblocked = false;
207 } else {
208 // Is blocked.
209 $iscontact = false;
210 $isblocked = true;
214 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
215 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
219 echo html_writer::end_tag('table');
223 * Retrieve users blocked by $user1
225 * @param object $user1 the user whose messages are being viewed
226 * @param object $user2 the user $user1 is talking to. If they are being blocked
227 * they will have a variable called 'isblocked' added to their user object
228 * @return array the users blocked by $user1
230 function message_get_blocked_users($user1=null, $user2=null) {
231 global $DB, $USER;
233 if (empty($user1)) {
234 $user1 = $USER;
237 if (!empty($user2)) {
238 $user2->isblocked = false;
241 $blockedusers = array();
243 $userfields = user_picture::fields('u', array('lastaccess'));
244 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
245 FROM {message_contacts} mc
246 JOIN {user} u ON u.id = mc.contactid
247 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
248 WHERE mc.userid = :user1id2 AND mc.blocked = 1
249 GROUP BY $userfields
250 ORDER BY u.firstname ASC";
251 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
253 foreach($rs as $rd) {
254 $blockedusers[] = $rd;
256 if (!empty($user2) && $user2->id == $rd->id) {
257 $user2->isblocked = true;
260 $rs->close();
262 return $blockedusers;
266 * Print users blocked by $user1. Called by message_print_contact_selector()
268 * @param array $blockedusers the users blocked by $user1
269 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
270 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
271 * @param string $titletodisplay Optionally specify a title to display above the participants
272 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
273 * @return void
275 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
276 global $DB, $USER;
278 $countblocked = count($blockedusers);
280 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
282 if (!empty($titletodisplay)) {
283 echo html_writer::start_tag('tr');
284 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
285 echo html_writer::end_tag('tr');
288 if ($countblocked) {
289 echo html_writer::start_tag('tr');
290 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
291 echo html_writer::end_tag('tr');
293 $isuserblocked = true;
294 $isusercontact = false;
295 foreach ($blockedusers as $blockeduser) {
296 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
300 echo html_writer::end_tag('table');
304 * Retrieve $user1's contacts (online, offline and strangers)
306 * @param object $user1 the user whose messages are being viewed
307 * @param object $user2 the user $user1 is talking to. If they are a contact
308 * they will have a variable called 'iscontact' added to their user object
309 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
311 function message_get_contacts($user1=null, $user2=null) {
312 global $DB, $CFG, $USER;
314 if (empty($user1)) {
315 $user1 = $USER;
318 if (!empty($user2)) {
319 $user2->iscontact = false;
322 $timetoshowusers = 300; //Seconds default
323 if (isset($CFG->block_online_users_timetosee)) {
324 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
327 // time which a user is counting as being active since
328 $timefrom = time()-$timetoshowusers;
330 // people in our contactlist who are online
331 $onlinecontacts = array();
332 // people in our contactlist who are offline
333 $offlinecontacts = array();
334 // people who are not in our contactlist but have sent us a message
335 $strangers = array();
337 $userfields = user_picture::fields('u', array('lastaccess'));
339 // get all in our contactlist who are not blocked in our contact list
340 // and count messages we have waiting from each of them
341 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
342 FROM {message_contacts} mc
343 JOIN {user} u ON u.id = mc.contactid
344 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
345 WHERE mc.userid = ? AND mc.blocked = 0
346 GROUP BY $userfields
347 ORDER BY u.firstname ASC";
349 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
350 foreach ($rs as $rd) {
351 if ($rd->lastaccess >= $timefrom) {
352 // they have been active recently, so are counted online
353 $onlinecontacts[] = $rd;
355 } else {
356 $offlinecontacts[] = $rd;
359 if (!empty($user2) && $user2->id == $rd->id) {
360 $user2->iscontact = true;
363 $rs->close();
365 // get messages from anyone who isn't in our contact list and count the number
366 // of messages we have from each of them
367 $strangersql = "SELECT $userfields, count(m.id) as messagecount
368 FROM {message} m
369 JOIN {user} u ON u.id = m.useridfrom
370 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
371 WHERE mc.id IS NULL AND m.useridto = ?
372 GROUP BY $userfields
373 ORDER BY u.firstname ASC";
375 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
376 foreach ($rs as $rd) {
377 $strangers[] = $rd;
379 $rs->close();
381 return array($onlinecontacts, $offlinecontacts, $strangers);
385 * Print $user1's contacts. Called by message_print_contact_selector()
387 * @param array $onlinecontacts $user1's contacts which are online
388 * @param array $offlinecontacts $user1's contacts which are offline
389 * @param array $strangers users which are not contacts but who have messaged $user1
390 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
391 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
392 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
393 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
394 * @param string $titletodisplay Optionally specify a title to display above the participants
395 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
396 * @return void
398 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
399 global $CFG, $PAGE, $OUTPUT;
401 $countonlinecontacts = count($onlinecontacts);
402 $countofflinecontacts = count($offlinecontacts);
403 $countstrangers = count($strangers);
404 $isuserblocked = null;
406 if ($countonlinecontacts + $countofflinecontacts == 0) {
407 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
410 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
412 if (!empty($titletodisplay)) {
413 message_print_heading($titletodisplay);
416 if($countonlinecontacts) {
417 // Print out list of online contacts.
419 if (empty($titletodisplay)) {
420 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
423 $isuserblocked = false;
424 $isusercontact = true;
425 foreach ($onlinecontacts as $contact) {
426 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
427 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
432 if ($countofflinecontacts) {
433 // Print out list of offline contacts.
435 if (empty($titletodisplay)) {
436 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
439 $isuserblocked = false;
440 $isusercontact = true;
441 foreach ($offlinecontacts as $contact) {
442 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
443 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
449 // Print out list of incoming contacts.
450 if ($countstrangers) {
451 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
453 $isuserblocked = false;
454 $isusercontact = false;
455 foreach ($strangers as $stranger) {
456 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
457 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
462 echo html_writer::end_tag('table');
464 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
465 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
470 * Print a select box allowing the user to choose to view new messages, course participants etc.
472 * Called by message_print_contact_selector()
473 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
474 * @param array $courses array of course objects. The courses the user is enrolled in.
475 * @param array $coursecontexts array of course contexts. Keyed on course id.
476 * @param int $countunreadtotal how many unread messages does the user have?
477 * @param int $countblocked how many users has the current user blocked?
478 * @param stdClass $user1 The user whose messages we are viewing.
479 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
480 * @return void
482 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
483 $options = array();
485 if ($countunreadtotal>0) { //if there are unread messages
486 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
489 $str = get_string('contacts', 'message');
490 $options[MESSAGE_VIEW_CONTACTS] = $str;
492 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
493 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
495 if (!empty($courses)) {
496 $courses_options = array();
498 foreach($courses as $course) {
499 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
500 //Not using short_text() as we want the end of the course name. Not the beginning.
501 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
502 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
503 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
504 } else {
505 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
510 if (!empty($courses_options)) {
511 $options[] = array(get_string('courses') => $courses_options);
515 if ($countblocked>0) {
516 $str = get_string('blockedusers','message', $countblocked);
517 $options[MESSAGE_VIEW_BLOCKED] = $str;
520 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
521 echo html_writer::start_tag('fieldset');
522 if ( !empty($user1) && !empty($user1->id) ) {
523 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'user1','value' => $user1->id));
525 echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing');
526 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
527 echo html_writer::end_tag('fieldset');
528 echo html_writer::end_tag('form');
532 * Load the course contexts for all of the users courses
534 * @param array $courses array of course objects. The courses the user is enrolled in.
535 * @return array of course contexts
537 function message_get_course_contexts($courses) {
538 $coursecontexts = array();
540 foreach($courses as $course) {
541 $coursecontexts[$course->id] = context_course::instance($course->id);
544 return $coursecontexts;
548 * strip off action parameters like 'removecontact'
550 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
551 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
553 function message_remove_url_params($moodleurl) {
554 $newurl = new moodle_url($moodleurl);
555 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
556 return $newurl->out();
560 * Count the number of messages with a field having a specified value.
561 * if $field is empty then return count of the whole array
562 * if $field is non-existent then return 0
564 * @param array $messagearray array of message objects
565 * @param string $field the field to inspect on the message objects
566 * @param string $value the value to test the field against
568 function message_count_messages($messagearray, $field='', $value='') {
569 if (!is_array($messagearray)) return 0;
570 if ($field == '' or empty($messagearray)) return count($messagearray);
572 $count = 0;
573 foreach ($messagearray as $message) {
574 $count += ($message->$field == $value) ? 1 : 0;
576 return $count;
580 * Returns the count of unread messages for user. Either from a specific user or from all users.
582 * @param object $user1 the first user. Defaults to $USER
583 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
584 * @return int the count of $user1's unread messages
586 function message_count_unread_messages($user1=null, $user2=null) {
587 global $USER, $DB;
589 if (empty($user1)) {
590 $user1 = $USER;
593 if (!empty($user2)) {
594 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
595 array($user1->id, $user2->id), "COUNT('id')");
596 } else {
597 return $DB->count_records_select('message', "useridto = ?",
598 array($user1->id), "COUNT('id')");
603 * Count the number of users blocked by $user1
605 * @param object $user1 user object
606 * @return int the number of blocked users
608 function message_count_blocked_users($user1=null) {
609 global $USER, $DB;
611 if (empty($user1)) {
612 $user1 = $USER;
615 $sql = "SELECT count(mc.id)
616 FROM {message_contacts} mc
617 WHERE mc.userid = :userid AND mc.blocked = 1";
618 $params = array('userid' => $user1->id);
620 return $DB->count_records_sql($sql, $params);
624 * Print the search form and search results if a search has been performed
626 * @param boolean $advancedsearch show basic or advanced search form
627 * @param object $user1 the current user
628 * @return boolean true if a search was performed
630 function message_print_search($advancedsearch = false, $user1=null) {
631 $frm = data_submitted();
633 $doingsearch = false;
634 if ($frm) {
635 if (confirm_sesskey()) {
636 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
637 } else {
638 $frm = false;
642 if (!empty($frm->combinedsearch)) {
643 $combinedsearchstring = $frm->combinedsearch;
644 } else {
645 //$combinedsearchstring = get_string('searchcombined','message').'...';
646 $combinedsearchstring = '';
649 if ($doingsearch) {
650 if ($advancedsearch) {
652 $messagesearch = '';
653 if (!empty($frm->keywords)) {
654 $messagesearch = $frm->keywords;
656 $personsearch = '';
657 if (!empty($frm->name)) {
658 $personsearch = $frm->name;
660 include('search_advanced.html');
661 } else {
662 include('search.html');
665 $showicontext = false;
666 message_print_search_results($frm, $showicontext, $user1);
668 return true;
669 } else {
671 if ($advancedsearch) {
672 $personsearch = $messagesearch = '';
673 include('search_advanced.html');
674 } else {
675 include('search.html');
677 return false;
682 * Get the users recent conversations meaning all the people they've recently
683 * sent or received a message from plus the most recent message sent to or received from each other user
685 * @param object $user the current user
686 * @param int $limitfrom can be used for paging
687 * @param int $limitto can be used for paging
688 * @return array
690 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
691 global $DB;
693 $userfields = user_picture::fields('u', array('lastaccess'));
694 //This query retrieves the last message received from and sent to each user
695 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
696 //It then joins with some other tables to get some additional data we need
698 //message ID is used instead of timecreated as it should sort the same and will be much faster
700 //There is a separate query for read and unread queries as they are stored in different tables
701 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
702 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
703 FROM {message_read} mr
704 JOIN (
705 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
706 FROM (
707 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
708 FROM {message_read} mr1
709 WHERE mr1.useridfrom = :userid1
710 AND mr1.notification = 0
711 GROUP BY mr1.useridto
712 UNION
713 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
714 FROM {message_read} mr2
715 WHERE mr2.useridto = :userid2
716 AND mr2.notification = 0
717 GROUP BY mr2.useridfrom
718 ) messages
719 GROUP BY messages.userid
720 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
721 JOIN {user} u ON u.id = messages2.userid
722 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
723 WHERE u.deleted = '0'
724 ORDER BY mr.id DESC";
725 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
726 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
728 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
729 FROM {message} m
730 JOIN (
731 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
732 FROM (
733 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
734 FROM {message} m1
735 WHERE m1.useridfrom = :userid1
736 AND m1.notification = 0
737 GROUP BY m1.useridto
738 UNION
739 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
740 FROM {message} m2
741 WHERE m2.useridto = :userid2
742 AND m2.notification = 0
743 GROUP BY m2.useridfrom
744 ) messages
745 GROUP BY messages.userid
746 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
747 JOIN {user} u ON u.id = messages2.userid
748 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
749 WHERE u.deleted = '0'
750 ORDER BY m.id DESC";
751 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
753 $conversations = array();
755 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
756 //$conversation->id (the array key) is the other user's ID
757 $conversation_arrays = array($unread, $read);
758 foreach ($conversation_arrays as $conversation_array) {
759 foreach ($conversation_array as $conversation) {
760 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
761 $conversations[$conversation->id] = $conversation;
766 // Sort the conversations by $conversation->timecreated, newest to oldest
767 // There may be multiple conversations with the same timecreated
768 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
769 $result = collatorlib::asort_objects_by_property($conversations, 'timecreated', collatorlib::SORT_NUMERIC);
770 $conversations = array_reverse($conversations);
772 return $conversations;
776 * Get the users recent event notifications
778 * @param object $user the current user
779 * @param int $limitfrom can be used for paging
780 * @param int $limitto can be used for paging
781 * @return array
783 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
784 global $DB;
786 $userfields = user_picture::fields('u', array('lastaccess'));
787 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
788 FROM {message_read} mr
789 JOIN {user} u ON u.id=mr.useridfrom
790 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
791 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
792 $params = array('userid1' => $user->id, 'notification' => 1);
794 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
795 return $notifications;
799 * Print the user's recent conversations
801 * @param stdClass $user the current user
802 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
804 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
805 global $USER;
807 echo html_writer::start_tag('p', array('class' => 'heading'));
808 echo get_string('mostrecentconversations', 'message');
809 echo html_writer::end_tag('p');
811 if (empty($user1)) {
812 $user1 = $USER;
815 $conversations = message_get_recent_conversations($user1);
817 // Attach context url information to create the "View this conversation" type links
818 foreach($conversations as $conversation) {
819 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
820 $conversation->contexturlname = get_string('thisconversation', 'message');
823 $showotheruser = true;
824 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
828 * Print the user's recent notifications
830 * @param stdClass $user the current user
832 function message_print_recent_notifications($user=null) {
833 global $USER;
835 echo html_writer::start_tag('p', array('class' => 'heading'));
836 echo get_string('mostrecentnotifications', 'message');
837 echo html_writer::end_tag('p');
839 if (empty($user)) {
840 $user = $USER;
843 $notifications = message_get_recent_notifications($user);
845 $showicontext = false;
846 $showotheruser = false;
847 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
851 * Print a list of recent messages
853 * @param array $messages the messages to display
854 * @param object $user the current user
855 * @param bool $showotheruser display information on the other user?
856 * @param bool $showicontext show text next to the action icons?
857 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
858 * @return void
860 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
861 global $OUTPUT;
862 static $dateformat;
864 if (empty($dateformat)) {
865 $dateformat = get_string('strftimedatetimeshort');
868 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
869 foreach ($messages as $message) {
870 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
872 if ($showotheruser) {
873 $strcontact = $strblock = $strhistory = null;
875 if ($showactionlinks) {
876 if ( $message->contactlistid ) {
877 if ($message->blocked == 0) { // The other user isn't blocked.
878 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
879 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
880 } else { // The other user is blocked.
881 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
882 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
884 } else {
885 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
886 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
889 //should we show just the icon or icon and text?
890 $histicontext = 'icon';
891 if ($showicontext) {
892 $histicontext = 'both';
894 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
896 echo html_writer::start_tag('span', array('class' => 'otheruser'));
898 echo html_writer::start_tag('span', array('class' => 'pix'));
899 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
900 echo html_writer::end_tag('span');
902 echo html_writer::start_tag('span', array('class' => 'contact'));
904 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
905 $action = null;
906 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
908 echo html_writer::end_tag('span');//end contact
910 if ($showactionlinks) {
911 echo $strcontact.$strblock.$strhistory;
913 echo html_writer::end_tag('span');//end otheruser
915 $messagetoprint = null;
916 if (!empty($message->smallmessage)) {
917 $messagetoprint = $message->smallmessage;
918 } else {
919 $messagetoprint = $message->fullmessage;
922 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
923 echo html_writer::tag('span', format_text($messagetoprint, $forcetexttohtml?FORMAT_MOODLE:FORMAT_HTML), array('class' => 'themessage'));
924 echo message_format_contexturl($message);
925 echo html_writer::end_tag('div');//end singlemessage
927 echo html_writer::end_tag('div');//end messagerecent
931 * Add the selected user as a contact for the current user
933 * @param int $contactid the ID of the user to add as a contact
934 * @param int $blocked 1 if you wish to block the contact
935 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
936 * Otherwise returns the result of update_record() or insert_record()
938 function message_add_contact($contactid, $blocked=0) {
939 global $USER, $DB;
941 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
942 return false;
945 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
946 // A record already exists. We may be changing blocking status.
948 if ($contact->blocked !== $blocked) {
949 // Blocking status has been changed.
950 $contact->blocked = $blocked;
951 return $DB->update_record('message_contacts', $contact);
952 } else {
953 // No change to blocking status.
954 return true;
957 } else {
958 // New contact record.
959 $contact = new stdClass();
960 $contact->userid = $USER->id;
961 $contact->contactid = $contactid;
962 $contact->blocked = $blocked;
963 return $DB->insert_record('message_contacts', $contact, false);
968 * remove a contact
970 * @param int $contactid the user ID of the contact to remove
971 * @return bool returns the result of delete_records()
973 function message_remove_contact($contactid) {
974 global $USER, $DB;
975 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
979 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
981 * @param int $contactid the user ID of the contact to unblock
982 * @return bool returns the result of delete_records()
984 function message_unblock_contact($contactid) {
985 global $USER, $DB;
986 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
990 * block a user
992 * @param int $contactid the user ID of the user to block
994 function message_block_contact($contactid) {
995 return message_add_contact($contactid, 1);
999 * Load a user's contact record
1001 * @param int $contactid the user ID of the user whose contact record you want
1002 * @return array message contacts
1004 function message_get_contact($contactid) {
1005 global $USER, $DB;
1006 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1010 * Print the results of a message search
1012 * @param mixed $frm submitted form data
1013 * @param bool $showicontext show text next to action icons?
1014 * @param object $currentuser the current user
1015 * @return void
1017 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1018 global $USER, $DB, $OUTPUT;
1020 if (empty($currentuser)) {
1021 $currentuser = $USER;
1024 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1026 $personsearch = false;
1027 $personsearchstring = null;
1028 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1029 $personsearch = true;
1030 $personsearchstring = $frm->name;
1031 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1032 $personsearch = true;
1033 $personsearchstring = $frm->combinedsearch;
1036 // Search for person.
1037 if ($personsearch) {
1038 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1039 $users = array();
1040 $mycourses = enrol_get_my_courses('id');
1041 $mycoursesids = array();
1042 foreach ($mycourses as $mycourse) {
1043 $mycoursesids[] = $mycourse->id;
1045 $susers = message_search_users($mycoursesids, $personsearchstring);
1046 foreach ($susers as $suser) {
1047 $users[$suser->id] = $suser;
1049 } else {
1050 $users = message_search_users(SITEID, $personsearchstring);
1053 if (!empty($users)) {
1054 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1055 echo get_string('userssearchresults', 'message', count($users));
1056 echo html_writer::end_tag('p');
1058 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1059 foreach ($users as $user) {
1061 if ( $user->contactlistid ) {
1062 if ($user->blocked == 0) { // User is not blocked.
1063 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1064 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1065 } else { // blocked
1066 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1067 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1069 } else {
1070 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1071 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1074 // Should we show just the icon or icon and text?
1075 $histicontext = 'icon';
1076 if ($showicontext) {
1077 $histicontext = 'both';
1079 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1081 echo html_writer::start_tag('tr');
1083 echo html_writer::start_tag('td', array('class' => 'pix'));
1084 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1085 echo html_writer::end_tag('td');
1087 echo html_writer::start_tag('td',array('class' => 'contact'));
1088 $action = null;
1089 $link = new moodle_url("/message/index.php?id=$user->id");
1090 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1091 echo html_writer::end_tag('td');
1093 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1094 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1095 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1097 echo html_writer::end_tag('tr');
1099 echo html_writer::end_tag('table');
1101 } else {
1102 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1103 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1104 echo html_writer::end_tag('p');
1108 // search messages for keywords
1109 $messagesearch = false;
1110 $messagesearchstring = null;
1111 if (!empty($frm->keywords)) {
1112 $messagesearch = true;
1113 $messagesearchstring = clean_text(trim($frm->keywords));
1114 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1115 $messagesearch = true;
1116 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1119 if ($messagesearch) {
1120 if ($messagesearchstring) {
1121 $keywords = explode(' ', $messagesearchstring);
1122 } else {
1123 $keywords = array();
1125 $tome = false;
1126 $fromme = false;
1127 $courseid = 'none';
1129 if (empty($frm->keywordsoption)) {
1130 $frm->keywordsoption = 'allmine';
1133 switch ($frm->keywordsoption) {
1134 case 'tome':
1135 $tome = true;
1136 break;
1137 case 'fromme':
1138 $fromme = true;
1139 break;
1140 case 'allmine':
1141 $tome = true;
1142 $fromme = true;
1143 break;
1144 case 'allusers':
1145 $courseid = SITEID;
1146 break;
1147 case 'courseusers':
1148 $courseid = $frm->courseid;
1149 break;
1150 default:
1151 $tome = true;
1152 $fromme = true;
1155 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1157 // Get a list of contacts.
1158 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1159 $contacts = array();
1162 // Print heading with number of results.
1163 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1164 $countresults = count($messages);
1165 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1166 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1167 } else {
1168 echo get_string('keywordssearchresults', 'message', $countresults);
1170 echo html_writer::end_tag('p');
1172 // Print table headings.
1173 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1175 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1176 $headertdend = html_writer::end_tag('td');
1177 echo html_writer::start_tag('tr');
1178 echo $headertdstart.get_string('from').$headertdend;
1179 echo $headertdstart.get_string('to').$headertdend;
1180 echo $headertdstart.get_string('message', 'message').$headertdend;
1181 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1182 echo html_writer::end_tag('tr');
1184 $blockedcount = 0;
1185 $dateformat = get_string('strftimedatetimeshort');
1186 $strcontext = get_string('context', 'message');
1187 foreach ($messages as $message) {
1189 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1190 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1191 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1192 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1195 $blockedcount ++;
1196 continue;
1199 // Load user-to record.
1200 if ($message->useridto !== $USER->id) {
1201 $userto = $DB->get_record('user', array('id' => $message->useridto));
1202 $tocontact = (array_key_exists($message->useridto, $contacts) and
1203 ($contacts[$message->useridto]->blocked == 0) );
1204 $toblocked = (array_key_exists($message->useridto, $contacts) and
1205 ($contacts[$message->useridto]->blocked == 1) );
1206 } else {
1207 $userto = false;
1208 $tocontact = false;
1209 $toblocked = false;
1212 // Load user-from record.
1213 if ($message->useridfrom !== $USER->id) {
1214 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1215 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1216 ($contacts[$message->useridfrom]->blocked == 0) );
1217 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1218 ($contacts[$message->useridfrom]->blocked == 1) );
1219 } else {
1220 $userfrom = false;
1221 $fromcontact = false;
1222 $fromblocked = false;
1225 // Find date string for this message.
1226 $date = usergetdate($message->timecreated);
1227 $datestring = $date['year'].$date['mon'].$date['mday'];
1229 // Print out message row.
1230 echo html_writer::start_tag('tr', array('valign' => 'top'));
1232 echo html_writer::start_tag('td', array('class' => 'contact'));
1233 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1234 echo html_writer::end_tag('td');
1236 echo html_writer::start_tag('td', array('class' => 'contact'));
1237 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1238 echo html_writer::end_tag('td');
1240 echo html_writer::start_tag('td', array('class' => 'summary'));
1241 echo message_get_fragment($message->smallmessage, $keywords);
1242 echo html_writer::start_tag('div', array('class' => 'link'));
1244 // If the user clicks the context link display message sender on the left.
1245 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1246 $leftsideuserid = $rightsideuserid = null;
1247 if ($currentuser->id == $message->useridto) {
1248 $leftsideuserid = $message->useridto;
1249 $rightsideuserid = $message->useridfrom;
1250 } else {
1251 $leftsideuserid = $message->useridfrom;
1252 $rightsideuserid = $message->useridto;
1254 message_history_link($leftsideuserid, $rightsideuserid, false,
1255 $messagesearchstring, 'm'.$message->id, $strcontext);
1256 echo html_writer::end_tag('div');
1257 echo html_writer::end_tag('td');
1259 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1261 echo html_writer::end_tag('tr');
1265 if ($blockedcount > 0) {
1266 echo html_writer::start_tag('tr');
1267 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1268 echo html_writer::end_tag('tr');
1270 echo html_writer::end_tag('table');
1272 } else {
1273 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1277 if (!$personsearch && !$messagesearch) {
1278 //they didn't enter any search terms
1279 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1282 echo html_writer::end_tag('div');
1286 * Print information on a user. Used when printing search results.
1288 * @param object/bool $user the user to display or false if you just want $USER
1289 * @param bool $iscontact is the user being displayed a contact?
1290 * @param bool $isblocked is the user being displayed blocked?
1291 * @param bool $includeicontext include text next to the action icons?
1292 * @return void
1294 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1295 global $USER, $OUTPUT;
1297 if ($user === false) {
1298 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1299 } else {
1300 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1302 $link = new moodle_url("/message/index.php?id=$user->id");
1303 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1304 get_string('sendmessageto', 'message', fullname($user))));
1306 $return = false;
1307 $script = null;
1308 if ($iscontact) {
1309 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1310 } else {
1311 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1314 if ($isblocked) {
1315 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1316 } else {
1317 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1323 * Print a message contact link
1325 * @param int $userid the ID of the user to apply to action to
1326 * @param string $linktype can be add, remove, block or unblock
1327 * @param bool $return if true return the link as a string. If false echo the link.
1328 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1329 * @param bool $text include text next to the icons?
1330 * @param bool $icon include a graphical icon?
1331 * @return string if $return is true otherwise bool
1333 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1334 global $OUTPUT, $PAGE;
1336 //hold onto the strings as we're probably creating a bunch of links
1337 static $str;
1339 if (empty($script)) {
1340 //strip off previous action params like 'removecontact'
1341 $script = message_remove_url_params($PAGE->url);
1344 if (empty($str->blockcontact)) {
1345 $str = new stdClass();
1346 $str->blockcontact = get_string('blockcontact', 'message');
1347 $str->unblockcontact = get_string('unblockcontact', 'message');
1348 $str->removecontact = get_string('removecontact', 'message');
1349 $str->addcontact = get_string('addcontact', 'message');
1352 $command = $linktype.'contact';
1353 $string = $str->{$command};
1355 $safealttext = s($string);
1357 $safestring = '';
1358 if (!empty($text)) {
1359 $safestring = $safealttext;
1362 $img = '';
1363 if ($icon) {
1364 $iconpath = null;
1365 switch ($linktype) {
1366 case 'block':
1367 $iconpath = 't/block';
1368 break;
1369 case 'unblock':
1370 $iconpath = 't/unblock';
1371 break;
1372 case 'remove':
1373 $iconpath = 't/removecontact';
1374 break;
1375 case 'add':
1376 default:
1377 $iconpath = 't/addcontact';
1380 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1383 $output = '<span class="'.$linktype.'contact">'.
1384 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1385 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1386 $img.
1387 $safestring.'</a></span>';
1389 if ($return) {
1390 return $output;
1391 } else {
1392 echo $output;
1393 return true;
1398 * echo or return a link to take the user to the full message history between themselves and another user
1400 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1401 * @param int $userid2 the ID of the other user
1402 * @param bool $return true to return the link as a string. False to echo the link.
1403 * @param string $keywords any keywords to highlight in the message history
1404 * @param string $position anchor name to jump to within the message history
1405 * @param string $linktext optionally specify the link text
1406 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1408 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1409 global $OUTPUT;
1410 static $strmessagehistory;
1412 if (empty($strmessagehistory)) {
1413 $strmessagehistory = get_string('messagehistory', 'message');
1416 if ($position) {
1417 $position = "#$position";
1419 if ($keywords) {
1420 $keywords = "&search=".urlencode($keywords);
1423 if ($linktext == 'icon') { // Icon only
1424 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1425 } else if ($linktext == 'both') { // Icon and standard name
1426 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1427 $fulllink .= '&nbsp;'.$strmessagehistory;
1428 } else if ($linktext) { // Custom name
1429 $fulllink = $linktext;
1430 } else { // Standard name only
1431 $fulllink = $strmessagehistory;
1434 $popupoptions = array(
1435 'height' => 500,
1436 'width' => 500,
1437 'menubar' => false,
1438 'location' => false,
1439 'status' => true,
1440 'scrollbars' => true,
1441 'resizable' => true);
1443 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1444 $action = null;
1445 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1447 $str = '<span class="history">'.$str.'</span>';
1449 if ($return) {
1450 return $str;
1451 } else {
1452 echo $str;
1453 return true;
1459 * Search through course users.
1461 * If $courseids contains the site course then this function searches
1462 * through all undeleted and confirmed users.
1464 * @param int|array $courseids Course ID or array of course IDs.
1465 * @param string $searchtext the text to search for.
1466 * @param string $sort the column name to order by.
1467 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1468 * @return array An array of {@link $USER} records.
1470 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1471 global $CFG, $USER, $DB;
1473 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1474 if (!$courseids) {
1475 $courseids = array(SITEID);
1478 // Allow an integer to be passed.
1479 if (!is_array($courseids)) {
1480 $courseids = array($courseids);
1483 $fullname = $DB->sql_fullname();
1484 $ufields = user_picture::fields('u');
1486 if (!empty($sort)) {
1487 $order = ' ORDER BY '. $sort;
1488 } else {
1489 $order = '';
1492 $params = array(
1493 'userid' => $USER->id,
1494 'query' => "%$searchtext%"
1497 if (empty($exceptions)) {
1498 $exceptions = array();
1499 } else if (!empty($exceptions) && is_string($exceptions)) {
1500 $exceptions = explode(',', $exceptions);
1503 // Ignore self and guest account.
1504 $exceptions[] = $USER->id;
1505 $exceptions[] = $CFG->siteguest;
1507 // Exclude exceptions from the search result.
1508 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1509 $except = ' AND u.id ' . $except;
1510 $params = array_merge($params_except, $params);
1512 if (in_array(SITEID, $courseids)) {
1513 // Search on site level.
1514 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1515 FROM {user} u
1516 LEFT JOIN {message_contacts} mc
1517 ON mc.contactid = u.id AND mc.userid = :userid
1518 WHERE u.deleted = '0' AND u.confirmed = '1'
1519 AND (".$DB->sql_like($fullname, ':query', false).")
1520 $except
1521 $order", $params);
1522 } else {
1523 // Search in courses.
1525 // Getting the context IDs or each course.
1526 $contextids = array();
1527 foreach ($courseids as $courseid) {
1528 $context = context_course::instance($courseid);
1529 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1531 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1532 $params = array_merge($params, $contextparams);
1534 // Everyone who has a role assignment in this course or higher.
1535 // TODO: add enabled enrolment join here (skodak)
1536 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1537 FROM {user} u
1538 JOIN {role_assignments} ra ON ra.userid = u.id
1539 LEFT JOIN {message_contacts} mc
1540 ON mc.contactid = u.id AND mc.userid = :userid
1541 WHERE u.deleted = '0' AND u.confirmed = '1'
1542 AND (".$DB->sql_like($fullname, ':query', false).")
1543 AND ra.contextid $contextwhere
1544 $except
1545 $order", $params);
1547 return $users;
1552 * Search a user's messages
1554 * Returns a list of posts found using an array of search terms
1555 * eg word +word -word
1557 * @param array $searchterms an array of search terms (strings)
1558 * @param bool $fromme include messages from the user?
1559 * @param bool $tome include messages to the user?
1560 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1561 * @param int $userid the user ID of the current user
1562 * @return mixed An array of messages or false if no matching messages were found
1564 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1565 global $CFG, $USER, $DB;
1567 // If user is searching all messages check they are allowed to before doing anything else.
1568 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1569 print_error('accessdenied','admin');
1572 // If no userid sent then assume current user.
1573 if ($userid == 0) $userid = $USER->id;
1575 // Some differences in SQL syntax.
1576 if ($DB->sql_regex_supported()) {
1577 $REGEXP = $DB->sql_regex(true);
1578 $NOTREGEXP = $DB->sql_regex(false);
1581 $searchcond = array();
1582 $params = array();
1583 $i = 0;
1585 // Preprocess search terms to check whether we have at least 1 eligible search term.
1586 // If we do we can drop words around it like 'a'.
1587 $dropshortwords = false;
1588 foreach ($searchterms as $searchterm) {
1589 if (strlen($searchterm) >= 2) {
1590 $dropshortwords = true;
1594 foreach ($searchterms as $searchterm) {
1595 $i++;
1597 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1599 if ($dropshortwords && strlen($searchterm) < 2) {
1600 continue;
1602 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1603 if (!$DB->sql_regex_supported()) {
1604 if (substr($searchterm, 0, 1) == '-') {
1605 $NOT = true;
1607 $searchterm = trim($searchterm, '+-');
1610 if (substr($searchterm,0,1) == "+") {
1611 $searchterm = substr($searchterm,1);
1612 $searchterm = preg_quote($searchterm, '|');
1613 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1614 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1616 } else if (substr($searchterm,0,1) == "-") {
1617 $searchterm = substr($searchterm,1);
1618 $searchterm = preg_quote($searchterm, '|');
1619 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1620 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1622 } else {
1623 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1624 $params['ss'.$i] = "%$searchterm%";
1628 if (empty($searchcond)) {
1629 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1630 $params['ss1'] = "%";
1631 } else {
1632 $searchcond = implode(" AND ", $searchcond);
1635 // There are several possibilities
1636 // 1. courseid = SITEID : The admin is searching messages by all users
1637 // 2. courseid = ?? : A teacher is searching messages by users in
1638 // one of their courses - currently disabled
1639 // 3. courseid = none : User is searching their own messages;
1640 // a. Messages from user
1641 // b. Messages to user
1642 // c. Messages to and from user
1644 if ($courseid == SITEID) { // Admin is searching all messages.
1645 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1646 FROM {message_read} m
1647 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1648 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1649 FROM {message} m
1650 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1652 } else if ($courseid !== 'none') {
1653 // This has not been implemented due to security concerns.
1654 $m_read = array();
1655 $m_unread = array();
1657 } else {
1659 if ($fromme and $tome) {
1660 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1661 $params['userid1'] = $userid;
1662 $params['userid2'] = $userid;
1664 } else if ($fromme) {
1665 $searchcond .= " AND m.useridfrom=:userid";
1666 $params['userid'] = $userid;
1668 } else if ($tome) {
1669 $searchcond .= " AND m.useridto=:userid";
1670 $params['userid'] = $userid;
1673 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1674 FROM {message_read} m
1675 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1676 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1677 FROM {message} m
1678 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1682 /// The keys may be duplicated in $m_read and $m_unread so we can't
1683 /// do a simple concatenation
1684 $messages = array();
1685 foreach ($m_read as $m) {
1686 $messages[] = $m;
1688 foreach ($m_unread as $m) {
1689 $messages[] = $m;
1692 return (empty($messages)) ? false : $messages;
1696 * Given a message object that we already know has a long message
1697 * this function truncates the message nicely to the first
1698 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1700 * @param string $message the message
1701 * @param int $minlength the minimum length to trim the message to
1702 * @return string the shortened message
1704 function message_shorten_message($message, $minlength = 0) {
1705 $i = 0;
1706 $tag = false;
1707 $length = strlen($message);
1708 $count = 0;
1709 $stopzone = false;
1710 $truncate = 0;
1711 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1714 for ($i=0; $i<$length; $i++) {
1715 $char = $message[$i];
1717 switch ($char) {
1718 case "<":
1719 $tag = true;
1720 break;
1721 case ">":
1722 $tag = false;
1723 break;
1724 default:
1725 if (!$tag) {
1726 if ($stopzone) {
1727 if ($char == '.' or $char == ' ') {
1728 $truncate = $i+1;
1729 break 2;
1732 $count++;
1734 break;
1736 if (!$stopzone) {
1737 if ($count > $minlength) {
1738 $stopzone = true;
1743 if (!$truncate) {
1744 $truncate = $i;
1747 return substr($message, 0, $truncate);
1752 * Given a string and an array of keywords, this function looks
1753 * for the first keyword in the string, and then chops out a
1754 * small section from the text that shows that word in context.
1756 * @param string $message the text to search
1757 * @param array $keywords array of keywords to find
1759 function message_get_fragment($message, $keywords) {
1761 $fullsize = 160;
1762 $halfsize = (int)($fullsize/2);
1764 $message = strip_tags($message);
1766 foreach ($keywords as $keyword) { // Just get the first one
1767 if ($keyword !== '') {
1768 break;
1771 if (empty($keyword)) { // None found, so just return start of message
1772 return message_shorten_message($message, 30);
1775 $leadin = $leadout = '';
1777 /// Find the start of the fragment
1778 $start = 0;
1779 $length = strlen($message);
1781 $pos = strpos($message, $keyword);
1782 if ($pos > $halfsize) {
1783 $start = $pos - $halfsize;
1784 $leadin = '...';
1786 /// Find the end of the fragment
1787 $end = $start + $fullsize;
1788 if ($end > $length) {
1789 $end = $length;
1790 } else {
1791 $leadout = '...';
1794 /// Pull out the fragment and format it
1796 $fragment = substr($message, $start, $end - $start);
1797 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1798 return $fragment;
1802 * Retrieve the messages between two users
1804 * @param object $user1 the current user
1805 * @param object $user2 the other user
1806 * @param int $limitnum the maximum number of messages to retrieve
1807 * @param bool $viewingnewmessages are we currently viewing new messages?
1809 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1810 global $DB, $CFG;
1812 $messages = array();
1814 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1815 //desc to get the last $limitnum messages then flip the order in php
1816 $sort = 'asc';
1817 if ($limitnum>0) {
1818 $sort = 'desc';
1821 $notificationswhere = null;
1822 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1823 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1824 $notificationswhere = 'AND notification=0';
1827 //prevent notifications of your own actions appearing in your own message history
1828 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1830 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1831 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1832 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1833 "timecreated $sort", '*', 0, $limitnum)) {
1834 foreach ($messages_read as $message) {
1835 $messages[] = $message;
1838 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1839 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1840 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1841 "timecreated $sort", '*', 0, $limitnum)) {
1842 foreach ($messages_new as $message) {
1843 $messages[] = $message;
1847 $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);
1849 //if we only want the last $limitnum messages
1850 $messagecount = count($messages);
1851 if ($limitnum > 0 && $messagecount > $limitnum) {
1852 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1855 return $messages;
1859 * Print the message history between two users
1861 * @param object $user1 the current user
1862 * @param object $user2 the other user
1863 * @param string $search search terms to highlight
1864 * @param int $messagelimit maximum number of messages to return
1865 * @param string $messagehistorylink the html for the message history link or false
1866 * @param bool $viewingnewmessages are we currently viewing new messages?
1868 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
1869 global $CFG, $OUTPUT;
1871 echo $OUTPUT->box_start('center');
1872 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1873 echo html_writer::start_tag('tr');
1875 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1876 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1877 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1878 echo html_writer::end_tag('td');
1880 echo html_writer::start_tag('td', array('align' => 'center'));
1881 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => ''));
1882 echo html_writer::end_tag('td');
1884 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1885 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1886 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1888 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
1890 $script = null;
1891 $text = true;
1892 $icon = false;
1894 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1895 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
1896 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1898 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1901 echo html_writer::end_tag('td');
1902 echo html_writer::end_tag('tr');
1903 echo html_writer::end_tag('table');
1904 echo $OUTPUT->box_end();
1906 if (!empty($messagehistorylink)) {
1907 echo $messagehistorylink;
1910 /// Get all the messages and print them
1911 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1912 $tablecontents = '';
1914 $current = new stdClass();
1915 $current->mday = '';
1916 $current->month = '';
1917 $current->year = '';
1918 $messagedate = get_string('strftimetime');
1919 $blockdate = get_string('strftimedaydate');
1920 foreach ($messages as $message) {
1921 if ($message->notification) {
1922 $notificationclass = ' notification';
1923 } else {
1924 $notificationclass = null;
1926 $date = usergetdate($message->timecreated);
1927 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1928 $current->mday = $date['mday'];
1929 $current->month = $date['month'];
1930 $current->year = $date['year'];
1932 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1933 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1935 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1938 $formatted_message = $side = null;
1939 if ($message->useridfrom == $user1->id) {
1940 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1941 $side = 'left';
1942 } else {
1943 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1944 $side = 'right';
1946 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1949 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1950 } else {
1951 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1956 * Format a message for display in the message history
1958 * @param object $message the message object
1959 * @param string $format optional date format
1960 * @param string $keywords keywords to highlight
1961 * @param string $class CSS class to apply to the div around the message
1962 * @return string the formatted message
1964 function message_format_message($message, $format='', $keywords='', $class='other') {
1966 static $dateformat;
1968 //if we haven't previously set the date format or they've supplied a new one
1969 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1970 if ($format) {
1971 $dateformat = $format;
1972 } else {
1973 $dateformat = get_string('strftimedatetimeshort');
1976 $time = userdate($message->timecreated, $dateformat);
1977 $options = new stdClass();
1978 $options->para = false;
1980 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1981 if (!empty($message->smallmessage)) {
1982 $messagetext = $message->smallmessage;
1983 } else {
1984 $messagetext = $message->fullmessage;
1986 if ($message->fullmessageformat == FORMAT_HTML) {
1987 //dont escape html tags by calling s() if html format or they will display in the UI
1988 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1989 } else {
1990 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1993 $messagetext .= message_format_contexturl($message);
1995 if ($keywords) {
1996 $messagetext = highlight($keywords, $messagetext);
1999 return <<<TEMPLATE
2000 <div class='message $class'>
2001 <a name="m'.{$message->id}.'"></a>
2002 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2003 </div>
2004 TEMPLATE;
2008 * Format a the context url and context url name of a message for display
2010 * @param object $message the message object
2011 * @return string the formatted string
2013 function message_format_contexturl($message) {
2014 $s = null;
2016 if (!empty($message->contexturl)) {
2017 $displaytext = null;
2018 if (!empty($message->contexturlname)) {
2019 $displaytext= $message->contexturlname;
2020 } else {
2021 $displaytext= $message->contexturl;
2023 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2024 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2025 $s .= html_writer::end_tag('div');
2028 return $s;
2032 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2034 * @param object $userfrom the message sender
2035 * @param object $userto the message recipient
2036 * @param string $message the message
2037 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2038 * @return int|false the ID of the new message or false
2040 function message_post_message($userfrom, $userto, $message, $format) {
2041 global $SITE, $CFG, $USER;
2043 $eventdata = new stdClass();
2044 $eventdata->component = 'moodle';
2045 $eventdata->name = 'instantmessage';
2046 $eventdata->userfrom = $userfrom;
2047 $eventdata->userto = $userto;
2049 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2050 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2052 if ($format == FORMAT_HTML) {
2053 $eventdata->fullmessagehtml = $message;
2054 //some message processors may revert to sending plain text even if html is supplied
2055 //so we keep both plain and html versions if we're intending to send html
2056 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2057 } else {
2058 $eventdata->fullmessage = $message;
2059 $eventdata->fullmessagehtml = '';
2062 $eventdata->fullmessageformat = $format;
2063 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2065 $s = new stdClass();
2066 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2067 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2069 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2070 if (!empty($eventdata->fullmessage)) {
2071 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2073 if (!empty($eventdata->fullmessagehtml)) {
2074 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2077 $eventdata->timecreated = time();
2078 return message_send($eventdata);
2082 * Print a row of contactlist displaying user picture, messages waiting and
2083 * block links etc
2085 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2086 * @param bool $incontactlist is the user a contact of ours?
2087 * @param bool $isblocked is the user blocked?
2088 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2089 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2090 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2091 * @return void
2093 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2094 global $OUTPUT, $USER;
2095 $fullname = fullname($contact);
2096 $fullnamelink = $fullname;
2098 $linkclass = '';
2099 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2100 $linkclass = 'messageselecteduser';
2103 // Are there any unread messages for this contact?
2104 if ($contact->messagecount > 0 ){
2105 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2108 $strcontact = $strblock = $strhistory = null;
2110 if ($showactionlinks) {
2111 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2112 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2113 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2116 echo html_writer::start_tag('tr');
2117 echo html_writer::start_tag('td', array('class' => 'pix'));
2118 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2119 echo html_writer::end_tag('td');
2121 echo html_writer::start_tag('td', array('class' => 'contact'));
2123 $popupoptions = array(
2124 'height' => MESSAGE_DISCUSSION_HEIGHT,
2125 'width' => MESSAGE_DISCUSSION_WIDTH,
2126 'menubar' => false,
2127 'location' => false,
2128 'status' => true,
2129 'scrollbars' => true,
2130 'resizable' => true);
2132 $link = $action = null;
2133 if (!empty($selectcontacturl)) {
2134 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2135 } else {
2136 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2137 $link = new moodle_url("/message/index.php?id=$contact->id");
2138 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2140 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2142 echo html_writer::end_tag('td');
2144 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2146 echo html_writer::end_tag('tr');
2150 * Constructs the add/remove contact link to display next to other users
2152 * @param bool $incontactlist is the user a contact
2153 * @param bool $isblocked is the user blocked
2154 * @param stdClass $contact contact object
2155 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2156 * @param bool $text include text next to the icons?
2157 * @param bool $icon include a graphical icon?
2158 * @return string
2160 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2161 $strcontact = '';
2163 if($incontactlist){
2164 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2165 } else if ($isblocked) {
2166 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2167 } else{
2168 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2171 return $strcontact;
2175 * Constructs the block contact link to display next to other users
2177 * @param bool $incontactlist is the user a contact?
2178 * @param bool $isblocked is the user blocked?
2179 * @param stdClass $contact contact object
2180 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2181 * @param bool $text include text next to the icons?
2182 * @param bool $icon include a graphical icon?
2183 * @return string
2185 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2186 $strblock = '';
2188 //commented out to allow the user to block a contact without having to remove them first
2189 /*if ($incontactlist) {
2190 //$strblock = '';
2191 } else*/
2192 if ($isblocked) {
2193 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2194 } else{
2195 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2198 return $strblock;
2202 * Moves messages from a particular user from the message table (unread messages) to message_read
2203 * This is typically only used when a user is deleted
2205 * @param object $userid User id
2206 * @return boolean success
2208 function message_move_userfrom_unread2read($userid) {
2209 global $DB;
2211 // move all unread messages from message table to message_read
2212 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2213 foreach ($messages as $message) {
2214 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2217 return true;
2221 * marks ALL messages being sent from $fromuserid to $touserid as read
2223 * @param int $touserid the id of the message recipient
2224 * @param int $fromuserid the id of the message sender
2225 * @return void
2227 function message_mark_messages_read($touserid, $fromuserid){
2228 global $DB;
2230 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2231 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2233 foreach ($messages as $message) {
2234 message_mark_message_read($message, time());
2237 $messages->close();
2241 * Mark a single message as read
2243 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2244 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2245 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2246 * @return int the ID of the message in the message_read table
2248 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2249 global $DB;
2251 $message->timeread = $timeread;
2253 $messageid = $message->id;
2254 unset($message->id);//unset because it will get a new id on insert into message_read
2256 //If any processors have pending actions abort them
2257 if (!$messageworkingempty) {
2258 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2260 $messagereadid = $DB->insert_record('message_read', $message);
2261 $DB->delete_records('message', array('id' => $messageid));
2262 return $messagereadid;
2266 * A helper function that prints a formatted heading
2268 * @param string $title the heading to display
2269 * @param int $colspan
2270 * @return void
2272 function message_print_heading($title, $colspan=3) {
2273 echo html_writer::start_tag('tr');
2274 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2275 echo html_writer::end_tag('tr');
2279 * Get all message processors, validate corresponding plugin existance and
2280 * system configuration
2282 * @param bool $ready only return ready-to-use processors
2283 * @return mixed $processors array of objects containing information on message processors
2285 function get_message_processors($ready = false) {
2286 global $DB, $CFG;
2288 static $processors;
2290 if (empty($processors)) {
2291 // Get all processors, ensure the name column is the first so it will be the array key
2292 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2293 foreach ($processors as &$processor){
2294 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2295 if (is_readable($processorfile)) {
2296 include_once($processorfile);
2297 $processclass = 'message_output_' . $processor->name;
2298 if (class_exists($processclass)) {
2299 $pclass = new $processclass();
2300 $processor->object = $pclass;
2301 $processor->configured = 0;
2302 if ($pclass->is_system_configured()) {
2303 $processor->configured = 1;
2305 $processor->hassettings = 0;
2306 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2307 $processor->hassettings = 1;
2309 $processor->available = 1;
2310 } else {
2311 print_error('errorcallingprocessor', 'message');
2313 } else {
2314 $processor->available = 0;
2318 if ($ready) {
2319 // Filter out enabled and system_configured processors
2320 $readyprocessors = $processors;
2321 foreach ($readyprocessors as $readyprocessor) {
2322 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2323 unset($readyprocessors[$readyprocessor->name]);
2326 return $readyprocessors;
2329 return $processors;
2333 * Get all message providers, validate their plugin existance and
2334 * system configuration
2336 * @return mixed $processors array of objects containing information on message processors
2338 function get_message_providers() {
2339 global $CFG, $DB;
2340 require_once($CFG->libdir . '/pluginlib.php');
2341 $pluginman = plugin_manager::instance();
2343 $providers = $DB->get_records('message_providers', null, 'name');
2345 // Remove all the providers whose plugins are disabled or don't exist
2346 foreach ($providers as $providerid => $provider) {
2347 $plugin = $pluginman->get_plugin_info($provider->component);
2348 if ($plugin) {
2349 if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2350 unset($providers[$providerid]); // Plugins does not exist
2351 continue;
2353 if ($plugin->is_enabled() === false) {
2354 unset($providers[$providerid]); // Plugin disabled
2355 continue;
2359 return $providers;
2363 * Get an instance of the message_output class for one of the output plugins.
2364 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2365 * @return message_output message_output the requested class.
2367 function get_message_processor($type) {
2368 global $CFG;
2370 // Note, we cannot use the get_message_processors function here, becaues this
2371 // code is called during install after installing each messaging plugin, and
2372 // get_message_processors caches the list of installed plugins.
2374 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2375 if (!is_readable($processorfile)) {
2376 throw new coding_exception('Unknown message processor type ' . $type);
2379 include_once($processorfile);
2381 $processclass = 'message_output_' . $type;
2382 if (!class_exists($processclass)) {
2383 throw new coding_exception('Message processor ' . $type .
2384 ' does not define the right class');
2387 return new $processclass();
2391 * Get messaging outputs default (site) preferences
2393 * @return object $processors object containing information on message processors
2395 function get_message_output_default_preferences() {
2396 return get_config('message');
2400 * Translate message default settings from binary value to the array of string
2401 * representing the settings to be stored. Also validate the provided value and
2402 * use default if it is malformed.
2404 * @param int $plugindefault Default setting suggested by plugin
2405 * @param string $processorname The name of processor
2406 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2408 function translate_message_default_setting($plugindefault, $processorname) {
2409 // Preset translation arrays
2410 $permittedvalues = array(
2411 0x04 => 'disallowed',
2412 0x08 => 'permitted',
2413 0x0c => 'forced',
2416 $loggedinstatusvalues = array(
2417 0x00 => null, // use null if loggedin/loggedoff is not defined
2418 0x01 => 'loggedin',
2419 0x02 => 'loggedoff',
2422 // define the default setting
2423 $processor = get_message_processor($processorname);
2424 $default = $processor->get_default_messaging_settings();
2426 // Validate the value. It should not exceed the maximum size
2427 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2428 debugging(get_string('errortranslatingdefault', 'message'));
2429 $plugindefault = $default;
2431 // Use plugin default setting of 'permitted' is 0
2432 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2433 $plugindefault = $default;
2436 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2437 $loggedin = $loggedoff = null;
2439 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2440 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2441 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2444 return array($permitted, $loggedin, $loggedoff);
2448 * Return a list of page types
2449 * @param string $pagetype current page type
2450 * @param stdClass $parentcontext Block's parent context
2451 * @param stdClass $currentcontext Current context of block
2453 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2454 return array('messages-*'=>get_string('page-message-x', 'message'));
2458 * Is $USER one of the supplied users?
2460 * $user2 will be null if viewing a user's recent conversations
2462 * @param stdClass the first user
2463 * @param stdClass the second user or null
2464 * @return bool True if the current user is one of either $user1 or $user2
2466 function message_current_user_is_involved($user1, $user2) {
2467 global $USER;
2469 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2470 throw new coding_exception('Invalid user object detected. Missing id.');
2473 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2474 return false;
2476 return true;