MDL-52060 phpunit: Improve get_message_processors reset
[moodle.git] / message / lib.php
CommitLineData
eb5334ff 1<?php
eb5334ff 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Library functions for messaging
19 *
6fbd60ef
AD
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
eb5334ff 23 */
172186b8 24
3b120e46 25require_once($CFG->libdir.'/eventslib.php');
26
e8e2d7f1 27define ('MESSAGE_SHORTLENGTH', 300);
d3875524 28
c8621a02
AD
29define ('MESSAGE_DISCUSSION_WIDTH',600);
30define ('MESSAGE_DISCUSSION_HEIGHT',500);
31
32define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
33
c8621a02
AD
34define('MESSAGE_HISTORY_SHORT',0);
35define('MESSAGE_HISTORY_ALL',1);
36
25bd5c75 37define('MESSAGE_VIEW_UNREAD_MESSAGES','unread');
38define('MESSAGE_VIEW_RECENT_CONVERSATIONS','recentconversations');
39define('MESSAGE_VIEW_RECENT_NOTIFICATIONS','recentnotifications');
40define('MESSAGE_VIEW_CONTACTS','contacts');
41define('MESSAGE_VIEW_BLOCKED','blockedusers');
42define('MESSAGE_VIEW_COURSE','course_');
43define('MESSAGE_VIEW_SEARCH','search');
c8621a02 44
c3931654
AD
45define('MESSAGE_SEARCH_MAX_RESULTS', 200);
46
32ef43e1 47define('MESSAGE_CONTACTS_PER_PAGE',10);
b2bce32f 48define('MESSAGE_MAX_COURSE_NAME_LENGTH', 30);
32ef43e1 49
7a04c476
RK
50/**
51 * Define contants for messaging default settings population. For unambiguity of
52 * plugin developer intentions we use 4-bit value (LSB numbering):
53 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
54 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
55 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
56 *
57 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
58 */
59
60define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
61define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010
62
63define('MESSAGE_DISALLOWED', 0x04); // 0100
64define('MESSAGE_PERMITTED', 0x08); // 1000
65define('MESSAGE_FORCED', 0x0c); // 1100
66
67define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100
68
1d72e9d4
RK
69/**
70 * Set default value for default outputs permitted setting
71 */
814e3735 72define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
1d72e9d4 73
bcab42da 74/**
ebe0c008
RK
75 * Print the selector that allows the user to view their contacts, course participants, their recent
76 * conversations etc
77 *
78 * @param int $countunreadtotal how many unread messages does the user have?
79 * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc
80 * @param object $user1 the user whose messages are being viewed
81 * @param object $user2 the user $user1 is talking to
82 * @param array $blockedusers an array of users blocked by $user1
83 * @param array $onlinecontacts an array of $user1's online contacts
84 * @param array $offlinecontacts an array of $user1's offline contacts
85 * @param array $strangers an array of users who have messaged $user1 who aren't contacts
447df209 86 * @param bool $showactionlinks show action links (add/remove contact etc)
ebe0c008
RK
87 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
88 * @return void
89 */
447df209 90function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) {
c8621a02 91 global $PAGE;
3a11c09f 92
bcab42da 93 echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align'));
c8621a02 94
bcab42da 95 //if 0 unread messages and they've requested unread messages then show contacts
25bd5c75 96 if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
97 $viewing = MESSAGE_VIEW_CONTACTS;
bcab42da 98 }
65c7853e 99
bcab42da 100 //if they have no blocked users and they've requested blocked users switch them over to contacts
25bd5c75 101 if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) {
102 $viewing = MESSAGE_VIEW_CONTACTS;
bcab42da 103 }
c8621a02 104
bcab42da 105 $onlyactivecourses = true;
106 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
107 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
43240ea1 108
bcab42da 109 $strunreadmessages = null;
110 if ($countunreadtotal>0) { //if there are unread messages
111 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
112 }
c8621a02 113
447df209 114 message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1);
c8621a02 115
25bd5c75 116 if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) {
447df209 117 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2);
25bd5c75 118 } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) {
447df209 119 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2);
25bd5c75 120 } else if ($viewing == MESSAGE_VIEW_BLOCKED) {
447df209 121 message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2);
25bd5c75 122 } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) {
bcab42da 123 $courseidtoshow = intval(substr($viewing, 7));
c8621a02 124
bcab42da 125 if (!empty($courseidtoshow)
126 && array_key_exists($courseidtoshow, $coursecontexts)
127 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
c8621a02 128
447df209 129 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2);
c8621a02 130 }
bcab42da 131 }
c8621a02 132
b34eb03b
DN
133 // Only show the search button if we're viewing our own contacts.
134 if ($viewing == MESSAGE_VIEW_CONTACTS && $user2 == null) {
447df209
AD
135 echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET'));
136 echo html_writer::start_tag('fieldset');
137 $managebuttonclass = 'visible';
447df209
AD
138 $strmanagecontacts = get_string('search','message');
139 echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH));
140 echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass));
141 echo html_writer::end_tag('fieldset');
142 echo html_writer::end_tag('form');
bcab42da 143 }
08cd70cf 144
c8621a02
AD
145 echo html_writer::end_tag('div');
146}
147
bcab42da 148/**
ebe0c008
RK
149 * Print course participants. Called by message_print_contact_selector()
150 *
151 * @param object $context the course context
152 * @param int $courseid the course ID
153 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
154 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
155 * @param string $titletodisplay Optionally specify a title to display above the participants
156 * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing
157 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of participants
158 * @return void
159 */
08cd70cf 160function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0, $user2=null) {
32ef43e1 161 global $DB, $USER, $PAGE, $OUTPUT;
c8621a02 162
bcab42da 163 if (empty($titletodisplay)) {
164 $titletodisplay = get_string('participants');
165 }
166
32ef43e1 167 $countparticipants = count_enrolled_users($context);
0a5b8e9e
AD
168
169 list($esql, $params) = get_enrolled_sql($context);
170 $params['mcuserid'] = $USER->id;
171 $ufields = user_picture::fields('u');
172
173 $sql = "SELECT $ufields, mc.id as contactlistid, mc.blocked
174 FROM {user} u
175 JOIN ($esql) je ON je.id = u.id
176 LEFT JOIN {message_contacts} mc ON mc.contactid = u.id AND mc.userid = :mcuserid
177 WHERE u.deleted = 0";
178
179 $participants = $DB->get_records_sql($sql, $params, $page * MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
31da70cc 180
32ef43e1 181 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
3d16b203 182 $pagingbar->maxdisplay = 4;
32ef43e1 183 echo $OUTPUT->render($pagingbar);
3a11c09f 184
35fe9b8a 185 echo html_writer::start_tag('div', array('id' => 'message_participants', 'class' => 'boxaligncenter'));
c8621a02 186
35fe9b8a 187 echo html_writer::tag('div' , $titletodisplay, array('class' => 'heading'));
c8621a02 188
35fe9b8a 189 $users = '';
c8621a02
AD
190 foreach ($participants as $participant) {
191 if ($participant->id != $USER->id) {
0a5b8e9e
AD
192
193 $iscontact = false;
194 $isblocked = false;
195 if ( $participant->contactlistid ) {
196 if ($participant->blocked == 0) {
197 // Is contact. Is not blocked.
198 $iscontact = true;
199 $isblocked = false;
200 } else {
201 // Is blocked.
202 $iscontact = false;
203 $isblocked = true;
204 }
205 }
206
c8621a02 207 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
35fe9b8a
BB
208 $content = message_print_contactlist_user($participant, $iscontact, $isblocked,
209 $contactselecturl, $showactionlinks, $user2);
210 $users .= html_writer::tag('li', $content);
c8621a02
AD
211 }
212 }
35fe9b8a
BB
213 if (strlen($users) > 0) {
214 echo html_writer::tag('ul', $users, array('id' => 'message-courseparticipants', 'class' => 'message-contacts'));
215 }
c8621a02 216
35fe9b8a 217 echo html_writer::end_tag('div');
c8621a02
AD
218}
219
bcab42da 220/**
ebe0c008
RK
221 * Retrieve users blocked by $user1
222 *
223 * @param object $user1 the user whose messages are being viewed
224 * @param object $user2 the user $user1 is talking to. If they are being blocked
225 * they will have a variable called 'isblocked' added to their user object
226 * @return array the users blocked by $user1
227 */
bcab42da 228function message_get_blocked_users($user1=null, $user2=null) {
c8621a02
AD
229 global $DB, $USER;
230
231 if (empty($user1)) {
232 $user1 = $USER;
233 }
234
235 if (!empty($user2)) {
236 $user2->isblocked = false;
237 }
238
19c5532b
AD
239 $blockedusers = array();
240
3a11c09f
PS
241 $userfields = user_picture::fields('u', array('lastaccess'));
242 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
243 FROM {message_contacts} mc
244 JOIN {user} u ON u.id = mc.contactid
245 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
01393790 246 WHERE u.deleted = 0 AND mc.userid = :user1id2 AND mc.blocked = 1
3a11c09f
PS
247 GROUP BY $userfields
248 ORDER BY u.firstname ASC";
bcab42da 249 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1' => $user1->id, 'user1id2' => $user1->id));
c8621a02 250
19c5532b
AD
251 foreach($rs as $rd) {
252 $blockedusers[] = $rd;
c8621a02 253
19c5532b
AD
254 if (!empty($user2) && $user2->id == $rd->id) {
255 $user2->isblocked = true;
c8621a02 256 }
c8621a02 257 }
19c5532b 258 $rs->close();
c8621a02
AD
259
260 return $blockedusers;
261}
262
bcab42da 263/**
ebe0c008
RK
264 * Print users blocked by $user1. Called by message_print_contact_selector()
265 *
266 * @param array $blockedusers the users blocked by $user1
267 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
268 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
269 * @param string $titletodisplay Optionally specify a title to display above the participants
270 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of blocked users
271 * @return void
272 */
bcab42da 273function message_print_blocked_users($blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $user2=null) {
35fe9b8a 274 global $OUTPUT;
c8621a02
AD
275
276 $countblocked = count($blockedusers);
277
35fe9b8a 278 echo html_writer::start_tag('div', array('id' => 'message_contacts', 'class' => 'boxaligncenter'));
c8621a02
AD
279
280 if (!empty($titletodisplay)) {
35fe9b8a 281 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
c8621a02
AD
282 }
283
284 if ($countblocked) {
35fe9b8a 285 echo html_writer::tag('div', get_string('blockedusers', 'message', $countblocked), array('class' => 'heading'));
c8621a02 286
25bd5c75 287 $isuserblocked = true;
288 $isusercontact = false;
35fe9b8a 289 $blockeduserslist = '';
c8621a02 290 foreach ($blockedusers as $blockeduser) {
35fe9b8a
BB
291 $content = message_print_contactlist_user($blockeduser, $isusercontact, $isuserblocked,
292 $contactselecturl, $showactionlinks, $user2);
293 $blockeduserslist .= html_writer::tag('li', $content);
c8621a02 294 }
35fe9b8a 295 echo html_writer::tag('ul', $blockeduserslist, array('id' => 'message-blockedusers', 'class' => 'message-contacts'));
c8621a02
AD
296 }
297
35fe9b8a 298 echo html_writer::end_tag('div');
c8621a02
AD
299}
300
bcab42da 301/**
ebe0c008
RK
302 * Retrieve $user1's contacts (online, offline and strangers)
303 *
304 * @param object $user1 the user whose messages are being viewed
305 * @param object $user2 the user $user1 is talking to. If they are a contact
306 * they will have a variable called 'iscontact' added to their user object
307 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
308 */
bcab42da 309function message_get_contacts($user1=null, $user2=null) {
c8621a02 310 global $DB, $CFG, $USER;
172186b8 311
c8621a02
AD
312 if (empty($user1)) {
313 $user1 = $USER;
314 }
315
316 if (!empty($user2)) {
317 $user2->iscontact = false;
318 }
e8e2d7f1 319
320 $timetoshowusers = 300; //Seconds default
321 if (isset($CFG->block_online_users_timetosee)) {
322 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
323 }
e8e2d7f1 324
f46b6587 325 // time which a user is counting as being active since
326 $timefrom = time()-$timetoshowusers;
531e58f1 327
f46b6587 328 // people in our contactlist who are online
329 $onlinecontacts = array();
330 // people in our contactlist who are offline
331 $offlinecontacts = array();
332 // people who are not in our contactlist but have sent us a message
627bb9ec
AD
333 $strangers = array();
334
3a11c09f 335 $userfields = user_picture::fields('u', array('lastaccess'));
f46b6587 336
1d422980 337 // get all in our contactlist who are not blocked in our contact list
f46b6587 338 // and count messages we have waiting from each of them
3a11c09f 339 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
fd1cb1e8 340 FROM {message_contacts} mc
341 JOIN {user} u ON u.id = mc.contactid
342 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
01393790 343 WHERE u.deleted = 0 AND mc.userid = ? AND mc.blocked = 0
3a11c09f 344 GROUP BY $userfields
bbe973da 345 ORDER BY u.firstname ASC";
fd1cb1e8 346
20222a3d
EL
347 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
348 foreach ($rs as $rd) {
349 if ($rd->lastaccess >= $timefrom) {
350 // they have been active recently, so are counted online
351 $onlinecontacts[] = $rd;
352
353 } else {
354 $offlinecontacts[] = $rd;
355 }
c8621a02 356
bcab42da 357 if (!empty($user2) && $user2->id == $rd->id) {
20222a3d 358 $user2->iscontact = true;
e8e2d7f1 359 }
f46b6587 360 }
20222a3d 361 $rs->close();
f46b6587 362
f46b6587 363 // get messages from anyone who isn't in our contact list and count the number
364 // of messages we have from each of them
3a11c09f 365 $strangersql = "SELECT $userfields, count(m.id) as messagecount
fd1cb1e8 366 FROM {message} m
367 JOIN {user} u ON u.id = m.useridfrom
368 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
01393790 369 WHERE u.deleted = 0 AND mc.id IS NULL AND m.useridto = ?
3a11c09f 370 GROUP BY $userfields
bbe973da 371 ORDER BY u.firstname ASC";
fd1cb1e8 372
20222a3d 373 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
25bd63b7 374 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
20222a3d 375 foreach ($rs as $rd) {
25bd63b7 376 $strangers[$rd->id] = $rd;
e8e2d7f1 377 }
20222a3d 378 $rs->close();
e8e2d7f1 379
25bd63b7 380 // Add noreply user and support user to the list, if they don't exist.
9a90e7c5 381 $supportuser = core_user::get_support_user();
25bd63b7
RT
382 if (!isset($strangers[$supportuser->id])) {
383 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
384 if ($supportuser->messagecount > 0) {
385 $strangers[$supportuser->id] = $supportuser;
386 }
9a90e7c5 387 }
25bd63b7 388
9a90e7c5 389 $noreplyuser = core_user::get_noreply_user();
25bd63b7
RT
390 if (!isset($strangers[$noreplyuser->id])) {
391 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
392 if ($noreplyuser->messagecount > 0) {
393 $strangers[$noreplyuser->id] = $noreplyuser;
394 }
9a90e7c5 395 }
c8621a02
AD
396 return array($onlinecontacts, $offlinecontacts, $strangers);
397}
398
bcab42da 399/**
ebe0c008
RK
400 * Print $user1's contacts. Called by message_print_contact_selector()
401 *
402 * @param array $onlinecontacts $user1's contacts which are online
403 * @param array $offlinecontacts $user1's contacts which are offline
404 * @param array $strangers users which are not contacts but who have messaged $user1
405 * @param string $contactselecturl the url to send the user to when a contact's name is clicked
406 * @param int $minmessages The minimum number of unread messages required from a user for them to be displayed
407 * Typically 0 (show all contacts) or 1 (only show contacts from whom we have a new message)
408 * @param bool $showactionlinks show action links (add/remove contact etc) next to the users
409 * @param string $titletodisplay Optionally specify a title to display above the participants
410 * @param object $user2 the user $user1 is talking to. They will be highlighted if they appear in the list of contacts
411 * @return void
412 */
bcab42da 413function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
c8621a02
AD
414 global $CFG, $PAGE, $OUTPUT;
415
f46b6587 416 $countonlinecontacts = count($onlinecontacts);
417 $countofflinecontacts = count($offlinecontacts);
418 $countstrangers = count($strangers);
25bd5c75 419 $isuserblocked = null;
f46b6587 420
a1157dda 421 if ($countonlinecontacts + $countofflinecontacts == 0) {
bcab42da 422 echo html_writer::tag('div', get_string('contactlistempty', 'message'), array('class' => 'heading'));
65ef518b 423 }
424
c8621a02 425 if (!empty($titletodisplay)) {
35fe9b8a 426 echo html_writer::tag('div', $titletodisplay, array('class' => 'heading'));
c8621a02
AD
427 }
428
f46b6587 429 if($countonlinecontacts) {
447df209 430 // Print out list of online contacts.
531e58f1 431
c8621a02 432 if (empty($titletodisplay)) {
35fe9b8a
BB
433 echo html_writer::tag('div',
434 get_string('onlinecontacts', 'message', $countonlinecontacts),
435 array('class' => 'heading'));
c8621a02 436 }
531e58f1 437
25bd5c75 438 $isuserblocked = false;
439 $isusercontact = true;
35fe9b8a 440 $contacts = '';
f46b6587 441 foreach ($onlinecontacts as $contact) {
bcab42da 442 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
35fe9b8a
BB
443 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
444 $contactselecturl, $showactionlinks, $user2);
445 $contacts .= html_writer::tag('li', $content);
c8621a02 446 }
65ef518b 447 }
35fe9b8a
BB
448 if (strlen($contacts) > 0) {
449 echo html_writer::tag('ul', $contacts, array('id' => 'message-onlinecontacts', 'class' => 'message-contacts'));
450 }
f46b6587 451 }
531e58f1 452
f46b6587 453 if ($countofflinecontacts) {
447df209 454 // Print out list of offline contacts.
531e58f1 455
c8621a02 456 if (empty($titletodisplay)) {
35fe9b8a
BB
457 echo html_writer::tag('div',
458 get_string('offlinecontacts', 'message', $countofflinecontacts),
459 array('class' => 'heading'));
c8621a02 460 }
576ad290 461
25bd5c75 462 $isuserblocked = false;
463 $isusercontact = true;
35fe9b8a 464 $contacts = '';
f46b6587 465 foreach ($offlinecontacts as $contact) {
bcab42da 466 if ($minmessages == 0 || $contact->messagecount >= $minmessages) {
35fe9b8a
BB
467 $content = message_print_contactlist_user($contact, $isusercontact, $isuserblocked,
468 $contactselecturl, $showactionlinks, $user2);
469 $contacts .= html_writer::tag('li', $content);
c8621a02 470 }
65ef518b 471 }
35fe9b8a
BB
472 if (strlen($contacts) > 0) {
473 echo html_writer::tag('ul', $contacts, array('id' => 'message-offlinecontacts', 'class' => 'message-contacts'));
474 }
bcab42da 475
f46b6587 476 }
65ef518b 477
447df209 478 // Print out list of incoming contacts.
f46b6587 479 if ($countstrangers) {
35fe9b8a 480 echo html_writer::tag('div', get_string('incomingcontacts', 'message', $countstrangers), array('class' => 'heading'));
531e58f1 481
25bd5c75 482 $isuserblocked = false;
483 $isusercontact = false;
35fe9b8a 484 $contacts = '';
f46b6587 485 foreach ($strangers as $stranger) {
bcab42da 486 if ($minmessages == 0 || $stranger->messagecount >= $minmessages) {
35fe9b8a
BB
487 $content = message_print_contactlist_user($stranger, $isusercontact, $isuserblocked,
488 $contactselecturl, $showactionlinks, $user2);
489 $contacts .= html_writer::tag('li', $content);
c8621a02 490 }
669be60c 491 }
35fe9b8a
BB
492 if (strlen($contacts) > 0) {
493 echo html_writer::tag('ul', $contacts, array('id' => 'message-incommingcontacts', 'class' => 'message-contacts'));
494 }
531e58f1 495
35fe9b8a 496 }
65ef518b 497
f46b6587 498 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
bcab42da 499 echo html_writer::tag('div','('.get_string('addsomecontactsincoming', 'message').')',array('class' => 'note'));
65ef518b 500 }
e8e2d7f1 501}
502
bcab42da 503/**
ebe0c008
RK
504 * Print a select box allowing the user to choose to view new messages, course participants etc.
505 *
506 * Called by message_print_contact_selector()
507 * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc
508 * @param array $courses array of course objects. The courses the user is enrolled in.
509 * @param array $coursecontexts array of course contexts. Keyed on course id.
510 * @param int $countunreadtotal how many unread messages does the user have?
511 * @param int $countblocked how many users has the current user blocked?
447df209 512 * @param stdClass $user1 The user whose messages we are viewing.
ebe0c008
RK
513 * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has
514 * @return void
515 */
447df209 516function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages, $user1 = null) {
18d0acf8 517 global $PAGE;
65c7853e 518 $options = array();
c8621a02
AD
519
520 if ($countunreadtotal>0) { //if there are unread messages
25bd5c75 521 $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages;
c8621a02
AD
522 }
523
d8ef2bc0 524 $str = get_string('contacts', 'message');
25bd5c75 525 $options[MESSAGE_VIEW_CONTACTS] = $str;
bcab42da 526
25bd5c75 527 $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message');
528 $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message');
c8621a02
AD
529
530 if (!empty($courses)) {
531 $courses_options = array();
532
533 foreach($courses as $course) {
534 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
b2bce32f 535 //Not using short_text() as we want the end of the course name. Not the beginning.
8ebbb06a 536 $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id]));
2f1e464a
PS
537 if (core_text::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) {
538 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.core_text::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH);
b2bce32f 539 } else {
8ebbb06a 540 $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname;
b2bce32f 541 }
c8621a02
AD
542 }
543 }
544
545 if (!empty($courses_options)) {
bcab42da 546 $options[] = array(get_string('courses') => $courses_options);
c8621a02
AD
547 }
548 }
549
31c532d0 550 if ($countblocked>0) {
bcab42da 551 $str = get_string('blockedusers','message', $countblocked);
25bd5c75 552 $options[MESSAGE_VIEW_BLOCKED] = $str;
31c532d0
AD
553 }
554
18d0acf8
BB
555 $select = new single_select($PAGE->url, 'viewing', $options, $viewing, false);
556 $select->set_label(get_string('messagenavigation', 'message'));
557
558 $renderer = $PAGE->get_renderer('core');
559 echo $renderer->render($select);
c8621a02
AD
560}
561
bcab42da 562/**
ebe0c008
RK
563 * Load the course contexts for all of the users courses
564 *
565 * @param array $courses array of course objects. The courses the user is enrolled in.
566 * @return array of course contexts
567 */
bcab42da 568function message_get_course_contexts($courses) {
c8621a02
AD
569 $coursecontexts = array();
570
571 foreach($courses as $course) {
bf0f06b1 572 $coursecontexts[$course->id] = context_course::instance($course->id);
c8621a02
AD
573 }
574
575 return $coursecontexts;
576}
577
cee92282
AD
578/**
579 * strip off action parameters like 'removecontact'
ebe0c008 580 *
bcab42da 581 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
582 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
cee92282 583 */
c8621a02 584function message_remove_url_params($moodleurl) {
c8621a02
AD
585 $newurl = new moodle_url($moodleurl);
586 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
587 return $newurl->out();
588}
589
bcab42da 590/**
591 * Count the number of messages with a field having a specified value.
592 * if $field is empty then return count of the whole array
593 * if $field is non-existent then return 0
ebe0c008 594 *
bcab42da 595 * @param array $messagearray array of message objects
596 * @param string $field the field to inspect on the message objects
597 * @param string $value the value to test the field against
598 */
e8e2d7f1 599function message_count_messages($messagearray, $field='', $value='') {
600 if (!is_array($messagearray)) return 0;
601 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 602
e8e2d7f1 603 $count = 0;
604 foreach ($messagearray as $message) {
605 $count += ($message->$field == $value) ? 1 : 0;
606 }
607 return $count;
172186b8 608}
609
c8621a02
AD
610/**
611 * Returns the count of unread messages for user. Either from a specific user or from all users.
ebe0c008 612 *
c8621a02
AD
613 * @param object $user1 the first user. Defaults to $USER
614 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
615 * @return int the count of $user1's unread messages
616 */
617function message_count_unread_messages($user1=null, $user2=null) {
618 global $USER, $DB;
e8e2d7f1 619
c8621a02
AD
620 if (empty($user1)) {
621 $user1 = $USER;
622 }
623
624 if (!empty($user2)) {
625 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
626 array($user1->id, $user2->id), "COUNT('id')");
627 } else {
628 return $DB->count_records_select('message', "useridto = ?",
629 array($user1->id), "COUNT('id')");
630 }
631}
632
bcab42da 633/**
634 * Count the number of users blocked by $user1
ebe0c008
RK
635 *
636 * @param object $user1 user object
637 * @return int the number of blocked users
bcab42da 638 */
c8621a02
AD
639function message_count_blocked_users($user1=null) {
640 global $USER, $DB;
641
642 if (empty($user1)) {
643 $user1 = $USER;
644 }
645
646 $sql = "SELECT count(mc.id)
647 FROM {message_contacts} mc
648 WHERE mc.userid = :userid AND mc.blocked = 1";
bcab42da 649 $params = array('userid' => $user1->id);
c8621a02
AD
650
651 return $DB->count_records_sql($sql, $params);
652}
653
654/**
bcab42da 655 * Print the search form and search results if a search has been performed
ebe0c008 656 *
bcab42da 657 * @param boolean $advancedsearch show basic or advanced search form
658 * @param object $user1 the current user
659 * @return boolean true if a search was performed
c8621a02
AD
660 */
661function message_print_search($advancedsearch = false, $user1=null) {
c8621a02 662 $frm = data_submitted();
3a11c09f 663
c8621a02
AD
664 $doingsearch = false;
665 if ($frm) {
31da70cc
PS
666 if (confirm_sesskey()) {
667 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
668 } else {
669 $frm = false;
670 }
c8621a02 671 }
531e58f1 672
c8621a02
AD
673 if (!empty($frm->combinedsearch)) {
674 $combinedsearchstring = $frm->combinedsearch;
675 } else {
a813a748
AD
676 //$combinedsearchstring = get_string('searchcombined','message').'...';
677 $combinedsearchstring = '';
c8621a02 678 }
531e58f1 679
c8621a02
AD
680 if ($doingsearch) {
681 if ($advancedsearch) {
3a11c09f 682
c8621a02
AD
683 $messagesearch = '';
684 if (!empty($frm->keywords)) {
685 $messagesearch = $frm->keywords;
686 }
687 $personsearch = '';
688 if (!empty($frm->name)) {
689 $personsearch = $frm->name;
690 }
691 include('search_advanced.html');
692 } else {
693 include('search.html');
694 }
695
696 $showicontext = false;
697 message_print_search_results($frm, $showicontext, $user1);
698
699 return true;
172186b8 700 } else {
c8621a02
AD
701
702 if ($advancedsearch) {
703 $personsearch = $messagesearch = '';
704 include('search_advanced.html');
705 } else {
706 include('search.html');
707 }
708 return false;
172186b8 709 }
710}
711
bcab42da 712/**
713 * Get the users recent conversations meaning all the people they've recently
714 * sent or received a message from plus the most recent message sent to or received from each other user
ebe0c008 715 *
bcab42da 716 * @param object $user the current user
717 * @param int $limitfrom can be used for paging
718 * @param int $limitto can be used for paging
719 * @return array
720 */
721function message_get_recent_conversations($user, $limitfrom=0, $limitto=100) {
722 global $DB;
723
f68b11f7
TH
724 $userfields = user_picture::fields('otheruser', array('lastaccess'));
725
726 // This query retrieves the most recent message received from or sent to
727 // seach other user.
728 //
729 // If two messages have the same timecreated, we take the one with the
730 // larger id.
731 //
732 // There is a separate query for read and unread messages as they are stored
733 // in different tables. They were originally retrieved in one query but it
734 // was so large that it was difficult to be confident in its correctness.
3d9c8578 735 $uniquefield = $DB->sql_concat('message.useridfrom', "'-'", 'message.useridto');
b5e9faa6 736 $sql = "SELECT $uniquefield, $userfields,
f68b11f7
TH
737 message.id as mid, message.notification, message.smallmessage, message.fullmessage,
738 message.fullmessagehtml, message.fullmessageformat, message.timecreated,
739 contact.id as contactlistid, contact.blocked
f68b11f7 740 FROM {message_read} message
b5e9faa6
AN
741 JOIN (
742 SELECT MAX(id) AS messageid,
743 matchedmessage.useridto,
744 matchedmessage.useridfrom
745 FROM {message_read} matchedmessage
746 INNER JOIN (
747 SELECT MAX(recentmessages.timecreated) timecreated,
748 recentmessages.useridfrom,
749 recentmessages.useridto
750 FROM {message_read} recentmessages
36d29c08
MN
751 WHERE (
752 (recentmessages.useridfrom = :userid1 AND recentmessages.timeuserfromdeleted = 0) OR
753 (recentmessages.useridto = :userid2 AND recentmessages.timeusertodeleted = 0)
754 )
b5e9faa6
AN
755 GROUP BY recentmessages.useridfrom, recentmessages.useridto
756 ) recent ON matchedmessage.useridto = recent.useridto
757 AND matchedmessage.useridfrom = recent.useridfrom
758 AND matchedmessage.timecreated = recent.timecreated
36d29c08
MN
759 WHERE (
760 (matchedmessage.useridfrom = :userid6 AND matchedmessage.timeuserfromdeleted = 0) OR
761 (matchedmessage.useridto = :userid7 AND matchedmessage.timeusertodeleted = 0)
762 )
b5e9faa6
AN
763 GROUP BY matchedmessage.useridto, matchedmessage.useridfrom
764 ) messagesubset ON messagesubset.messageid = message.id
765 JOIN {user} otheruser ON (message.useridfrom = :userid4 AND message.useridto = otheruser.id)
766 OR (message.useridto = :userid5 AND message.useridfrom = otheruser.id)
767 LEFT JOIN {message_contacts} contact ON contact.userid = :userid3 AND contact.userid = otheruser.id
768 WHERE otheruser.deleted = 0 AND message.notification = 0
f68b11f7 769 ORDER BY message.timecreated DESC";
b5e9faa6
AN
770 $params = array(
771 'userid1' => $user->id,
772 'userid2' => $user->id,
773 'userid3' => $user->id,
774 'userid4' => $user->id,
775 'userid5' => $user->id,
36d29c08
MN
776 'userid6' => $user->id,
777 'userid7' => $user->id
b5e9faa6 778 );
f68b11f7
TH
779 $read = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
780
781 // We want to get the messages that have not been read. These are stored in the 'message' table. It is the
782 // exact same query as the one above, except for the table we are querying. So, simply replace references to
783 // the 'message_read' table with the 'message' table.
784 $sql = str_replace('{message_read}', '{message}', $sql);
785 $unread = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
bcab42da 786
f68b11f7
TH
787 // Union the 2 result sets together looking for the message with the most
788 // recent timecreated for each other user.
789 // $conversation->id (the array key) is the other user's ID.
d9b5f9bb 790 $conversations = array();
bcab42da 791 $conversation_arrays = array($unread, $read);
792 foreach ($conversation_arrays as $conversation_array) {
793 foreach ($conversation_array as $conversation) {
b5e9faa6 794 if (!isset($conversations[$conversation->id])) {
bcab42da 795 $conversations[$conversation->id] = $conversation;
b5e9faa6
AN
796 } else {
797 $current = $conversations[$conversation->id];
798 if ($current->timecreated < $conversation->timecreated) {
799 $conversations[$conversation->id] = $conversation;
800 } else if ($current->timecreated == $conversation->timecreated) {
801 if ($current->mid < $conversation->mid) {
802 $conversations[$conversation->id] = $conversation;
803 }
804 }
bcab42da 805 }
806 }
807 }
808
6109f7af
AD
809 // Sort the conversations by $conversation->timecreated, newest to oldest
810 // There may be multiple conversations with the same timecreated
811 // The conversations array contains both read and unread messages (different tables) so sorting by ID won't work
2f1e464a 812 $result = core_collator::asort_objects_by_property($conversations, 'timecreated', core_collator::SORT_NUMERIC);
6109f7af 813 $conversations = array_reverse($conversations);
bcab42da 814
815 return $conversations;
816}
817
bcab42da 818/**
819 * Get the users recent event notifications
ebe0c008 820 *
bcab42da 821 * @param object $user the current user
822 * @param int $limitfrom can be used for paging
823 * @param int $limitto can be used for paging
824 * @return array
825 */
826function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
827 global $DB;
828
829 $userfields = user_picture::fields('u', array('lastaccess'));
4048f5b3 830 $sql = "SELECT mr.id AS message_read_id, $userfields, mr.notification, mr.smallmessage, mr.fullmessage, mr.fullmessagehtml, mr.fullmessageformat, mr.timecreated as timecreated, mr.contexturl, mr.contexturlname
bcab42da 831 FROM {message_read} mr
832 JOIN {user} u ON u.id=mr.useridfrom
833 WHERE mr.useridto = :userid1 AND u.deleted = '0' AND mr.notification = :notification
e6aae58d 834 ORDER BY mr.timecreated DESC";
bcab42da 835 $params = array('userid1' => $user->id, 'notification' => 1);
836
837 $notifications = $DB->get_records_sql($sql, $params, $limitfrom, $limitto);
838 return $notifications;
839}
840
841/**
842 * Print the user's recent conversations
ebe0c008 843 *
6fbd60ef 844 * @param stdClass $user the current user
bcab42da 845 * @param bool $showicontext flag indicating whether or not to show text next to the action icons
846 */
447df209 847function message_print_recent_conversations($user1 = null, $showicontext = false, $showactionlinks = true) {
bcab42da 848 global $USER;
849
850 echo html_writer::start_tag('p', array('class' => 'heading'));
851 echo get_string('mostrecentconversations', 'message');
852 echo html_writer::end_tag('p');
853
447df209
AD
854 if (empty($user1)) {
855 $user1 = $USER;
bcab42da 856 }
857
447df209 858 $conversations = message_get_recent_conversations($user1);
bcab42da 859
178ba8bc
AD
860 // Attach context url information to create the "View this conversation" type links
861 foreach($conversations as $conversation) {
447df209 862 $conversation->contexturl = new moodle_url("/message/index.php?user1={$user1->id}&user2={$conversation->id}");
178ba8bc
AD
863 $conversation->contexturlname = get_string('thisconversation', 'message');
864 }
865
bcab42da 866 $showotheruser = true;
447df209 867 message_print_recent_messages_table($conversations, $user1, $showotheruser, $showicontext, false, $showactionlinks);
bcab42da 868}
869
870/**
871 * Print the user's recent notifications
ebe0c008 872 *
6fbd60ef 873 * @param stdClass $user the current user
bcab42da 874 */
875function message_print_recent_notifications($user=null) {
876 global $USER;
877
878 echo html_writer::start_tag('p', array('class' => 'heading'));
879 echo get_string('mostrecentnotifications', 'message');
880 echo html_writer::end_tag('p');
881
882 if (empty($user)) {
883 $user = $USER;
884 }
885
886 $notifications = message_get_recent_notifications($user);
887
888 $showicontext = false;
889 $showotheruser = false;
9949e91a 890 message_print_recent_messages_table($notifications, $user, $showotheruser, $showicontext, true);
e8e2d7f1 891}
892
bcab42da 893/**
894 * Print a list of recent messages
ebe0c008 895 *
4048f5b3
PS
896 * @access private
897 *
bcab42da 898 * @param array $messages the messages to display
4048f5b3 899 * @param stdClass $user the current user
bcab42da 900 * @param bool $showotheruser display information on the other user?
901 * @param bool $showicontext show text next to the action icons?
9949e91a 902 * @param bool $forcetexttohtml Force text to go through @see text_to_html() via @see format_text()
4048f5b3 903 * @param bool $showactionlinks
ebe0c008 904 * @return void
bcab42da 905 */
447df209 906function message_print_recent_messages_table($messages, $user = null, $showotheruser = true, $showicontext = false, $forcetexttohtml = false, $showactionlinks = true) {
bcab42da 907 global $OUTPUT;
908 static $dateformat;
e8e2d7f1 909
bcab42da 910 if (empty($dateformat)) {
911 $dateformat = get_string('strftimedatetimeshort');
912 }
e8e2d7f1 913
bcab42da 914 echo html_writer::start_tag('div', array('class' => 'messagerecent'));
915 foreach ($messages as $message) {
916 echo html_writer::start_tag('div', array('class' => 'singlemessage'));
917
918 if ($showotheruser) {
447df209
AD
919 $strcontact = $strblock = $strhistory = null;
920
921 if ($showactionlinks) {
922 if ( $message->contactlistid ) {
923 if ($message->blocked == 0) { // The other user isn't blocked.
924 $strcontact = message_contact_link($message->id, 'remove', true, null, $showicontext);
925 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
926 } else { // The other user is blocked.
927 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
928 $strblock = message_contact_link($message->id, 'unblock', true, null, $showicontext);
929 }
930 } else {
bcab42da 931 $strcontact = message_contact_link($message->id, 'add', true, null, $showicontext);
447df209 932 $strblock = message_contact_link($message->id, 'block', true, null, $showicontext);
bcab42da 933 }
bcab42da 934
447df209
AD
935 //should we show just the icon or icon and text?
936 $histicontext = 'icon';
937 if ($showicontext) {
938 $histicontext = 'both';
939 }
940 $strhistory = message_history_link($user->id, $message->id, true, '', '', $histicontext);
bcab42da 941 }
bcab42da 942 echo html_writer::start_tag('span', array('class' => 'otheruser'));
943
944 echo html_writer::start_tag('span', array('class' => 'pix'));
945 echo $OUTPUT->user_picture($message, array('size' => 20, 'courseid' => SITEID));
946 echo html_writer::end_tag('span');
947
948 echo html_writer::start_tag('span', array('class' => 'contact'));
949
447df209 950 $link = new moodle_url("/message/index.php?user1={$user->id}&user2=$message->id");
bcab42da 951 $action = null;
952 echo $OUTPUT->action_link($link, fullname($message), $action, array('title' => get_string('sendmessageto', 'message', fullname($message))));
953
954 echo html_writer::end_tag('span');//end contact
955
447df209
AD
956 if ($showactionlinks) {
957 echo $strcontact.$strblock.$strhistory;
958 }
bcab42da 959 echo html_writer::end_tag('span');//end otheruser
960 }
4048f5b3
PS
961
962 $messagetext = message_format_message_text($message, $forcetexttohtml);
bcab42da 963
964 echo html_writer::tag('span', userdate($message->timecreated, $dateformat), array('class' => 'messagedate'));
4048f5b3 965 echo html_writer::tag('span', $messagetext, array('class' => 'themessage'));
bcab42da 966 echo message_format_contexturl($message);
967 echo html_writer::end_tag('div');//end singlemessage
968 }
969 echo html_writer::end_tag('div');//end messagerecent
970}
971
4048f5b3
PS
972/**
973 * Try to guess how to convert the message to html.
974 *
975 * @access private
976 *
977 * @param stdClass $message
978 * @param bool $forcetexttohtml
979 * @return string html fragment
980 */
981function message_format_message_text($message, $forcetexttohtml = false) {
982 // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
983
984 $options = new stdClass();
985 $options->para = false;
986
987 $format = $message->fullmessageformat;
988
40e50128 989 if (strval($message->smallmessage) !== '') {
4048f5b3 990 if ($message->notification == 1) {
40e50128 991 if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
4048f5b3
PS
992 $format = FORMAT_PLAIN;
993 }
994 }
995 $messagetext = $message->smallmessage;
996
997 } else if ($message->fullmessageformat == FORMAT_HTML) {
40e50128 998 if (strval($message->fullmessagehtml) !== '') {
4048f5b3
PS
999 $messagetext = $message->fullmessagehtml;
1000 } else {
1001 $messagetext = $message->fullmessage;
1002 $format = FORMAT_MOODLE;
1003 }
1004
1005 } else {
40e50128 1006 if (strval($message->fullmessage) !== '') {
4048f5b3
PS
1007 $messagetext = $message->fullmessage;
1008 } else {
1009 $messagetext = $message->fullmessagehtml;
1010 $format = FORMAT_HTML;
1011 }
1012 }
1013
1014 if ($forcetexttohtml) {
1015 // This is a crazy hack, why not set proper format when creating the notifications?
1016 if ($format === FORMAT_PLAIN) {
1017 $format = FORMAT_MOODLE;
1018 }
1019 }
1020 return format_text($messagetext, $format, $options);
1021}
1022
bcab42da 1023/**
1024 * Add the selected user as a contact for the current user
ebe0c008 1025 *
bcab42da 1026 * @param int $contactid the ID of the user to add as a contact
1027 * @param int $blocked 1 if you wish to block the contact
1028 * @return bool/int false if the $contactid isnt a valid user id. True if no changes made.
1029 * Otherwise returns the result of update_record() or insert_record()
1030 */
e8e2d7f1 1031function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 1032 global $USER, $DB;
531e58f1 1033
bcab42da 1034 if (!$DB->record_exists('user', array('id' => $contactid))) { // invalid userid
e8e2d7f1 1035 return false;
1036 }
531e58f1 1037
3f3d9521 1038 // Check if a record already exists as we may be changing blocking status.
bcab42da 1039 if (($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) !== false) {
3f3d9521 1040 // Check if blocking status has been changed.
42c0b047 1041 if ($contact->blocked != $blocked) {
e8e2d7f1 1042 $contact->blocked = $blocked;
3f3d9521
MN
1043 $DB->update_record('message_contacts', $contact);
1044
1045 if ($blocked == 1) {
1046 // Trigger event for blocking a contact.
1047 $event = \core\event\message_contact_blocked::create(array(
1048 'objectid' => $contact->id,
1049 'userid' => $contact->userid,
1050 'relateduserid' => $contact->contactid,
1051 'context' => context_user::instance($contact->userid)
1052 ));
1053 $event->add_record_snapshot('message_contacts', $contact);
1054 $event->trigger();
cd609365
MN
1055 } else {
1056 // Trigger event for unblocking a contact.
1057 $event = \core\event\message_contact_unblocked::create(array(
1058 'objectid' => $contact->id,
1059 'userid' => $contact->userid,
1060 'relateduserid' => $contact->contactid,
1061 'context' => context_user::instance($contact->userid)
1062 ));
1063 $event->add_record_snapshot('message_contacts', $contact);
1064 $event->trigger();
3f3d9521
MN
1065 }
1066
1067 return true;
e8e2d7f1 1068 } else {
447df209 1069 // No change to blocking status.
e8e2d7f1 1070 return true;
1071 }
531e58f1 1072
172186b8 1073 } else {
447df209 1074 // New contact record.
92701024 1075 $contact = new stdClass();
e8e2d7f1 1076 $contact->userid = $USER->id;
1077 $contact->contactid = $contactid;
1078 $contact->blocked = $blocked;
0d9bdf61
MN
1079 $contact->id = $DB->insert_record('message_contacts', $contact);
1080
2236a565 1081 $eventparams = array(
0d9bdf61
MN
1082 'objectid' => $contact->id,
1083 'userid' => $contact->userid,
1084 'relateduserid' => $contact->contactid,
1085 'context' => context_user::instance($contact->userid)
2236a565
FM
1086 );
1087
1088 if ($blocked) {
1089 $event = \core\event\message_contact_blocked::create($eventparams);
1090 } else {
1091 $event = \core\event\message_contact_added::create($eventparams);
1092 }
1093 // Trigger event.
0d9bdf61
MN
1094 $event->trigger();
1095
1096 return true;
172186b8 1097 }
1098}
1099
bcab42da 1100/**
1101 * remove a contact
ebe0c008 1102 *
6fbd60ef 1103 * @param int $contactid the user ID of the contact to remove
bcab42da 1104 * @return bool returns the result of delete_records()
1105 */
e8e2d7f1 1106function message_remove_contact($contactid) {
fd1cb1e8 1107 global $USER, $DB;
5edf9f3b
MN
1108
1109 if ($contact = $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid))) {
1110 $DB->delete_records('message_contacts', array('id' => $contact->id));
1111
1112 // Trigger event for removing a contact.
1113 $event = \core\event\message_contact_removed::create(array(
1114 'objectid' => $contact->id,
1115 'userid' => $contact->userid,
1116 'relateduserid' => $contact->contactid,
1117 'context' => context_user::instance($contact->userid)
1118 ));
1119 $event->add_record_snapshot('message_contacts', $contact);
1120 $event->trigger();
1121
1122 return true;
1123 }
1124
1125 return false;
e8e2d7f1 1126}
1127
bcab42da 1128/**
1129 * Unblock a contact. Note that this reverts the previously blocked user back to a non-contact.
ebe0c008 1130 *
bcab42da 1131 * @param int $contactid the user ID of the contact to unblock
1132 * @return bool returns the result of delete_records()
1133 */
e8e2d7f1 1134function message_unblock_contact($contactid) {
cd609365 1135 return message_add_contact($contactid, 0);
e8e2d7f1 1136}
1137
bcab42da 1138/**
3f3d9521 1139 * Block a user.
ebe0c008 1140 *
bcab42da 1141 * @param int $contactid the user ID of the user to block
3f3d9521 1142 * @return bool
bcab42da 1143 */
e8e2d7f1 1144function message_block_contact($contactid) {
1145 return message_add_contact($contactid, 1);
1146}
1147
36d29c08
MN
1148/**
1149 * Checks if a user can delete a message.
1150 *
1151 * @param stdClass $message the message to delete
1152 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
1153 * but will still seem as if it was by the user)
1154 * @return bool Returns true if a user can delete the message, false otherwise.
1155 */
1156function message_can_delete_message($message, $userid) {
1157 global $USER;
1158
1159 if ($message->useridfrom == $userid) {
1160 $userdeleting = 'useridfrom';
1161 } else if ($message->useridto == $userid) {
1162 $userdeleting = 'useridto';
1163 } else {
1164 return false;
1165 }
1166
1167 $systemcontext = context_system::instance();
1168
1169 // Let's check if the user is allowed to delete this message.
1170 if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
1171 ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
1172 $USER->id == $message->$userdeleting))) {
1173 return true;
1174 }
1175
1176 return false;
1177}
1178
1179/**
1180 * Deletes a message.
1181 *
1182 * This function does not verify any permissions.
1183 *
1184 * @param stdClass $message the message to delete
1185 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
1186 * but will still seem as if it was by the user)
1187 * @return bool
1188 */
1189function message_delete_message($message, $userid) {
1190 global $DB;
1191
1192 // The column we want to alter.
1193 if ($message->useridfrom == $userid) {
1194 $coltimedeleted = 'timeuserfromdeleted';
1195 } else if ($message->useridto == $userid) {
1196 $coltimedeleted = 'timeusertodeleted';
1197 } else {
1198 return false;
1199 }
1200
1201 // Don't update it if it's already been deleted.
1202 if ($message->$coltimedeleted > 0) {
1203 return false;
1204 }
1205
1206 // Get the table we want to update.
1207 if (isset($message->timeread)) {
1208 $messagetable = 'message_read';
1209 } else {
1210 $messagetable = 'message';
1211 }
1212
1213 // Mark the message as deleted.
1214 $updatemessage = new stdClass();
1215 $updatemessage->id = $message->id;
1216 $updatemessage->$coltimedeleted = time();
b5e617e2
MN
1217 $success = $DB->update_record($messagetable, $updatemessage);
1218
1219 if ($success) {
1220 // Trigger event for deleting a message.
1221 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
1222 $userid, $messagetable, $message->id)->trigger();
1223 }
1224
1225 return $success;
36d29c08
MN
1226}
1227
bcab42da 1228/**
1229 * Load a user's contact record
ebe0c008 1230 *
bcab42da 1231 * @param int $contactid the user ID of the user whose contact record you want
ebe0c008 1232 * @return array message contacts
bcab42da 1233 */
e8e2d7f1 1234function message_get_contact($contactid) {
fd1cb1e8 1235 global $USER, $DB;
bcab42da 1236 return $DB->get_record('message_contacts', array('userid' => $USER->id, 'contactid' => $contactid));
e8e2d7f1 1237}
531e58f1 1238
bcab42da 1239/**
1240 * Print the results of a message search
ebe0c008 1241 *
bcab42da 1242 * @param mixed $frm submitted form data
1243 * @param bool $showicontext show text next to action icons?
dd6d83c1 1244 * @param object $currentuser the current user
ebe0c008 1245 * @return void
bcab42da 1246 */
dd6d83c1 1247function message_print_search_results($frm, $showicontext=false, $currentuser=null) {
bcab42da 1248 global $USER, $DB, $OUTPUT;
c8621a02 1249
dd6d83c1
AD
1250 if (empty($currentuser)) {
1251 $currentuser = $USER;
c8621a02 1252 }
e8e2d7f1 1253
bcab42da 1254 echo html_writer::start_tag('div', array('class' => 'mdl-left'));
e8e2d7f1 1255
c8621a02
AD
1256 $personsearch = false;
1257 $personsearchstring = null;
e8e2d7f1 1258 if (!empty($frm->personsubmit) and !empty($frm->name)) {
c8621a02
AD
1259 $personsearch = true;
1260 $personsearchstring = $frm->name;
1261 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1262 $personsearch = true;
1263 $personsearchstring = $frm->combinedsearch;
1264 }
531e58f1 1265
447df209 1266 // Search for person.
c8621a02 1267 if ($personsearch) {
b71d4dd2 1268 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 1269 $users = array();
a03330bd
FM
1270 $mycourses = enrol_get_my_courses('id');
1271 $mycoursesids = array();
e8e2d7f1 1272 foreach ($mycourses as $mycourse) {
a03330bd
FM
1273 $mycoursesids[] = $mycourse->id;
1274 }
1275 $susers = message_search_users($mycoursesids, $personsearchstring);
1276 foreach ($susers as $suser) {
1277 $users[$suser->id] = $suser;
e8e2d7f1 1278 }
1279 } else {
c8621a02 1280 $users = message_search_users(SITEID, $personsearchstring);
e8e2d7f1 1281 }
1282
1283 if (!empty($users)) {
bcab42da 1284 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c3931654
AD
1285 echo get_string('userssearchresults', 'message', count($users));
1286 echo html_writer::end_tag('p');
1287
bcab42da 1288 echo html_writer::start_tag('table', array('class' => 'messagesearchresults'));
e8e2d7f1 1289 foreach ($users as $user) {
531e58f1 1290
7390832c 1291 if ( $user->contactlistid ) {
447df209 1292 if ($user->blocked == 0) { // User is not blocked.
c8621a02
AD
1293 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
1294 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
e8e2d7f1 1295 } else { // blocked
c8621a02
AD
1296 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1297 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
e8e2d7f1 1298 }
e8e2d7f1 1299 } else {
c8621a02
AD
1300 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
1301 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
1302 }
1303
447df209 1304 // Should we show just the icon or icon and text?
c8621a02
AD
1305 $histicontext = 'icon';
1306 if ($showicontext) {
1307 $histicontext = 'both';
e8e2d7f1 1308 }
c8621a02 1309 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
531e58f1 1310
bcab42da 1311 echo html_writer::start_tag('tr');
40a26286 1312
bcab42da 1313 echo html_writer::start_tag('td', array('class' => 'pix'));
1314 echo $OUTPUT->user_picture($user, array('size' => 20, 'courseid' => SITEID));
1315 echo html_writer::end_tag('td');
1316
1317 echo html_writer::start_tag('td',array('class' => 'contact'));
c8621a02 1318 $action = null;
bcab42da 1319 $link = new moodle_url("/message/index.php?id=$user->id");
1320 echo $OUTPUT->action_link($link, fullname($user), $action, array('title' => get_string('sendmessageto', 'message', fullname($user))));
1321 echo html_writer::end_tag('td');
576ad290 1322
bcab42da 1323 echo html_writer::tag('td', $strcontact, array('class' => 'link'));
1324 echo html_writer::tag('td', $strblock, array('class' => 'link'));
1325 echo html_writer::tag('td', $strhistory, array('class' => 'link'));
531e58f1 1326
bcab42da 1327 echo html_writer::end_tag('tr');
e8e2d7f1 1328 }
bcab42da 1329 echo html_writer::end_tag('table');
531e58f1 1330
e8e2d7f1 1331 } else {
bcab42da 1332 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c8621a02 1333 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
c3931654 1334 echo html_writer::end_tag('p');
e8e2d7f1 1335 }
c8621a02 1336 }
531e58f1 1337
c8621a02
AD
1338 // search messages for keywords
1339 $messagesearch = false;
1340 $messagesearchstring = null;
1341 if (!empty($frm->keywords)) {
1342 $messagesearch = true;
1343 $messagesearchstring = clean_text(trim($frm->keywords));
1344 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
1345 $messagesearch = true;
1346 $messagesearchstring = clean_text(trim($frm->combinedsearch));
1347 }
531e58f1 1348
c8621a02
AD
1349 if ($messagesearch) {
1350 if ($messagesearchstring) {
1351 $keywords = explode(' ', $messagesearchstring);
ff49c389 1352 } else {
1353 $keywords = array();
1354 }
e8e2d7f1 1355 $tome = false;
1356 $fromme = false;
1357 $courseid = 'none';
1358
c8621a02
AD
1359 if (empty($frm->keywordsoption)) {
1360 $frm->keywordsoption = 'allmine';
1361 }
1362
e8e2d7f1 1363 switch ($frm->keywordsoption) {
1364 case 'tome':
1365 $tome = true;
1366 break;
1367 case 'fromme':
1368 $fromme = true;
1369 break;
1370 case 'allmine':
1371 $tome = true;
1372 $fromme = true;
1373 break;
1374 case 'allusers':
1375 $courseid = SITEID;
1376 break;
1377 case 'courseusers':
1378 $courseid = $frm->courseid;
1379 break;
1380 default:
1381 $tome = true;
1382 $fromme = true;
1383 }
1384
1385 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 1386
447df209 1387 // Get a list of contacts.
bcab42da 1388 if (($contacts = $DB->get_records('message_contacts', array('userid' => $USER->id), '', 'contactid, blocked') ) === false) {
082864f9 1389 $contacts = array();
1390 }
e8e2d7f1 1391
447df209 1392 // Print heading with number of results.
bcab42da 1393 echo html_writer::start_tag('p', array('class' => 'heading searchresultcount'));
c3931654 1394 $countresults = count($messages);
bcab42da 1395 if ($countresults == MESSAGE_SEARCH_MAX_RESULTS) {
c3931654
AD
1396 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
1397 } else {
a813a748 1398 echo get_string('keywordssearchresults', 'message', $countresults);
c3931654
AD
1399 }
1400 echo html_writer::end_tag('p');
082864f9 1401
447df209 1402 // Print table headings.
bcab42da 1403 echo html_writer::start_tag('table', array('class' => 'messagesearchresults', 'cellspacing' => '0'));
c3931654 1404
bcab42da 1405 $headertdstart = html_writer::start_tag('td', array('class' => 'messagesearchresultscol'));
c3931654 1406 $headertdend = html_writer::end_tag('td');
bcab42da 1407 echo html_writer::start_tag('tr');
c3931654
AD
1408 echo $headertdstart.get_string('from').$headertdend;
1409 echo $headertdstart.get_string('to').$headertdend;
1410 echo $headertdstart.get_string('message', 'message').$headertdend;
1411 echo $headertdstart.get_string('timesent', 'message').$headertdend;
bcab42da 1412 echo html_writer::end_tag('tr');
082864f9 1413
1414 $blockedcount = 0;
54d8f804 1415 $dateformat = get_string('strftimedatetimeshort');
38c6a928 1416 $strcontext = get_string('context', 'message');
e8e2d7f1 1417 foreach ($messages as $message) {
082864f9 1418
447df209 1419 // Ignore messages to and from blocked users unless $frm->includeblocked is set.
b71d4dd2 1420 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 1421 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
1422 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
1423 )
1424 ) {
1425 $blockedcount ++;
e8e2d7f1 1426 continue;
1427 }
531e58f1 1428
447df209 1429 // Load user-to record.
082864f9 1430 if ($message->useridto !== $USER->id) {
3bcf6b3c 1431 $userto = core_user::get_user($message->useridto);
531e58f1 1432 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 1433 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 1434 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 1435 ($contacts[$message->useridto]->blocked == 1) );
1436 } else {
1437 $userto = false;
1438 $tocontact = false;
1439 $toblocked = false;
1440 }
531e58f1 1441
447df209 1442 // Load user-from record.
082864f9 1443 if ($message->useridfrom !== $USER->id) {
3bcf6b3c 1444 $userfrom = core_user::get_user($message->useridfrom);
531e58f1 1445 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 1446 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 1447 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 1448 ($contacts[$message->useridfrom]->blocked == 1) );
1449 } else {
1450 $userfrom = false;
1451 $fromcontact = false;
1452 $fromblocked = false;
1453 }
1454
447df209 1455 // Find date string for this message.
e520509a 1456 $date = usergetdate($message->timecreated);
1457 $datestring = $date['year'].$date['mon'].$date['mday'];
1458
447df209 1459 // Print out message row.
bcab42da 1460 echo html_writer::start_tag('tr', array('valign' => 'top'));
1461
1462 echo html_writer::start_tag('td', array('class' => 'contact'));
c8621a02 1463 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
bcab42da 1464 echo html_writer::end_tag('td');
1465
1466 echo html_writer::start_tag('td', array('class' => 'contact'));
c8621a02 1467 message_print_user($userto, $tocontact, $toblocked, $showicontext);
bcab42da 1468 echo html_writer::end_tag('td');
1469
1470 echo html_writer::start_tag('td', array('class' => 'summary'));
f91528d9 1471 echo message_get_fragment($message->smallmessage, $keywords);
bcab42da 1472 echo html_writer::start_tag('div', array('class' => 'link'));
c8621a02 1473
447df209
AD
1474 // If the user clicks the context link display message sender on the left.
1475 // EXCEPT if the current user is in the conversation. Current user == always on the left.
dd6d83c1
AD
1476 $leftsideuserid = $rightsideuserid = null;
1477 if ($currentuser->id == $message->useridto) {
1478 $leftsideuserid = $message->useridto;
1479 $rightsideuserid = $message->useridfrom;
c8621a02 1480 } else {
dd6d83c1
AD
1481 $leftsideuserid = $message->useridfrom;
1482 $rightsideuserid = $message->useridto;
c8621a02 1483 }
dd6d83c1 1484 message_history_link($leftsideuserid, $rightsideuserid, false,
c8621a02 1485 $messagesearchstring, 'm'.$message->id, $strcontext);
bcab42da 1486 echo html_writer::end_tag('div');
1487 echo html_writer::end_tag('td');
1488
1489 echo html_writer::tag('td', userdate($message->timecreated, $dateformat), array('class' => 'date'));
1490
1491 echo html_writer::end_tag('tr');
082864f9 1492 }
531e58f1 1493
e8e2d7f1 1494
e520509a 1495 if ($blockedcount > 0) {
bcab42da 1496 echo html_writer::start_tag('tr');
1497 echo html_writer::tag('td', get_string('blockedmessages', 'message', $blockedcount), array('colspan' => 4, 'align' => 'center'));
1498 echo html_writer::end_tag('tr');
e520509a 1499 }
bcab42da 1500 echo html_writer::end_tag('table');
531e58f1 1501
e8e2d7f1 1502 } else {
bcab42da 1503 echo html_writer::tag('p', get_string('keywordssearchresults', 'message', 0), array('class' => 'heading'));
e8e2d7f1 1504 }
c8621a02 1505 }
e8e2d7f1 1506
c8621a02 1507 if (!$personsearch && !$messagesearch) {
71666cf3 1508 //they didn't enter any search terms
aa9a6867 1509 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 1510 }
1511
bcab42da 1512 echo html_writer::end_tag('div');
e8e2d7f1 1513}
1514
bcab42da 1515/**
1516 * Print information on a user. Used when printing search results.
ebe0c008 1517 *
bcab42da 1518 * @param object/bool $user the user to display or false if you just want $USER
1519 * @param bool $iscontact is the user being displayed a contact?
1520 * @param bool $isblocked is the user being displayed blocked?
1521 * @param bool $includeicontext include text next to the action icons?
ebe0c008 1522 * @return void
bcab42da 1523 */
c8621a02 1524function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
7cb1a1ad 1525 global $USER, $OUTPUT;
1d422980 1526
3bcf6b3c
RT
1527 $userpictureparams = array('size' => 20, 'courseid' => SITEID);
1528
082864f9 1529 if ($user === false) {
3bcf6b3c
RT
1530 echo $OUTPUT->user_picture($USER, $userpictureparams);
1531 } else if (core_user::is_real_user($user->id)) { // If not real user, then don't show any links.
1532 $userpictureparams['link'] = false;
1533 echo $OUTPUT->user_picture($USER, $userpictureparams);
1534 echo fullname($user);
082864f9 1535 } else {
3bcf6b3c 1536 echo $OUTPUT->user_picture($user, $userpictureparams);
f2bba619
FM
1537
1538 $link = new moodle_url("/message/index.php?id=$user->id");
1539 echo $OUTPUT->action_link($link, fullname($user), null, array('title' =>
1540 get_string('sendmessageto', 'message', fullname($user))));
c8621a02
AD
1541
1542 $return = false;
1543 $script = null;
082864f9 1544 if ($iscontact) {
c8621a02 1545 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
082864f9 1546 } else {
c8621a02 1547 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
082864f9 1548 }
f2bba619 1549
082864f9 1550 if ($isblocked) {
c8621a02 1551 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
082864f9 1552 } else {
c8621a02 1553 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
082864f9 1554 }
1555 }
1556}
1557
bcab42da 1558/**
1559 * Print a message contact link
ebe0c008 1560 *
bcab42da 1561 * @param int $userid the ID of the user to apply to action to
1562 * @param string $linktype can be add, remove, block or unblock
1563 * @param bool $return if true return the link as a string. If false echo the link.
1564 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
1565 * @param bool $text include text next to the icons?
1566 * @param bool $icon include a graphical icon?
1567 * @return string if $return is true otherwise bool
1568 */
c8621a02 1569function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
bcab42da 1570 global $OUTPUT, $PAGE;
e520509a 1571
6898e848 1572 //hold onto the strings as we're probably creating a bunch of links
e520509a 1573 static $str;
1574
c8621a02 1575 if (empty($script)) {
cee92282 1576 //strip off previous action params like 'removecontact'
4090a30f 1577 $script = message_remove_url_params($PAGE->url);
c8621a02
AD
1578 }
1579
e520509a 1580 if (empty($str->blockcontact)) {
b85b25eb 1581 $str = new stdClass();
e520509a 1582 $str->blockcontact = get_string('blockcontact', 'message');
1583 $str->unblockcontact = get_string('unblockcontact', 'message');
1584 $str->removecontact = get_string('removecontact', 'message');
1585 $str->addcontact = get_string('addcontact', 'message');
1586 }
1587
5d6b319b 1588 $command = $linktype.'contact';
1589 $string = $str->{$command};
6898e848
AD
1590
1591 $safealttext = s($string);
1592
1593 $safestring = '';
3a11c09f 1594 if (!empty($text)) {
6898e848 1595 $safestring = $safealttext;
c8621a02
AD
1596 }
1597
1598 $img = '';
1599 if ($icon) {
6898e848
AD
1600 $iconpath = null;
1601 switch ($linktype) {
1602 case 'block':
1603 $iconpath = 't/block';
1604 break;
1605 case 'unblock':
f2bba619 1606 $iconpath = 't/unblock';
6898e848
AD
1607 break;
1608 case 'remove':
f2bba619 1609 $iconpath = 't/removecontact';
6898e848
AD
1610 break;
1611 case 'add':
1612 default:
f2bba619 1613 $iconpath = 't/addcontact';
6898e848
AD
1614 }
1615
1616 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
082864f9 1617 }
5d6b319b 1618
c8621a02 1619 $output = '<span class="'.$linktype.'contact">'.
5d6b319b 1620 '<a href="'.$script.'&amp;'.$command.'='.$userid.
01e85326 1621 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
c8621a02 1622 $img.
6898e848 1623 $safestring.'</a></span>';
5d6b319b 1624
e520509a 1625 if ($return) {
1626 return $output;
082864f9 1627 } else {
e520509a 1628 echo $output;
082864f9 1629 return true;
1630 }
1631}
1632
bcab42da 1633/**
1634 * echo or return a link to take the user to the full message history between themselves and another user
ebe0c008 1635 *
dd6d83c1 1636 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
bcab42da 1637 * @param int $userid2 the ID of the other user
1638 * @param bool $return true to return the link as a string. False to echo the link.
1639 * @param string $keywords any keywords to highlight in the message history
1640 * @param string $position anchor name to jump to within the message history
1641 * @param string $linktext optionally specify the link text
1642 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
1643 */
1644function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
8f0137e1 1645 global $OUTPUT, $PAGE;
830d0af6 1646 static $strmessagehistory;
1647
1648 if (empty($strmessagehistory)) {
1649 $strmessagehistory = get_string('messagehistory', 'message');
1650 }
2514081c 1651
e520509a 1652 if ($position) {
1653 $position = "#$position";
1654 }
38c6a928 1655 if ($keywords) {
1656 $keywords = "&search=".urlencode($keywords);
1657 }
62119d65 1658
830d0af6 1659 if ($linktext == 'icon') { // Icon only
f2bba619 1660 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 1661 } else if ($linktext == 'both') { // Icon and standard name
f2bba619 1662 $fulllink = '<img src="'.$OUTPUT->pix_url('t/messages') . '" class="iconsmall" alt="" />';
830d0af6 1663 $fulllink .= '&nbsp;'.$strmessagehistory;
1664 } else if ($linktext) { // Custom name
1665 $fulllink = $linktext;
1666 } else { // Standard name only
1667 $fulllink = $strmessagehistory;
fd7006f6 1668 }
1669
40a26286 1670 $popupoptions = array(
1671 'height' => 500,
1672 'width' => 500,
1673 'menubar' => false,
1674 'location' => false,
1675 'status' => true,
1676 'scrollbars' => true,
1677 'resizable' => true);
1678
dd6d83c1 1679 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
8f0137e1
MG
1680 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
1681 $link->param('viewing', $PAGE->url->get_param('viewing'));
1682 }
c8621a02 1683 $action = null;
bcab42da 1684 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
62119d65 1685
5d6b319b 1686 $str = '<span class="history">'.$str.'</span>';
1687
bcab42da 1688 if ($return) {
62119d65 1689 return $str;
1690 } else {
1691 echo $str;
1692 return true;
1693 }
1694}
e8e2d7f1 1695
1696
1697/**
a03330bd
FM
1698 * Search through course users.
1699 *
1700 * If $courseids contains the site course then this function searches
1701 * through all undeleted and confirmed users.
e8e2d7f1 1702 *
a03330bd
FM
1703 * @param int|array $courseids Course ID or array of course IDs.
1704 * @param string $searchtext the text to search for.
1705 * @param string $sort the column name to order by.
2e2d1977 1706 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
a03330bd 1707 * @return array An array of {@link $USER} records.
e8e2d7f1 1708 */
a03330bd 1709function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 1710 global $CFG, $USER, $DB;
e8e2d7f1 1711
a03330bd
FM
1712 // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
1713 if (!$courseids) {
1714 $courseids = array(SITEID);
1715 }
1716
1717 // Allow an integer to be passed.
1718 if (!is_array($courseids)) {
1719 $courseids = array($courseids);
1720 }
1721
245ac557 1722 $fullname = $DB->sql_fullname();
2e2d1977 1723 $ufields = user_picture::fields('u');
e8e2d7f1 1724
1725 if (!empty($sort)) {
1726 $order = ' ORDER BY '. $sort;
1727 } else {
1728 $order = '';
1729 }
1730
2e2d1977
AD
1731 $params = array(
1732 'userid' => $USER->id,
1733 'query' => "%$searchtext%"
1734 );
1735
1736 if (empty($exceptions)) {
1737 $exceptions = array();
1738 } else if (!empty($exceptions) && is_string($exceptions)) {
1739 $exceptions = explode(',', $exceptions);
1740 }
1741
1742 // Ignore self and guest account.
1743 $exceptions[] = $USER->id;
1744 $exceptions[] = $CFG->siteguest;
1745
1746 // Exclude exceptions from the search result.
1747 list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
1748 $except = ' AND u.id ' . $except;
1749 $params = array_merge($params_except, $params);
a03330bd
FM
1750
1751 if (in_array(SITEID, $courseids)) {
1752 // Search on site level.
3a11c09f 1753 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
d9eef08a 1754 FROM {user} u
fd1cb1e8 1755 LEFT JOIN {message_contacts} mc
2e2d1977 1756 ON mc.contactid = u.id AND mc.userid = :userid
3a11c09f 1757 WHERE u.deleted = '0' AND u.confirmed = '1'
2e2d1977 1758 AND (".$DB->sql_like($fullname, ':query', false).")
fd1cb1e8 1759 $except
1760 $order", $params);
e8e2d7f1 1761 } else {
a03330bd 1762 // Search in courses.
a03330bd
FM
1763
1764 // Getting the context IDs or each course.
1765 $contextids = array();
1766 foreach ($courseids as $courseid) {
1767 $context = context_course::instance($courseid);
1768 $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
1769 }
2e2d1977 1770 list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
a03330bd
FM
1771 $params = array_merge($params, $contextparams);
1772
1773 // Everyone who has a role assignment in this course or higher.
1774 // TODO: add enabled enrolment join here (skodak)
186fc534 1775 $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mc.blocked
b6e52658 1776 FROM {user} u
fd1cb1e8 1777 JOIN {role_assignments} ra ON ra.userid = u.id
1778 LEFT JOIN {message_contacts} mc
2e2d1977 1779 ON mc.contactid = u.id AND mc.userid = :userid
3a11c09f 1780 WHERE u.deleted = '0' AND u.confirmed = '1'
2e2d1977 1781 AND (".$DB->sql_like($fullname, ':query', false).")
a03330bd 1782 AND ra.contextid $contextwhere
fd1cb1e8 1783 $except
1784 $order", $params);
d76a5a7f 1785
1786 return $users;
e8e2d7f1 1787 }
1788}
1789
bcab42da 1790/**
447df209
AD
1791 * Search a user's messages
1792 *
1793 * Returns a list of posts found using an array of search terms
1794 * eg word +word -word
ebe0c008 1795 *
bcab42da 1796 * @param array $searchterms an array of search terms (strings)
1797 * @param bool $fromme include messages from the user?
1798 * @param bool $tome include messages to the user?
1799 * @param mixed $courseid SITEID for admins searching all messages. Other behaviour not yet implemented
1800 * @param int $userid the user ID of the current user
1801 * @return mixed An array of messages or false if no matching messages were found
1802 */
082864f9 1803function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
fd1cb1e8 1804 global $CFG, $USER, $DB;
e8e2d7f1 1805
447df209 1806 // If user is searching all messages check they are allowed to before doing anything else.
bf0f06b1 1807 if ($courseid == SITEID && !has_capability('moodle/site:readallmessages', context_system::instance())) {
48e03792
AD
1808 print_error('accessdenied','admin');
1809 }
1810
447df209 1811 // If no userid sent then assume current user.
531e58f1 1812 if ($userid == 0) $userid = $USER->id;
082864f9 1813
447df209 1814 // Some differences in SQL syntax.
d9eef08a 1815 if ($DB->sql_regex_supported()) {
1816 $REGEXP = $DB->sql_regex(true);
1817 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 1818 }
1819
d9eef08a 1820 $searchcond = array();
1821 $params = array();
1822 $i = 0;
e8e2d7f1 1823
447df209
AD
1824 // Preprocess search terms to check whether we have at least 1 eligible search term.
1825 // If we do we can drop words around it like 'a'.
c3931654
AD
1826 $dropshortwords = false;
1827 foreach ($searchterms as $searchterm) {
1828 if (strlen($searchterm) >= 2) {
1829 $dropshortwords = true;
1830 }
1831 }
1832
e8e2d7f1 1833 foreach ($searchterms as $searchterm) {
d9eef08a 1834 $i++;
1835
447df209 1836 $NOT = false; // Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle.
d9eef08a 1837
c3931654 1838 if ($dropshortwords && strlen($searchterm) < 2) {
e8e2d7f1 1839 continue;
1840 }
447df209 1841 // Under Oracle and MSSQL, trim the + and - operators and perform simpler LIKE search.
d9eef08a 1842 if (!$DB->sql_regex_supported()) {
1843 if (substr($searchterm, 0, 1) == '-') {
47586394 1844 $NOT = true;
d9eef08a 1845 }
6bb4875f 1846 $searchterm = trim($searchterm, '+-');
1847 }
1848
e8e2d7f1 1849 if (substr($searchterm,0,1) == "+") {
1850 $searchterm = substr($searchterm,1);
d9eef08a 1851 $searchterm = preg_quote($searchterm, '|');
3d143595 1852 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
d9eef08a 1853 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1854
e8e2d7f1 1855 } else if (substr($searchterm,0,1) == "-") {
1856 $searchterm = substr($searchterm,1);
d9eef08a 1857 $searchterm = preg_quote($searchterm, '|');
3d143595 1858 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
d9eef08a 1859 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1860
e8e2d7f1 1861 } else {
47586394 1862 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
d9eef08a 1863 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 1864 }
172186b8 1865 }
1866
d9eef08a 1867 if (empty($searchcond)) {
dd54dc31 1868 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
ff49c389 1869 $params['ss1'] = "%";
1870 } else {
1871 $searchcond = implode(" AND ", $searchcond);
8a51efe9 1872 }
e8e2d7f1 1873
447df209
AD
1874 // There are several possibilities
1875 // 1. courseid = SITEID : The admin is searching messages by all users
1876 // 2. courseid = ?? : A teacher is searching messages by users in
1877 // one of their courses - currently disabled
1878 // 3. courseid = none : User is searching their own messages;
1879 // a. Messages from user
1880 // b. Messages to user
1881 // c. Messages to and from user
082864f9 1882
36d29c08
MN
1883 if ($fromme && $tome) {
1884 $searchcond .= " AND ((useridto = :useridto AND timeusertodeleted = 0) OR
1885 (useridfrom = :useridfrom AND timeuserfromdeleted = 0))";
1886 $params['useridto'] = $userid;
1887 $params['useridfrom'] = $userid;
1888 } else if ($fromme) {
1889 $searchcond .= " AND (useridfrom = :useridfrom AND timeuserfromdeleted = 0)";
1890 $params['useridfrom'] = $userid;
1891 } else if ($tome) {
1892 $searchcond .= " AND (useridto = :useridto AND timeusertodeleted = 0)";
1893 $params['useridto'] = $userid;
1894 }
447df209 1895 if ($courseid == SITEID) { // Admin is searching all messages.
f91528d9 1896 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
d9eef08a 1897 FROM {message_read} m
c3931654 1898 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
f91528d9 1899 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
d9eef08a 1900 FROM {message} m
c3931654 1901 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
d9eef08a 1902
1903 } else if ($courseid !== 'none') {
447df209 1904 // This has not been implemented due to security concerns.
d9eef08a 1905 $m_read = array();
1906 $m_unread = array();
e8e2d7f1 1907
082864f9 1908 } else {
531e58f1 1909
d9eef08a 1910 if ($fromme and $tome) {
1911 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1912 $params['userid1'] = $userid;
1913 $params['userid2'] = $userid;
1914
1915 } else if ($fromme) {
1916 $searchcond .= " AND m.useridfrom=:userid";
1917 $params['userid'] = $userid;
531e58f1 1918
d9eef08a 1919 } else if ($tome) {
1920 $searchcond .= " AND m.useridto=:userid";
1921 $params['userid'] = $userid;
1922 }
531e58f1 1923
f91528d9 1924 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
d9eef08a 1925 FROM {message_read} m
c3931654 1926 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
f91528d9 1927 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.smallmessage, m.fullmessage, m.timecreated
d9eef08a 1928 FROM {message} m
c3931654 1929 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
531e58f1 1930
e8e2d7f1 1931 }
1932
082864f9 1933 /// The keys may be duplicated in $m_read and $m_unread so we can't
1934 /// do a simple concatenation
92701024 1935 $messages = array();
d9eef08a 1936 foreach ($m_read as $m) {
1937 $messages[] = $m;
1938 }
1939 foreach ($m_unread as $m) {
1940 $messages[] = $m;
1941 }
e8e2d7f1 1942
1943 return (empty($messages)) ? false : $messages;
172186b8 1944}
1945
bcab42da 1946/**
1947 * Given a message object that we already know has a long message
1948 * this function truncates the message nicely to the first
1949 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
ebe0c008 1950 *
bcab42da 1951 * @param string $message the message
1952 * @param int $minlength the minimum length to trim the message to
1953 * @return string the shortened message
1954 */
1955function message_shorten_message($message, $minlength = 0) {
e8e2d7f1 1956 $i = 0;
1957 $tag = false;
1958 $length = strlen($message);
1959 $count = 0;
1960 $stopzone = false;
1961 $truncate = 0;
1962 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 1963
e8e2d7f1 1964
1965 for ($i=0; $i<$length; $i++) {
1966 $char = $message[$i];
1967
1968 switch ($char) {
1969 case "<":
1970 $tag = true;
1971 break;
1972 case ">":
1973 $tag = false;
1974 break;
1975 default:
1976 if (!$tag) {
1977 if ($stopzone) {
1978 if ($char == '.' or $char == ' ') {
1979 $truncate = $i+1;
1980 break 2;
1981 }
1982 }
1983 $count++;
1984 }
1985 break;
1986 }
1987 if (!$stopzone) {
1988 if ($count > $minlength) {
1989 $stopzone = true;
1990 }
1991 }
1992 }
1993
1994 if (!$truncate) {
1995 $truncate = $i;
1996 }
1997
1998 return substr($message, 0, $truncate);
1999}
2000
38c6a928 2001
d9eef08a 2002/**
38c6a928 2003 * Given a string and an array of keywords, this function looks
2004 * for the first keyword in the string, and then chops out a
2005 * small section from the text that shows that word in context.
ebe0c008 2006 *
bcab42da 2007 * @param string $message the text to search
2008 * @param array $keywords array of keywords to find
38c6a928 2009 */
2010function message_get_fragment($message, $keywords) {
2011
f3832596 2012 $fullsize = 160;
38c6a928 2013 $halfsize = (int)($fullsize/2);
2014
2015 $message = strip_tags($message);
2016
2017 foreach ($keywords as $keyword) { // Just get the first one
2018 if ($keyword !== '') {
2019 break;
2020 }
2021 }
2022 if (empty($keyword)) { // None found, so just return start of message
2023 return message_shorten_message($message, 30);
2024 }
2025
2026 $leadin = $leadout = '';
2027
2028/// Find the start of the fragment
2029 $start = 0;
2030 $length = strlen($message);
2031
2032 $pos = strpos($message, $keyword);
2033 if ($pos > $halfsize) {
2034 $start = $pos - $halfsize;
2035 $leadin = '...';
2036 }
2037/// Find the end of the fragment
2038 $end = $start + $fullsize;
2039 if ($end > $length) {
2040 $end = $length;
2041 } else {
2042 $leadout = '...';
2043 }
2044
2045/// Pull out the fragment and format it
2046
2047 $fragment = substr($message, $start, $end - $start);
2048 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
2049 return $fragment;
2050}
2051
bcab42da 2052/**
2053 * Retrieve the messages between two users
ebe0c008 2054 *
bcab42da 2055 * @param object $user1 the current user
2056 * @param object $user2 the other user
2057 * @param int $limitnum the maximum number of messages to retrieve
2058 * @param bool $viewingnewmessages are we currently viewing new messages?
2059 */
a813a748
AD
2060function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
2061 global $DB, $CFG;
fd1cb1e8 2062
c8621a02
AD
2063 $messages = array();
2064
2065 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
2066 //desc to get the last $limitnum messages then flip the order in php
2067 $sort = 'asc';
2068 if ($limitnum>0) {
2069 $sort = 'desc';
2070 }
2071
a813a748
AD
2072 $notificationswhere = null;
2073 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
2074 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
2075 $notificationswhere = 'AND notification=0';
2076 }
2077
33bd52f3
AD
2078 //prevent notifications of your own actions appearing in your own message history
2079 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
2080
36d29c08
MN
2081 $sql = "((useridto = ? AND useridfrom = ? AND timeusertodeleted = 0) OR
2082 (useridto = ? AND useridfrom = ? AND timeuserfromdeleted = 0))";
2083 if ($messages_read = $DB->get_records_select('message_read', $sql . $notificationswhere . $ownnotificationwhere,
33bd52f3 2084 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02
AD
2085 "timecreated $sort", '*', 0, $limitnum)) {
2086 foreach ($messages_read as $message) {
6109f7af 2087 $messages[] = $message;
c8621a02
AD
2088 }
2089 }
36d29c08 2090 if ($messages_new = $DB->get_records_select('message', $sql . $ownnotificationwhere,
33bd52f3 2091 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02 2092 "timecreated $sort", '*', 0, $limitnum)) {
b9ee0638 2093 foreach ($messages_new as $message) {
6109f7af 2094 $messages[] = $message;
b9ee0638 2095 }
2096 }
c8621a02 2097
2f1e464a 2098 $result = core_collator::asort_objects_by_property($messages, 'timecreated', core_collator::SORT_NUMERIC);
6109f7af 2099
c8621a02 2100 //if we only want the last $limitnum messages
2846b9a6 2101 $messagecount = count($messages);
6109f7af
AD
2102 if ($limitnum > 0 && $messagecount > $limitnum) {
2103 $messages = array_slice($messages, $messagecount - $limitnum, $limitnum, true);
c8621a02 2104 }
3a11c09f 2105
b9ee0638 2106 return $messages;
2107}
2108
bcab42da 2109/**
2110 * Print the message history between two users
ebe0c008 2111 *
bcab42da 2112 * @param object $user1 the current user
2113 * @param object $user2 the other user
2114 * @param string $search search terms to highlight
2115 * @param int $messagelimit maximum number of messages to return
2116 * @param string $messagehistorylink the html for the message history link or false
2117 * @param bool $viewingnewmessages are we currently viewing new messages?
2118 */
447df209 2119function message_print_message_history($user1, $user2 ,$search = '', $messagelimit = 0, $messagehistorylink = false, $viewingnewmessages = false, $showactionlinks = true) {
36d29c08
MN
2120 global $OUTPUT, $PAGE;
2121
2122 $PAGE->requires->yui_module(
2123 array('moodle-core_message-toolbox'),
2124 'M.core_message.toolbox.deletemsg.init',
2125 array(array())
2126 );
c8621a02 2127
e19367db
BB
2128 echo $OUTPUT->box_start('center', 'message_user_pictures');
2129 echo $OUTPUT->box_start('user');
2130 echo $OUTPUT->box_start('generalbox', 'user1');
bcab42da 2131 echo $OUTPUT->user_picture($user1, array('size' => 100, 'courseid' => SITEID));
2132 echo html_writer::tag('div', fullname($user1), array('class' => 'heading'));
e19367db
BB
2133 echo $OUTPUT->box_end();
2134 echo $OUTPUT->box_end();
bcab42da 2135
e19367db
BB
2136 $imgattr = array('src' => $OUTPUT->pix_url('i/twoway'), 'alt' => '', 'width' => 16, 'height' => 16);
2137 echo $OUTPUT->box(html_writer::empty_tag('img', $imgattr), 'between');
bcab42da 2138
e19367db
BB
2139 echo $OUTPUT->box_start('user');
2140 echo $OUTPUT->box_start('generalbox', 'user2');
9a90e7c5
RT
2141 // Show user picture with link is real user else without link.
2142 if (core_user::is_real_user($user2->id)) {
2143 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID));
2144 } else {
2145 echo $OUTPUT->user_picture($user2, array('size' => 100, 'courseid' => SITEID, 'link' => false));
2146 }
bcab42da 2147 echo html_writer::tag('div', fullname($user2), array('class' => 'heading'));
c8621a02 2148
447df209 2149 if ($showactionlinks && isset($user2->iscontact) && isset($user2->isblocked)) {
c8621a02
AD
2150
2151 $script = null;
2152 $text = true;
2153 $icon = false;
2154
447df209
AD
2155 $strcontact = message_get_contact_add_remove_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
2156 $strblock = message_get_contact_block_link($user2->iscontact, $user2->isblocked, $user2, $script, $text, $icon);
35fe9b8a 2157 $useractionlinks = $strcontact.'&nbsp;|&nbsp;'.$strblock;
41117b3e 2158
bcab42da 2159 echo html_writer::tag('div', $useractionlinks, array('class' => 'useractionlinks'));
c8621a02 2160 }
e19367db
BB
2161 echo $OUTPUT->box_end();
2162 echo $OUTPUT->box_end();
c8621a02
AD
2163 echo $OUTPUT->box_end();
2164
2165 if (!empty($messagehistorylink)) {
2166 echo $messagehistorylink;
2167 }
2168
2169 /// Get all the messages and print them
a813a748 2170 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
c8621a02
AD
2171 $tablecontents = '';
2172
8e803c3f 2173 $current = new stdClass();
c8621a02
AD
2174 $current->mday = '';
2175 $current->month = '';
2176 $current->year = '';
2177 $messagedate = get_string('strftimetime');
2178 $blockdate = get_string('strftimedaydate');
36d29c08 2179 $messagenumber = 0;
c8621a02 2180 foreach ($messages as $message) {
36d29c08 2181 $messagenumber++;
a813a748
AD
2182 if ($message->notification) {
2183 $notificationclass = ' notification';
2184 } else {
2185 $notificationclass = null;
2186 }
c8621a02
AD
2187 $date = usergetdate($message->timecreated);
2188 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
2189 $current->mday = $date['mday'];
2190 $current->month = $date['month'];
2191 $current->year = $date['year'];
2192
bcab42da 2193 $datestring = html_writer::empty_tag('a', array('name' => $date['year'].$date['mon'].$date['mday']));
2194 $tablecontents .= html_writer::tag('div', $datestring, array('class' => 'mdl-align heading'));
2195
2196 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'mdl-align');
c8621a02 2197 }
bcab42da 2198
c8621a02 2199 if ($message->useridfrom == $user1->id) {
bcab42da 2200 $formatted_message = message_format_message($message, $messagedate, $search, 'me');
2201 $side = 'left';
c8621a02 2202 } else {
bcab42da 2203 $formatted_message = message_format_message($message, $messagedate, $search, 'other');
2204 $side = 'right';
c8621a02 2205 }
36d29c08
MN
2206
2207 // Check if it is a read message or not.
2208 if (isset($message->timeread)) {
2209 $type = 'message_read';
2210 } else {
2211 $type = 'message';
2212 }
2213
2214 if (message_can_delete_message($message, $user1->id)) {
2215 $usergroup = optional_param('usergroup', MESSAGE_VIEW_UNREAD_MESSAGES, PARAM_ALPHANUMEXT);
2216 $viewing = optional_param('viewing', $usergroup, PARAM_ALPHANUMEXT);
2217 $deleteurl = new moodle_url('/message/index.php', array('user1' => $user1->id, 'user2' => $user2->id,
2218 'viewing' => $viewing, 'deletemessageid' => $message->id, 'deletemessagetype' => $type,
2219 'sesskey' => sesskey()));
2220
2221 $deleteicon = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete')));
2222 $deleteicon = html_writer::tag('div', $deleteicon, array('class' => 'deleteicon accesshide'));
2223 $formatted_message .= $deleteicon;
2224 }
2225
2226 $tablecontents .= html_writer::tag('div', $formatted_message, array('class' => "mdl-left messagecontent
2227 $side $notificationclass", 'id' => 'message_' . $messagenumber));
c8621a02
AD
2228 }
2229
bcab42da 2230 echo html_writer::nonempty_tag('div', $tablecontents, array('class' => 'mdl-left messagehistory'));
c8621a02 2231 } else {
bcab42da 2232 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class' => 'mdl-align messagehistory'));
c8621a02
AD
2233 }
2234}
2235
bcab42da 2236/**
2237 * Format a message for display in the message history
ebe0c008 2238 *
bcab42da 2239 * @param object $message the message object
2240 * @param string $format optional date format
2241 * @param string $keywords keywords to highlight
2242 * @param string $class CSS class to apply to the div around the message
2243 * @return string the formatted message
2244 */
2245function message_format_message($message, $format='', $keywords='', $class='other') {
acd21a2d 2246
2247 static $dateformat;
2248
bcab42da 2249 //if we haven't previously set the date format or they've supplied a new one
2250 if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
acd21a2d 2251 if ($format) {
2252 $dateformat = $format;
2253 } else {
bcab42da 2254 $dateformat = get_string('strftimedatetimeshort');
acd21a2d 2255 }
b9ee0638 2256 }
acd21a2d 2257 $time = userdate($message->timecreated, $dateformat);
6ee2611c 2258
4048f5b3 2259 $messagetext = message_format_message_text($message, false);
bcab42da 2260
2261 if ($keywords) {
2262 $messagetext = highlight($keywords, $messagetext);
2263 }
2264
4048f5b3
PS
2265 $messagetext .= message_format_contexturl($message);
2266
1555e10c
PS
2267 $messagetext = clean_text($messagetext, FORMAT_HTML);
2268
a2592fec
AD
2269 return <<<TEMPLATE
2270<div class='message $class'>
f5482be6 2271 <a name="m{$message->id}"></a>
a2592fec
AD
2272 <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
2273</div>
2274TEMPLATE;
bcab42da 2275}
2276
2277/**
2278 * Format a the context url and context url name of a message for display
ebe0c008 2279 *
bcab42da 2280 * @param object $message the message object
2281 * @return string the formatted string
2282 */
2283function message_format_contexturl($message) {
2284 $s = null;
2285
14a0e7dd
AD
2286 if (!empty($message->contexturl)) {
2287 $displaytext = null;
2288 if (!empty($message->contexturlname)) {
2289 $displaytext= $message->contexturlname;
2290 } else {
2291 $displaytext= $message->contexturl;
2292 }
bcab42da 2293 $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
2294 $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
2295 $s .= html_writer::end_tag('div');
38c6a928 2296 }
14a0e7dd 2297
bcab42da 2298 return $s;
b9ee0638 2299}
e8e2d7f1 2300
fd1cb1e8 2301/**
bcab42da 2302 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
ebe0c008 2303 *
bcab42da 2304 * @param object $userfrom the message sender
2305 * @param object $userto the message recipient
2306 * @param string $message the message
2307 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
3a00a167 2308 * @return int|false the ID of the new message or false
405f01ee 2309 */
bcab42da 2310function message_post_message($userfrom, $userto, $message, $format) {
27a39763 2311 global $SITE, $CFG, $USER;
4ffa1463 2312
8e803c3f 2313 $eventdata = new stdClass();
1560760f 2314 $eventdata->component = 'moodle';
1c50df9f 2315 $eventdata->name = 'instantmessage';
3b120e46 2316 $eventdata->userfrom = $userfrom;
2317 $eventdata->userto = $userto;
4ffa1463
AD
2318
2319 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
2320 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
2321
bcab42da 2322 if ($format == FORMAT_HTML) {
156205fc 2323 $eventdata->fullmessagehtml = $message;
22e23da6
AD
2324 //some message processors may revert to sending plain text even if html is supplied
2325 //so we keep both plain and html versions if we're intending to send html
2326 $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
156205fc
AD
2327 } else {
2328 $eventdata->fullmessage = $message;
2329 $eventdata->fullmessagehtml = '';
2330 }
31da70cc 2331
c8621a02 2332 $eventdata->fullmessageformat = $format;
7e98f60b 2333 $eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
27a39763
AD
2334
2335 $s = new stdClass();
bf0f06b1 2336 $s->sitename = format_string($SITE->shortname, true, array('context' => context_course::instance(SITEID)));
536a56e7 2337 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
27a39763 2338
4ffa1463 2339 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
6ee2611c
AD
2340 if (!empty($eventdata->fullmessage)) {
2341 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
2342 }
6ee2611c
AD
2343 if (!empty($eventdata->fullmessagehtml)) {
2344 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
2345 }
31da70cc 2346
a1b53dcf 2347 $eventdata->timecreated = time();
5e12b369 2348 $eventdata->notification = 0;
7c7d3afa 2349 return message_send($eventdata);
405f01ee 2350}
e8e2d7f1 2351
f46b6587 2352/**
1d422980 2353 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 2354 * block links etc
ebe0c008 2355 *
bcab42da 2356 * @param object $contact contact object containing all fields required for $OUTPUT->user_picture()
2357 * @param bool $incontactlist is the user a contact of ours?
2358 * @param bool $isblocked is the user blocked?
2359 * @param string $selectcontacturl the url to send the user to when a contact's name is clicked
2360 * @param bool $showactionlinks display action links next to the other users (add contact, block user etc)
2361 * @param object $selecteduser the user the current user is viewing (if any). They will be highlighted.
ebe0c008 2362 * @return void
f46b6587 2363 */
a402c309 2364function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
8f0137e1 2365 global $OUTPUT, $USER, $COURSE;
f46b6587 2366 $fullname = fullname($contact);
2367 $fullnamelink = $fullname;
35fe9b8a 2368 $output = '';
f46b6587 2369
a402c309 2370 $linkclass = '';
bcab42da 2371 if (!empty($selecteduser) && $contact->id == $selecteduser->id) {
a402c309
AD
2372 $linkclass = 'messageselecteduser';
2373 }
2374
447df209 2375 // Are there any unread messages for this contact?
f46b6587 2376 if ($contact->messagecount > 0 ){
2377 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
2378 }
2379
c8621a02 2380 $strcontact = $strblock = $strhistory = null;
f46b6587 2381
c8621a02 2382 if ($showactionlinks) {
9a90e7c5
RT
2383 // Show block and delete links if user is real user.
2384 if (core_user::is_real_user($contact->id)) {
2385 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
2386 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
2387 }
c8621a02 2388 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
f46b6587 2389 }
2390
35fe9b8a
BB
2391 $output .= html_writer::start_tag('div', array('class' => 'pix'));
2392 $output .= $OUTPUT->user_picture($contact, array('size' => 20, 'courseid' => $COURSE->id));
2393 $output .= html_writer::end_tag('div');
1d422980 2394
40a26286 2395 $popupoptions = array(
c8621a02
AD
2396 'height' => MESSAGE_DISCUSSION_HEIGHT,
2397 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 2398 'menubar' => false,
2399 'location' => false,
2400 'status' => true,
2401 'scrollbars' => true,
2402 'resizable' => true);
2403
c8621a02
AD
2404 $link = $action = null;
2405 if (!empty($selectcontacturl)) {
25bd5c75 2406 $link = new moodle_url($selectcontacturl.'&user2='.$contact->id);
c8621a02 2407 } else {
06d30c43
AD
2408 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
2409 $link = new moodle_url("/message/index.php?id=$contact->id");
c8621a02
AD
2410 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
2411 }
bcab42da 2412
f46b6587 2413
35fe9b8a
BB
2414 if (strlen($strcontact . $strblock . $strhistory) > 0) {
2415 $output .= html_writer::tag('div', $strcontact . $strblock . $strhistory, array('class' => 'link'));
bcab42da 2416
35fe9b8a
BB
2417 $output .= html_writer::start_tag('div', array('class' => 'contact'));
2418 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2419 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2420 $output .= html_writer::end_tag('div');
2421 } else {
2422 $output .= html_writer::start_tag('div', array('class' => 'contact nolinks'));
2423 $linkattr = array('class' => $linkclass, 'title' => get_string('sendmessageto', 'message', $fullname));
2424 $output .= $OUTPUT->action_link($link, $fullnamelink, $action, $linkattr);
2425 $output .= html_writer::end_tag('div');
2426 }
2427
2428 return $output;
f46b6587 2429}
2430
bcab42da 2431/**
2432 * Constructs the add/remove contact link to display next to other users
ebe0c008 2433 *
bcab42da 2434 * @param bool $incontactlist is the user a contact
2435 * @param bool $isblocked is the user blocked
6fbd60ef 2436 * @param stdClass $contact contact object
bcab42da 2437 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2438 * @param bool $text include text next to the icons?
2439 * @param bool $icon include a graphical icon?
2440 * @return string
2441 */
c8621a02
AD
2442function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2443 $strcontact = '';
2444
2445 if($incontactlist){
2446 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
2447 } else if ($isblocked) {
2448 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2449 } else{
2450 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
2451 }
2452
2453 return $strcontact;
2454}
2455
bcab42da 2456/**
2457 * Constructs the block contact link to display next to other users
ebe0c008 2458 *
6fbd60ef
AD
2459 * @param bool $incontactlist is the user a contact?
2460 * @param bool $isblocked is the user blocked?
2461 * @param stdClass $contact contact object
bcab42da 2462 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
2463 * @param bool $text include text next to the icons?
2464 * @param bool $icon include a graphical icon?
2465 * @return string
2466 */
c8621a02
AD
2467function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
2468 $strblock = '';
2469
2470 //commented out to allow the user to block a contact without having to remove them first
2471 /*if ($incontactlist) {
2472 //$strblock = '';
2473 } else*/
2474 if ($isblocked) {
35fe9b8a 2475 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
c8621a02 2476 } else{
35fe9b8a 2477 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
c8621a02
AD
2478 }
2479
2480 return $strblock;
2481}
2482
ebe0c008
RK
2483/**
2484 * Moves messages from a particular user from the message table (unread messages) to message_read
2485 * This is typically only used when a user is deleted
2486 *
2487 * @param object $userid User id
2488 * @return boolean success
2489 */
6bdf4c99 2490function message_move_userfrom_unread2read($userid) {
6bdf4c99 2491 global $DB;
2492
71666cf3 2493 // move all unread messages from message table to message_read
6bdf4c99 2494 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
2495 foreach ($messages as $message) {
ee7cd81a 2496 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
6bdf4c99 2497 }
2498 }
2499 return true;
2500}
2501
ee7cd81a 2502/**
ebe0c008
RK
2503 * marks ALL messages being sent from $fromuserid to $touserid as read
2504 *
2505 * @param int $touserid the id of the message recipient
2506 * @param int $fromuserid the id of the message sender
2507 * @return void
2508 */
727c69ca 2509function message_mark_messages_read($touserid, $fromuserid) {
c8621a02
AD
2510 global $DB;
2511
ee7cd81a 2512 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
bcab42da 2513 $messages = $DB->get_recordset_sql($sql, array('useridto' => $touserid,'useridfrom' => $fromuserid));
1560760f 2514
c8621a02 2515 foreach ($messages as $message) {
ee7cd81a
AD
2516 message_mark_message_read($message, time());
2517 }
19c5532b
AD
2518
2519 $messages->close();
ee7cd81a
AD
2520}
2521
2522/**
ebe0c008
RK
2523 * Mark a single message as read
2524 *
6fbd60ef 2525 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
ebe0c008
RK
2526 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
2527 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
2528 * @return int the ID of the message in the message_read table
2529 */
ee7cd81a
AD
2530function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
2531 global $DB;
31da70cc 2532
ee7cd81a 2533 $message->timeread = $timeread;
c8621a02 2534
ee7cd81a
AD
2535 $messageid = $message->id;
2536 unset($message->id);//unset because it will get a new id on insert into message_read
1560760f 2537
ee7cd81a
AD
2538 //If any processors have pending actions abort them
2539 if (!$messageworkingempty) {
2540 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
c8621a02 2541 }
3a00a167 2542 $messagereadid = $DB->insert_record('message_read', $message);
5b091909 2543
ee7cd81a 2544 $DB->delete_records('message', array('id' => $messageid));
5b091909 2545
cbfd685a
MN
2546 // Get the context for the user who received the message.
2547 $context = context_user::instance($message->useridto, IGNORE_MISSING);
2548 // If the user no longer exists the context value will be false, in this case use the system context.
2549 if ($context === false) {
2550 $context = context_system::instance();
2551 }
2552
5b091909 2553 // Trigger event for reading a message.
f3d98189 2554 $event = \core\event\message_viewed::create(array(
5b091909
MN
2555 'objectid' => $messagereadid,
2556 'userid' => $message->useridto, // Using the user who read the message as they are the ones performing the action.
cbfd685a 2557 'context' => $context,
5b091909
MN
2558 'relateduserid' => $message->useridfrom,
2559 'other' => array(
2560 'messageid' => $messageid
2561 )
2562 ));
2563 $event->trigger();
2564
3a00a167 2565 return $messagereadid;
65fbace7 2566}
bcab42da 2567
75c34c23 2568/**
814e3735
RK
2569 * Get all message processors, validate corresponding plugin existance and
2570 * system configuration
ebe0c008 2571 *
814e3735 2572 * @param bool $ready only return ready-to-use processors
ed23ad31 2573 * @param bool $reset Reset list of message processors (used in unit tests)
e61a9638 2574 * @param bool $resetonly Just reset, then exit
814e3735 2575 * @return mixed $processors array of objects containing information on message processors
75c34c23 2576 */
e61a9638 2577function get_message_processors($ready = false, $reset = false, $resetonly = false) {
75c34c23
RK
2578 global $DB, $CFG;
2579
1d72e9d4 2580 static $processors;
ed23ad31
YB
2581 if ($reset) {
2582 $processors = array();
e61a9638
MN
2583
2584 if ($resetonly) {
2585 return $processors;
2586 }
ed23ad31 2587 }
1d72e9d4
RK
2588
2589 if (empty($processors)) {
814e3735
RK
2590 // Get all processors, ensure the name column is the first so it will be the array key
2591 $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
1d72e9d4
RK
2592 foreach ($processors as &$processor){
2593 $processorfile = $CFG->dirroot. '/message/output/'.$processor->name.'/message_output_'.$processor->name.'.php';
2594 if (is_readable($processorfile)) {
2595 include_once($processorfile);
2596 $processclass = 'message_output_' . $processor->name;
2597 if (class_exists($processclass)) {
2598 $pclass = new $processclass();
814e3735 2599 $processor->object = $pclass;
1d72e9d4
RK
2600 $processor->configured = 0;
2601 if ($pclass->is_system_configured()) {
2602 $processor->configured = 1;
2603 }
2604 $processor->hassettings = 0;
2605 if (is_readable($CFG->dirroot.'/message/output/'.$processor->name.'/settings.php')) {
2606 $processor->hassettings = 1;
2607 }
2608 $processor->available = 1;
2609 } else {
2610 print_error('errorcallingprocessor', 'message');
75c34c23 2611 }
75c34c23 2612 } else {
1d72e9d4 2613 $processor->available = 0;
75c34c23 2614 }
75c34c23
RK
2615 }
2616 }
814e3735 2617 if ($ready) {
72e6af03
RK
2618 // Filter out enabled and system_configured processors
2619 $readyprocessors = $processors;
2620 foreach ($readyprocessors as $readyprocessor) {
2621 if (!($readyprocessor->enabled && $readyprocessor->configured)) {
2622 unset($readyprocessors[$readyprocessor->name]);
2623 }
2624 }
2625 return $readyprocessors;
1d72e9d4
RK
2626 }
2627
75c34c23
RK
2628 return $processors;
2629}
814e3735 2630
7fcd3c30
RK
2631/**
2632 * Get all message providers, validate their plugin existance and
2633 * system configuration
2634 *
2635 * @return mixed $processors array of objects containing information on message processors
2636 */
2637function get_message_providers() {
2638 global $CFG, $DB;
e87214bd
PS
2639
2640 $pluginman = core_plugin_manager::instance();
7fcd3c30
RK
2641
2642 $providers = $DB->get_records('message_providers', null, 'name');
2643
2644 // Remove all the providers whose plugins are disabled or don't exist
2645 foreach ($providers as $providerid => $provider) {
2646 $plugin = $pluginman->get_plugin_info($provider->component);
2647 if ($plugin) {
e87214bd 2648 if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7fcd3c30
RK
2649 unset($providers[$providerid]); // Plugins does not exist
2650 continue;
2651 }
2652 if ($plugin->is_enabled() === false) {
2653 unset($providers[$providerid]); // Plugin disabled
2654 continue;
2655 }
2656 }
2657 }
2658 return $providers;
2659}
2660
7529f9e9
TH
2661/**
2662 * Get an instance of the message_output class for one of the output plugins.
2663 * @param string $type the message output type. E.g. 'email' or 'jabber'.
2664 * @return message_output message_output the requested class.
2665 */
2666function get_message_processor($type) {
2667 global $CFG;
2668
2669 // Note, we cannot use the get_message_processors function here, becaues this
2670 // code is called during install after installing each messaging plugin, and
2671 // get_message_processors caches the list of installed plugins.
2672
2673 $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
2674 if (!is_readable($processorfile)) {
2675 throw new coding_exception('Unknown message processor type ' . $type);
2676 }
2677
2678 include_once($processorfile);
2679
2680 $processclass = 'message_output_' . $type;
2681 if (!class_exists($processclass)) {
2682 throw new coding_exception('Message processor ' . $type .
2683 ' does not define the right class');
2684 }
2685
2686 return new $processclass();
2687}
2688
814e3735
RK
2689/**
2690 * Get messaging outputs default (site) preferences
ebe0c008 2691 *
814e3735
RK
2692 * @return object $processors object containing information on message processors
2693 */
2694function get_message_output_default_preferences() {
820a8188 2695 return get_config('message');
814e3735 2696}
7a04c476
RK
2697
2698/**
2699 * Translate message default settings from binary value to the array of string
2700 * representing the settings to be stored. Also validate the provided value and
2701 * use default if it is malformed.
ebe0c008 2702 *
7a04c476
RK
2703 * @param int $plugindefault Default setting suggested by plugin
2704 * @param string $processorname The name of processor
2705 * @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
2706 */
2707function translate_message_default_setting($plugindefault, $processorname) {
2708 // Preset translation arrays
2709 $permittedvalues = array(
2710 0x04 => 'disallowed',
2711 0x08 => 'permitted',
2712 0x0c => 'forced',
2713 );
2714
2715 $loggedinstatusvalues = array(
2716 0x00 => null, // use null if loggedin/loggedoff is not defined
2717 0x01 => 'loggedin',
2718 0x02 => 'loggedoff',
2719 );
2720
2721 // define the default setting
7529f9e9
TH
2722 $processor = get_message_processor($processorname);
2723 $default = $processor->get_default_messaging_settings();
7a04c476
RK
2724
2725 // Validate the value. It should not exceed the maximum size
2726 if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
681570b4 2727 debugging(get_string('errortranslatingdefault', 'message'));
7a04c476
RK
2728 $plugindefault = $default;
2729 }
2730 // Use plugin default setting of 'permitted' is 0
2731 if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
2732 $plugindefault = $default;
2733 }
2734
2735 $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
83807514 2736 $loggedin = $loggedoff = null;
7a04c476
RK
2737
2738 if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
83807514
RK
2739 $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
2740 $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
7a04c476
RK
2741 }
2742
2743 return array($permitted, $loggedin, $loggedoff);
2744}
46d3b9be 2745
35d72562
AD
2746/**
2747 * Return a list of page types
2748 * @param string $pagetype current page type
2749 * @param stdClass $parentcontext Block's parent context
2750 * @param stdClass $currentcontext Current context of block
2751 */
b38e2e28 2752function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
35d72562
AD
2753 return array('messages-*'=>get_string('page-message-x', 'message'));
2754}
babc03f4 2755
193edf7f 2756/**
127ef540 2757 * Get messages sent or/and received by the specified users.
193edf7f
JL
2758 *
2759 * @param int $useridto the user id who received the message
127ef540 2760 * @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
193edf7f 2761 * @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
127ef540 2762 * @param bool $read true for retrieving read messages, false for unread
193edf7f
JL
2763 * @param string $sort the column name to order by including optionally direction
2764 * @param int $limitfrom limit from
2765 * @param int $limitnum limit num
2766 * @return external_description
2767 * @since 2.8
2768 */
2769function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
2770 $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
2771 global $DB;
2772
2773 $messagetable = $read ? '{message_read}' : '{message}';
193edf7f
JL
2774 $params = array('deleted' => 0);
2775
2776 // Empty useridto means that we are going to retrieve messages send by the useridfrom to any user.
2777 if (empty($useridto)) {
2778 $userfields = get_all_user_name_fields(true, 'u', '', 'userto');
2779 $joinsql = "JOIN {user} u ON u.id = mr.useridto";
2780 $usersql = "mr.useridfrom = :useridfrom AND u.deleted = :deleted";
2781 $params['useridfrom'] = $useridfrom;
2782 } else {
2783 $userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
2784 // Left join because useridfrom may be -10 or -20 (no-reply and support users).
2785 $joinsql = "LEFT JOIN {user} u ON u.id = mr.useridfrom";
2786 $usersql = "mr.useridto = :useridto AND (u.deleted IS NULL OR u.deleted = :deleted)";
2787 $params['useridto'] = $useridto;
2788 if (!empty($useridfrom)) {
2789 $usersql .= " AND mr.useridfrom = :useridfrom";
2790 $params['useridfrom'] = $useridfrom;
2791 }
2792 }
2793
2794 // Now, if retrieve notifications, conversations or both.
2795 $typesql = "";
2796 if ($notifications !== -1) {
2797 $typesql = "AND mr.notification = :notification";
2798 $params['notification'] = ($notifications) ? 1 : 0;
2799 }
2800
2801 $sql = "SELECT mr.*, $userfields
2802 FROM $messagetable mr
127ef540
SH
2803 $joinsql
2804 WHERE $usersql
2805 $typesql
193edf7f
JL
2806 ORDER BY $sort";
2807
2808 $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2809 return $messages;
2810}
cf4a17cb
FM
2811
2812/**
2813 * Requires the JS libraries to send a message using a dialog.
2814 *
2815 * @return void
2816 */
2817function message_messenger_requirejs() {
2818 global $PAGE;
2819
2820 static $done = false;
2821 if ($done) {
2822 return;
2823 }
2824
2825 $PAGE->requires->yui_module(
2826 array('moodle-core_message-messenger'),
2827 'Y.M.core_message.messenger.init',
2828 array(array())
2829 );
2830 $PAGE->requires->strings_for_js(array(
2831 'errorwhilesendingmessage',
2832 'messagesent',
2833 'messagetosend',
2834 'sendingmessage',
2835 'sendmessage',
2836 'viewconversation',
2837 ), 'core_message');
cd0c9ac8
RW
2838 $PAGE->requires->strings_for_js(array(
2839 'userisblockingyou',
2840 'userisblockingyounoncontact'
2841 ), 'message');
cf4a17cb
FM
2842 $PAGE->requires->string_for_js('error', 'core');
2843
2844 $done = true;
2845}
2846
2847/**
2848 * Returns the attributes to place on a link to open the 'Send message' dialog.
2849 *
2850 * @param object $user User object.
2851 * @return void
2852 */
2853function message_messenger_sendmessage_link_params($user) {
cd0c9ac8 2854 $params = array(
cf4a17cb
FM
2855 'data-trigger' => 'core_message-messenger::sendmessage',
2856 'data-fullname' => fullname($user),
2857 'data-userid' => $user->id,
2858 'role' => 'button'
2859 );
cd0c9ac8
RW
2860
2861 if (message_is_user_non_contact_blocked($user)) {
2862 $params['data-blocked-string'] = 'userisblockingyounoncontact';
2863 } else if (message_is_user_blocked($user)) {
2864 $params['data-blocked-string'] = 'userisblockingyou';
2865 }
2866
2867 return $params;
2868}
2869
2870/**
2871 * Determines if a user is permitted to send another user a private message.
2872 * If no sender is provided then it defaults to the logged in user.
2873 *
2874 * @param object $recipient User object.
2875 * @param object $sender User object.
2876 * @return bool true if user is permitted, false otherwise.
2877 */
2878function message_can_post_message($recipient, $sender = null) {
2879 global $USER, $DB;
2880
2881 if (is_null($sender)) {
2882 // The message is from the logged in user, unless otherwise specified.
2883 $sender = $USER;
2884 }
2885
2886 if (!has_capability('moodle/site:sendmessage', context_system::instance(), $sender)) {
2887 return false;
2888 }
2889
2890 // The recipient blocks messages from non-contacts and the
2891 // sender isn't a contact.
2892 if (message_is_user_non_contact_blocked($recipient, $sender)) {
2893 return false;
2894 }
2895
2896 // The recipient has specifically blocked this sender.
2897 if (message_is_user_blocked($recipient, $sender)) {
2898 return false;
2899 }
2900
2901 return true;
2902}
2903
2904/**
2905 * Checks if the recipient is allowing messages from users that aren't a
2906 * contact. If not then it checks to make sure the sender is in the
2907 * recipient's contacts.
2908 *
2909 * @param object $recipient User object.
2910 * @param object $sender User object.
2911 * @return bool true if $sender is blocked, false otherwise.
2912 */
2913function message_is_user_non_contact_blocked($recipient, $sender = null) {
2914 global $USER, $DB;
2915
2916 if (is_null($sender)) {
2917 // The message is from the logged in user, unless otherwise specified.
2918 $sender = $USER;
2919 }
2920
2921 $blockednoncontacts = get_user_preferences('message_blocknoncontacts', '', $recipient->id);
2922 if (!empty($blockednoncontacts)) {
2923 // Confirm the sender is a contact of the recipient.
2924 $exists = $DB->record_exists('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id));
2925 if ($exists) {
2926 // All good, the recipient is a contact of the sender.
2927 return false;
2928 } else {
2929 // Oh no, the recipient is not a contact. Looks like we can't send the message.
2930 return true;
2931 }
2932 }
2933
2934 return false;
2935}
2936
2937/**
2938 * Checks if the recipient has specifically blocked the sending user.
2939 *
2940 * Note: This function will always return false if the sender has the
2941 * readallmessages capability at the system context level.
2942 *
2943 * @param object $recipient User object.
2944 * @param object $sender User object.
2945 * @return bool true if $sender is blocked, false otherwise.
2946 */
2947function message_is_user_blocked($recipient, $sender = null) {
2948 global $USER, $DB;
2949
2950 if (is_null($sender)) {
2951 // The message is from the logged in user, unless otherwise specified.
2952 $sender = $USER;
2953 }
2954
2955 $systemcontext = context_system::instance();
2956 if (has_capability('moodle/site:readallmessages', $systemcontext, $sender)) {
2957 return false;
2958 }
2959
2960 if ($contact = $DB->get_record('message_contacts', array('userid' => $recipient->id, 'contactid' => $sender->id))) {
2961 if ($contact->blocked) {
2962 return true;
2963 }
2964 }
2965
2966 return false;
cf4a17cb 2967}