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