message MDL-24771 another big commit of messaging fixes
[moodle.git] / message / lib.php
CommitLineData
eb5334ff 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library functions for messaging
20 *
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package message
24 */
172186b8 25
3b120e46 26require_once($CFG->libdir.'/eventslib.php');
27
e8e2d7f1 28
29define ('MESSAGE_SHORTLENGTH', 300);
fd7006f6 30define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
31
c8621a02
AD
32define ('MESSAGE_DISCUSSION_WIDTH',600);
33define ('MESSAGE_DISCUSSION_HEIGHT',500);
34
35define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
36
37define ('CONTACT_ID','id');
38
39define('MESSAGE_HISTORY_SHORT',0);
40define('MESSAGE_HISTORY_ALL',1);
41
42//some constants used as function arguments. Just to make function calls a bit more understandable
43define('IS_CONTACT',true);
44define('IS_NOT_CONTACT',false);
45
46define('IS_BLOCKED',true);
47define('IS_NOT_BLOCKED',false);
48
49define('VIEW_UNREAD_MESSAGES','unread');
50define('VIEW_CONTACTS','contacts');
51define('VIEW_BLOCKED','blockedusers');
52define('VIEW_COURSE','course_');
53
cf455865 54define('SHOW_ACTION_LINKS_IN_CONTACT_LIST', true);
c8621a02 55
c3931654
AD
56define('MESSAGE_SEARCH_MAX_RESULTS', 200);
57
32ef43e1
AD
58define('MESSAGE_CONTACTS_PER_PAGE',10);
59
05753d2b 60if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
2a38a6be 61 $CFG->message_contacts_refresh = 60;
fd7006f6 62}
5d6b319b 63if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
64 $CFG->message_chat_refresh = 5;
fd7006f6 65}
f520438c 66if (!isset($CFG->message_offline_time)) {
67 $CFG->message_offline_time = 300;
68}
172186b8 69
32ef43e1 70function message_print_contact_selector($countunreadtotal, $usergroup, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page=0) {
c8621a02 71 global $PAGE;
3a11c09f 72
c8621a02
AD
73 echo html_writer::start_tag('div', array('class'=>'contactselector mdl-align'));
74
75 //if 0 unread messages and they've requested unread messages then show contacts
76 if ($countunreadtotal==0 && $usergroup==VIEW_UNREAD_MESSAGES) {
77 $usergroup = VIEW_CONTACTS;
78 }
79
65c7853e
AD
80 //if they have no blocked users and they've requested blocked users switch them over to contacts
81 if (count($blockedusers)==0 && $usergroup==VIEW_BLOCKED) {
82 $usergroup = VIEW_CONTACTS;
83 }
84
c8621a02
AD
85 $onlyactivecourses = true;
86 $courses = enrol_get_users_courses($user1->id, $onlyactivecourses);
87 $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them
88
43240ea1
AD
89 $strunreadmessages = null;
90 if ($countunreadtotal>0) { //if there are unread messages
91 $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal);
92 }
93
94 message_print_usergroup_selector($usergroup, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages);
c8621a02
AD
95
96 $refreshpage = false;
97
98 if ($usergroup==VIEW_UNREAD_MESSAGES) {
99 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 1, $showcontactactionlinks,$strunreadmessages, $user2);
100 } else if ($usergroup==VIEW_CONTACTS) {
b32778c4 101 message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2);
c8621a02
AD
102 } else if ($usergroup==VIEW_BLOCKED) {
103 message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2);
104 } else if (substr($usergroup, 0, 7)==VIEW_COURSE) {
105 $courseidtoshow = intval(substr($usergroup, 7));
106
107 if (!empty($courseidtoshow)
108 && array_key_exists($courseidtoshow, $coursecontexts)
109 && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
110
32ef43e1 111 message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page);
c8621a02 112 } else {
71666cf3 113 //shouldn't get here. User trying to access a course they're not in perhaps.
02f2c7bd 114 add_to_log(SITEID, 'message', 'view', 'index.php', $usergroup);
c8621a02
AD
115 }
116 }
117
118 echo html_writer::start_tag('form', array('action'=>'contacts.php?advanced=1'));
119 echo html_writer::start_tag('fieldset');
120 $managebuttonclass = 'hiddenelement';
121 if ($usergroup == VIEW_CONTACTS) {
122 $managebuttonclass = 'visible';
123 }
1e77f974 124 $strmanagecontacts = get_string('search','message');
c8621a02
AD
125 echo html_writer::empty_tag('input', array('type'=>'submit','value'=>$strmanagecontacts,'class'=>$managebuttonclass));
126 echo html_writer::end_tag('fieldset');
127 echo html_writer::end_tag('form');
128 echo html_writer::end_tag('div');
129}
130
32ef43e1
AD
131function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null, $page=0) {
132 global $DB, $USER, $PAGE, $OUTPUT;
c8621a02 133
32ef43e1
AD
134 $countparticipants = count_enrolled_users($context);
135 $participants = get_enrolled_users($context, '', 0, 'u.*', '', $page*MESSAGE_CONTACTS_PER_PAGE, MESSAGE_CONTACTS_PER_PAGE);
136
137 $pagingbar = new paging_bar($countparticipants, $page, MESSAGE_CONTACTS_PER_PAGE, $PAGE->url, 'page');
138 echo $OUTPUT->render($pagingbar);
3a11c09f 139
c8621a02
AD
140 echo '<table id="message_participants" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
141
142 if (!empty($titletodisplay)) {
143 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
144 }
145
146 if (empty($titletodisplay)) {
147 echo '<tr><td colspan="3" class="heading">';
148 echo get_string('participants');
149 echo '</td></tr>';
150 }
151
152 //todo these need to come from somewhere if the course participants list is to show users with unread messages
153 $iscontact = true;
154 $isblocked = false;
155 foreach ($participants as $participant) {
156 if ($participant->id != $USER->id) {
157 $participant->messagecount = 0;//todo it would be nice if the course participant could report new messages
158 message_print_contactlist_user($participant, $iscontact, $isblocked, $contactselecturl, $showactionlinks);
159 }
160 }
161 //$participants->close();
162
163 echo '</table>';
164}
165
166function message_get_blocked_users($user1=null, &$user2=null) {
167 global $DB, $USER;
168
169 if (empty($user1)) {
170 $user1 = $USER;
171 }
172
173 if (!empty($user2)) {
174 $user2->isblocked = false;
175 }
176
3a11c09f
PS
177 $userfields = user_picture::fields('u', array('lastaccess'));
178 $blockeduserssql = "SELECT $userfields, COUNT(m.id) AS messagecount
179 FROM {message_contacts} mc
180 JOIN {user} u ON u.id = mc.contactid
181 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = :user1id1
182 WHERE mc.userid = :user1id2 AND mc.blocked = 1
183 GROUP BY $userfields
184 ORDER BY u.firstname ASC";
c8621a02
AD
185 $rs = $DB->get_recordset_sql($blockeduserssql, array('user1id1'=>$user1->id, 'user1id2'=>$user1->id));
186
187 $blockedusers = array();
188 if (!empty($rs)) {
189 foreach($rs as $rd) {
190 $blockedusers[] = $rd;
191
192 if (!empty($user2) && $user2->id==$rd->id) {
193 $user2->isblocked = true;
194 }
195 }
196 unset($rd);
197 $rs->close();
198 }
199
200 return $blockedusers;
201}
202
203function message_print_blocked_users(&$blockedusers, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null) {
204 global $DB, $USER;
205
206 $countblocked = count($blockedusers);
207
208 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
209
210 if (!empty($titletodisplay)) {
211 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
212 }
213
214 if ($countblocked) {
215 echo '<tr><td colspan="3" class="heading">';
216 echo get_string('blockedusers', 'message', $countblocked);
217 echo '</td></tr>';
218
219 foreach ($blockedusers as $blockeduser) {
220 message_print_contactlist_user($blockeduser, IS_NOT_CONTACT, IS_BLOCKED, $contactselecturl, $showactionlinks);
221 }
222 }
223
224 echo '</table>';
225}
226
227function message_get_contacts($user1=null, &$user2=null) {
228 global $DB, $CFG, $USER;
172186b8 229
c8621a02
AD
230 if (empty($user1)) {
231 $user1 = $USER;
232 }
233
234 if (!empty($user2)) {
235 $user2->iscontact = false;
236 }
e8e2d7f1 237
238 $timetoshowusers = 300; //Seconds default
239 if (isset($CFG->block_online_users_timetosee)) {
240 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
241 }
e8e2d7f1 242
f46b6587 243 // time which a user is counting as being active since
244 $timefrom = time()-$timetoshowusers;
531e58f1 245
f46b6587 246 // people in our contactlist who are online
247 $onlinecontacts = array();
248 // people in our contactlist who are offline
249 $offlinecontacts = array();
250 // people who are not in our contactlist but have sent us a message
627bb9ec
AD
251 $strangers = array();
252
3a11c09f 253 $userfields = user_picture::fields('u', array('lastaccess'));
f46b6587 254
1d422980 255 // get all in our contactlist who are not blocked in our contact list
f46b6587 256 // and count messages we have waiting from each of them
3a11c09f 257 $contactsql = "SELECT $userfields, COUNT(m.id) AS messagecount
fd1cb1e8 258 FROM {message_contacts} mc
259 JOIN {user} u ON u.id = mc.contactid
260 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
1d422980 261 WHERE mc.userid = ? AND mc.blocked = 0
3a11c09f 262 GROUP BY $userfields
bbe973da 263 ORDER BY u.firstname ASC";
fd1cb1e8 264
c8621a02 265 if ($rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id))){
fd1cb1e8 266 foreach($rs as $rd){
f46b6587 267
268 if($rd->lastaccess >= $timefrom){
269 // they have been active recently, so are counted online
270 $onlinecontacts[] = $rd;
c8621a02 271
f46b6587 272 }else{
273 $offlinecontacts[] = $rd;
e8e2d7f1 274 }
c8621a02
AD
275
276 if (!empty($user2) && $user2->id==$rd->id) {
277 $user2->iscontact = true;
278 }
e8e2d7f1 279 }
f46b6587 280 unset($rd);
fd1cb1e8 281 $rs->close();
f46b6587 282 }
283
f46b6587 284 // get messages from anyone who isn't in our contact list and count the number
285 // of messages we have from each of them
3a11c09f 286 $strangersql = "SELECT $userfields, count(m.id) as messagecount
fd1cb1e8 287 FROM {message} m
288 JOIN {user} u ON u.id = m.useridfrom
289 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
1d422980 290 WHERE mc.id IS NULL AND m.useridto = ?
3a11c09f 291 GROUP BY $userfields
bbe973da 292 ORDER BY u.firstname ASC";
fd1cb1e8 293
294 if($rs = $DB->get_recordset_sql($strangersql, array($USER->id))){
295 foreach($rs as $rd){
f46b6587 296 $strangers[] = $rd;
297 }
298 unset($rd);
fd1cb1e8 299 $rs->close();
e8e2d7f1 300 }
301
c8621a02
AD
302 return array($onlinecontacts, $offlinecontacts, $strangers);
303}
304
305function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refresh=true, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null) {
306 global $CFG, $PAGE, $OUTPUT;
307
f46b6587 308 $countonlinecontacts = count($onlinecontacts);
309 $countofflinecontacts = count($offlinecontacts);
310 $countstrangers = count($strangers);
311
a1157dda 312 if ($countonlinecontacts + $countofflinecontacts == 0) {
669be60c 313 echo '<div class="heading">';
65ef518b 314 print_string('contactlistempty', 'message');
a1157dda 315 echo '</div>';
65c7853e
AD
316 //echo '<div class="note">';
317 //print_string('addsomecontacts', 'message', message_remove_url_params($PAGE->url).'?tab=search');
318 //echo '</div>';
65ef518b 319 }
320
04b687e8 321 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
531e58f1 322
c8621a02
AD
323 if (!empty($titletodisplay)) {
324 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
325 }
326
f46b6587 327 if($countonlinecontacts) {
328 /// print out list of online contacts
531e58f1 329
c8621a02
AD
330 if (empty($titletodisplay)) {
331 echo '<tr><td colspan="3" class="heading">';
332 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
333 echo '</td></tr>';
334 }
531e58f1 335
f46b6587 336 foreach ($onlinecontacts as $contact) {
c8621a02
AD
337 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
338 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
339 }
65ef518b 340 }
f46b6587 341 }
531e58f1 342
f46b6587 343 if ($countofflinecontacts) {
344 /// print out list of offline contacts
531e58f1 345
c8621a02
AD
346 if (empty($titletodisplay)) {
347 echo '<tr><td colspan="3" class="heading">';
348 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
349 echo '</td></tr>';
350 }
576ad290 351
f46b6587 352 foreach ($offlinecontacts as $contact) {
c8621a02
AD
353 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
354 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
355 }
65ef518b 356 }
f46b6587 357 echo '<tr><td colspan="3">&nbsp;</td></tr>';
358 }
65ef518b 359
f46b6587 360 /// print out list of incoming contacts
361 if ($countstrangers) {
362 echo '<tr><td colspan="3" class="heading">';
363 echo get_string('incomingcontacts', 'message', $countstrangers);
364 echo '</td></tr>';
531e58f1 365
f46b6587 366 foreach ($strangers as $stranger) {
65fbace7 367 if ($minmessages==0 || $stranger->messagecount>=$minmessages) {
c8621a02
AD
368 message_print_contactlist_user($stranger, IS_NOT_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks);
369 }
669be60c 370 }
f46b6587 371 }
531e58f1 372
f46b6587 373 echo '</table>';
65ef518b 374
f46b6587 375 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
376 echo '<div class="note">(';
377 print_string('addsomecontactsincoming', 'message');
378 echo ')</div>';
65ef518b 379 }
b9ee0638 380
531e58f1 381 echo '<br />';
a9d9b46a 382
c8621a02
AD
383 if ($refresh) {
384 $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
a1b53dcf 385
c8621a02
AD
386 echo $OUTPUT->container_start('messagejsautorefresh note center');
387 echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
388 echo $OUTPUT->container_end();
a1b53dcf 389
4652f2d4
AD
390 echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
391 echo $OUTPUT->single_button(message_remove_url_params($PAGE->url), get_string('refresh'));
392 echo $OUTPUT->container_end();
393 }
e8e2d7f1 394}
395
43240ea1
AD
396function message_print_usergroup_selector($usergroup, &$courses, &$coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
397 $strblockedusers = null;
65c7853e 398 $options = array();
c8621a02
AD
399
400 if ($countunreadtotal>0) { //if there are unread messages
65c7853e 401 $options[VIEW_UNREAD_MESSAGES] = $strunreadmessages;
c8621a02
AD
402 }
403
404 if ($countblocked>0) {
405 $strblockedusers = get_string('blockedusers','message', $countblocked);
65c7853e 406 $options[VIEW_BLOCKED] = $strblockedusers;
c8621a02
AD
407 }
408
409 $strcontacts = get_string('mycontacts', 'message');
410 $options[VIEW_CONTACTS] = $strcontacts;
411
412 if (!empty($courses)) {
413 $courses_options = array();
414
415 foreach($courses as $course) {
416 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
248403fa 417 $courses_options[VIEW_COURSE.$course->id] = $course->shortname;
c8621a02
AD
418 }
419 }
420
421 if (!empty($courses_options)) {
422 $options[] = array(get_string('courses')=>$courses_options);
423 }
424 }
425
426 echo html_writer::start_tag('form', array('id'=>'usergroupform','method'=>'get','action'=>''));
229f4e92
AD
427 echo html_writer::start_tag('fieldset');
428 echo html_writer::select($options, 'usergroup', $usergroup, false, array('id'=>'usergroup','onchange'=>'this.form.submit()'));
429 echo html_writer::end_tag('fieldset');
c8621a02
AD
430 echo html_writer::end_tag('form');
431}
432
433function message_get_course_contexts(&$courses) {
434 $coursecontexts = array();
435
436 foreach($courses as $course) {
437 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
438 }
439
440 return $coursecontexts;
441}
442
cee92282
AD
443/**
444 * strip off action parameters like 'removecontact'
445 */
c8621a02 446function message_remove_url_params($moodleurl) {
c8621a02
AD
447 $newurl = new moodle_url($moodleurl);
448 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
449 return $newurl->out();
450}
451
e8e2d7f1 452
e8e2d7f1 453/// $messagearray is an array of objects
454/// $field is a valid property of object
455/// $value is the value $field should equal to be counted
456/// if $field is empty then return count of the whole array
457/// if $field is non-existent then return 0;
458function message_count_messages($messagearray, $field='', $value='') {
459 if (!is_array($messagearray)) return 0;
460 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 461
e8e2d7f1 462 $count = 0;
463 foreach ($messagearray as $message) {
464 $count += ($message->$field == $value) ? 1 : 0;
465 }
466 return $count;
172186b8 467}
468
c8621a02
AD
469/**
470 * Returns the count of unread messages for user. Either from a specific user or from all users.
471 * @global <type> $USER
472 * @global <type> $DB
473 * @param object $user1 the first user. Defaults to $USER
474 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
475 * @return int the count of $user1's unread messages
476 */
477function message_count_unread_messages($user1=null, $user2=null) {
478 global $USER, $DB;
e8e2d7f1 479
c8621a02
AD
480 if (empty($user1)) {
481 $user1 = $USER;
482 }
483
484 if (!empty($user2)) {
485 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
486 array($user1->id, $user2->id), "COUNT('id')");
487 } else {
488 return $DB->count_records_select('message', "useridto = ?",
489 array($user1->id), "COUNT('id')");
490 }
491}
492
493function message_count_blocked_users($user1=null) {
494 global $USER, $DB;
495
496 if (empty($user1)) {
497 $user1 = $USER;
498 }
499
500 $sql = "SELECT count(mc.id)
501 FROM {message_contacts} mc
502 WHERE mc.userid = :userid AND mc.blocked = 1";
503 $params = array('userid'=>$user1->id);
504
505 return $DB->count_records_sql($sql, $params);
506}
507
508/**
509 *
510 * @global <type> $USER
511 * @global <type> $PAGE
512 * @global <type> $OUTPUT
513 * @param boolean advancedsearch show basic or advanced search form
514 * @return boolean was a search performed?
515 */
516function message_print_search($advancedsearch = false, $user1=null) {
517 global $USER, $PAGE, $OUTPUT;
518
519 $frm = data_submitted();
3a11c09f 520
c8621a02
AD
521 $doingsearch = false;
522 if ($frm) {
523 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
524 }
531e58f1 525
c8621a02
AD
526 if (!empty($frm->combinedsearch)) {
527 $combinedsearchstring = $frm->combinedsearch;
528 } else {
a813a748
AD
529 //$combinedsearchstring = get_string('searchcombined','message').'...';
530 $combinedsearchstring = '';
c8621a02 531 }
531e58f1 532
a813a748 533 //$PAGE->requires->js_init_call('M.core_message.init_search_page', array($combinedsearchstring));
531e58f1 534
c8621a02
AD
535 if ($doingsearch) {
536 if ($advancedsearch) {
3a11c09f 537
c8621a02
AD
538 $messagesearch = '';
539 if (!empty($frm->keywords)) {
540 $messagesearch = $frm->keywords;
541 }
542 $personsearch = '';
543 if (!empty($frm->name)) {
544 $personsearch = $frm->name;
545 }
546 include('search_advanced.html');
547 } else {
548 include('search.html');
549 }
550
551 $showicontext = false;
552 message_print_search_results($frm, $showicontext, $user1);
553
554 return true;
172186b8 555 } else {
1ac41751 556/*
531e58f1 557/// unfinished buggy code disabled in search.html anyway
d76a5a7f 558 // find all courses this use has readallmessages capabilities in
559 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
172186b8 560 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
561 $cs = '<select name="courseselect">';
562 foreach ($teachers as $tcourse) {
d76a5a7f 563 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
172186b8 564 }
565 $cs .= '</select>';
566 }
1ac41751 567*/
c8621a02
AD
568
569 if ($advancedsearch) {
570 $personsearch = $messagesearch = '';
571 include('search_advanced.html');
572 } else {
573 include('search.html');
574 }
575 return false;
172186b8 576 }
577}
578
579function message_print_settings() {
3dcb80cb 580 global $USER, $OUTPUT, $PAGE;
531e58f1 581
d6b4fed0 582 if ($frm = data_submitted() and confirm_sesskey()) {
acef58f4 583
e8e2d7f1 584 $pref = array();
e8e2d7f1 585 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
3f85157b 586 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
e8e2d7f1 587
588 set_user_preferences($pref);
531e58f1 589
c8621a02 590 redirect(message_remove_url_params($PAGE->url), get_string('settingssaved', 'message'), 1);
e8e2d7f1 591 }
592
fd7006f6 593 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
3f85157b 594 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
531e58f1 595
e8e2d7f1 596 include('settings.html');
597}
598
599
600
601function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 602 global $USER, $DB;
531e58f1 603
fd1cb1e8 604 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
e8e2d7f1 605 return false;
606 }
531e58f1 607
fd1cb1e8 608 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
e8e2d7f1 609 /// record already exists - we may be changing blocking status
531e58f1 610
e8e2d7f1 611 if ($contact->blocked !== $blocked) {
612 /// change to blocking status
613 $contact->blocked = $blocked;
fd1cb1e8 614 return $DB->update_record('message_contacts', $contact);
e8e2d7f1 615 } else {
616 /// no changes to blocking status
617 return true;
618 }
531e58f1 619
172186b8 620 } else {
e8e2d7f1 621 /// new contact record
622 unset($contact);
623 $contact->userid = $USER->id;
624 $contact->contactid = $contactid;
625 $contact->blocked = $blocked;
fd1cb1e8 626 return $DB->insert_record('message_contacts', $contact, false);
172186b8 627 }
628}
629
e8e2d7f1 630function message_remove_contact($contactid) {
fd1cb1e8 631 global $USER, $DB;
632 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 633}
634
635function message_unblock_contact($contactid) {
fd1cb1e8 636 global $USER, $DB;
637 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 638}
639
640function message_block_contact($contactid) {
641 return message_add_contact($contactid, 1);
642}
643
644function message_get_contact($contactid) {
fd1cb1e8 645 global $USER, $DB;
646 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 647}
531e58f1 648
e8e2d7f1 649
650
c8621a02
AD
651function message_print_search_results($frm, $showicontext=false, $user1=null) {
652 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
653
654 if (empty($user1)) {
655 $user1 = $USER;
656 }
e8e2d7f1 657
c8621a02 658 echo '<div class="mdl-left">';
e8e2d7f1 659
c8621a02
AD
660 $personsearch = false;
661 $personsearchstring = null;
e8e2d7f1 662 if (!empty($frm->personsubmit) and !empty($frm->name)) {
c8621a02
AD
663 $personsearch = true;
664 $personsearchstring = $frm->name;
665 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
666 $personsearch = true;
667 $personsearchstring = $frm->combinedsearch;
668 }
531e58f1 669
c8621a02
AD
670 /// search for person
671 if ($personsearch) {
b71d4dd2 672 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 673 $users = array();
df997f84 674 $mycourses = enrol_get_my_courses();
e8e2d7f1 675 foreach ($mycourses as $mycourse) {
c8621a02 676 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
e8e2d7f1 677 foreach ($susers as $suser) $users[$suser->id] = $suser;
678 }
679 }
680 } else {
c8621a02 681 $users = message_search_users(SITEID, $personsearchstring);
e8e2d7f1 682 }
683
684 if (!empty($users)) {
c3931654
AD
685 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
686 echo get_string('userssearchresults', 'message', count($users));
687 echo html_writer::end_tag('p');
688
c8621a02 689 echo '<table class="messagesearchresults">';
e8e2d7f1 690 foreach ($users as $user) {
531e58f1 691
7390832c 692 if ( $user->contactlistid ) {
693 if ($user->blocked == 0) { /// not blocked
c8621a02
AD
694 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
695 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
e8e2d7f1 696 } else { // blocked
c8621a02
AD
697 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
698 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
e8e2d7f1 699 }
e8e2d7f1 700 } else {
c8621a02
AD
701 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
702 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
703 }
704
705 //should we show just the icon or icon and text?
706 $histicontext = 'icon';
707 if ($showicontext) {
708 $histicontext = 'both';
e8e2d7f1 709 }
c8621a02 710 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
531e58f1 711
669be60c 712 echo '<tr><td class="pix">';
812dbaf7 713 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e8e2d7f1 714 echo '</td>';
669be60c 715 echo '<td class="contact">';
40a26286 716 $popupoptions = array(
c8621a02
AD
717 'height' => MESSAGE_DISCUSSION_HEIGHT,
718 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 719 'menubar' => false,
720 'location' => false,
721 'status' => true,
722 'scrollbars' => true,
723 'resizable' => true);
724
c8621a02 725 //$link = new moodle_url("/message/discussion.php?id=$user->id");
02f2c7bd 726 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
727 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
728 $action = null;
9bf16314 729 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
576ad290 730
e8e2d7f1 731 echo '</td>';
531e58f1 732
669be60c 733 echo '<td class="link">'.$strcontact.'</td>';
734 echo '<td class="link">'.$strblock.'</td>';
735 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 736 echo '</tr>';
737 }
738 echo '</table>';
531e58f1 739
e8e2d7f1 740 } else {
c3931654 741 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
c8621a02 742 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
c3931654 743 echo html_writer::end_tag('p');
e8e2d7f1 744 }
c8621a02 745 }
531e58f1 746
c8621a02
AD
747 // search messages for keywords
748 $messagesearch = false;
749 $messagesearchstring = null;
750 if (!empty($frm->keywords)) {
751 $messagesearch = true;
752 $messagesearchstring = clean_text(trim($frm->keywords));
753 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
754 $messagesearch = true;
755 $messagesearchstring = clean_text(trim($frm->combinedsearch));
756 }
531e58f1 757
c8621a02
AD
758 if ($messagesearch) {
759 if ($messagesearchstring) {
760 $keywords = explode(' ', $messagesearchstring);
ff49c389 761 } else {
762 $keywords = array();
763 }
e8e2d7f1 764 $tome = false;
765 $fromme = false;
766 $courseid = 'none';
767
c8621a02
AD
768 if (empty($frm->keywordsoption)) {
769 $frm->keywordsoption = 'allmine';
770 }
771
e8e2d7f1 772 switch ($frm->keywordsoption) {
773 case 'tome':
774 $tome = true;
775 break;
776 case 'fromme':
777 $fromme = true;
778 break;
779 case 'allmine':
780 $tome = true;
781 $fromme = true;
782 break;
783 case 'allusers':
784 $courseid = SITEID;
785 break;
786 case 'courseusers':
787 $courseid = $frm->courseid;
788 break;
789 default:
790 $tome = true;
791 $fromme = true;
792 }
793
794 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 795
e8e2d7f1 796 /// get a list of contacts
fd1cb1e8 797 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
082864f9 798 $contacts = array();
799 }
e8e2d7f1 800
082864f9 801 /// print heading with number of results
c3931654
AD
802 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
803 $countresults = count($messages);
804 if ($countresults==MESSAGE_SEARCH_MAX_RESULTS) {
805 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
806 } else {
a813a748 807 echo get_string('keywordssearchresults', 'message', $countresults);
c3931654
AD
808 }
809 echo html_writer::end_tag('p');
082864f9 810
811 /// print table headings
c8621a02 812 echo '<table class="messagesearchresults" cellspacing="0">';
c3931654
AD
813
814 $headertdstart = html_writer::start_tag('td', array('class'=>'messagesearchresultscol'));
815 $headertdend = html_writer::end_tag('td');
082864f9 816 echo '<tr>';
c3931654
AD
817 echo $headertdstart.get_string('from').$headertdend;
818 echo $headertdstart.get_string('to').$headertdend;
819 echo $headertdstart.get_string('message', 'message').$headertdend;
820 echo $headertdstart.get_string('timesent', 'message').$headertdend;
082864f9 821 echo "</tr>\n";
822
823 $blockedcount = 0;
54d8f804 824 $dateformat = get_string('strftimedatetimeshort');
38c6a928 825 $strcontext = get_string('context', 'message');
e8e2d7f1 826 foreach ($messages as $message) {
082864f9 827
828 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 829 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 830 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
831 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
832 )
833 ) {
834 $blockedcount ++;
e8e2d7f1 835 continue;
836 }
531e58f1 837
082864f9 838 /// load up user to record
839 if ($message->useridto !== $USER->id) {
fd1cb1e8 840 $userto = $DB->get_record('user', array('id'=>$message->useridto));
531e58f1 841 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 842 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 843 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 844 ($contacts[$message->useridto]->blocked == 1) );
845 } else {
846 $userto = false;
847 $tocontact = false;
848 $toblocked = false;
849 }
531e58f1 850
082864f9 851 /// load up user from record
852 if ($message->useridfrom !== $USER->id) {
fd1cb1e8 853 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
531e58f1 854 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 855 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 856 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 857 ($contacts[$message->useridfrom]->blocked == 1) );
858 } else {
859 $userfrom = false;
860 $fromcontact = false;
861 $fromblocked = false;
862 }
863
e520509a 864 /// find date string for this message
865 $date = usergetdate($message->timecreated);
866 $datestring = $date['year'].$date['mon'].$date['mday'];
867
082864f9 868 /// print out message row
869 echo '<tr valign="top">';
669be60c 870 echo '<td class="contact">';
c8621a02 871 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
e8e2d7f1 872 echo '</td>';
669be60c 873 echo '<td class="contact">';
c8621a02 874 message_print_user($userto, $tocontact, $toblocked, $showicontext);
e8e2d7f1 875 echo '</td>';
3d143595 876 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
669be60c 877 echo '<br /><div class="link">';
c8621a02 878
71666cf3 879 //find the user involved that isn't the current user
c8621a02
AD
880 $user2id = null;
881 if ($user1->id == $message->useridto) {
882 $user2id = $message->useridfrom;
883 } else {
884 $user2id = $message->useridto;
885 }
886 message_history_link($user1->id, $user2id, false,
887 $messagesearchstring, 'm'.$message->id, $strcontext);
f520438c 888 echo '</div>';
e520509a 889 echo '</td>';
669be60c 890 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 891 echo "</tr>\n";
892 }
531e58f1 893
e8e2d7f1 894
e520509a 895 if ($blockedcount > 0) {
896 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
897 }
e8e2d7f1 898 echo '</table>';
531e58f1 899
e8e2d7f1 900 } else {
c8621a02 901 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', 0).' ("'.s($messagesearchstring).'")</p>';
e8e2d7f1 902 }
c8621a02 903 }
e8e2d7f1 904
c8621a02 905 if (!$personsearch && !$messagesearch) {
71666cf3 906 //they didn't enter any search terms
aa9a6867 907 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 908 }
909
082864f9 910 echo '<br />';
c8621a02 911 echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('tab' => 'search')), get_string('newsearch', 'message'));
e8e2d7f1 912
913 echo '</div>';
914}
915
916
c8621a02 917function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
7cb1a1ad 918 global $USER, $OUTPUT;
1d422980 919
082864f9 920 if ($user === false) {
812dbaf7 921 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
082864f9 922 } else {
a813a748 923 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e520509a 924 echo '&nbsp;';
c8621a02
AD
925
926 $return = false;
927 $script = null;
082864f9 928 if ($iscontact) {
c8621a02 929 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
082864f9 930 } else {
c8621a02 931 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
082864f9 932 }
933 echo '&nbsp;';
934 if ($isblocked) {
c8621a02 935 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
082864f9 936 } else {
c8621a02 937 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
082864f9 938 }
e520509a 939 echo '<br />';
576ad290 940
40a26286 941 $popupoptions = array(
c8621a02
AD
942 'height' => MESSAGE_DISCUSSION_HEIGHT,
943 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 944 'menubar' => false,
945 'location' => false,
946 'status' => true,
947 'scrollbars' => true,
948 'resizable' => true);
949
c8621a02 950 //$link = new moodle_url("/message/discussion.php?id=$user->id");
02f2c7bd 951 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
952 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
953 $action = null;
9bf16314 954 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
40a26286 955
082864f9 956 }
957}
958
959
960/// linktype can be: add, remove, block, unblock
c8621a02
AD
961function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
962 global $USER, $CFG, $OUTPUT, $PAGE;
e520509a 963
6898e848 964 //hold onto the strings as we're probably creating a bunch of links
e520509a 965 static $str;
966
c8621a02 967 if (empty($script)) {
cee92282
AD
968 //strip off previous action params like 'removecontact'
969 $theurl = message_remove_url_params($PAGE->url);
970
971 if (strpos($theurl, '?')===false) {
972 $script = $theurl.'?tab=contacts';
973 } else {
974 $script = $theurl.'&amp;tab=contacts';
975 }
c8621a02
AD
976 }
977
e520509a 978 if (empty($str->blockcontact)) {
979 $str->blockcontact = get_string('blockcontact', 'message');
980 $str->unblockcontact = get_string('unblockcontact', 'message');
981 $str->removecontact = get_string('removecontact', 'message');
982 $str->addcontact = get_string('addcontact', 'message');
983 }
984
5d6b319b 985 $command = $linktype.'contact';
986 $string = $str->{$command};
6898e848
AD
987
988 $safealttext = s($string);
989
990 $safestring = '';
3a11c09f 991 if (!empty($text)) {
6898e848 992 $safestring = $safealttext;
c8621a02
AD
993 }
994
995 $img = '';
996 if ($icon) {
6898e848
AD
997 $iconpath = null;
998 switch ($linktype) {
999 case 'block':
1000 $iconpath = 't/block';
1001 break;
1002 case 'unblock':
1003 $iconpath = 't/userblue';
1004 break;
1005 case 'remove':
1006 $iconpath = 'i/cross_red_big';
1007 break;
1008 case 'add':
1009 default:
1010 $iconpath = 't/addgreen';
1011 }
1012
1013 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
082864f9 1014 }
5d6b319b 1015
c8621a02 1016 $output = '<span class="'.$linktype.'contact">'.
5d6b319b 1017 '<a href="'.$script.'&amp;'.$command.'='.$userid.
01e85326 1018 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
c8621a02 1019 $img.
6898e848 1020 $safestring.'</a></span>';
5d6b319b 1021
e520509a 1022 if ($return) {
1023 return $output;
082864f9 1024 } else {
e520509a 1025 echo $output;
082864f9 1026 return true;
1027 }
1028}
1029
c8621a02 1030function message_history_link($userid1, $userid2, $returnstr=false, $keywords='', $position='', $linktext='') {
f2a1963c 1031 global $USER, $CFG, $OUTPUT;
62119d65 1032
830d0af6 1033 static $strmessagehistory;
1034
1035 if (empty($strmessagehistory)) {
1036 $strmessagehistory = get_string('messagehistory', 'message');
1037 }
2514081c 1038
e520509a 1039 if ($position) {
1040 $position = "#$position";
1041 }
38c6a928 1042 if ($keywords) {
1043 $keywords = "&search=".urlencode($keywords);
1044 }
62119d65 1045
830d0af6 1046 if ($linktext == 'icon') { // Icon only
b5d0cafc 1047 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 1048 } else if ($linktext == 'both') { // Icon and standard name
b5d0cafc 1049 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
830d0af6 1050 $fulllink .= '&nbsp;'.$strmessagehistory;
1051 } else if ($linktext) { // Custom name
1052 $fulllink = $linktext;
1053 } else { // Standard name only
1054 $fulllink = $strmessagehistory;
fd7006f6 1055 }
1056
40a26286 1057 $popupoptions = array(
1058 'height' => 500,
1059 'width' => 500,
1060 'menubar' => false,
1061 'location' => false,
1062 'status' => true,
1063 'scrollbars' => true,
1064 'resizable' => true);
1065
02f2c7bd 1066 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
c8621a02
AD
1067 //$action = new popup_action('click', $link, "message_history_$userid1", $popupoptions);
1068 $action = null;
9bf16314 1069 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
62119d65 1070
5d6b319b 1071 $str = '<span class="history">'.$str.'</span>';
1072
62119d65 1073 if ($returnstr) {
1074 return $str;
1075 } else {
1076 echo $str;
1077 return true;
1078 }
1079}
e8e2d7f1 1080
1081
1082/**
1083 * Search through course users
1084 *
531e58f1 1085 * If $coursid specifies the site course then this function searches
e8e2d7f1 1086 * through all undeleted and confirmed users
1087 *
7390832c 1088 * @uses $CFG, $USER
e8e2d7f1 1089 * @uses SITEID
1090 * @param int $courseid The course in question.
1091 * @param string $searchtext ?
1092 * @param string $sort ?
531e58f1 1093 * @param string $exceptions ?
e8e2d7f1 1094 * @return array An array of {@link $USER} records.
1095 * @todo Finish documenting this function
1096 */
1097function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 1098 global $CFG, $USER, $DB;
e8e2d7f1 1099
245ac557 1100 $fullname = $DB->sql_fullname();
e8e2d7f1 1101
1102 if (!empty($exceptions)) {
1103 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1104 } else {
1105 $except = '';
1106 }
1107
1108 if (!empty($sort)) {
1109 $order = ' ORDER BY '. $sort;
1110 } else {
1111 $order = '';
1112 }
1113
3a11c09f 1114 $ufields = user_picture::fields('u');
e8e2d7f1 1115 if (!$courseid or $courseid == SITEID) {
fd1cb1e8 1116 $params = array($USER->id, "%$searchtext%");
3a11c09f 1117 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
d9eef08a 1118 FROM {user} u
fd1cb1e8 1119 LEFT JOIN {message_contacts} mc
1d422980 1120 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1121 WHERE u.deleted = '0' AND u.confirmed = '1'
dd54dc31 1122 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1123 $except
1124 $order", $params);
e8e2d7f1 1125 } else {
3a11c09f 1126//TODO: add enabled enrolment join here (skodak)
d76a5a7f 1127 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1128 $contextlists = get_related_contexts_string($context);
531e58f1 1129
91421f3e 1130 // everyone who has a role assignment in this course or higher
fd1cb1e8 1131 $params = array($USER->id, "%$searchtext%");
3a11c09f
PS
1132 $users = $DB->get_records_sql("SELECT $ufields,
1133 FROM {user} u, mc.id as contactlistid, mc.blocked
fd1cb1e8 1134 JOIN {role_assignments} ra ON ra.userid = u.id
1135 LEFT JOIN {message_contacts} mc
1d422980 1136 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1137 WHERE u.deleted = '0' AND u.confirmed = '1'
fd1cb1e8 1138 AND ra.contextid $contextlists
dd54dc31 1139 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1140 $except
1141 $order", $params);
d76a5a7f 1142
1143 return $users;
e8e2d7f1 1144 }
1145}
1146
1147
1148
1149
082864f9 1150function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 1151/// Returns a list of posts found using an array of search terms
1152/// eg word +word -word
1153///
fd1cb1e8 1154 global $CFG, $USER, $DB;
e8e2d7f1 1155
082864f9 1156 /// If no userid sent then assume current user
531e58f1 1157 if ($userid == 0) $userid = $USER->id;
082864f9 1158
6eb7722f 1159 /// Some differences in SQL syntax
d9eef08a 1160 if ($DB->sql_regex_supported()) {
1161 $REGEXP = $DB->sql_regex(true);
1162 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 1163 }
1164
d9eef08a 1165 $searchcond = array();
1166 $params = array();
1167 $i = 0;
e8e2d7f1 1168
c3931654
AD
1169 //preprocess search terms to check whether we have at least 1 eligible search term
1170 //if we do we can drop words around it like 'a'
1171 $dropshortwords = false;
1172 foreach ($searchterms as $searchterm) {
1173 if (strlen($searchterm) >= 2) {
1174 $dropshortwords = true;
1175 }
1176 }
1177
e8e2d7f1 1178 foreach ($searchterms as $searchterm) {
d9eef08a 1179 $i++;
1180
47586394 1181 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
d9eef08a 1182
c3931654 1183 if ($dropshortwords && strlen($searchterm) < 2) {
e8e2d7f1 1184 continue;
1185 }
6bb4875f 1186 /// Under Oracle and MSSQL, trim the + and - operators and perform
1187 /// simpler LIKE search
d9eef08a 1188 if (!$DB->sql_regex_supported()) {
1189 if (substr($searchterm, 0, 1) == '-') {
47586394 1190 $NOT = true;
d9eef08a 1191 }
6bb4875f 1192 $searchterm = trim($searchterm, '+-');
1193 }
1194
e8e2d7f1 1195 if (substr($searchterm,0,1) == "+") {
1196 $searchterm = substr($searchterm,1);
d9eef08a 1197 $searchterm = preg_quote($searchterm, '|');
3d143595 1198 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
d9eef08a 1199 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1200
e8e2d7f1 1201 } else if (substr($searchterm,0,1) == "-") {
1202 $searchterm = substr($searchterm,1);
d9eef08a 1203 $searchterm = preg_quote($searchterm, '|');
3d143595 1204 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
d9eef08a 1205 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1206
e8e2d7f1 1207 } else {
47586394 1208 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
d9eef08a 1209 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 1210 }
172186b8 1211 }
1212
d9eef08a 1213 if (empty($searchcond)) {
dd54dc31 1214 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
ff49c389 1215 $params['ss1'] = "%";
1216 } else {
1217 $searchcond = implode(" AND ", $searchcond);
8a51efe9 1218 }
e8e2d7f1 1219
082864f9 1220 /// There are several possibilities
1221 /// 1. courseid = SITEID : The admin is searching messages by all users
1222 /// 2. courseid = ?? : A teacher is searching messages by users in
1223 /// one of their courses - currently disabled
1224 /// 3. courseid = none : User is searching their own messages;
1225 /// a. Messages from user
1226 /// b. Messages to user
1227 /// c. Messages to and from user
1228
1229 if ($courseid == SITEID) { /// admin is searching all messages
3d143595 1230 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1231 FROM {message_read} m
c3931654 1232 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1233 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1234 FROM {message} m
c3931654 1235 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
d9eef08a 1236
1237 } else if ($courseid !== 'none') {
082864f9 1238 /// This has not been implemented due to security concerns
d9eef08a 1239 $m_read = array();
1240 $m_unread = array();
e8e2d7f1 1241
082864f9 1242 } else {
531e58f1 1243
d9eef08a 1244 if ($fromme and $tome) {
1245 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1246 $params['userid1'] = $userid;
1247 $params['userid2'] = $userid;
1248
1249 } else if ($fromme) {
1250 $searchcond .= " AND m.useridfrom=:userid";
1251 $params['userid'] = $userid;
531e58f1 1252
d9eef08a 1253 } else if ($tome) {
1254 $searchcond .= " AND m.useridto=:userid";
1255 $params['userid'] = $userid;
1256 }
531e58f1 1257
3d143595 1258 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1259 FROM {message_read} m
c3931654 1260 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1261 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1262 FROM {message} m
c3931654 1263 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
531e58f1 1264
e8e2d7f1 1265 }
1266
082864f9 1267 /// The keys may be duplicated in $m_read and $m_unread so we can't
1268 /// do a simple concatenation
1269 $message = array();
d9eef08a 1270 foreach ($m_read as $m) {
1271 $messages[] = $m;
1272 }
1273 foreach ($m_unread as $m) {
1274 $messages[] = $m;
1275 }
e8e2d7f1 1276
1277 return (empty($messages)) ? false : $messages;
172186b8 1278}
1279
e8e2d7f1 1280
1281
1282/// Borrowed with changes from mod/forum/lib.php
1283function message_shorten_message($message, $minlength=0) {
1284// Given a post object that we already know has a long message
1285// this function truncates the message nicely to the first
1286// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1287
1288 $i = 0;
1289 $tag = false;
1290 $length = strlen($message);
1291 $count = 0;
1292 $stopzone = false;
1293 $truncate = 0;
1294 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 1295
e8e2d7f1 1296
1297 for ($i=0; $i<$length; $i++) {
1298 $char = $message[$i];
1299
1300 switch ($char) {
1301 case "<":
1302 $tag = true;
1303 break;
1304 case ">":
1305 $tag = false;
1306 break;
1307 default:
1308 if (!$tag) {
1309 if ($stopzone) {
1310 if ($char == '.' or $char == ' ') {
1311 $truncate = $i+1;
1312 break 2;
1313 }
1314 }
1315 $count++;
1316 }
1317 break;
1318 }
1319 if (!$stopzone) {
1320 if ($count > $minlength) {
1321 $stopzone = true;
1322 }
1323 }
1324 }
1325
1326 if (!$truncate) {
1327 $truncate = $i;
1328 }
1329
1330 return substr($message, 0, $truncate);
1331}
1332
38c6a928 1333
d9eef08a 1334/**
38c6a928 1335 * Given a string and an array of keywords, this function looks
1336 * for the first keyword in the string, and then chops out a
1337 * small section from the text that shows that word in context.
1338 */
1339function message_get_fragment($message, $keywords) {
1340
1341 $fullsize = 120;
1342 $halfsize = (int)($fullsize/2);
1343
1344 $message = strip_tags($message);
1345
1346 foreach ($keywords as $keyword) { // Just get the first one
1347 if ($keyword !== '') {
1348 break;
1349 }
1350 }
1351 if (empty($keyword)) { // None found, so just return start of message
1352 return message_shorten_message($message, 30);
1353 }
1354
1355 $leadin = $leadout = '';
1356
1357/// Find the start of the fragment
1358 $start = 0;
1359 $length = strlen($message);
1360
1361 $pos = strpos($message, $keyword);
1362 if ($pos > $halfsize) {
1363 $start = $pos - $halfsize;
1364 $leadin = '...';
1365 }
1366/// Find the end of the fragment
1367 $end = $start + $fullsize;
1368 if ($end > $length) {
1369 $end = $length;
1370 } else {
1371 $leadout = '...';
1372 }
1373
1374/// Pull out the fragment and format it
1375
1376 $fragment = substr($message, $start, $end - $start);
1377 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1378 return $fragment;
1379}
1380
c8621a02 1381//retrieve the messages between two users
a813a748
AD
1382function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1383 global $DB, $CFG;
fd1cb1e8 1384
c8621a02
AD
1385 $messages = array();
1386
1387 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1388 //desc to get the last $limitnum messages then flip the order in php
1389 $sort = 'asc';
1390 if ($limitnum>0) {
1391 $sort = 'desc';
1392 }
1393
a813a748
AD
1394 $notificationswhere = null;
1395 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1396 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1397 $notificationswhere = 'AND notification=0';
1398 }
1399
1400 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
1401 (useridto = ? AND useridfrom = ?)) $notificationswhere", array($user1->id, $user2->id, $user2->id, $user1->id),
c8621a02
AD
1402 "timecreated $sort", '*', 0, $limitnum)) {
1403 foreach ($messages_read as $message) {
1404 $messages[$message->timecreated] = $message;
1405 }
1406 }
fd1cb1e8 1407 if ($messages_new = $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
1408 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
c8621a02 1409 "timecreated $sort", '*', 0, $limitnum)) {
b9ee0638 1410 foreach ($messages_new as $message) {
c8621a02 1411 $messages[$message->timecreated] = $message;
b9ee0638 1412 }
1413 }
c8621a02
AD
1414
1415 //if we only want the last $limitnum messages
1416 if ($limitnum>0) {
1417 ksort($messages);
1418 $messages = array_slice($messages, count($messages)-$limitnum, $limitnum, true);
1419 }
3a11c09f 1420
b9ee0638 1421 return $messages;
1422}
1423
a813a748 1424function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
c8621a02
AD
1425 global $CFG, $OUTPUT;
1426
1427 echo $OUTPUT->box_start('center');
1428 echo '<table cellpadding="10" class="message_user_pictures"><tr>';
1429 echo '<td align="center" id="user1">';
1430 echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID));
1431 echo '<div class="heading">'.fullname($user1).'</div>';
1432 echo '</td>';
1433 echo '<td align="center">';
b11681e0
PS
1434 echo '<img src="'.$OUTPUT->pix_url('t/left').'" alt="'.get_string('from').'" />';
1435 echo '<img src="'.$OUTPUT->pix_url('t/right').'" alt="'.get_string('to').'" />';
c8621a02
AD
1436 echo '</td>';
1437 echo '<td align="center" id="user2">';
1438 echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID));
1439 echo '<div class="heading">'.fullname($user2).'</div>';
1440
1441 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1442 $incontactlist = $user2->iscontact;
1443 $isblocked = $user2->isblocked;
1444
1445 $script = null;
1446 $text = true;
1447 $icon = false;
1448
1449 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1450 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
41117b3e
AD
1451 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1452
1453 echo html_writer::tag('div', $useractionlinks, array('class'=>'useractionlinks'));
c8621a02
AD
1454 }
1455
1456 echo '</td>';
1457 echo '</tr></table>';
1458 echo $OUTPUT->box_end();
1459
1460 if (!empty($messagehistorylink)) {
1461 echo $messagehistorylink;
1462 }
1463
1464 /// Get all the messages and print them
a813a748 1465 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
c8621a02
AD
1466 $tablecontents = '';
1467
8e803c3f 1468 $current = new stdClass();
c8621a02
AD
1469 $current->mday = '';
1470 $current->month = '';
1471 $current->year = '';
1472 $messagedate = get_string('strftimetime');
1473 $blockdate = get_string('strftimedaydate');
1474 foreach ($messages as $message) {
a813a748
AD
1475 if ($message->notification) {
1476 $notificationclass = ' notification';
1477 } else {
1478 $notificationclass = null;
1479 }
c8621a02
AD
1480 $date = usergetdate($message->timecreated);
1481 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1482 $current->mday = $date['mday'];
1483 $current->month = $date['month'];
1484 $current->year = $date['year'];
1485
1486 $tablecontents .= '<div class="mdl-align heading"><a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
1487 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center').'</div>';
1488 }
1489 if ($message->useridfrom == $user1->id) {
a813a748 1490 $tablecontents .= "<div class='mdl-left left $notificationclass'>".message_format_message($message, $user1, $messagedate, $search, 'me').'</div><br />';
c8621a02 1491 } else {
a813a748 1492 $tablecontents .= "<div class='mdl-left right $notificationclass'>".message_format_message($message, $user2, $messagedate, $search, 'other').'</div><br />';
c8621a02
AD
1493 }
1494 }
1495
1496 echo html_writer::nonempty_tag('div', $tablecontents, array('class'=>'mdl-left messagehistory'));
1497 } else {
22c2732d 1498 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class'=>'mdl-align messagehistory'));
c8621a02
AD
1499 }
1500}
1501
030e3e03 1502function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 1503
1504 static $dateformat;
1505
1506 if (empty($dateformat)) {
1507 if ($format) {
1508 $dateformat = $format;
1509 } else {
54d8f804 1510 $format = get_string('strftimedatetimeshort');
acd21a2d 1511 }
b9ee0638 1512 }
acd21a2d 1513 $time = userdate($message->timecreated, $dateformat);
8e803c3f 1514 $options = new stdClass();
ff6048dd 1515 $options->para = false;
6ee2611c
AD
1516
1517 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1518 if (!empty($message->smallmessage)) {
1519 $messagetext = format_text($message->smallmessage, null, $options);
1520 } else {
1521 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1522 }
1523
14a0e7dd
AD
1524 if (!empty($message->contexturl)) {
1525 $displaytext = null;
1526 if (!empty($message->contexturlname)) {
1527 $displaytext= $message->contexturlname;
1528 } else {
1529 $displaytext= $message->contexturl;
1530 }
1531 $messagetext .= html_writer::start_tag('div',array('class'=>'messagecontext'));
1532 $messagetext .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1533 $messagetext .= html_writer::end_tag('div');
1534 }
1535
38c6a928 1536 if ($keywords) {
1537 $messagetext = highlight($keywords, $messagetext);
1538 }
14a0e7dd 1539
229f4e92 1540 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
b9ee0638 1541}
e8e2d7f1 1542
fd1cb1e8 1543/**
405f01ee 1544 * Inserts a message into the database, but also forwards it
1545 * via other means if appropriate.
1546 */
1547function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
27a39763
AD
1548 global $SITE, $CFG, $USER;
1549
8e803c3f 1550 $eventdata = new stdClass();
1560760f 1551 $eventdata->component = 'moodle';
1c50df9f 1552 $eventdata->name = 'instantmessage';
3b120e46 1553 $eventdata->userfrom = $userfrom;
1554 $eventdata->userto = $userto;
cf455865 1555 $eventdata->subject = get_string('unreadnewmessage', 'message', fullname($userfrom));
3b120e46 1556 $eventdata->fullmessage = $message;
c8621a02 1557 $eventdata->fullmessageformat = $format;
3b120e46 1558 $eventdata->fullmessagehtml = '';
6ee2611c 1559 $eventdata->smallmessage = $message;
27a39763
AD
1560
1561 $s = new stdClass();
1562 $s->sitename = $SITE->shortname;
1563 $s->url = $CFG->wwwroot.'/message/index.php?id='.$userfrom->id;//.'&user='.$userto->id;
1564
1565 $emailtagline = get_string('emailtagline', 'message', $s);
6ee2611c
AD
1566 if (!empty($eventdata->fullmessage)) {
1567 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1568 }
6ee2611c
AD
1569 if (!empty($eventdata->fullmessagehtml)) {
1570 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1571 }
27a39763 1572
a1b53dcf 1573 $eventdata->timecreated = time();
7c7d3afa 1574 return message_send($eventdata);
405f01ee 1575}
e8e2d7f1 1576
c135a425 1577
fd1cb1e8 1578/**
c135a425 1579 * Returns a list of all user ids who have used messaging in the site
1580 * This was the simple way to code the SQL ... is it going to blow up
1581 * on large datasets?
1582 */
1583function message_get_participants() {
fd1cb1e8 1584 global $CFG, $DB;
1585
76b0191c 1586 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1587 UNION SELECT useridto as id,1 FROM {message}
1588 UNION SELECT useridfrom as id,1 FROM {message_read}
1589 UNION SELECT useridto as id,1 FROM {message_read}
1590 UNION SELECT userid as id,1 FROM {message_contacts}
1591 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1592}
1593
f46b6587 1594/**
1d422980 1595 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 1596 * block links etc
7cb1a1ad 1597 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
f46b6587 1598 * @param $incontactlist is the user a contact of ours?
c8621a02 1599 * @param $selectcontacturl string the url to send the user to when a contact's name is clicked
f46b6587 1600 */
c8621a02
AD
1601function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true) {
1602 global $OUTPUT, $USER;
f46b6587 1603 $fullname = fullname($contact);
1604 $fullnamelink = $fullname;
1605
1606 /// are there any unread messages for this contact?
1607 if ($contact->messagecount > 0 ){
1608 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1609 }
1610
c8621a02 1611 $strcontact = $strblock = $strhistory = null;
f46b6587 1612
c8621a02
AD
1613 if ($showactionlinks) {
1614 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
1615 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
1616 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
f46b6587 1617 }
1618
f46b6587 1619 echo '<tr><td class="pix">';
812dbaf7 1620 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
f46b6587 1621 echo '</td>';
1622 echo '<td class="contact">';
1d422980 1623
40a26286 1624 $popupoptions = array(
c8621a02
AD
1625 'height' => MESSAGE_DISCUSSION_HEIGHT,
1626 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 1627 'menubar' => false,
1628 'location' => false,
1629 'status' => true,
1630 'scrollbars' => true,
1631 'resizable' => true);
1632
c8621a02
AD
1633 $link = $action = null;
1634 if (!empty($selectcontacturl)) {
1635 $link = new moodle_url($selectcontacturl.'&'.CONTACT_ID.'='.$contact->id);
1636 } else {
1637 //I suspect this else clause can be removed and maybe the $selectcontacturl arg can be removed and hardcoded
1638 $link = new moodle_url("/message/discussion.php?id=$contact->id");
1639 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1640 }
9bf16314 1641 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
f46b6587 1642
1643 echo '</td>';
1644 echo '<td class="link">&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory.'</td>';
1645 echo '</tr>';
1646}
1647
c8621a02
AD
1648function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1649 $strcontact = '';
1650
1651 if($incontactlist){
1652 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
1653 } else if ($isblocked) {
1654 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1655 } else{
1656 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1657 }
1658
1659 return $strcontact;
1660}
1661
1662function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1663 $strblock = '';
1664
1665 //commented out to allow the user to block a contact without having to remove them first
1666 /*if ($incontactlist) {
1667 //$strblock = '';
1668 } else*/
1669 if ($isblocked) {
1670 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
1671 } else{
1672 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
1673 }
1674
1675 return $strblock;
1676}
1677
6bdf4c99 1678 /**
1679 * Moves unread messages from message table to message_read for a given from user
1680 * @param object $userid User id
1681 * @return boolean success
1682 */
1683function message_move_userfrom_unread2read($userid) {
1684
1685 global $DB;
1686
71666cf3 1687 // move all unread messages from message table to message_read
6bdf4c99 1688 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1689 foreach ($messages as $message) {
ee7cd81a 1690 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
6bdf4c99 1691 }
1692 }
1693 return true;
1694}
1695
1c50df9f 1696function message_get_popup_messages($destuserid, $fromuserid=NULL){
1697 global $DB;
1d422980 1698
1c50df9f 1699 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1700
a1b53dcf 1701 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1c50df9f 1702
1703 //for every message to process check if it's for current user and process
1704 $messages = array();
1705 foreach ($messagesproc as $msgp){
1706 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1707 if ($fromuserid){
1708 $query['useridfrom'] = $fromuserid;
1709 }
1710 if ($message = $DB->get_record('message', $query)){
1711 $messages[] = $message;
1712 /// Move the entry to the other table
1713 $message->timeread = time();
1714 $messageid = $message->id;
1715 unset($message->id);
1d422980 1716
1c50df9f 1717 //delete what we've processed and check if can move message
1718 $DB->delete_records('message_working', array('id' => $msgp->id));
1719 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
ee7cd81a 1720 message_mark_message_read($message, time(), true);
1c50df9f 1721 }
1722 }
1723 }
1724 return $messages;
c8621a02
AD
1725}
1726
ee7cd81a
AD
1727/**
1728* marks ALL messages being sent from $fromuserid to $touserid as read
1729* @param int $touserid the id of the message recipient
1730* @param int $fromuserid the id of the message sender
1731* @return void
1732*/
1560760f 1733function message_mark_messages_read($touserid, $fromuserid){
c8621a02
AD
1734 global $DB;
1735
ee7cd81a 1736 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
1560760f
AD
1737 $messages = $DB->get_recordset_sql($sql, array('useridto'=>$touserid,'useridfrom'=>$fromuserid));
1738
c8621a02 1739 foreach ($messages as $message) {
ee7cd81a
AD
1740 message_mark_message_read($message, time());
1741 }
1742}
1743
1744/**
1745* Mark a single message as read
1746* @param message an object with an object property ie $message->id which is an id in the message table
1747* @param int $timeread the timestamp for when the message should be marked read. Usually time().
1748* @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
1749* @return void
1750*/
1751function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
1752 global $DB;
1753
1754 $message->timeread = $timeread;
c8621a02 1755
ee7cd81a
AD
1756 $messageid = $message->id;
1757 unset($message->id);//unset because it will get a new id on insert into message_read
1560760f 1758
ee7cd81a
AD
1759 //If any processors have pending actions abort them
1760 if (!$messageworkingempty) {
1761 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
c8621a02 1762 }
ee7cd81a
AD
1763 $DB->insert_record('message_read', $message);
1764 $DB->delete_records('message', array('id' => $messageid));
65fbace7 1765}