SCORM MDL-22741 add missing restore code - added to HEAD to keep consistency even...
[moodle.git] / message / lib.php
CommitLineData
eb5334ff 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Library functions for messaging
20 *
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package message
24 */
172186b8 25
3b120e46 26require_once($CFG->libdir.'/eventslib.php');
27
e8e2d7f1 28
29define ('MESSAGE_SHORTLENGTH', 300);
fd7006f6 30define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
31
05753d2b 32if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
2a38a6be 33 $CFG->message_contacts_refresh = 60;
fd7006f6 34}
5d6b319b 35if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
36 $CFG->message_chat_refresh = 5;
fd7006f6 37}
f520438c 38if (!isset($CFG->message_offline_time)) {
39 $CFG->message_offline_time = 300;
40}
172186b8 41
42
43function message_print_contacts() {
7cb1a1ad 44 global $USER, $CFG, $DB, $PAGE, $OUTPUT;
e8e2d7f1 45
46 $timetoshowusers = 300; //Seconds default
47 if (isset($CFG->block_online_users_timetosee)) {
48 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
49 }
e8e2d7f1 50
f46b6587 51 // time which a user is counting as being active since
52 $timefrom = time()-$timetoshowusers;
531e58f1 53
f46b6587 54 // people in our contactlist who are online
55 $onlinecontacts = array();
56 // people in our contactlist who are offline
57 $offlinecontacts = array();
58 // people who are not in our contactlist but have sent us a message
59 $strangers = array();
60
61
1d422980 62 // get all in our contactlist who are not blocked in our contact list
f46b6587 63 // and count messages we have waiting from each of them
1d422980 64 $contactsql = "SELECT u.id, u.firstname, u.lastname, u.picture,
f46b6587 65 u.imagealt, u.lastaccess, count(m.id) as messagecount
fd1cb1e8 66 FROM {message_contacts} mc
67 JOIN {user} u ON u.id = mc.contactid
68 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
1d422980 69 WHERE mc.userid = ? AND mc.blocked = 0
fd1cb1e8 70 GROUP BY u.id, u.firstname, u.lastname, u.picture,
71 u.imagealt, u.lastaccess
bbe973da 72 ORDER BY u.firstname ASC";
fd1cb1e8 73
74 if ($rs = $DB->get_recordset_sql($contactsql, array($USER->id, $USER->id))){
75 foreach($rs as $rd){
f46b6587 76
77 if($rd->lastaccess >= $timefrom){
78 // they have been active recently, so are counted online
79 $onlinecontacts[] = $rd;
80 }else{
81 $offlinecontacts[] = $rd;
e8e2d7f1 82 }
83 }
f46b6587 84 unset($rd);
fd1cb1e8 85 $rs->close();
f46b6587 86 }
87
88
89 // get messages from anyone who isn't in our contact list and count the number
90 // of messages we have from each of them
1d422980 91 $strangersql = "SELECT u.id, u.firstname, u.lastname, u.picture,
f46b6587 92 u.imagealt, u.lastaccess, count(m.id) as messagecount
fd1cb1e8 93 FROM {message} m
94 JOIN {user} u ON u.id = m.useridfrom
95 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
1d422980 96 WHERE mc.id IS NULL AND m.useridto = ?
fd1cb1e8 97 GROUP BY u.id, u.firstname, u.lastname, u.picture,
98 u.imagealt, u.lastaccess
bbe973da 99 ORDER BY u.firstname ASC";
fd1cb1e8 100
101 if($rs = $DB->get_recordset_sql($strangersql, array($USER->id))){
102 foreach($rs as $rd){
f46b6587 103 $strangers[] = $rd;
104 }
105 unset($rd);
fd1cb1e8 106 $rs->close();
e8e2d7f1 107 }
108
f46b6587 109 $countonlinecontacts = count($onlinecontacts);
110 $countofflinecontacts = count($offlinecontacts);
111 $countstrangers = count($strangers);
112
a1157dda 113 if ($countonlinecontacts + $countofflinecontacts == 0) {
669be60c 114 echo '<div class="heading">';
65ef518b 115 print_string('contactlistempty', 'message');
a1157dda 116 echo '</div>';
669be60c 117 echo '<div class="note">';
65ef518b 118 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
a1157dda 119 echo '</div>';
65ef518b 120 }
121
04b687e8 122 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
531e58f1 123
f46b6587 124 if($countonlinecontacts) {
125 /// print out list of online contacts
531e58f1 126
f46b6587 127 echo '<tr><td colspan="3" class="heading">';
128 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
129 echo '</td></tr>';
531e58f1 130
f46b6587 131 foreach ($onlinecontacts as $contact) {
132 message_print_contactlist_user($contact);
65ef518b 133 }
f46b6587 134 }
135 echo '<tr><td colspan="3">&nbsp;</td></tr>';
531e58f1 136
f46b6587 137 if ($countofflinecontacts) {
138 /// print out list of offline contacts
531e58f1 139
f46b6587 140 echo '<tr><td colspan="3" class="heading">';
141 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
142 echo '</td></tr>';
576ad290 143
f46b6587 144 foreach ($offlinecontacts as $contact) {
145 message_print_contactlist_user($contact);
65ef518b 146 }
f46b6587 147 echo '<tr><td colspan="3">&nbsp;</td></tr>';
148 }
65ef518b 149
f46b6587 150 /// print out list of incoming contacts
151 if ($countstrangers) {
152 echo '<tr><td colspan="3" class="heading">';
153 echo get_string('incomingcontacts', 'message', $countstrangers);
154 echo '</td></tr>';
531e58f1 155
f46b6587 156 foreach ($strangers as $stranger) {
157 message_print_contactlist_user($stranger, false);
669be60c 158 }
f46b6587 159 }
531e58f1 160
f46b6587 161 echo '</table>';
65ef518b 162
f46b6587 163 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
164 echo '<div class="note">(';
165 print_string('addsomecontactsincoming', 'message');
166 echo ')</div>';
65ef518b 167 }
b9ee0638 168
531e58f1 169 echo '<br />';
a9d9b46a 170
5f3bf83f 171 $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
a1b53dcf 172
7cb1a1ad 173 echo $OUTPUT->container_start('messagejsautorefresh note center');
a1b53dcf 174 echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
7cb1a1ad 175 echo $OUTPUT->container_end();
a1b53dcf 176
7cb1a1ad 177 echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
5c2ed7e2 178 echo $OUTPUT->single_button('index.php', get_string('refresh'));
7cb1a1ad 179 echo $OUTPUT->container_end();
e8e2d7f1 180}
181
182
e8e2d7f1 183/// $messagearray is an array of objects
184/// $field is a valid property of object
185/// $value is the value $field should equal to be counted
186/// if $field is empty then return count of the whole array
187/// if $field is non-existent then return 0;
188function message_count_messages($messagearray, $field='', $value='') {
189 if (!is_array($messagearray)) return 0;
190 if ($field == '' or empty($messagearray)) return count($messagearray);
531e58f1 191
e8e2d7f1 192 $count = 0;
193 foreach ($messagearray as $message) {
194 $count += ($message->$field == $value) ? 1 : 0;
195 }
196 return $count;
172186b8 197}
198
e8e2d7f1 199
172186b8 200function message_print_search() {
521fb444 201 global $USER, $OUTPUT;
531e58f1 202
294ce987 203 if ($frm = data_submitted()) {
531e58f1 204
172186b8 205 message_print_search_results($frm);
531e58f1 206
172186b8 207 } else {
1ac41751 208/*
531e58f1 209/// unfinished buggy code disabled in search.html anyway
d76a5a7f 210 // find all courses this use has readallmessages capabilities in
211 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
172186b8 212 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
213 $cs = '<select name="courseselect">';
214 foreach ($teachers as $tcourse) {
d76a5a7f 215 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
172186b8 216 }
217 $cs .= '</select>';
218 }
1ac41751 219*/
172186b8 220 include('search.html');
221 }
222}
223
224function message_print_settings() {
54b16692 225 global $USER, $OUTPUT;
531e58f1 226
d6b4fed0 227 if ($frm = data_submitted() and confirm_sesskey()) {
acef58f4 228
e8e2d7f1 229 $pref = array();
230 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
231 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
3f85157b 232 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
e49617af 233 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
531e58f1 234 $pref['message_noframesjs'] = (isset($frm->noframesjs)) ? '1' : '0';
e8e2d7f1 235 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
acef58f4 236 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
e8e2d7f1 237 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
238 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
e8e2d7f1 239
240 set_user_preferences($pref);
531e58f1 241
9ae3253e 242 redirect('index.php', get_string('settingssaved', 'message'), 1);
e8e2d7f1 243 }
244
245 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
fd7006f6 246 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
3f85157b 247 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
9aa959f2 248 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
531e58f1 249 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ? 'checked="checked"' : '';
e8e2d7f1 250 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
251 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
252 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
d776d59e 253 $format_select = html_writer::select(array(FORMAT_PLAIN => get_string('formatplain'),
4b9210f3
PS
254 FORMAT_HTML => get_string('formathtml')),
255 'emailformat', get_user_preferences('message_emailformat', FORMAT_PLAIN));
531e58f1 256
e8e2d7f1 257 include('settings.html');
258}
259
260
261
262function message_add_contact($contactid, $blocked=0) {
fd1cb1e8 263 global $USER, $DB;
531e58f1 264
fd1cb1e8 265 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
e8e2d7f1 266 return false;
267 }
531e58f1 268
fd1cb1e8 269 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
e8e2d7f1 270 /// record already exists - we may be changing blocking status
531e58f1 271
e8e2d7f1 272 if ($contact->blocked !== $blocked) {
273 /// change to blocking status
274 $contact->blocked = $blocked;
fd1cb1e8 275 return $DB->update_record('message_contacts', $contact);
e8e2d7f1 276 } else {
277 /// no changes to blocking status
278 return true;
279 }
531e58f1 280
172186b8 281 } else {
e8e2d7f1 282 /// new contact record
283 unset($contact);
284 $contact->userid = $USER->id;
285 $contact->contactid = $contactid;
286 $contact->blocked = $blocked;
fd1cb1e8 287 return $DB->insert_record('message_contacts', $contact, false);
172186b8 288 }
289}
290
e8e2d7f1 291function message_remove_contact($contactid) {
fd1cb1e8 292 global $USER, $DB;
293 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 294}
295
296function message_unblock_contact($contactid) {
fd1cb1e8 297 global $USER, $DB;
298 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 299}
300
301function message_block_contact($contactid) {
302 return message_add_contact($contactid, 1);
303}
304
305function message_get_contact($contactid) {
fd1cb1e8 306 global $USER, $DB;
307 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
e8e2d7f1 308}
531e58f1 309
e8e2d7f1 310
311
172186b8 312function message_print_search_results($frm) {
aa9a6867 313 global $USER, $CFG, $DB, $OUTPUT;
e8e2d7f1 314
85db96c5 315 echo '<div class="mdl-align">';
e8e2d7f1 316
317 /// search for person
318 if (!empty($frm->personsubmit) and !empty($frm->name)) {
531e58f1 319
b71d4dd2 320 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 321 $users = array();
df997f84 322 $mycourses = enrol_get_my_courses();
e8e2d7f1 323 foreach ($mycourses as $mycourse) {
324 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
325 foreach ($susers as $suser) $users[$suser->id] = $suser;
326 }
327 }
328 } else {
329 $users = message_search_users(SITEID, $frm->name);
330 }
331
332 if (!empty($users)) {
333 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
334 echo '<table class="message_users">';
335 foreach ($users as $user) {
531e58f1 336
7390832c 337 if ( $user->contactlistid ) {
338 if ($user->blocked == 0) { /// not blocked
082864f9 339 $strcontact = message_contact_link($user->id, 'remove', true);
340 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 341 } else { // blocked
082864f9 342 $strcontact = message_contact_link($user->id, 'add', true);
343 $strblock = message_contact_link($user->id, 'unblock', true);
e8e2d7f1 344 }
e8e2d7f1 345 } else {
082864f9 346 $strcontact = message_contact_link($user->id, 'add', true);
347 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 348 }
f520438c 349 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
531e58f1 350
669be60c 351 echo '<tr><td class="pix">';
812dbaf7 352 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
e8e2d7f1 353 echo '</td>';
669be60c 354 echo '<td class="contact">';
40a26286 355 $popupoptions = array(
356 'height' => 500,
357 'width' => 500,
358 'menubar' => false,
359 'location' => false,
360 'status' => true,
361 'scrollbars' => true,
362 'resizable' => true);
363
9bf16314
PS
364 $link = new moodle_url("/message/discussion.php?id=$user->id");
365 $action = new popup_action('click', $link, "message_$user->id", $popupoptions);
366 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
576ad290 367
e8e2d7f1 368 echo '</td>';
531e58f1 369
669be60c 370 echo '<td class="link">'.$strcontact.'</td>';
371 echo '<td class="link">'.$strblock.'</td>';
372 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 373 echo '</tr>';
374 }
375 echo '</table>';
531e58f1 376
e8e2d7f1 377 } else {
aa9a6867 378 echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
e8e2d7f1 379 }
531e58f1 380
381
e8e2d7f1 382 /// search messages for keywords
ff49c389 383 } else if (!empty($frm->keywordssubmit)) {
38c6a928 384 $keywordstring = clean_text(trim($frm->keywords));
ff49c389 385 if ($keywordstring) {
386 $keywords = explode(' ', $keywordstring);
387 } else {
388 $keywords = array();
389 }
e8e2d7f1 390 $tome = false;
391 $fromme = false;
392 $courseid = 'none';
393
394 switch ($frm->keywordsoption) {
395 case 'tome':
396 $tome = true;
397 break;
398 case 'fromme':
399 $fromme = true;
400 break;
401 case 'allmine':
402 $tome = true;
403 $fromme = true;
404 break;
405 case 'allusers':
406 $courseid = SITEID;
407 break;
408 case 'courseusers':
409 $courseid = $frm->courseid;
410 break;
411 default:
412 $tome = true;
413 $fromme = true;
414 }
415
416 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
531e58f1 417
e8e2d7f1 418 /// get a list of contacts
fd1cb1e8 419 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
082864f9 420 $contacts = array();
421 }
e8e2d7f1 422
082864f9 423 /// print heading with number of results
669be60c 424 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
082864f9 425
426 /// print table headings
669be60c 427 echo '<table class="searchresults" cellspacing="0">';
082864f9 428 echo '<tr>';
fd7006f6 429 echo '<td><strong>'.get_string('from').'</strong></td>';
430 echo '<td><strong>'.get_string('to').'</strong></td>';
431 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
432 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
082864f9 433 echo "</tr>\n";
434
435 $blockedcount = 0;
54d8f804 436 $dateformat = get_string('strftimedatetimeshort');
38c6a928 437 $strcontext = get_string('context', 'message');
e8e2d7f1 438 foreach ($messages as $message) {
082864f9 439
440 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 441 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 442 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
443 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
444 )
445 ) {
446 $blockedcount ++;
e8e2d7f1 447 continue;
448 }
531e58f1 449
082864f9 450 /// load up user to record
451 if ($message->useridto !== $USER->id) {
fd1cb1e8 452 $userto = $DB->get_record('user', array('id'=>$message->useridto));
531e58f1 453 $tocontact = (array_key_exists($message->useridto, $contacts) and
082864f9 454 ($contacts[$message->useridto]->blocked == 0) );
531e58f1 455 $toblocked = (array_key_exists($message->useridto, $contacts) and
082864f9 456 ($contacts[$message->useridto]->blocked == 1) );
457 } else {
458 $userto = false;
459 $tocontact = false;
460 $toblocked = false;
461 }
531e58f1 462
082864f9 463 /// load up user from record
464 if ($message->useridfrom !== $USER->id) {
fd1cb1e8 465 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
531e58f1 466 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
082864f9 467 ($contacts[$message->useridfrom]->blocked == 0) );
531e58f1 468 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
082864f9 469 ($contacts[$message->useridfrom]->blocked == 1) );
470 } else {
471 $userfrom = false;
472 $fromcontact = false;
473 $fromblocked = false;
474 }
475
e520509a 476 /// find date string for this message
477 $date = usergetdate($message->timecreated);
478 $datestring = $date['year'].$date['mon'].$date['mday'];
479
082864f9 480 /// print out message row
481 echo '<tr valign="top">';
669be60c 482 echo '<td class="contact">';
b9ee0638 483 message_print_user($userfrom, $fromcontact, $fromblocked);
e8e2d7f1 484 echo '</td>';
669be60c 485 echo '<td class="contact">';
b9ee0638 486 message_print_user($userto, $tocontact, $toblocked);
e8e2d7f1 487 echo '</td>';
3d143595 488 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
669be60c 489 echo '<br /><div class="link">';
531e58f1 490 message_history_link($message->useridto, $message->useridfrom, false,
2973ec18 491 $keywordstring, 'm'.$message->id, $strcontext);
f520438c 492 echo '</div>';
e520509a 493 echo '</td>';
669be60c 494 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 495 echo "</tr>\n";
496 }
531e58f1 497
e8e2d7f1 498
e520509a 499 if ($blockedcount > 0) {
500 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
501 }
e8e2d7f1 502 echo '</table>';
531e58f1 503
e8e2d7f1 504 } else {
aa9a6867 505 echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
e8e2d7f1 506 }
507
508
509 /// what the ????, probably an empty search string, duh!
510 } else {
aa9a6867 511 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
e8e2d7f1 512 }
513
082864f9 514 echo '<br />';
5c2ed7e2 515 echo $OUTPUT->single_button(new moodle_url('index.php', array('tab' => 'search')), get_string('newsearch', 'message'));
e8e2d7f1 516
517 echo '</div>';
518}
519
520
082864f9 521function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
7cb1a1ad 522 global $USER, $OUTPUT;
1d422980 523
082864f9 524 if ($user === false) {
812dbaf7 525 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
082864f9 526 } else {
812dbaf7 527 echo $OUTPUT->user_picture($USE, array('size'=>20, 'courseid'=>SITEID));
e520509a 528 echo '&nbsp;';
082864f9 529 if ($iscontact) {
530 message_contact_link($user->id, 'remove');
531 } else {
532 message_contact_link($user->id, 'add');
533 }
534 echo '&nbsp;';
535 if ($isblocked) {
536 message_contact_link($user->id, 'unblock');
537 } else {
538 message_contact_link($user->id, 'block');
539 }
e520509a 540 echo '<br />';
576ad290 541
40a26286 542 $popupoptions = array(
543 'height' => 500,
544 'width' => 500,
545 'menubar' => false,
546 'location' => false,
547 'status' => true,
548 'scrollbars' => true,
549 'resizable' => true);
550
9bf16314
PS
551 $link = new moodle_url("/message/discussion.php?id=$user->id");
552 $action = new popup_action('click', $link, "message_$user->id", $popupoptions);
553 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
40a26286 554
082864f9 555 }
556}
557
558
559/// linktype can be: add, remove, block, unblock
5d6b319b 560function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
55a6bb2d 561 global $USER, $CFG, $OUTPUT;
e520509a 562
563 static $str;
564
565 if (empty($str->blockcontact)) {
566 $str->blockcontact = get_string('blockcontact', 'message');
567 $str->unblockcontact = get_string('unblockcontact', 'message');
568 $str->removecontact = get_string('removecontact', 'message');
569 $str->addcontact = get_string('addcontact', 'message');
570 }
571
5d6b319b 572 $command = $linktype.'contact';
573 $string = $str->{$command};
1d422980 574 $alttext = $text ? '' : $string;
5d6b319b 575 $text = $text ? '&nbsp;'.$string : '';
576
082864f9 577 switch ($linktype) {
578 case 'block':
ddedf979 579 $icon = 't/go';
082864f9 580 break;
581 case 'unblock':
ddedf979 582 $icon = 't/stop';
082864f9 583 break;
584 case 'remove':
ddedf979 585 $icon = 't/user';
082864f9 586 break;
587 case 'add':
588 default:
ddedf979 589 $icon = 't/usernot';
082864f9 590 }
5d6b319b 591
592 $output = '<span class="'.$linktype.'">'.
593 '<a href="'.$script.'&amp;'.$command.'='.$userid.
0d3bb48d 594 '&amp;sesskey='.sesskey().'" title="'.s($string).'">'.
b5d0cafc 595 '<img src="'.$OUTPUT->pix_url($icon).'" class="iconsmall" alt="'.s($alttext).'" />'.
5d6b319b 596 $text.'</a></span>';
597
e520509a 598 if ($return) {
599 return $output;
082864f9 600 } else {
e520509a 601 echo $output;
082864f9 602 return true;
603 }
604}
605
38c6a928 606function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
f2a1963c 607 global $USER, $CFG, $OUTPUT;
62119d65 608
830d0af6 609 static $strmessagehistory;
610
611 if (empty($strmessagehistory)) {
612 $strmessagehistory = get_string('messagehistory', 'message');
613 }
2514081c 614
62119d65 615 if (!$userid2) {
616 $userid2 = $USER->id;
617 }
e520509a 618 if ($position) {
619 $position = "#$position";
620 }
38c6a928 621 if ($keywords) {
622 $keywords = "&search=".urlencode($keywords);
623 }
62119d65 624
830d0af6 625 if ($linktext == 'icon') { // Icon only
b5d0cafc 626 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
830d0af6 627 } else if ($linktext == 'both') { // Icon and standard name
b5d0cafc 628 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
830d0af6 629 $fulllink .= '&nbsp;'.$strmessagehistory;
630 } else if ($linktext) { // Custom name
631 $fulllink = $linktext;
632 } else { // Standard name only
633 $fulllink = $strmessagehistory;
fd7006f6 634 }
635
40a26286 636 $popupoptions = array(
637 'height' => 500,
638 'width' => 500,
639 'menubar' => false,
640 'location' => false,
641 'status' => true,
642 'scrollbars' => true,
643 'resizable' => true);
644
3ea5951e
PS
645 $link = new moodle_url("/message/history.php?user1=$userid1&user2=$userid2$keywords$position");
646 $action = new popup_action('click', $link, "message_history_$userid1", $popupoptions);
9bf16314 647 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
62119d65 648
5d6b319b 649 $str = '<span class="history">'.$str.'</span>';
650
62119d65 651 if ($returnstr) {
652 return $str;
653 } else {
654 echo $str;
655 return true;
656 }
657}
e8e2d7f1 658
659
660/**
661 * Search through course users
662 *
531e58f1 663 * If $coursid specifies the site course then this function searches
e8e2d7f1 664 * through all undeleted and confirmed users
665 *
7390832c 666 * @uses $CFG, $USER
e8e2d7f1 667 * @uses SITEID
668 * @param int $courseid The course in question.
669 * @param string $searchtext ?
670 * @param string $sort ?
531e58f1 671 * @param string $exceptions ?
e8e2d7f1 672 * @return array An array of {@link $USER} records.
673 * @todo Finish documenting this function
674 */
675function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
fd1cb1e8 676 global $CFG, $USER, $DB;
e8e2d7f1 677
245ac557 678 $fullname = $DB->sql_fullname();
679 $LIKE = $DB->sql_ilike();
e8e2d7f1 680
681 if (!empty($exceptions)) {
682 $except = ' AND u.id NOT IN ('. $exceptions .') ';
683 } else {
684 $except = '';
685 }
686
687 if (!empty($sort)) {
688 $order = ' ORDER BY '. $sort;
689 } else {
690 $order = '';
691 }
692
693 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
7390832c 694 $fields = 'u.id, u.firstname, u.lastname, u.picture, u.imagealt, mc.id as contactlistid, mc.blocked';
e8e2d7f1 695
696 if (!$courseid or $courseid == SITEID) {
fd1cb1e8 697 $params = array($USER->id, "%$searchtext%");
698 return $DB->get_records_sql("SELECT $fields
d9eef08a 699 FROM {user} u
fd1cb1e8 700 LEFT JOIN {message_contacts} mc
1d422980 701 ON mc.contactid = u.id AND mc.userid = ?
fd1cb1e8 702 WHERE $select
703 AND ($fullname $LIKE ?)
704 $except
705 $order", $params);
e8e2d7f1 706 } else {
707
d76a5a7f 708 $context = get_context_instance(CONTEXT_COURSE, $courseid);
709 $contextlists = get_related_contexts_string($context);
531e58f1 710
d76a5a7f 711 // everyone who has a role assignement in this course or higher
fd1cb1e8 712 $params = array($USER->id, "%$searchtext%");
713 $users = $DB->get_records_sql("SELECT $fields
714 FROM {user} u
715 JOIN {role_assignments} ra ON ra.userid = u.id
716 LEFT JOIN {message_contacts} mc
1d422980 717 ON mc.contactid = u.id AND mc.userid = ?
fd1cb1e8 718 WHERE $select
719 AND ra.contextid $contextlists
720 AND ($fullname $LIKE ?)
721 $except
722 $order", $params);
d76a5a7f 723
724 return $users;
e8e2d7f1 725 }
726}
727
728
729
730
082864f9 731function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 732/// Returns a list of posts found using an array of search terms
733/// eg word +word -word
734///
fd1cb1e8 735 global $CFG, $USER, $DB;
e8e2d7f1 736
082864f9 737 /// If no userid sent then assume current user
531e58f1 738 if ($userid == 0) $userid = $USER->id;
082864f9 739
6eb7722f 740 /// Some differences in SQL syntax
d9eef08a 741 if ($DB->sql_regex_supported()) {
742 $REGEXP = $DB->sql_regex(true);
743 $NOTREGEXP = $DB->sql_regex(false);
e8e2d7f1 744 }
745
d9eef08a 746 $LIKE = $DB->sql_ilike();
747
748 $searchcond = array();
749 $params = array();
750 $i = 0;
e8e2d7f1 751
752 foreach ($searchterms as $searchterm) {
d9eef08a 753 $i++;
754
755 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
756
e8e2d7f1 757 if (strlen($searchterm) < 2) {
758 continue;
759 }
6bb4875f 760 /// Under Oracle and MSSQL, trim the + and - operators and perform
761 /// simpler LIKE search
d9eef08a 762 if (!$DB->sql_regex_supported()) {
763 if (substr($searchterm, 0, 1) == '-') {
764 $NOT = ' NOT ';
765 }
6bb4875f 766 $searchterm = trim($searchterm, '+-');
767 }
768
e8e2d7f1 769 if (substr($searchterm,0,1) == "+") {
770 $searchterm = substr($searchterm,1);
d9eef08a 771 $searchterm = preg_quote($searchterm, '|');
3d143595 772 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
d9eef08a 773 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
774
e8e2d7f1 775 } else if (substr($searchterm,0,1) == "-") {
776 $searchterm = substr($searchterm,1);
d9eef08a 777 $searchterm = preg_quote($searchterm, '|');
3d143595 778 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
d9eef08a 779 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
780
e8e2d7f1 781 } else {
3d143595 782 $searchcond[] = "m.fullmessage $NOT $LIKE :ss$i";
d9eef08a 783 $params['ss'.$i] = "%$searchterm%";
e8e2d7f1 784 }
172186b8 785 }
786
d9eef08a 787 if (empty($searchcond)) {
ff49c389 788 $searchcond = " m.fullmessage $LIKE :ss1";
789 $params['ss1'] = "%";
790 } else {
791 $searchcond = implode(" AND ", $searchcond);
8a51efe9 792 }
e8e2d7f1 793
e8e2d7f1 794
082864f9 795 /// There are several possibilities
796 /// 1. courseid = SITEID : The admin is searching messages by all users
797 /// 2. courseid = ?? : A teacher is searching messages by users in
798 /// one of their courses - currently disabled
799 /// 3. courseid = none : User is searching their own messages;
800 /// a. Messages from user
801 /// b. Messages to user
802 /// c. Messages to and from user
803
804 if ($courseid == SITEID) { /// admin is searching all messages
3d143595 805 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 806 FROM {message_read} m
807 WHERE $searchcond", $params);
3d143595 808 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 809 FROM {message} m
810 WHERE $searchcond", $params);
811
812 } else if ($courseid !== 'none') {
082864f9 813 /// This has not been implemented due to security concerns
d9eef08a 814 $m_read = array();
815 $m_unread = array();
e8e2d7f1 816
082864f9 817 } else {
531e58f1 818
d9eef08a 819 if ($fromme and $tome) {
820 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
821 $params['userid1'] = $userid;
822 $params['userid2'] = $userid;
823
824 } else if ($fromme) {
825 $searchcond .= " AND m.useridfrom=:userid";
826 $params['userid'] = $userid;
531e58f1 827
d9eef08a 828 } else if ($tome) {
829 $searchcond .= " AND m.useridto=:userid";
830 $params['userid'] = $userid;
831 }
531e58f1 832
3d143595 833 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 834 FROM {message_read} m
835 WHERE $searchcond", $params);
3d143595 836 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
d9eef08a 837 FROM {message} m
838 WHERE $searchcond", $params);
531e58f1 839
e8e2d7f1 840 }
841
082864f9 842 /// The keys may be duplicated in $m_read and $m_unread so we can't
843 /// do a simple concatenation
844 $message = array();
d9eef08a 845 foreach ($m_read as $m) {
846 $messages[] = $m;
847 }
848 foreach ($m_unread as $m) {
849 $messages[] = $m;
850 }
e8e2d7f1 851
852 return (empty($messages)) ? false : $messages;
172186b8 853}
854
e8e2d7f1 855
856
857/// Borrowed with changes from mod/forum/lib.php
858function message_shorten_message($message, $minlength=0) {
859// Given a post object that we already know has a long message
860// this function truncates the message nicely to the first
861// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
862
863 $i = 0;
864 $tag = false;
865 $length = strlen($message);
866 $count = 0;
867 $stopzone = false;
868 $truncate = 0;
869 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
531e58f1 870
e8e2d7f1 871
872 for ($i=0; $i<$length; $i++) {
873 $char = $message[$i];
874
875 switch ($char) {
876 case "<":
877 $tag = true;
878 break;
879 case ">":
880 $tag = false;
881 break;
882 default:
883 if (!$tag) {
884 if ($stopzone) {
885 if ($char == '.' or $char == ' ') {
886 $truncate = $i+1;
887 break 2;
888 }
889 }
890 $count++;
891 }
892 break;
893 }
894 if (!$stopzone) {
895 if ($count > $minlength) {
896 $stopzone = true;
897 }
898 }
899 }
900
901 if (!$truncate) {
902 $truncate = $i;
903 }
904
905 return substr($message, 0, $truncate);
906}
907
38c6a928 908
d9eef08a 909/**
38c6a928 910 * Given a string and an array of keywords, this function looks
911 * for the first keyword in the string, and then chops out a
912 * small section from the text that shows that word in context.
913 */
914function message_get_fragment($message, $keywords) {
915
916 $fullsize = 120;
917 $halfsize = (int)($fullsize/2);
918
919 $message = strip_tags($message);
920
921 foreach ($keywords as $keyword) { // Just get the first one
922 if ($keyword !== '') {
923 break;
924 }
925 }
926 if (empty($keyword)) { // None found, so just return start of message
927 return message_shorten_message($message, 30);
928 }
929
930 $leadin = $leadout = '';
931
932/// Find the start of the fragment
933 $start = 0;
934 $length = strlen($message);
935
936 $pos = strpos($message, $keyword);
937 if ($pos > $halfsize) {
938 $start = $pos - $halfsize;
939 $leadin = '...';
940 }
941/// Find the end of the fragment
942 $end = $start + $fullsize;
943 if ($end > $length) {
944 $end = $length;
945 } else {
946 $leadout = '...';
947 }
948
949/// Pull out the fragment and format it
950
951 $fragment = substr($message, $start, $end - $start);
952 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
953 return $fragment;
954}
955
956
b9ee0638 957function message_get_history($user1, $user2) {
fd1cb1e8 958 global $DB;
959
960 $messages = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
961 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
b9ee0638 962 'timecreated');
fd1cb1e8 963 if ($messages_new = $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
964 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
b9ee0638 965 'timecreated')) {
966 foreach ($messages_new as $message) {
967 $messages[] = $message;
968 }
969 }
970 return $messages;
971}
972
030e3e03 973function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 974
975 static $dateformat;
976
977 if (empty($dateformat)) {
978 if ($format) {
979 $dateformat = $format;
980 } else {
54d8f804 981 $format = get_string('strftimedatetimeshort');
acd21a2d 982 }
b9ee0638 983 }
acd21a2d 984 $time = userdate($message->timecreated, $dateformat);
fd1cb1e8 985 $options = new object();
ff6048dd 986 $options->para = false;
3d143595 987 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
38c6a928 988 if ($keywords) {
989 $messagetext = highlight($keywords, $messagetext);
990 }
030e3e03 991 return '<div class="message '.$class.'"><a name="m'.$message->id.'"></a><span class="author">'.s(fullname($user)).'</span> <span class="time">['.$time.']</span>: <span class="content">'.$messagetext.'</span></div>';
b9ee0638 992}
e8e2d7f1 993
fd1cb1e8 994/**
405f01ee 995 * Inserts a message into the database, but also forwards it
996 * via other means if appropriate.
997 */
998function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
fd1cb1e8 999 global $CFG, $SITE, $USER, $DB;
1d422980 1000
3b120e46 1001 $eventdata = new object();
1c50df9f 1002 $eventdata->component = 'message';
1003 $eventdata->name = 'instantmessage';
3b120e46 1004 $eventdata->userfrom = $userfrom;
1005 $eventdata->userto = $userto;
1c50df9f 1006 $eventdata->subject = "IM";
3b120e46 1007 $eventdata->fullmessage = $message;
1008 $eventdata->fullmessageformat = FORMAT_PLAIN;
1009 $eventdata->fullmessagehtml = '';
a1b53dcf 1010 $eventdata->smallmessage = '';
1011 $eventdata->timecreated = time();
7c7d3afa 1012 return message_send($eventdata);
f49edc81 1013
405f01ee 1014}
e8e2d7f1 1015
c135a425 1016
fd1cb1e8 1017/**
c135a425 1018 * Returns a list of all user ids who have used messaging in the site
1019 * This was the simple way to code the SQL ... is it going to blow up
1020 * on large datasets?
1021 */
1022function message_get_participants() {
fd1cb1e8 1023 global $CFG, $DB;
1024
76b0191c 1025 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1026 UNION SELECT useridto as id,1 FROM {message}
1027 UNION SELECT useridfrom as id,1 FROM {message_read}
1028 UNION SELECT useridto as id,1 FROM {message_read}
1029 UNION SELECT userid as id,1 FROM {message_contacts}
1030 UNION SELECT contactid as id,1 from {message_contacts}");
c135a425 1031}
1032
f46b6587 1033/**
1d422980 1034 * Print a row of contactlist displaying user picture, messages waiting and
f46b6587 1035 * block links etc
7cb1a1ad 1036 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
f46b6587 1037 * @param $incontactlist is the user a contact of ours?
1038 */
1039function message_print_contactlist_user($contact, $incontactlist = true){
40a26286 1040 global $OUTPUT;
f46b6587 1041 $fullname = fullname($contact);
1042 $fullnamelink = $fullname;
1043
1044 /// are there any unread messages for this contact?
1045 if ($contact->messagecount > 0 ){
1046 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1047 }
1048
1049
1050 if($incontactlist){
1051 $strcontact = message_contact_link($contact->id, 'remove', true);
1052 $strblock = '';
1053 }else{
1054 $strcontact = message_contact_link($contact->id, 'add', true);
1055 $strblock = '&nbsp;'. message_contact_link($contact->id, 'block', true);
1056 }
1057
1058 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
1059
1060 echo '<tr><td class="pix">';
812dbaf7 1061 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
f46b6587 1062 echo '</td>';
1063 echo '<td class="contact">';
1d422980 1064
40a26286 1065 $popupoptions = array(
1066 'height' => 500,
1067 'width' => 500,
1068 'menubar' => false,
1069 'location' => false,
1070 'status' => true,
1071 'scrollbars' => true,
1072 'resizable' => true);
1073
3ea5951e 1074 $link = new moodle_url("/message/discussion.php?id=$contact->id");
9bf16314
PS
1075 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1076 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
f46b6587 1077
1078 echo '</td>';
1079 echo '<td class="link">&nbsp;'.$strcontact.$strblock.'&nbsp;'.$strhistory.'</td>';
1080 echo '</tr>';
1081}
1082
6bdf4c99 1083 /**
1084 * Moves unread messages from message table to message_read for a given from user
1085 * @param object $userid User id
1086 * @return boolean success
1087 */
1088function message_move_userfrom_unread2read($userid) {
1089
1090 global $DB;
1091
1092 // move all unread messages from message table to messasge_read
1093 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1094 foreach ($messages as $message) {
1095 $message->timeread = 0; //the message was never read
1096 $messageid = $message->id;
1097 unset($message->id);
1098 if ($DB->insert_record('message_read', $message)) {
1099 $DB->delete_records('message', array('id' => $messageid));
1100 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
1101 } else {
1102 return false;
1103 }
1104 }
1105 }
1106 return true;
1107}
1108
1c50df9f 1109function message_get_popup_messages($destuserid, $fromuserid=NULL){
1110 global $DB;
1d422980 1111
1c50df9f 1112 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1113
a1b53dcf 1114 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1c50df9f 1115
1116 //for every message to process check if it's for current user and process
1117 $messages = array();
1118 foreach ($messagesproc as $msgp){
1119 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1120 if ($fromuserid){
1121 $query['useridfrom'] = $fromuserid;
1122 }
1123 if ($message = $DB->get_record('message', $query)){
1124 $messages[] = $message;
1125 /// Move the entry to the other table
1126 $message->timeread = time();
1127 $messageid = $message->id;
1128 unset($message->id);
1d422980 1129
1c50df9f 1130 //delete what we've processed and check if can move message
1131 $DB->delete_records('message_working', array('id' => $msgp->id));
1132 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
1133 if ($DB->insert_record('message_read', $message)) {
1134 $DB->delete_records('message', array('id' => $messageid));
1135 }
1136 }
1137 }
1138 }
1139 return $messages;
eb5334ff 1140}