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