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