Now excel can be generated under iso-8859-1 (safer) based on the
[moodle.git] / message / lib.php
CommitLineData
172186b8 1<?php
2/// library functions for messaging
3
e8e2d7f1 4
5define ('MESSAGE_SHORTLENGTH', 300);
fd7006f6 6define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
7
05753d2b 8if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
2a38a6be 9 $CFG->message_contacts_refresh = 60;
fd7006f6 10}
5d6b319b 11if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
12 $CFG->message_chat_refresh = 5;
fd7006f6 13}
f520438c 14if (!isset($CFG->message_offline_time)) {
15 $CFG->message_offline_time = 300;
16}
172186b8 17
18
19function message_print_contacts() {
e8e2d7f1 20 global $USER, $CFG;
21
22 $timetoshowusers = 300; //Seconds default
23 if (isset($CFG->block_online_users_timetosee)) {
24 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
25 }
26 $timefrom = time()-$timetoshowusers;
27
28
29 /// get lists of contacts and unread messages
444f6252 30 $onlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
e8e2d7f1 31 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
32 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess>=$timefrom
33 AND mc.blocked='0'
fd7006f6 34 ORDER BY u.firstname ASC");
e8e2d7f1 35
444f6252 36 $offlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
e8e2d7f1 37 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
38 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess<$timefrom
39 AND mc.blocked='0'
fd7006f6 40 ORDER BY u.firstname ASC");
e8e2d7f1 41
42 $unreadmessages = get_records_sql("SELECT m.id, m.useridfrom, u.firstname, u.lastname, u.picture
43 FROM {$CFG->prefix}user u, {$CFG->prefix}message m
44 WHERE m.useridto='$USER->id' AND u.id=m.useridfrom");
45
46 $blockedcontacts = get_records_select('message_contacts', "userid='$USER->id' AND blocked='1'", '', 'contactid, id');
47
48
65ef518b 49 $countonlinecontacts = (is_array($onlinecontacts)) ? count($onlinecontacts) : 0;
50 $countofflinecontacts = (is_array($offlinecontacts)) ? count($offlinecontacts) : 0;
e8e2d7f1 51
52/// Cycle through messages and extract those that are from unknown contacts
53/// We can take advantage of the keys for $onlinecontacts and $offlinecontacts
54/// which are set to the userid and therefore we just need to see if the key
55/// exists in either of those arrays
56/// We can also discard any messages from users in our blocked contact list
57 $unknownmessages = array();
58 if (!empty($unreadmessages)) {
59 /// make sure we have valid arrays to test against - they may be boolean false
60 if (empty($onlinecontacts)) $onlinecontacts = array();
61 if (empty($offlinecontacts)) $offlinecontacts = array();
62 if (empty($blockedcontacts)) $blockedcontacts = array();
63 foreach ($unreadmessages as $unreadmessage) {
64 if (array_key_exists($unreadmessage->useridfrom, $onlinecontacts) or
65 array_key_exists($unreadmessage->useridfrom, $offlinecontacts) or
66 array_key_exists($unreadmessage->useridfrom, $blockedcontacts) ) {
67 continue;
68 }
69 if (!isset($unknownmessages[$unreadmessage->useridfrom])) {
70 $message = $unreadmessage;
71 $message->count = 1;
72 $unknownmessages[$unreadmessage->useridfrom] = $message;
73 } else {
74 $unknownmessages[$unreadmessage->useridfrom]->count++;
75 }
76 }
77 }
78
a1157dda 79 if ($countonlinecontacts + $countofflinecontacts == 0) {
669be60c 80 echo '<div class="heading">';
65ef518b 81 print_string('contactlistempty', 'message');
a1157dda 82 echo '</div>';
669be60c 83 echo '<div class="note">';
65ef518b 84 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
a1157dda 85 echo '</div>';
65ef518b 86 }
87
88 if(!empty($onlinecontacts) || !empty($offlinecontacts) || !empty($unknownmessages)) {
89
90 echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0" border="0">';
91
92 if(!empty($onlinecontacts)) {
93 /// print out list of online contacts
94
669be60c 95 echo '<tr><td colspan="3" class="heading">';
65ef518b 96 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
97 echo '</td></tr>';
98
99 if (!empty($onlinecontacts)) {
100 foreach ($onlinecontacts as $contact) {
101 if ($contact->blocked == 1) continue;
102 $fullname = fullname($contact);
103 $fullnamelink = $fullname;
104 /// are there any unread messages for this contact?
105 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
106 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
107 }
108 /// link to remove from contact list
109 $strcontact = message_contact_link($contact->id, 'remove', true);
110 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
111
669be60c 112 echo '<tr><td class="pix">';
65ef518b 113 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
114 echo '</td>';
669be60c 115 echo '<td class="contact">';
65ef518b 116 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
117 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
118 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
119 echo '</td>';
669be60c 120 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
65ef518b 121 echo '</tr>';
122 }
e520509a 123 }
65ef518b 124 echo '<tr><td colspan="3">&nbsp;</td></tr>';
125 }
126
a1157dda 127 if (!empty($offlinecontacts)) {
65ef518b 128 /// print out list of offline contacts
a1157dda 129
669be60c 130 echo '<tr><td colspan="3" class="heading">';
65ef518b 131 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
132 echo '</td></tr>';
a1157dda 133
134 foreach ($offlinecontacts as $contact) {
135 if ($contact->blocked == 1) continue;
136 $fullname = fullname($contact);
137 $fullnamelink = $fullname;
65ef518b 138 /// are there any unread messages for this contact?
a1157dda 139 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
140 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
65ef518b 141 }
a1157dda 142 /// link to remove from contact list
143 $strcontact = message_contact_link($contact->id, 'remove', true);
144 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
145
669be60c 146 echo '<tr><td class="pix">';
a1157dda 147 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
148 echo '</td>';
669be60c 149 echo '<td class="contact">';
a1157dda 150 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
151 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
152 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
153 echo '</td>';
669be60c 154 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
a1157dda 155 echo '</tr>';
65ef518b 156 }
157 echo '<tr><td colspan="3">&nbsp;</td></tr>';
e8e2d7f1 158 }
e8e2d7f1 159
65ef518b 160
161 /// print out list of incoming contacts
162 if (!empty($unknownmessages)) {
669be60c 163 echo '<tr><td colspan="3" class="heading">';
65ef518b 164 echo get_string('incomingcontacts', 'message', count($unknownmessages));
165 echo '</td></tr>';
a1157dda 166
65ef518b 167 foreach ($unknownmessages as $messageuser) {
168 $fullname = fullname($messageuser);
169 $fullnamelink = $fullname;
170 if ($messageuser->count) {
171 $fullnamelink = '<strong>'.$fullnamelink.' ('.$messageuser->count.')</strong>';
172 }
173 /// link to add to contact list
174
175 $strcontact = message_contact_link($messageuser->useridfrom, 'add', true);
176 $strblock = message_contact_link($messageuser->useridfrom, 'block', true);
177 $strhistory = message_history_link($messageuser->useridfrom, 0, true, '', '', 'icon');
178
669be60c 179 echo '<tr><td class="pix">';
65ef518b 180 print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, true, 'userwindow');
181 echo '</td>';
669be60c 182 echo '<td class="contact">';
65ef518b 183 link_to_popup_window("/message/discussion.php?id=$messageuser->useridfrom", "message_$messageuser->useridfrom",
184 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
185 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
186 echo '</td>';
669be60c 187 echo '<td class="link">&nbsp;'.$strcontact.'&nbsp;'.$strblock.'&nbsp;'.$strhistory.'</td>';
65ef518b 188 echo '</tr>';
189 }
190 }
191
192 echo '</table>';
669be60c 193
194 if (!empty($unknownmessages) && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
195 echo '<div class="note">(';
196 print_string('addsomecontactsincoming', 'message');
197 echo ')</div>';
198 }
199
65ef518b 200
201 }
b9ee0638 202
669be60c 203 echo '<br /><p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
a9d9b46a 204
e8e2d7f1 205}
206
207
208
209
210/// $messagearray is an array of objects
211/// $field is a valid property of object
212/// $value is the value $field should equal to be counted
213/// if $field is empty then return count of the whole array
214/// if $field is non-existent then return 0;
215function message_count_messages($messagearray, $field='', $value='') {
216 if (!is_array($messagearray)) return 0;
217 if ($field == '' or empty($messagearray)) return count($messagearray);
218
219 $count = 0;
220 foreach ($messagearray as $message) {
221 $count += ($message->$field == $value) ? 1 : 0;
222 }
223 return $count;
172186b8 224}
225
e8e2d7f1 226
172186b8 227function message_print_search() {
9ae3253e 228 global $USER;
172186b8 229
230 if ($frm = data_submitted()) {
231
232 message_print_search_results($frm);
233
234 } else {
1ac41751 235/*
236/// unfinished buggy code disabled in search.html anyway
d76a5a7f 237 // find all courses this use has readallmessages capabilities in
238 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
172186b8 239 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
240 $cs = '<select name="courseselect">';
241 foreach ($teachers as $tcourse) {
d76a5a7f 242 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
172186b8 243 }
244 $cs .= '</select>';
245 }
1ac41751 246*/
172186b8 247 include('search.html');
248 }
249}
250
251function message_print_settings() {
9ae3253e 252 global $USER;
e8e2d7f1 253
172186b8 254 if ($frm = data_submitted()) {
acef58f4 255
e8e2d7f1 256 $pref = array();
257 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
258 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
3f85157b 259 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
e49617af 260 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
e8e2d7f1 261 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
acef58f4 262 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
e8e2d7f1 263 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
264 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
e8e2d7f1 265
266 set_user_preferences($pref);
267
9ae3253e 268 redirect('index.php', get_string('settingssaved', 'message'), 1);
e8e2d7f1 269 }
270
271 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
fd7006f6 272 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
3f85157b 273 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
9aa959f2 274 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
e8e2d7f1 275 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
276 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
277 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
278 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
279 FORMAT_HTML => get_string('formathtml')),
280 'emailformat',
281 get_user_preferences('message_emailformat', FORMAT_PLAIN),
282 false, '', '0', true );
283
284 include('settings.html');
285}
286
287
288
289function message_add_contact($contactid, $blocked=0) {
290 global $USER;
291
292 if (!record_exists('user', 'id', $contactid)) { // invalid userid
293 return false;
294 }
295
296 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
297 /// record already exists - we may be changing blocking status
298
299 if ($contact->blocked !== $blocked) {
300 /// change to blocking status
301 $contact->blocked = $blocked;
302 return update_record('message_contacts', $contact);
303 } else {
304 /// no changes to blocking status
305 return true;
306 }
307
172186b8 308 } else {
e8e2d7f1 309 /// new contact record
310 unset($contact);
311 $contact->userid = $USER->id;
312 $contact->contactid = $contactid;
313 $contact->blocked = $blocked;
314 return insert_record('message_contacts', $contact, false);
172186b8 315 }
316}
317
e8e2d7f1 318function message_remove_contact($contactid) {
319 global $USER;
e8e2d7f1 320 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
321}
322
323function message_unblock_contact($contactid) {
082864f9 324 global $USER;
325 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
e8e2d7f1 326}
327
328function message_block_contact($contactid) {
329 return message_add_contact($contactid, 1);
330}
331
332function message_get_contact($contactid) {
333 global $USER;
334 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
335}
336
337
338
172186b8 339function message_print_search_results($frm) {
9ae3253e 340 global $USER, $CFG;
e8e2d7f1 341
342 echo '<div align="center">';
343
344 /// search for person
345 if (!empty($frm->personsubmit) and !empty($frm->name)) {
346
b71d4dd2 347 if (optional_param('mycourses', 0, PARAM_BOOL)) {
e8e2d7f1 348 $users = array();
349 $mycourses = get_my_courses($USER->id);
350 foreach ($mycourses as $mycourse) {
351 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
352 foreach ($susers as $suser) $users[$suser->id] = $suser;
353 }
354 }
355 } else {
356 $users = message_search_users(SITEID, $frm->name);
357 }
358
359 if (!empty($users)) {
360 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
361 echo '<table class="message_users">';
362 foreach ($users as $user) {
082864f9 363
e8e2d7f1 364 if (($contact = message_get_contact($user->id)) !== false) {
365 if ($contact->blocked == 0) { /// not blocked
082864f9 366 $strcontact = message_contact_link($user->id, 'remove', true);
367 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 368 } else { // blocked
082864f9 369 $strcontact = message_contact_link($user->id, 'add', true);
370 $strblock = message_contact_link($user->id, 'unblock', true);
e8e2d7f1 371 }
e8e2d7f1 372 } else {
082864f9 373 $strcontact = message_contact_link($user->id, 'add', true);
374 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 375 }
f520438c 376 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
082864f9 377
669be60c 378 echo '<tr><td class="pix">';
e520509a 379 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
e8e2d7f1 380 echo '</td>';
669be60c 381 echo '<td class="contact">';
5d6b319b 382 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
405f01ee 383 500, 500, get_string('sendmessageto', 'message', fullname($user)),
384 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
e8e2d7f1 385 echo '</td>';
386
669be60c 387 echo '<td class="link">'.$strcontact.'</td>';
388 echo '<td class="link">'.$strblock.'</td>';
389 echo '<td class="link">'.$strhistory.'</td>';
e8e2d7f1 390 echo '</tr>';
391 }
392 echo '</table>';
393
394 } else {
395 notify(get_string('nosearchresults', 'message'));
396 }
397
398
399 /// search messages for keywords
400 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
38c6a928 401 $keywordstring = clean_text(trim($frm->keywords));
402 $keywords = explode(' ', $keywordstring);
e8e2d7f1 403 $tome = false;
404 $fromme = false;
405 $courseid = 'none';
406
407 switch ($frm->keywordsoption) {
408 case 'tome':
409 $tome = true;
410 break;
411 case 'fromme':
412 $fromme = true;
413 break;
414 case 'allmine':
415 $tome = true;
416 $fromme = true;
417 break;
418 case 'allusers':
419 $courseid = SITEID;
420 break;
421 case 'courseusers':
422 $courseid = $frm->courseid;
423 break;
424 default:
425 $tome = true;
426 $fromme = true;
427 }
428
429 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
430
431 /// get a list of contacts
082864f9 432 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
433 $contacts = array();
434 }
e8e2d7f1 435
082864f9 436 /// print heading with number of results
669be60c 437 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
082864f9 438
439 /// print table headings
669be60c 440 echo '<table class="searchresults" cellspacing="0">';
082864f9 441 echo '<tr>';
fd7006f6 442 echo '<td><strong>'.get_string('from').'</strong></td>';
443 echo '<td><strong>'.get_string('to').'</strong></td>';
444 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
445 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
082864f9 446 echo "</tr>\n";
447
448 $blockedcount = 0;
e520509a 449 $dateformat = get_string('strftimedatetime');
38c6a928 450 $strcontext = get_string('context', 'message');
e8e2d7f1 451 foreach ($messages as $message) {
082864f9 452
453 /// ignore messages to and from blocked users unless $frm->includeblocked is set
b71d4dd2 454 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
082864f9 455 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
456 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
457 )
458 ) {
459 $blockedcount ++;
e8e2d7f1 460 continue;
461 }
082864f9 462
463 /// load up user to record
464 if ($message->useridto !== $USER->id) {
465 $userto = get_record('user', 'id', $message->useridto);
466 $tocontact = (array_key_exists($message->useridto, $contacts) and
467 ($contacts[$message->useridto]->blocked == 0) );
468 $toblocked = (array_key_exists($message->useridto, $contacts) and
469 ($contacts[$message->useridto]->blocked == 1) );
470 } else {
471 $userto = false;
472 $tocontact = false;
473 $toblocked = false;
474 }
475
476 /// load up user from record
477 if ($message->useridfrom !== $USER->id) {
478 $userfrom = get_record('user', 'id', $message->useridfrom);
479 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
480 ($contacts[$message->useridfrom]->blocked == 0) );
481 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
482 ($contacts[$message->useridfrom]->blocked == 1) );
483 } else {
484 $userfrom = false;
485 $fromcontact = false;
486 $fromblocked = false;
487 }
488
e520509a 489 /// find date string for this message
490 $date = usergetdate($message->timecreated);
491 $datestring = $date['year'].$date['mon'].$date['mday'];
492
082864f9 493 /// print out message row
494 echo '<tr valign="top">';
669be60c 495 echo '<td class="contact">';
b9ee0638 496 message_print_user($userfrom, $fromcontact, $fromblocked);
e8e2d7f1 497 echo '</td>';
669be60c 498 echo '<td class="contact">';
b9ee0638 499 message_print_user($userto, $tocontact, $toblocked);
e8e2d7f1 500 echo '</td>';
669be60c 501 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
502 echo '<br /><div class="link">';
e6ca6912 503 message_history_link($message->useridto, $message->useridfrom, false,
2973ec18 504 $keywordstring, 'm'.$message->id, $strcontext);
f520438c 505 echo '</div>';
e520509a 506 echo '</td>';
669be60c 507 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 508 echo "</tr>\n";
509 }
510
e8e2d7f1 511
e520509a 512 if ($blockedcount > 0) {
513 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
514 }
e8e2d7f1 515 echo '</table>';
516
517 } else {
518 notify(get_string('nosearchresults', 'message'));
519 }
520
521
522 /// what the ????, probably an empty search string, duh!
523 } else {
524 notify(get_string('emptysearchstring', 'message'));
525 }
526
082864f9 527 echo '<br />';
9ae3253e 528 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
e8e2d7f1 529
530 echo '</div>';
531}
532
533
082864f9 534function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
535 global $USER;
536 if ($user === false) {
e520509a 537 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
082864f9 538 } else {
e520509a 539 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
540 echo '&nbsp;';
082864f9 541 if ($iscontact) {
542 message_contact_link($user->id, 'remove');
543 } else {
544 message_contact_link($user->id, 'add');
545 }
546 echo '&nbsp;';
547 if ($isblocked) {
548 message_contact_link($user->id, 'unblock');
549 } else {
550 message_contact_link($user->id, 'block');
551 }
e520509a 552 echo '<br />';
5d6b319b 553 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
405f01ee 554 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
555 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
082864f9 556 }
557}
558
559
560/// linktype can be: add, remove, block, unblock
5d6b319b 561function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
e520509a 562 global $USER, $CFG;
563
564 static $str;
565
566 if (empty($str->blockcontact)) {
567 $str->blockcontact = get_string('blockcontact', 'message');
568 $str->unblockcontact = get_string('unblockcontact', 'message');
569 $str->removecontact = get_string('removecontact', 'message');
570 $str->addcontact = get_string('addcontact', 'message');
571 }
572
5d6b319b 573 $command = $linktype.'contact';
574 $string = $str->{$command};
575 $text = $text ? '&nbsp;'.$string : '';
576
082864f9 577 switch ($linktype) {
578 case 'block':
5d6b319b 579 $icon = '/t/go.gif';
082864f9 580 break;
581 case 'unblock':
5d6b319b 582 $icon = '/t/stop.gif';
082864f9 583 break;
584 case 'remove':
5d6b319b 585 $icon = '/t/user.gif';
082864f9 586 break;
587 case 'add':
588 default:
5d6b319b 589 $icon = '/t/usernot.gif';
082864f9 590 }
5d6b319b 591
592 $output = '<span class="'.$linktype.'">'.
593 '<a href="'.$script.'&amp;'.$command.'='.$userid.
0d3bb48d 594 '&amp;sesskey='.sesskey().'" title="'.s($string).'">'.
595 '<img src="'.$CFG->pixpath.$icon.'" height="11" width="11" border="0" alt="'.s($string).'" />'.
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='') {
fd7006f6 607 global $USER, $CFG;
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
0d3bb48d 626 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0" alt="'.$strmessagehistory.'" />';
830d0af6 627 } else if ($linktext == 'both') { // Icon and standard name
0d3bb48d 628 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0" alt="'.$strmessagehistory.'" />';
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
38c6a928 636 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$keywords$position",
669be60c 637 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
5fb86983 638 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
62119d65 639
5d6b319b 640 $str = '<span class="history">'.$str.'</span>';
641
62119d65 642 if ($returnstr) {
643 return $str;
644 } else {
645 echo $str;
646 return true;
647 }
648}
e8e2d7f1 649
650
651/**
652 * Search through course users
653 *
654 * If $coursid specifies the site course then this function searches
655 * through all undeleted and confirmed users
656 *
657 * @uses $CFG
658 * @uses SITEID
659 * @param int $courseid The course in question.
660 * @param string $searchtext ?
661 * @param string $sort ?
662 * @param string $exceptions ?
663 * @return array An array of {@link $USER} records.
664 * @todo Finish documenting this function
665 */
666function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
667 global $CFG;
668
92a2d92a 669 $fullname = sql_fullname();
6eb7722f 670 $LIKE = sql_ilike();
e8e2d7f1 671
672 if (!empty($exceptions)) {
673 $except = ' AND u.id NOT IN ('. $exceptions .') ';
674 } else {
675 $except = '';
676 }
677
678 if (!empty($sort)) {
679 $order = ' ORDER BY '. $sort;
680 } else {
681 $order = '';
682 }
683
684 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
444f6252 685 $fields = 'u.id, u.firstname, u.lastname, u.picture';
e8e2d7f1 686
687 if (!$courseid or $courseid == SITEID) {
444f6252 688 return get_records_sql("SELECT $fields
e8e2d7f1 689 FROM {$CFG->prefix}user u
690 WHERE $select
691 AND ($fullname $LIKE '%$searchtext%')
692 $except $order");
693 } else {
694
d76a5a7f 695 $context = get_context_instance(CONTEXT_COURSE, $courseid);
696 $contextlists = get_related_contexts_string($context);
697
698 // everyone who has a role assignement in this course or higher
699 $users = get_records_sql("SELECT $fields
700 FROM {$CFG->prefix}user u,
701 {$CFG->prefix}role_assignments ra
702 WHERE $select
703 AND ra.contextid $contextlists
704 AND u.id = ra.userid
705 AND ($fullname $LIKE '%$searchtext%')
706 $except $order");
707
708 return $users;
e8e2d7f1 709 }
710}
711
712
713
714
082864f9 715function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 716/// Returns a list of posts found using an array of search terms
717/// eg word +word -word
718///
719
720 global $CFG, $USER;
721
082864f9 722 /// If no userid sent then assume current user
723 if ($userid == 0) $userid = $USER->id;
724
6eb7722f 725 /// Some differences in SQL syntax
726 $LIKE = sql_ilike();
727 $NOTLIKE = 'NOT ' . $LIKE;
e8e2d7f1 728 if ($CFG->dbtype == "postgres7") {
e8e2d7f1 729 $REGEXP = "~*";
730 $NOTREGEXP = "!~*";
731 } else {
e8e2d7f1 732 $REGEXP = "REGEXP";
733 $NOTREGEXP = "NOT REGEXP";
734 }
735
736 $messagesearch = "";
737
738 foreach ($searchterms as $searchterm) {
739 if (strlen($searchterm) < 2) {
740 continue;
741 }
6bb4875f 742 /// Under Oracle and MSSQL, trim the + and - operators and perform
743 /// simpler LIKE search
744 if ($CFG->dbtype == 'oci8po' || $CFG->dbtype == 'mssql' || $CFG->dbtype == 'mssql_n' || $CFG->dbtype == 'odbc_mssql') {
745 $searchterm = trim($searchterm, '+-');
746 }
747
e8e2d7f1 748 if ($messagesearch) {
749 $messagesearch .= " AND ";
750 }
751
752 if (substr($searchterm,0,1) == "+") {
753 $searchterm = substr($searchterm,1);
754 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
755 } else if (substr($searchterm,0,1) == "-") {
756 $searchterm = substr($searchterm,1);
757 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
758 } else {
759 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
760 }
172186b8 761 }
762
8a51efe9 763 if ($messagesearch == '') { // if only 1 letter words searched
764 return false;
765 }
e8e2d7f1 766
767 $messagesearch = "($messagesearch) ";
768
769
082864f9 770 /// There are several possibilities
771 /// 1. courseid = SITEID : The admin is searching messages by all users
772 /// 2. courseid = ?? : A teacher is searching messages by users in
773 /// one of their courses - currently disabled
774 /// 3. courseid = none : User is searching their own messages;
775 /// a. Messages from user
776 /// b. Messages to user
777 /// c. Messages to and from user
778
779 if ($courseid == SITEID) { /// admin is searching all messages
780 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
781 FROM {$CFG->prefix}message_read m
782 WHERE $messagesearch");
783 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
784 FROM {$CFG->prefix}message m
785 WHERE $messagesearch");
786
787 if ($m_read === false) $m_read = array();
788 if ($m_unread === false) $m_unread = array();
e8e2d7f1 789
082864f9 790 } elseif ($courseid !== 'none') {
791 /// This has not been implemented due to security concerns
e8e2d7f1 792
082864f9 793 } else {
794
795 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
796 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
797 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
798
799 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
800 FROM {$CFG->prefix}message_read m
801 WHERE $messagesearch");
802 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
803 FROM {$CFG->prefix}message m
804 WHERE $messagesearch");
805
806 if ($m_read === false) $m_read = array();
807 if ($m_unread === false) $m_unread = array();
808
e8e2d7f1 809 }
810
082864f9 811 /// The keys may be duplicated in $m_read and $m_unread so we can't
812 /// do a simple concatenation
813 $message = array();
814 foreach ($m_read as $m) $messages[] = $m;
815 foreach ($m_unread as $m) $messages[] = $m;
e8e2d7f1 816
e8e2d7f1 817
818 return (empty($messages)) ? false : $messages;
172186b8 819}
820
e8e2d7f1 821
822
823/// Borrowed with changes from mod/forum/lib.php
824function message_shorten_message($message, $minlength=0) {
825// Given a post object that we already know has a long message
826// this function truncates the message nicely to the first
827// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
828
829 $i = 0;
830 $tag = false;
831 $length = strlen($message);
832 $count = 0;
833 $stopzone = false;
834 $truncate = 0;
835 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
836
837
838 for ($i=0; $i<$length; $i++) {
839 $char = $message[$i];
840
841 switch ($char) {
842 case "<":
843 $tag = true;
844 break;
845 case ">":
846 $tag = false;
847 break;
848 default:
849 if (!$tag) {
850 if ($stopzone) {
851 if ($char == '.' or $char == ' ') {
852 $truncate = $i+1;
853 break 2;
854 }
855 }
856 $count++;
857 }
858 break;
859 }
860 if (!$stopzone) {
861 if ($count > $minlength) {
862 $stopzone = true;
863 }
864 }
865 }
866
867 if (!$truncate) {
868 $truncate = $i;
869 }
870
871 return substr($message, 0, $truncate);
872}
873
38c6a928 874
875/*
876 * Given a string and an array of keywords, this function looks
877 * for the first keyword in the string, and then chops out a
878 * small section from the text that shows that word in context.
879 */
880function message_get_fragment($message, $keywords) {
881
882 $fullsize = 120;
883 $halfsize = (int)($fullsize/2);
884
885 $message = strip_tags($message);
886
887 foreach ($keywords as $keyword) { // Just get the first one
888 if ($keyword !== '') {
889 break;
890 }
891 }
892 if (empty($keyword)) { // None found, so just return start of message
893 return message_shorten_message($message, 30);
894 }
895
896 $leadin = $leadout = '';
897
898/// Find the start of the fragment
899 $start = 0;
900 $length = strlen($message);
901
902 $pos = strpos($message, $keyword);
903 if ($pos > $halfsize) {
904 $start = $pos - $halfsize;
905 $leadin = '...';
906 }
907/// Find the end of the fragment
908 $end = $start + $fullsize;
909 if ($end > $length) {
910 $end = $length;
911 } else {
912 $leadout = '...';
913 }
914
915/// Pull out the fragment and format it
916
917 $fragment = substr($message, $start, $end - $start);
918 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
919 return $fragment;
920}
921
922
b9ee0638 923function message_get_history($user1, $user2) {
924 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
925 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
926 'timecreated');
927 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
928 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
929 'timecreated')) {
930 foreach ($messages_new as $message) {
931 $messages[] = $message;
932 }
933 }
934 return $messages;
935}
936
030e3e03 937function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
acd21a2d 938
939 static $dateformat;
940
941 if (empty($dateformat)) {
942 if ($format) {
943 $dateformat = $format;
944 } else {
945 $format = get_string('strftimedaytime');
946 }
b9ee0638 947 }
acd21a2d 948 $time = userdate($message->timecreated, $dateformat);
ff6048dd 949 $options->para = false;
950 $messagetext = format_text($message->message, $message->format, $options);
38c6a928 951 if ($keywords) {
952 $messagetext = highlight($keywords, $messagetext);
953 }
030e3e03 954 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 955}
e8e2d7f1 956
405f01ee 957/*
958 * Inserts a message into the database, but also forwards it
959 * via other means if appropriate.
960 */
961function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
962
963 global $CFG, $SITE;
964
965/// Save the new message in the database
966
967 $savemessage = NULL;
968 $savemessage->useridfrom = $userfrom->id;
969 $savemessage->useridto = $userto->id;
970 $savemessage->message = $message;
971 $savemessage->format = $format;
972 $savemessage->timecreated = time();
973 $savemessage->messagetype = 'direct';
974
2973ec18 975 if (!$savemessage->id = insert_record('message', $savemessage)) {
405f01ee 976 return false;
977 }
978
979
980/// Check to see if anything else needs to be done with it
981
982 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
983
54bf5de8 984 if (!isset($preference->message_emailmessages) or $preference->message_emailmessages) { // Receiver wants mail forwarding
985 if (!isset($preference->message_emailtimenosee)) {
986 $preference->message_emailtimenosee = 10;
987 }
7c8b82a9 988 if (!isset($preference->message_emailformat)) {
989 $preference->message_emailformat = FORMAT_HTML;
990 }
405f01ee 991 if ((time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
992
993 $message = stripslashes_safe($message);
994 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
995
996 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
997
998 $messagetext = format_text_email($message, $format).
999 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1000
49487025 1001 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
405f01ee 1002 $messagehtml = format_text($message, $format);
1003 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1004 } else {
1005 $messagehtml = NULL;
1006 }
1007
54bf5de8 1008 if (!empty($preference->message_emailaddress)) {
1009 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1010 }
405f01ee 1011 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
1012 }
1013 }
1014
2973ec18 1015 return $savemessage->id;
405f01ee 1016}
e8e2d7f1 1017
c135a425 1018
1019/*
1020 * Returns a list of all user ids who have used messaging in the site
1021 * This was the simple way to code the SQL ... is it going to blow up
1022 * on large datasets?
1023 */
1024function message_get_participants() {
1025
1026 global $CFG;
1027
7686b6b1 1028 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1029 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1030 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1031 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1032 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1033 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");
c135a425 1034}
1035
172186b8 1036?>