MDL-33876 skip deleted users in enrol_database sync
[moodle.git] / message / lib.php
blobfeb364b3657739f9ce2752d2e4755eb2c7e2bb7a
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 //$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
30 if (isset($PAGE)) {
31 //TODO: this is a mega crazy hack - it is not acceptable to call anything when including lib!!! (skodak)
32 $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
35 define ('MESSAGE_DISCUSSION_WIDTH',600);
36 define ('MESSAGE_DISCUSSION_HEIGHT',500);
38 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
40 define('MESSAGE_HISTORY_SHORT',0);
41 define('MESSAGE_HISTORY_ALL',1);
43 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
44 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
45 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
46 define('MESSAGE_VIEW_CONTACTS','contacts');
47 define('MESSAGE_VIEW_BLOCKED','blockedusers');
48 define('MESSAGE_VIEW_COURSE','course_');
49 define('MESSAGE_VIEW_SEARCH','search');
51 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
53 define('MESSAGE_CONTACTS_PER_PAGE',10);
54 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
56 /**
57 * Define contants for messaging default settings population. For unambiguity of
58 * plugin developer intentions we use 4-bit value (LSB numbering):
59 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
60 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
61 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
63 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
66 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
67 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
69 define('MESSAGE_DISALLOWED', 0x04); // 0100
70 define('MESSAGE_PERMITTED', 0x08); // 1000
71 define('MESSAGE_FORCED', 0x0c); // 1100
73 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
75 /**
76 * Set default value for default outputs permitted setting
78 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
80 //TODO: defaults must be initialised via settings - this is a bad hack! (skodak)
81 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
82 $CFG->message_contacts_refresh = 60;
84 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
85 $CFG->message_chat_refresh = 5;
87 if (!isset($CFG->message_offline_time)) {
88 $CFG->message_offline_time = 300;
91 /**
92 * Print the selector that allows the user to view their contacts, course participants, their recent
93 * conversations etc
95 * @param int $countunreadtotal how many unread messages does the user have?
96 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
97 * @param object $user1 the user whose messages are being viewed
98 * @param object $user2 the user $user1 is talking to
99 * @param array $blockedusers an array of users blocked by $user1
100 * @param array $onlinecontacts an array of $user1's online contacts
101 * @param array $offlinecontacts an array of $user1's offline contacts
102 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
103 * @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
104 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
105 * @return void
107 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
108 global $PAGE;
110 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
112 //if 0 unread messages and they've requested unread messages then show contacts
113 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
114 $viewing = MESSAGE_VIEW_CONTACTS;
117 //if they have no blocked users and they've requested blocked users switch them over to contacts
118 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
119 $viewing = MESSAGE_VIEW_CONTACTS;
122 $onlyactivecourses = true;
123 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
124 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
126 $strunreadmessages = null;
127 if ($countunreadtotal>0) { //if there are unread messages
128 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
131 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
133 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
134 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
135 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
136 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
137 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
138 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
139 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
140 $courseidtoshow = intval(substr($viewing, 7));
142 if (!empty($courseidtoshow)
143 && array_key_exists($courseidtoshow, $coursecontexts)
144 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
146 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
147 } else {
148 //shouldn't get here. User trying to access a course they're not in perhaps.
149 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
153 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
154 echo html_writer::start_tag('fieldset');
155 $managebuttonclass = 'visible';
156 if ($viewing == MESSAGE_VIEW_SEARCH) {
157 $managebuttonclass = 'hiddenelement';
159 $strmanagecontacts = get_string('search','message');
160 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
161 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
162 echo html_writer::end_tag('fieldset');
163 echo html_writer::end_tag('form');
165 echo html_writer::end_tag('div');
169 * Print course participants. Called by message_print_contact_selector()
171 * @param object $context the course context
172 * @param int $courseid the course ID
173 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
174 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
175 * @param string $titletodisplay Optionally specify a title to display above the participants
176 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
177 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
178 * @return void
180 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
181 global $DB, $USER, $PAGE, $OUTPUT;
183 if (empty($titletodisplay)) {
184 $titletodisplay = get_string('participants');
187 $countparticipants = count_enrolled_users($context);
188 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
190 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
191 echo $OUTPUT->render($pagingbar);
193 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
195 echo html_writer::start_tag('tr');
196 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
197 echo html_writer::end_tag('tr');
199 //todo these need to come from somewhere if the course participants list is to show users with unread messages
200 $iscontact = true;
201 $isblocked = false;
202 foreach ($participants as $participant) {
203 if ($participant->id != $USER->id) {
204 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
205 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
209 echo html_writer::end_tag('table');
213 * Retrieve users blocked by $user1
215 * @param object $user1 the user whose messages are being viewed
216 * @param object $user2 the user $user1 is talking to. If they are being blocked
217 * they will have a variable called 'isblocked' added to their user object
218 * @return array the users blocked by $user1
220 function message_get_blocked_users($user1=null, $user2=null) {
221 global $DB, $USER;
223 if (empty($user1)) {
224 $user1 = $USER;
227 if (!empty($user2)) {
228 $user2->isblocked = false;
231 $blockedusers = array();
233 $userfields = user_picture::fields('u', array('lastaccess'));
234 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
235 FROM {message_contacts} mc
236 JOIN {user} u ON u.id = mc.contactid
237 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
238 WHERE mc.userid = :user1id2 AND mc.blocked = 1
239 GROUP BY $userfields
240 ORDER BY u.firstname ASC";
241 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
243 foreach($rs as $rd) {
244 $blockedusers[] = $rd;
246 if (!empty($user2) && $user2->id == $rd->id) {
247 $user2->isblocked = true;
250 $rs->close();
252 return $blockedusers;
256 * Print users blocked by $user1. Called by message_print_contact_selector()
258 * @param array $blockedusers the users blocked by $user1
259 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
260 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
261 * @param string $titletodisplay Optionally specify a title to display above the participants
262 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
263 * @return void
265 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
266 global $DB, $USER;
268 $countblocked = count($blockedusers);
270 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
272 if (!empty($titletodisplay)) {
273 echo html_writer::start_tag('tr');
274 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
275 echo html_writer::end_tag('tr');
278 if ($countblocked) {
279 echo html_writer::start_tag('tr');
280 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
281 echo html_writer::end_tag('tr');
283 $isuserblocked = true;
284 $isusercontact = false;
285 foreach ($blockedusers as $blockeduser) {
286 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
290 echo html_writer::end_tag('table');
294 * Retrieve $user1's contacts (online, offline and strangers)
296 * @param object $user1 the user whose messages are being viewed
297 * @param object $user2 the user $user1 is talking to. If they are a contact
298 * they will have a variable called 'iscontact' added to their user object
299 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
301 function message_get_contacts($user1=null, $user2=null) {
302 global $DB, $CFG, $USER;
304 if (empty($user1)) {
305 $user1 = $USER;
308 if (!empty($user2)) {
309 $user2->iscontact = false;
312 $timetoshowusers = 300; //Seconds default
313 if (isset($CFG->block_online_users_timetosee)) {
314 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
317 // time which a user is counting as being active since
318 $timefrom = time()-$timetoshowusers;
320 // people in our contactlist who are online
321 $onlinecontacts = array();
322 // people in our contactlist who are offline
323 $offlinecontacts = array();
324 // people who are not in our contactlist but have sent us a message
325 $strangers = array();
327 $userfields = user_picture::fields('u', array('lastaccess'));
329 // get all in our contactlist who are not blocked in our contact list
330 // and count messages we have waiting from each of them
331 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
332 FROM {message_contacts} mc
333 JOIN {user} u ON u.id = mc.contactid
334 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
335 WHERE mc.userid = ? AND mc.blocked = 0
336 GROUP BY $userfields
337 ORDER BY u.firstname ASC";
339 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
340 foreach ($rs as $rd) {
341 if ($rd->lastaccess >= $timefrom) {
342 // they have been active recently, so are counted online
343 $onlinecontacts[] = $rd;
345 } else {
346 $offlinecontacts[] = $rd;
349 if (!empty($user2) && $user2->id == $rd->id) {
350 $user2->iscontact = true;
353 $rs->close();
355 // get messages from anyone who isn't in our contact list and count the number
356 // of messages we have from each of them
357 $strangersql = "SELECT $userfields, count(m.id) as messagecount
358 FROM {message} m
359 JOIN {user} u ON u.id = m.useridfrom
360 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
361 WHERE mc.id IS NULL AND m.useridto = ?
362 GROUP BY $userfields
363 ORDER BY u.firstname ASC";
365 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
366 foreach ($rs as $rd) {
367 $strangers[] = $rd;
369 $rs->close();
371 return array($onlinecontacts, $offlinecontacts, $strangers);
375 * Print $user1's contacts. Called by message_print_contact_selector()
377 * @param array $onlinecontacts $user1's contacts which are online
378 * @param array $offlinecontacts $user1's contacts which are offline
379 * @param array $strangers users which are not contacts but who have messaged $user1
380 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
381 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
382 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
383 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
384 * @param string $titletodisplay Optionally specify a title to display above the participants
385 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
386 * @return void
388 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
389 global $CFG, $PAGE, $OUTPUT;
391 $countonlinecontacts = count($onlinecontacts);
392 $countofflinecontacts = count($offlinecontacts);
393 $countstrangers = count($strangers);
394 $isuserblocked = null;
396 if ($countonlinecontacts + $countofflinecontacts == 0) {
397 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
400 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
402 if (!empty($titletodisplay)) {
403 message_print_heading($titletodisplay);
406 if($countonlinecontacts) {
407 /// print out list of online contacts
409 if (empty($titletodisplay)) {
410 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
413 $isuserblocked = false;
414 $isusercontact = true;
415 foreach ($onlinecontacts as $contact) {
416 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
417 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
422 if ($countofflinecontacts) {
423 /// print out list of offline contacts
425 if (empty($titletodisplay)) {
426 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
429 $isuserblocked = false;
430 $isusercontact = true;
431 foreach ($offlinecontacts as $contact) {
432 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
433 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
439 /// print out list of incoming contacts
440 if ($countstrangers) {
441 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
443 $isuserblocked = false;
444 $isusercontact = false;
445 foreach ($strangers as $stranger) {
446 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
447 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
452 echo html_writer::end_tag('table');
454 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
455 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
460 * Print a select box allowing the user to choose to view new messages, course participants etc.
462 * Called by message_print_contact_selector()
463 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
464 * @param array $courses array of course objects. The courses the user is enrolled in.
465 * @param array $coursecontexts array of course contexts. Keyed on course id.
466 * @param int $countunreadtotal how many unread messages does the user have?
467 * @param int $countblocked how many users has the current user blocked?
468 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
469 * @return void
471 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
472 $options = array();
474 if ($countunreadtotal>0) { //if there are unread messages
475 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
478 $str = get_string('mycontacts', 'message');
479 $options[MESSAGE_VIEW_CONTACTS] = $str;
481 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
482 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
484 if (!empty($courses)) {
485 $courses_options = array();
487 foreach($courses as $course) {
488 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
489 //Not using short_text() as we want the end of the course name. Not the beginning.
490 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
491 if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
492 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
493 } else {
494 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
499 if (!empty($courses_options)) {
500 $options[] = array(get_string('courses') => $courses_options);
504 if ($countblocked>0) {
505 $str = get_string('blockedusers','message', $countblocked);
506 $options[MESSAGE_VIEW_BLOCKED] = $str;
509 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
510 echo html_writer::start_tag('fieldset');
511 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
512 echo html_writer::end_tag('fieldset');
513 echo html_writer::end_tag('form');
517 * Load the course contexts for all of the users courses
519 * @param array $courses array of course objects. The courses the user is enrolled in.
520 * @return array of course contexts
522 function message_get_course_contexts($courses) {
523 $coursecontexts = array();
525 foreach($courses as $course) {
526 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
529 return $coursecontexts;
533 * strip off action parameters like 'removecontact'
535 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
536 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
538 function message_remove_url_params($moodleurl) {
539 $newurl = new moodle_url($moodleurl);
540 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
541 return $newurl->out();
545 * Count the number of messages with a field having a specified value.
546 * if $field is empty then return count of the whole array
547 * if $field is non-existent then return 0
549 * @param array $messagearray array of message objects
550 * @param string $field the field to inspect on the message objects
551 * @param string $value the value to test the field against
553 function message_count_messages($messagearray, $field='', $value='') {
554 if (!is_array($messagearray)) return 0;
555 if ($field == '' or empty($messagearray)) return count($messagearray);
557 $count = 0;
558 foreach ($messagearray as $message) {
559 $count += ($message->$field == $value) ? 1 : 0;
561 return $count;
565 * Returns the count of unread messages for user. Either from a specific user or from all users.
567 * @param object $user1 the first user. Defaults to $USER
568 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
569 * @return int the count of $user1's unread messages
571 function message_count_unread_messages($user1=null, $user2=null) {
572 global $USER, $DB;
574 if (empty($user1)) {
575 $user1 = $USER;
578 if (!empty($user2)) {
579 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
580 array($user1->id, $user2->id), "COUNT('id')");
581 } else {
582 return $DB->count_records_select('message', "useridto = ?",
583 array($user1->id), "COUNT('id')");
588 * Count the number of users blocked by $user1
590 * @param object $user1 user object
591 * @return int the number of blocked users
593 function message_count_blocked_users($user1=null) {
594 global $USER, $DB;
596 if (empty($user1)) {
597 $user1 = $USER;
600 $sql = "SELECT count(mc.id)
601 FROM {message_contacts} mc
602 WHERE mc.userid = :userid AND mc.blocked = 1";
603 $params = array('userid' => $user1->id);
605 return $DB->count_records_sql($sql, $params);
609 * Print the search form and search results if a search has been performed
611 * @param boolean $advancedsearch show basic or advanced search form
612 * @param object $user1 the current user
613 * @return boolean true if a search was performed
615 function message_print_search($advancedsearch = false, $user1=null) {
616 $frm = data_submitted();
618 $doingsearch = false;
619 if ($frm) {
620 if (confirm_sesskey()) {
621 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
622 } else {
623 $frm = false;
627 if (!empty($frm->combinedsearch)) {
628 $combinedsearchstring = $frm->combinedsearch;
629 } else {
630 //$combinedsearchstring = get_string('searchcombined','message').'...';
631 $combinedsearchstring = '';
634 if ($doingsearch) {
635 if ($advancedsearch) {
637 $messagesearch = '';
638 if (!empty($frm->keywords)) {
639 $messagesearch = $frm->keywords;
641 $personsearch = '';
642 if (!empty($frm->name)) {
643 $personsearch = $frm->name;
645 include('search_advanced.html');
646 } else {
647 include('search.html');
650 $showicontext = false;
651 message_print_search_results($frm, $showicontext, $user1);
653 return true;
654 } else {
656 if ($advancedsearch) {
657 $personsearch = $messagesearch = '';
658 include('search_advanced.html');
659 } else {
660 include('search.html');
662 return false;
667 * Get the users recent conversations meaning all the people they've recently
668 * sent or received a message from plus the most recent message sent to or received from each other user
670 * @param object $user the current user
671 * @param int $limitfrom can be used for paging
672 * @param int $limitto can be used for paging
673 * @return array
675 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
676 global $DB;
678 $userfields = user_picture::fields('u', array('lastaccess'));
679 //This query retrieves the last message received from and sent to each user
680 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
681 //It then joins with some other tables to get some additional data we need
683 //message ID is used instead of timecreated as it should sort the same and will be much faster
685 //There is a separate query for read and unread queries as they are stored in different tables
686 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
687 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
688 FROM {message_read} mr
689 JOIN (
690 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
691 FROM (
692 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
693 FROM {message_read} mr1
694 WHERE mr1.useridfrom = :userid1
695 AND mr1.notification = 0
696 GROUP BY mr1.useridto
697 UNION
698 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
699 FROM {message_read} mr2
700 WHERE mr2.useridto = :userid2
701 AND mr2.notification = 0
702 GROUP BY mr2.useridfrom
703 ) messages
704 GROUP BY messages.userid
705 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
706 JOIN {user} u ON u.id = messages2.userid
707 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
708 WHERE u.deleted = '0'
709 ORDER BY mr.id DESC";
710 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
711 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
713 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
714 FROM {message} m
715 JOIN (
716 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
717 FROM (
718 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
719 FROM {message} m1
720 WHERE m1.useridfrom = :userid1
721 AND m1.notification = 0
722 GROUP BY m1.useridto
723 UNION
724 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
725 FROM {message} m2
726 WHERE m2.useridto = :userid2
727 AND m2.notification = 0
728 GROUP BY m2.useridfrom
729 ) messages
730 GROUP BY messages.userid
731 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
732 JOIN {user} u ON u.id = messages2.userid
733 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
734 WHERE u.deleted = '0'
735 ORDER BY m.id DESC";
736 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
738 $conversations = array();
740 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
741 //$conversation->id (the array key) is the other user's ID
742 $conversation_arrays = array($unread, $read);
743 foreach ($conversation_arrays as $conversation_array) {
744 foreach ($conversation_array as $conversation) {
745 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
746 $conversations[$conversation->id] = $conversation;
751 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
752 //and there may be multiple conversations with the same timecreated value.
753 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
754 usort($conversations, "conversationsort");
756 return $conversations;
760 * Sort function used to order conversations
762 * @param object $a A conversation object
763 * @param object $b A conversation object
764 * @return integer
766 function conversationsort($a, $b)
768 if ($a->timecreated == $b->timecreated) {
769 return 0;
771 return ($a->timecreated > $b->timecreated) ? -1 : 1;
775 * Get the users recent event notifications
777 * @param object $user the current user
778 * @param int $limitfrom can be used for paging
779 * @param int $limitto can be used for paging
780 * @return array
782 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
783 global $DB;
785 $userfields = user_picture::fields('u', array('lastaccess'));
786 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
787 FROM {message_read} mr
788 JOIN {user} u ON u.id=mr.useridfrom
789 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
790 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
791 $params = array('userid1' => $user->id, 'notification' => 1);
793 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
794 return $notifications;
798 * Print the user's recent conversations
800 * @param stdClass $user the current user
801 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
803 function message_print_recent_conversations($user=null, $showicontext=false) {
804 global $USER;
806 echo html_writer::start_tag('p', array('class' => 'heading'));
807 echo get_string('mostrecentconversations', 'message');
808 echo html_writer::end_tag('p');
810 if (empty($user)) {
811 $user = $USER;
814 $conversations = message_get_recent_conversations($user);
816 // Attach context url information to create the "View this conversation" type links
817 foreach($conversations as $conversation) {
818 $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
819 $conversation->contexturlname = get_string('thisconversation', 'message');
822 $showotheruser = true;
823 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
827 * Print the user's recent notifications
829 * @param stdClass $user the current user
831 function message_print_recent_notifications($user=null) {
832 global $USER;
834 echo html_writer::start_tag('p', array('class' => 'heading'));
835 echo get_string('mostrecentnotifications', 'message');
836 echo html_writer::end_tag('p');
838 if (empty($user)) {
839 $user = $USER;
842 $notifications = message_get_recent_notifications($user);
844 $showicontext = false;
845 $showotheruser = false;
846 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
850 * Print a list of recent messages
852 * @param array $messages the messages to display
853 * @param object $user the current user
854 * @param bool $showotheruser display information on the other user?
855 * @param bool $showicontext show text next to the action icons?
856 * @return void
858 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
859 global $OUTPUT;
860 static $dateformat;
862 if (empty($dateformat)) {
863 $dateformat = get_string('strftimedatetimeshort');
866 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
867 foreach ($messages as $message) {
868 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
870 if ($showotheruser) {
871 if ( $message->contactlistid ) {
872 if ($message->blocked == 0) { /// not blocked
873 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
874 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
875 } else { // blocked
876 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
877 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
879 } else {
880 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
881 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
884 //should we show just the icon or icon and text?
885 $histicontext = 'icon';
886 if ($showicontext) {
887 $histicontext = 'both';
889 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
891 echo html_writer::start_tag('span', array('class' => 'otheruser'));
893 echo html_writer::start_tag('span', array('class' => 'pix'));
894 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
895 echo html_writer::end_tag('span');
897 echo html_writer::start_tag('span', array('class' => 'contact'));
899 $link = new moodle_url("/message/index.php?id=$message->id");
900 $action = null;
901 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
903 echo html_writer::end_tag('span');//end contact
905 echo $strcontact.$strblock.$strhistory;
906 echo html_writer::end_tag('span');//end otheruser
908 $messagetoprint = null;
909 if (!empty($message->smallmessage)) {
910 $messagetoprint = $message->smallmessage;
911 } else {
912 $messagetoprint = $message->fullmessage;
915 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
916 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
917 echo message_format_contexturl($message);
918 echo html_writer::end_tag('div');//end singlemessage
920 echo html_writer::end_tag('div');//end messagerecent
924 * Add the selected user as a contact for the current user
926 * @param int $contactid the ID of the user to add as a contact
927 * @param int $blocked 1 if you wish to block the contact
928 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
929 * Otherwise returns the result of update_record() or insert_record()
931 function message_add_contact($contactid, $blocked=0) {
932 global $USER, $DB;
934 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
935 return false;
938 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
939 /// record already exists - we may be changing blocking status
941 if ($contact->blocked !== $blocked) {
942 /// change to blocking status
943 $contact->blocked = $blocked;
944 return $DB->update_record('message_contacts', $contact);
945 } else {
946 /// no changes to blocking status
947 return true;
950 } else {
951 /// new contact record
952 $contact = new stdClass();
953 $contact->userid = $USER->id;
954 $contact->contactid = $contactid;
955 $contact->blocked = $blocked;
956 return $DB->insert_record('message_contacts', $contact, false);
961 * remove a contact
963 * @param int $contactid the user ID of the contact to remove
964 * @return bool returns the result of delete_records()
966 function message_remove_contact($contactid) {
967 global $USER, $DB;
968 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
972 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
974 * @param int $contactid the user ID of the contact to unblock
975 * @return bool returns the result of delete_records()
977 function message_unblock_contact($contactid) {
978 global $USER, $DB;
979 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
983 * block a user
985 * @param int $contactid the user ID of the user to block
987 function message_block_contact($contactid) {
988 return message_add_contact($contactid, 1);
992 * Load a user's contact record
994 * @param int $contactid the user ID of the user whose contact record you want
995 * @return array message contacts
997 function message_get_contact($contactid) {
998 global $USER, $DB;
999 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1003 * Print the results of a message search
1005 * @param mixed $frm submitted form data
1006 * @param bool $showicontext show text next to action icons?
1007 * @param object $currentuser the current user
1008 * @return void
1010 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1011 global $USER, $DB, $OUTPUT;
1013 if (empty($currentuser)) {
1014 $currentuser = $USER;
1017 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1019 $personsearch = false;
1020 $personsearchstring = null;
1021 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1022 $personsearch = true;
1023 $personsearchstring = $frm->name;
1024 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1025 $personsearch = true;
1026 $personsearchstring = $frm->combinedsearch;
1029 /// search for person
1030 if ($personsearch) {
1031 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1032 $users = array();
1033 $mycourses = enrol_get_my_courses();
1034 foreach ($mycourses as $mycourse) {
1035 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1036 foreach ($susers as $suser) $users[$suser->id] = $suser;
1039 } else {
1040 $users = message_search_users(SITEID, $personsearchstring);
1043 if (!empty($users)) {
1044 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1045 echo get_string('userssearchresults', 'message', count($users));
1046 echo html_writer::end_tag('p');
1048 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1049 foreach ($users as $user) {
1051 if ( $user->contactlistid ) {
1052 if ($user->blocked == 0) { /// not blocked
1053 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1054 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1055 } else { // blocked
1056 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1057 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1059 } else {
1060 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1061 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1064 //should we show just the icon or icon and text?
1065 $histicontext = 'icon';
1066 if ($showicontext) {
1067 $histicontext = 'both';
1069 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1071 echo html_writer::start_tag('tr');
1073 echo html_writer::start_tag('td', array('class' => 'pix'));
1074 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1075 echo html_writer::end_tag('td');
1077 echo html_writer::start_tag('td',array('class' => 'contact'));
1078 $action = null;
1079 $link = new moodle_url("/message/index.php?id=$user->id");
1080 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1081 echo html_writer::end_tag('td');
1083 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1084 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1085 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1087 echo html_writer::end_tag('tr');
1089 echo html_writer::end_tag('table');
1091 } else {
1092 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1093 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1094 echo html_writer::end_tag('p');
1098 // search messages for keywords
1099 $messagesearch = false;
1100 $messagesearchstring = null;
1101 if (!empty($frm->keywords)) {
1102 $messagesearch = true;
1103 $messagesearchstring = clean_text(trim($frm->keywords));
1104 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1105 $messagesearch = true;
1106 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1109 if ($messagesearch) {
1110 if ($messagesearchstring) {
1111 $keywords = explode(' ', $messagesearchstring);
1112 } else {
1113 $keywords = array();
1115 $tome = false;
1116 $fromme = false;
1117 $courseid = 'none';
1119 if (empty($frm->keywordsoption)) {
1120 $frm->keywordsoption = 'allmine';
1123 switch ($frm->keywordsoption) {
1124 case 'tome':
1125 $tome = true;
1126 break;
1127 case 'fromme':
1128 $fromme = true;
1129 break;
1130 case 'allmine':
1131 $tome = true;
1132 $fromme = true;
1133 break;
1134 case 'allusers':
1135 $courseid = SITEID;
1136 break;
1137 case 'courseusers':
1138 $courseid = $frm->courseid;
1139 break;
1140 default:
1141 $tome = true;
1142 $fromme = true;
1145 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1147 /// get a list of contacts
1148 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1149 $contacts = array();
1152 /// print heading with number of results
1153 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1154 $countresults = count($messages);
1155 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1156 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1157 } else {
1158 echo get_string('keywordssearchresults', 'message', $countresults);
1160 echo html_writer::end_tag('p');
1162 /// print table headings
1163 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1165 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1166 $headertdend = html_writer::end_tag('td');
1167 echo html_writer::start_tag('tr');
1168 echo $headertdstart.get_string('from').$headertdend;
1169 echo $headertdstart.get_string('to').$headertdend;
1170 echo $headertdstart.get_string('message', 'message').$headertdend;
1171 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1172 echo html_writer::end_tag('tr');
1174 $blockedcount = 0;
1175 $dateformat = get_string('strftimedatetimeshort');
1176 $strcontext = get_string('context', 'message');
1177 foreach ($messages as $message) {
1179 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1180 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1181 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1182 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1185 $blockedcount ++;
1186 continue;
1189 /// load up user to record
1190 if ($message->useridto !== $USER->id) {
1191 $userto = $DB->get_record('user', array('id' => $message->useridto));
1192 $tocontact = (array_key_exists($message->useridto, $contacts) and
1193 ($contacts[$message->useridto]->blocked == 0) );
1194 $toblocked = (array_key_exists($message->useridto, $contacts) and
1195 ($contacts[$message->useridto]->blocked == 1) );
1196 } else {
1197 $userto = false;
1198 $tocontact = false;
1199 $toblocked = false;
1202 /// load up user from record
1203 if ($message->useridfrom !== $USER->id) {
1204 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1205 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1206 ($contacts[$message->useridfrom]->blocked == 0) );
1207 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1208 ($contacts[$message->useridfrom]->blocked == 1) );
1209 } else {
1210 $userfrom = false;
1211 $fromcontact = false;
1212 $fromblocked = false;
1215 /// find date string for this message
1216 $date = usergetdate($message->timecreated);
1217 $datestring = $date['year'].$date['mon'].$date['mday'];
1219 /// print out message row
1220 echo html_writer::start_tag('tr', array('valign' => 'top'));
1222 echo html_writer::start_tag('td', array('class' => 'contact'));
1223 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1224 echo html_writer::end_tag('td');
1226 echo html_writer::start_tag('td', array('class' => 'contact'));
1227 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1228 echo html_writer::end_tag('td');
1230 echo html_writer::start_tag('td', array('class' => 'summary'));
1231 echo message_get_fragment($message->fullmessage, $keywords);
1232 echo html_writer::start_tag('div', array('class' => 'link'));
1234 //If the user clicks the context link display message sender on the left
1235 //EXCEPT if the current user is in the conversation. Current user == always on the left
1236 $leftsideuserid = $rightsideuserid = null;
1237 if ($currentuser->id == $message->useridto) {
1238 $leftsideuserid = $message->useridto;
1239 $rightsideuserid = $message->useridfrom;
1240 } else {
1241 $leftsideuserid = $message->useridfrom;
1242 $rightsideuserid = $message->useridto;
1244 message_history_link($leftsideuserid, $rightsideuserid, false,
1245 $messagesearchstring, 'm'.$message->id, $strcontext);
1246 echo html_writer::end_tag('div');
1247 echo html_writer::end_tag('td');
1249 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1251 echo html_writer::end_tag('tr');
1255 if ($blockedcount > 0) {
1256 echo html_writer::start_tag('tr');
1257 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1258 echo html_writer::end_tag('tr');
1260 echo html_writer::end_tag('table');
1262 } else {
1263 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1267 if (!$personsearch && !$messagesearch) {
1268 //they didn't enter any search terms
1269 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1272 echo html_writer::end_tag('div');
1276 * Print information on a user. Used when printing search results.
1278 * @param object/bool $user the user to display or false if you just want $USER
1279 * @param bool $iscontact is the user being displayed a contact?
1280 * @param bool $isblocked is the user being displayed blocked?
1281 * @param bool $includeicontext include text next to the action icons?
1282 * @return void
1284 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1285 global $USER, $OUTPUT;
1287 if ($user === false) {
1288 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1289 } else {
1290 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1291 echo '&nbsp;';
1293 $return = false;
1294 $script = null;
1295 if ($iscontact) {
1296 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1297 } else {
1298 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1300 echo '&nbsp;';
1301 if ($isblocked) {
1302 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1303 } else {
1304 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1307 $popupoptions = array(
1308 'height' => MESSAGE_DISCUSSION_HEIGHT,
1309 'width' => MESSAGE_DISCUSSION_WIDTH,
1310 'menubar' => false,
1311 'location' => false,
1312 'status' => true,
1313 'scrollbars' => true,
1314 'resizable' => true);
1316 $link = new moodle_url("/message/index.php?id=$user->id");
1317 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1318 $action = null;
1319 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1325 * Print a message contact link
1327 * @param int $userid the ID of the user to apply to action to
1328 * @param string $linktype can be add, remove, block or unblock
1329 * @param bool $return if true return the link as a string. If false echo the link.
1330 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1331 * @param bool $text include text next to the icons?
1332 * @param bool $icon include a graphical icon?
1333 * @return string if $return is true otherwise bool
1335 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1336 global $OUTPUT, $PAGE;
1338 //hold onto the strings as we're probably creating a bunch of links
1339 static $str;
1341 if (empty($script)) {
1342 //strip off previous action params like 'removecontact'
1343 $script = message_remove_url_params($PAGE->url);
1346 if (empty($str->blockcontact)) {
1347 $str = new stdClass();
1348 $str->blockcontact = get_string('blockcontact', 'message');
1349 $str->unblockcontact = get_string('unblockcontact', 'message');
1350 $str->removecontact = get_string('removecontact', 'message');
1351 $str->addcontact = get_string('addcontact', 'message');
1354 $command = $linktype.'contact';
1355 $string = $str->{$command};
1357 $safealttext = s($string);
1359 $safestring = '';
1360 if (!empty($text)) {
1361 $safestring = $safealttext;
1364 $img = '';
1365 if ($icon) {
1366 $iconpath = null;
1367 switch ($linktype) {
1368 case 'block':
1369 $iconpath = 't/block';
1370 break;
1371 case 'unblock':
1372 $iconpath = 't/userblue';
1373 break;
1374 case 'remove':
1375 $iconpath = 'i/cross_red_big';
1376 break;
1377 case 'add':
1378 default:
1379 $iconpath = 't/addgreen';
1382 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1385 $output = '<span class="'.$linktype.'contact">'.
1386 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1387 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1388 $img.
1389 $safestring.'</a></span>';
1391 if ($return) {
1392 return $output;
1393 } else {
1394 echo $output;
1395 return true;
1400 * echo or return a link to take the user to the full message history between themselves and another user
1402 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1403 * @param int $userid2 the ID of the other user
1404 * @param bool $return true to return the link as a string. False to echo the link.
1405 * @param string $keywords any keywords to highlight in the message history
1406 * @param string $position anchor name to jump to within the message history
1407 * @param string $linktext optionally specify the link text
1408 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1410 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1411 global $OUTPUT;
1412 static $strmessagehistory;
1414 if (empty($strmessagehistory)) {
1415 $strmessagehistory = get_string('messagehistory', 'message');
1418 if ($position) {
1419 $position = "#$position";
1421 if ($keywords) {
1422 $keywords = "&search=".urlencode($keywords);
1425 if ($linktext == 'icon') { // Icon only
1426 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1427 } else if ($linktext == 'both') { // Icon and standard name
1428 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1429 $fulllink .= '&nbsp;'.$strmessagehistory;
1430 } else if ($linktext) { // Custom name
1431 $fulllink = $linktext;
1432 } else { // Standard name only
1433 $fulllink = $strmessagehistory;
1436 $popupoptions = array(
1437 'height' => 500,
1438 'width' => 500,
1439 'menubar' => false,
1440 'location' => false,
1441 'status' => true,
1442 'scrollbars' => true,
1443 'resizable' => true);
1445 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1446 $action = null;
1447 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1449 $str = '<span class="history">'.$str.'</span>';
1451 if ($return) {
1452 return $str;
1453 } else {
1454 echo $str;
1455 return true;
1461 * Search through course users
1463 * If $coursid specifies the site course then this function searches
1464 * through all undeleted and confirmed users
1465 * @param int $courseid The course in question.
1466 * @param string $searchtext the text to search for
1467 * @param string $sort the column name to order by
1468 * @param string $exceptions comma separated list of user IDs to exclude
1469 * @return array An array of {@link $USER} records.
1471 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1472 global $CFG, $USER, $DB;
1474 $fullname = $DB->sql_fullname();
1476 if (!empty($exceptions)) {
1477 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1478 } else {
1479 $except = '';
1482 if (!empty($sort)) {
1483 $order = ' ORDER BY '. $sort;
1484 } else {
1485 $order = '';
1488 $ufields = user_picture::fields('u');
1489 if (!$courseid or $courseid == SITEID) {
1490 $params = array($USER->id, "%$searchtext%");
1491 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1492 FROM {user} u
1493 LEFT JOIN {message_contacts} mc
1494 ON mc.contactid = u.id AND mc.userid = ?
1495 WHERE u.deleted = '0' AND u.confirmed = '1'
1496 AND (".$DB->sql_like($fullname, '?', false).")
1497 $except
1498 $order", $params);
1499 } else {
1500 //TODO: add enabled enrolment join here (skodak)
1501 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1502 $contextlists = get_related_contexts_string($context);
1504 // everyone who has a role assignment in this course or higher
1505 $params = array($USER->id, "%$searchtext%");
1506 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1507 FROM {user} u
1508 JOIN {role_assignments} ra ON ra.userid = u.id
1509 LEFT JOIN {message_contacts} mc
1510 ON mc.contactid = u.id AND mc.userid = ?
1511 WHERE u.deleted = '0' AND u.confirmed = '1'
1512 AND ra.contextid $contextlists
1513 AND (".$DB->sql_like($fullname, '?', false).")
1514 $except
1515 $order", $params);
1517 return $users;
1522 * search a user's messages
1524 * @param array $searchterms an array of search terms (strings)
1525 * @param bool $fromme include messages from the user?
1526 * @param bool $tome include messages to the user?
1527 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1528 * @param int $userid the user ID of the current user
1529 * @return mixed An array of messages or false if no matching messages were found
1531 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1532 /// Returns a list of posts found using an array of search terms
1533 /// eg word +word -word
1535 global $CFG, $USER, $DB;
1537 // If user is searching all messages check they are allowed to before doing anything else
1538 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) {
1539 print_error('accessdenied','admin');
1542 /// If no userid sent then assume current user
1543 if ($userid == 0) $userid = $USER->id;
1545 /// Some differences in SQL syntax
1546 if ($DB->sql_regex_supported()) {
1547 $REGEXP = $DB->sql_regex(true);
1548 $NOTREGEXP = $DB->sql_regex(false);
1551 $searchcond = array();
1552 $params = array();
1553 $i = 0;
1555 //preprocess search terms to check whether we have at least 1 eligible search term
1556 //if we do we can drop words around it like 'a'
1557 $dropshortwords = false;
1558 foreach ($searchterms as $searchterm) {
1559 if (strlen($searchterm) >= 2) {
1560 $dropshortwords = true;
1564 foreach ($searchterms as $searchterm) {
1565 $i++;
1567 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1569 if ($dropshortwords && strlen($searchterm) < 2) {
1570 continue;
1572 /// Under Oracle and MSSQL, trim the + and - operators and perform
1573 /// simpler LIKE search
1574 if (!$DB->sql_regex_supported()) {
1575 if (substr($searchterm, 0, 1) == '-') {
1576 $NOT = true;
1578 $searchterm = trim($searchterm, '+-');
1581 if (substr($searchterm,0,1) == "+") {
1582 $searchterm = substr($searchterm,1);
1583 $searchterm = preg_quote($searchterm, '|');
1584 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1585 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1587 } else if (substr($searchterm,0,1) == "-") {
1588 $searchterm = substr($searchterm,1);
1589 $searchterm = preg_quote($searchterm, '|');
1590 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1591 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1593 } else {
1594 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1595 $params['ss'.$i] = "%$searchterm%";
1599 if (empty($searchcond)) {
1600 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1601 $params['ss1'] = "%";
1602 } else {
1603 $searchcond = implode(" AND ", $searchcond);
1606 /// There are several possibilities
1607 /// 1. courseid = SITEID : The admin is searching messages by all users
1608 /// 2. courseid = ?? : A teacher is searching messages by users in
1609 /// one of their courses - currently disabled
1610 /// 3. courseid = none : User is searching their own messages;
1611 /// a. Messages from user
1612 /// b. Messages to user
1613 /// c. Messages to and from user
1615 if ($courseid == SITEID) { /// admin is searching all messages
1616 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1617 FROM {message_read} m
1618 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1619 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1620 FROM {message} m
1621 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1623 } else if ($courseid !== 'none') {
1624 /// This has not been implemented due to security concerns
1625 $m_read = array();
1626 $m_unread = array();
1628 } else {
1630 if ($fromme and $tome) {
1631 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1632 $params['userid1'] = $userid;
1633 $params['userid2'] = $userid;
1635 } else if ($fromme) {
1636 $searchcond .= " AND m.useridfrom=:userid";
1637 $params['userid'] = $userid;
1639 } else if ($tome) {
1640 $searchcond .= " AND m.useridto=:userid";
1641 $params['userid'] = $userid;
1644 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1645 FROM {message_read} m
1646 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1647 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
1648 FROM {message} m
1649 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1653 /// The keys may be duplicated in $m_read and $m_unread so we can't
1654 /// do a simple concatenation
1655 $messages = array();
1656 foreach ($m_read as $m) {
1657 $messages[] = $m;
1659 foreach ($m_unread as $m) {
1660 $messages[] = $m;
1663 return (empty($messages)) ? false : $messages;
1667 * Given a message object that we already know has a long message
1668 * this function truncates the message nicely to the first
1669 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1671 * @param string $message the message
1672 * @param int $minlength the minimum length to trim the message to
1673 * @return string the shortened message
1675 function message_shorten_message($message, $minlength = 0) {
1676 $i = 0;
1677 $tag = false;
1678 $length = strlen($message);
1679 $count = 0;
1680 $stopzone = false;
1681 $truncate = 0;
1682 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1685 for ($i=0; $i<$length; $i++) {
1686 $char = $message[$i];
1688 switch ($char) {
1689 case "<":
1690 $tag = true;
1691 break;
1692 case ">":
1693 $tag = false;
1694 break;
1695 default:
1696 if (!$tag) {
1697 if ($stopzone) {
1698 if ($char == '.' or $char == ' ') {
1699 $truncate = $i+1;
1700 break 2;
1703 $count++;
1705 break;
1707 if (!$stopzone) {
1708 if ($count > $minlength) {
1709 $stopzone = true;
1714 if (!$truncate) {
1715 $truncate = $i;
1718 return substr($message, 0, $truncate);
1723 * Given a string and an array of keywords, this function looks
1724 * for the first keyword in the string, and then chops out a
1725 * small section from the text that shows that word in context.
1727 * @param string $message the text to search
1728 * @param array $keywords array of keywords to find
1730 function message_get_fragment($message, $keywords) {
1732 $fullsize = 160;
1733 $halfsize = (int)($fullsize/2);
1735 $message = strip_tags($message);
1737 foreach ($keywords as $keyword) { // Just get the first one
1738 if ($keyword !== '') {
1739 break;
1742 if (empty($keyword)) { // None found, so just return start of message
1743 return message_shorten_message($message, 30);
1746 $leadin = $leadout = '';
1748 /// Find the start of the fragment
1749 $start = 0;
1750 $length = strlen($message);
1752 $pos = strpos($message, $keyword);
1753 if ($pos > $halfsize) {
1754 $start = $pos - $halfsize;
1755 $leadin = '...';
1757 /// Find the end of the fragment
1758 $end = $start + $fullsize;
1759 if ($end > $length) {
1760 $end = $length;
1761 } else {
1762 $leadout = '...';
1765 /// Pull out the fragment and format it
1767 $fragment = substr($message, $start, $end - $start);
1768 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1769 return $fragment;
1773 * Retrieve the messages between two users
1775 * @param object $user1 the current user
1776 * @param object $user2 the other user
1777 * @param int $limitnum the maximum number of messages to retrieve
1778 * @param bool $viewingnewmessages are we currently viewing new messages?
1780 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1781 global $DB, $CFG;
1783 $messages = array();
1785 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1786 //desc to get the last $limitnum messages then flip the order in php
1787 $sort = 'asc';
1788 if ($limitnum>0) {
1789 $sort = 'desc';
1792 $notificationswhere = null;
1793 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1794 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1795 $notificationswhere = 'AND notification=0';
1798 //prevent notifications of your own actions appearing in your own message history
1799 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1801 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1802 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1803 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1804 "timecreated $sort", '*', 0, $limitnum)) {
1805 foreach ($messages_read as $message) {
1806 $messages[$message->timecreated] = $message;
1809 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1810 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1811 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1812 "timecreated $sort", '*', 0, $limitnum)) {
1813 foreach ($messages_new as $message) {
1814 $messages[$message->timecreated] = $message;
1818 //if we only want the last $limitnum messages
1819 ksort($messages);
1820 $messagecount = count($messages);
1821 if ($limitnum>0 && $messagecount>$limitnum) {
1822 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
1825 return $messages;
1829 * Print the message history between two users
1831 * @param object $user1 the current user
1832 * @param object $user2 the other user
1833 * @param string $search search terms to highlight
1834 * @param int $messagelimit maximum number of messages to return
1835 * @param string $messagehistorylink the html for the message history link or false
1836 * @param bool $viewingnewmessages are we currently viewing new messages?
1838 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1839 global $CFG, $OUTPUT;
1841 echo $OUTPUT->box_start('center');
1842 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1843 echo html_writer::start_tag('tr');
1845 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1846 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1847 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1848 echo html_writer::end_tag('td');
1850 echo html_writer::start_tag('td', array('align' => 'center'));
1851 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1852 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1853 echo html_writer::end_tag('td');
1855 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1856 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1857 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1859 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1860 $incontactlist = $user2->iscontact;
1861 $isblocked = $user2->isblocked;
1863 $script = null;
1864 $text = true;
1865 $icon = false;
1867 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1868 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1869 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1871 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1874 echo html_writer::end_tag('td');
1875 echo html_writer::end_tag('tr');
1876 echo html_writer::end_tag('table');
1877 echo $OUTPUT->box_end();
1879 if (!empty($messagehistorylink)) {
1880 echo $messagehistorylink;
1883 /// Get all the messages and print them
1884 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1885 $tablecontents = '';
1887 $current = new stdClass();
1888 $current->mday = '';
1889 $current->month = '';
1890 $current->year = '';
1891 $messagedate = get_string('strftimetime');
1892 $blockdate = get_string('strftimedaydate');
1893 foreach ($messages as $message) {
1894 if ($message->notification) {
1895 $notificationclass = ' notification';
1896 } else {
1897 $notificationclass = null;
1899 $date = usergetdate($message->timecreated);
1900 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1901 $current->mday = $date['mday'];
1902 $current->month = $date['month'];
1903 $current->year = $date['year'];
1905 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1906 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1908 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1911 $formatted_message = $side = null;
1912 if ($message->useridfrom == $user1->id) {
1913 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1914 $side = 'left';
1915 } else {
1916 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1917 $side = 'right';
1919 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1922 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1923 } else {
1924 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1929 * Format a message for display in the message history
1931 * @param object $message the message object
1932 * @param string $format optional date format
1933 * @param string $keywords keywords to highlight
1934 * @param string $class CSS class to apply to the div around the message
1935 * @return string the formatted message
1937 function message_format_message($message, $format='', $keywords='', $class='other') {
1939 static $dateformat;
1941 //if we haven't previously set the date format or they've supplied a new one
1942 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1943 if ($format) {
1944 $dateformat = $format;
1945 } else {
1946 $dateformat = get_string('strftimedatetimeshort');
1949 $time = userdate($message->timecreated, $dateformat);
1950 $options = new stdClass();
1951 $options->para = false;
1953 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1954 if (!empty($message->smallmessage)) {
1955 $messagetext = $message->smallmessage;
1956 } else {
1957 $messagetext = $message->fullmessage;
1959 if ($message->fullmessageformat == FORMAT_HTML) {
1960 //dont escape html tags by calling s() if html format or they will display in the UI
1961 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1962 } else {
1963 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1966 $messagetext .= message_format_contexturl($message);
1968 if ($keywords) {
1969 $messagetext = highlight($keywords, $messagetext);
1972 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1976 * Format a the context url and context url name of a message for display
1978 * @param object $message the message object
1979 * @return string the formatted string
1981 function message_format_contexturl($message) {
1982 $s = null;
1984 if (!empty($message->contexturl)) {
1985 $displaytext = null;
1986 if (!empty($message->contexturlname)) {
1987 $displaytext= $message->contexturlname;
1988 } else {
1989 $displaytext= $message->contexturl;
1991 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1992 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1993 $s .= html_writer::end_tag('div');
1996 return $s;
2000 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2002 * @param object $userfrom the message sender
2003 * @param object $userto the message recipient
2004 * @param string $message the message
2005 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2006 * @return int|false the ID of the new message or false
2008 function message_post_message($userfrom, $userto, $message, $format) {
2009 global $SITE, $CFG, $USER;
2011 $eventdata = new stdClass();
2012 $eventdata->component = 'moodle';
2013 $eventdata->name = 'instantmessage';
2014 $eventdata->userfrom = $userfrom;
2015 $eventdata->userto = $userto;
2017 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2018 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2020 if ($format == FORMAT_HTML) {
2021 $eventdata->fullmessagehtml = $message;
2022 //some message processors may revert to sending plain text even if html is supplied
2023 //so we keep both plain and html versions if we're intending to send html
2024 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2025 } else {
2026 $eventdata->fullmessage = $message;
2027 $eventdata->fullmessagehtml = '';
2030 $eventdata->fullmessageformat = $format;
2031 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2033 $s = new stdClass();
2034 $s->sitename = format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
2035 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2037 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2038 if (!empty($eventdata->fullmessage)) {
2039 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2041 if (!empty($eventdata->fullmessagehtml)) {
2042 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2045 $eventdata->timecreated = time();
2046 return message_send($eventdata);
2050 * Print a row of contactlist displaying user picture, messages waiting and
2051 * block links etc
2053 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2054 * @param bool $incontactlist is the user a contact of ours?
2055 * @param bool $isblocked is the user blocked?
2056 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2057 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2058 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2059 * @return void
2061 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2062 global $OUTPUT, $USER;
2063 $fullname = fullname($contact);
2064 $fullnamelink = $fullname;
2066 $linkclass = '';
2067 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2068 $linkclass = 'messageselecteduser';
2071 /// are there any unread messages for this contact?
2072 if ($contact->messagecount > 0 ){
2073 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2076 $strcontact = $strblock = $strhistory = null;
2078 if ($showactionlinks) {
2079 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2080 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2081 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2084 echo html_writer::start_tag('tr');
2085 echo html_writer::start_tag('td', array('class' => 'pix'));
2086 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2087 echo html_writer::end_tag('td');
2089 echo html_writer::start_tag('td', array('class' => 'contact'));
2091 $popupoptions = array(
2092 'height' => MESSAGE_DISCUSSION_HEIGHT,
2093 'width' => MESSAGE_DISCUSSION_WIDTH,
2094 'menubar' => false,
2095 'location' => false,
2096 'status' => true,
2097 'scrollbars' => true,
2098 'resizable' => true);
2100 $link = $action = null;
2101 if (!empty($selectcontacturl)) {
2102 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2103 } else {
2104 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2105 $link = new moodle_url("/message/index.php?id=$contact->id");
2106 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2108 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2110 echo html_writer::end_tag('td');
2112 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2114 echo html_writer::end_tag('tr');
2118 * Constructs the add/remove contact link to display next to other users
2120 * @param bool $incontactlist is the user a contact
2121 * @param bool $isblocked is the user blocked
2122 * @param stdClass $contact contact object
2123 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2124 * @param bool $text include text next to the icons?
2125 * @param bool $icon include a graphical icon?
2126 * @return string
2128 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2129 $strcontact = '';
2131 if($incontactlist){
2132 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2133 } else if ($isblocked) {
2134 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2135 } else{
2136 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2139 return $strcontact;
2143 * Constructs the block contact link to display next to other users
2145 * @param bool $incontactlist is the user a contact?
2146 * @param bool $isblocked is the user blocked?
2147 * @param stdClass $contact contact object
2148 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2149 * @param bool $text include text next to the icons?
2150 * @param bool $icon include a graphical icon?
2151 * @return string
2153 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2154 $strblock = '';
2156 //commented out to allow the user to block a contact without having to remove them first
2157 /*if ($incontactlist) {
2158 //$strblock = '';
2159 } else*/
2160 if ($isblocked) {
2161 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2162 } else{
2163 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2166 return $strblock;
2170 * Moves messages from a particular user from the message table (unread messages) to message_read
2171 * This is typically only used when a user is deleted
2173 * @param object $userid User id
2174 * @return boolean success
2176 function message_move_userfrom_unread2read($userid) {
2177 global $DB;
2179 // move all unread messages from message table to message_read
2180 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2181 foreach ($messages as $message) {
2182 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2185 return true;
2189 * marks ALL messages being sent from $fromuserid to $touserid as read
2191 * @param int $touserid the id of the message recipient
2192 * @param int $fromuserid the id of the message sender
2193 * @return void
2195 function message_mark_messages_read($touserid, $fromuserid){
2196 global $DB;
2198 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2199 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2201 foreach ($messages as $message) {
2202 message_mark_message_read($message, time());
2205 $messages->close();
2209 * Mark a single message as read
2211 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2212 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2213 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2214 * @return int the ID of the message in the message_read table
2216 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2217 global $DB;
2219 $message->timeread = $timeread;
2221 $messageid = $message->id;
2222 unset($message->id);//unset because it will get a new id on insert into message_read
2224 //If any processors have pending actions abort them
2225 if (!$messageworkingempty) {
2226 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2228 $messagereadid = $DB->insert_record('message_read', $message);
2229 $DB->delete_records('message', array('id' => $messageid));
2230 return $messagereadid;
2234 * A helper function that prints a formatted heading
2236 * @param string $title the heading to display
2237 * @param int $colspan
2238 * @return void
2240 function message_print_heading($title, $colspan=3) {
2241 echo html_writer::start_tag('tr');
2242 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2243 echo html_writer::end_tag('tr');
2247 * Get all message processors, validate corresponding plugin existance and
2248 * system configuration
2250 * @param bool $ready only return ready-to-use processors
2251 * @return mixed $processors array of objects containing information on message processors
2253 function get_message_processors($ready = false) {
2254 global $DB, $CFG;
2256 static $processors;
2258 if (empty($processors)) {
2259 // Get all processors, ensure the name column is the first so it will be the array key
2260 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2261 foreach ($processors as &$processor){
2262 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2263 if (is_readable($processorfile)) {
2264 include_once($processorfile);
2265 $processclass = 'message_output_' . $processor->name;
2266 if (class_exists($processclass)) {
2267 $pclass = new $processclass();
2268 $processor->object = $pclass;
2269 $processor->configured = 0;
2270 if ($pclass->is_system_configured()) {
2271 $processor->configured = 1;
2273 $processor->hassettings = 0;
2274 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2275 $processor->hassettings = 1;
2277 $processor->available = 1;
2278 } else {
2279 print_error('errorcallingprocessor', 'message');
2281 } else {
2282 $processor->available = 0;
2286 if ($ready) {
2287 // Filter out enabled and system_configured processors
2288 $readyprocessors = $processors;
2289 foreach ($readyprocessors as $readyprocessor) {
2290 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2291 unset($readyprocessors[$readyprocessor->name]);
2294 return $readyprocessors;
2297 return $processors;
2301 * Get all message providers, validate their plugin existance and
2302 * system configuration
2304 * @return mixed $processors array of objects containing information on message processors
2306 function get_message_providers() {
2307 global $CFG, $DB;
2308 require_once($CFG->libdir . '/pluginlib.php');
2309 $pluginman = plugin_manager::instance();
2311 $providers = $DB->get_records('message_providers', null, 'name');
2313 // Remove all the providers whose plugins are disabled or don't exist
2314 foreach ($providers as $providerid => $provider) {
2315 $plugin = $pluginman->get_plugin_info($provider->component);
2316 if ($plugin) {
2317 if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2318 unset($providers[$providerid]); // Plugins does not exist
2319 continue;
2321 if ($plugin->is_enabled() === false) {
2322 unset($providers[$providerid]); // Plugin disabled
2323 continue;
2327 return $providers;
2331 * Get an instance of the message_output class for one of the output plugins.
2332 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2333 * @return message_output message_output the requested class.
2335 function get_message_processor($type) {
2336 global $CFG;
2338 // Note, we cannot use the get_message_processors function here, becaues this
2339 // code is called during install after installing each messaging plugin, and
2340 // get_message_processors caches the list of installed plugins.
2342 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2343 if (!is_readable($processorfile)) {
2344 throw new coding_exception('Unknown message processor type ' . $type);
2347 include_once($processorfile);
2349 $processclass = 'message_output_' . $type;
2350 if (!class_exists($processclass)) {
2351 throw new coding_exception('Message processor ' . $type .
2352 ' does not define the right class');
2355 return new $processclass();
2359 * Get messaging outputs default (site) preferences
2361 * @return object $processors object containing information on message processors
2363 function get_message_output_default_preferences() {
2364 return get_config('message');
2368 * Translate message default settings from binary value to the array of string
2369 * representing the settings to be stored. Also validate the provided value and
2370 * use default if it is malformed.
2372 * @param int $plugindefault Default setting suggested by plugin
2373 * @param string $processorname The name of processor
2374 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2376 function translate_message_default_setting($plugindefault, $processorname) {
2377 // Preset translation arrays
2378 $permittedvalues = array(
2379 0x04 => 'disallowed',
2380 0x08 => 'permitted',
2381 0x0c => 'forced',
2384 $loggedinstatusvalues = array(
2385 0x00 => null, // use null if loggedin/loggedoff is not defined
2386 0x01 => 'loggedin',
2387 0x02 => 'loggedoff',
2390 // define the default setting
2391 $processor = get_message_processor($processorname);
2392 $default = $processor->get_default_messaging_settings();
2394 // Validate the value. It should not exceed the maximum size
2395 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2396 debugging(get_string('errortranslatingdefault', 'message'));
2397 $plugindefault = $default;
2399 // Use plugin default setting of 'permitted' is 0
2400 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2401 $plugindefault = $default;
2404 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2405 $loggedin = $loggedoff = null;
2407 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2408 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2409 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2412 return array($permitted, $loggedin, $loggedoff);
2416 * Return a list of page types
2417 * @param string $pagetype current page type
2418 * @param stdClass $parentcontext Block's parent context
2419 * @param stdClass $currentcontext Current context of block
2421 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2422 return array('messages-*'=>get_string('page-message-x', 'message'));
2426 * Is $USER one of the supplied users?
2428 * $user2 will be null if viewing a user's recent conversations
2430 * @param stdClass the first user
2431 * @param stdClass the second user or null
2432 * @return bool True if the current user is one of either $user1 or $user2
2434 function message_current_user_is_involved($user1, $user2) {
2435 global $USER;
2437 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2438 throw new coding_exception('Invalid user object detected. Missing id.');
2441 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2442 return false;
2444 return true;