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