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