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