Merge branch 'wip-mdl-51101' of git://github.com/rajeshtaneja/moodle
[moodle.git] / message / lib.php
blobf7a767608aafa3469475a905231b312caaa68053
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 return $DB->update_record($messagetable, $updatemessage);
1221 * Load a user's contact record
1223 * @param int $contactid the user ID of the user whose contact record you want
1224 * @return array message contacts
1226 function message_get_contact($contactid) {
1227 global $USER, $DB;
1228 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
1232 * Print the results of a message search
1234 * @param mixed $frm submitted form data
1235 * @param bool $showicontext show text next to action icons?
1236 * @param object $currentuser the current user
1237 * @return void
1239 function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
1240 global $USER, $DB, $OUTPUT;
1242 if (empty($currentuser)) {
1243 $currentuser = $USER;
1246 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
1248 $personsearch = false;
1249 $personsearchstring = null;
1250 if (!empty($frm->personsubmit) and !empty($frm->name)) {
1251 $personsearch = true;
1252 $personsearchstring = $frm->name;
1253 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1254 $personsearch = true;
1255 $personsearchstring = $frm->combinedsearch;
1258 // Search for person.
1259 if ($personsearch) {
1260 if (optional_param('mycourses', 0, PARAM_BOOL)) {
1261 $users = array();
1262 $mycourses = enrol_get_my_courses('id');
1263 $mycoursesids = array();
1264 foreach ($mycourses as $mycourse) {
1265 $mycoursesids[] = $mycourse->id;
1267 $susers = message_search_users($mycoursesids, $personsearchstring);
1268 foreach ($susers as $suser) {
1269 $users[$suser->id] = $suser;
1271 } else {
1272 $users = message_search_users(SITEID, $personsearchstring);
1275 if (!empty($users)) {
1276 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1277 echo get_string('userssearchresults', 'message', count($users));
1278 echo html_writer::end_tag('p');
1280 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
1281 foreach ($users as $user) {
1283 if ( $user->contactlistid ) {
1284 if ($user->blocked == 0) { // User is not blocked.
1285 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1286 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1287 } else { // blocked
1288 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1289 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
1291 } else {
1292 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1293 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1296 // Should we show just the icon or icon and text?
1297 $histicontext = 'icon';
1298 if ($showicontext) {
1299 $histicontext = 'both';
1301 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
1303 echo html_writer::start_tag('tr');
1305 echo html_writer::start_tag('td', array('class' => 'pix'));
1306 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1307 echo html_writer::end_tag('td');
1309 echo html_writer::start_tag('td',array('class' => 'contact'));
1310 $action = null;
1311 $link = new moodle_url("/message/index.php?id=$user->id");
1312 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1313 echo html_writer::end_tag('td');
1315 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1316 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1317 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
1319 echo html_writer::end_tag('tr');
1321 echo html_writer::end_tag('table');
1323 } else {
1324 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1325 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
1326 echo html_writer::end_tag('p');
1330 // search messages for keywords
1331 $messagesearch = false;
1332 $messagesearchstring = null;
1333 if (!empty($frm->keywords)) {
1334 $messagesearch = true;
1335 $messagesearchstring = clean_text(trim($frm->keywords));
1336 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1337 $messagesearch = true;
1338 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1341 if ($messagesearch) {
1342 if ($messagesearchstring) {
1343 $keywords = explode(' ', $messagesearchstring);
1344 } else {
1345 $keywords = array();
1347 $tome = false;
1348 $fromme = false;
1349 $courseid = 'none';
1351 if (empty($frm->keywordsoption)) {
1352 $frm->keywordsoption = 'allmine';
1355 switch ($frm->keywordsoption) {
1356 case 'tome':
1357 $tome = true;
1358 break;
1359 case 'fromme':
1360 $fromme = true;
1361 break;
1362 case 'allmine':
1363 $tome = true;
1364 $fromme = true;
1365 break;
1366 case 'allusers':
1367 $courseid = SITEID;
1368 break;
1369 case 'courseusers':
1370 $courseid = $frm->courseid;
1371 break;
1372 default:
1373 $tome = true;
1374 $fromme = true;
1377 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
1379 // Get a list of contacts.
1380 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
1381 $contacts = array();
1384 // Print heading with number of results.
1385 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
1386 $countresults = count($messages);
1387 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
1388 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1389 } else {
1390 echo get_string('keywordssearchresults', 'message', $countresults);
1392 echo html_writer::end_tag('p');
1394 // Print table headings.
1395 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
1397 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
1398 $headertdend = html_writer::end_tag('td');
1399 echo html_writer::start_tag('tr');
1400 echo $headertdstart.get_string('from').$headertdend;
1401 echo $headertdstart.get_string('to').$headertdend;
1402 echo $headertdstart.get_string('message', 'message').$headertdend;
1403 echo $headertdstart.get_string('timesent', 'message').$headertdend;
1404 echo html_writer::end_tag('tr');
1406 $blockedcount = 0;
1407 $dateformat = get_string('strftimedatetimeshort');
1408 $strcontext = get_string('context', 'message');
1409 foreach ($messages as $message) {
1411 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
1412 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
1413 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1414 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1417 $blockedcount ++;
1418 continue;
1421 // Load user-to record.
1422 if ($message->useridto !== $USER->id) {
1423 $userto = core_user::get_user($message->useridto);
1424 $tocontact = (array_key_exists($message->useridto, $contacts) and
1425 ($contacts[$message->useridto]->blocked == 0) );
1426 $toblocked = (array_key_exists($message->useridto, $contacts) and
1427 ($contacts[$message->useridto]->blocked == 1) );
1428 } else {
1429 $userto = false;
1430 $tocontact = false;
1431 $toblocked = false;
1434 // Load user-from record.
1435 if ($message->useridfrom !== $USER->id) {
1436 $userfrom = core_user::get_user($message->useridfrom);
1437 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
1438 ($contacts[$message->useridfrom]->blocked == 0) );
1439 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
1440 ($contacts[$message->useridfrom]->blocked == 1) );
1441 } else {
1442 $userfrom = false;
1443 $fromcontact = false;
1444 $fromblocked = false;
1447 // Find date string for this message.
1448 $date = usergetdate($message->timecreated);
1449 $datestring = $date['year'].$date['mon'].$date['mday'];
1451 // Print out message row.
1452 echo html_writer::start_tag('tr', array('valign' => 'top'));
1454 echo html_writer::start_tag('td', array('class' => 'contact'));
1455 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
1456 echo html_writer::end_tag('td');
1458 echo html_writer::start_tag('td', array('class' => 'contact'));
1459 message_print_user($userto, $tocontact, $toblocked, $showicontext);
1460 echo html_writer::end_tag('td');
1462 echo html_writer::start_tag('td', array('class' => 'summary'));
1463 echo message_get_fragment($message->smallmessage, $keywords);
1464 echo html_writer::start_tag('div', array('class' => 'link'));
1466 // If the user clicks the context link display message sender on the left.
1467 // EXCEPT if the current user is in the conversation. Current user == always on the left.
1468 $leftsideuserid = $rightsideuserid = null;
1469 if ($currentuser->id == $message->useridto) {
1470 $leftsideuserid = $message->useridto;
1471 $rightsideuserid = $message->useridfrom;
1472 } else {
1473 $leftsideuserid = $message->useridfrom;
1474 $rightsideuserid = $message->useridto;
1476 message_history_link($leftsideuserid, $rightsideuserid, false,
1477 $messagesearchstring, 'm'.$message->id, $strcontext);
1478 echo html_writer::end_tag('div');
1479 echo html_writer::end_tag('td');
1481 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1483 echo html_writer::end_tag('tr');
1487 if ($blockedcount > 0) {
1488 echo html_writer::start_tag('tr');
1489 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1490 echo html_writer::end_tag('tr');
1492 echo html_writer::end_tag('table');
1494 } else {
1495 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
1499 if (!$personsearch && !$messagesearch) {
1500 //they didn't enter any search terms
1501 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
1504 echo html_writer::end_tag('div');
1508 * Print information on a user. Used when printing search results.
1510 * @param object/bool $user the user to display or false if you just want $USER
1511 * @param bool $iscontact is the user being displayed a contact?
1512 * @param bool $isblocked is the user being displayed blocked?
1513 * @param bool $includeicontext include text next to the action icons?
1514 * @return void
1516 function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
1517 global $USER, $OUTPUT;
1519 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1521 if ($user === false) {
1522 echo $OUTPUT->user_picture($USER, $userpictureparams);
1523 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1524 $userpictureparams['link'] = false;
1525 echo $OUTPUT->user_picture($USER, $userpictureparams);
1526 echo fullname($user);
1527 } else {
1528 echo $OUTPUT->user_picture($user, $userpictureparams);
1530 $link = new moodle_url("/message/index.php?id=$user->id");
1531 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1532 get_string('sendmessageto', 'message', fullname($user))));
1534 $return = false;
1535 $script = null;
1536 if ($iscontact) {
1537 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
1538 } else {
1539 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
1542 if ($isblocked) {
1543 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
1544 } else {
1545 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
1551 * Print a message contact link
1553 * @param int $userid the ID of the user to apply to action to
1554 * @param string $linktype can be add, remove, block or unblock
1555 * @param bool $return if true return the link as a string. If false echo the link.
1556 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1557 * @param bool $text include text next to the icons?
1558 * @param bool $icon include a graphical icon?
1559 * @return string if $return is true otherwise bool
1561 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
1562 global $OUTPUT, $PAGE;
1564 //hold onto the strings as we're probably creating a bunch of links
1565 static $str;
1567 if (empty($script)) {
1568 //strip off previous action params like 'removecontact'
1569 $script = message_remove_url_params($PAGE->url);
1572 if (empty($str->blockcontact)) {
1573 $str = new stdClass();
1574 $str->blockcontact = get_string('blockcontact', 'message');
1575 $str->unblockcontact = get_string('unblockcontact', 'message');
1576 $str->removecontact = get_string('removecontact', 'message');
1577 $str->addcontact = get_string('addcontact', 'message');
1580 $command = $linktype.'contact';
1581 $string = $str->{$command};
1583 $safealttext = s($string);
1585 $safestring = '';
1586 if (!empty($text)) {
1587 $safestring = $safealttext;
1590 $img = '';
1591 if ($icon) {
1592 $iconpath = null;
1593 switch ($linktype) {
1594 case 'block':
1595 $iconpath = 't/block';
1596 break;
1597 case 'unblock':
1598 $iconpath = 't/unblock';
1599 break;
1600 case 'remove':
1601 $iconpath = 't/removecontact';
1602 break;
1603 case 'add':
1604 default:
1605 $iconpath = 't/addcontact';
1608 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
1611 $output = '<span class="'.$linktype.'contact">'.
1612 '<a href="'.$script.'&amp;'.$command.'='.$userid.
1613 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
1614 $img.
1615 $safestring.'</a></span>';
1617 if ($return) {
1618 return $output;
1619 } else {
1620 echo $output;
1621 return true;
1626 * echo or return a link to take the user to the full message history between themselves and another user
1628 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
1629 * @param int $userid2 the ID of the other user
1630 * @param bool $return true to return the link as a string. False to echo the link.
1631 * @param string $keywords any keywords to highlight in the message history
1632 * @param string $position anchor name to jump to within the message history
1633 * @param string $linktext optionally specify the link text
1634 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1636 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1637 global $OUTPUT, $PAGE;
1638 static $strmessagehistory;
1640 if (empty($strmessagehistory)) {
1641 $strmessagehistory = get_string('messagehistory', 'message');
1644 if ($position) {
1645 $position = "#$position";
1647 if ($keywords) {
1648 $keywords = "&search=".urlencode($keywords);
1651 if ($linktext == 'icon') { // Icon only
1652 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
1653 } else if ($linktext == 'both') { // Icon and standard name
1654 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
1655 $fulllink .= '&nbsp;'.$strmessagehistory;
1656 } else if ($linktext) { // Custom name
1657 $fulllink = $linktext;
1658 } else { // Standard name only
1659 $fulllink = $strmessagehistory;
1662 $popupoptions = array(
1663 'height' => 500,
1664 'width' => 500,
1665 'menubar' => false,
1666 'location' => false,
1667 'status' => true,
1668 'scrollbars' => true,
1669 'resizable' => true);
1671 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
1672 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1673 $link->param('viewing', $PAGE->url->get_param('viewing'));
1675 $action = null;
1676 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
1678 $str = '<span class="history">'.$str.'</span>';
1680 if ($return) {
1681 return $str;
1682 } else {
1683 echo $str;
1684 return true;
1690 * Search through course users.
1692 * If $courseids contains the site course then this function searches
1693 * through all undeleted and confirmed users.
1695 * @param int|array $courseids Course ID or array of course IDs.
1696 * @param string $searchtext the text to search for.
1697 * @param string $sort the column name to order by.
1698 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
1699 * @return array An array of {@link $USER} records.
1701 function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
1702 global $CFG, $USER, $DB;
1704 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1705 if (!$courseids) {
1706 $courseids = array(SITEID);
1709 // Allow an integer to be passed.
1710 if (!is_array($courseids)) {
1711 $courseids = array($courseids);
1714 $fullname = $DB->sql_fullname();
1715 $ufields = user_picture::fields('u');
1717 if (!empty($sort)) {
1718 $order = ' ORDER BY '. $sort;
1719 } else {
1720 $order = '';
1723 $params = array(
1724 'userid' => $USER->id,
1725 'query' => "%$searchtext%"
1728 if (empty($exceptions)) {
1729 $exceptions = array();
1730 } else if (!empty($exceptions) && is_string($exceptions)) {
1731 $exceptions = explode(',', $exceptions);
1734 // Ignore self and guest account.
1735 $exceptions[] = $USER->id;
1736 $exceptions[] = $CFG->siteguest;
1738 // Exclude exceptions from the search result.
1739 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1740 $except = ' AND u.id ' . $except;
1741 $params = array_merge($params_except, $params);
1743 if (in_array(SITEID, $courseids)) {
1744 // Search on site level.
1745 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1746 FROM {user} u
1747 LEFT JOIN {message_contacts} mc
1748 ON mc.contactid = u.id AND mc.userid = :userid
1749 WHERE u.deleted = '0' AND u.confirmed = '1'
1750 AND (".$DB->sql_like($fullname, ':query', false).")
1751 $except
1752 $order", $params);
1753 } else {
1754 // Search in courses.
1756 // Getting the context IDs or each course.
1757 $contextids = array();
1758 foreach ($courseids as $courseid) {
1759 $context = context_course::instance($courseid);
1760 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1762 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
1763 $params = array_merge($params, $contextparams);
1765 // Everyone who has a role assignment in this course or higher.
1766 // TODO: add enabled enrolment join here (skodak)
1767 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
1768 FROM {user} u
1769 JOIN {role_assignments} ra ON ra.userid = u.id
1770 LEFT JOIN {message_contacts} mc
1771 ON mc.contactid = u.id AND mc.userid = :userid
1772 WHERE u.deleted = '0' AND u.confirmed = '1'
1773 AND (".$DB->sql_like($fullname, ':query', false).")
1774 AND ra.contextid $contextwhere
1775 $except
1776 $order", $params);
1778 return $users;
1783 * Search a user's messages
1785 * Returns a list of posts found using an array of search terms
1786 * eg word +word -word
1788 * @param array $searchterms an array of search terms (strings)
1789 * @param bool $fromme include messages from the user?
1790 * @param bool $tome include messages to the user?
1791 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1792 * @param int $userid the user ID of the current user
1793 * @return mixed An array of messages or false if no matching messages were found
1795 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
1796 global $CFG, $USER, $DB;
1798 // If user is searching all messages check they are allowed to before doing anything else.
1799 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
1800 print_error('accessdenied','admin');
1803 // If no userid sent then assume current user.
1804 if ($userid == 0) $userid = $USER->id;
1806 // Some differences in SQL syntax.
1807 if ($DB->sql_regex_supported()) {
1808 $REGEXP = $DB->sql_regex(true);
1809 $NOTREGEXP = $DB->sql_regex(false);
1812 $searchcond = array();
1813 $params = array();
1814 $i = 0;
1816 // Preprocess search terms to check whether we have at least 1 eligible search term.
1817 // If we do we can drop words around it like 'a'.
1818 $dropshortwords = false;
1819 foreach ($searchterms as $searchterm) {
1820 if (strlen($searchterm) >= 2) {
1821 $dropshortwords = true;
1825 foreach ($searchterms as $searchterm) {
1826 $i++;
1828 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
1830 if ($dropshortwords && strlen($searchterm) < 2) {
1831 continue;
1833 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
1834 if (!$DB->sql_regex_supported()) {
1835 if (substr($searchterm, 0, 1) == '-') {
1836 $NOT = true;
1838 $searchterm = trim($searchterm, '+-');
1841 if (substr($searchterm,0,1) == "+") {
1842 $searchterm = substr($searchterm,1);
1843 $searchterm = preg_quote($searchterm, '|');
1844 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
1845 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1847 } else if (substr($searchterm,0,1) == "-") {
1848 $searchterm = substr($searchterm,1);
1849 $searchterm = preg_quote($searchterm, '|');
1850 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
1851 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1853 } else {
1854 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
1855 $params['ss'.$i] = "%$searchterm%";
1859 if (empty($searchcond)) {
1860 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
1861 $params['ss1'] = "%";
1862 } else {
1863 $searchcond = implode(" AND ", $searchcond);
1866 // There are several possibilities
1867 // 1. courseid = SITEID : The admin is searching messages by all users
1868 // 2. courseid = ?? : A teacher is searching messages by users in
1869 // one of their courses - currently disabled
1870 // 3. courseid = none : User is searching their own messages;
1871 // a. Messages from user
1872 // b. Messages to user
1873 // c. Messages to and from user
1875 if ($fromme && $tome) {
1876 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
1877 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
1878 $params['useridto'] = $userid;
1879 $params['useridfrom'] = $userid;
1880 } else if ($fromme) {
1881 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
1882 $params['useridfrom'] = $userid;
1883 } else if ($tome) {
1884 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
1885 $params['useridto'] = $userid;
1887 if ($courseid == SITEID) { // Admin is searching all messages.
1888 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1889 FROM {message_read} m
1890 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1891 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1892 FROM {message} m
1893 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1895 } else if ($courseid !== 'none') {
1896 // This has not been implemented due to security concerns.
1897 $m_read = array();
1898 $m_unread = array();
1900 } else {
1902 if ($fromme and $tome) {
1903 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1904 $params['userid1'] = $userid;
1905 $params['userid2'] = $userid;
1907 } else if ($fromme) {
1908 $searchcond .= " AND m.useridfrom=:userid";
1909 $params['userid'] = $userid;
1911 } else if ($tome) {
1912 $searchcond .= " AND m.useridto=:userid";
1913 $params['userid'] = $userid;
1916 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1917 FROM {message_read} m
1918 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1919 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
1920 FROM {message} m
1921 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
1925 /// The keys may be duplicated in $m_read and $m_unread so we can't
1926 /// do a simple concatenation
1927 $messages = array();
1928 foreach ($m_read as $m) {
1929 $messages[] = $m;
1931 foreach ($m_unread as $m) {
1932 $messages[] = $m;
1935 return (empty($messages)) ? false : $messages;
1939 * Given a message object that we already know has a long message
1940 * this function truncates the message nicely to the first
1941 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1943 * @param string $message the message
1944 * @param int $minlength the minimum length to trim the message to
1945 * @return string the shortened message
1947 function message_shorten_message($message, $minlength = 0) {
1948 $i = 0;
1949 $tag = false;
1950 $length = strlen($message);
1951 $count = 0;
1952 $stopzone = false;
1953 $truncate = 0;
1954 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
1957 for ($i=0; $i<$length; $i++) {
1958 $char = $message[$i];
1960 switch ($char) {
1961 case "<":
1962 $tag = true;
1963 break;
1964 case ">":
1965 $tag = false;
1966 break;
1967 default:
1968 if (!$tag) {
1969 if ($stopzone) {
1970 if ($char == '.' or $char == ' ') {
1971 $truncate = $i+1;
1972 break 2;
1975 $count++;
1977 break;
1979 if (!$stopzone) {
1980 if ($count > $minlength) {
1981 $stopzone = true;
1986 if (!$truncate) {
1987 $truncate = $i;
1990 return substr($message, 0, $truncate);
1995 * Given a string and an array of keywords, this function looks
1996 * for the first keyword in the string, and then chops out a
1997 * small section from the text that shows that word in context.
1999 * @param string $message the text to search
2000 * @param array $keywords array of keywords to find
2002 function message_get_fragment($message, $keywords) {
2004 $fullsize = 160;
2005 $halfsize = (int)($fullsize/2);
2007 $message = strip_tags($message);
2009 foreach ($keywords as $keyword) { // Just get the first one
2010 if ($keyword !== '') {
2011 break;
2014 if (empty($keyword)) { // None found, so just return start of message
2015 return message_shorten_message($message, 30);
2018 $leadin = $leadout = '';
2020 /// Find the start of the fragment
2021 $start = 0;
2022 $length = strlen($message);
2024 $pos = strpos($message, $keyword);
2025 if ($pos > $halfsize) {
2026 $start = $pos - $halfsize;
2027 $leadin = '...';
2029 /// Find the end of the fragment
2030 $end = $start + $fullsize;
2031 if ($end > $length) {
2032 $end = $length;
2033 } else {
2034 $leadout = '...';
2037 /// Pull out the fragment and format it
2039 $fragment = substr($message, $start, $end - $start);
2040 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
2041 return $fragment;
2045 * Retrieve the messages between two users
2047 * @param object $user1 the current user
2048 * @param object $user2 the other user
2049 * @param int $limitnum the maximum number of messages to retrieve
2050 * @param bool $viewingnewmessages are we currently viewing new messages?
2052 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
2053 global $DB, $CFG;
2055 $messages = array();
2057 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
2058 //desc to get the last $limitnum messages then flip the order in php
2059 $sort = 'asc';
2060 if ($limitnum>0) {
2061 $sort = 'desc';
2064 $notificationswhere = null;
2065 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
2066 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
2067 $notificationswhere = 'AND notification=0';
2070 //prevent notifications of your own actions appearing in your own message history
2071 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
2073 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
2074 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
2075 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
2076 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
2077 "timecreated $sort", '*', 0, $limitnum)) {
2078 foreach ($messages_read as $message) {
2079 $messages[] = $message;
2082 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
2083 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
2084 "timecreated $sort", '*', 0, $limitnum)) {
2085 foreach ($messages_new as $message) {
2086 $messages[] = $message;
2090 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
2092 //if we only want the last $limitnum messages
2093 $messagecount = count($messages);
2094 if ($limitnum > 0 && $messagecount > $limitnum) {
2095 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
2098 return $messages;
2102 * Print the message history between two users
2104 * @param object $user1 the current user
2105 * @param object $user2 the other user
2106 * @param string $search search terms to highlight
2107 * @param int $messagelimit maximum number of messages to return
2108 * @param string $messagehistorylink the html for the message history link or false
2109 * @param bool $viewingnewmessages are we currently viewing new messages?
2111 function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
2112 global $OUTPUT, $PAGE;
2114 $PAGE->requires->yui_module(
2115 array('moodle-core_message-toolbox'),
2116 'M.core_message.toolbox.deletemsg.init',
2117 array(array())
2120 echo $OUTPUT->box_start('center', 'message_user_pictures');
2121 echo $OUTPUT->box_start('user');
2122 echo $OUTPUT->box_start('generalbox', 'user1');
2123 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2124 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
2125 echo $OUTPUT->box_end();
2126 echo $OUTPUT->box_end();
2128 $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16);
2129 echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between');
2131 echo $OUTPUT->box_start('user');
2132 echo $OUTPUT->box_start('generalbox', 'user2');
2133 // Show user picture with link is real user else without link.
2134 if (core_user::is_real_user($user2->id)) {
2135 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2136 } else {
2137 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2139 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
2141 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
2143 $script = null;
2144 $text = true;
2145 $icon = false;
2147 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2148 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2149 $useractionlinks = $strcontact.'&nbsp;|&nbsp;'.$strblock;
2151 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
2153 echo $OUTPUT->box_end();
2154 echo $OUTPUT->box_end();
2155 echo $OUTPUT->box_end();
2157 if (!empty($messagehistorylink)) {
2158 echo $messagehistorylink;
2161 /// Get all the messages and print them
2162 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
2163 $tablecontents = '';
2165 $current = new stdClass();
2166 $current->mday = '';
2167 $current->month = '';
2168 $current->year = '';
2169 $messagedate = get_string('strftimetime');
2170 $blockdate = get_string('strftimedaydate');
2171 $messagenumber = 0;
2172 foreach ($messages as $message) {
2173 $messagenumber++;
2174 if ($message->notification) {
2175 $notificationclass = ' notification';
2176 } else {
2177 $notificationclass = null;
2179 $date = usergetdate($message->timecreated);
2180 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2181 $current->mday = $date['mday'];
2182 $current->month = $date['month'];
2183 $current->year = $date['year'];
2185 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2186 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2188 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
2191 if ($message->useridfrom == $user1->id) {
2192 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2193 $side = 'left';
2194 } else {
2195 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2196 $side = 'right';
2199 // Check if it is a read message or not.
2200 if (isset($message->timeread)) {
2201 $type = 'message_read';
2202 } else {
2203 $type = 'message';
2206 if (message_can_delete_message($message, $user1->id)) {
2207 $usergroup = optional_param('usergroup', MESSAGE_VIEW_UNREAD_MESSAGES, PARAM_ALPHANUMEXT);
2208 $viewing = optional_param('viewing', $usergroup, PARAM_ALPHANUMEXT);
2209 $deleteurl = new moodle_url('/message/index.php', array('user1' => $user1->id, 'user2' => $user2->id,
2210 'viewing' => $viewing, 'deletemessageid' => $message->id, 'deletemessagetype' => $type,
2211 'sesskey' => sesskey()));
2213 $deleteicon = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete')));
2214 $deleteicon = html_writer::tag('div', $deleteicon, array('class' => 'deleteicon accesshide'));
2215 $formatted_message .= $deleteicon;
2218 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left messagecontent
2219 $side $notificationclass", 'id' => 'message_' . $messagenumber));
2222 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
2223 } else {
2224 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
2229 * Format a message for display in the message history
2231 * @param object $message the message object
2232 * @param string $format optional date format
2233 * @param string $keywords keywords to highlight
2234 * @param string $class CSS class to apply to the div around the message
2235 * @return string the formatted message
2237 function message_format_message($message, $format='', $keywords='', $class='other') {
2239 static $dateformat;
2241 //if we haven't previously set the date format or they've supplied a new one
2242 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
2243 if ($format) {
2244 $dateformat = $format;
2245 } else {
2246 $dateformat = get_string('strftimedatetimeshort');
2249 $time = userdate($message->timecreated, $dateformat);
2251 $messagetext = message_format_message_text($message, false);
2253 if ($keywords) {
2254 $messagetext = highlight($keywords, $messagetext);
2257 $messagetext .= message_format_contexturl($message);
2259 $messagetext = clean_text($messagetext, FORMAT_HTML);
2261 return <<<TEMPLATE
2262 <div class='message $class'>
2263 <a name="m{$message->id}"></a>
2264 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2265 </div>
2266 TEMPLATE;
2270 * Format a the context url and context url name of a message for display
2272 * @param object $message the message object
2273 * @return string the formatted string
2275 function message_format_contexturl($message) {
2276 $s = null;
2278 if (!empty($message->contexturl)) {
2279 $displaytext = null;
2280 if (!empty($message->contexturlname)) {
2281 $displaytext= $message->contexturlname;
2282 } else {
2283 $displaytext= $message->contexturl;
2285 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2286 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2287 $s .= html_writer::end_tag('div');
2290 return $s;
2294 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
2296 * @param object $userfrom the message sender
2297 * @param object $userto the message recipient
2298 * @param string $message the message
2299 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
2300 * @return int|false the ID of the new message or false
2302 function message_post_message($userfrom, $userto, $message, $format) {
2303 global $SITE, $CFG, $USER;
2305 $eventdata = new stdClass();
2306 $eventdata->component = 'moodle';
2307 $eventdata->name = 'instantmessage';
2308 $eventdata->userfrom = $userfrom;
2309 $eventdata->userto = $userto;
2311 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2312 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2314 if ($format == FORMAT_HTML) {
2315 $eventdata->fullmessagehtml = $message;
2316 //some message processors may revert to sending plain text even if html is supplied
2317 //so we keep both plain and html versions if we're intending to send html
2318 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
2319 } else {
2320 $eventdata->fullmessage = $message;
2321 $eventdata->fullmessagehtml = '';
2324 $eventdata->fullmessageformat = $format;
2325 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
2327 $s = new stdClass();
2328 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
2329 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
2331 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
2332 if (!empty($eventdata->fullmessage)) {
2333 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2335 if (!empty($eventdata->fullmessagehtml)) {
2336 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2339 $eventdata->timecreated = time();
2340 $eventdata->notification = 0;
2341 return message_send($eventdata);
2345 * Print a row of contactlist displaying user picture, messages waiting and
2346 * block links etc
2348 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2349 * @param bool $incontactlist is the user a contact of ours?
2350 * @param bool $isblocked is the user blocked?
2351 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2352 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2353 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
2354 * @return void
2356 function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
2357 global $OUTPUT, $USER, $COURSE;
2358 $fullname = fullname($contact);
2359 $fullnamelink = $fullname;
2360 $output = '';
2362 $linkclass = '';
2363 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
2364 $linkclass = 'messageselecteduser';
2367 // Are there any unread messages for this contact?
2368 if ($contact->messagecount > 0 ){
2369 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2372 $strcontact = $strblock = $strhistory = null;
2374 if ($showactionlinks) {
2375 // Show block and delete links if user is real user.
2376 if (core_user::is_real_user($contact->id)) {
2377 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2378 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2380 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
2383 $output .= html_writer::start_tag('div', array('class' => 'pix'));
2384 $output .= $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2385 $output .= html_writer::end_tag('div');
2387 $popupoptions = array(
2388 'height' => MESSAGE_DISCUSSION_HEIGHT,
2389 'width' => MESSAGE_DISCUSSION_WIDTH,
2390 'menubar' => false,
2391 'location' => false,
2392 'status' => true,
2393 'scrollbars' => true,
2394 'resizable' => true);
2396 $link = $action = null;
2397 if (!empty($selectcontacturl)) {
2398 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
2399 } else {
2400 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2401 $link = new moodle_url("/message/index.php?id=$contact->id");
2402 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2406 if (strlen($strcontact . $strblock . $strhistory) > 0) {
2407 $output .= html_writer::tag('div', $strcontact . $strblock . $strhistory, array('class' => 'link'));
2409 $output .= html_writer::start_tag('div', array('class' => 'contact'));
2410 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2411 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2412 $output .= html_writer::end_tag('div');
2413 } else {
2414 $output .= html_writer::start_tag('div', array('class' => 'contact nolinks'));
2415 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2416 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2417 $output .= html_writer::end_tag('div');
2420 return $output;
2424 * Constructs the add/remove contact link to display next to other users
2426 * @param bool $incontactlist is the user a contact
2427 * @param bool $isblocked is the user blocked
2428 * @param stdClass $contact contact object
2429 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2430 * @param bool $text include text next to the icons?
2431 * @param bool $icon include a graphical icon?
2432 * @return string
2434 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2435 $strcontact = '';
2437 if($incontactlist){
2438 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2439 } else if ($isblocked) {
2440 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2441 } else{
2442 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2445 return $strcontact;
2449 * Constructs the block contact link to display next to other users
2451 * @param bool $incontactlist is the user a contact?
2452 * @param bool $isblocked is the user blocked?
2453 * @param stdClass $contact contact object
2454 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2455 * @param bool $text include text next to the icons?
2456 * @param bool $icon include a graphical icon?
2457 * @return string
2459 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2460 $strblock = '';
2462 //commented out to allow the user to block a contact without having to remove them first
2463 /*if ($incontactlist) {
2464 //$strblock = '';
2465 } else*/
2466 if ($isblocked) {
2467 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2468 } else{
2469 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2472 return $strblock;
2476 * Moves messages from a particular user from the message table (unread messages) to message_read
2477 * This is typically only used when a user is deleted
2479 * @param object $userid User id
2480 * @return boolean success
2482 function message_move_userfrom_unread2read($userid) {
2483 global $DB;
2485 // move all unread messages from message table to message_read
2486 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2487 foreach ($messages as $message) {
2488 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
2491 return true;
2495 * marks ALL messages being sent from $fromuserid to $touserid as read
2497 * @param int $touserid the id of the message recipient
2498 * @param int $fromuserid the id of the message sender
2499 * @return void
2501 function message_mark_messages_read($touserid, $fromuserid) {
2502 global $DB;
2504 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
2505 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
2507 foreach ($messages as $message) {
2508 message_mark_message_read($message, time());
2511 $messages->close();
2515 * Mark a single message as read
2517 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
2518 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2519 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2520 * @return int the ID of the message in the message_read table
2522 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2523 global $DB;
2525 $message->timeread = $timeread;
2527 $messageid = $message->id;
2528 unset($message->id);//unset because it will get a new id on insert into message_read
2530 //If any processors have pending actions abort them
2531 if (!$messageworkingempty) {
2532 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
2534 $messagereadid = $DB->insert_record('message_read', $message);
2536 $DB->delete_records('message', array('id' => $messageid));
2538 // Get the context for the user who received the message.
2539 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2540 // If the user no longer exists the context value will be false, in this case use the system context.
2541 if ($context === false) {
2542 $context = context_system::instance();
2545 // Trigger event for reading a message.
2546 $event = \core\event\message_viewed::create(array(
2547 'objectid' => $messagereadid,
2548 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
2549 'context' => $context,
2550 'relateduserid' => $message->useridfrom,
2551 'other' => array(
2552 'messageid' => $messageid
2555 $event->trigger();
2557 return $messagereadid;
2561 * Get all message processors, validate corresponding plugin existance and
2562 * system configuration
2564 * @param bool $ready only return ready-to-use processors
2565 * @param bool $reset Reset list of message processors (used in unit tests)
2566 * @return mixed $processors array of objects containing information on message processors
2568 function get_message_processors($ready = false, $reset = false) {
2569 global $DB, $CFG;
2571 static $processors;
2572 if ($reset) {
2573 $processors = array();
2576 if (empty($processors)) {
2577 // Get all processors, ensure the name column is the first so it will be the array key
2578 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
2579 foreach ($processors as &$processor){
2580 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2581 if (is_readable($processorfile)) {
2582 include_once($processorfile);
2583 $processclass = 'message_output_' . $processor->name;
2584 if (class_exists($processclass)) {
2585 $pclass = new $processclass();
2586 $processor->object = $pclass;
2587 $processor->configured = 0;
2588 if ($pclass->is_system_configured()) {
2589 $processor->configured = 1;
2591 $processor->hassettings = 0;
2592 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2593 $processor->hassettings = 1;
2595 $processor->available = 1;
2596 } else {
2597 print_error('errorcallingprocessor', 'message');
2599 } else {
2600 $processor->available = 0;
2604 if ($ready) {
2605 // Filter out enabled and system_configured processors
2606 $readyprocessors = $processors;
2607 foreach ($readyprocessors as $readyprocessor) {
2608 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2609 unset($readyprocessors[$readyprocessor->name]);
2612 return $readyprocessors;
2615 return $processors;
2619 * Get all message providers, validate their plugin existance and
2620 * system configuration
2622 * @return mixed $processors array of objects containing information on message processors
2624 function get_message_providers() {
2625 global $CFG, $DB;
2627 $pluginman = core_plugin_manager::instance();
2629 $providers = $DB->get_records('message_providers', null, 'name');
2631 // Remove all the providers whose plugins are disabled or don't exist
2632 foreach ($providers as $providerid => $provider) {
2633 $plugin = $pluginman->get_plugin_info($provider->component);
2634 if ($plugin) {
2635 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
2636 unset($providers[$providerid]); // Plugins does not exist
2637 continue;
2639 if ($plugin->is_enabled() === false) {
2640 unset($providers[$providerid]); // Plugin disabled
2641 continue;
2645 return $providers;
2649 * Get an instance of the message_output class for one of the output plugins.
2650 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2651 * @return message_output message_output the requested class.
2653 function get_message_processor($type) {
2654 global $CFG;
2656 // Note, we cannot use the get_message_processors function here, becaues this
2657 // code is called during install after installing each messaging plugin, and
2658 // get_message_processors caches the list of installed plugins.
2660 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2661 if (!is_readable($processorfile)) {
2662 throw new coding_exception('Unknown message processor type ' . $type);
2665 include_once($processorfile);
2667 $processclass = 'message_output_' . $type;
2668 if (!class_exists($processclass)) {
2669 throw new coding_exception('Message processor ' . $type .
2670 ' does not define the right class');
2673 return new $processclass();
2677 * Get messaging outputs default (site) preferences
2679 * @return object $processors object containing information on message processors
2681 function get_message_output_default_preferences() {
2682 return get_config('message');
2686 * Translate message default settings from binary value to the array of string
2687 * representing the settings to be stored. Also validate the provided value and
2688 * use default if it is malformed.
2690 * @param int $plugindefault Default setting suggested by plugin
2691 * @param string $processorname The name of processor
2692 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2694 function translate_message_default_setting($plugindefault, $processorname) {
2695 // Preset translation arrays
2696 $permittedvalues = array(
2697 0x04 => 'disallowed',
2698 0x08 => 'permitted',
2699 0x0c => 'forced',
2702 $loggedinstatusvalues = array(
2703 0x00 => null, // use null if loggedin/loggedoff is not defined
2704 0x01 => 'loggedin',
2705 0x02 => 'loggedoff',
2708 // define the default setting
2709 $processor = get_message_processor($processorname);
2710 $default = $processor->get_default_messaging_settings();
2712 // Validate the value. It should not exceed the maximum size
2713 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
2714 debugging(get_string('errortranslatingdefault', 'message'));
2715 $plugindefault = $default;
2717 // Use plugin default setting of 'permitted' is 0
2718 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2719 $plugindefault = $default;
2722 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
2723 $loggedin = $loggedoff = null;
2725 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
2726 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2727 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
2730 return array($permitted, $loggedin, $loggedoff);
2734 * Return a list of page types
2735 * @param string $pagetype current page type
2736 * @param stdClass $parentcontext Block's parent context
2737 * @param stdClass $currentcontext Current context of block
2739 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
2740 return array('messages-*'=>get_string('page-message-x', 'message'));
2744 * Get messages sent or/and received by the specified users.
2746 * @param int $useridto the user id who received the message
2747 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
2748 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
2749 * @param bool $read true for retrieving read messages, false for unread
2750 * @param string $sort the column name to order by including optionally direction
2751 * @param int $limitfrom limit from
2752 * @param int $limitnum limit num
2753 * @return external_description
2754 * @since 2.8
2756 function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
2757 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
2758 global $DB;
2760 $messagetable = $read ? '{message_read}' : '{message}';
2761 $params = array('deleted' => 0);
2763 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
2764 if (empty($useridto)) {
2765 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
2766 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
2767 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
2768 $params['useridfrom'] = $useridfrom;
2769 } else {
2770 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
2771 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
2772 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
2773 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
2774 $params['useridto'] = $useridto;
2775 if (!empty($useridfrom)) {
2776 $usersql .= " AND mr.useridfrom = :useridfrom";
2777 $params['useridfrom'] = $useridfrom;
2781 // Now, if retrieve notifications, conversations or both.
2782 $typesql = "";
2783 if ($notifications !== -1) {
2784 $typesql = "AND mr.notification = :notification";
2785 $params['notification'] = ($notifications) ? 1 : 0;
2788 $sql = "SELECT mr.*, $userfields
2789 FROM $messagetable mr
2790 $joinsql
2791 WHERE $usersql
2792 $typesql
2793 ORDER BY $sort";
2795 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2796 return $messages;
2800 * Requires the JS libraries to send a message using a dialog.
2802 * @return void
2804 function message_messenger_requirejs() {
2805 global $PAGE;
2807 static $done = false;
2808 if ($done) {
2809 return;
2812 $PAGE->requires->yui_module(
2813 array('moodle-core_message-messenger'),
2814 'Y.M.core_message.messenger.init',
2815 array(array())
2817 $PAGE->requires->strings_for_js(array(
2818 'errorwhilesendingmessage',
2819 'messagesent',
2820 'messagetosend',
2821 'sendingmessage',
2822 'sendmessage',
2823 'viewconversation',
2824 ), 'core_message');
2825 $PAGE->requires->string_for_js('error', 'core');
2827 $done = true;
2831 * Returns the attributes to place on a link to open the 'Send message' dialog.
2833 * @param object $user User object.
2834 * @return void
2836 function message_messenger_sendmessage_link_params($user) {
2837 return array(
2838 'data-trigger' => 'core_message-messenger::sendmessage',
2839 'data-fullname' => fullname($user),
2840 'data-userid' => $user->id,
2841 'role' => 'button'