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