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