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