MDL-52136 mod_forum: forum_post is templatable
[moodle.git] / message / lib.php
blob9ded749f2dcf1d14d8154466491eccb273856597
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions for messaging
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir.'/eventslib.php');
27 define ('MESSAGE_SHORTLENGTH', 300);
29 define ('MESSAGE_DISCUSSION_WIDTH',600);
30 define ('MESSAGE_DISCUSSION_HEIGHT',500);
32 define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
34 define('MESSAGE_HISTORY_SHORT',0);
35 define('MESSAGE_HISTORY_ALL',1);
37 define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38 define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39 define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40 define('MESSAGE_VIEW_CONTACTS','contacts');
41 define('MESSAGE_VIEW_BLOCKED','blockedusers');
42 define('MESSAGE_VIEW_COURSE','course_');
43 define('MESSAGE_VIEW_SEARCH','search');
45 define('MESSAGE_SEARCH_MAX_RESULTS', 200);
47 define('MESSAGE_CONTACTS_PER_PAGE',10);
48 define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
50 /**
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
60 define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61 define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
63 define('MESSAGE_DISALLOWED', 0x04); // 0100
64 define('MESSAGE_PERMITTED', 0x08); // 1000
65 define('MESSAGE_FORCED', 0x0c); // 1100
67 define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
69 /**
70 * Set default value for default outputs permitted setting
72 define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
74 /**
75 * Print the selector that allows the user to view their contacts, course participants, their recent
76 * conversations etc
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
86 * @param bool $showactionlinks show action links (add/remove contact etc)
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
88 * @return void
90 function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
91 global $PAGE;
93 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
95 //if 0 unread messages and they've requested unread messages then show contacts
96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97 $viewing = MESSAGE_VIEW_CONTACTS;
100 //if they have no blocked users and they've requested blocked users switch them over to contacts
101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102 $viewing = MESSAGE_VIEW_CONTACTS;
105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
118 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
120 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
121 message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
123 $courseidtoshow = intval(substr($viewing, 7));
125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
133 // Only show the search button if we're viewing our own contacts.
134 if ($viewing == MESSAGE_VIEW_CONTACTS && $user2 == null) {
135 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
136 echo html_writer::start_tag('fieldset');
137 $managebuttonclass = 'visible';
138 $strmanagecontacts = get_string('search','message');
139 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
140 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
141 echo html_writer::end_tag('fieldset');
142 echo html_writer::end_tag('form');
145 echo html_writer::end_tag('div');
149 * Print course participants. Called by message_print_contact_selector()
151 * @param object $context the course context
152 * @param int $courseid the course ID
153 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
154 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
155 * @param string $titletodisplay Optionally specify a title to display above the participants
156 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
157 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
158 * @return void
160 function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
161 global $DB, $USER, $PAGE, $OUTPUT;
163 if (empty($titletodisplay)) {
164 $titletodisplay = get_string('participants');
167 $countparticipants = count_enrolled_users($context);
169 list($esql, $params) = get_enrolled_sql($context);
170 $params['mcuserid'] = $USER->id;
171 $ufields = user_picture::fields('u');
173 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
174 FROM {user} u
175 JOIN ($esql) je ON je.id = u.id
176 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
177 WHERE u.deleted = 0";
179 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
181 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
182 $pagingbar->maxdisplay = 4;
183 echo $OUTPUT->render($pagingbar);
185 echo html_writer::start_tag('div', array('id' => 'message_participants', 'class' => 'boxaligncenter'));
187 echo html_writer::tag('div' , $titletodisplay, array('class' => 'heading'));
189 $users = '';
190 foreach ($participants as $participant) {
191 if ($participant->id != $USER->id) {
193 $iscontact = false;
194 $isblocked = false;
195 if ( $participant->contactlistid ) {
196 if ($participant->blocked == 0) {
197 // Is contact. Is not blocked.
198 $iscontact = true;
199 $isblocked = false;
200 } else {
201 // Is blocked.
202 $iscontact = false;
203 $isblocked = true;
207 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
208 $content = message_print_contactlist_user($participant, $iscontact, $isblocked,
209 $contactselecturl, $showactionlinks, $user2);
210 $users .= html_writer::tag('li', $content);
213 if (strlen($users) > 0) {
214 echo html_writer::tag('ul', $users, array('id' => 'message-courseparticipants', 'class' => 'message-contacts'));
217 echo html_writer::end_tag('div');
221 * Retrieve users blocked by $user1
223 * @param object $user1 the user whose messages are being viewed
224 * @param object $user2 the user $user1 is talking to. If they are being blocked
225 * they will have a variable called 'isblocked' added to their user object
226 * @return array the users blocked by $user1
228 function message_get_blocked_users($user1=null, $user2=null) {
229 global $DB, $USER;
231 if (empty($user1)) {
232 $user1 = $USER;
235 if (!empty($user2)) {
236 $user2->isblocked = false;
239 $blockedusers = array();
241 $userfields = user_picture::fields('u', array('lastaccess'));
242 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
243 FROM {message_contacts} mc
244 JOIN {user} u ON u.id = mc.contactid
245 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
246 WHERE u.deleted = 0 AND mc.userid = :user1id2 AND mc.blocked = 1
247 GROUP BY $userfields
248 ORDER BY u.firstname ASC";
249 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
251 foreach($rs as $rd) {
252 $blockedusers[] = $rd;
254 if (!empty($user2) && $user2->id == $rd->id) {
255 $user2->isblocked = true;
258 $rs->close();
260 return $blockedusers;
264 * Print users blocked by $user1. Called by message_print_contact_selector()
266 * @param array $blockedusers the users blocked by $user1
267 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
268 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
269 * @param string $titletodisplay Optionally specify a title to display above the participants
270 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
271 * @return void
273 function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
274 global $OUTPUT;
276 $countblocked = count($blockedusers);
278 echo html_writer::start_tag('div', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
280 if (!empty($titletodisplay)) {
281 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
284 if ($countblocked) {
285 echo html_writer::tag('div', get_string('blockedusers', 'message', $countblocked), array('class' => 'heading'));
287 $isuserblocked = true;
288 $isusercontact = false;
289 $blockeduserslist = '';
290 foreach ($blockedusers as $blockeduser) {
291 $content = message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked,
292 $contactselecturl, $showactionlinks, $user2);
293 $blockeduserslist .= html_writer::tag('li', $content);
295 echo html_writer::tag('ul', $blockeduserslist, array('id' => 'message-blockedusers', 'class' => 'message-contacts'));
298 echo html_writer::end_tag('div');
302 * Retrieve $user1's contacts (online, offline and strangers)
304 * @param object $user1 the user whose messages are being viewed
305 * @param object $user2 the user $user1 is talking to. If they are a contact
306 * they will have a variable called 'iscontact' added to their user object
307 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
309 function message_get_contacts($user1=null, $user2=null) {
310 global $DB, $CFG, $USER;
312 if (empty($user1)) {
313 $user1 = $USER;
316 if (!empty($user2)) {
317 $user2->iscontact = false;
320 $timetoshowusers = 300; //Seconds default
321 if (isset($CFG->block_online_users_timetosee)) {
322 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
325 // time which a user is counting as being active since
326 $timefrom = time()-$timetoshowusers;
328 // people in our contactlist who are online
329 $onlinecontacts = array();
330 // people in our contactlist who are offline
331 $offlinecontacts = array();
332 // people who are not in our contactlist but have sent us a message
333 $strangers = array();
335 $userfields = user_picture::fields('u', array('lastaccess'));
337 // get all in our contactlist who are not blocked in our contact list
338 // and count messages we have waiting from each of them
339 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
340 FROM {message_contacts} mc
341 JOIN {user} u ON u.id = mc.contactid
342 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
343 WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0
344 GROUP BY $userfields
345 ORDER BY u.firstname ASC";
347 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
348 foreach ($rs as $rd) {
349 if ($rd->lastaccess >= $timefrom) {
350 // they have been active recently, so are counted online
351 $onlinecontacts[] = $rd;
353 } else {
354 $offlinecontacts[] = $rd;
357 if (!empty($user2) && $user2->id == $rd->id) {
358 $user2->iscontact = true;
361 $rs->close();
363 // get messages from anyone who isn't in our contact list and count the number
364 // of messages we have from each of them
365 $strangersql = "SELECT $userfields, count(m.id) as messagecount
366 FROM {message} m
367 JOIN {user} u ON u.id = m.useridfrom
368 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
369 WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ?
370 GROUP BY $userfields
371 ORDER BY u.firstname ASC";
373 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
374 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
375 foreach ($rs as $rd) {
376 $strangers[$rd->id] = $rd;
378 $rs->close();
380 // Add noreply user and support user to the list, if they don't exist.
381 $supportuser = core_user::get_support_user();
382 if (!isset($strangers[$supportuser->id])) {
383 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
384 if ($supportuser->messagecount > 0) {
385 $strangers[$supportuser->id] = $supportuser;
389 $noreplyuser = core_user::get_noreply_user();
390 if (!isset($strangers[$noreplyuser->id])) {
391 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
392 if ($noreplyuser->messagecount > 0) {
393 $strangers[$noreplyuser->id] = $noreplyuser;
396 return array($onlinecontacts, $offlinecontacts, $strangers);
400 * Print $user1's contacts. Called by message_print_contact_selector()
402 * @param array $onlinecontacts $user1's contacts which are online
403 * @param array $offlinecontacts $user1's contacts which are offline
404 * @param array $strangers users which are not contacts but who have messaged $user1
405 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
406 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
407 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
408 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
409 * @param string $titletodisplay Optionally specify a title to display above the participants
410 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
411 * @return void
413 function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
414 global $CFG, $PAGE, $OUTPUT;
416 $countonlinecontacts = count($onlinecontacts);
417 $countofflinecontacts = count($offlinecontacts);
418 $countstrangers = count($strangers);
419 $isuserblocked = null;
421 if ($countonlinecontacts + $countofflinecontacts == 0) {
422 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
425 if (!empty($titletodisplay)) {
426 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
429 if($countonlinecontacts) {
430 // Print out list of online contacts.
432 if (empty($titletodisplay)) {
433 echo html_writer::tag('div',
434 get_string('onlinecontacts', 'message', $countonlinecontacts),
435 array('class' => 'heading'));
438 $isuserblocked = false;
439 $isusercontact = true;
440 $contacts = '';
441 foreach ($onlinecontacts as $contact) {
442 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
443 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
444 $contactselecturl, $showactionlinks, $user2);
445 $contacts .= html_writer::tag('li', $content);
448 if (strlen($contacts) > 0) {
449 echo html_writer::tag('ul', $contacts, array('id' => 'message-onlinecontacts', 'class' => 'message-contacts'));
453 if ($countofflinecontacts) {
454 // Print out list of offline contacts.
456 if (empty($titletodisplay)) {
457 echo html_writer::tag('div',
458 get_string('offlinecontacts', 'message', $countofflinecontacts),
459 array('class' => 'heading'));
462 $isuserblocked = false;
463 $isusercontact = true;
464 $contacts = '';
465 foreach ($offlinecontacts as $contact) {
466 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
467 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
468 $contactselecturl, $showactionlinks, $user2);
469 $contacts .= html_writer::tag('li', $content);
472 if (strlen($contacts) > 0) {
473 echo html_writer::tag('ul', $contacts, array('id' => 'message-offlinecontacts', 'class' => 'message-contacts'));
478 // Print out list of incoming contacts.
479 if ($countstrangers) {
480 echo html_writer::tag('div', get_string('incomingcontacts', 'message', $countstrangers), array('class' => 'heading'));
482 $isuserblocked = false;
483 $isusercontact = false;
484 $contacts = '';
485 foreach ($strangers as $stranger) {
486 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
487 $content = message_print_contactlist_user($stranger, $isusercontact, $isuserblocked,
488 $contactselecturl, $showactionlinks, $user2);
489 $contacts .= html_writer::tag('li', $content);
492 if (strlen($contacts) > 0) {
493 echo html_writer::tag('ul', $contacts, array('id' => 'message-incommingcontacts', 'class' => 'message-contacts'));
498 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
499 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
504 * Print a select box allowing the user to choose to view new messages, course participants etc.
506 * Called by message_print_contact_selector()
507 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
508 * @param array $courses array of course objects. The courses the user is enrolled in.
509 * @param array $coursecontexts array of course contexts. Keyed on course id.
510 * @param int $countunreadtotal how many unread messages does the user have?
511 * @param int $countblocked how many users has the current user blocked?
512 * @param stdClass $user1 The user whose messages we are viewing.
513 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
514 * @return void
516 function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
517 global $PAGE;
518 $options = array();
520 if ($countunreadtotal>0) { //if there are unread messages
521 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
524 $str = get_string('contacts', 'message');
525 $options[MESSAGE_VIEW_CONTACTS] = $str;
527 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
528 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
530 if (!empty($courses)) {
531 $courses_options = array();
533 foreach($courses as $course) {
534 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
535 //Not using short_text() as we want the end of the course name. Not the beginning.
536 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
537 if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
538 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
539 } else {
540 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
545 if (!empty($courses_options)) {
546 $options[] = array(get_string('courses') => $courses_options);
550 if ($countblocked>0) {
551 $str = get_string('blockedusers','message', $countblocked);
552 $options[MESSAGE_VIEW_BLOCKED] = $str;
555 $select = new single_select($PAGE->url, 'viewing', $options, $viewing, false);
556 $select->set_label(get_string('messagenavigation', 'message'));
558 $renderer = $PAGE->get_renderer('core');
559 echo $renderer->render($select);
563 * Load the course contexts for all of the users courses
565 * @param array $courses array of course objects. The courses the user is enrolled in.
566 * @return array of course contexts
568 function message_get_course_contexts($courses) {
569 $coursecontexts = array();
571 foreach($courses as $course) {
572 $coursecontexts[$course->id] = context_course::instance($course->id);
575 return $coursecontexts;
579 * strip off action parameters like 'removecontact'
581 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
582 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
584 function message_remove_url_params($moodleurl) {
585 $newurl = new moodle_url($moodleurl);
586 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
587 return $newurl->out();
591 * Count the number of messages with a field having a specified value.
592 * if $field is empty then return count of the whole array
593 * if $field is non-existent then return 0
595 * @param array $messagearray array of message objects
596 * @param string $field the field to inspect on the message objects
597 * @param string $value the value to test the field against
599 function message_count_messages($messagearray, $field='', $value='') {
600 if (!is_array($messagearray)) return 0;
601 if ($field == '' or empty($messagearray)) return count($messagearray);
603 $count = 0;
604 foreach ($messagearray as $message) {
605 $count += ($message->$field == $value) ? 1 : 0;
607 return $count;
611 * Returns the count of unread messages for user. Either from a specific user or from all users.
613 * @param object $user1 the first user. Defaults to $USER
614 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
615 * @return int the count of $user1's unread messages
617 function message_count_unread_messages($user1=null, $user2=null) {
618 global $USER, $DB;
620 if (empty($user1)) {
621 $user1 = $USER;
624 if (!empty($user2)) {
625 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
626 array($user1->id, $user2->id), "COUNT('id')");
627 } else {
628 return $DB->count_records_select('message', "useridto = ?",
629 array($user1->id), "COUNT('id')");
634 * Count the number of users blocked by $user1
636 * @param object $user1 user object
637 * @return int the number of blocked users
639 function message_count_blocked_users($user1=null) {
640 global $USER, $DB;
642 if (empty($user1)) {
643 $user1 = $USER;
646 $sql = "SELECT count(mc.id)
647 FROM {message_contacts} mc
648 WHERE mc.userid = :userid AND mc.blocked = 1";
649 $params = array('userid' => $user1->id);
651 return $DB->count_records_sql($sql, $params);
655 * Print the search form and search results if a search has been performed
657 * @param boolean $advancedsearch show basic or advanced search form
658 * @param object $user1 the current user
659 * @return boolean true if a search was performed
661 function message_print_search($advancedsearch = false, $user1=null) {
662 $frm = data_submitted();
664 $doingsearch = false;
665 if ($frm) {
666 if (confirm_sesskey()) {
667 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
668 } else {
669 $frm = false;
673 if (!empty($frm->combinedsearch)) {
674 $combinedsearchstring = $frm->combinedsearch;
675 } else {
676 //$combinedsearchstring = get_string('searchcombined','message').'...';
677 $combinedsearchstring = '';
680 if ($doingsearch) {
681 if ($advancedsearch) {
683 $messagesearch = '';
684 if (!empty($frm->keywords)) {
685 $messagesearch = $frm->keywords;
687 $personsearch = '';
688 if (!empty($frm->name)) {
689 $personsearch = $frm->name;
691 include('search_advanced.html');
692 } else {
693 include('search.html');
696 $showicontext = false;
697 message_print_search_results($frm, $showicontext, $user1);
699 return true;
700 } else {
702 if ($advancedsearch) {
703 $personsearch = $messagesearch = '';
704 include('search_advanced.html');
705 } else {
706 include('search.html');
708 return false;
713 * Get the users recent conversations meaning all the people they've recently
714 * sent or received a message from plus the most recent message sent to or received from each other user
716 * @param object $user the current user
717 * @param int $limitfrom can be used for paging
718 * @param int $limitto can be used for paging
719 * @return array
721 function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
722 global $DB;
724 $userfields = user_picture::fields('otheruser', array('lastaccess'));
726 // This query retrieves the most recent message received from or sent to
727 // seach other user.
729 // If two messages have the same timecreated, we take the one with the
730 // larger id.
732 // There is a separate query for read and unread messages as they are stored
733 // in different tables. They were originally retrieved in one query but it
734 // was so large that it was difficult to be confident in its correctness.
735 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
736 $sql = "SELECT $uniquefield, $userfields,
737 message.id as mid, message.notification, message.smallmessage, message.fullmessage,
738 message.fullmessagehtml, message.fullmessageformat, message.timecreated,
739 contact.id as contactlistid, contact.blocked
740 FROM {message_read} message
741 JOIN (
742 SELECT MAX(id) AS messageid,
743 matchedmessage.useridto,
744 matchedmessage.useridfrom
745 FROM {message_read} matchedmessage
746 INNER JOIN (
747 SELECT MAX(recentmessages.timecreated) timecreated,
748 recentmessages.useridfrom,
749 recentmessages.useridto
750 FROM {message_read} recentmessages
751 WHERE (
752 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
753 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
755 GROUP BY recentmessages.useridfrom, recentmessages.useridto
756 ) recent ON matchedmessage.useridto = recent.useridto
757 AND matchedmessage.useridfrom = recent.useridfrom
758 AND matchedmessage.timecreated = recent.timecreated
759 WHERE (
760 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
761 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
763 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
764 ) messagesubset ON messagesubset.messageid = message.id
765 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
766 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
767 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.userid = otheruser.id
768 WHERE otheruser.deleted = 0 AND message.notification = 0
769 ORDER BY message.timecreated DESC";
770 $params = array(
771 'userid1' => $user->id,
772 'userid2' => $user->id,
773 'userid3' => $user->id,
774 'userid4' => $user->id,
775 'userid5' => $user->id,
776 'userid6' => $user->id,
777 'userid7' => $user->id
779 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
781 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
782 // exact same query as the one above, except for the table we are querying. So, simply replace references to
783 // the 'message_read' table with the 'message' table.
784 $sql = str_replace('{message_read}', '{message}', $sql);
785 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
787 // Union the 2 result sets together looking for the message with the most
788 // recent timecreated for each other user.
789 // $conversation->id (the array key) is the other user's ID.
790 $conversations = array();
791 $conversation_arrays = array($unread, $read);
792 foreach ($conversation_arrays as $conversation_array) {
793 foreach ($conversation_array as $conversation) {
794 if (!isset($conversations[$conversation->id])) {
795 $conversations[$conversation->id] = $conversation;
796 } else {
797 $current = $conversations[$conversation->id];
798 if ($current->timecreated < $conversation->timecreated) {
799 $conversations[$conversation->id] = $conversation;
800 } else if ($current->timecreated == $conversation->timecreated) {
801 if ($current->mid < $conversation->mid) {
802 $conversations[$conversation->id] = $conversation;
809 // Sort the conversations by $conversation->timecreated, newest to oldest
810 // There may be multiple conversations with the same timecreated
811 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
812 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
813 $conversations = array_reverse($conversations);
815 return $conversations;
819 * Get the users recent event notifications
821 * @param object $user the current user
822 * @param int $limitfrom can be used for paging
823 * @param int $limitto can be used for paging
824 * @return array
826 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
827 global $DB;
829 $userfields = user_picture::fields('u', array('lastaccess'));
830 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
831 FROM {message_read} mr
832 JOIN {user} u ON u.id=mr.useridfrom
833 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
834 ORDER BY mr.timecreated DESC";
835 $params = array('userid1' => $user->id, 'notification' => 1);
837 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
838 return $notifications;
842 * Print the user's recent conversations
844 * @param stdClass $user the current user
845 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
847 function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
848 global $USER;
850 echo html_writer::start_tag('p', array('class' => 'heading'));
851 echo get_string('mostrecentconversations', 'message');
852 echo html_writer::end_tag('p');
854 if (empty($user1)) {
855 $user1 = $USER;
858 $conversations = message_get_recent_conversations($user1);
860 // Attach context url information to create the "View this conversation" type links
861 foreach($conversations as $conversation) {
862 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
863 $conversation->contexturlname = get_string('thisconversation', 'message');
866 $showotheruser = true;
867 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
871 * Print the user's recent notifications
873 * @param stdClass $user the current user
875 function message_print_recent_notifications($user=null) {
876 global $USER;
878 echo html_writer::start_tag('p', array('class' => 'heading'));
879 echo get_string('mostrecentnotifications', 'message');
880 echo html_writer::end_tag('p');
882 if (empty($user)) {
883 $user = $USER;
886 $notifications = message_get_recent_notifications($user);
888 $showicontext = false;
889 $showotheruser = false;
890 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
894 * Print a list of recent messages
896 * @access private
898 * @param array $messages the messages to display
899 * @param stdClass $user the current user
900 * @param bool $showotheruser display information on the other user?
901 * @param bool $showicontext show text next to the action icons?
902 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
903 * @param bool $showactionlinks
904 * @return void
906 function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
907 global $OUTPUT;
908 static $dateformat;
910 if (empty($dateformat)) {
911 $dateformat = get_string('strftimedatetimeshort');
914 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
915 foreach ($messages as $message) {
916 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
918 if ($showotheruser) {
919 $strcontact = $strblock = $strhistory = null;
921 if ($showactionlinks) {
922 if ( $message->contactlistid ) {
923 if ($message->blocked == 0) { // The other user isn't blocked.
924 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
925 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
926 } else { // The other user is blocked.
927 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
928 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
930 } else {
931 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
932 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
935 //should we show just the icon or icon and text?
936 $histicontext = 'icon';
937 if ($showicontext) {
938 $histicontext = 'both';
940 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
942 echo html_writer::start_tag('span', array('class' => 'otheruser'));
944 echo html_writer::start_tag('span', array('class' => 'pix'));
945 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
946 echo html_writer::end_tag('span');
948 echo html_writer::start_tag('span', array('class' => 'contact'));
950 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
951 $action = null;
952 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
954 echo html_writer::end_tag('span');//end contact
956 if ($showactionlinks) {
957 echo $strcontact.$strblock.$strhistory;
959 echo html_writer::end_tag('span');//end otheruser
962 $messagetext = message_format_message_text($message, $forcetexttohtml);
964 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
965 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
966 echo message_format_contexturl($message);
967 echo html_writer::end_tag('div');//end singlemessage
969 echo html_writer::end_tag('div');//end messagerecent
973 * Try to guess how to convert the message to html.
975 * @access private
977 * @param stdClass $message
978 * @param bool $forcetexttohtml
979 * @return string html fragment
981 function message_format_message_text($message, $forcetexttohtml = false) {
982 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
984 $options = new stdClass();
985 $options->para = false;
987 $format = $message->fullmessageformat;
989 if (strval($message->smallmessage) !== '') {
990 if ($message->notification == 1) {
991 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
992 $format = FORMAT_PLAIN;
995 $messagetext = $message->smallmessage;
997 } else if ($message->fullmessageformat == FORMAT_HTML) {
998 if (strval($message->fullmessagehtml) !== '') {
999 $messagetext = $message->fullmessagehtml;
1000 } else {
1001 $messagetext = $message->fullmessage;
1002 $format = FORMAT_MOODLE;
1005 } else {
1006 if (strval($message->fullmessage) !== '') {
1007 $messagetext = $message->fullmessage;
1008 } else {
1009 $messagetext = $message->fullmessagehtml;
1010 $format = FORMAT_HTML;
1014 if ($forcetexttohtml) {
1015 // This is a crazy hack, why not set proper format when creating the notifications?
1016 if ($format === FORMAT_PLAIN) {
1017 $format = FORMAT_MOODLE;
1020 return format_text($messagetext, $format, $options);
1024 * Add the selected user as a contact for the current user
1026 * @param int $contactid the ID of the user to add as a contact
1027 * @param int $blocked 1 if you wish to block the contact
1028 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
1029 * Otherwise returns the result of update_record() or insert_record()
1031 function message_add_contact($contactid, $blocked=0) {
1032 global $USER, $DB;
1034 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
1035 return false;
1038 // Check if a record already exists as we may be changing blocking status.
1039 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
1040 // Check if blocking status has been changed.
1041 if ($contact->blocked != $blocked) {
1042 $contact->blocked = $blocked;
1043 $DB->update_record('message_contacts', $contact);
1045 if ($blocked == 1) {
1046 // Trigger event for blocking a contact.
1047 $event = \core\event\message_contact_blocked::create(array(
1048 'objectid' => $contact->id,
1049 'userid' => $contact->userid,
1050 'relateduserid' => $contact->contactid,
1051 'context' => context_user::instance($contact->userid)
1053 $event->add_record_snapshot('message_contacts', $contact);
1054 $event->trigger();
1055 } else {
1056 // Trigger event for unblocking a contact.
1057 $event = \core\event\message_contact_unblocked::create(array(
1058 'objectid' => $contact->id,
1059 'userid' => $contact->userid,
1060 'relateduserid' => $contact->contactid,
1061 'context' => context_user::instance($contact->userid)
1063 $event->add_record_snapshot('message_contacts', $contact);
1064 $event->trigger();
1067 return true;
1068 } else {
1069 // No change to blocking status.
1070 return true;
1073 } else {
1074 // New contact record.
1075 $contact = new stdClass();
1076 $contact->userid = $USER->id;
1077 $contact->contactid = $contactid;
1078 $contact->blocked = $blocked;
1079 $contact->id = $DB->insert_record('message_contacts', $contact);
1081 $eventparams = array(
1082 'objectid' => $contact->id,
1083 'userid' => $contact->userid,
1084 'relateduserid' => $contact->contactid,
1085 'context' => context_user::instance($contact->userid)
1088 if ($blocked) {
1089 $event = \core\event\message_contact_blocked::create($eventparams);
1090 } else {
1091 $event = \core\event\message_contact_added::create($eventparams);
1093 // Trigger event.
1094 $event->trigger();
1096 return true;
1101 * remove a contact
1103 * @param int $contactid the user ID of the contact to remove
1104 * @return bool returns the result of delete_records()
1106 function message_remove_contact($contactid) {
1107 global $USER, $DB;
1109 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1110 $DB->delete_records('message_contacts', array('id' => $contact->id));
1112 // Trigger event for removing a contact.
1113 $event = \core\event\message_contact_removed::create(array(
1114 'objectid' => $contact->id,
1115 'userid' => $contact->userid,
1116 'relateduserid' => $contact->contactid,
1117 'context' => context_user::instance($contact->userid)
1119 $event->add_record_snapshot('message_contacts', $contact);
1120 $event->trigger();
1122 return true;
1125 return false;
1129 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
1131 * @param int $contactid the user ID of the contact to unblock
1132 * @return bool returns the result of delete_records()
1134 function message_unblock_contact($contactid) {
1135 return message_add_contact($contactid, 0);
1139 * Block a user.
1141 * @param int $contactid the user ID of the user to block
1142 * @return bool
1144 function message_block_contact($contactid) {
1145 return message_add_contact($contactid, 1);
1149 * Checks if a user can delete a message.
1151 * @param stdClass $message the message to delete
1152 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
1153 * but will still seem as if it was by the user)
1154 * @return bool Returns true if a user can delete the message, false otherwise.
1156 function message_can_delete_message($message, $userid) {
1157 global $USER;
1159 if ($message->useridfrom == $userid) {
1160 $userdeleting = 'useridfrom';
1161 } else if ($message->useridto == $userid) {
1162 $userdeleting = 'useridto';
1163 } else {
1164 return false;
1167 $systemcontext = context_system::instance();
1169 // Let's check if the user is allowed to delete this message.
1170 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1171 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1172 $USER->id == $message->$userdeleting))) {
1173 return true;
1176 return false;
1180 * Deletes a message.
1182 * This function does not verify any permissions.
1184 * @param stdClass $message the message to delete
1185 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
1186 * but will still seem as if it was by the user)
1187 * @return bool
1189 function message_delete_message($message, $userid) {
1190 global $DB;
1192 // The column we want to alter.
1193 if ($message->useridfrom == $userid) {
1194 $coltimedeleted = 'timeuserfromdeleted';
1195 } else if ($message->useridto == $userid) {
1196 $coltimedeleted = 'timeusertodeleted';
1197 } else {
1198 return false;
1201 // Don't update it if it's already been deleted.
1202 if ($message->$coltimedeleted > 0) {
1203 return false;
1206 // Get the table we want to update.
1207 if (isset($message->timeread)) {
1208 $messagetable = 'message_read';
1209 } else {
1210 $messagetable = 'message';
1213 // Mark the message as deleted.
1214 $updatemessage = new stdClass();
1215 $updatemessage->id = $message->id;
1216 $updatemessage->$coltimedeleted = time();
1217 $success = $DB->update_record($messagetable, $updatemessage);
1219 if ($success) {
1220 // Trigger event for deleting a message.
1221 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1222 $userid, $messagetable, $message->id)->trigger();
1225 return $success;
1229 * Load a user's contact record
1231 * @param int $contactid the user ID of the user whose contact record you want
1232 * @return array message contacts
1234 function message_get_contact($contactid) {
1235 global $USER, $DB;
1236 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1240 * Print the results of a message search
1242 * @param mixed $frm submitted form data
1243 * @param bool $showicontext show text next to action icons?
1244 * @param object $currentuser the current user
1245 * @return void
1247 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1248 global $USER, $DB, $OUTPUT;
1250 if (empty($currentuser)) {
1251 $currentuser = $USER;
1254 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1256 $personsearch = false;
1257 $personsearchstring = null;
1258 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1259 $personsearch = true;
1260 $personsearchstring = $frm->name;
1261 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1262 $personsearch = true;
1263 $personsearchstring = $frm->combinedsearch;
1266 // Search for person.
1267 if ($personsearch) {
1268 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1269 $users = array();
1270 $mycourses = enrol_get_my_courses('id');
1271 $mycoursesids = array();
1272 foreach ($mycourses as $mycourse) {
1273 $mycoursesids[] = $mycourse->id;
1275 $susers = message_search_users($mycoursesids, $personsearchstring);
1276 foreach ($susers as $suser) {
1277 $users[$suser->id] = $suser;
1279 } else {
1280 $users = message_search_users(SITEID, $personsearchstring);
1283 if (!empty($users)) {
1284 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1285 echo get_string('userssearchresults', 'message', count($users));
1286 echo html_writer::end_tag('p');
1288 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1289 foreach ($users as $user) {
1291 if ( $user->contactlistid ) {
1292 if ($user->blocked == 0) { // User is not blocked.
1293 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1294 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1295 } else { // blocked
1296 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1297 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1299 } else {
1300 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1301 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1304 // Should we show just the icon or icon and text?
1305 $histicontext = 'icon';
1306 if ($showicontext) {
1307 $histicontext = 'both';
1309 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1311 echo html_writer::start_tag('tr');
1313 echo html_writer::start_tag('td', array('class' => 'pix'));
1314 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1315 echo html_writer::end_tag('td');
1317 echo html_writer::start_tag('td',array('class' => 'contact'));
1318 $action = null;
1319 $link = new moodle_url("/message/index.php?id=$user->id");
1320 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1321 echo html_writer::end_tag('td');
1323 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1324 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1325 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1327 echo html_writer::end_tag('tr');
1329 echo html_writer::end_tag('table');
1331 } else {
1332 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1333 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1334 echo html_writer::end_tag('p');
1338 // search messages for keywords
1339 $messagesearch = false;
1340 $messagesearchstring = null;
1341 if (!empty($frm->keywords)) {
1342 $messagesearch = true;
1343 $messagesearchstring = clean_text(trim($frm->keywords));
1344 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1345 $messagesearch = true;
1346 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1349 if ($messagesearch) {
1350 if ($messagesearchstring) {
1351 $keywords = explode(' ', $messagesearchstring);
1352 } else {
1353 $keywords = array();
1355 $tome = false;
1356 $fromme = false;
1357 $courseid = 'none';
1359 if (empty($frm->keywordsoption)) {
1360 $frm->keywordsoption = 'allmine';
1363 switch ($frm->keywordsoption) {
1364 case 'tome':
1365 $tome = true;
1366 break;
1367 case 'fromme':
1368 $fromme = true;
1369 break;
1370 case 'allmine':
1371 $tome = true;
1372 $fromme = true;
1373 break;
1374 case 'allusers':
1375 $courseid = SITEID;
1376 break;
1377 case 'courseusers':
1378 $courseid = $frm->courseid;
1379 break;
1380 default:
1381 $tome = true;
1382 $fromme = true;
1385 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1387 // Get a list of contacts.
1388 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1389 $contacts = array();
1392 // Print heading with number of results.
1393 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1394 $countresults = count($messages);
1395 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1396 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1397 } else {
1398 echo get_string('keywordssearchresults', 'message', $countresults);
1400 echo html_writer::end_tag('p');
1402 // Print table headings.
1403 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1405 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1406 $headertdend = html_writer::end_tag('td');
1407 echo html_writer::start_tag('tr');
1408 echo $headertdstart.get_string('from').$headertdend;
1409 echo $headertdstart.get_string('to').$headertdend;
1410 echo $headertdstart.get_string('message', 'message').$headertdend;
1411 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1412 echo html_writer::end_tag('tr');
1414 $blockedcount = 0;
1415 $dateformat = get_string('strftimedatetimeshort');
1416 $strcontext = get_string('context', 'message');
1417 foreach ($messages as $message) {
1419 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1420 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1421 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1422 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1425 $blockedcount ++;
1426 continue;
1429 // Load user-to record.
1430 if ($message->useridto !== $USER->id) {
1431 $userto = core_user::get_user($message->useridto);
1432 $tocontact = (array_key_exists($message->useridto, $contacts) and
1433 ($contacts[$message->useridto]->blocked == 0) );
1434 $toblocked = (array_key_exists($message->useridto, $contacts) and
1435 ($contacts[$message->useridto]->blocked == 1) );
1436 } else {
1437 $userto = false;
1438 $tocontact = false;
1439 $toblocked = false;
1442 // Load user-from record.
1443 if ($message->useridfrom !== $USER->id) {
1444 $userfrom = core_user::get_user($message->useridfrom);
1445 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1446 ($contacts[$message->useridfrom]->blocked == 0) );
1447 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1448 ($contacts[$message->useridfrom]->blocked == 1) );
1449 } else {
1450 $userfrom = false;
1451 $fromcontact = false;
1452 $fromblocked = false;
1455 // Find date string for this message.
1456 $date = usergetdate($message->timecreated);
1457 $datestring = $date['year'].$date['mon'].$date['mday'];
1459 // Print out message row.
1460 echo html_writer::start_tag('tr', array('valign' => 'top'));
1462 echo html_writer::start_tag('td', array('class' => 'contact'));
1463 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1464 echo html_writer::end_tag('td');
1466 echo html_writer::start_tag('td', array('class' => 'contact'));
1467 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1468 echo html_writer::end_tag('td');
1470 echo html_writer::start_tag('td', array('class' => 'summary'));
1471 echo message_get_fragment($message->smallmessage, $keywords);
1472 echo html_writer::start_tag('div', array('class' => 'link'));
1474 // If the user clicks the context link display message sender on the left.
1475 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1476 $leftsideuserid = $rightsideuserid = null;
1477 if ($currentuser->id == $message->useridto) {
1478 $leftsideuserid = $message->useridto;
1479 $rightsideuserid = $message->useridfrom;
1480 } else {
1481 $leftsideuserid = $message->useridfrom;
1482 $rightsideuserid = $message->useridto;
1484 message_history_link($leftsideuserid, $rightsideuserid, false,
1485 $messagesearchstring, 'm'.$message->id, $strcontext);
1486 echo html_writer::end_tag('div');
1487 echo html_writer::end_tag('td');
1489 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1491 echo html_writer::end_tag('tr');
1495 if ($blockedcount > 0) {
1496 echo html_writer::start_tag('tr');
1497 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1498 echo html_writer::end_tag('tr');
1500 echo html_writer::end_tag('table');
1502 } else {
1503 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1507 if (!$personsearch && !$messagesearch) {
1508 //they didn't enter any search terms
1509 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1512 echo html_writer::end_tag('div');
1516 * Print information on a user. Used when printing search results.
1518 * @param object/bool $user the user to display or false if you just want $USER
1519 * @param bool $iscontact is the user being displayed a contact?
1520 * @param bool $isblocked is the user being displayed blocked?
1521 * @param bool $includeicontext include text next to the action icons?
1522 * @return void
1524 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1525 global $USER, $OUTPUT;
1527 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1529 if ($user === false) {
1530 echo $OUTPUT->user_picture($USER, $userpictureparams);
1531 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1532 $userpictureparams['link'] = false;
1533 echo $OUTPUT->user_picture($USER, $userpictureparams);
1534 echo fullname($user);
1535 } else {
1536 echo $OUTPUT->user_picture($user, $userpictureparams);
1538 $link = new moodle_url("/message/index.php?id=$user->id");
1539 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1540 get_string('sendmessageto', 'message', fullname($user))));
1542 $return = false;
1543 $script = null;
1544 if ($iscontact) {
1545 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1546 } else {
1547 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1550 if ($isblocked) {
1551 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1552 } else {
1553 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1559 * Print a message contact link
1561 * @param int $userid the ID of the user to apply to action to
1562 * @param string $linktype can be add, remove, block or unblock
1563 * @param bool $return if true return the link as a string. If false echo the link.
1564 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1565 * @param bool $text include text next to the icons?
1566 * @param bool $icon include a graphical icon?
1567 * @return string if $return is true otherwise bool
1569 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1570 global $OUTPUT, $PAGE;
1572 //hold onto the strings as we're probably creating a bunch of links
1573 static $str;
1575 if (empty($script)) {
1576 //strip off previous action params like 'removecontact'
1577 $script = message_remove_url_params($PAGE->url);
1580 if (empty($str->blockcontact)) {
1581 $str = new stdClass();
1582 $str->blockcontact = get_string('blockcontact', 'message');
1583 $str->unblockcontact = get_string('unblockcontact', 'message');
1584 $str->removecontact = get_string('removecontact', 'message');
1585 $str->addcontact = get_string('addcontact', 'message');
1588 $command = $linktype.'contact';
1589 $string = $str->{$command};
1591 $safealttext = s($string);
1593 $safestring = '';
1594 if (!empty($text)) {
1595 $safestring = $safealttext;
1598 $img = '';
1599 if ($icon) {
1600 $iconpath = null;
1601 switch ($linktype) {
1602 case 'block':
1603 $iconpath = 't/block';
1604 break;
1605 case 'unblock':
1606 $iconpath = 't/unblock';
1607 break;
1608 case 'remove':
1609 $iconpath = 't/removecontact';
1610 break;
1611 case 'add':
1612 default:
1613 $iconpath = 't/addcontact';
1616 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1619 $output = '<span class="'.$linktype.'contact">'.
1620 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1621 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1622 $img.
1623 $safestring.'</a></span>';
1625 if ($return) {
1626 return $output;
1627 } else {
1628 echo $output;
1629 return true;
1634 * echo or return a link to take the user to the full message history between themselves and another user
1636 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1637 * @param int $userid2 the ID of the other user
1638 * @param bool $return true to return the link as a string. False to echo the link.
1639 * @param string $keywords any keywords to highlight in the message history
1640 * @param string $position anchor name to jump to within the message history
1641 * @param string $linktext optionally specify the link text
1642 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1644 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1645 global $OUTPUT, $PAGE;
1646 static $strmessagehistory;
1648 if (empty($strmessagehistory)) {
1649 $strmessagehistory = get_string('messagehistory', 'message');
1652 if ($position) {
1653 $position = "#$position";
1655 if ($keywords) {
1656 $keywords = "&search=".urlencode($keywords);
1659 if ($linktext == 'icon') { // Icon only
1660 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1661 } else if ($linktext == 'both') { // Icon and standard name
1662 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1663 $fulllink .= '&nbsp;'.$strmessagehistory;
1664 } else if ($linktext) { // Custom name
1665 $fulllink = $linktext;
1666 } else { // Standard name only
1667 $fulllink = $strmessagehistory;
1670 $popupoptions = array(
1671 'height' => 500,
1672 'width' => 500,
1673 'menubar' => false,
1674 'location' => false,
1675 'status' => true,
1676 'scrollbars' => true,
1677 'resizable' => true);
1679 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1680 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1681 $link->param('viewing', $PAGE->url->get_param('viewing'));
1683 $action = null;
1684 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1686 $str = '<span class="history">'.$str.'</span>';
1688 if ($return) {
1689 return $str;
1690 } else {
1691 echo $str;
1692 return true;
1698 * Search through course users.
1700 * If $courseids contains the site course then this function searches
1701 * through all undeleted and confirmed users.
1703 * @param int|array $courseids Course ID or array of course IDs.
1704 * @param string $searchtext the text to search for.
1705 * @param string $sort the column name to order by.
1706 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1707 * @return array An array of {@link $USER} records.
1709 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1710 global $CFG, $USER, $DB;
1712 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1713 if (!$courseids) {
1714 $courseids = array(SITEID);
1717 // Allow an integer to be passed.
1718 if (!is_array($courseids)) {
1719 $courseids = array($courseids);
1722 $fullname = $DB->sql_fullname();
1723 $ufields = user_picture::fields('u');
1725 if (!empty($sort)) {
1726 $order = ' ORDER BY '. $sort;
1727 } else {
1728 $order = '';
1731 $params = array(
1732 'userid' => $USER->id,
1733 'query' => "%$searchtext%"
1736 if (empty($exceptions)) {
1737 $exceptions = array();
1738 } else if (!empty($exceptions) && is_string($exceptions)) {
1739 $exceptions = explode(',', $exceptions);
1742 // Ignore self and guest account.
1743 $exceptions[] = $USER->id;
1744 $exceptions[] = $CFG->siteguest;
1746 // Exclude exceptions from the search result.
1747 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1748 $except = ' AND u.id ' . $except;
1749 $params = array_merge($params_except, $params);
1751 if (in_array(SITEID, $courseids)) {
1752 // Search on site level.
1753 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1754 FROM {user} u
1755 LEFT JOIN {message_contacts} mc
1756 ON mc.contactid = u.id AND mc.userid = :userid
1757 WHERE u.deleted = '0' AND u.confirmed = '1'
1758 AND (".$DB->sql_like($fullname, ':query', false).")
1759 $except
1760 $order", $params);
1761 } else {
1762 // Search in courses.
1764 // Getting the context IDs or each course.
1765 $contextids = array();
1766 foreach ($courseids as $courseid) {
1767 $context = context_course::instance($courseid);
1768 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1770 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1771 $params = array_merge($params, $contextparams);
1773 // Everyone who has a role assignment in this course or higher.
1774 // TODO: add enabled enrolment join here (skodak)
1775 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1776 FROM {user} u
1777 JOIN {role_assignments} ra ON ra.userid = u.id
1778 LEFT JOIN {message_contacts} mc
1779 ON mc.contactid = u.id AND mc.userid = :userid
1780 WHERE u.deleted = '0' AND u.confirmed = '1'
1781 AND (".$DB->sql_like($fullname, ':query', false).")
1782 AND ra.contextid $contextwhere
1783 $except
1784 $order", $params);
1786 return $users;
1791 * Search a user's messages
1793 * Returns a list of posts found using an array of search terms
1794 * eg word +word -word
1796 * @param array $searchterms an array of search terms (strings)
1797 * @param bool $fromme include messages from the user?
1798 * @param bool $tome include messages to the user?
1799 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1800 * @param int $userid the user ID of the current user
1801 * @return mixed An array of messages or false if no matching messages were found
1803 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1804 global $CFG, $USER, $DB;
1806 // If user is searching all messages check they are allowed to before doing anything else.
1807 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1808 print_error('accessdenied','admin');
1811 // If no userid sent then assume current user.
1812 if ($userid == 0) $userid = $USER->id;
1814 // Some differences in SQL syntax.
1815 if ($DB->sql_regex_supported()) {
1816 $REGEXP = $DB->sql_regex(true);
1817 $NOTREGEXP = $DB->sql_regex(false);
1820 $searchcond = array();
1821 $params = array();
1822 $i = 0;
1824 // Preprocess search terms to check whether we have at least 1 eligible search term.
1825 // If we do we can drop words around it like 'a'.
1826 $dropshortwords = false;
1827 foreach ($searchterms as $searchterm) {
1828 if (strlen($searchterm) >= 2) {
1829 $dropshortwords = true;
1833 foreach ($searchterms as $searchterm) {
1834 $i++;
1836 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1838 if ($dropshortwords && strlen($searchterm) < 2) {
1839 continue;
1841 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1842 if (!$DB->sql_regex_supported()) {
1843 if (substr($searchterm, 0, 1) == '-') {
1844 $NOT = true;
1846 $searchterm = trim($searchterm, '+-');
1849 if (substr($searchterm,0,1) == "+") {
1850 $searchterm = substr($searchterm,1);
1851 $searchterm = preg_quote($searchterm, '|');
1852 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1853 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1855 } else if (substr($searchterm,0,1) == "-") {
1856 $searchterm = substr($searchterm,1);
1857 $searchterm = preg_quote($searchterm, '|');
1858 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1859 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1861 } else {
1862 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1863 $params['ss'.$i] = "%$searchterm%";
1867 if (empty($searchcond)) {
1868 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1869 $params['ss1'] = "%";
1870 } else {
1871 $searchcond = implode(" AND ", $searchcond);
1874 // There are several possibilities
1875 // 1. courseid = SITEID : The admin is searching messages by all users
1876 // 2. courseid = ?? : A teacher is searching messages by users in
1877 // one of their courses - currently disabled
1878 // 3. courseid = none : User is searching their own messages;
1879 // a. Messages from user
1880 // b. Messages to user
1881 // c. Messages to and from user
1883 if ($fromme && $tome) {
1884 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
1885 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
1886 $params['useridto'] = $userid;
1887 $params['useridfrom'] = $userid;
1888 } else if ($fromme) {
1889 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
1890 $params['useridfrom'] = $userid;
1891 } else if ($tome) {
1892 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
1893 $params['useridto'] = $userid;
1895 if ($courseid == SITEID) { // Admin is searching all messages.
1896 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1897 FROM {message_read} m
1898 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1899 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1900 FROM {message} m
1901 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1903 } else if ($courseid !== 'none') {
1904 // This has not been implemented due to security concerns.
1905 $m_read = array();
1906 $m_unread = array();
1908 } else {
1910 if ($fromme and $tome) {
1911 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1912 $params['userid1'] = $userid;
1913 $params['userid2'] = $userid;
1915 } else if ($fromme) {
1916 $searchcond .= " AND m.useridfrom=:userid";
1917 $params['userid'] = $userid;
1919 } else if ($tome) {
1920 $searchcond .= " AND m.useridto=:userid";
1921 $params['userid'] = $userid;
1924 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1925 FROM {message_read} m
1926 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1927 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1928 FROM {message} m
1929 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1933 /// The keys may be duplicated in $m_read and $m_unread so we can't
1934 /// do a simple concatenation
1935 $messages = array();
1936 foreach ($m_read as $m) {
1937 $messages[] = $m;
1939 foreach ($m_unread as $m) {
1940 $messages[] = $m;
1943 return (empty($messages)) ? false : $messages;
1947 * Given a message object that we already know has a long message
1948 * this function truncates the message nicely to the first
1949 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1951 * @param string $message the message
1952 * @param int $minlength the minimum length to trim the message to
1953 * @return string the shortened message
1955 function message_shorten_message($message, $minlength = 0) {
1956 $i = 0;
1957 $tag = false;
1958 $length = strlen($message);
1959 $count = 0;
1960 $stopzone = false;
1961 $truncate = 0;
1962 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1965 for ($i=0; $i<$length; $i++) {
1966 $char = $message[$i];
1968 switch ($char) {
1969 case "<":
1970 $tag = true;
1971 break;
1972 case ">":
1973 $tag = false;
1974 break;
1975 default:
1976 if (!$tag) {
1977 if ($stopzone) {
1978 if ($char == '.' or $char == ' ') {
1979 $truncate = $i+1;
1980 break 2;
1983 $count++;
1985 break;
1987 if (!$stopzone) {
1988 if ($count > $minlength) {
1989 $stopzone = true;
1994 if (!$truncate) {
1995 $truncate = $i;
1998 return substr($message, 0, $truncate);
2003 * Given a string and an array of keywords, this function looks
2004 * for the first keyword in the string, and then chops out a
2005 * small section from the text that shows that word in context.
2007 * @param string $message the text to search
2008 * @param array $keywords array of keywords to find
2010 function message_get_fragment($message, $keywords) {
2012 $fullsize = 160;
2013 $halfsize = (int)($fullsize/2);
2015 $message = strip_tags($message);
2017 foreach ($keywords as $keyword) { // Just get the first one
2018 if ($keyword !== '') {
2019 break;
2022 if (empty($keyword)) { // None found, so just return start of message
2023 return message_shorten_message($message, 30);
2026 $leadin = $leadout = '';
2028 /// Find the start of the fragment
2029 $start = 0;
2030 $length = strlen($message);
2032 $pos = strpos($message, $keyword);
2033 if ($pos > $halfsize) {
2034 $start = $pos - $halfsize;
2035 $leadin = '...';
2037 /// Find the end of the fragment
2038 $end = $start + $fullsize;
2039 if ($end > $length) {
2040 $end = $length;
2041 } else {
2042 $leadout = '...';
2045 /// Pull out the fragment and format it
2047 $fragment = substr($message, $start, $end - $start);
2048 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
2049 return $fragment;
2053 * Retrieve the messages between two users
2055 * @param object $user1 the current user
2056 * @param object $user2 the other user
2057 * @param int $limitnum the maximum number of messages to retrieve
2058 * @param bool $viewingnewmessages are we currently viewing new messages?
2060 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
2061 global $DB, $CFG;
2063 $messages = array();
2065 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
2066 //desc to get the last $limitnum messages then flip the order in php
2067 $sort = 'asc';
2068 if ($limitnum>0) {
2069 $sort = 'desc';
2072 $notificationswhere = null;
2073 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
2074 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
2075 $notificationswhere = 'AND notification=0';
2078 //prevent notifications of your own actions appearing in your own message history
2079 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
2081 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
2082 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
2083 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
2084 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
2085 "timecreated $sort", '*', 0, $limitnum)) {
2086 foreach ($messages_read as $message) {
2087 $messages[] = $message;
2090 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
2091 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
2092 "timecreated $sort", '*', 0, $limitnum)) {
2093 foreach ($messages_new as $message) {
2094 $messages[] = $message;
2098 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
2100 //if we only want the last $limitnum messages
2101 $messagecount = count($messages);
2102 if ($limitnum > 0 && $messagecount > $limitnum) {
2103 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
2106 return $messages;
2110 * Print the message history between two users
2112 * @param object $user1 the current user
2113 * @param object $user2 the other user
2114 * @param string $search search terms to highlight
2115 * @param int $messagelimit maximum number of messages to return
2116 * @param string $messagehistorylink the html for the message history link or false
2117 * @param bool $viewingnewmessages are we currently viewing new messages?
2119 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
2120 global $OUTPUT, $PAGE;
2122 $PAGE->requires->yui_module(
2123 array('moodle-core_message-toolbox'),
2124 'M.core_message.toolbox.deletemsg.init',
2125 array(array())
2128 echo $OUTPUT->box_start('center', 'message_user_pictures');
2129 echo $OUTPUT->box_start('user');
2130 echo $OUTPUT->box_start('generalbox', 'user1');
2131 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2132 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
2133 echo $OUTPUT->box_end();
2134 echo $OUTPUT->box_end();
2136 $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16);
2137 echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between');
2139 echo $OUTPUT->box_start('user');
2140 echo $OUTPUT->box_start('generalbox', 'user2');
2141 // Show user picture with link is real user else without link.
2142 if (core_user::is_real_user($user2->id)) {
2143 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2144 } else {
2145 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2147 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2149 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2151 $script = null;
2152 $text = true;
2153 $icon = false;
2155 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2156 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2157 $useractionlinks = $strcontact.'&nbsp;|&nbsp;'.$strblock;
2159 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2161 echo $OUTPUT->box_end();
2162 echo $OUTPUT->box_end();
2163 echo $OUTPUT->box_end();
2165 if (!empty($messagehistorylink)) {
2166 echo $messagehistorylink;
2169 /// Get all the messages and print them
2170 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2171 $tablecontents = '';
2173 $current = new stdClass();
2174 $current->mday = '';
2175 $current->month = '';
2176 $current->year = '';
2177 $messagedate = get_string('strftimetime');
2178 $blockdate = get_string('strftimedaydate');
2179 $messagenumber = 0;
2180 foreach ($messages as $message) {
2181 $messagenumber++;
2182 if ($message->notification) {
2183 $notificationclass = ' notification';
2184 } else {
2185 $notificationclass = null;
2187 $date = usergetdate($message->timecreated);
2188 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2189 $current->mday = $date['mday'];
2190 $current->month = $date['month'];
2191 $current->year = $date['year'];
2193 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2194 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2196 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2199 if ($message->useridfrom == $user1->id) {
2200 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2201 $side = 'left';
2202 } else {
2203 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2204 $side = 'right';
2207 // Check if it is a read message or not.
2208 if (isset($message->timeread)) {
2209 $type = 'message_read';
2210 } else {
2211 $type = 'message';
2214 if (message_can_delete_message($message, $user1->id)) {
2215 $usergroup = optional_param('usergroup', MESSAGE_VIEW_UNREAD_MESSAGES, PARAM_ALPHANUMEXT);
2216 $viewing = optional_param('viewing', $usergroup, PARAM_ALPHANUMEXT);
2217 $deleteurl = new moodle_url('/message/index.php', array('user1' => $user1->id, 'user2' => $user2->id,
2218 'viewing' => $viewing, 'deletemessageid' => $message->id, 'deletemessagetype' => $type,
2219 'sesskey' => sesskey()));
2221 $deleteicon = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete')));
2222 $deleteicon = html_writer::tag('div', $deleteicon, array('class' => 'deleteicon accesshide'));
2223 $formatted_message .= $deleteicon;
2226 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left messagecontent
2227 $side $notificationclass", 'id' => 'message_' . $messagenumber));
2230 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2231 } else {
2232 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2237 * Format a message for display in the message history
2239 * @param object $message the message object
2240 * @param string $format optional date format
2241 * @param string $keywords keywords to highlight
2242 * @param string $class CSS class to apply to the div around the message
2243 * @return string the formatted message
2245 function message_format_message($message, $format='', $keywords='', $class='other') {
2247 static $dateformat;
2249 //if we haven't previously set the date format or they've supplied a new one
2250 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2251 if ($format) {
2252 $dateformat = $format;
2253 } else {
2254 $dateformat = get_string('strftimedatetimeshort');
2257 $time = userdate($message->timecreated, $dateformat);
2259 $messagetext = message_format_message_text($message, false);
2261 if ($keywords) {
2262 $messagetext = highlight($keywords, $messagetext);
2265 $messagetext .= message_format_contexturl($message);
2267 $messagetext = clean_text($messagetext, FORMAT_HTML);
2269 return <<<TEMPLATE
2270 <div class='message $class'>
2271 <a name="m{$message->id}"></a>
2272 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2273 </div>
2274 TEMPLATE;
2278 * Format a the context url and context url name of a message for display
2280 * @param object $message the message object
2281 * @return string the formatted string
2283 function message_format_contexturl($message) {
2284 $s = null;
2286 if (!empty($message->contexturl)) {
2287 $displaytext = null;
2288 if (!empty($message->contexturlname)) {
2289 $displaytext= $message->contexturlname;
2290 } else {
2291 $displaytext= $message->contexturl;
2293 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2294 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2295 $s .= html_writer::end_tag('div');
2298 return $s;
2302 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2304 * @param object $userfrom the message sender
2305 * @param object $userto the message recipient
2306 * @param string $message the message
2307 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2308 * @return int|false the ID of the new message or false
2310 function message_post_message($userfrom, $userto, $message, $format) {
2311 global $SITE, $CFG, $USER;
2313 $eventdata = new stdClass();
2314 $eventdata->component = 'moodle';
2315 $eventdata->name = 'instantmessage';
2316 $eventdata->userfrom = $userfrom;
2317 $eventdata->userto = $userto;
2319 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2320 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2322 if ($format == FORMAT_HTML) {
2323 $eventdata->fullmessagehtml = $message;
2324 //some message processors may revert to sending plain text even if html is supplied
2325 //so we keep both plain and html versions if we're intending to send html
2326 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2327 } else {
2328 $eventdata->fullmessage = $message;
2329 $eventdata->fullmessagehtml = '';
2332 $eventdata->fullmessageformat = $format;
2333 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2335 $s = new stdClass();
2336 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2337 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2339 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2340 if (!empty($eventdata->fullmessage)) {
2341 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2343 if (!empty($eventdata->fullmessagehtml)) {
2344 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2347 $eventdata->timecreated = time();
2348 $eventdata->notification = 0;
2349 return message_send($eventdata);
2353 * Print a row of contactlist displaying user picture, messages waiting and
2354 * block links etc
2356 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2357 * @param bool $incontactlist is the user a contact of ours?
2358 * @param bool $isblocked is the user blocked?
2359 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2360 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2361 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2362 * @return void
2364 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2365 global $OUTPUT, $USER, $COURSE;
2366 $fullname = fullname($contact);
2367 $fullnamelink = $fullname;
2368 $output = '';
2370 $linkclass = '';
2371 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2372 $linkclass = 'messageselecteduser';
2375 // Are there any unread messages for this contact?
2376 if ($contact->messagecount > 0 ){
2377 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2380 $strcontact = $strblock = $strhistory = null;
2382 if ($showactionlinks) {
2383 // Show block and delete links if user is real user.
2384 if (core_user::is_real_user($contact->id)) {
2385 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2386 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2388 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2391 $output .= html_writer::start_tag('div', array('class' => 'pix'));
2392 $output .= $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2393 $output .= html_writer::end_tag('div');
2395 $popupoptions = array(
2396 'height' => MESSAGE_DISCUSSION_HEIGHT,
2397 'width' => MESSAGE_DISCUSSION_WIDTH,
2398 'menubar' => false,
2399 'location' => false,
2400 'status' => true,
2401 'scrollbars' => true,
2402 'resizable' => true);
2404 $link = $action = null;
2405 if (!empty($selectcontacturl)) {
2406 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2407 } else {
2408 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2409 $link = new moodle_url("/message/index.php?id=$contact->id");
2410 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2414 if (strlen($strcontact . $strblock . $strhistory) > 0) {
2415 $output .= html_writer::tag('div', $strcontact . $strblock . $strhistory, array('class' => 'link'));
2417 $output .= html_writer::start_tag('div', array('class' => 'contact'));
2418 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2419 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2420 $output .= html_writer::end_tag('div');
2421 } else {
2422 $output .= html_writer::start_tag('div', array('class' => 'contact nolinks'));
2423 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2424 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2425 $output .= html_writer::end_tag('div');
2428 return $output;
2432 * Constructs the add/remove contact link to display next to other users
2434 * @param bool $incontactlist is the user a contact
2435 * @param bool $isblocked is the user blocked
2436 * @param stdClass $contact contact object
2437 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2438 * @param bool $text include text next to the icons?
2439 * @param bool $icon include a graphical icon?
2440 * @return string
2442 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2443 $strcontact = '';
2445 if($incontactlist){
2446 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2447 } else if ($isblocked) {
2448 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2449 } else{
2450 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2453 return $strcontact;
2457 * Constructs the block contact link to display next to other users
2459 * @param bool $incontactlist is the user a contact?
2460 * @param bool $isblocked is the user blocked?
2461 * @param stdClass $contact contact object
2462 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2463 * @param bool $text include text next to the icons?
2464 * @param bool $icon include a graphical icon?
2465 * @return string
2467 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2468 $strblock = '';
2470 //commented out to allow the user to block a contact without having to remove them first
2471 /*if ($incontactlist) {
2472 //$strblock = '';
2473 } else*/
2474 if ($isblocked) {
2475 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2476 } else{
2477 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2480 return $strblock;
2484 * Moves messages from a particular user from the message table (unread messages) to message_read
2485 * This is typically only used when a user is deleted
2487 * @param object $userid User id
2488 * @return boolean success
2490 function message_move_userfrom_unread2read($userid) {
2491 global $DB;
2493 // move all unread messages from message table to message_read
2494 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2495 foreach ($messages as $message) {
2496 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2499 return true;
2503 * marks ALL messages being sent from $fromuserid to $touserid as read
2505 * @param int $touserid the id of the message recipient
2506 * @param int $fromuserid the id of the message sender
2507 * @return void
2509 function message_mark_messages_read($touserid, $fromuserid) {
2510 global $DB;
2512 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2513 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2515 foreach ($messages as $message) {
2516 message_mark_message_read($message, time());
2519 $messages->close();
2523 * Mark a single message as read
2525 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2526 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2527 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2528 * @return int the ID of the message in the message_read table
2530 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2531 global $DB;
2533 $message->timeread = $timeread;
2535 $messageid = $message->id;
2536 unset($message->id);//unset because it will get a new id on insert into message_read
2538 //If any processors have pending actions abort them
2539 if (!$messageworkingempty) {
2540 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2542 $messagereadid = $DB->insert_record('message_read', $message);
2544 $DB->delete_records('message', array('id' => $messageid));
2546 // Get the context for the user who received the message.
2547 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2548 // If the user no longer exists the context value will be false, in this case use the system context.
2549 if ($context === false) {
2550 $context = context_system::instance();
2553 // Trigger event for reading a message.
2554 $event = \core\event\message_viewed::create(array(
2555 'objectid' => $messagereadid,
2556 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2557 'context' => $context,
2558 'relateduserid' => $message->useridfrom,
2559 'other' => array(
2560 'messageid' => $messageid
2563 $event->trigger();
2565 return $messagereadid;
2569 * Get all message processors, validate corresponding plugin existance and
2570 * system configuration
2572 * @param bool $ready only return ready-to-use processors
2573 * @param bool $reset Reset list of message processors (used in unit tests)
2574 * @param bool $resetonly Just reset, then exit
2575 * @return mixed $processors array of objects containing information on message processors
2577 function get_message_processors($ready = false, $reset = false, $resetonly = false) {
2578 global $DB, $CFG;
2580 static $processors;
2581 if ($reset) {
2582 $processors = array();
2584 if ($resetonly) {
2585 return $processors;
2589 if (empty($processors)) {
2590 // Get all processors, ensure the name column is the first so it will be the array key
2591 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2592 foreach ($processors as &$processor){
2593 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2594 if (is_readable($processorfile)) {
2595 include_once($processorfile);
2596 $processclass = 'message_output_' . $processor->name;
2597 if (class_exists($processclass)) {
2598 $pclass = new $processclass();
2599 $processor->object = $pclass;
2600 $processor->configured = 0;
2601 if ($pclass->is_system_configured()) {
2602 $processor->configured = 1;
2604 $processor->hassettings = 0;
2605 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2606 $processor->hassettings = 1;
2608 $processor->available = 1;
2609 } else {
2610 print_error('errorcallingprocessor', 'message');
2612 } else {
2613 $processor->available = 0;
2617 if ($ready) {
2618 // Filter out enabled and system_configured processors
2619 $readyprocessors = $processors;
2620 foreach ($readyprocessors as $readyprocessor) {
2621 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2622 unset($readyprocessors[$readyprocessor->name]);
2625 return $readyprocessors;
2628 return $processors;
2632 * Get all message providers, validate their plugin existance and
2633 * system configuration
2635 * @return mixed $processors array of objects containing information on message processors
2637 function get_message_providers() {
2638 global $CFG, $DB;
2640 $pluginman = core_plugin_manager::instance();
2642 $providers = $DB->get_records('message_providers', null, 'name');
2644 // Remove all the providers whose plugins are disabled or don't exist
2645 foreach ($providers as $providerid => $provider) {
2646 $plugin = $pluginman->get_plugin_info($provider->component);
2647 if ($plugin) {
2648 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2649 unset($providers[$providerid]); // Plugins does not exist
2650 continue;
2652 if ($plugin->is_enabled() === false) {
2653 unset($providers[$providerid]); // Plugin disabled
2654 continue;
2658 return $providers;
2662 * Get an instance of the message_output class for one of the output plugins.
2663 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2664 * @return message_output message_output the requested class.
2666 function get_message_processor($type) {
2667 global $CFG;
2669 // Note, we cannot use the get_message_processors function here, becaues this
2670 // code is called during install after installing each messaging plugin, and
2671 // get_message_processors caches the list of installed plugins.
2673 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2674 if (!is_readable($processorfile)) {
2675 throw new coding_exception('Unknown message processor type ' . $type);
2678 include_once($processorfile);
2680 $processclass = 'message_output_' . $type;
2681 if (!class_exists($processclass)) {
2682 throw new coding_exception('Message processor ' . $type .
2683 ' does not define the right class');
2686 return new $processclass();
2690 * Get messaging outputs default (site) preferences
2692 * @return object $processors object containing information on message processors
2694 function get_message_output_default_preferences() {
2695 return get_config('message');
2699 * Translate message default settings from binary value to the array of string
2700 * representing the settings to be stored. Also validate the provided value and
2701 * use default if it is malformed.
2703 * @param int $plugindefault Default setting suggested by plugin
2704 * @param string $processorname The name of processor
2705 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2707 function translate_message_default_setting($plugindefault, $processorname) {
2708 // Preset translation arrays
2709 $permittedvalues = array(
2710 0x04 => 'disallowed',
2711 0x08 => 'permitted',
2712 0x0c => 'forced',
2715 $loggedinstatusvalues = array(
2716 0x00 => null, // use null if loggedin/loggedoff is not defined
2717 0x01 => 'loggedin',
2718 0x02 => 'loggedoff',
2721 // define the default setting
2722 $processor = get_message_processor($processorname);
2723 $default = $processor->get_default_messaging_settings();
2725 // Validate the value. It should not exceed the maximum size
2726 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2727 debugging(get_string('errortranslatingdefault', 'message'));
2728 $plugindefault = $default;
2730 // Use plugin default setting of 'permitted' is 0
2731 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2732 $plugindefault = $default;
2735 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2736 $loggedin = $loggedoff = null;
2738 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2739 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2740 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2743 return array($permitted, $loggedin, $loggedoff);
2747 * Return a list of page types
2748 * @param string $pagetype current page type
2749 * @param stdClass $parentcontext Block's parent context
2750 * @param stdClass $currentcontext Current context of block
2752 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2753 return array('messages-*'=>get_string('page-message-x', 'message'));
2757 * Get messages sent or/and received by the specified users.
2758 * Please note that this function return deleted messages too.
2760 * @param int $useridto the user id who received the message
2761 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
2762 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
2763 * @param bool $read true for retrieving read messages, false for unread
2764 * @param string $sort the column name to order by including optionally direction
2765 * @param int $limitfrom limit from
2766 * @param int $limitnum limit num
2767 * @return external_description
2768 * @since 2.8
2770 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
2771 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
2772 global $DB;
2774 $messagetable = $read ? '{message_read}' : '{message}';
2775 $params = array('deleted' => 0);
2777 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
2778 if (empty($useridto)) {
2779 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
2780 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
2781 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
2782 $params['useridfrom'] = $useridfrom;
2783 } else {
2784 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
2785 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
2786 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
2787 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
2788 $params['useridto'] = $useridto;
2789 if (!empty($useridfrom)) {
2790 $usersql .= " AND mr.useridfrom = :useridfrom";
2791 $params['useridfrom'] = $useridfrom;
2795 // Now, if retrieve notifications, conversations or both.
2796 $typesql = "";
2797 if ($notifications !== -1) {
2798 $typesql = "AND mr.notification = :notification";
2799 $params['notification'] = ($notifications) ? 1 : 0;
2802 $sql = "SELECT mr.*, $userfields
2803 FROM $messagetable mr
2804 $joinsql
2805 WHERE $usersql
2806 $typesql
2807 ORDER BY $sort";
2809 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2810 return $messages;
2814 * Requires the JS libraries to send a message using a dialog.
2816 * @return void
2818 function message_messenger_requirejs() {
2819 global $PAGE;
2821 static $done = false;
2822 if ($done) {
2823 return;
2826 $PAGE->requires->yui_module(
2827 array('moodle-core_message-messenger'),
2828 'Y.M.core_message.messenger.init',
2829 array(array())
2831 $PAGE->requires->strings_for_js(array(
2832 'errorwhilesendingmessage',
2833 'messagesent',
2834 'messagetosend',
2835 'sendingmessage',
2836 'sendmessage',
2837 'viewconversation',
2838 ), 'core_message');
2839 $PAGE->requires->strings_for_js(array(
2840 'userisblockingyou',
2841 'userisblockingyounoncontact'
2842 ), 'message');
2843 $PAGE->requires->string_for_js('error', 'core');
2845 $done = true;
2849 * Returns the attributes to place on a link to open the 'Send message' dialog.
2851 * @param object $user User object.
2852 * @return void
2854 function message_messenger_sendmessage_link_params($user) {
2855 $params = array(
2856 'data-trigger' => 'core_message-messenger::sendmessage',
2857 'data-fullname' => fullname($user),
2858 'data-userid' => $user->id,
2859 'role' => 'button'
2862 if (message_is_user_non_contact_blocked($user)) {
2863 $params['data-blocked-string'] = 'userisblockingyounoncontact';
2864 } else if (message_is_user_blocked($user)) {
2865 $params['data-blocked-string'] = 'userisblockingyou';
2868 return $params;
2872 * Determines if a user is permitted to send another user a private message.
2873 * If no sender is provided then it defaults to the logged in user.
2875 * @param object $recipient User object.
2876 * @param object $sender User object.
2877 * @return bool true if user is permitted, false otherwise.
2879 function message_can_post_message($recipient, $sender = null) {
2880 global $USER, $DB;
2882 if (is_null($sender)) {
2883 // The message is from the logged in user, unless otherwise specified.
2884 $sender = $USER;
2887 if (!has_capability('moodle/site:sendmessage', context_system::instance(), $sender)) {
2888 return false;
2891 // The recipient blocks messages from non-contacts and the
2892 // sender isn't a contact.
2893 if (message_is_user_non_contact_blocked($recipient, $sender)) {
2894 return false;
2897 // The recipient has specifically blocked this sender.
2898 if (message_is_user_blocked($recipient, $sender)) {
2899 return false;
2902 return true;
2906 * Checks if the recipient is allowing messages from users that aren't a
2907 * contact. If not then it checks to make sure the sender is in the
2908 * recipient's contacts.
2910 * @param object $recipient User object.
2911 * @param object $sender User object.
2912 * @return bool true if $sender is blocked, false otherwise.
2914 function message_is_user_non_contact_blocked($recipient, $sender = null) {
2915 global $USER, $DB;
2917 if (is_null($sender)) {
2918 // The message is from the logged in user, unless otherwise specified.
2919 $sender = $USER;
2922 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
2923 if (!empty($blockednoncontacts)) {
2924 // Confirm the sender is a contact of the recipient.
2925 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
2926 if ($exists) {
2927 // All good, the recipient is a contact of the sender.
2928 return false;
2929 } else {
2930 // Oh no, the recipient is not a contact. Looks like we can't send the message.
2931 return true;
2935 return false;
2939 * Checks if the recipient has specifically blocked the sending user.
2941 * Note: This function will always return false if the sender has the
2942 * readallmessages capability at the system context level.
2944 * @param object $recipient User object.
2945 * @param object $sender User object.
2946 * @return bool true if $sender is blocked, false otherwise.
2948 function message_is_user_blocked($recipient, $sender = null) {
2949 global $USER, $DB;
2951 if (is_null($sender)) {
2952 // The message is from the logged in user, unless otherwise specified.
2953 $sender = $USER;
2956 $systemcontext = context_system::instance();
2957 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender)) {
2958 return false;
2961 if ($contact = $DB->get_record('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id))) {
2962 if ($contact->blocked) {
2963 return true;
2967 return false;