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