MDL-26333 dml - fix test (AS not in tables/views)
[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);
31da70cc 143
32ef43e1
AD
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
20222a3d
EL
272 $rs = $DB->get_recordset_sql($contactsql, array($user1->id, $user1->id));
273 foreach ($rs as $rd) {
274 if ($rd->lastaccess >= $timefrom) {
275 // they have been active recently, so are counted online
276 $onlinecontacts[] = $rd;
277
278 } else {
279 $offlinecontacts[] = $rd;
280 }
c8621a02 281
20222a3d
EL
282 if (!empty($user2) && $user2->id==$rd->id) {
283 $user2->iscontact = true;
e8e2d7f1 284 }
f46b6587 285 }
20222a3d 286 $rs->close();
f46b6587 287
f46b6587 288 // get messages from anyone who isn't in our contact list and count the number
289 // of messages we have from each of them
3a11c09f 290 $strangersql = "SELECT $userfields, count(m.id) as messagecount
fd1cb1e8 291 FROM {message} m
292 JOIN {user} u ON u.id = m.useridfrom
293 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
1d422980 294 WHERE mc.id IS NULL AND m.useridto = ?
3a11c09f 295 GROUP BY $userfields
bbe973da 296 ORDER BY u.firstname ASC";
fd1cb1e8 297
20222a3d
EL
298 $rs = $DB->get_recordset_sql($strangersql, array($USER->id));
299 foreach ($rs as $rd) {
300 $strangers[] = $rd;
e8e2d7f1 301 }
20222a3d 302 $rs->close();
e8e2d7f1 303
c8621a02
AD
304 return array($onlinecontacts, $offlinecontacts, $strangers);
305}
306
a402c309 307function message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refresh=true, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null, $user2=null) {
c8621a02
AD
308 global $CFG, $PAGE, $OUTPUT;
309
f46b6587 310 $countonlinecontacts = count($onlinecontacts);
311 $countofflinecontacts = count($offlinecontacts);
312 $countstrangers = count($strangers);
313
a1157dda 314 if ($countonlinecontacts + $countofflinecontacts == 0) {
669be60c 315 echo '<div class="heading">';
65ef518b 316 print_string('contactlistempty', 'message');
a1157dda 317 echo '</div>';
65c7853e
AD
318 //echo '<div class="note">';
319 //print_string('addsomecontacts', 'message', message_remove_url_params($PAGE->url).'?tab=search');
320 //echo '</div>';
65ef518b 321 }
322
04b687e8 323 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
531e58f1 324
c8621a02
AD
325 if (!empty($titletodisplay)) {
326 echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
327 }
328
f46b6587 329 if($countonlinecontacts) {
330 /// print out list of online contacts
531e58f1 331
c8621a02
AD
332 if (empty($titletodisplay)) {
333 echo '<tr><td colspan="3" class="heading">';
334 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
335 echo '</td></tr>';
336 }
531e58f1 337
f46b6587 338 foreach ($onlinecontacts as $contact) {
c8621a02 339 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
a402c309 340 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks, $user2);
c8621a02 341 }
65ef518b 342 }
f46b6587 343 }
531e58f1 344
f46b6587 345 if ($countofflinecontacts) {
346 /// print out list of offline contacts
531e58f1 347
c8621a02
AD
348 if (empty($titletodisplay)) {
349 echo '<tr><td colspan="3" class="heading">';
350 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
351 echo '</td></tr>';
352 }
576ad290 353
f46b6587 354 foreach ($offlinecontacts as $contact) {
c8621a02 355 if ($minmessages==0 || $contact->messagecount>=$minmessages) {
a402c309 356 message_print_contactlist_user($contact, IS_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks, $user2);
c8621a02 357 }
65ef518b 358 }
f46b6587 359 echo '<tr><td colspan="3">&nbsp;</td></tr>';
360 }
65ef518b 361
f46b6587 362 /// print out list of incoming contacts
363 if ($countstrangers) {
364 echo '<tr><td colspan="3" class="heading">';
365 echo get_string('incomingcontacts', 'message', $countstrangers);
366 echo '</td></tr>';
531e58f1 367
f46b6587 368 foreach ($strangers as $stranger) {
65fbace7 369 if ($minmessages==0 || $stranger->messagecount>=$minmessages) {
a402c309 370 message_print_contactlist_user($stranger, IS_NOT_CONTACT, IS_NOT_BLOCKED, $contactselecturl, $showactionlinks, $user2);
c8621a02 371 }
669be60c 372 }
f46b6587 373 }
531e58f1 374
f46b6587 375 echo '</table>';
65ef518b 376
f46b6587 377 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
378 echo '<div class="note">(';
379 print_string('addsomecontactsincoming', 'message');
380 echo ')</div>';
65ef518b 381 }
b9ee0638 382
531e58f1 383 echo '<br />';
a9d9b46a 384
c8621a02
AD
385 if ($refresh) {
386 $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
a1b53dcf 387
c8621a02
AD
388 echo $OUTPUT->container_start('messagejsautorefresh note center');
389 echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
390 echo $OUTPUT->container_end();
a1b53dcf 391
4652f2d4
AD
392 echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
393 echo $OUTPUT->single_button(message_remove_url_params($PAGE->url), get_string('refresh'));
394 echo $OUTPUT->container_end();
395 }
e8e2d7f1 396}
397
43240ea1
AD
398function message_print_usergroup_selector($usergroup, &$courses, &$coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) {
399 $strblockedusers = null;
65c7853e 400 $options = array();
c8621a02
AD
401
402 if ($countunreadtotal>0) { //if there are unread messages
65c7853e 403 $options[VIEW_UNREAD_MESSAGES] = $strunreadmessages;
c8621a02
AD
404 }
405
c8621a02
AD
406 $strcontacts = get_string('mycontacts', 'message');
407 $options[VIEW_CONTACTS] = $strcontacts;
408
409 if (!empty($courses)) {
410 $courses_options = array();
411
412 foreach($courses as $course) {
413 if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
248403fa 414 $courses_options[VIEW_COURSE.$course->id] = $course->shortname;
c8621a02
AD
415 }
416 }
417
418 if (!empty($courses_options)) {
419 $options[] = array(get_string('courses')=>$courses_options);
420 }
421 }
422
31c532d0
AD
423 if ($countblocked>0) {
424 $strblockedusers = get_string('blockedusers','message', $countblocked);
425 $options[VIEW_BLOCKED] = $strblockedusers;
426 }
427
c8621a02 428 echo html_writer::start_tag('form', array('id'=>'usergroupform','method'=>'get','action'=>''));
229f4e92
AD
429 echo html_writer::start_tag('fieldset');
430 echo html_writer::select($options, 'usergroup', $usergroup, false, array('id'=>'usergroup','onchange'=>'this.form.submit()'));
431 echo html_writer::end_tag('fieldset');
c8621a02
AD
432 echo html_writer::end_tag('form');
433}
434
435function message_get_course_contexts(&$courses) {
436 $coursecontexts = array();
437
438 foreach($courses as $course) {
439 $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
440 }
441
442 return $coursecontexts;
443}
444
cee92282
AD
445/**
446 * strip off action parameters like 'removecontact'
447 */
c8621a02 448function message_remove_url_params($moodleurl) {
c8621a02
AD
449 $newurl = new moodle_url($moodleurl);
450 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
451 return $newurl->out();
452}
453
e8e2d7f1 454
e8e2d7f1 455/// $messagearray is an array of objects
456/// $field is a valid property of object
457/// $value is the value $field should equal to be counted
458/// if $field is empty then return count of the whole array
459/// if $field is non-existent then return 0;
460function message_count_messages($messagearray, $field='', $value='') {
461 if (!is_array($messagearray)) return 0;
462 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 463
e8e2d7f1 464 $count = 0;
465 foreach ($messagearray as $message) {
466 $count += ($message->$field == $value) ? 1 : 0;
467 }
468 return $count;
172186b8 469}
470
c8621a02
AD
471/**
472 * Returns the count of unread messages for user. Either from a specific user or from all users.
473 * @global <type> $USER
474 * @global <type> $DB
475 * @param object $user1 the first user. Defaults to $USER
476 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
477 * @return int the count of $user1's unread messages
478 */
479function message_count_unread_messages($user1=null, $user2=null) {
480 global $USER, $DB;
e8e2d7f1 481
c8621a02
AD
482 if (empty($user1)) {
483 $user1 = $USER;
484 }
485
486 if (!empty($user2)) {
487 return $DB->count_records_select('message', "useridto = ? AND useridfrom = ?",
488 array($user1->id, $user2->id), "COUNT('id')");
489 } else {
490 return $DB->count_records_select('message', "useridto = ?",
491 array($user1->id), "COUNT('id')");
492 }
493}
494
495function message_count_blocked_users($user1=null) {
496 global $USER, $DB;
497
498 if (empty($user1)) {
499 $user1 = $USER;
500 }
501
502 $sql = "SELECT count(mc.id)
503 FROM {message_contacts} mc
504 WHERE mc.userid = :userid AND mc.blocked = 1";
505 $params = array('userid'=>$user1->id);
506
507 return $DB->count_records_sql($sql, $params);
508}
509
510/**
511 *
512 * @global <type> $USER
513 * @global <type> $PAGE
514 * @global <type> $OUTPUT
515 * @param boolean advancedsearch show basic or advanced search form
516 * @return boolean was a search performed?
517 */
518function message_print_search($advancedsearch = false, $user1=null) {
519 global $USER, $PAGE, $OUTPUT;
520
521 $frm = data_submitted();
3a11c09f 522
c8621a02
AD
523 $doingsearch = false;
524 if ($frm) {
31da70cc
PS
525 if (confirm_sesskey()) {
526 $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
527 } else {
528 $frm = false;
529 }
c8621a02 530 }
531e58f1 531
c8621a02
AD
532 if (!empty($frm->combinedsearch)) {
533 $combinedsearchstring = $frm->combinedsearch;
534 } else {
a813a748
AD
535 //$combinedsearchstring = get_string('searchcombined','message').'...';
536 $combinedsearchstring = '';
c8621a02 537 }
531e58f1 538
a813a748 539 //$PAGE->requires->js_init_call('M.core_message.init_search_page', array($combinedsearchstring));
531e58f1 540
c8621a02
AD
541 if ($doingsearch) {
542 if ($advancedsearch) {
3a11c09f 543
c8621a02
AD
544 $messagesearch = '';
545 if (!empty($frm->keywords)) {
546 $messagesearch = $frm->keywords;
547 }
548 $personsearch = '';
549 if (!empty($frm->name)) {
550 $personsearch = $frm->name;
551 }
552 include('search_advanced.html');
553 } else {
554 include('search.html');
555 }
556
557 $showicontext = false;
558 message_print_search_results($frm, $showicontext, $user1);
559
560 return true;
172186b8 561 } else {
1ac41751 562/*
531e58f1 563/// unfinished buggy code disabled in search.html anyway
d76a5a7f 564 // find all courses this use has readallmessages capabilities in
565 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
172186b8 566 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
567 $cs = '<select name="courseselect">';
568 foreach ($teachers as $tcourse) {
d76a5a7f 569 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
172186b8 570 }
571 $cs .= '</select>';
572 }
1ac41751 573*/
c8621a02
AD
574
575 if ($advancedsearch) {
576 $personsearch = $messagesearch = '';
577 include('search_advanced.html');
578 } else {
579 include('search.html');
580 }
581 return false;
172186b8 582 }
583}
584
585function message_print_settings() {
3dcb80cb 586 global $USER, $OUTPUT, $PAGE;
531e58f1 587
d6b4fed0 588 if ($frm = data_submitted() and confirm_sesskey()) {
acef58f4 589
e8e2d7f1 590 $pref = array();
e8e2d7f1 591 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
3f85157b 592 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
e8e2d7f1 593
594 set_user_preferences($pref);
531e58f1 595
c8621a02 596 redirect(message_remove_url_params($PAGE->url), get_string('settingssaved', 'message'), 1);
e8e2d7f1 597 }
598
fd7006f6 599 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
3f85157b 600 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
531e58f1 601
e8e2d7f1 602 include('settings.html');
603}
604
605
606
607function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 608 global $USER, $DB;
531e58f1 609
fd1cb1e8 610 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
e8e2d7f1 611 return false;
612 }
531e58f1 613
fd1cb1e8 614 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
e8e2d7f1 615 /// record already exists - we may be changing blocking status
531e58f1 616
e8e2d7f1 617 if ($contact->blocked !== $blocked) {
618 /// change to blocking status
619 $contact->blocked = $blocked;
fd1cb1e8 620 return $DB->update_record('message_contacts', $contact);
e8e2d7f1 621 } else {
622 /// no changes to blocking status
623 return true;
624 }
531e58f1 625
172186b8 626 } else {
e8e2d7f1 627 /// new contact record
628 unset($contact);
629 $contact->userid = $USER->id;
630 $contact->contactid = $contactid;
631 $contact->blocked = $blocked;
fd1cb1e8 632 return $DB->insert_record('message_contacts', $contact, false);
172186b8 633 }
634}
635
e8e2d7f1 636function message_remove_contact($contactid) {
fd1cb1e8 637 global $USER, $DB;
638 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 639}
640
641function message_unblock_contact($contactid) {
fd1cb1e8 642 global $USER, $DB;
643 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 644}
645
646function message_block_contact($contactid) {
647 return message_add_contact($contactid, 1);
648}
649
650function message_get_contact($contactid) {
fd1cb1e8 651 global $USER, $DB;
652 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 653}
531e58f1 654
e8e2d7f1 655
656
c8621a02
AD
657function message_print_search_results($frm, $showicontext=false, $user1=null) {
658 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
659
660 if (empty($user1)) {
661 $user1 = $USER;
662 }
e8e2d7f1 663
c8621a02 664 echo '<div class="mdl-left">';
e8e2d7f1 665
c8621a02
AD
666 $personsearch = false;
667 $personsearchstring = null;
e8e2d7f1 668 if (!empty($frm->personsubmit) and !empty($frm->name)) {
c8621a02
AD
669 $personsearch = true;
670 $personsearchstring = $frm->name;
671 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
672 $personsearch = true;
673 $personsearchstring = $frm->combinedsearch;
674 }
531e58f1 675
c8621a02
AD
676 /// search for person
677 if ($personsearch) {
b71d4dd2 678 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 679 $users = array();
df997f84 680 $mycourses = enrol_get_my_courses();
e8e2d7f1 681 foreach ($mycourses as $mycourse) {
c8621a02 682 if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
e8e2d7f1 683 foreach ($susers as $suser) $users[$suser->id] = $suser;
684 }
685 }
686 } else {
c8621a02 687 $users = message_search_users(SITEID, $personsearchstring);
e8e2d7f1 688 }
689
690 if (!empty($users)) {
c3931654
AD
691 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
692 echo get_string('userssearchresults', 'message', count($users));
693 echo html_writer::end_tag('p');
694
c8621a02 695 echo '<table class="messagesearchresults">';
e8e2d7f1 696 foreach ($users as $user) {
531e58f1 697
7390832c 698 if ( $user->contactlistid ) {
699 if ($user->blocked == 0) { /// not blocked
c8621a02
AD
700 $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
701 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
e8e2d7f1 702 } else { // blocked
c8621a02
AD
703 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
704 $strblock = message_contact_link($user->id, 'unblock', true, null, $showicontext);
e8e2d7f1 705 }
e8e2d7f1 706 } else {
c8621a02
AD
707 $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
708 $strblock = message_contact_link($user->id, 'block', true, null, $showicontext);
709 }
710
711 //should we show just the icon or icon and text?
712 $histicontext = 'icon';
713 if ($showicontext) {
714 $histicontext = 'both';
e8e2d7f1 715 }
c8621a02 716 $strhistory = message_history_link($USER->id, $user->id, true, '', '', $histicontext);
531e58f1 717
669be60c 718 echo '<tr><td class="pix">';
812dbaf7 719 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e8e2d7f1 720 echo '</td>';
669be60c 721 echo '<td class="contact">';
40a26286 722 $popupoptions = array(
c8621a02
AD
723 'height' => MESSAGE_DISCUSSION_HEIGHT,
724 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 725 'menubar' => false,
726 'location' => false,
727 'status' => true,
728 'scrollbars' => true,
729 'resizable' => true);
730
02f2c7bd 731 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
732 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
733 $action = null;
9bf16314 734 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
576ad290 735
e8e2d7f1 736 echo '</td>';
531e58f1 737
669be60c 738 echo '<td class="link">'.$strcontact.'</td>';
739 echo '<td class="link">'.$strblock.'</td>';
740 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 741 echo '</tr>';
742 }
743 echo '</table>';
531e58f1 744
e8e2d7f1 745 } else {
c3931654 746 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
c8621a02 747 echo get_string('userssearchresults', 'message', 0).'<br /><br />';
c3931654 748 echo html_writer::end_tag('p');
e8e2d7f1 749 }
c8621a02 750 }
531e58f1 751
c8621a02
AD
752 // search messages for keywords
753 $messagesearch = false;
754 $messagesearchstring = null;
755 if (!empty($frm->keywords)) {
756 $messagesearch = true;
757 $messagesearchstring = clean_text(trim($frm->keywords));
758 } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
759 $messagesearch = true;
760 $messagesearchstring = clean_text(trim($frm->combinedsearch));
761 }
531e58f1 762
c8621a02
AD
763 if ($messagesearch) {
764 if ($messagesearchstring) {
765 $keywords = explode(' ', $messagesearchstring);
ff49c389 766 } else {
767 $keywords = array();
768 }
e8e2d7f1 769 $tome = false;
770 $fromme = false;
771 $courseid = 'none';
772
c8621a02
AD
773 if (empty($frm->keywordsoption)) {
774 $frm->keywordsoption = 'allmine';
775 }
776
e8e2d7f1 777 switch ($frm->keywordsoption) {
778 case 'tome':
779 $tome = true;
780 break;
781 case 'fromme':
782 $fromme = true;
783 break;
784 case 'allmine':
785 $tome = true;
786 $fromme = true;
787 break;
788 case 'allusers':
789 $courseid = SITEID;
790 break;
791 case 'courseusers':
792 $courseid = $frm->courseid;
793 break;
794 default:
795 $tome = true;
796 $fromme = true;
797 }
798
799 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 800
e8e2d7f1 801 /// get a list of contacts
fd1cb1e8 802 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
082864f9 803 $contacts = array();
804 }
e8e2d7f1 805
082864f9 806 /// print heading with number of results
c3931654
AD
807 echo html_writer::start_tag('p', array('class'=>'heading searchresultcount'));
808 $countresults = count($messages);
809 if ($countresults==MESSAGE_SEARCH_MAX_RESULTS) {
810 echo get_string('keywordssearchresultstoomany', 'message', $countresults).' ("'.s($messagesearchstring).'")';
811 } else {
a813a748 812 echo get_string('keywordssearchresults', 'message', $countresults);
c3931654
AD
813 }
814 echo html_writer::end_tag('p');
082864f9 815
816 /// print table headings
c8621a02 817 echo '<table class="messagesearchresults" cellspacing="0">';
c3931654
AD
818
819 $headertdstart = html_writer::start_tag('td', array('class'=>'messagesearchresultscol'));
820 $headertdend = html_writer::end_tag('td');
082864f9 821 echo '<tr>';
c3931654
AD
822 echo $headertdstart.get_string('from').$headertdend;
823 echo $headertdstart.get_string('to').$headertdend;
824 echo $headertdstart.get_string('message', 'message').$headertdend;
825 echo $headertdstart.get_string('timesent', 'message').$headertdend;
082864f9 826 echo "</tr>\n";
827
828 $blockedcount = 0;
54d8f804 829 $dateformat = get_string('strftimedatetimeshort');
38c6a928 830 $strcontext = get_string('context', 'message');
e8e2d7f1 831 foreach ($messages as $message) {
082864f9 832
833 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 834 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 835 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
836 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
837 )
838 ) {
839 $blockedcount ++;
e8e2d7f1 840 continue;
841 }
531e58f1 842
082864f9 843 /// load up user to record
844 if ($message->useridto !== $USER->id) {
fd1cb1e8 845 $userto = $DB->get_record('user', array('id'=>$message->useridto));
531e58f1 846 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 847 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 848 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 849 ($contacts[$message->useridto]->blocked == 1) );
850 } else {
851 $userto = false;
852 $tocontact = false;
853 $toblocked = false;
854 }
531e58f1 855
082864f9 856 /// load up user from record
857 if ($message->useridfrom !== $USER->id) {
fd1cb1e8 858 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
531e58f1 859 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 860 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 861 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 862 ($contacts[$message->useridfrom]->blocked == 1) );
863 } else {
864 $userfrom = false;
865 $fromcontact = false;
866 $fromblocked = false;
867 }
868
e520509a 869 /// find date string for this message
870 $date = usergetdate($message->timecreated);
871 $datestring = $date['year'].$date['mon'].$date['mday'];
872
082864f9 873 /// print out message row
874 echo '<tr valign="top">';
669be60c 875 echo '<td class="contact">';
c8621a02 876 message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
e8e2d7f1 877 echo '</td>';
669be60c 878 echo '<td class="contact">';
c8621a02 879 message_print_user($userto, $tocontact, $toblocked, $showicontext);
e8e2d7f1 880 echo '</td>';
3d143595 881 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
669be60c 882 echo '<br /><div class="link">';
c8621a02 883
71666cf3 884 //find the user involved that isn't the current user
c8621a02
AD
885 $user2id = null;
886 if ($user1->id == $message->useridto) {
887 $user2id = $message->useridfrom;
888 } else {
889 $user2id = $message->useridto;
890 }
891 message_history_link($user1->id, $user2id, false,
892 $messagesearchstring, 'm'.$message->id, $strcontext);
f520438c 893 echo '</div>';
e520509a 894 echo '</td>';
669be60c 895 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 896 echo "</tr>\n";
897 }
531e58f1 898
e8e2d7f1 899
e520509a 900 if ($blockedcount > 0) {
901 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
902 }
e8e2d7f1 903 echo '</table>';
531e58f1 904
e8e2d7f1 905 } else {
f20b0afa 906 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', 0).'</p>';
e8e2d7f1 907 }
c8621a02 908 }
e8e2d7f1 909
c8621a02 910 if (!$personsearch && !$messagesearch) {
71666cf3 911 //they didn't enter any search terms
aa9a6867 912 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 913 }
914
31c532d0
AD
915 //echo '<br />';
916 //echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('tab' => 'search')), get_string('newsearch', 'message'));
e8e2d7f1 917
918 echo '</div>';
919}
920
921
c8621a02 922function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
7cb1a1ad 923 global $USER, $OUTPUT;
1d422980 924
082864f9 925 if ($user === false) {
812dbaf7 926 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
082864f9 927 } else {
a813a748 928 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e520509a 929 echo '&nbsp;';
c8621a02
AD
930
931 $return = false;
932 $script = null;
082864f9 933 if ($iscontact) {
c8621a02 934 message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
082864f9 935 } else {
c8621a02 936 message_contact_link($user->id, 'add', $return, $script, $includeicontext);
082864f9 937 }
938 echo '&nbsp;';
939 if ($isblocked) {
c8621a02 940 message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
082864f9 941 } else {
c8621a02 942 message_contact_link($user->id, 'block', $return, $script, $includeicontext);
082864f9 943 }
e520509a 944 echo '<br />';
576ad290 945
40a26286 946 $popupoptions = array(
c8621a02
AD
947 'height' => MESSAGE_DISCUSSION_HEIGHT,
948 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 949 'menubar' => false,
950 'location' => false,
951 'status' => true,
952 'scrollbars' => true,
953 'resizable' => true);
954
02f2c7bd 955 $link = new moodle_url("/message/index.php?id=$user->id");
c8621a02
AD
956 //$action = new popup_action('click', $link, "message_$user->id", $popupoptions);
957 $action = null;
9bf16314 958 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
40a26286 959
082864f9 960 }
961}
962
963
964/// linktype can be: add, remove, block, unblock
c8621a02
AD
965function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
966 global $USER, $CFG, $OUTPUT, $PAGE;
e520509a 967
6898e848 968 //hold onto the strings as we're probably creating a bunch of links
e520509a 969 static $str;
970
c8621a02 971 if (empty($script)) {
cee92282 972 //strip off previous action params like 'removecontact'
4090a30f 973 $script = message_remove_url_params($PAGE->url);
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
f3832596 1339 $fullsize = 160;
38c6a928 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
2846b9a6
AD
1419 ksort($messages);
1420 $messagecount = count($messages);
1421 if ($limitnum>0 && $messagecount>$limitnum) {
1422 $messages = array_slice($messages, $messagecount-$limitnum, $limitnum, true);
c8621a02 1423 }
3a11c09f 1424
b9ee0638 1425 return $messages;
1426}
1427
a813a748 1428function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $messagehistorylink=false, $viewingnewmessages=false) {
c8621a02
AD
1429 global $CFG, $OUTPUT;
1430
1431 echo $OUTPUT->box_start('center');
1432 echo '<table cellpadding="10" class="message_user_pictures"><tr>';
1433 echo '<td align="center" id="user1">';
1434 echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID));
1435 echo '<div class="heading">'.fullname($user1).'</div>';
1436 echo '</td>';
1437 echo '<td align="center">';
b11681e0
PS
1438 echo '<img src="'.$OUTPUT->pix_url('t/left').'" alt="'.get_string('from').'" />';
1439 echo '<img src="'.$OUTPUT->pix_url('t/right').'" alt="'.get_string('to').'" />';
c8621a02
AD
1440 echo '</td>';
1441 echo '<td align="center" id="user2">';
1442 echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID));
1443 echo '<div class="heading">'.fullname($user2).'</div>';
1444
1445 if (isset($user2->iscontact) && isset($user2->isblocked)) {
1446 $incontactlist = $user2->iscontact;
1447 $isblocked = $user2->isblocked;
1448
1449 $script = null;
1450 $text = true;
1451 $icon = false;
1452
1453 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
1454 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $user2, $script, $text, $icon);
41117b3e
AD
1455 $useractionlinks = $strcontact.'&nbsp;|'.$strblock;
1456
1457 echo html_writer::tag('div', $useractionlinks, array('class'=>'useractionlinks'));
c8621a02
AD
1458 }
1459
1460 echo '</td>';
1461 echo '</tr></table>';
1462 echo $OUTPUT->box_end();
1463
1464 if (!empty($messagehistorylink)) {
1465 echo $messagehistorylink;
1466 }
1467
1468 /// Get all the messages and print them
a813a748 1469 if ($messages = message_get_history($user1, $user2, $messagelimit, $viewingnewmessages)) {
c8621a02
AD
1470 $tablecontents = '';
1471
8e803c3f 1472 $current = new stdClass();
c8621a02
AD
1473 $current->mday = '';
1474 $current->month = '';
1475 $current->year = '';
1476 $messagedate = get_string('strftimetime');
1477 $blockdate = get_string('strftimedaydate');
1478 foreach ($messages as $message) {
a813a748
AD
1479 if ($message->notification) {
1480 $notificationclass = ' notification';
1481 } else {
1482 $notificationclass = null;
1483 }
c8621a02
AD
1484 $date = usergetdate($message->timecreated);
1485 if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
1486 $current->mday = $date['mday'];
1487 $current->month = $date['month'];
1488 $current->year = $date['year'];
1489
1490 $tablecontents .= '<div class="mdl-align heading"><a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
1491 $tablecontents .= $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center').'</div>';
1492 }
1493 if ($message->useridfrom == $user1->id) {
a813a748 1494 $tablecontents .= "<div class='mdl-left left $notificationclass'>".message_format_message($message, $user1, $messagedate, $search, 'me').'</div><br />';
c8621a02 1495 } else {
a813a748 1496 $tablecontents .= "<div class='mdl-left right $notificationclass'>".message_format_message($message, $user2, $messagedate, $search, 'other').'</div><br />';
c8621a02
AD
1497 }
1498 }
1499
1500 echo html_writer::nonempty_tag('div', $tablecontents, array('class'=>'mdl-left messagehistory'));
1501 } else {
22c2732d 1502 echo html_writer::nonempty_tag('div', '('.get_string('nomessagesfound', 'message').')', array('class'=>'mdl-align messagehistory'));
c8621a02
AD
1503 }
1504}
1505
030e3e03 1506function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 1507
1508 static $dateformat;
1509
1510 if (empty($dateformat)) {
1511 if ($format) {
1512 $dateformat = $format;
1513 } else {
54d8f804 1514 $format = get_string('strftimedatetimeshort');
acd21a2d 1515 }
b9ee0638 1516 }
acd21a2d 1517 $time = userdate($message->timecreated, $dateformat);
8e803c3f 1518 $options = new stdClass();
ff6048dd 1519 $options->para = false;
6ee2611c
AD
1520
1521 //if supplied display small messages as fullmessage may contain boilerplate text that shouldnt appear in the messaging UI
1522 if (!empty($message->smallmessage)) {
2846b9a6 1523 $messagetext = format_text($message->smallmessage, FORMAT_MOODLE, $options);
6ee2611c
AD
1524 } else {
1525 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
1526 }
1527
14a0e7dd
AD
1528 if (!empty($message->contexturl)) {
1529 $displaytext = null;
1530 if (!empty($message->contexturlname)) {
1531 $displaytext= $message->contexturlname;
1532 } else {
1533 $displaytext= $message->contexturl;
1534 }
1535 $messagetext .= html_writer::start_tag('div',array('class'=>'messagecontext'));
1536 $messagetext .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
1537 $messagetext .= html_writer::end_tag('div');
1538 }
1539
38c6a928 1540 if ($keywords) {
1541 $messagetext = highlight($keywords, $messagetext);
1542 }
14a0e7dd 1543
229f4e92 1544 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a> <span class="time">'.$time.'</span>: <span class="content">'.$messagetext.'</span></div>';
b9ee0638 1545}
e8e2d7f1 1546
fd1cb1e8 1547/**
405f01ee 1548 * Inserts a message into the database, but also forwards it
1549 * via other means if appropriate.
1550 */
1551function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
27a39763 1552 global $SITE, $CFG, $USER;
4ffa1463 1553
8e803c3f 1554 $eventdata = new stdClass();
1560760f 1555 $eventdata->component = 'moodle';
1c50df9f 1556 $eventdata->name = 'instantmessage';
3b120e46 1557 $eventdata->userfrom = $userfrom;
1558 $eventdata->userto = $userto;
4ffa1463
AD
1559
1560 //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
1561 $eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
1562
156205fc
AD
1563 if ($format==FORMAT_HTML) {
1564 $eventdata->fullmessage = '';
1565 $eventdata->fullmessagehtml = $message;
1566 } else {
1567 $eventdata->fullmessage = $message;
1568 $eventdata->fullmessagehtml = '';
1569 }
31da70cc 1570
c8621a02 1571 $eventdata->fullmessageformat = $format;
156205fc 1572 $eventdata->smallmessage = strip_tags($message);//strip just in case there are is any html that would break the popup notification
27a39763
AD
1573
1574 $s = new stdClass();
1575 $s->sitename = $SITE->shortname;
536a56e7 1576 $s->url = $CFG->wwwroot.'/message/index.php?user='.$userto->id.'&id='.$userfrom->id;
27a39763 1577
4ffa1463 1578 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $userto->lang);
6ee2611c
AD
1579 if (!empty($eventdata->fullmessage)) {
1580 $eventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n".$emailtagline;
1581 }
6ee2611c
AD
1582 if (!empty($eventdata->fullmessagehtml)) {
1583 $eventdata->fullmessagehtml .= "<br /><br />---------------------------------------------------------------------<br />".$emailtagline;
1584 }
31da70cc 1585
a1b53dcf 1586 $eventdata->timecreated = time();
7c7d3afa 1587 return message_send($eventdata);
405f01ee 1588}
e8e2d7f1 1589
c135a425 1590
fd1cb1e8 1591/**
c135a425 1592 * Returns a list of all user ids who have used messaging in the site
1593 * This was the simple way to code the SQL ... is it going to blow up
1594 * on large datasets?
1595 */
1596function message_get_participants() {
fd1cb1e8 1597 global $CFG, $DB;
1598
76b0191c 1599 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1600 UNION SELECT useridto as id,1 FROM {message}
1601 UNION SELECT useridfrom as id,1 FROM {message_read}
1602 UNION SELECT useridto as id,1 FROM {message_read}
1603 UNION SELECT userid as id,1 FROM {message_contacts}
1604 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1605}
1606
f46b6587 1607/**
1d422980 1608 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 1609 * block links etc
7cb1a1ad 1610 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
f46b6587 1611 * @param $incontactlist is the user a contact of ours?
c8621a02 1612 * @param $selectcontacturl string the url to send the user to when a contact's name is clicked
f46b6587 1613 */
a402c309 1614function message_print_contactlist_user($contact, $incontactlist = true, $isblocked = false, $selectcontacturl = null, $showactionlinks = true, $selecteduser=null) {
c8621a02 1615 global $OUTPUT, $USER;
f46b6587 1616 $fullname = fullname($contact);
1617 $fullnamelink = $fullname;
1618
a402c309
AD
1619 $linkclass = '';
1620 if (!empty($selecteduser) && $contact->id==$selecteduser->id) {
1621 $linkclass = 'messageselecteduser';
1622 }
1623
f46b6587 1624 /// are there any unread messages for this contact?
1625 if ($contact->messagecount > 0 ){
1626 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1627 }
1628
c8621a02 1629 $strcontact = $strblock = $strhistory = null;
f46b6587 1630
c8621a02
AD
1631 if ($showactionlinks) {
1632 $strcontact = message_get_contact_add_remove_link($incontactlist, $isblocked, $contact);
1633 $strblock = message_get_contact_block_link($incontactlist, $isblocked, $contact);
1634 $strhistory = message_history_link($USER->id, $contact->id, true, '', '', 'icon');
f46b6587 1635 }
1636
f46b6587 1637 echo '<tr><td class="pix">';
812dbaf7 1638 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
f46b6587 1639 echo '</td>';
1640 echo '<td class="contact">';
1d422980 1641
40a26286 1642 $popupoptions = array(
c8621a02
AD
1643 'height' => MESSAGE_DISCUSSION_HEIGHT,
1644 'width' => MESSAGE_DISCUSSION_WIDTH,
40a26286 1645 'menubar' => false,
1646 'location' => false,
1647 'status' => true,
1648 'scrollbars' => true,
1649 'resizable' => true);
1650
c8621a02
AD
1651 $link = $action = null;
1652 if (!empty($selectcontacturl)) {
1653 $link = new moodle_url($selectcontacturl.'&'.CONTACT_ID.'='.$contact->id);
1654 } else {
06d30c43
AD
1655 //can $selectcontacturl be removed and maybe the be removed and hardcoded?
1656 $link = new moodle_url("/message/index.php?id=$contact->id");
c8621a02
AD
1657 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1658 }
a402c309 1659 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('class'=>$linkclass,'title'=>get_string('sendmessageto', 'message', $fullname)));
f46b6587 1660
1661 echo '</td>';
1662 echo '<td class="link">&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory.'</td>';
1663 echo '</tr>';
1664}
1665
c8621a02
AD
1666function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1667 $strcontact = '';
1668
1669 if($incontactlist){
1670 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
1671 } else if ($isblocked) {
1672 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1673 } else{
1674 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
1675 }
1676
1677 return $strcontact;
1678}
1679
1680function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
1681 $strblock = '';
1682
1683 //commented out to allow the user to block a contact without having to remove them first
1684 /*if ($incontactlist) {
1685 //$strblock = '';
1686 } else*/
1687 if ($isblocked) {
1688 $strblock = '&nbsp;'.message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
1689 } else{
1690 $strblock = '&nbsp;'.message_contact_link($contact->id, 'block', true, $script, $text, $icon);
1691 }
1692
1693 return $strblock;
1694}
1695
6bdf4c99 1696 /**
1697 * Moves unread messages from message table to message_read for a given from user
1698 * @param object $userid User id
1699 * @return boolean success
1700 */
1701function message_move_userfrom_unread2read($userid) {
1702
1703 global $DB;
1704
71666cf3 1705 // move all unread messages from message table to message_read
6bdf4c99 1706 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1707 foreach ($messages as $message) {
ee7cd81a 1708 message_mark_message_read($message, 0); //set timeread to 0 as the message was never read
6bdf4c99 1709 }
1710 }
1711 return true;
1712}
1713
1c50df9f 1714function message_get_popup_messages($destuserid, $fromuserid=NULL){
1715 global $DB;
1d422980 1716
1c50df9f 1717 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1718
a1b53dcf 1719 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1c50df9f 1720
1721 //for every message to process check if it's for current user and process
1722 $messages = array();
1723 foreach ($messagesproc as $msgp){
1724 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1725 if ($fromuserid){
1726 $query['useridfrom'] = $fromuserid;
1727 }
1728 if ($message = $DB->get_record('message', $query)){
1729 $messages[] = $message;
1730 /// Move the entry to the other table
1731 $message->timeread = time();
1732 $messageid = $message->id;
1733 unset($message->id);
1d422980 1734
1c50df9f 1735 //delete what we've processed and check if can move message
1736 $DB->delete_records('message_working', array('id' => $msgp->id));
1737 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
ee7cd81a 1738 message_mark_message_read($message, time(), true);
1c50df9f 1739 }
1740 }
1741 }
1742 return $messages;
c8621a02
AD
1743}
1744
ee7cd81a
AD
1745/**
1746* marks ALL messages being sent from $fromuserid to $touserid as read
1747* @param int $touserid the id of the message recipient
1748* @param int $fromuserid the id of the message sender
1749* @return void
1750*/
1560760f 1751function message_mark_messages_read($touserid, $fromuserid){
c8621a02
AD
1752 global $DB;
1753
ee7cd81a 1754 $sql = 'SELECT m.* FROM {message} m WHERE m.useridto=:useridto AND m.useridfrom=:useridfrom';
1560760f
AD
1755 $messages = $DB->get_recordset_sql($sql, array('useridto'=>$touserid,'useridfrom'=>$fromuserid));
1756
c8621a02 1757 foreach ($messages as $message) {
ee7cd81a
AD
1758 message_mark_message_read($message, time());
1759 }
1760}
1761
1762/**
1763* Mark a single message as read
1764* @param message an object with an object property ie $message->id which is an id in the message table
1765* @param int $timeread the timestamp for when the message should be marked read. Usually time().
1766* @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
1767* @return void
1768*/
1769function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
1770 global $DB;
31da70cc 1771
ee7cd81a 1772 $message->timeread = $timeread;
c8621a02 1773
ee7cd81a
AD
1774 $messageid = $message->id;
1775 unset($message->id);//unset because it will get a new id on insert into message_read
1560760f 1776
ee7cd81a
AD
1777 //If any processors have pending actions abort them
1778 if (!$messageworkingempty) {
1779 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
c8621a02 1780 }
ee7cd81a
AD
1781 $DB->insert_record('message_read', $message);
1782 $DB->delete_records('message', array('id' => $messageid));
65fbace7 1783}