Merge branch 'MDL-26607_search_error' of git://github.com/andyjdavis/moodle
[moodle.git] / message / lib.php
CommitLineData
eb5334ff 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library functions for messaging
20 *
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package message
24 */
172186b8 25
3b120e46 26require_once($CFG->libdir.'/eventslib.php');
27
e8e2d7f1 28define ('MESSAGE_SHORTLENGTH', 300);
d3875524 29
94363029
AD
30//$PAGE isnt set if we're being loaded by cron which doesnt display popups anyway
31if (isset($PAGE)) {
32 $PAGE->set_popup_notification_allowed(false); // We are in a message window (so don't pop up a new one)
33}
fd7006f6 34
c8621a02
AD
35define ('MESSAGE_DISCUSSION_WIDTH',600);
36define ('MESSAGE_DISCUSSION_HEIGHT',500);
37
38define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
39
c8621a02
AD
40define('MESSAGE_HISTORY_SHORT',0);
41define('MESSAGE_HISTORY_ALL',1);
42
25bd5c75 43define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
44define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
45define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
46define('MESSAGE_VIEW_CONTACTS','contacts');
47define('MESSAGE_VIEW_BLOCKED','blockedusers');
48define('MESSAGE_VIEW_COURSE','course_');
49define('MESSAGE_VIEW_SEARCH','search');
c8621a02 50
c3931654
AD
51define('MESSAGE_SEARCH_MAX_RESULTS', 200);
52
32ef43e1 53define('MESSAGE_CONTACTS_PER_PAGE',10);
b2bce32f 54define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
32ef43e1 55
05753d2b 56if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
2a38a6be 57 $CFG->message_contacts_refresh = 60;
fd7006f6 58}
5d6b319b 59if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
60 $CFG->message_chat_refresh = 5;
fd7006f6 61}
f520438c 62if (!isset($CFG->message_offline_time)) {
63 $CFG->message_offline_time = 300;
64}
172186b8 65
bcab42da 66/**
67* Print the selector that allows the user to view their contacts, course participants, their recent
68* conversations etc
69* @param int $countunreadtotal how many unread messages does the user have?
25bd5c75 70* @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
bcab42da 71* @param object $user1 the user whose messages are being viewed
72* @param object $user2 the user $user1 is talking to
73* @param array $blockedusers an array of users blocked by $user1
74* @param array $onlinecontacts an array of $user1's online contacts
75* @param array $offlinecontacts an array of $user1's offline contacts
76* @param array $strangers an array of users who have messaged $user1 who aren't contacts
77* @param bool $showcontactactionlinks show action links (add/remove contact etc) next to the users in the contact selector
78* @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
79* @return void
80*/
81function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
c8621a02 82 global $PAGE;
3a11c09f 83
bcab42da 84 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
c8621a02 85
bcab42da 86 //if 0 unread messages and they've requested unread messages then show contacts
25bd5c75 87 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
88 $viewing = MESSAGE_VIEW_CONTACTS;
bcab42da 89 }
65c7853e 90
bcab42da 91 //if they have no blocked users and they've requested blocked users switch them over to contacts
25bd5c75 92 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
93 $viewing = MESSAGE_VIEW_CONTACTS;
bcab42da 94 }
c8621a02 95
bcab42da 96 $onlyactivecourses = true;
97 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
98 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
43240ea1 99
bcab42da 100 $strunreadmessages = null;
101 if ($countunreadtotal>0) { //if there are unread messages
102 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
103 }
c8621a02 104
bcab42da 105 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
c8621a02 106
25bd5c75 107 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
bcab42da 108 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
25bd5c75 109 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
bcab42da 110 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
25bd5c75 111 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
bcab42da 112 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
25bd5c75 113 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
bcab42da 114 $courseidtoshow = intval(substr($viewing, 7));
c8621a02 115
bcab42da 116 if (!empty($courseidtoshow)
117 && array_key_exists($courseidtoshow, $coursecontexts)
118 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
c8621a02 119
bcab42da 120 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2);
121 } else {
122 //shouldn't get here. User trying to access a course they're not in perhaps.
123 add_to_log(SITEID, 'message', 'view', 'index.php', $viewing);
c8621a02 124 }
bcab42da 125 }
c8621a02 126
bcab42da 127 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
128 echo html_writer::start_tag('fieldset');
129 $managebuttonclass = 'visible';
25bd5c75 130 if ($viewing == MESSAGE_VIEW_SEARCH) {
bcab42da 131 $managebuttonclass = 'hiddenelement';
132 }
133 $strmanagecontacts = get_string('search','message');
25bd5c75 134 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
bcab42da 135 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
136 echo html_writer::end_tag('fieldset');
137 echo html_writer::end_tag('form');
08cd70cf 138
c8621a02
AD
139 echo html_writer::end_tag('div');
140}
141
bcab42da 142/**
143* Print course participants. Called by message_print_contact_selector()
144* @param object $context the course context
145* @param int $courseid the course ID
146* @param string $contactselecturl the url to send the user to when a contact's name is clicked
147* @param bool $showactionlinks show action links (add/remove contact etc) next to the users
148* @param string $titletodisplay Optionally specify a title to display above the participants
149* @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
150* @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
151* @return void
152*/
08cd70cf 153function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
32ef43e1 154 global $DB, $USER, $PAGE, $OUTPUT;
c8621a02 155
bcab42da 156 if (empty($titletodisplay)) {
157 $titletodisplay = get_string('participants');
158 }
159
32ef43e1
AD
160 $countparticipants = count_enrolled_users($context);
161 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
31da70cc 162
32ef43e1
AD
163 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
164 echo $OUTPUT->render($pagingbar);
3a11c09f 165
bcab42da 166 echo html_writer::start_tag('table', array('id' => 'message_participants', 'class' => 'boxaligncenter', 'cellspacing' => '2', 'cellpadding' => '0', 'border' => '0'));
c8621a02 167
bcab42da 168 echo html_writer::start_tag('tr');
169 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
170 echo html_writer::end_tag('tr');
c8621a02
AD
171
172 //todo these need to come from somewhere if the course participants list is to show users with unread messages
173 $iscontact = true;
174 $isblocked = false;
175 foreach ($participants as $participant) {
176 if ($participant->id != $USER->id) {
177 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
08cd70cf 178 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks, $user2);
c8621a02
AD
179 }
180 }
c8621a02 181
bcab42da 182 echo html_writer::end_tag('table');
c8621a02
AD
183}
184
bcab42da 185/**
186* Retrieve users blocked by $user1
187* @param object $user1 the user whose messages are being viewed
188* @param object $user2 the user $user1 is talking to. If they are being blocked
189* they will have a variable called 'isblocked' added to their user object
190* @return array the users blocked by $user1
191*/
192function message_get_blocked_users($user1=null, $user2=null) {
c8621a02
AD
193 global $DB, $USER;
194
195 if (empty($user1)) {
196 $user1 = $USER;
197 }
198
199 if (!empty($user2)) {
200 $user2->isblocked = false;
201 }
202
3a11c09f
PS
203 $userfields = user_picture::fields('u', array('lastaccess'));
204 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
205 FROM {message_contacts} mc
206 JOIN {user} u ON u.id = mc.contactid
207 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
208 WHERE mc.userid = :user1id2 AND mc.blocked = 1
209 GROUP BY $userfields
210 ORDER BY u.firstname ASC";
bcab42da 211 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
c8621a02
AD
212
213 $blockedusers = array();
214 if (!empty($rs)) {
215 foreach($rs as $rd) {
216 $blockedusers[] = $rd;
217
bcab42da 218 if (!empty($user2) && $user2->id == $rd->id) {
c8621a02
AD
219 $user2->isblocked = true;
220 }
221 }
222 unset($rd);
223 $rs->close();
224 }
225
226 return $blockedusers;
227}
228
bcab42da 229/**
230* Print users blocked by $user1. Called by message_print_contact_selector()
231* @param array $blockedusers the users blocked by $user1
232* @param string $contactselecturl the url to send the user to when a contact's name is clicked
233* @param bool $showactionlinks show action links (add/remove contact etc) next to the users
234* @param string $titletodisplay Optionally specify a title to display above the participants
235* @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
236* @return void
237*/
238function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
c8621a02
AD
239 global $DB, $USER;
240
241 $countblocked = count($blockedusers);
242
bcab42da 243 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
c8621a02
AD
244
245 if (!empty($titletodisplay)) {
bcab42da 246 echo html_writer::start_tag('tr');
247 echo html_writer::tag('td', $titletodisplay, array('colspan' => 3, 'class' => 'heading'));
248 echo html_writer::end_tag('tr');
c8621a02
AD
249 }
250
251 if ($countblocked) {
bcab42da 252 echo html_writer::start_tag('tr');
253 echo html_writer::tag('td', get_string('blockedusers', 'message', $countblocked), array('colspan' => 3, 'class' => 'heading'));
254 echo html_writer::end_tag('tr');
c8621a02 255
25bd5c75 256 $isuserblocked = true;
257 $isusercontact = false;
c8621a02 258 foreach ($blockedusers as $blockeduser) {
25bd5c75 259 message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
c8621a02
AD
260 }
261 }
262
bcab42da 263 echo html_writer::end_tag('table');
c8621a02
AD
264}
265
bcab42da 266/**
267* Retrieve $user1's contacts (online, offline and strangers)
268* @param object $user1 the user whose messages are being viewed
269* @param object $user2 the user $user1 is talking to. If they are a contact
270* they will have a variable called 'iscontact' added to their user object
271* @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
272*/
273function message_get_contacts($user1=null, $user2=null) {
c8621a02 274 global $DB, $CFG, $USER;
172186b8 275
c8621a02
AD
276 if (empty($user1)) {
277 $user1 = $USER;
278 }
279
280 if (!empty($user2)) {
281 $user2->iscontact = false;
282 }
e8e2d7f1 283
284 $timetoshowusers = 300; //Seconds default
285 if (isset($CFG->block_online_users_timetosee)) {
286 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
287 }
e8e2d7f1 288
f46b6587 289 // time which a user is counting as being active since
290 $timefrom = time()-$timetoshowusers;
531e58f1 291
f46b6587 292 // people in our contactlist who are online
293 $onlinecontacts = array();
294 // people in our contactlist who are offline
295 $offlinecontacts = array();
296 // people who are not in our contactlist but have sent us a message
627bb9ec
AD
297 $strangers = array();
298
3a11c09f 299 $userfields = user_picture::fields('u', array('lastaccess'));
f46b6587 300
1d422980 301 // get all in our contactlist who are not blocked in our contact list
f46b6587 302 // and count messages we have waiting from each of them
3a11c09f 303 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
fd1cb1e8 304 FROM {message_contacts} mc
305 JOIN {user} u ON u.id = mc.contactid
306 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
1d422980 307 WHERE mc.userid = ? AND mc.blocked = 0
3a11c09f 308 GROUP BY $userfields
bbe973da 309 ORDER BY u.firstname ASC";
fd1cb1e8 310
20222a3d
EL
311 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
312 foreach ($rs as $rd) {
313 if ($rd->lastaccess >= $timefrom) {
314 // they have been active recently, so are counted online
315 $onlinecontacts[] = $rd;
316
317 } else {
318 $offlinecontacts[] = $rd;
319 }
c8621a02 320
bcab42da 321 if (!empty($user2) && $user2->id == $rd->id) {
20222a3d 322 $user2->iscontact = true;
e8e2d7f1 323 }
f46b6587 324 }
20222a3d 325 $rs->close();
f46b6587 326
f46b6587 327 // get messages from anyone who isn't in our contact list and count the number
328 // of messages we have from each of them
3a11c09f 329 $strangersql = "SELECT $userfields, count(m.id) as messagecount
fd1cb1e8 330 FROM {message} m
331 JOIN {user} u ON u.id = m.useridfrom
332 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
1d422980 333 WHERE mc.id IS NULL AND m.useridto = ?
3a11c09f 334 GROUP BY $userfields
bbe973da 335 ORDER BY u.firstname ASC";
fd1cb1e8 336
20222a3d
EL
337 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
338 foreach ($rs as $rd) {
339 $strangers[] = $rd;
e8e2d7f1 340 }
20222a3d 341 $rs->close();
e8e2d7f1 342
c8621a02
AD
343 return array($onlinecontacts, $offlinecontacts, $strangers);
344}
345
bcab42da 346/**
347* Print $user1's contacts. Called by message_print_contact_selector()
348* @param array $onlinecontacts $user1's contacts which are online
349* @param array $offlinecontacts $user1's contacts which are offline
350* @param array $strangers users which are not contacts but who have messaged $user1
351* @param string $contactselecturl the url to send the user to when a contact's name is clicked
352* @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
353* Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
354* @param bool $showactionlinks show action links (add/remove contact etc) next to the users
355* @param string $titletodisplay Optionally specify a title to display above the participants
356* @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
357* @return void
358*/
359function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
c8621a02
AD
360 global $CFG, $PAGE, $OUTPUT;
361
f46b6587 362 $countonlinecontacts = count($onlinecontacts);
363 $countofflinecontacts = count($offlinecontacts);
364 $countstrangers = count($strangers);
25bd5c75 365 $isuserblocked = null;
f46b6587 366
a1157dda 367 if ($countonlinecontacts + $countofflinecontacts == 0) {
bcab42da 368 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
65ef518b 369 }
370
bcab42da 371 echo html_writer::start_tag('table', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
531e58f1 372
c8621a02 373 if (!empty($titletodisplay)) {
bcab42da 374 message_print_heading($titletodisplay);
c8621a02
AD
375 }
376
f46b6587 377 if($countonlinecontacts) {
378 /// print out list of online contacts
531e58f1 379
c8621a02 380 if (empty($titletodisplay)) {
bcab42da 381 message_print_heading(get_string('onlinecontacts', 'message', $countonlinecontacts));
c8621a02 382 }
531e58f1 383
25bd5c75 384 $isuserblocked = false;
385 $isusercontact = true;
f46b6587 386 foreach ($onlinecontacts as $contact) {
bcab42da 387 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
25bd5c75 388 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
c8621a02 389 }
65ef518b 390 }
f46b6587 391 }
531e58f1 392
f46b6587 393 if ($countofflinecontacts) {
394 /// print out list of offline contacts
531e58f1 395
c8621a02 396 if (empty($titletodisplay)) {
bcab42da 397 message_print_heading(get_string('offlinecontacts', 'message', $countofflinecontacts));
c8621a02 398 }
576ad290 399
25bd5c75 400 $isuserblocked = false;
401 $isusercontact = true;
f46b6587 402 foreach ($offlinecontacts as $contact) {
bcab42da 403 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
25bd5c75 404 message_print_contactlist_user($contact, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
c8621a02 405 }
65ef518b 406 }
bcab42da 407
f46b6587 408 }
65ef518b 409
f46b6587 410 /// print out list of incoming contacts
411 if ($countstrangers) {
bcab42da 412 message_print_heading(get_string('incomingcontacts', 'message', $countstrangers));
531e58f1 413
25bd5c75 414 $isuserblocked = false;
415 $isusercontact = false;
f46b6587 416 foreach ($strangers as $stranger) {
bcab42da 417 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
25bd5c75 418 message_print_contactlist_user($stranger, $isusercontact, $isuserblocked, $contactselecturl, $showactionlinks, $user2);
c8621a02 419 }
669be60c 420 }
f46b6587 421 }
531e58f1 422
bcab42da 423 echo html_writer::end_tag('table');
65ef518b 424
f46b6587 425 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
bcab42da 426 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
65ef518b 427 }
e8e2d7f1 428}
429
bcab42da 430/**
431* Print a select box allowing the user to choose to view new messages, course participants etc.
432* Called by message_print_contact_selector()
25bd5c75 433* @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
bcab42da 434* @param array $courses array of course objects. The courses the user is enrolled in.
435* @param array $coursecontexts array of course contexts. Keyed on course id.
436* @param int $countunreadtotal how many unread messages does the user have?
437* @param int $countblocked how many users has the current user blocked?
438* @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
439* @return void
440*/
441function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
65c7853e 442 $options = array();
a8ccca53 443 $textlib = textlib_get_instance(); // going to use textlib services
c8621a02
AD
444
445 if ($countunreadtotal>0) { //if there are unread messages
25bd5c75 446 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
c8621a02
AD
447 }
448
bcab42da 449 $str = get_string('mycontacts', 'message');
25bd5c75 450 $options[MESSAGE_VIEW_CONTACTS] = $str;
bcab42da 451
25bd5c75 452 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
453 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
c8621a02
AD
454
455 if (!empty($courses)) {
456 $courses_options = array();
457
458 foreach($courses as $course) {
459 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
b2bce32f 460 //Not using short_text() as we want the end of the course name. Not the beginning.
b2bce32f 461 if ($textlib->strlen($course->shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
25bd5c75 462 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.$textlib->substr($course->shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
b2bce32f 463 } else {
25bd5c75 464 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $course->shortname;
b2bce32f 465 }
c8621a02
AD
466 }
467 }
468
469 if (!empty($courses_options)) {
bcab42da 470 $options[] = array(get_string('courses') => $courses_options);
c8621a02
AD
471 }
472 }
473
31c532d0 474 if ($countblocked>0) {
bcab42da 475 $str = get_string('blockedusers','message', $countblocked);
25bd5c75 476 $options[MESSAGE_VIEW_BLOCKED] = $str;
31c532d0
AD
477 }
478
bcab42da 479 echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => ''));
229f4e92 480 echo html_writer::start_tag('fieldset');
25bd5c75 481 echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()'));
229f4e92 482 echo html_writer::end_tag('fieldset');
c8621a02
AD
483 echo html_writer::end_tag('form');
484}
485
bcab42da 486/**
487* Load the course contexts for all of the users courses
488* @param array $courses array of course objects. The courses the user is enrolled in.
489* @return array of course contexts
490*/
491function message_get_course_contexts($courses) {
c8621a02
AD
492 $coursecontexts = array();
493
494 foreach($courses as $course) {
495 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
496 }
497
498 return $coursecontexts;
499}
500
cee92282
AD
501/**
502 * strip off action parameters like 'removecontact'
bcab42da 503 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
504 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
cee92282 505 */
c8621a02 506function message_remove_url_params($moodleurl) {
c8621a02
AD
507 $newurl = new moodle_url($moodleurl);
508 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
509 return $newurl->out();
510}
511
bcab42da 512/**
513 * Count the number of messages with a field having a specified value.
514 * if $field is empty then return count of the whole array
515 * if $field is non-existent then return 0
516 * @param array $messagearray array of message objects
517 * @param string $field the field to inspect on the message objects
518 * @param string $value the value to test the field against
519 */
e8e2d7f1 520function message_count_messages($messagearray, $field='', $value='') {
521 if (!is_array($messagearray)) return 0;
522 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 523
e8e2d7f1 524 $count = 0;
525 foreach ($messagearray as $message) {
526 $count += ($message->$field == $value) ? 1 : 0;
527 }
528 return $count;
172186b8 529}
530
c8621a02
AD
531/**
532 * Returns the count of unread messages for user. Either from a specific user or from all users.
c8621a02
AD
533 * @param object $user1 the first user. Defaults to $USER
534 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
535 * @return int the count of $user1's unread messages
536 */
537function message_count_unread_messages($user1=null, $user2=null) {
538 global $USER, $DB;
e8e2d7f1 539
c8621a02
AD
540 if (empty($user1)) {
541 $user1 = $USER;
542 }
543
544 if (!empty($user2)) {
545 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
546 array($user1->id, $user2->id), "COUNT('id')");
547 } else {
548 return $DB->count_records_select('message', "useridto = ?",
549 array($user1->id), "COUNT('id')");
550 }
551}
552
bcab42da 553/**
554 * Count the number of users blocked by $user1
555 * @param $user1
556 */
c8621a02
AD
557function message_count_blocked_users($user1=null) {
558 global $USER, $DB;
559
560 if (empty($user1)) {
561 $user1 = $USER;
562 }
563
564 $sql = "SELECT count(mc.id)
565 FROM {message_contacts} mc
566 WHERE mc.userid = :userid AND mc.blocked = 1";
bcab42da 567 $params = array('userid' => $user1->id);
c8621a02
AD
568
569 return $DB->count_records_sql($sql, $params);
570}
571
572/**
bcab42da 573 * Print the search form and search results if a search has been performed
574 * @param boolean $advancedsearch show basic or advanced search form
575 * @param object $user1 the current user
576 * @return boolean true if a search was performed
c8621a02
AD
577 */
578function message_print_search($advancedsearch = false, $user1=null) {
c8621a02 579 $frm = data_submitted();
3a11c09f 580
c8621a02
AD
581 $doingsearch = false;
582 if ($frm) {
31da70cc
PS
583 if (confirm_sesskey()) {
584 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
585 } else {
586 $frm = false;
587 }
c8621a02 588 }
531e58f1 589
c8621a02
AD
590 if (!empty($frm->combinedsearch)) {
591 $combinedsearchstring = $frm->combinedsearch;
592 } else {
a813a748
AD
593 //$combinedsearchstring = get_string('searchcombined','message').'...';
594 $combinedsearchstring = '';
c8621a02 595 }
531e58f1 596
c8621a02
AD
597 if ($doingsearch) {
598 if ($advancedsearch) {
3a11c09f 599
c8621a02
AD
600 $messagesearch = '';
601 if (!empty($frm->keywords)) {
602 $messagesearch = $frm->keywords;
603 }
604 $personsearch = '';
605 if (!empty($frm->name)) {
606 $personsearch = $frm->name;
607 }
608 include('search_advanced.html');
609 } else {
610 include('search.html');
611 }
612
613 $showicontext = false;
614 message_print_search_results($frm, $showicontext, $user1);
615
616 return true;
172186b8 617 } else {
c8621a02
AD
618
619 if ($advancedsearch) {
620 $personsearch = $messagesearch = '';
621 include('search_advanced.html');
622 } else {
623 include('search.html');
624 }
625 return false;
172186b8 626 }
627}
628
bcab42da 629/**
630 * Get the users recent conversations meaning all the people they've recently
631 * sent or received a message from plus the most recent message sent to or received from each other user
632 * @param object $user the current user
633 * @param int $limitfrom can be used for paging
634 * @param int $limitto can be used for paging
635 * @return array
636 */
637function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
638 global $DB;
639
640 $userfields = user_picture::fields('u', array('lastaccess'));
641 //This query retrieves the last message received from and sent to each user
642 //It unions that data then, within that set, it finds the most recent message you've exchanged with each user over all
643 //It then joins with some other tables to get some additional data we need
644
645 //message ID is used instead of timecreated as it should sort the same and will be much faster
646
647 //There is a separate query for read and unread queries as they are stored in different tables
648 //They were originally retrieved in one query but it was so large that it was difficult to be confident in its correctness
649 $sql = "SELECT $userfields, mr.id as mid, mr.smallmessage, mr.fullmessage, mr.timecreated, mc.id as contactlistid, mc.blocked
650 FROM {message_read} mr
651 JOIN (
652 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
653 FROM (
654 SELECT mr1.useridto AS userid, MAX(mr1.id) AS mid
655 FROM {message_read} mr1
656 WHERE mr1.useridfrom = :userid1
657 AND mr1.notification = 0
658 GROUP BY mr1.useridto
659 UNION
660 SELECT mr2.useridfrom AS userid, MAX(mr2.id) AS mid
661 FROM {message_read} mr2
662 WHERE mr2.useridto = :userid2
663 AND mr2.notification = 0
664 GROUP BY mr2.useridfrom
665 ) messages
666 GROUP BY messages.userid
667 ) messages2 ON mr.id = messages2.mid AND (mr.useridto = messages2.userid OR mr.useridfrom = messages2.userid)
668 JOIN {user} u ON u.id = messages2.userid
669 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
670 WHERE u.deleted = '0'
671 ORDER BY mr.id DESC";
672 $params = array('userid1' => $user->id, 'userid2' => $user->id, 'userid3' => $user->id);
673 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
674
675 $sql = "SELECT $userfields, m.id as mid, m.smallmessage, m.fullmessage, m.timecreated, mc.id as contactlistid, mc.blocked
676 FROM {message} m
677 JOIN (
678 SELECT messages.userid AS userid, MAX(messages.mid) AS mid
679 FROM (
680 SELECT m1.useridto AS userid, MAX(m1.id) AS mid
681 FROM {message} m1
682 WHERE m1.useridfrom = :userid1
683 AND m1.notification = 0
684 GROUP BY m1.useridto
685 UNION
686 SELECT m2.useridfrom AS userid, MAX(m2.id) AS mid
687 FROM {message} m2
688 WHERE m2.useridto = :userid2
689 AND m2.notification = 0
690 GROUP BY m2.useridfrom
691 ) messages
692 GROUP BY messages.userid
693 ) messages2 ON m.id = messages2.mid AND (m.useridto = messages2.userid OR m.useridfrom = messages2.userid)
694 JOIN {user} u ON u.id = messages2.userid
695 LEFT JOIN {message_contacts} mc ON mc.userid = :userid3 AND mc.contactid = u.id
696 WHERE u.deleted = '0'
697 ORDER BY m.id DESC";
698 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
699
700 $conversations = array();
701
702 //Union the 2 result sets together looking for the message with the most recent timecreated for each other user
703 //$conversation->id (the array key) is the other user's ID
704 $conversation_arrays = array($unread, $read);
705 foreach ($conversation_arrays as $conversation_array) {
706 foreach ($conversation_array as $conversation) {
707 if (empty($conversations[$conversation->id]) || $conversations[$conversation->id]->timecreated < $conversation->timecreated ) {
708 $conversations[$conversation->id] = $conversation;
709 }
710 }
711 }
712
713 //Sort the conversations. This is a bit complicated as we need to sort by $conversation->timecreated
714 //and there may be multiple conversations with the same timecreated value.
715 //The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
716 usort($conversations, "conversationsort");
717
718 return $conversations;
719}
720
721/**
722 * Sort function used to order conversations
723 * @param object $a A conversation object
724 * @param object $b A conversation object
725 * @return integer
726 */
727function conversationsort($a, $b)
728{
729 if ($a->timecreated == $b->timecreated) {
730 return 0;
731 }
732 return ($a->timecreated > $b->timecreated) ? -1 : 1;
733}
734
735/**
736 * Get the users recent event notifications
737 * @param object $user the current user
738 * @param int $limitfrom can be used for paging
739 * @param int $limitto can be used for paging
740 * @return array
741 */
742function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
743 global $DB;
744
745 $userfields = user_picture::fields('u', array('lastaccess'));
746 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.smallmessage, mr.fullmessage, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
747 FROM {message_read} mr
748 JOIN {user} u ON u.id=mr.useridfrom
749 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
750 ORDER BY mr.id DESC";//ordering by id should give the same result as ordering by timecreated but will be faster
751 $params = array('userid1' => $user->id, 'notification' => 1);
752
753 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
754 return $notifications;
755}
756
757/**
758 * Print the user's recent conversations
759 * @param object $user1 the current user
760 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
761 */
762function message_print_recent_conversations($user=null, $showicontext=false) {
763 global $USER;
764
765 echo html_writer::start_tag('p', array('class' => 'heading'));
766 echo get_string('mostrecentconversations', 'message');
767 echo html_writer::end_tag('p');
768
769 if (empty($user)) {
770 $user = $USER;
771 }
772
773 $conversations = message_get_recent_conversations($user);
774
775 $showotheruser = true;
776 message_print_recent_messages_table($conversations, $user, $showotheruser, $showicontext);
777}
778
779/**
780 * Print the user's recent notifications
781 * @param object $user1 the current user
782 */
783function message_print_recent_notifications($user=null) {
784 global $USER;
785
786 echo html_writer::start_tag('p', array('class' => 'heading'));
787 echo get_string('mostrecentnotifications', 'message');
788 echo html_writer::end_tag('p');
789
790 if (empty($user)) {
791 $user = $USER;
792 }
793
794 $notifications = message_get_recent_notifications($user);
795
796 $showicontext = false;
797 $showotheruser = false;
798 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext);
e8e2d7f1 799}
800
bcab42da 801/**
802 * Print a list of recent messages
803 * @staticvar type $dateformat
804 * @param array $messages the messages to display
805 * @param object $user the current user
806 * @param bool $showotheruser display information on the other user?
807 * @param bool $showicontext show text next to the action icons?
808 */
809function message_print_recent_messages_table($messages, $user=null, $showotheruser=true, $showicontext=false) {
810 global $OUTPUT;
811 static $dateformat;
e8e2d7f1 812
bcab42da 813 if (empty($dateformat)) {
814 $dateformat = get_string('strftimedatetimeshort');
815 }
e8e2d7f1 816
bcab42da 817 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
818 foreach ($messages as $message) {
819 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
820
821 if ($showotheruser) {
822 if ( $message->contactlistid ) {
823 if ($message->blocked == 0) { /// not blocked
824 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
825 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
826 } else { // blocked
827 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
828 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
829 }
830 } else {
831 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
832 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
833 }
834
835 //should we show just the icon or icon and text?
836 $histicontext = 'icon';
837 if ($showicontext) {
838 $histicontext = 'both';
839 }
840 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
841
842 echo html_writer::start_tag('span', array('class' => 'otheruser'));
843
844 echo html_writer::start_tag('span', array('class' => 'pix'));
845 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
846 echo html_writer::end_tag('span');
847
848 echo html_writer::start_tag('span', array('class' => 'contact'));
849
850 $link = new moodle_url("/message/index.php?id=$message->id");
851 $action = null;
852 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
853
854 echo html_writer::end_tag('span');//end contact
855
856 echo $strcontact.$strblock.$strhistory;
857 echo html_writer::end_tag('span');//end otheruser
858 }
859 $messagetoprint = null;
860 if (!empty($message->smallmessage)) {
861 $messagetoprint = $message->smallmessage;
862 } else {
863 $messagetoprint = $message->fullmessage;
864 }
865
866 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
867 echo html_writer::tag('span', format_text($messagetoprint, FORMAT_HTML), array('class' => 'themessage'));
868 echo message_format_contexturl($message);
869 echo html_writer::end_tag('div');//end singlemessage
870 }
871 echo html_writer::end_tag('div');//end messagerecent
872}
873
874/**
875 * Add the selected user as a contact for the current user
876 * @param int $contactid the ID of the user to add as a contact
877 * @param int $blocked 1 if you wish to block the contact
878 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
879 * Otherwise returns the result of update_record() or insert_record()
880 */
e8e2d7f1 881function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 882 global $USER, $DB;
531e58f1 883
bcab42da 884 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
e8e2d7f1 885 return false;
886 }
531e58f1 887
bcab42da 888 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
e8e2d7f1 889 /// record already exists - we may be changing blocking status
531e58f1 890
e8e2d7f1 891 if ($contact->blocked !== $blocked) {
892 /// change to blocking status
893 $contact->blocked = $blocked;
fd1cb1e8 894 return $DB->update_record('message_contacts', $contact);
e8e2d7f1 895 } else {
896 /// no changes to blocking status
897 return true;
898 }
531e58f1 899
172186b8 900 } else {
e8e2d7f1 901 /// new contact record
902 unset($contact);
903 $contact->userid = $USER->id;
904 $contact->contactid = $contactid;
905 $contact->blocked = $blocked;
fd1cb1e8 906 return $DB->insert_record('message_contacts', $contact, false);
172186b8 907 }
908}
909
bcab42da 910/**
911 * remove a contact
912 * @param type $contactid the user ID of the contact to remove
913 * @return bool returns the result of delete_records()
914 */
e8e2d7f1 915function message_remove_contact($contactid) {
fd1cb1e8 916 global $USER, $DB;
bcab42da 917 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
e8e2d7f1 918}
919
bcab42da 920/**
921 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
922 * @param int $contactid the user ID of the contact to unblock
923 * @return bool returns the result of delete_records()
924 */
e8e2d7f1 925function message_unblock_contact($contactid) {
fd1cb1e8 926 global $USER, $DB;
bcab42da 927 return $DB->delete_records('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
e8e2d7f1 928}
929
bcab42da 930/**
931 * block a user
932 * @param int $contactid the user ID of the user to block
933 */
e8e2d7f1 934function message_block_contact($contactid) {
935 return message_add_contact($contactid, 1);
936}
937
bcab42da 938/**
939 * Load a user's contact record
940 * @param int $contactid the user ID of the user whose contact record you want
941 */
e8e2d7f1 942function message_get_contact($contactid) {
fd1cb1e8 943 global $USER, $DB;
bcab42da 944 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
e8e2d7f1 945}
531e58f1 946
bcab42da 947/**
948 * Print the results of a message search
949 * @param mixed $frm submitted form data
950 * @param bool $showicontext show text next to action icons?
951 * @param object $user1 the current user
952 */
c8621a02 953function message_print_search_results($frm, $showicontext=false, $user1=null) {
bcab42da 954 global $USER, $DB, $OUTPUT;
c8621a02
AD
955
956 if (empty($user1)) {
957 $user1 = $USER;
958 }
e8e2d7f1 959
bcab42da 960 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
e8e2d7f1 961
c8621a02
AD
962 $personsearch = false;
963 $personsearchstring = null;
e8e2d7f1 964 if (!empty($frm->personsubmit) and !empty($frm->name)) {
c8621a02
AD
965 $personsearch = true;
966 $personsearchstring = $frm->name;
967 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
968 $personsearch = true;
969 $personsearchstring = $frm->combinedsearch;
970 }
531e58f1 971
c8621a02
AD
972 /// search for person
973 if ($personsearch) {
b71d4dd2 974 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 975 $users = array();
df997f84 976 $mycourses = enrol_get_my_courses();
e8e2d7f1 977 foreach ($mycourses as $mycourse) {
c8621a02 978 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
e8e2d7f1 979 foreach ($susers as $suser) $users[$suser->id] = $suser;
980 }
981 }
982 } else {
c8621a02 983 $users = message_search_users(SITEID, $personsearchstring);
e8e2d7f1 984 }
985
986 if (!empty($users)) {
bcab42da 987 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c3931654
AD
988 echo get_string('userssearchresults', 'message', count($users));
989 echo html_writer::end_tag('p');
990
bcab42da 991 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
e8e2d7f1 992 foreach ($users as $user) {
531e58f1 993
7390832c 994 if ( $user->contactlistid ) {
995 if ($user->blocked == 0) { /// not blocked
c8621a02
AD
996 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
997 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
e8e2d7f1 998 } else { // blocked
c8621a02
AD
999 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1000 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
e8e2d7f1 1001 }
e8e2d7f1 1002 } else {
c8621a02
AD
1003 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1004 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1005 }
1006
1007 //should we show just the icon or icon and text?
1008 $histicontext = 'icon';
1009 if ($showicontext) {
1010 $histicontext = 'both';
e8e2d7f1 1011 }
c8621a02 1012 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
531e58f1 1013
bcab42da 1014 echo html_writer::start_tag('tr');
40a26286 1015
bcab42da 1016 echo html_writer::start_tag('td', array('class' => 'pix'));
1017 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1018 echo html_writer::end_tag('td');
1019
1020 echo html_writer::start_tag('td',array('class' => 'contact'));
c8621a02 1021 $action = null;
bcab42da 1022 $link = new moodle_url("/message/index.php?id=$user->id");
1023 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1024 echo html_writer::end_tag('td');
576ad290 1025
bcab42da 1026 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1027 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1028 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
531e58f1 1029
bcab42da 1030 echo html_writer::end_tag('tr');
e8e2d7f1 1031 }
bcab42da 1032 echo html_writer::end_tag('table');
531e58f1 1033
e8e2d7f1 1034 } else {
bcab42da 1035 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c8621a02 1036 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
c3931654 1037 echo html_writer::end_tag('p');
e8e2d7f1 1038 }
c8621a02 1039 }
531e58f1 1040
c8621a02
AD
1041 // search messages for keywords
1042 $messagesearch = false;
1043 $messagesearchstring = null;
1044 if (!empty($frm->keywords)) {
1045 $messagesearch = true;
1046 $messagesearchstring = clean_text(trim($frm->keywords));
1047 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1048 $messagesearch = true;
1049 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1050 }
531e58f1 1051
c8621a02
AD
1052 if ($messagesearch) {
1053 if ($messagesearchstring) {
1054 $keywords = explode(' ', $messagesearchstring);
ff49c389 1055 } else {
1056 $keywords = array();
1057 }
e8e2d7f1 1058 $tome = false;
1059 $fromme = false;
1060 $courseid = 'none';
1061
c8621a02
AD
1062 if (empty($frm->keywordsoption)) {
1063 $frm->keywordsoption = 'allmine';
1064 }
1065
e8e2d7f1 1066 switch ($frm->keywordsoption) {
1067 case 'tome':
1068 $tome = true;
1069 break;
1070 case 'fromme':
1071 $fromme = true;
1072 break;
1073 case 'allmine':
1074 $tome = true;
1075 $fromme = true;
1076 break;
1077 case 'allusers':
1078 $courseid = SITEID;
1079 break;
1080 case 'courseusers':
1081 $courseid = $frm->courseid;
1082 break;
1083 default:
1084 $tome = true;
1085 $fromme = true;
1086 }
1087
1088 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 1089
e8e2d7f1 1090 /// get a list of contacts
bcab42da 1091 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
082864f9 1092 $contacts = array();
1093 }
e8e2d7f1 1094
082864f9 1095 /// print heading with number of results
bcab42da 1096 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c3931654 1097 $countresults = count($messages);
bcab42da 1098 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
c3931654
AD
1099 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1100 } else {
a813a748 1101 echo get_string('keywordssearchresults', 'message', $countresults);
c3931654
AD
1102 }
1103 echo html_writer::end_tag('p');
082864f9 1104
1105 /// print table headings
bcab42da 1106 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
c3931654 1107
bcab42da 1108 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
c3931654 1109 $headertdend = html_writer::end_tag('td');
bcab42da 1110 echo html_writer::start_tag('tr');
c3931654
AD
1111 echo $headertdstart.get_string('from').$headertdend;
1112 echo $headertdstart.get_string('to').$headertdend;
1113 echo $headertdstart.get_string('message', 'message').$headertdend;
1114 echo $headertdstart.get_string('timesent', 'message').$headertdend;
bcab42da 1115 echo html_writer::end_tag('tr');
082864f9 1116
1117 $blockedcount = 0;
54d8f804 1118 $dateformat = get_string('strftimedatetimeshort');
38c6a928 1119 $strcontext = get_string('context', 'message');
e8e2d7f1 1120 foreach ($messages as $message) {
082864f9 1121
1122 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 1123 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 1124 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1125 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1126 )
1127 ) {
1128 $blockedcount ++;
e8e2d7f1 1129 continue;
1130 }
531e58f1 1131
082864f9 1132 /// load up user to record
1133 if ($message->useridto !== $USER->id) {
bcab42da 1134 $userto = $DB->get_record('user', array('id' => $message->useridto));
531e58f1 1135 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 1136 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 1137 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 1138 ($contacts[$message->useridto]->blocked == 1) );
1139 } else {
1140 $userto = false;
1141 $tocontact = false;
1142 $toblocked = false;
1143 }
531e58f1 1144
082864f9 1145 /// load up user from record
1146 if ($message->useridfrom !== $USER->id) {
bcab42da 1147 $userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
531e58f1 1148 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 1149 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 1150 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 1151 ($contacts[$message->useridfrom]->blocked == 1) );
1152 } else {
1153 $userfrom = false;
1154 $fromcontact = false;
1155 $fromblocked = false;
1156 }
1157
e520509a 1158 /// find date string for this message
1159 $date = usergetdate($message->timecreated);
1160 $datestring = $date['year'].$date['mon'].$date['mday'];
1161
082864f9 1162 /// print out message row
bcab42da 1163 echo html_writer::start_tag('tr', array('valign' => 'top'));
1164
1165 echo html_writer::start_tag('td', array('class' => 'contact'));
c8621a02 1166 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
bcab42da 1167 echo html_writer::end_tag('td');
1168
1169 echo html_writer::start_tag('td', array('class' => 'contact'));
c8621a02 1170 message_print_user($userto, $tocontact, $toblocked, $showicontext);
bcab42da 1171 echo html_writer::end_tag('td');
1172
1173 echo html_writer::start_tag('td', array('class' => 'summary'));
1174 echo message_get_fragment($message->fullmessage, $keywords);
1175 echo html_writer::start_tag('div', array('class' => 'link'));
c8621a02 1176
71666cf3 1177 //find the user involved that isn't the current user
c8621a02
AD
1178 $user2id = null;
1179 if ($user1->id == $message->useridto) {
1180 $user2id = $message->useridfrom;
1181 } else {
1182 $user2id = $message->useridto;
1183 }
1184 message_history_link($user1->id, $user2id, false,
1185 $messagesearchstring, 'm'.$message->id, $strcontext);
bcab42da 1186 echo html_writer::end_tag('div');
1187 echo html_writer::end_tag('td');
1188
1189 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1190
1191 echo html_writer::end_tag('tr');
082864f9 1192 }
531e58f1 1193
e8e2d7f1 1194
e520509a 1195 if ($blockedcount > 0) {
bcab42da 1196 echo html_writer::start_tag('tr');
1197 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1198 echo html_writer::end_tag('tr');
e520509a 1199 }
bcab42da 1200 echo html_writer::end_tag('table');
531e58f1 1201
e8e2d7f1 1202 } else {
bcab42da 1203 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
e8e2d7f1 1204 }
c8621a02 1205 }
e8e2d7f1 1206
c8621a02 1207 if (!$personsearch && !$messagesearch) {
71666cf3 1208 //they didn't enter any search terms
aa9a6867 1209 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 1210 }
1211
bcab42da 1212 echo html_writer::end_tag('div');
e8e2d7f1 1213}
1214
bcab42da 1215/**
1216 * Print information on a user. Used when printing search results.
1217 * @param object/bool $user the user to display or false if you just want $USER
1218 * @param bool $iscontact is the user being displayed a contact?
1219 * @param bool $isblocked is the user being displayed blocked?
1220 * @param bool $includeicontext include text next to the action icons?
1221 */
c8621a02 1222function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
7cb1a1ad 1223 global $USER, $OUTPUT;
1d422980 1224
082864f9 1225 if ($user === false) {
bcab42da 1226 echo $OUTPUT->user_picture($USER, array('size' => 20, 'courseid' => SITEID));
082864f9 1227 } else {
bcab42da 1228 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
e520509a 1229 echo '&nbsp;';
c8621a02
AD
1230
1231 $return = false;
1232 $script = null;
082864f9 1233 if ($iscontact) {
c8621a02 1234 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
082864f9 1235 } else {
c8621a02 1236 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
082864f9 1237 }
1238 echo '&nbsp;';
1239 if ($isblocked) {
c8621a02 1240 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
082864f9 1241 } else {
c8621a02 1242 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
082864f9 1243 }
576ad290 1244
40a26286 1245 $popupoptions = array(
c8621a02
AD
1246 'height' => MESSAGE_DISCUSSION_HEIGHT,
1247 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 1248 'menubar' => false,
1249 'location' => false,
1250 'status' => true,
1251 'scrollbars' => true,
1252 'resizable' => true);
1253
02f2c7bd 1254 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
1255 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
1256 $action = null;
bcab42da 1257 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
40a26286 1258
082864f9 1259 }
1260}
1261
bcab42da 1262/**
1263 * Print a message contact link
1264 * @staticvar type $str
1265 * @param int $userid the ID of the user to apply to action to
1266 * @param string $linktype can be add, remove, block or unblock
1267 * @param bool $return if true return the link as a string. If false echo the link.
1268 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1269 * @param bool $text include text next to the icons?
1270 * @param bool $icon include a graphical icon?
1271 * @return string if $return is true otherwise bool
1272 */
c8621a02 1273function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
bcab42da 1274 global $OUTPUT, $PAGE;
e520509a 1275
6898e848 1276 //hold onto the strings as we're probably creating a bunch of links
e520509a 1277 static $str;
1278
c8621a02 1279 if (empty($script)) {
cee92282 1280 //strip off previous action params like 'removecontact'
4090a30f 1281 $script = message_remove_url_params($PAGE->url);
c8621a02
AD
1282 }
1283
e520509a 1284 if (empty($str->blockcontact)) {
1285 $str->blockcontact = get_string('blockcontact', 'message');
1286 $str->unblockcontact = get_string('unblockcontact', 'message');
1287 $str->removecontact = get_string('removecontact', 'message');
1288 $str->addcontact = get_string('addcontact', 'message');
1289 }
1290
5d6b319b 1291 $command = $linktype.'contact';
1292 $string = $str->{$command};
6898e848
AD
1293
1294 $safealttext = s($string);
1295
1296 $safestring = '';
3a11c09f 1297 if (!empty($text)) {
6898e848 1298 $safestring = $safealttext;
c8621a02
AD
1299 }
1300
1301 $img = '';
1302 if ($icon) {
6898e848
AD
1303 $iconpath = null;
1304 switch ($linktype) {
1305 case 'block':
1306 $iconpath = 't/block';
1307 break;
1308 case 'unblock':
1309 $iconpath = 't/userblue';
1310 break;
1311 case 'remove':
1312 $iconpath = 'i/cross_red_big';
1313 break;
1314 case 'add':
1315 default:
1316 $iconpath = 't/addgreen';
1317 }
1318
1319 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
082864f9 1320 }
5d6b319b 1321
c8621a02 1322 $output = '<span class="'.$linktype.'contact">'.
5d6b319b 1323 '<a href="'.$script.'&amp;'.$command.'='.$userid.
01e85326 1324 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
c8621a02 1325 $img.
6898e848 1326 $safestring.'</a></span>';
5d6b319b 1327
e520509a 1328 if ($return) {
1329 return $output;
082864f9 1330 } else {
e520509a 1331 echo $output;
082864f9 1332 return true;
1333 }
1334}
1335
bcab42da 1336/**
1337 * echo or return a link to take the user to the full message history between themselves and another user
1338 * @staticvar type $strmessagehistory
1339 * @param int $userid1 the ID of the current user
1340 * @param int $userid2 the ID of the other user
1341 * @param bool $return true to return the link as a string. False to echo the link.
1342 * @param string $keywords any keywords to highlight in the message history
1343 * @param string $position anchor name to jump to within the message history
1344 * @param string $linktext optionally specify the link text
1345 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1346 */
1347function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
1348 global $OUTPUT;
62119d65 1349
830d0af6 1350 static $strmessagehistory;
1351
1352 if (empty($strmessagehistory)) {
1353 $strmessagehistory = get_string('messagehistory', 'message');
1354 }
2514081c 1355
e520509a 1356 if ($position) {
1357 $position = "#$position";
1358 }
38c6a928 1359 if ($keywords) {
1360 $keywords = "&search=".urlencode($keywords);
1361 }
62119d65 1362
830d0af6 1363 if ($linktext == 'icon') { // Icon only
b5d0cafc 1364 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 1365 } else if ($linktext == 'both') { // Icon and standard name
b5d0cafc 1366 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
830d0af6 1367 $fulllink .= '&nbsp;'.$strmessagehistory;
1368 } else if ($linktext) { // Custom name
1369 $fulllink = $linktext;
1370 } else { // Standard name only
1371 $fulllink = $strmessagehistory;
fd7006f6 1372 }
1373
40a26286 1374 $popupoptions = array(
1375 'height' => 500,
1376 'width' => 500,
1377 'menubar' => false,
1378 'location' => false,
1379 'status' => true,
1380 'scrollbars' => true,
1381 'resizable' => true);
1382
02f2c7bd 1383 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
c8621a02 1384 $action = null;
bcab42da 1385 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
62119d65 1386
5d6b319b 1387 $str = '<span class="history">'.$str.'</span>';
1388
bcab42da 1389 if ($return) {
62119d65 1390 return $str;
1391 } else {
1392 echo $str;
1393 return true;
1394 }
1395}
e8e2d7f1 1396
1397
1398/**
1399 * Search through course users
1400 *
531e58f1 1401 * If $coursid specifies the site course then this function searches
e8e2d7f1 1402 * through all undeleted and confirmed users
e8e2d7f1 1403 * @param int $courseid The course in question.
bcab42da 1404 * @param string $searchtext the text to search for
1405 * @param string $sort the column name to order by
1406 * @param string $exceptions comma separated list of user IDs to exclude
e8e2d7f1 1407 * @return array An array of {@link $USER} records.
e8e2d7f1 1408 */
1409function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 1410 global $CFG, $USER, $DB;
e8e2d7f1 1411
245ac557 1412 $fullname = $DB->sql_fullname();
e8e2d7f1 1413
1414 if (!empty($exceptions)) {
1415 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1416 } else {
1417 $except = '';
1418 }
1419
1420 if (!empty($sort)) {
1421 $order = ' ORDER BY '. $sort;
1422 } else {
1423 $order = '';
1424 }
1425
3a11c09f 1426 $ufields = user_picture::fields('u');
e8e2d7f1 1427 if (!$courseid or $courseid == SITEID) {
fd1cb1e8 1428 $params = array($USER->id, "%$searchtext%");
3a11c09f 1429 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
d9eef08a 1430 FROM {user} u
fd1cb1e8 1431 LEFT JOIN {message_contacts} mc
1d422980 1432 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1433 WHERE u.deleted = '0' AND u.confirmed = '1'
dd54dc31 1434 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1435 $except
1436 $order", $params);
e8e2d7f1 1437 } else {
3a11c09f 1438//TODO: add enabled enrolment join here (skodak)
d76a5a7f 1439 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1440 $contextlists = get_related_contexts_string($context);
531e58f1 1441
91421f3e 1442 // everyone who has a role assignment in this course or higher
fd1cb1e8 1443 $params = array($USER->id, "%$searchtext%");
b6e52658
AD
1444 $users = $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
1445 FROM {user} u
fd1cb1e8 1446 JOIN {role_assignments} ra ON ra.userid = u.id
1447 LEFT JOIN {message_contacts} mc
1d422980 1448 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1449 WHERE u.deleted = '0' AND u.confirmed = '1'
fd1cb1e8 1450 AND ra.contextid $contextlists
dd54dc31 1451 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1452 $except
1453 $order", $params);
d76a5a7f 1454
1455 return $users;
e8e2d7f1 1456 }
1457}
1458
bcab42da 1459/**
1460 * search a user's messages
1461 * @param array $searchterms an array of search terms (strings)
1462 * @param bool $fromme include messages from the user?
1463 * @param bool $tome include messages to the user?
1464 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1465 * @param int $userid the user ID of the current user
1466 * @return mixed An array of messages or false if no matching messages were found
1467 */
082864f9 1468function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 1469/// Returns a list of posts found using an array of search terms
1470/// eg word +word -word
1471///
fd1cb1e8 1472 global $CFG, $USER, $DB;
e8e2d7f1 1473
082864f9 1474 /// If no userid sent then assume current user
531e58f1 1475 if ($userid == 0) $userid = $USER->id;
082864f9 1476
6eb7722f 1477 /// Some differences in SQL syntax
d9eef08a 1478 if ($DB->sql_regex_supported()) {
1479 $REGEXP = $DB->sql_regex(true);
1480 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 1481 }
1482
d9eef08a 1483 $searchcond = array();
1484 $params = array();
1485 $i = 0;
e8e2d7f1 1486
c3931654
AD
1487 //preprocess search terms to check whether we have at least 1 eligible search term
1488 //if we do we can drop words around it like 'a'
1489 $dropshortwords = false;
1490 foreach ($searchterms as $searchterm) {
1491 if (strlen($searchterm) >= 2) {
1492 $dropshortwords = true;
1493 }
1494 }
1495
e8e2d7f1 1496 foreach ($searchterms as $searchterm) {
d9eef08a 1497 $i++;
1498
47586394 1499 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
d9eef08a 1500
c3931654 1501 if ($dropshortwords && strlen($searchterm) < 2) {
e8e2d7f1 1502 continue;
1503 }
6bb4875f 1504 /// Under Oracle and MSSQL, trim the + and - operators and perform
1505 /// simpler LIKE search
d9eef08a 1506 if (!$DB->sql_regex_supported()) {
1507 if (substr($searchterm, 0, 1) == '-') {
47586394 1508 $NOT = true;
d9eef08a 1509 }
6bb4875f 1510 $searchterm = trim($searchterm, '+-');
1511 }
1512
e8e2d7f1 1513 if (substr($searchterm,0,1) == "+") {
1514 $searchterm = substr($searchterm,1);
d9eef08a 1515 $searchterm = preg_quote($searchterm, '|');
3d143595 1516 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
d9eef08a 1517 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1518
e8e2d7f1 1519 } else if (substr($searchterm,0,1) == "-") {
1520 $searchterm = substr($searchterm,1);
d9eef08a 1521 $searchterm = preg_quote($searchterm, '|');
3d143595 1522 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
d9eef08a 1523 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1524
e8e2d7f1 1525 } else {
47586394 1526 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
d9eef08a 1527 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 1528 }
172186b8 1529 }
1530
d9eef08a 1531 if (empty($searchcond)) {
dd54dc31 1532 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
ff49c389 1533 $params['ss1'] = "%";
1534 } else {
1535 $searchcond = implode(" AND ", $searchcond);
8a51efe9 1536 }
e8e2d7f1 1537
082864f9 1538 /// There are several possibilities
1539 /// 1. courseid = SITEID : The admin is searching messages by all users
1540 /// 2. courseid = ?? : A teacher is searching messages by users in
1541 /// one of their courses - currently disabled
1542 /// 3. courseid = none : User is searching their own messages;
1543 /// a. Messages from user
1544 /// b. Messages to user
1545 /// c. Messages to and from user
1546
1547 if ($courseid == SITEID) { /// admin is searching all messages
3d143595 1548 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1549 FROM {message_read} m
c3931654 1550 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1551 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1552 FROM {message} m
c3931654 1553 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
d9eef08a 1554
1555 } else if ($courseid !== 'none') {
082864f9 1556 /// This has not been implemented due to security concerns
d9eef08a 1557 $m_read = array();
1558 $m_unread = array();
e8e2d7f1 1559
082864f9 1560 } else {
531e58f1 1561
d9eef08a 1562 if ($fromme and $tome) {
1563 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1564 $params['userid1'] = $userid;
1565 $params['userid2'] = $userid;
1566
1567 } else if ($fromme) {
1568 $searchcond .= " AND m.useridfrom=:userid";
1569 $params['userid'] = $userid;
531e58f1 1570
d9eef08a 1571 } else if ($tome) {
1572 $searchcond .= " AND m.useridto=:userid";
1573 $params['userid'] = $userid;
1574 }
531e58f1 1575
3d143595 1576 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1577 FROM {message_read} m
c3931654 1578 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1579 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1580 FROM {message} m
c3931654 1581 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
531e58f1 1582
e8e2d7f1 1583 }
1584
082864f9 1585 /// The keys may be duplicated in $m_read and $m_unread so we can't
1586 /// do a simple concatenation
1587 $message = array();
d9eef08a 1588 foreach ($m_read as $m) {
1589 $messages[] = $m;
1590 }
1591 foreach ($m_unread as $m) {
1592 $messages[] = $m;
1593 }
e8e2d7f1 1594
1595 return (empty($messages)) ? false : $messages;
172186b8 1596}
1597
bcab42da 1598/**
1599 * Given a message object that we already know has a long message
1600 * this function truncates the message nicely to the first
1601 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1602 * @param string $message the message
1603 * @param int $minlength the minimum length to trim the message to
1604 * @return string the shortened message
1605 */
1606function message_shorten_message($message, $minlength = 0) {
e8e2d7f1 1607 $i = 0;
1608 $tag = false;
1609 $length = strlen($message);
1610 $count = 0;
1611 $stopzone = false;
1612 $truncate = 0;
1613 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 1614
e8e2d7f1 1615
1616 for ($i=0; $i<$length; $i++) {
1617 $char = $message[$i];
1618
1619 switch ($char) {
1620 case "<":
1621 $tag = true;
1622 break;
1623 case ">":
1624 $tag = false;
1625 break;
1626 default:
1627 if (!$tag) {
1628 if ($stopzone) {
1629 if ($char == '.' or $char == ' ') {
1630 $truncate = $i+1;
1631 break 2;
1632 }
1633 }
1634 $count++;
1635 }
1636 break;
1637 }
1638 if (!$stopzone) {
1639 if ($count > $minlength) {
1640 $stopzone = true;
1641 }
1642 }
1643 }
1644
1645 if (!$truncate) {
1646 $truncate = $i;
1647 }
1648
1649 return substr($message, 0, $truncate);
1650}
1651
38c6a928 1652
d9eef08a 1653/**
38c6a928 1654 * Given a string and an array of keywords, this function looks
1655 * for the first keyword in the string, and then chops out a
1656 * small section from the text that shows that word in context.
bcab42da 1657 * @param string $message the text to search
1658 * @param array $keywords array of keywords to find
38c6a928 1659 */
1660function message_get_fragment($message, $keywords) {
1661
f3832596 1662 $fullsize = 160;
38c6a928 1663 $halfsize = (int)($fullsize/2);
1664
1665 $message = strip_tags($message);
1666
1667 foreach ($keywords as $keyword) { // Just get the first one
1668 if ($keyword !== '') {
1669 break;
1670 }
1671 }
1672 if (empty($keyword)) { // None found, so just return start of message
1673 return message_shorten_message($message, 30);
1674 }
1675
1676 $leadin = $leadout = '';
1677
1678/// Find the start of the fragment
1679 $start = 0;
1680 $length = strlen($message);
1681
1682 $pos = strpos($message, $keyword);
1683 if ($pos > $halfsize) {
1684 $start = $pos - $halfsize;
1685 $leadin = '...';
1686 }
1687/// Find the end of the fragment
1688 $end = $start + $fullsize;
1689 if ($end > $length) {
1690 $end = $length;
1691 } else {
1692 $leadout = '...';
1693 }
1694
1695/// Pull out the fragment and format it
1696
1697 $fragment = substr($message, $start, $end - $start);
1698 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1699 return $fragment;
1700}
1701
bcab42da 1702/**
1703 * Retrieve the messages between two users
1704 * @param object $user1 the current user
1705 * @param object $user2 the other user
1706 * @param int $limitnum the maximum number of messages to retrieve
1707 * @param bool $viewingnewmessages are we currently viewing new messages?
1708 */
a813a748
AD
1709function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1710 global $DB, $CFG;
fd1cb1e8 1711
c8621a02
AD
1712 $messages = array();
1713
1714 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1715 //desc to get the last $limitnum messages then flip the order in php
1716 $sort = 'asc';
1717 if ($limitnum>0) {
1718 $sort = 'desc';
1719 }
1720
a813a748
AD
1721 $notificationswhere = null;
1722 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1723 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1724 $notificationswhere = 'AND notification=0';
1725 }
1726
33bd52f3
AD
1727 //prevent notifications of your own actions appearing in your own message history
1728 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1729
a813a748 1730 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
33bd52f3
AD
1731 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1732 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02
AD
1733 "timecreated $sort", '*', 0, $limitnum)) {
1734 foreach ($messages_read as $message) {
1735 $messages[$message->timecreated] = $message;
1736 }
1737 }
33bd52f3
AD
1738 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1739 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1740 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02 1741 "timecreated $sort", '*', 0, $limitnum)) {
b9ee0638 1742 foreach ($messages_new as $message) {
c8621a02 1743 $messages[$message->timecreated] = $message;
b9ee0638 1744 }
1745 }
c8621a02
AD
1746
1747 //if we only want the last $limitnum messages
2846b9a6
AD
1748 ksort($messages);
1749 $messagecount = count($messages);
1750 if ($limitnum>0 && $messagecount>$limitnum) {
1751 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
c8621a02 1752 }
3a11c09f 1753
b9ee0638 1754 return $messages;
1755}
1756
bcab42da 1757/**
1758 * Print the message history between two users
1759 * @param object $user1 the current user
1760 * @param object $user2 the other user
1761 * @param string $search search terms to highlight
1762 * @param int $messagelimit maximum number of messages to return
1763 * @param string $messagehistorylink the html for the message history link or false
1764 * @param bool $viewingnewmessages are we currently viewing new messages?
1765 */
a813a748 1766function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
c8621a02
AD
1767 global $CFG, $OUTPUT;
1768
1769 echo $OUTPUT->box_start('center');
bcab42da 1770 echo html_writer::start_tag('table', array('cellpadding' => '10', 'class' => 'message_user_pictures'));
1771 echo html_writer::start_tag('tr');
1772
1773 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user1'));
1774 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
1775 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
1776 echo html_writer::end_tag('td');
1777
1778 echo html_writer::start_tag('td', array('align' => 'center'));
1779 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/left'), 'alt' => get_string('from')));
1780 echo html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/right'), 'alt' => get_string('to')));
1781 echo html_writer::end_tag('td');
1782
1783 echo html_writer::start_tag('td', array('align' => 'center', 'id' => 'user2'));
1784 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
1785 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
c8621a02
AD
1786
1787 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1788 $incontactlist = $user2->iscontact;
1789 $isblocked = $user2->isblocked;
1790
1791 $script = null;
1792 $text = true;
1793 $icon = false;
1794
1795 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1796 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
41117b3e
AD
1797 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1798
bcab42da 1799 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
c8621a02
AD
1800 }
1801
bcab42da 1802 echo html_writer::end_tag('td');
1803 echo html_writer::end_tag('tr');
1804 echo html_writer::end_tag('table');
c8621a02
AD
1805 echo $OUTPUT->box_end();
1806
1807 if (!empty($messagehistorylink)) {
1808 echo $messagehistorylink;
1809 }
1810
1811 /// Get all the messages and print them
a813a748 1812 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
c8621a02
AD
1813 $tablecontents = '';
1814
8e803c3f 1815 $current = new stdClass();
c8621a02
AD
1816 $current->mday = '';
1817 $current->month = '';
1818 $current->year = '';
1819 $messagedate = get_string('strftimetime');
1820 $blockdate = get_string('strftimedaydate');
1821 foreach ($messages as $message) {
a813a748
AD
1822 if ($message->notification) {
1823 $notificationclass = ' notification';
1824 } else {
1825 $notificationclass = null;
1826 }
c8621a02
AD
1827 $date = usergetdate($message->timecreated);
1828 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1829 $current->mday = $date['mday'];
1830 $current->month = $date['month'];
1831 $current->year = $date['year'];
1832
bcab42da 1833 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
1834 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
1835
1836 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
c8621a02 1837 }
bcab42da 1838
1839 $formatted_message = $side = null;
c8621a02 1840 if ($message->useridfrom == $user1->id) {
bcab42da 1841 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
1842 $side = 'left';
c8621a02 1843 } else {
bcab42da 1844 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
1845 $side = 'right';
c8621a02 1846 }
bcab42da 1847 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left $side $notificationclass"));
c8621a02
AD
1848 }
1849
bcab42da 1850 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
c8621a02 1851 } else {
bcab42da 1852 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
c8621a02
AD
1853 }
1854}
1855
bcab42da 1856/**
1857 * Format a message for display in the message history
1858 * @param object $message the message object
1859 * @param string $format optional date format
1860 * @param string $keywords keywords to highlight
1861 * @param string $class CSS class to apply to the div around the message
1862 * @return string the formatted message
1863 */
1864function message_format_message($message, $format='', $keywords='', $class='other') {
acd21a2d 1865
1866 static $dateformat;
1867
bcab42da 1868 //if we haven't previously set the date format or they've supplied a new one
1869 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
acd21a2d 1870 if ($format) {
1871 $dateformat = $format;
1872 } else {
bcab42da 1873 $dateformat = get_string('strftimedatetimeshort');
acd21a2d 1874 }
b9ee0638 1875 }
acd21a2d 1876 $time = userdate($message->timecreated, $dateformat);
8e803c3f 1877 $options = new stdClass();
ff6048dd 1878 $options->para = false;
6ee2611c
AD
1879
1880 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1881 if (!empty($message->smallmessage)) {
2846b9a6 1882 $messagetext = format_text($message->smallmessage, FORMAT_MOODLE, $options);
6ee2611c
AD
1883 } else {
1884 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1885 }
1886
bcab42da 1887 $messagetext .= message_format_contexturl($message);
1888
1889 if ($keywords) {
1890 $messagetext = highlight($keywords, $messagetext);
1891 }
1892
1893 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
1894}
1895
1896/**
1897 * Format a the context url and context url name of a message for display
1898 * @param object $message the message object
1899 * @return string the formatted string
1900 */
1901function message_format_contexturl($message) {
1902 $s = null;
1903
14a0e7dd
AD
1904 if (!empty($message->contexturl)) {
1905 $displaytext = null;
1906 if (!empty($message->contexturlname)) {
1907 $displaytext= $message->contexturlname;
1908 } else {
1909 $displaytext= $message->contexturl;
1910 }
bcab42da 1911 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
1912 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1913 $s .= html_writer::end_tag('div');
38c6a928 1914 }
14a0e7dd 1915
bcab42da 1916 return $s;
b9ee0638 1917}
e8e2d7f1 1918
fd1cb1e8 1919/**
bcab42da 1920 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
1921 * @param object $userfrom the message sender
1922 * @param object $userto the message recipient
1923 * @param string $message the message
1924 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
3a00a167 1925 * @return int|false the ID of the new message or false
405f01ee 1926 */
bcab42da 1927function message_post_message($userfrom, $userto, $message, $format) {
27a39763 1928 global $SITE, $CFG, $USER;
4ffa1463 1929
8e803c3f 1930 $eventdata = new stdClass();
1560760f 1931 $eventdata->component = 'moodle';
1c50df9f 1932 $eventdata->name = 'instantmessage';
3b120e46 1933 $eventdata->userfrom = $userfrom;
1934 $eventdata->userto = $userto;
4ffa1463
AD
1935
1936 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
1937 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
1938
bcab42da 1939 if ($format == FORMAT_HTML) {
156205fc
AD
1940 $eventdata->fullmessage = '';
1941 $eventdata->fullmessagehtml = $message;
1942 } else {
1943 $eventdata->fullmessage = $message;
1944 $eventdata->fullmessagehtml = '';
1945 }
31da70cc 1946
c8621a02 1947 $eventdata->fullmessageformat = $format;
156205fc 1948 $eventdata->smallmessage = strip_tags($message);//strip just in case there are is any html that would break the popup notification
27a39763
AD
1949
1950 $s = new stdClass();
1951 $s->sitename = $SITE->shortname;
536a56e7 1952 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
27a39763 1953
4ffa1463 1954 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
6ee2611c
AD
1955 if (!empty($eventdata->fullmessage)) {
1956 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1957 }
6ee2611c
AD
1958 if (!empty($eventdata->fullmessagehtml)) {
1959 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1960 }
31da70cc 1961
a1b53dcf 1962 $eventdata->timecreated = time();
7c7d3afa 1963 return message_send($eventdata);
405f01ee 1964}
e8e2d7f1 1965
c135a425 1966
fd1cb1e8 1967/**
c135a425 1968 * Returns a list of all user ids who have used messaging in the site
1969 * This was the simple way to code the SQL ... is it going to blow up
1970 * on large datasets?
1971 */
1972function message_get_participants() {
fd1cb1e8 1973 global $CFG, $DB;
1974
76b0191c 1975 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1976 UNION SELECT useridto as id,1 FROM {message}
1977 UNION SELECT useridfrom as id,1 FROM {message_read}
1978 UNION SELECT useridto as id,1 FROM {message_read}
1979 UNION SELECT userid as id,1 FROM {message_contacts}
1980 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1981}
1982
f46b6587 1983/**
1d422980 1984 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 1985 * block links etc
bcab42da 1986 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
1987 * @param bool $incontactlist is the user a contact of ours?
1988 * @param bool $isblocked is the user blocked?
1989 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
1990 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
1991 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
f46b6587 1992 */
a402c309 1993function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
c8621a02 1994 global $OUTPUT, $USER;
f46b6587 1995 $fullname = fullname($contact);
1996 $fullnamelink = $fullname;
1997
a402c309 1998 $linkclass = '';
bcab42da 1999 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
a402c309
AD
2000 $linkclass = 'messageselecteduser';
2001 }
2002
f46b6587 2003 /// are there any unread messages for this contact?
2004 if ($contact->messagecount > 0 ){
2005 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2006 }
2007
c8621a02 2008 $strcontact = $strblock = $strhistory = null;
f46b6587 2009
c8621a02
AD
2010 if ($showactionlinks) {
2011 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2012 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2013 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
f46b6587 2014 }
2015
bcab42da 2016 echo html_writer::start_tag('tr');
2017 echo html_writer::start_tag('td', array('class' => 'pix'));
2018 echo $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => SITEID));
2019 echo html_writer::end_tag('td');
2020
2021 echo html_writer::start_tag('td', array('class' => 'contact'));
1d422980 2022
40a26286 2023 $popupoptions = array(
c8621a02
AD
2024 'height' => MESSAGE_DISCUSSION_HEIGHT,
2025 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 2026 'menubar' => false,
2027 'location' => false,
2028 'status' => true,
2029 'scrollbars' => true,
2030 'resizable' => true);
2031
c8621a02
AD
2032 $link = $action = null;
2033 if (!empty($selectcontacturl)) {
25bd5c75 2034 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
c8621a02 2035 } else {
06d30c43
AD
2036 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2037 $link = new moodle_url("/message/index.php?id=$contact->id");
c8621a02
AD
2038 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2039 }
bcab42da 2040 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class' => $linkclass,'title' => get_string('sendmessageto', 'message', $fullname)));
2041
2042 echo html_writer::end_tag('td');
f46b6587 2043
bcab42da 2044 echo html_writer::tag('td', '&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory, array('class' => 'link'));
2045
2046 echo html_writer::end_tag('tr');
f46b6587 2047}
2048
bcab42da 2049/**
2050 * Constructs the add/remove contact link to display next to other users
2051 * @param bool $incontactlist is the user a contact
2052 * @param bool $isblocked is the user blocked
2053 * @param type $contact contact object
2054 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2055 * @param bool $text include text next to the icons?
2056 * @param bool $icon include a graphical icon?
2057 * @return string
2058 */
c8621a02
AD
2059function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2060 $strcontact = '';
2061
2062 if($incontactlist){
2063 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2064 } else if ($isblocked) {
2065 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2066 } else{
2067 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2068 }
2069
2070 return $strcontact;
2071}
2072
bcab42da 2073/**
2074 * Constructs the block contact link to display next to other users
2075 * @param bool $incontactlist is the user a contact
2076 * @param bool $isblocked is the user blocked
2077 * @param type $contact contact object
2078 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2079 * @param bool $text include text next to the icons?
2080 * @param bool $icon include a graphical icon?
2081 * @return string
2082 */
c8621a02
AD
2083function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2084 $strblock = '';
2085
2086 //commented out to allow the user to block a contact without having to remove them first
2087 /*if ($incontactlist) {
2088 //$strblock = '';
2089 } else*/
2090 if ($isblocked) {
2091 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
2092 } else{
2093 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
2094 }
2095
2096 return $strblock;
2097}
2098
6bdf4c99 2099 /**
bcab42da 2100 * Moves messages from a particular user from the message table (unread messages) to message_read
2101 * This is typically only used when a user is deleted
2102 * @param object $userid User id
6bdf4c99 2103 * @return boolean success
2104 */
2105function message_move_userfrom_unread2read($userid) {
6bdf4c99 2106 global $DB;
2107
71666cf3 2108 // move all unread messages from message table to message_read
6bdf4c99 2109 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2110 foreach ($messages as $message) {
ee7cd81a 2111 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
6bdf4c99 2112 }
2113 }
2114 return true;
2115}
2116
ee7cd81a
AD
2117/**
2118* marks ALL messages being sent from $fromuserid to $touserid as read
2119* @param int $touserid the id of the message recipient
2120* @param int $fromuserid the id of the message sender
2121* @return void
2122*/
1560760f 2123function message_mark_messages_read($touserid, $fromuserid){
c8621a02
AD
2124 global $DB;
2125
ee7cd81a 2126 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
bcab42da 2127 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
1560760f 2128
c8621a02 2129 foreach ($messages as $message) {
ee7cd81a
AD
2130 message_mark_message_read($message, time());
2131 }
2132}
2133
2134/**
2135* Mark a single message as read
2136* @param message an object with an object property ie $message->id which is an id in the message table
2137* @param int $timeread the timestamp for when the message should be marked read. Usually time().
2138* @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
3a00a167 2139* @return int the ID of the message in the message_read table
ee7cd81a
AD
2140*/
2141function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2142 global $DB;
31da70cc 2143
ee7cd81a 2144 $message->timeread = $timeread;
c8621a02 2145
ee7cd81a
AD
2146 $messageid = $message->id;
2147 unset($message->id);//unset because it will get a new id on insert into message_read
1560760f 2148
ee7cd81a
AD
2149 //If any processors have pending actions abort them
2150 if (!$messageworkingempty) {
2151 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
c8621a02 2152 }
3a00a167 2153 $messagereadid = $DB->insert_record('message_read', $message);
ee7cd81a 2154 $DB->delete_records('message', array('id' => $messageid));
3a00a167 2155 return $messagereadid;
65fbace7 2156}
bcab42da 2157
2158/**
2159 * A helper function that prints a formatted heading
2160 * @param string $title the heading to display
2161 * @param int $colspan
2162 */
2163function message_print_heading($title, $colspan=3) {
2164 echo html_writer::start_tag('tr');
2165 echo html_writer::tag('td', $title, array('colspan' => $colspan, 'class' => 'heading'));
2166 echo html_writer::end_tag('tr');
2167}