mod-wiki MDL-25001 Added missing arguments to optional_param_calls
[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
c8621a02
AD
404 $strcontacts = get_string('mycontacts', 'message');
405 $options[VIEW_CONTACTS] = $strcontacts;
406
407 if (!empty($courses)) {
408 $courses_options = array();
409
410 foreach($courses as $course) {
411 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
248403fa 412 $courses_options[VIEW_COURSE.$course->id] = $course->shortname;
c8621a02
AD
413 }
414 }
415
416 if (!empty($courses_options)) {
417 $options[] = array(get_string('courses')=>$courses_options);
418 }
419 }
420
31c532d0
AD
421 if ($countblocked>0) {
422 $strblockedusers = get_string('blockedusers','message', $countblocked);
423 $options[VIEW_BLOCKED] = $strblockedusers;
424 }
425
c8621a02 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
02f2c7bd 725 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
726 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
727 $action = null;
9bf16314 728 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
576ad290 729
e8e2d7f1 730 echo '</td>';
531e58f1 731
669be60c 732 echo '<td class="link">'.$strcontact.'</td>';
733 echo '<td class="link">'.$strblock.'</td>';
734 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 735 echo '</tr>';
736 }
737 echo '</table>';
531e58f1 738
e8e2d7f1 739 } else {
c3931654 740 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
c8621a02 741 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
c3931654 742 echo html_writer::end_tag('p');
e8e2d7f1 743 }
c8621a02 744 }
531e58f1 745
c8621a02
AD
746 // search messages for keywords
747 $messagesearch = false;
748 $messagesearchstring = null;
749 if (!empty($frm->keywords)) {
750 $messagesearch = true;
751 $messagesearchstring = clean_text(trim($frm->keywords));
752 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
753 $messagesearch = true;
754 $messagesearchstring = clean_text(trim($frm->combinedsearch));
755 }
531e58f1 756
c8621a02
AD
757 if ($messagesearch) {
758 if ($messagesearchstring) {
759 $keywords = explode(' ', $messagesearchstring);
ff49c389 760 } else {
761 $keywords = array();
762 }
e8e2d7f1 763 $tome = false;
764 $fromme = false;
765 $courseid = 'none';
766
c8621a02
AD
767 if (empty($frm->keywordsoption)) {
768 $frm->keywordsoption = 'allmine';
769 }
770
e8e2d7f1 771 switch ($frm->keywordsoption) {
772 case 'tome':
773 $tome = true;
774 break;
775 case 'fromme':
776 $fromme = true;
777 break;
778 case 'allmine':
779 $tome = true;
780 $fromme = true;
781 break;
782 case 'allusers':
783 $courseid = SITEID;
784 break;
785 case 'courseusers':
786 $courseid = $frm->courseid;
787 break;
788 default:
789 $tome = true;
790 $fromme = true;
791 }
792
793 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 794
e8e2d7f1 795 /// get a list of contacts
fd1cb1e8 796 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
082864f9 797 $contacts = array();
798 }
e8e2d7f1 799
082864f9 800 /// print heading with number of results
c3931654
AD
801 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
802 $countresults = count($messages);
803 if ($countresults==MESSAGE_SEARCH_MAX_RESULTS) {
804 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
805 } else {
a813a748 806 echo get_string('keywordssearchresults', 'message', $countresults);
c3931654
AD
807 }
808 echo html_writer::end_tag('p');
082864f9 809
810 /// print table headings
c8621a02 811 echo '<table class="messagesearchresults" cellspacing="0">';
c3931654
AD
812
813 $headertdstart = html_writer::start_tag('td', array('class'=>'messagesearchresultscol'));
814 $headertdend = html_writer::end_tag('td');
082864f9 815 echo '<tr>';
c3931654
AD
816 echo $headertdstart.get_string('from').$headertdend;
817 echo $headertdstart.get_string('to').$headertdend;
818 echo $headertdstart.get_string('message', 'message').$headertdend;
819 echo $headertdstart.get_string('timesent', 'message').$headertdend;
082864f9 820 echo "</tr>\n";
821
822 $blockedcount = 0;
54d8f804 823 $dateformat = get_string('strftimedatetimeshort');
38c6a928 824 $strcontext = get_string('context', 'message');
e8e2d7f1 825 foreach ($messages as $message) {
082864f9 826
827 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 828 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 829 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
830 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
831 )
832 ) {
833 $blockedcount ++;
e8e2d7f1 834 continue;
835 }
531e58f1 836
082864f9 837 /// load up user to record
838 if ($message->useridto !== $USER->id) {
fd1cb1e8 839 $userto = $DB->get_record('user', array('id'=>$message->useridto));
531e58f1 840 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 841 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 842 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 843 ($contacts[$message->useridto]->blocked == 1) );
844 } else {
845 $userto = false;
846 $tocontact = false;
847 $toblocked = false;
848 }
531e58f1 849
082864f9 850 /// load up user from record
851 if ($message->useridfrom !== $USER->id) {
fd1cb1e8 852 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
531e58f1 853 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 854 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 855 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 856 ($contacts[$message->useridfrom]->blocked == 1) );
857 } else {
858 $userfrom = false;
859 $fromcontact = false;
860 $fromblocked = false;
861 }
862
e520509a 863 /// find date string for this message
864 $date = usergetdate($message->timecreated);
865 $datestring = $date['year'].$date['mon'].$date['mday'];
866
082864f9 867 /// print out message row
868 echo '<tr valign="top">';
669be60c 869 echo '<td class="contact">';
c8621a02 870 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
e8e2d7f1 871 echo '</td>';
669be60c 872 echo '<td class="contact">';
c8621a02 873 message_print_user($userto, $tocontact, $toblocked, $showicontext);
e8e2d7f1 874 echo '</td>';
3d143595 875 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
669be60c 876 echo '<br /><div class="link">';
c8621a02 877
71666cf3 878 //find the user involved that isn't the current user
c8621a02
AD
879 $user2id = null;
880 if ($user1->id == $message->useridto) {
881 $user2id = $message->useridfrom;
882 } else {
883 $user2id = $message->useridto;
884 }
885 message_history_link($user1->id, $user2id, false,
886 $messagesearchstring, 'm'.$message->id, $strcontext);
f520438c 887 echo '</div>';
e520509a 888 echo '</td>';
669be60c 889 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 890 echo "</tr>\n";
891 }
531e58f1 892
e8e2d7f1 893
e520509a 894 if ($blockedcount > 0) {
895 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
896 }
e8e2d7f1 897 echo '</table>';
531e58f1 898
e8e2d7f1 899 } else {
c8621a02 900 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', 0).' ("'.s($messagesearchstring).'")</p>';
e8e2d7f1 901 }
c8621a02 902 }
e8e2d7f1 903
c8621a02 904 if (!$personsearch && !$messagesearch) {
71666cf3 905 //they didn't enter any search terms
aa9a6867 906 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 907 }
908
31c532d0
AD
909 //echo '<br />';
910 //echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('tab' => 'search')), get_string('newsearch', 'message'));
e8e2d7f1 911
912 echo '</div>';
913}
914
915
c8621a02 916function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
7cb1a1ad 917 global $USER, $OUTPUT;
1d422980 918
082864f9 919 if ($user === false) {
812dbaf7 920 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
082864f9 921 } else {
a813a748 922 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e520509a 923 echo '&nbsp;';
c8621a02
AD
924
925 $return = false;
926 $script = null;
082864f9 927 if ($iscontact) {
c8621a02 928 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
082864f9 929 } else {
c8621a02 930 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
082864f9 931 }
932 echo '&nbsp;';
933 if ($isblocked) {
c8621a02 934 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
082864f9 935 } else {
c8621a02 936 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
082864f9 937 }
e520509a 938 echo '<br />';
576ad290 939
40a26286 940 $popupoptions = array(
c8621a02
AD
941 'height' => MESSAGE_DISCUSSION_HEIGHT,
942 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 943 'menubar' => false,
944 'location' => false,
945 'status' => true,
946 'scrollbars' => true,
947 'resizable' => true);
948
02f2c7bd 949 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
950 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
951 $action = null;
9bf16314 952 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
40a26286 953
082864f9 954 }
955}
956
957
958/// linktype can be: add, remove, block, unblock
c8621a02
AD
959function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
960 global $USER, $CFG, $OUTPUT, $PAGE;
e520509a 961
6898e848 962 //hold onto the strings as we're probably creating a bunch of links
e520509a 963 static $str;
964
c8621a02 965 if (empty($script)) {
cee92282
AD
966 //strip off previous action params like 'removecontact'
967 $theurl = message_remove_url_params($PAGE->url);
968
969 if (strpos($theurl, '?')===false) {
970 $script = $theurl.'?tab=contacts';
971 } else {
972 $script = $theurl.'&amp;tab=contacts';
973 }
c8621a02
AD
974 }
975
e520509a 976 if (empty($str->blockcontact)) {
977 $str->blockcontact = get_string('blockcontact', 'message');
978 $str->unblockcontact = get_string('unblockcontact', 'message');
979 $str->removecontact = get_string('removecontact', 'message');
980 $str->addcontact = get_string('addcontact', 'message');
981 }
982
5d6b319b 983 $command = $linktype.'contact';
984 $string = $str->{$command};
6898e848
AD
985
986 $safealttext = s($string);
987
988 $safestring = '';
3a11c09f 989 if (!empty($text)) {
6898e848 990 $safestring = $safealttext;
c8621a02
AD
991 }
992
993 $img = '';
994 if ($icon) {
6898e848
AD
995 $iconpath = null;
996 switch ($linktype) {
997 case 'block':
998 $iconpath = 't/block';
999 break;
1000 case 'unblock':
1001 $iconpath = 't/userblue';
1002 break;
1003 case 'remove':
1004 $iconpath = 'i/cross_red_big';
1005 break;
1006 case 'add':
1007 default:
1008 $iconpath = 't/addgreen';
1009 }
1010
1011 $img = '<img src="'.$OUTPUT->pix_url($iconpath).'" class="iconsmall" alt="'.$safealttext.'" />';
082864f9 1012 }
5d6b319b 1013
c8621a02 1014 $output = '<span class="'.$linktype.'contact">'.
5d6b319b 1015 '<a href="'.$script.'&amp;'.$command.'='.$userid.
01e85326 1016 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
c8621a02 1017 $img.
6898e848 1018 $safestring.'</a></span>';
5d6b319b 1019
e520509a 1020 if ($return) {
1021 return $output;
082864f9 1022 } else {
e520509a 1023 echo $output;
082864f9 1024 return true;
1025 }
1026}
1027
c8621a02 1028function message_history_link($userid1, $userid2, $returnstr=false, $keywords='', $position='', $linktext='') {
f2a1963c 1029 global $USER, $CFG, $OUTPUT;
62119d65 1030
830d0af6 1031 static $strmessagehistory;
1032
1033 if (empty($strmessagehistory)) {
1034 $strmessagehistory = get_string('messagehistory', 'message');
1035 }
2514081c 1036
e520509a 1037 if ($position) {
1038 $position = "#$position";
1039 }
38c6a928 1040 if ($keywords) {
1041 $keywords = "&search=".urlencode($keywords);
1042 }
62119d65 1043
830d0af6 1044 if ($linktext == 'icon') { // Icon only
b5d0cafc 1045 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 1046 } else if ($linktext == 'both') { // Icon and standard name
b5d0cafc 1047 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
830d0af6 1048 $fulllink .= '&nbsp;'.$strmessagehistory;
1049 } else if ($linktext) { // Custom name
1050 $fulllink = $linktext;
1051 } else { // Standard name only
1052 $fulllink = $strmessagehistory;
fd7006f6 1053 }
1054
40a26286 1055 $popupoptions = array(
1056 'height' => 500,
1057 'width' => 500,
1058 'menubar' => false,
1059 'location' => false,
1060 'status' => true,
1061 'scrollbars' => true,
1062 'resizable' => true);
1063
02f2c7bd 1064 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user=$userid1&id=$userid2$keywords$position");
c8621a02
AD
1065 //$action = new popup_action('click', $link, "message_history_$userid1", $popupoptions);
1066 $action = null;
9bf16314 1067 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
62119d65 1068
5d6b319b 1069 $str = '<span class="history">'.$str.'</span>';
1070
62119d65 1071 if ($returnstr) {
1072 return $str;
1073 } else {
1074 echo $str;
1075 return true;
1076 }
1077}
e8e2d7f1 1078
1079
1080/**
1081 * Search through course users
1082 *
531e58f1 1083 * If $coursid specifies the site course then this function searches
e8e2d7f1 1084 * through all undeleted and confirmed users
1085 *
7390832c 1086 * @uses $CFG, $USER
e8e2d7f1 1087 * @uses SITEID
1088 * @param int $courseid The course in question.
1089 * @param string $searchtext ?
1090 * @param string $sort ?
531e58f1 1091 * @param string $exceptions ?
e8e2d7f1 1092 * @return array An array of {@link $USER} records.
1093 * @todo Finish documenting this function
1094 */
1095function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 1096 global $CFG, $USER, $DB;
e8e2d7f1 1097
245ac557 1098 $fullname = $DB->sql_fullname();
e8e2d7f1 1099
1100 if (!empty($exceptions)) {
1101 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1102 } else {
1103 $except = '';
1104 }
1105
1106 if (!empty($sort)) {
1107 $order = ' ORDER BY '. $sort;
1108 } else {
1109 $order = '';
1110 }
1111
3a11c09f 1112 $ufields = user_picture::fields('u');
e8e2d7f1 1113 if (!$courseid or $courseid == SITEID) {
fd1cb1e8 1114 $params = array($USER->id, "%$searchtext%");
3a11c09f 1115 return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mc.blocked
d9eef08a 1116 FROM {user} u
fd1cb1e8 1117 LEFT JOIN {message_contacts} mc
1d422980 1118 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1119 WHERE u.deleted = '0' AND u.confirmed = '1'
dd54dc31 1120 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1121 $except
1122 $order", $params);
e8e2d7f1 1123 } else {
3a11c09f 1124//TODO: add enabled enrolment join here (skodak)
d76a5a7f 1125 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1126 $contextlists = get_related_contexts_string($context);
531e58f1 1127
91421f3e 1128 // everyone who has a role assignment in this course or higher
fd1cb1e8 1129 $params = array($USER->id, "%$searchtext%");
3a11c09f
PS
1130 $users = $DB->get_records_sql("SELECT $ufields,
1131 FROM {user} u, mc.id as contactlistid, mc.blocked
fd1cb1e8 1132 JOIN {role_assignments} ra ON ra.userid = u.id
1133 LEFT JOIN {message_contacts} mc
1d422980 1134 ON mc.contactid = u.id AND mc.userid = ?
3a11c09f 1135 WHERE u.deleted = '0' AND u.confirmed = '1'
fd1cb1e8 1136 AND ra.contextid $contextlists
dd54dc31 1137 AND (".$DB->sql_like($fullname, '?', false).")
fd1cb1e8 1138 $except
1139 $order", $params);
d76a5a7f 1140
1141 return $users;
e8e2d7f1 1142 }
1143}
1144
1145
1146
1147
082864f9 1148function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 1149/// Returns a list of posts found using an array of search terms
1150/// eg word +word -word
1151///
fd1cb1e8 1152 global $CFG, $USER, $DB;
e8e2d7f1 1153
082864f9 1154 /// If no userid sent then assume current user
531e58f1 1155 if ($userid == 0) $userid = $USER->id;
082864f9 1156
6eb7722f 1157 /// Some differences in SQL syntax
d9eef08a 1158 if ($DB->sql_regex_supported()) {
1159 $REGEXP = $DB->sql_regex(true);
1160 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 1161 }
1162
d9eef08a 1163 $searchcond = array();
1164 $params = array();
1165 $i = 0;
e8e2d7f1 1166
c3931654
AD
1167 //preprocess search terms to check whether we have at least 1 eligible search term
1168 //if we do we can drop words around it like 'a'
1169 $dropshortwords = false;
1170 foreach ($searchterms as $searchterm) {
1171 if (strlen($searchterm) >= 2) {
1172 $dropshortwords = true;
1173 }
1174 }
1175
e8e2d7f1 1176 foreach ($searchterms as $searchterm) {
d9eef08a 1177 $i++;
1178
47586394 1179 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
d9eef08a 1180
c3931654 1181 if ($dropshortwords && strlen($searchterm) < 2) {
e8e2d7f1 1182 continue;
1183 }
6bb4875f 1184 /// Under Oracle and MSSQL, trim the + and - operators and perform
1185 /// simpler LIKE search
d9eef08a 1186 if (!$DB->sql_regex_supported()) {
1187 if (substr($searchterm, 0, 1) == '-') {
47586394 1188 $NOT = true;
d9eef08a 1189 }
6bb4875f 1190 $searchterm = trim($searchterm, '+-');
1191 }
1192
e8e2d7f1 1193 if (substr($searchterm,0,1) == "+") {
1194 $searchterm = substr($searchterm,1);
d9eef08a 1195 $searchterm = preg_quote($searchterm, '|');
3d143595 1196 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
d9eef08a 1197 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1198
e8e2d7f1 1199 } else if (substr($searchterm,0,1) == "-") {
1200 $searchterm = substr($searchterm,1);
d9eef08a 1201 $searchterm = preg_quote($searchterm, '|');
3d143595 1202 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
d9eef08a 1203 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1204
e8e2d7f1 1205 } else {
47586394 1206 $searchcond[] = $DB->sql_like("m.fullmessage", ":ss$i", false, true, $NOT);
d9eef08a 1207 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 1208 }
172186b8 1209 }
1210
d9eef08a 1211 if (empty($searchcond)) {
dd54dc31 1212 $searchcond = " ".$DB->sql_like('m.fullmessage', ':ss1', false);
ff49c389 1213 $params['ss1'] = "%";
1214 } else {
1215 $searchcond = implode(" AND ", $searchcond);
8a51efe9 1216 }
e8e2d7f1 1217
082864f9 1218 /// There are several possibilities
1219 /// 1. courseid = SITEID : The admin is searching messages by all users
1220 /// 2. courseid = ?? : A teacher is searching messages by users in
1221 /// one of their courses - currently disabled
1222 /// 3. courseid = none : User is searching their own messages;
1223 /// a. Messages from user
1224 /// b. Messages to user
1225 /// c. Messages to and from user
1226
1227 if ($courseid == SITEID) { /// admin is searching all messages
3d143595 1228 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1229 FROM {message_read} m
c3931654 1230 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1231 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1232 FROM {message} m
c3931654 1233 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
d9eef08a 1234
1235 } else if ($courseid !== 'none') {
082864f9 1236 /// This has not been implemented due to security concerns
d9eef08a 1237 $m_read = array();
1238 $m_unread = array();
e8e2d7f1 1239
082864f9 1240 } else {
531e58f1 1241
d9eef08a 1242 if ($fromme and $tome) {
1243 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
1244 $params['userid1'] = $userid;
1245 $params['userid2'] = $userid;
1246
1247 } else if ($fromme) {
1248 $searchcond .= " AND m.useridfrom=:userid";
1249 $params['userid'] = $userid;
531e58f1 1250
d9eef08a 1251 } else if ($tome) {
1252 $searchcond .= " AND m.useridto=:userid";
1253 $params['userid'] = $userid;
1254 }
531e58f1 1255
3d143595 1256 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1257 FROM {message_read} m
c3931654 1258 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
3d143595 1259 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 1260 FROM {message} m
c3931654 1261 WHERE $searchcond", $params, 0, MESSAGE_SEARCH_MAX_RESULTS);
531e58f1 1262
e8e2d7f1 1263 }
1264
082864f9 1265 /// The keys may be duplicated in $m_read and $m_unread so we can't
1266 /// do a simple concatenation
1267 $message = array();
d9eef08a 1268 foreach ($m_read as $m) {
1269 $messages[] = $m;
1270 }
1271 foreach ($m_unread as $m) {
1272 $messages[] = $m;
1273 }
e8e2d7f1 1274
1275 return (empty($messages)) ? false : $messages;
172186b8 1276}
1277
e8e2d7f1 1278
1279
1280/// Borrowed with changes from mod/forum/lib.php
1281function message_shorten_message($message, $minlength=0) {
1282// Given a post object that we already know has a long message
1283// this function truncates the message nicely to the first
1284// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1285
1286 $i = 0;
1287 $tag = false;
1288 $length = strlen($message);
1289 $count = 0;
1290 $stopzone = false;
1291 $truncate = 0;
1292 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 1293
e8e2d7f1 1294
1295 for ($i=0; $i<$length; $i++) {
1296 $char = $message[$i];
1297
1298 switch ($char) {
1299 case "<":
1300 $tag = true;
1301 break;
1302 case ">":
1303 $tag = false;
1304 break;
1305 default:
1306 if (!$tag) {
1307 if ($stopzone) {
1308 if ($char == '.' or $char == ' ') {
1309 $truncate = $i+1;
1310 break 2;
1311 }
1312 }
1313 $count++;
1314 }
1315 break;
1316 }
1317 if (!$stopzone) {
1318 if ($count > $minlength) {
1319 $stopzone = true;
1320 }
1321 }
1322 }
1323
1324 if (!$truncate) {
1325 $truncate = $i;
1326 }
1327
1328 return substr($message, 0, $truncate);
1329}
1330
38c6a928 1331
d9eef08a 1332/**
38c6a928 1333 * Given a string and an array of keywords, this function looks
1334 * for the first keyword in the string, and then chops out a
1335 * small section from the text that shows that word in context.
1336 */
1337function message_get_fragment($message, $keywords) {
1338
1339 $fullsize = 120;
1340 $halfsize = (int)($fullsize/2);
1341
1342 $message = strip_tags($message);
1343
1344 foreach ($keywords as $keyword) { // Just get the first one
1345 if ($keyword !== '') {
1346 break;
1347 }
1348 }
1349 if (empty($keyword)) { // None found, so just return start of message
1350 return message_shorten_message($message, 30);
1351 }
1352
1353 $leadin = $leadout = '';
1354
1355/// Find the start of the fragment
1356 $start = 0;
1357 $length = strlen($message);
1358
1359 $pos = strpos($message, $keyword);
1360 if ($pos > $halfsize) {
1361 $start = $pos - $halfsize;
1362 $leadin = '...';
1363 }
1364/// Find the end of the fragment
1365 $end = $start + $fullsize;
1366 if ($end > $length) {
1367 $end = $length;
1368 } else {
1369 $leadout = '...';
1370 }
1371
1372/// Pull out the fragment and format it
1373
1374 $fragment = substr($message, $start, $end - $start);
1375 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
1376 return $fragment;
1377}
1378
c8621a02 1379//retrieve the messages between two users
a813a748
AD
1380function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
1381 global $DB, $CFG;
fd1cb1e8 1382
c8621a02
AD
1383 $messages = array();
1384
1385 //we want messages sorted oldest to newest but if getting a subset of messages we need to sort
1386 //desc to get the last $limitnum messages then flip the order in php
1387 $sort = 'asc';
1388 if ($limitnum>0) {
1389 $sort = 'desc';
1390 }
1391
a813a748
AD
1392 $notificationswhere = null;
1393 //we have just moved new messages to read. If theyre here to see new messages dont hide notifications
1394 if (!$viewingnewmessages && $CFG->messaginghidereadnotifications) {
1395 $notificationswhere = 'AND notification=0';
1396 }
1397
33bd52f3
AD
1398 //prevent notifications of your own actions appearing in your own message history
1399 $ownnotificationwhere = ' AND NOT (useridfrom=? AND notification=1)';
1400
a813a748 1401 if ($messages_read = $DB->get_records_select('message_read', "((useridto = ? AND useridfrom = ?) OR
33bd52f3
AD
1402 (useridto = ? AND useridfrom = ?)) $notificationswhere $ownnotificationwhere",
1403 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02
AD
1404 "timecreated $sort", '*', 0, $limitnum)) {
1405 foreach ($messages_read as $message) {
1406 $messages[$message->timecreated] = $message;
1407 }
1408 }
33bd52f3
AD
1409 if ($messages_new = $DB->get_records_select('message', "((useridto = ? AND useridfrom = ?) OR
1410 (useridto = ? AND useridfrom = ?)) $ownnotificationwhere",
1411 array($user1->id, $user2->id, $user2->id, $user1->id, $user1->id),
c8621a02 1412 "timecreated $sort", '*', 0, $limitnum)) {
b9ee0638 1413 foreach ($messages_new as $message) {
c8621a02 1414 $messages[$message->timecreated] = $message;
b9ee0638 1415 }
1416 }
c8621a02
AD
1417
1418 //if we only want the last $limitnum messages
1419 if ($limitnum>0) {
1420 ksort($messages);
1421 $messages = array_slice($messages, count($messages)-$limitnum, $limitnum, true);
1422 }
3a11c09f 1423
b9ee0638 1424 return $messages;
1425}
1426
a813a748 1427function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
c8621a02
AD
1428 global $CFG, $OUTPUT;
1429
1430 echo $OUTPUT->box_start('center');
1431 echo '<table cellpadding="10" class="message_user_pictures"><tr>';
1432 echo '<td align="center" id="user1">';
1433 echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID));
1434 echo '<div class="heading">'.fullname($user1).'</div>';
1435 echo '</td>';
1436 echo '<td align="center">';
b11681e0
PS
1437 echo '<img src="'.$OUTPUT->pix_url('t/left').'" alt="'.get_string('from').'" />';
1438 echo '<img src="'.$OUTPUT->pix_url('t/right').'" alt="'.get_string('to').'" />';
c8621a02
AD
1439 echo '</td>';
1440 echo '<td align="center" id="user2">';
1441 echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID));
1442 echo '<div class="heading">'.fullname($user2).'</div>';
1443
1444 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1445 $incontactlist = $user2->iscontact;
1446 $isblocked = $user2->isblocked;
1447
1448 $script = null;
1449 $text = true;
1450 $icon = false;
1451
1452 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1453 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
41117b3e
AD
1454 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1455
1456 echo html_writer::tag('div', $useractionlinks, array('class'=>'useractionlinks'));
c8621a02
AD
1457 }
1458
1459 echo '</td>';
1460 echo '</tr></table>';
1461 echo $OUTPUT->box_end();
1462
1463 if (!empty($messagehistorylink)) {
1464 echo $messagehistorylink;
1465 }
1466
1467 /// Get all the messages and print them
a813a748 1468 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
c8621a02
AD
1469 $tablecontents = '';
1470
8e803c3f 1471 $current = new stdClass();
c8621a02
AD
1472 $current->mday = '';
1473 $current->month = '';
1474 $current->year = '';
1475 $messagedate = get_string('strftimetime');
1476 $blockdate = get_string('strftimedaydate');
1477 foreach ($messages as $message) {
a813a748
AD
1478 if ($message->notification) {
1479 $notificationclass = ' notification';
1480 } else {
1481 $notificationclass = null;
1482 }
c8621a02
AD
1483 $date = usergetdate($message->timecreated);
1484 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1485 $current->mday = $date['mday'];
1486 $current->month = $date['month'];
1487 $current->year = $date['year'];
1488
1489 $tablecontents .= '<div class="mdl-align heading"><a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
1490 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center').'</div>';
1491 }
1492 if ($message->useridfrom == $user1->id) {
a813a748 1493 $tablecontents .= "<div class='mdl-left left $notificationclass'>".message_format_message($message, $user1, $messagedate, $search, 'me').'</div><br />';
c8621a02 1494 } else {
a813a748 1495 $tablecontents .= "<div class='mdl-left right $notificationclass'>".message_format_message($message, $user2, $messagedate, $search, 'other').'</div><br />';
c8621a02
AD
1496 }
1497 }
1498
1499 echo html_writer::nonempty_tag('div', $tablecontents, array('class'=>'mdl-left messagehistory'));
1500 } else {
22c2732d 1501 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class'=>'mdl-align messagehistory'));
c8621a02
AD
1502 }
1503}
1504
030e3e03 1505function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 1506
1507 static $dateformat;
1508
1509 if (empty($dateformat)) {
1510 if ($format) {
1511 $dateformat = $format;
1512 } else {
54d8f804 1513 $format = get_string('strftimedatetimeshort');
acd21a2d 1514 }
b9ee0638 1515 }
acd21a2d 1516 $time = userdate($message->timecreated, $dateformat);
8e803c3f 1517 $options = new stdClass();
ff6048dd 1518 $options->para = false;
6ee2611c
AD
1519
1520 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1521 if (!empty($message->smallmessage)) {
1522 $messagetext = format_text($message->smallmessage, null, $options);
1523 } else {
1524 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1525 }
1526
14a0e7dd
AD
1527 if (!empty($message->contexturl)) {
1528 $displaytext = null;
1529 if (!empty($message->contexturlname)) {
1530 $displaytext= $message->contexturlname;
1531 } else {
1532 $displaytext= $message->contexturl;
1533 }
1534 $messagetext .= html_writer::start_tag('div',array('class'=>'messagecontext'));
1535 $messagetext .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1536 $messagetext .= html_writer::end_tag('div');
1537 }
1538
38c6a928 1539 if ($keywords) {
1540 $messagetext = highlight($keywords, $messagetext);
1541 }
14a0e7dd 1542
229f4e92 1543 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
b9ee0638 1544}
e8e2d7f1 1545
fd1cb1e8 1546/**
405f01ee 1547 * Inserts a message into the database, but also forwards it
1548 * via other means if appropriate.
1549 */
1550function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
27a39763
AD
1551 global $SITE, $CFG, $USER;
1552
8e803c3f 1553 $eventdata = new stdClass();
1560760f 1554 $eventdata->component = 'moodle';
1c50df9f 1555 $eventdata->name = 'instantmessage';
3b120e46 1556 $eventdata->userfrom = $userfrom;
1557 $eventdata->userto = $userto;
cf455865 1558 $eventdata->subject = get_string('unreadnewmessage', 'message', fullname($userfrom));
3b120e46 1559 $eventdata->fullmessage = $message;
c8621a02 1560 $eventdata->fullmessageformat = $format;
3b120e46 1561 $eventdata->fullmessagehtml = '';
6ee2611c 1562 $eventdata->smallmessage = $message;
27a39763
AD
1563
1564 $s = new stdClass();
1565 $s->sitename = $SITE->shortname;
1566 $s->url = $CFG->wwwroot.'/message/index.php?id='.$userfrom->id;//.'&user='.$userto->id;
1567
1568 $emailtagline = get_string('emailtagline', 'message', $s);
6ee2611c
AD
1569 if (!empty($eventdata->fullmessage)) {
1570 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1571 }
6ee2611c
AD
1572 if (!empty($eventdata->fullmessagehtml)) {
1573 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1574 }
27a39763 1575
a1b53dcf 1576 $eventdata->timecreated = time();
7c7d3afa 1577 return message_send($eventdata);
405f01ee 1578}
e8e2d7f1 1579
c135a425 1580
fd1cb1e8 1581/**
c135a425 1582 * Returns a list of all user ids who have used messaging in the site
1583 * This was the simple way to code the SQL ... is it going to blow up
1584 * on large datasets?
1585 */
1586function message_get_participants() {
fd1cb1e8 1587 global $CFG, $DB;
1588
76b0191c 1589 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1590 UNION SELECT useridto as id,1 FROM {message}
1591 UNION SELECT useridfrom as id,1 FROM {message_read}
1592 UNION SELECT useridto as id,1 FROM {message_read}
1593 UNION SELECT userid as id,1 FROM {message_contacts}
1594 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1595}
1596
f46b6587 1597/**
1d422980 1598 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 1599 * block links etc
7cb1a1ad 1600 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
f46b6587 1601 * @param $incontactlist is the user a contact of ours?
c8621a02 1602 * @param $selectcontacturl string the url to send the user to when a contact's name is clicked
f46b6587 1603 */
c8621a02
AD
1604function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true) {
1605 global $OUTPUT, $USER;
f46b6587 1606 $fullname = fullname($contact);
1607 $fullnamelink = $fullname;
1608
1609 /// are there any unread messages for this contact?
1610 if ($contact->messagecount > 0 ){
1611 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1612 }
1613
c8621a02 1614 $strcontact = $strblock = $strhistory = null;
f46b6587 1615
c8621a02
AD
1616 if ($showactionlinks) {
1617 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
1618 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
1619 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
f46b6587 1620 }
1621
f46b6587 1622 echo '<tr><td class="pix">';
812dbaf7 1623 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
f46b6587 1624 echo '</td>';
1625 echo '<td class="contact">';
1d422980 1626
40a26286 1627 $popupoptions = array(
c8621a02
AD
1628 'height' => MESSAGE_DISCUSSION_HEIGHT,
1629 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 1630 'menubar' => false,
1631 'location' => false,
1632 'status' => true,
1633 'scrollbars' => true,
1634 'resizable' => true);
1635
c8621a02
AD
1636 $link = $action = null;
1637 if (!empty($selectcontacturl)) {
1638 $link = new moodle_url($selectcontacturl.'&'.CONTACT_ID.'='.$contact->id);
1639 } else {
06d30c43
AD
1640 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
1641 $link = new moodle_url("/message/index.php?id=$contact->id");
c8621a02
AD
1642 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1643 }
9bf16314 1644 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
f46b6587 1645
1646 echo '</td>';
1647 echo '<td class="link">&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory.'</td>';
1648 echo '</tr>';
1649}
1650
c8621a02
AD
1651function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1652 $strcontact = '';
1653
1654 if($incontactlist){
1655 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
1656 } else if ($isblocked) {
1657 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1658 } else{
1659 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1660 }
1661
1662 return $strcontact;
1663}
1664
1665function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1666 $strblock = '';
1667
1668 //commented out to allow the user to block a contact without having to remove them first
1669 /*if ($incontactlist) {
1670 //$strblock = '';
1671 } else*/
1672 if ($isblocked) {
1673 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
1674 } else{
1675 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
1676 }
1677
1678 return $strblock;
1679}
1680
6bdf4c99 1681 /**
1682 * Moves unread messages from message table to message_read for a given from user
1683 * @param object $userid User id
1684 * @return boolean success
1685 */
1686function message_move_userfrom_unread2read($userid) {
1687
1688 global $DB;
1689
71666cf3 1690 // move all unread messages from message table to message_read
6bdf4c99 1691 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1692 foreach ($messages as $message) {
ee7cd81a 1693 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
6bdf4c99 1694 }
1695 }
1696 return true;
1697}
1698
1c50df9f 1699function message_get_popup_messages($destuserid, $fromuserid=NULL){
1700 global $DB;
1d422980 1701
1c50df9f 1702 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1703
a1b53dcf 1704 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1c50df9f 1705
1706 //for every message to process check if it's for current user and process
1707 $messages = array();
1708 foreach ($messagesproc as $msgp){
1709 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1710 if ($fromuserid){
1711 $query['useridfrom'] = $fromuserid;
1712 }
1713 if ($message = $DB->get_record('message', $query)){
1714 $messages[] = $message;
1715 /// Move the entry to the other table
1716 $message->timeread = time();
1717 $messageid = $message->id;
1718 unset($message->id);
1d422980 1719
1c50df9f 1720 //delete what we've processed and check if can move message
1721 $DB->delete_records('message_working', array('id' => $msgp->id));
1722 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
ee7cd81a 1723 message_mark_message_read($message, time(), true);
1c50df9f 1724 }
1725 }
1726 }
1727 return $messages;
c8621a02
AD
1728}
1729
ee7cd81a
AD
1730/**
1731* marks ALL messages being sent from $fromuserid to $touserid as read
1732* @param int $touserid the id of the message recipient
1733* @param int $fromuserid the id of the message sender
1734* @return void
1735*/
1560760f 1736function message_mark_messages_read($touserid, $fromuserid){
c8621a02
AD
1737 global $DB;
1738
ee7cd81a 1739 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
1560760f
AD
1740 $messages = $DB->get_recordset_sql($sql, array('useridto'=>$touserid,'useridfrom'=>$fromuserid));
1741
c8621a02 1742 foreach ($messages as $message) {
ee7cd81a
AD
1743 message_mark_message_read($message, time());
1744 }
1745}
1746
1747/**
1748* Mark a single message as read
1749* @param message an object with an object property ie $message->id which is an id in the message table
1750* @param int $timeread the timestamp for when the message should be marked read. Usually time().
1751* @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
1752* @return void
1753*/
1754function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
1755 global $DB;
1756
1757 $message->timeread = $timeread;
c8621a02 1758
ee7cd81a
AD
1759 $messageid = $message->id;
1760 unset($message->id);//unset because it will get a new id on insert into message_read
1560760f 1761
ee7cd81a
AD
1762 //If any processors have pending actions abort them
1763 if (!$messageworkingempty) {
1764 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
c8621a02 1765 }
ee7cd81a
AD
1766 $DB->insert_record('message_read', $message);
1767 $DB->delete_records('message', array('id' => $messageid));
65fbace7 1768}