MDL-36712: Assignment grading with custom scale is affected by the current language
[moodle.git] / message / lib.php
blobcac237b126245788d5ea8da1ff816b908bf2bb1a
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::label(get_string('messagenavigation', 'message'), 'viewing');
512 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
513 echo html_writer::end_tag('fieldset');
514 echo html_writer::end_tag('form');
518 * Load the course contexts for all of the users courses
520 * @param array $courses array of course objects. The courses the user is enrolled in.
521 * @return array of course contexts
523 function message_get_course_contexts($courses) {
524 $coursecontexts = array();
526 foreach($courses as $course) {
527 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
530 return $coursecontexts;
534 * strip off action parameters like 'removecontact'
536 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
537 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
539 function message_remove_url_params($moodleurl) {
540 $newurl = new moodle_url($moodleurl);
541 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
542 return $newurl->out();
546 * Count the number of messages with a field having a specified value.
547 * if $field is empty then return count of the whole array
548 * if $field is non-existent then return 0
550 * @param array $messagearray array of message objects
551 * @param string $field the field to inspect on the message objects
552 * @param string $value the value to test the field against
554 function message_count_messages($messagearray, $field='', $value='') {
555 if (!is_array($messagearray)) return 0;
556 if ($field == '' or empty($messagearray)) return count($messagearray);
558 $count = 0;
559 foreach ($messagearray as $message) {
560 $count += ($message->$field == $value) ? 1 : 0;
562 return $count;
566 * Returns the count of unread messages for user. Either from a specific user or from all users.
568 * @param object $user1 the first user. Defaults to $USER
569 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
570 * @return int the count of $user1's unread messages
572 function message_count_unread_messages($user1=null, $user2=null) {
573 global $USER, $DB;
575 if (empty($user1)) {
576 $user1 = $USER;
579 if (!empty($user2)) {
580 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
581 array($user1->id, $user2->id), "COUNT('id')");
582 } else {
583 return $DB->count_records_select('message', "useridto = ?",
584 array($user1->id), "COUNT('id')");
589 * Count the number of users blocked by $user1
591 * @param object $user1 user object
592 * @return int the number of blocked users
594 function message_count_blocked_users($user1=null) {
595 global $USER, $DB;
597 if (empty($user1)) {
598 $user1 = $USER;
601 $sql = "SELECT count(mc.id)
602 FROM {message_contacts} mc
603 WHERE mc.userid = :userid AND mc.blocked = 1";
604 $params = array('userid' => $user1->id);
606 return $DB->count_records_sql($sql, $params);
610 * Print the search form and search results if a search has been performed
612 * @param boolean $advancedsearch show basic or advanced search form
613 * @param object $user1 the current user
614 * @return boolean true if a search was performed
616 function message_print_search($advancedsearch = false, $user1=null) {
617 $frm = data_submitted();
619 $doingsearch = false;
620 if ($frm) {
621 if (confirm_sesskey()) {
622 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
623 } else {
624 $frm = false;
628 if (!empty($frm->combinedsearch)) {
629 $combinedsearchstring = $frm->combinedsearch;
630 } else {
631 //$combinedsearchstring = get_string('searchcombined','message').'...';
632 $combinedsearchstring = '';
635 if ($doingsearch) {
636 if ($advancedsearch) {
638 $messagesearch = '';
639 if (!empty($frm->keywords)) {
640 $messagesearch = $frm->keywords;
642 $personsearch = '';
643 if (!empty($frm->name)) {
644 $personsearch = $frm->name;
646 include('search_advanced.html');
647 } else {
648 include('search.html');
651 $showicontext = false;
652 message_print_search_results($frm, $showicontext, $user1);
654 return true;
655 } else {
657 if ($advancedsearch) {
658 $personsearch = $messagesearch = '';
659 include('search_advanced.html');
660 } else {
661 include('search.html');
663 return false;
668 * Get the users recent conversations meaning all the people they've recently
669 * sent or received a message from plus the most recent message sent to or received from each other user
671 * @param object $user the current user
672 * @param int $limitfrom can be used for paging
673 * @param int $limitto can be used for paging
674 * @return array
676 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
677 global $DB;
679 $userfields = user_picture::fields('u', array('lastaccess'));
680 //This query retrieves the last message received from and sent to each user
681 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
682 //It then joins with some other tables to get some additional data we need
684 //message ID is used instead of timecreated as it should sort the same and will be much faster
686 //There is a separate query for read and unread queries as they are stored in different tables
687 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
688 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
689 FROM {message_read} mr
690 JOIN (
691 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
692 FROM (
693 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
694 FROM {message_read} mr1
695 WHERE mr1.useridfrom = :userid1
696 AND mr1.notification = 0
697 GROUP BY mr1.useridto
698 UNION
699 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
700 FROM {message_read} mr2
701 WHERE mr2.useridto = :userid2
702 AND mr2.notification = 0
703 GROUP BY mr2.useridfrom
704 ) messages
705 GROUP BY messages.userid
706 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
707 JOIN {user} u ON u.id = messages2.userid
708 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
709 WHERE u.deleted = '0'
710 ORDER BY mr.id DESC";
711 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
712 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
714 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
715 FROM {message} m
716 JOIN (
717 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
718 FROM (
719 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
720 FROM {message} m1
721 WHERE m1.useridfrom = :userid1
722 AND m1.notification = 0
723 GROUP BY m1.useridto
724 UNION
725 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
726 FROM {message} m2
727 WHERE m2.useridto = :userid2
728 AND m2.notification = 0
729 GROUP BY m2.useridfrom
730 ) messages
731 GROUP BY messages.userid
732 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
733 JOIN {user} u ON u.id = messages2.userid
734 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
735 WHERE u.deleted = '0'
736 ORDER BY m.id DESC";
737 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
739 $conversations = array();
741 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
742 //$conversation->id (the array key) is the other user's ID
743 $conversation_arrays = array($unread, $read);
744 foreach ($conversation_arrays as $conversation_array) {
745 foreach ($conversation_array as $conversation) {
746 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
747 $conversations[$conversation->id] = $conversation;
752 // Sort the conversations by $conversation->timecreated, newest to oldest
753 // There may be multiple conversations with the same timecreated
754 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
755 $result = collatorlib::asort_objects_by_property($conversations, 'timecreated', collatorlib::SORT_NUMERIC);
756 $conversations = array_reverse($conversations);
758 return $conversations;
762 * Get the users recent event notifications
764 * @param object $user the current user
765 * @param int $limitfrom can be used for paging
766 * @param int $limitto can be used for paging
767 * @return array
769 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
770 global $DB;
772 $userfields = user_picture::fields('u', array('lastaccess'));
773 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
774 FROM {message_read} mr
775 JOIN {user} u ON u.id=mr.useridfrom
776 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
777 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
778 $params = array('userid1' => $user->id, 'notification' => 1);
780 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
781 return $notifications;
785 * Print the user's recent conversations
787 * @param stdClass $user the current user
788 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
790 function message_print_recent_conversations($user=null, $showicontext=false) {
791 global $USER;
793 echo html_writer::start_tag('p', array('class' => 'heading'));
794 echo get_string('mostrecentconversations', 'message');
795 echo html_writer::end_tag('p');
797 if (empty($user)) {
798 $user = $USER;
801 $conversations = message_get_recent_conversations($user);
803 // Attach context url information to create the "View this conversation" type links
804 foreach($conversations as $conversation) {
805 $conversation->contexturl = new moodle_url("/message/index.php?user2={$conversation->id}");
806 $conversation->contexturlname = get_string('thisconversation', 'message');
809 $showotheruser = true;
810 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
814 * Print the user's recent notifications
816 * @param stdClass $user the current user
818 function message_print_recent_notifications($user=null) {
819 global $USER;
821 echo html_writer::start_tag('p', array('class' => 'heading'));
822 echo get_string('mostrecentnotifications', 'message');
823 echo html_writer::end_tag('p');
825 if (empty($user)) {
826 $user = $USER;
829 $notifications = message_get_recent_notifications($user);
831 $showicontext = false;
832 $showotheruser = false;
833 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
837 * Print a list of recent messages
839 * @param array $messages the messages to display
840 * @param object $user the current user
841 * @param bool $showotheruser display information on the other user?
842 * @param bool $showicontext show text next to the action icons?
843 * @return void
845 function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
846 global $OUTPUT;
847 static $dateformat;
849 if (empty($dateformat)) {
850 $dateformat = get_string('strftimedatetimeshort');
853 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
854 foreach ($messages as $message) {
855 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
857 if ($showotheruser) {
858 if ( $message->contactlistid ) {
859 if ($message->blocked == 0) { /// not blocked
860 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
861 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
862 } else { // blocked
863 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
864 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
866 } else {
867 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
868 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
871 //should we show just the icon or icon and text?
872 $histicontext = 'icon';
873 if ($showicontext) {
874 $histicontext = 'both';
876 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
878 echo html_writer::start_tag('span', array('class' => 'otheruser'));
880 echo html_writer::start_tag('span', array('class' => 'pix'));
881 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
882 echo html_writer::end_tag('span');
884 echo html_writer::start_tag('span', array('class' => 'contact'));
886 $link = new moodle_url("/message/index.php?id=$message->id");
887 $action = null;
888 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
890 echo html_writer::end_tag('span');//end contact
892 echo $strcontact.$strblock.$strhistory;
893 echo html_writer::end_tag('span');//end otheruser
895 $messagetoprint = null;
896 if (!empty($message->smallmessage)) {
897 $messagetoprint = $message->smallmessage;
898 } else {
899 $messagetoprint = $message->fullmessage;
902 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
903 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
904 echo message_format_contexturl($message);
905 echo html_writer::end_tag('div');//end singlemessage
907 echo html_writer::end_tag('div');//end messagerecent
911 * Add the selected user as a contact for the current user
913 * @param int $contactid the ID of the user to add as a contact
914 * @param int $blocked 1 if you wish to block the contact
915 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
916 * Otherwise returns the result of update_record() or insert_record()
918 function message_add_contact($contactid, $blocked=0) {
919 global $USER, $DB;
921 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
922 return false;
925 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
926 /// record already exists - we may be changing blocking status
928 if ($contact->blocked !== $blocked) {
929 /// change to blocking status
930 $contact->blocked = $blocked;
931 return $DB->update_record('message_contacts', $contact);
932 } else {
933 /// no changes to blocking status
934 return true;
937 } else {
938 /// new contact record
939 $contact = new stdClass();
940 $contact->userid = $USER->id;
941 $contact->contactid = $contactid;
942 $contact->blocked = $blocked;
943 return $DB->insert_record('message_contacts', $contact, false);
948 * remove a contact
950 * @param int $contactid the user ID of the contact to remove
951 * @return bool returns the result of delete_records()
953 function message_remove_contact($contactid) {
954 global $USER, $DB;
955 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
959 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
961 * @param int $contactid the user ID of the contact to unblock
962 * @return bool returns the result of delete_records()
964 function message_unblock_contact($contactid) {
965 global $USER, $DB;
966 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
970 * block a user
972 * @param int $contactid the user ID of the user to block
974 function message_block_contact($contactid) {
975 return message_add_contact($contactid, 1);
979 * Load a user's contact record
981 * @param int $contactid the user ID of the user whose contact record you want
982 * @return array message contacts
984 function message_get_contact($contactid) {
985 global $USER, $DB;
986 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
990 * Print the results of a message search
992 * @param mixed $frm submitted form data
993 * @param bool $showicontext show text next to action icons?
994 * @param object $currentuser the current user
995 * @return void
997 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
998 global $USER, $DB, $OUTPUT;
1000 if (empty($currentuser)) {
1001 $currentuser = $USER;
1004 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1006 $personsearch = false;
1007 $personsearchstring = null;
1008 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1009 $personsearch = true;
1010 $personsearchstring = $frm->name;
1011 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1012 $personsearch = true;
1013 $personsearchstring = $frm->combinedsearch;
1016 /// search for person
1017 if ($personsearch) {
1018 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1019 $users = array();
1020 $mycourses = enrol_get_my_courses();
1021 foreach ($mycourses as $mycourse) {
1022 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
1023 foreach ($susers as $suser) $users[$suser->id] = $suser;
1026 } else {
1027 $users = message_search_users(SITEID, $personsearchstring);
1030 if (!empty($users)) {
1031 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1032 echo get_string('userssearchresults', 'message', count($users));
1033 echo html_writer::end_tag('p');
1035 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1036 foreach ($users as $user) {
1038 if ( $user->contactlistid ) {
1039 if ($user->blocked == 0) { /// not blocked
1040 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1041 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1042 } else { // blocked
1043 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1044 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1046 } else {
1047 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1048 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1051 //should we show just the icon or icon and text?
1052 $histicontext = 'icon';
1053 if ($showicontext) {
1054 $histicontext = 'both';
1056 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1058 echo html_writer::start_tag('tr');
1060 echo html_writer::start_tag('td', array('class' => 'pix'));
1061 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1062 echo html_writer::end_tag('td');
1064 echo html_writer::start_tag('td',array('class' => 'contact'));
1065 $action = null;
1066 $link = new moodle_url("/message/index.php?id=$user->id");
1067 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1068 echo html_writer::end_tag('td');
1070 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1071 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1072 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1074 echo html_writer::end_tag('tr');
1076 echo html_writer::end_tag('table');
1078 } else {
1079 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1080 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1081 echo html_writer::end_tag('p');
1085 // search messages for keywords
1086 $messagesearch = false;
1087 $messagesearchstring = null;
1088 if (!empty($frm->keywords)) {
1089 $messagesearch = true;
1090 $messagesearchstring = clean_text(trim($frm->keywords));
1091 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1092 $messagesearch = true;
1093 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1096 if ($messagesearch) {
1097 if ($messagesearchstring) {
1098 $keywords = explode(' ', $messagesearchstring);
1099 } else {
1100 $keywords = array();
1102 $tome = false;
1103 $fromme = false;
1104 $courseid = 'none';
1106 if (empty($frm->keywordsoption)) {
1107 $frm->keywordsoption = 'allmine';
1110 switch ($frm->keywordsoption) {
1111 case 'tome':
1112 $tome = true;
1113 break;
1114 case 'fromme':
1115 $fromme = true;
1116 break;
1117 case 'allmine':
1118 $tome = true;
1119 $fromme = true;
1120 break;
1121 case 'allusers':
1122 $courseid = SITEID;
1123 break;
1124 case 'courseusers':
1125 $courseid = $frm->courseid;
1126 break;
1127 default:
1128 $tome = true;
1129 $fromme = true;
1132 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1134 /// get a list of contacts
1135 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1136 $contacts = array();
1139 /// print heading with number of results
1140 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1141 $countresults = count($messages);
1142 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1143 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1144 } else {
1145 echo get_string('keywordssearchresults', 'message', $countresults);
1147 echo html_writer::end_tag('p');
1149 /// print table headings
1150 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1152 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1153 $headertdend = html_writer::end_tag('td');
1154 echo html_writer::start_tag('tr');
1155 echo $headertdstart.get_string('from').$headertdend;
1156 echo $headertdstart.get_string('to').$headertdend;
1157 echo $headertdstart.get_string('message', 'message').$headertdend;
1158 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1159 echo html_writer::end_tag('tr');
1161 $blockedcount = 0;
1162 $dateformat = get_string('strftimedatetimeshort');
1163 $strcontext = get_string('context', 'message');
1164 foreach ($messages as $message) {
1166 /// ignore messages to and from blocked users unless $frm->includeblocked is set
1167 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1168 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1169 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1172 $blockedcount ++;
1173 continue;
1176 /// load up user to record
1177 if ($message->useridto !== $USER->id) {
1178 $userto = $DB->get_record('user', array('id' => $message->useridto));
1179 $tocontact = (array_key_exists($message->useridto, $contacts) and
1180 ($contacts[$message->useridto]->blocked == 0) );
1181 $toblocked = (array_key_exists($message->useridto, $contacts) and
1182 ($contacts[$message->useridto]->blocked == 1) );
1183 } else {
1184 $userto = false;
1185 $tocontact = false;
1186 $toblocked = false;
1189 /// load up user from record
1190 if ($message->useridfrom !== $USER->id) {
1191 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
1192 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1193 ($contacts[$message->useridfrom]->blocked == 0) );
1194 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1195 ($contacts[$message->useridfrom]->blocked == 1) );
1196 } else {
1197 $userfrom = false;
1198 $fromcontact = false;
1199 $fromblocked = false;
1202 /// find date string for this message
1203 $date = usergetdate($message->timecreated);
1204 $datestring = $date['year'].$date['mon'].$date['mday'];
1206 /// print out message row
1207 echo html_writer::start_tag('tr', array('valign' => 'top'));
1209 echo html_writer::start_tag('td', array('class' => 'contact'));
1210 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1211 echo html_writer::end_tag('td');
1213 echo html_writer::start_tag('td', array('class' => 'contact'));
1214 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1215 echo html_writer::end_tag('td');
1217 echo html_writer::start_tag('td', array('class' => 'summary'));
1218 echo message_get_fragment($message->smallmessage, $keywords);
1219 echo html_writer::start_tag('div', array('class' => 'link'));
1221 //If the user clicks the context link display message sender on the left
1222 //EXCEPT if the current user is in the conversation. Current user == always on the left
1223 $leftsideuserid = $rightsideuserid = null;
1224 if ($currentuser->id == $message->useridto) {
1225 $leftsideuserid = $message->useridto;
1226 $rightsideuserid = $message->useridfrom;
1227 } else {
1228 $leftsideuserid = $message->useridfrom;
1229 $rightsideuserid = $message->useridto;
1231 message_history_link($leftsideuserid, $rightsideuserid, false,
1232 $messagesearchstring, 'm'.$message->id, $strcontext);
1233 echo html_writer::end_tag('div');
1234 echo html_writer::end_tag('td');
1236 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1238 echo html_writer::end_tag('tr');
1242 if ($blockedcount > 0) {
1243 echo html_writer::start_tag('tr');
1244 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1245 echo html_writer::end_tag('tr');
1247 echo html_writer::end_tag('table');
1249 } else {
1250 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1254 if (!$personsearch && !$messagesearch) {
1255 //they didn't enter any search terms
1256 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1259 echo html_writer::end_tag('div');
1263 * Print information on a user. Used when printing search results.
1265 * @param object/bool $user the user to display or false if you just want $USER
1266 * @param bool $iscontact is the user being displayed a contact?
1267 * @param bool $isblocked is the user being displayed blocked?
1268 * @param bool $includeicontext include text next to the action icons?
1269 * @return void
1271 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1272 global $USER, $OUTPUT;
1274 if ($user === false) {
1275 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
1276 } else {
1277 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1278 echo '&nbsp;';
1280 $return = false;
1281 $script = null;
1282 if ($iscontact) {
1283 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1284 } else {
1285 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1287 echo '&nbsp;';
1288 if ($isblocked) {
1289 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1290 } else {
1291 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1294 $popupoptions = array(
1295 'height' => MESSAGE_DISCUSSION_HEIGHT,
1296 'width' => MESSAGE_DISCUSSION_WIDTH,
1297 'menubar' => false,
1298 'location' => false,
1299 'status' => true,
1300 'scrollbars' => true,
1301 'resizable' => true);
1303 $link = new moodle_url("/message/index.php?id=$user->id");
1304 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1305 $action = null;
1306 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1312 * Print a message contact link
1314 * @param int $userid the ID of the user to apply to action to
1315 * @param string $linktype can be add, remove, block or unblock
1316 * @param bool $return if true return the link as a string. If false echo the link.
1317 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1318 * @param bool $text include text next to the icons?
1319 * @param bool $icon include a graphical icon?
1320 * @return string if $return is true otherwise bool
1322 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1323 global $OUTPUT, $PAGE;
1325 //hold onto the strings as we're probably creating a bunch of links
1326 static $str;
1328 if (empty($script)) {
1329 //strip off previous action params like 'removecontact'
1330 $script = message_remove_url_params($PAGE->url);
1333 if (empty($str->blockcontact)) {
1334 $str = new stdClass();
1335 $str->blockcontact = get_string('blockcontact', 'message');
1336 $str->unblockcontact = get_string('unblockcontact', 'message');
1337 $str->removecontact = get_string('removecontact', 'message');
1338 $str->addcontact = get_string('addcontact', 'message');
1341 $command = $linktype.'contact';
1342 $string = $str->{$command};
1344 $safealttext = s($string);
1346 $safestring = '';
1347 if (!empty($text)) {
1348 $safestring = $safealttext;
1351 $img = '';
1352 if ($icon) {
1353 $iconpath = null;
1354 switch ($linktype) {
1355 case 'block':
1356 $iconpath = 't/block';
1357 break;
1358 case 'unblock':
1359 $iconpath = 't/userblue';
1360 break;
1361 case 'remove':
1362 $iconpath = 'i/cross_red_big';
1363 break;
1364 case 'add':
1365 default:
1366 $iconpath = 't/addgreen';
1369 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1372 $output = '<span class="'.$linktype.'contact">'.
1373 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1374 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1375 $img.
1376 $safestring.'</a></span>';
1378 if ($return) {
1379 return $output;
1380 } else {
1381 echo $output;
1382 return true;
1387 * echo or return a link to take the user to the full message history between themselves and another user
1389 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1390 * @param int $userid2 the ID of the other user
1391 * @param bool $return true to return the link as a string. False to echo the link.
1392 * @param string $keywords any keywords to highlight in the message history
1393 * @param string $position anchor name to jump to within the message history
1394 * @param string $linktext optionally specify the link text
1395 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1397 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1398 global $OUTPUT;
1399 static $strmessagehistory;
1401 if (empty($strmessagehistory)) {
1402 $strmessagehistory = get_string('messagehistory', 'message');
1405 if ($position) {
1406 $position = "#$position";
1408 if ($keywords) {
1409 $keywords = "&search=".urlencode($keywords);
1412 if ($linktext == 'icon') { // Icon only
1413 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1414 } else if ($linktext == 'both') { // Icon and standard name
1415 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
1416 $fulllink .= '&nbsp;'.$strmessagehistory;
1417 } else if ($linktext) { // Custom name
1418 $fulllink = $linktext;
1419 } else { // Standard name only
1420 $fulllink = $strmessagehistory;
1423 $popupoptions = array(
1424 'height' => 500,
1425 'width' => 500,
1426 'menubar' => false,
1427 'location' => false,
1428 'status' => true,
1429 'scrollbars' => true,
1430 'resizable' => true);
1432 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1433 $action = null;
1434 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1436 $str = '<span class="history">'.$str.'</span>';
1438 if ($return) {
1439 return $str;
1440 } else {
1441 echo $str;
1442 return true;
1448 * Search through course users
1450 * If $coursid specifies the site course then this function searches
1451 * through all undeleted and confirmed users
1452 * @param int $courseid The course in question.
1453 * @param string $searchtext the text to search for
1454 * @param string $sort the column name to order by
1455 * @param string $exceptions comma separated list of user IDs to exclude
1456 * @return array An array of {@link $USER} records.
1458 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
1459 global $CFG, $USER, $DB;
1461 $fullname = $DB->sql_fullname();
1463 if (!empty($exceptions)) {
1464 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1465 } else {
1466 $except = '';
1469 if (!empty($sort)) {
1470 $order = ' ORDER BY '. $sort;
1471 } else {
1472 $order = '';
1475 $ufields = user_picture::fields('u');
1476 if (!$courseid or $courseid == SITEID) {
1477 $params = array($USER->id, "%$searchtext%");
1478 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1479 FROM {user} u
1480 LEFT JOIN {message_contacts} mc
1481 ON mc.contactid = u.id AND mc.userid = ?
1482 WHERE u.deleted = '0' AND u.confirmed = '1'
1483 AND (".$DB->sql_like($fullname, '?', false).")
1484 $except
1485 $order", $params);
1486 } else {
1487 //TODO: add enabled enrolment join here (skodak)
1488 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1489 $contextlists = get_related_contexts_string($context);
1491 // everyone who has a role assignment in this course or higher
1492 $params = array($USER->id, "%$searchtext%");
1493 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1494 FROM {user} u
1495 JOIN {role_assignments} ra ON ra.userid = u.id
1496 LEFT JOIN {message_contacts} mc
1497 ON mc.contactid = u.id AND mc.userid = ?
1498 WHERE u.deleted = '0' AND u.confirmed = '1'
1499 AND ra.contextid $contextlists
1500 AND (".$DB->sql_like($fullname, '?', false).")
1501 $except
1502 $order", $params);
1504 return $users;
1509 * search a user's messages
1511 * @param array $searchterms an array of search terms (strings)
1512 * @param bool $fromme include messages from the user?
1513 * @param bool $tome include messages to the user?
1514 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1515 * @param int $userid the user ID of the current user
1516 * @return mixed An array of messages or false if no matching messages were found
1518 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1519 /// Returns a list of posts found using an array of search terms
1520 /// eg word +word -word
1522 global $CFG, $USER, $DB;
1524 // If user is searching all messages check they are allowed to before doing anything else
1525 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) {
1526 print_error('accessdenied','admin');
1529 /// If no userid sent then assume current user
1530 if ($userid == 0) $userid = $USER->id;
1532 /// Some differences in SQL syntax
1533 if ($DB->sql_regex_supported()) {
1534 $REGEXP = $DB->sql_regex(true);
1535 $NOTREGEXP = $DB->sql_regex(false);
1538 $searchcond = array();
1539 $params = array();
1540 $i = 0;
1542 //preprocess search terms to check whether we have at least 1 eligible search term
1543 //if we do we can drop words around it like 'a'
1544 $dropshortwords = false;
1545 foreach ($searchterms as $searchterm) {
1546 if (strlen($searchterm) >= 2) {
1547 $dropshortwords = true;
1551 foreach ($searchterms as $searchterm) {
1552 $i++;
1554 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1556 if ($dropshortwords && strlen($searchterm) < 2) {
1557 continue;
1559 /// Under Oracle and MSSQL, trim the + and - operators and perform
1560 /// simpler LIKE search
1561 if (!$DB->sql_regex_supported()) {
1562 if (substr($searchterm, 0, 1) == '-') {
1563 $NOT = true;
1565 $searchterm = trim($searchterm, '+-');
1568 if (substr($searchterm,0,1) == "+") {
1569 $searchterm = substr($searchterm,1);
1570 $searchterm = preg_quote($searchterm, '|');
1571 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1572 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1574 } else if (substr($searchterm,0,1) == "-") {
1575 $searchterm = substr($searchterm,1);
1576 $searchterm = preg_quote($searchterm, '|');
1577 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1578 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1580 } else {
1581 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1582 $params['ss'.$i] = "%$searchterm%";
1586 if (empty($searchcond)) {
1587 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1588 $params['ss1'] = "%";
1589 } else {
1590 $searchcond = implode(" AND ", $searchcond);
1593 /// There are several possibilities
1594 /// 1. courseid = SITEID : The admin is searching messages by all users
1595 /// 2. courseid = ?? : A teacher is searching messages by users in
1596 /// one of their courses - currently disabled
1597 /// 3. courseid = none : User is searching their own messages;
1598 /// a. Messages from user
1599 /// b. Messages to user
1600 /// c. Messages to and from user
1602 if ($courseid == SITEID) { /// admin is searching all messages
1603 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1604 FROM {message_read} m
1605 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1606 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1607 FROM {message} m
1608 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1610 } else if ($courseid !== 'none') {
1611 /// This has not been implemented due to security concerns
1612 $m_read = array();
1613 $m_unread = array();
1615 } else {
1617 if ($fromme and $tome) {
1618 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1619 $params['userid1'] = $userid;
1620 $params['userid2'] = $userid;
1622 } else if ($fromme) {
1623 $searchcond .= " AND m.useridfrom=:userid";
1624 $params['userid'] = $userid;
1626 } else if ($tome) {
1627 $searchcond .= " AND m.useridto=:userid";
1628 $params['userid'] = $userid;
1631 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1632 FROM {message_read} m
1633 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1634 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1635 FROM {message} m
1636 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1640 /// The keys may be duplicated in $m_read and $m_unread so we can't
1641 /// do a simple concatenation
1642 $messages = array();
1643 foreach ($m_read as $m) {
1644 $messages[] = $m;
1646 foreach ($m_unread as $m) {
1647 $messages[] = $m;
1650 return (empty($messages)) ? false : $messages;
1654 * Given a message object that we already know has a long message
1655 * this function truncates the message nicely to the first
1656 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1658 * @param string $message the message
1659 * @param int $minlength the minimum length to trim the message to
1660 * @return string the shortened message
1662 function message_shorten_message($message, $minlength = 0) {
1663 $i = 0;
1664 $tag = false;
1665 $length = strlen($message);
1666 $count = 0;
1667 $stopzone = false;
1668 $truncate = 0;
1669 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1672 for ($i=0; $i<$length; $i++) {
1673 $char = $message[$i];
1675 switch ($char) {
1676 case "<":
1677 $tag = true;
1678 break;
1679 case ">":
1680 $tag = false;
1681 break;
1682 default:
1683 if (!$tag) {
1684 if ($stopzone) {
1685 if ($char == '.' or $char == ' ') {
1686 $truncate = $i+1;
1687 break 2;
1690 $count++;
1692 break;
1694 if (!$stopzone) {
1695 if ($count > $minlength) {
1696 $stopzone = true;
1701 if (!$truncate) {
1702 $truncate = $i;
1705 return substr($message, 0, $truncate);
1710 * Given a string and an array of keywords, this function looks
1711 * for the first keyword in the string, and then chops out a
1712 * small section from the text that shows that word in context.
1714 * @param string $message the text to search
1715 * @param array $keywords array of keywords to find
1717 function message_get_fragment($message, $keywords) {
1719 $fullsize = 160;
1720 $halfsize = (int)($fullsize/2);
1722 $message = strip_tags($message);
1724 foreach ($keywords as $keyword) { // Just get the first one
1725 if ($keyword !== '') {
1726 break;
1729 if (empty($keyword)) { // None found, so just return start of message
1730 return message_shorten_message($message, 30);
1733 $leadin = $leadout = '';
1735 /// Find the start of the fragment
1736 $start = 0;
1737 $length = strlen($message);
1739 $pos = strpos($message, $keyword);
1740 if ($pos > $halfsize) {
1741 $start = $pos - $halfsize;
1742 $leadin = '...';
1744 /// Find the end of the fragment
1745 $end = $start + $fullsize;
1746 if ($end > $length) {
1747 $end = $length;
1748 } else {
1749 $leadout = '...';
1752 /// Pull out the fragment and format it
1754 $fragment = substr($message, $start, $end - $start);
1755 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1756 return $fragment;
1760 * Retrieve the messages between two users
1762 * @param object $user1 the current user
1763 * @param object $user2 the other user
1764 * @param int $limitnum the maximum number of messages to retrieve
1765 * @param bool $viewingnewmessages are we currently viewing new messages?
1767 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1768 global $DB, $CFG;
1770 $messages = array();
1772 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1773 //desc to get the last $limitnum messages then flip the order in php
1774 $sort = 'asc';
1775 if ($limitnum>0) {
1776 $sort = 'desc';
1779 $notificationswhere = null;
1780 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1781 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1782 $notificationswhere = 'AND notification=0';
1785 //prevent notifications of your own actions appearing in your own message history
1786 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1788 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1789 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1790 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1791 "timecreated $sort", '*', 0, $limitnum)) {
1792 foreach ($messages_read as $message) {
1793 $messages[] = $message;
1796 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1797 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1798 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
1799 "timecreated $sort", '*', 0, $limitnum)) {
1800 foreach ($messages_new as $message) {
1801 $messages[] = $message;
1805 $result = collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);
1807 //if we only want the last $limitnum messages
1808 $messagecount = count($messages);
1809 if ($limitnum > 0 && $messagecount > $limitnum) {
1810 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
1813 return $messages;
1817 * Print the message history between two users
1819 * @param object $user1 the current user
1820 * @param object $user2 the other user
1821 * @param string $search search terms to highlight
1822 * @param int $messagelimit maximum number of messages to return
1823 * @param string $messagehistorylink the html for the message history link or false
1824 * @param bool $viewingnewmessages are we currently viewing new messages?
1826 function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
1827 global $CFG, $OUTPUT;
1829 echo $OUTPUT->box_start('center');
1830 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1831 echo html_writer::start_tag('tr');
1833 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1834 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1835 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1836 echo html_writer::end_tag('td');
1838 echo html_writer::start_tag('td', array('align' => 'center'));
1839 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1840 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1841 echo html_writer::end_tag('td');
1843 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1844 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1845 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
1847 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1848 $incontactlist = $user2->iscontact;
1849 $isblocked = $user2->isblocked;
1851 $script = null;
1852 $text = true;
1853 $icon = false;
1855 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1856 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1857 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1859 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
1862 echo html_writer::end_tag('td');
1863 echo html_writer::end_tag('tr');
1864 echo html_writer::end_tag('table');
1865 echo $OUTPUT->box_end();
1867 if (!empty($messagehistorylink)) {
1868 echo $messagehistorylink;
1871 /// Get all the messages and print them
1872 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
1873 $tablecontents = '';
1875 $current = new stdClass();
1876 $current->mday = '';
1877 $current->month = '';
1878 $current->year = '';
1879 $messagedate = get_string('strftimetime');
1880 $blockdate = get_string('strftimedaydate');
1881 foreach ($messages as $message) {
1882 if ($message->notification) {
1883 $notificationclass = ' notification';
1884 } else {
1885 $notificationclass = null;
1887 $date = usergetdate($message->timecreated);
1888 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1889 $current->mday = $date['mday'];
1890 $current->month = $date['month'];
1891 $current->year = $date['year'];
1893 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1894 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1896 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
1899 $formatted_message = $side = null;
1900 if ($message->useridfrom == $user1->id) {
1901 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1902 $side = 'left';
1903 } else {
1904 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1905 $side = 'right';
1907 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
1910 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
1911 } else {
1912 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
1917 * Format a message for display in the message history
1919 * @param object $message the message object
1920 * @param string $format optional date format
1921 * @param string $keywords keywords to highlight
1922 * @param string $class CSS class to apply to the div around the message
1923 * @return string the formatted message
1925 function message_format_message($message, $format='', $keywords='', $class='other') {
1927 static $dateformat;
1929 //if we haven't previously set the date format or they've supplied a new one
1930 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
1931 if ($format) {
1932 $dateformat = $format;
1933 } else {
1934 $dateformat = get_string('strftimedatetimeshort');
1937 $time = userdate($message->timecreated, $dateformat);
1938 $options = new stdClass();
1939 $options->para = false;
1941 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1942 if (!empty($message->smallmessage)) {
1943 $messagetext = $message->smallmessage;
1944 } else {
1945 $messagetext = $message->fullmessage;
1947 if ($message->fullmessageformat == FORMAT_HTML) {
1948 //dont escape html tags by calling s() if html format or they will display in the UI
1949 $messagetext = html_to_text(format_text($messagetext, $message->fullmessageformat, $options));
1950 } else {
1951 $messagetext = format_text(s($messagetext), $message->fullmessageformat, $options);
1954 $messagetext .= message_format_contexturl($message);
1956 if ($keywords) {
1957 $messagetext = highlight($keywords, $messagetext);
1960 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1964 * Format a the context url and context url name of a message for display
1966 * @param object $message the message object
1967 * @return string the formatted string
1969 function message_format_contexturl($message) {
1970 $s = null;
1972 if (!empty($message->contexturl)) {
1973 $displaytext = null;
1974 if (!empty($message->contexturlname)) {
1975 $displaytext= $message->contexturlname;
1976 } else {
1977 $displaytext= $message->contexturl;
1979 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1980 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1981 $s .= html_writer::end_tag('div');
1984 return $s;
1988 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1990 * @param object $userfrom the message sender
1991 * @param object $userto the message recipient
1992 * @param string $message the message
1993 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
1994 * @return int|false the ID of the new message or false
1996 function message_post_message($userfrom, $userto, $message, $format) {
1997 global $SITE, $CFG, $USER;
1999 $eventdata = new stdClass();
2000 $eventdata->component = 'moodle';
2001 $eventdata->name = 'instantmessage';
2002 $eventdata->userfrom = $userfrom;
2003 $eventdata->userto = $userto;
2005 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2006 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2008 if ($format == FORMAT_HTML) {
2009 $eventdata->fullmessagehtml = $message;
2010 //some message processors may revert to sending plain text even if html is supplied
2011 //so we keep both plain and html versions if we're intending to send html
2012 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2013 } else {
2014 $eventdata->fullmessage = $message;
2015 $eventdata->fullmessagehtml = '';
2018 $eventdata->fullmessageformat = $format;
2019 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2021 $s = new stdClass();
2022 $s->sitename = format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
2023 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2025 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2026 if (!empty($eventdata->fullmessage)) {
2027 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2029 if (!empty($eventdata->fullmessagehtml)) {
2030 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2033 $eventdata->timecreated = time();
2034 return message_send($eventdata);
2038 * Print a row of contactlist displaying user picture, messages waiting and
2039 * block links etc
2041 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2042 * @param bool $incontactlist is the user a contact of ours?
2043 * @param bool $isblocked is the user blocked?
2044 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2045 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2046 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2047 * @return void
2049 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2050 global $OUTPUT, $USER;
2051 $fullname = fullname($contact);
2052 $fullnamelink = $fullname;
2054 $linkclass = '';
2055 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2056 $linkclass = 'messageselecteduser';
2059 /// are there any unread messages for this contact?
2060 if ($contact->messagecount > 0 ){
2061 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2064 $strcontact = $strblock = $strhistory = null;
2066 if ($showactionlinks) {
2067 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2068 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2069 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2072 echo html_writer::start_tag('tr');
2073 echo html_writer::start_tag('td', array('class' => 'pix'));
2074 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2075 echo html_writer::end_tag('td');
2077 echo html_writer::start_tag('td', array('class' => 'contact'));
2079 $popupoptions = array(
2080 'height' => MESSAGE_DISCUSSION_HEIGHT,
2081 'width' => MESSAGE_DISCUSSION_WIDTH,
2082 'menubar' => false,
2083 'location' => false,
2084 'status' => true,
2085 'scrollbars' => true,
2086 'resizable' => true);
2088 $link = $action = null;
2089 if (!empty($selectcontacturl)) {
2090 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2091 } else {
2092 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2093 $link = new moodle_url("/message/index.php?id=$contact->id");
2094 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2096 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2098 echo html_writer::end_tag('td');
2100 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2102 echo html_writer::end_tag('tr');
2106 * Constructs the add/remove contact link to display next to other users
2108 * @param bool $incontactlist is the user a contact
2109 * @param bool $isblocked is the user blocked
2110 * @param stdClass $contact contact object
2111 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2112 * @param bool $text include text next to the icons?
2113 * @param bool $icon include a graphical icon?
2114 * @return string
2116 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2117 $strcontact = '';
2119 if($incontactlist){
2120 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2121 } else if ($isblocked) {
2122 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2123 } else{
2124 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2127 return $strcontact;
2131 * Constructs the block contact link to display next to other users
2133 * @param bool $incontactlist is the user a contact?
2134 * @param bool $isblocked is the user blocked?
2135 * @param stdClass $contact contact object
2136 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2137 * @param bool $text include text next to the icons?
2138 * @param bool $icon include a graphical icon?
2139 * @return string
2141 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2142 $strblock = '';
2144 //commented out to allow the user to block a contact without having to remove them first
2145 /*if ($incontactlist) {
2146 //$strblock = '';
2147 } else*/
2148 if ($isblocked) {
2149 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2150 } else{
2151 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2154 return $strblock;
2158 * Moves messages from a particular user from the message table (unread messages) to message_read
2159 * This is typically only used when a user is deleted
2161 * @param object $userid User id
2162 * @return boolean success
2164 function message_move_userfrom_unread2read($userid) {
2165 global $DB;
2167 // move all unread messages from message table to message_read
2168 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2169 foreach ($messages as $message) {
2170 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2173 return true;
2177 * marks ALL messages being sent from $fromuserid to $touserid as read
2179 * @param int $touserid the id of the message recipient
2180 * @param int $fromuserid the id of the message sender
2181 * @return void
2183 function message_mark_messages_read($touserid, $fromuserid){
2184 global $DB;
2186 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2187 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2189 foreach ($messages as $message) {
2190 message_mark_message_read($message, time());
2193 $messages->close();
2197 * Mark a single message as read
2199 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2200 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2201 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2202 * @return int the ID of the message in the message_read table
2204 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2205 global $DB;
2207 $message->timeread = $timeread;
2209 $messageid = $message->id;
2210 unset($message->id);//unset because it will get a new id on insert into message_read
2212 //If any processors have pending actions abort them
2213 if (!$messageworkingempty) {
2214 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2216 $messagereadid = $DB->insert_record('message_read', $message);
2217 $DB->delete_records('message', array('id' => $messageid));
2218 return $messagereadid;
2222 * A helper function that prints a formatted heading
2224 * @param string $title the heading to display
2225 * @param int $colspan
2226 * @return void
2228 function message_print_heading($title, $colspan=3) {
2229 echo html_writer::start_tag('tr');
2230 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2231 echo html_writer::end_tag('tr');
2235 * Get all message processors, validate corresponding plugin existance and
2236 * system configuration
2238 * @param bool $ready only return ready-to-use processors
2239 * @return mixed $processors array of objects containing information on message processors
2241 function get_message_processors($ready = false) {
2242 global $DB, $CFG;
2244 static $processors;
2246 if (empty($processors)) {
2247 // Get all processors, ensure the name column is the first so it will be the array key
2248 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2249 foreach ($processors as &$processor){
2250 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2251 if (is_readable($processorfile)) {
2252 include_once($processorfile);
2253 $processclass = 'message_output_' . $processor->name;
2254 if (class_exists($processclass)) {
2255 $pclass = new $processclass();
2256 $processor->object = $pclass;
2257 $processor->configured = 0;
2258 if ($pclass->is_system_configured()) {
2259 $processor->configured = 1;
2261 $processor->hassettings = 0;
2262 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2263 $processor->hassettings = 1;
2265 $processor->available = 1;
2266 } else {
2267 print_error('errorcallingprocessor', 'message');
2269 } else {
2270 $processor->available = 0;
2274 if ($ready) {
2275 // Filter out enabled and system_configured processors
2276 $readyprocessors = $processors;
2277 foreach ($readyprocessors as $readyprocessor) {
2278 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2279 unset($readyprocessors[$readyprocessor->name]);
2282 return $readyprocessors;
2285 return $processors;
2289 * Get all message providers, validate their plugin existance and
2290 * system configuration
2292 * @return mixed $processors array of objects containing information on message processors
2294 function get_message_providers() {
2295 global $CFG, $DB;
2296 require_once($CFG->libdir . '/pluginlib.php');
2297 $pluginman = plugin_manager::instance();
2299 $providers = $DB->get_records('message_providers', null, 'name');
2301 // Remove all the providers whose plugins are disabled or don't exist
2302 foreach ($providers as $providerid => $provider) {
2303 $plugin = $pluginman->get_plugin_info($provider->component);
2304 if ($plugin) {
2305 if ($plugin->get_status() === plugin_manager::PLUGIN_STATUS_MISSING) {
2306 unset($providers[$providerid]); // Plugins does not exist
2307 continue;
2309 if ($plugin->is_enabled() === false) {
2310 unset($providers[$providerid]); // Plugin disabled
2311 continue;
2315 return $providers;
2319 * Get an instance of the message_output class for one of the output plugins.
2320 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2321 * @return message_output message_output the requested class.
2323 function get_message_processor($type) {
2324 global $CFG;
2326 // Note, we cannot use the get_message_processors function here, becaues this
2327 // code is called during install after installing each messaging plugin, and
2328 // get_message_processors caches the list of installed plugins.
2330 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2331 if (!is_readable($processorfile)) {
2332 throw new coding_exception('Unknown message processor type ' . $type);
2335 include_once($processorfile);
2337 $processclass = 'message_output_' . $type;
2338 if (!class_exists($processclass)) {
2339 throw new coding_exception('Message processor ' . $type .
2340 ' does not define the right class');
2343 return new $processclass();
2347 * Get messaging outputs default (site) preferences
2349 * @return object $processors object containing information on message processors
2351 function get_message_output_default_preferences() {
2352 return get_config('message');
2356 * Translate message default settings from binary value to the array of string
2357 * representing the settings to be stored. Also validate the provided value and
2358 * use default if it is malformed.
2360 * @param int $plugindefault Default setting suggested by plugin
2361 * @param string $processorname The name of processor
2362 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2364 function translate_message_default_setting($plugindefault, $processorname) {
2365 // Preset translation arrays
2366 $permittedvalues = array(
2367 0x04 => 'disallowed',
2368 0x08 => 'permitted',
2369 0x0c => 'forced',
2372 $loggedinstatusvalues = array(
2373 0x00 => null, // use null if loggedin/loggedoff is not defined
2374 0x01 => 'loggedin',
2375 0x02 => 'loggedoff',
2378 // define the default setting
2379 $processor = get_message_processor($processorname);
2380 $default = $processor->get_default_messaging_settings();
2382 // Validate the value. It should not exceed the maximum size
2383 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2384 debugging(get_string('errortranslatingdefault', 'message'));
2385 $plugindefault = $default;
2387 // Use plugin default setting of 'permitted' is 0
2388 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2389 $plugindefault = $default;
2392 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2393 $loggedin = $loggedoff = null;
2395 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2396 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2397 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2400 return array($permitted, $loggedin, $loggedoff);
2404 * Return a list of page types
2405 * @param string $pagetype current page type
2406 * @param stdClass $parentcontext Block's parent context
2407 * @param stdClass $currentcontext Current context of block
2409 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2410 return array('messages-*'=>get_string('page-message-x', 'message'));
2414 * Is $USER one of the supplied users?
2416 * $user2 will be null if viewing a user's recent conversations
2418 * @param stdClass the first user
2419 * @param stdClass the second user or null
2420 * @return bool True if the current user is one of either $user1 or $user2
2422 function message_current_user_is_involved($user1, $user2) {
2423 global $USER;
2425 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
2426 throw new coding_exception('Invalid user object detected. Missing id.');
2429 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
2430 return false;
2432 return true;