Some tweaks here and there to the display
[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
8if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 30 seconds
9 $CFG->message_contacts_refresh = 30;
10}
11if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
12 $CFG->message_chat_refresh = 5;
13}
172186b8 14
15
16function message_print_contacts() {
e8e2d7f1 17 global $USER, $CFG;
18
19 $timetoshowusers = 300; //Seconds default
20 if (isset($CFG->block_online_users_timetosee)) {
21 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
22 }
23 $timefrom = time()-$timetoshowusers;
24
25
26 /// get lists of contacts and unread messages
444f6252 27 $onlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
e8e2d7f1 28 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
29 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess>=$timefrom
30 AND mc.blocked='0'
fd7006f6 31 ORDER BY u.firstname ASC");
e8e2d7f1 32
444f6252 33 $offlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
e8e2d7f1 34 FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
35 WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess<$timefrom
36 AND mc.blocked='0'
fd7006f6 37 ORDER BY u.firstname ASC");
e8e2d7f1 38
39 $unreadmessages = get_records_sql("SELECT m.id, m.useridfrom, u.firstname, u.lastname, u.picture
40 FROM {$CFG->prefix}user u, {$CFG->prefix}message m
41 WHERE m.useridto='$USER->id' AND u.id=m.useridfrom");
42
43 $blockedcontacts = get_records_select('message_contacts', "userid='$USER->id' AND blocked='1'", '', 'contactid, id');
44
45
e520509a 46 echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0" border="0">';
e8e2d7f1 47
48
49/// print out list of online contacts
e8e2d7f1 50
51 $countcontacts = (is_array($onlinecontacts)) ? count($onlinecontacts) : 0;
52
fd7006f6 53 echo '<tr><td colspan="3" class="message_heading">';
54 echo get_string('onlinecontacts', 'message', $countcontacts);
e8e2d7f1 55 echo '</td></tr>';
56
57 if (!empty($onlinecontacts)) {
58 foreach ($onlinecontacts as $contact) {
59 if ($contact->blocked == 1) continue;
e520509a 60 $fullname = fullname($contact);
61 $fullnamelink = $fullname;
e8e2d7f1 62 /// are there any unread messages for this contact?
63 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
e520509a 64 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
e8e2d7f1 65 }
66 /// link to remove from contact list
ce2d60ad 67 $strcontact = message_contact_link($contact->id, 'remove', true);
68 $strhistory = message_contact_link($contact->id, 'history', true);
e8e2d7f1 69
b9ee0638 70 echo '<tr><td class="message_pix">';
e520509a 71 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
e8e2d7f1 72 echo '</td>';
73 echo '<td class="message_contact">';
405f01ee 74 link_to_popup_window("/message/user.php?id=$contact->id", "message_$contact->id",
75 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
76 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
e8e2d7f1 77 echo '</td>';
ce2d60ad 78 echo '<td class="message_link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
e8e2d7f1 79 echo '</tr>';
80 }
81 }
82 echo '<tr><td colspan="3">&nbsp;</td></tr>';
e8e2d7f1 83
84
85/// print out list of offline contacts
e8e2d7f1 86
87 $countcontacts = (is_array($offlinecontacts)) ? count($offlinecontacts) : 0;
88
fd7006f6 89 echo '<tr><td colspan="3" class="message_heading">';
90 echo get_string('offlinecontacts', 'message', $countcontacts);
e8e2d7f1 91 echo '</td></tr>';
92
93 if (!empty($offlinecontacts)) {
94 foreach ($offlinecontacts as $contact) {
95 if ($contact->blocked == 1) continue;
e520509a 96 $fullname = fullname($contact);
97 $fullnamelink = $fullname;
e8e2d7f1 98 /// are there any unread messages for this contact?
99 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
e520509a 100 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
e8e2d7f1 101 }
102 /// link to remove from contact list
e520509a 103 $strcontact = message_contact_link($contact->id, 'remove', true);
ce2d60ad 104 $strhistory = message_contact_link($contact->id, 'history', true);
e8e2d7f1 105
b9ee0638 106 echo '<tr><td class="message_pix">';
e520509a 107 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
e8e2d7f1 108 echo '</td>';
109 echo '<td class="message_contact">';
405f01ee 110 link_to_popup_window("/message/user.php?id=$contact->id", "message_$contact->id",
111 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
112 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
e8e2d7f1 113 echo '</td>';
ce2d60ad 114 echo '<td class="message_link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
e8e2d7f1 115 echo '</tr>';
116 }
117 }
118 echo '<tr><td colspan="3">&nbsp;</td></tr>';
e8e2d7f1 119
120
121/// Cycle through messages and extract those that are from unknown contacts
122/// We can take advantage of the keys for $onlinecontacts and $offlinecontacts
123/// which are set to the userid and therefore we just need to see if the key
124/// exists in either of those arrays
125/// We can also discard any messages from users in our blocked contact list
126 $unknownmessages = array();
127 if (!empty($unreadmessages)) {
128 /// make sure we have valid arrays to test against - they may be boolean false
129 if (empty($onlinecontacts)) $onlinecontacts = array();
130 if (empty($offlinecontacts)) $offlinecontacts = array();
131 if (empty($blockedcontacts)) $blockedcontacts = array();
132 foreach ($unreadmessages as $unreadmessage) {
133 if (array_key_exists($unreadmessage->useridfrom, $onlinecontacts) or
134 array_key_exists($unreadmessage->useridfrom, $offlinecontacts) or
135 array_key_exists($unreadmessage->useridfrom, $blockedcontacts) ) {
136 continue;
137 }
138 if (!isset($unknownmessages[$unreadmessage->useridfrom])) {
139 $message = $unreadmessage;
140 $message->count = 1;
141 $unknownmessages[$unreadmessage->useridfrom] = $message;
142 } else {
143 $unknownmessages[$unreadmessage->useridfrom]->count++;
144 }
145 }
146 }
147
148/// print out list of incoming contacts
149 if (!empty($unknownmessages)) {
fd7006f6 150 echo '<tr><td colspan="3" class="message_heading">';
151 echo get_string('incomingcontacts', 'message', count($unknownmessages));
e8e2d7f1 152 echo '</td></tr>';
e8e2d7f1 153
e8e2d7f1 154 foreach ($unknownmessages as $messageuser) {
e520509a 155 $fullname = fullname($messageuser);
156 $fullnamelink = $fullname;
157 if ($messageuser->count) {
158 $fullnamelink = '<strong>'.$fullnamelink.' ('.$messageuser->count.')</strong>';
159 }
e8e2d7f1 160 /// link to add to contact list
082864f9 161
e520509a 162 $strcontact = message_contact_link($messageuser->useridfrom, 'add', true);
444f6252 163 $strblock = message_contact_link($messageuser->useridfrom, 'block', true);
ce2d60ad 164 $strhistory = message_contact_link($messageuser->useridfrom, 'history', true);
e8e2d7f1 165
b9ee0638 166 echo '<tr><td class="message_pix">';
e520509a 167 print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, true, 'userwindow');
e8e2d7f1 168 echo '</td>';
169 echo '<td class="message_contact">';
405f01ee 170 link_to_popup_window("/message/user.php?id=$messageuser->useridfrom", "message_$messageuser->useridfrom",
171 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
172 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
e8e2d7f1 173 echo '</td>';
ce2d60ad 174 echo '<td class="message_link">&nbsp;'.$strcontact.'&nbsp;'.$strblock.'&nbsp;'.$strhistory.'</td>';
e8e2d7f1 175 echo '</tr>';
176 }
e8e2d7f1 177 }
178
179 echo '</table>';
b9ee0638 180
fd7006f6 181 echo '<p align="center" class="message_small_note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
e8e2d7f1 182}
183
184
185
186
187/// $messagearray is an array of objects
188/// $field is a valid property of object
189/// $value is the value $field should equal to be counted
190/// if $field is empty then return count of the whole array
191/// if $field is non-existent then return 0;
192function message_count_messages($messagearray, $field='', $value='') {
193 if (!is_array($messagearray)) return 0;
194 if ($field == '' or empty($messagearray)) return count($messagearray);
195
196 $count = 0;
197 foreach ($messagearray as $message) {
198 $count += ($message->$field == $value) ? 1 : 0;
199 }
200 return $count;
172186b8 201}
202
e8e2d7f1 203
172186b8 204function message_print_search() {
444f6252 205 global $ME, $USER;
172186b8 206
207 if ($frm = data_submitted()) {
208
209 message_print_search_results($frm);
210
211 } else {
172186b8 212 if ($teachers = get_records('user_teachers', 'userid', $USER->id, '', 'id, course')) {
213
214 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
215 $cs = '<select name="courseselect">';
216 foreach ($teachers as $tcourse) {
217 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->course]->shortname."</option>\n";
218 }
219 $cs .= '</select>';
220 }
221
222 include('search.html');
223 }
224}
225
226function message_print_settings() {
e8e2d7f1 227 global $ME, $USER;
228
172186b8 229 if ($frm = data_submitted()) {
e8e2d7f1 230 $pref = array();
231 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
232 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
233 $pref['message_maxmessages'] = ((int)$frm->maxmessages > 0) ? (int)$frm->maxmessages : '20';
234 $pref['message_deletemessagesdays'] = ((int)($frm->deletemessagesdays) > 0) ? (int)$frm->deletemessagesdays : '30';
235 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
236 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
237 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
238 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
239
240 set_user_preferences($pref);
241
405f01ee 242 redirect($ME, 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"' : '';
e8e2d7f1 247 $txmaxmessages = get_user_preferences('message_maxmessages', 20);
248 $txdeletemessagesdays = get_user_preferences('message_deletemessagesdays', 30);
249 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
250 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
251 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
252 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
253 FORMAT_HTML => get_string('formathtml')),
254 'emailformat',
255 get_user_preferences('message_emailformat', FORMAT_PLAIN),
256 false, '', '0', true );
257
258 include('settings.html');
259}
260
261
262
263function message_add_contact($contactid, $blocked=0) {
264 global $USER;
265
266 if (!record_exists('user', 'id', $contactid)) { // invalid userid
267 return false;
268 }
269
270 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
271 /// record already exists - we may be changing blocking status
272
273 if ($contact->blocked !== $blocked) {
274 /// change to blocking status
275 $contact->blocked = $blocked;
276 return update_record('message_contacts', $contact);
277 } else {
278 /// no changes to blocking status
279 return true;
280 }
281
172186b8 282 } else {
e8e2d7f1 283 /// new contact record
284 unset($contact);
285 $contact->userid = $USER->id;
286 $contact->contactid = $contactid;
287 $contact->blocked = $blocked;
288 return insert_record('message_contacts', $contact, false);
172186b8 289 }
290}
291
e8e2d7f1 292function message_remove_contact($contactid) {
293 global $USER;
e8e2d7f1 294 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
295}
296
297function message_unblock_contact($contactid) {
082864f9 298 global $USER;
299 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
e8e2d7f1 300}
301
302function message_block_contact($contactid) {
303 return message_add_contact($contactid, 1);
304}
305
306function message_get_contact($contactid) {
307 global $USER;
308 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
309}
310
311
312
172186b8 313function message_print_search_results($frm) {
fd7006f6 314 global $ME, $USER, $CFG;
e8e2d7f1 315
316 echo '<div align="center">';
317
318 /// search for person
319 if (!empty($frm->personsubmit) and !empty($frm->name)) {
320
321 if ($frm->mycourses) {
322 $users = array();
323 $mycourses = get_my_courses($USER->id);
324 foreach ($mycourses as $mycourse) {
325 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
326 foreach ($susers as $suser) $users[$suser->id] = $suser;
327 }
328 }
329 } else {
330 $users = message_search_users(SITEID, $frm->name);
331 }
332
333 if (!empty($users)) {
334 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
335 echo '<table class="message_users">';
336 foreach ($users as $user) {
082864f9 337
e8e2d7f1 338 if (($contact = message_get_contact($user->id)) !== false) {
339 if ($contact->blocked == 0) { /// not blocked
082864f9 340 $strcontact = message_contact_link($user->id, 'remove', true);
341 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 342 } else { // blocked
082864f9 343 $strcontact = message_contact_link($user->id, 'add', true);
344 $strblock = message_contact_link($user->id, 'unblock', true);
e8e2d7f1 345 }
e8e2d7f1 346 } else {
082864f9 347 $strcontact = message_contact_link($user->id, 'add', true);
348 $strblock = message_contact_link($user->id, 'block', true);
e8e2d7f1 349 }
082864f9 350
b9ee0638 351 echo '<tr><td class="message_pix">';
e520509a 352 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
e8e2d7f1 353 echo '</td>';
354 echo '<td class="message_contact">';
405f01ee 355 link_to_popup_window("/message/user.php?id=$user->id", "message_$user->id", fullname($user),
356 500, 500, get_string('sendmessageto', 'message', fullname($user)),
357 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
e8e2d7f1 358 echo '</td>';
359
360 echo '<td class="message_link">'.$strcontact.'</td>';
361 echo '<td class="message_link">'.$strblock.'</td>';
362 echo '</tr>';
363 }
364 echo '</table>';
365
366 } else {
367 notify(get_string('nosearchresults', 'message'));
368 }
369
370
371 /// search messages for keywords
372 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
373 $keywords = explode(' ', $frm->keywords);
374 $tome = false;
375 $fromme = false;
376 $courseid = 'none';
377
378 switch ($frm->keywordsoption) {
379 case 'tome':
380 $tome = true;
381 break;
382 case 'fromme':
383 $fromme = true;
384 break;
385 case 'allmine':
386 $tome = true;
387 $fromme = true;
388 break;
389 case 'allusers':
390 $courseid = SITEID;
391 break;
392 case 'courseusers':
393 $courseid = $frm->courseid;
394 break;
395 default:
396 $tome = true;
397 $fromme = true;
398 }
399
400 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
401
402 /// get a list of contacts
082864f9 403 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
404 $contacts = array();
405 }
e8e2d7f1 406
082864f9 407 /// print heading with number of results
fd7006f6 408 echo '<strong>'.get_string('keywordssearchresults', 'message', count($messages)).'</strong>';
082864f9 409
410 /// print table headings
fd7006f6 411 echo '<table class="message_search_results">';
082864f9 412 echo '<tr>';
fd7006f6 413 echo '<td><strong>'.get_string('from').'</strong></td>';
414 echo '<td><strong>'.get_string('to').'</strong></td>';
415 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
416 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
082864f9 417 echo "</tr>\n";
418
419 $blockedcount = 0;
e520509a 420 $dateformat = get_string('strftimedatetime');
fd7006f6 421 $strmore = get_string('more');
e8e2d7f1 422 foreach ($messages as $message) {
082864f9 423
424 /// ignore messages to and from blocked users unless $frm->includeblocked is set
425 if ((!$frm->includeblocked) and (
426 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
427 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
428 )
429 ) {
430 $blockedcount ++;
e8e2d7f1 431 continue;
432 }
082864f9 433
434 /// load up user to record
435 if ($message->useridto !== $USER->id) {
436 $userto = get_record('user', 'id', $message->useridto);
437 $tocontact = (array_key_exists($message->useridto, $contacts) and
438 ($contacts[$message->useridto]->blocked == 0) );
439 $toblocked = (array_key_exists($message->useridto, $contacts) and
440 ($contacts[$message->useridto]->blocked == 1) );
441 } else {
442 $userto = false;
443 $tocontact = false;
444 $toblocked = false;
445 }
446
447 /// load up user from record
448 if ($message->useridfrom !== $USER->id) {
449 $userfrom = get_record('user', 'id', $message->useridfrom);
450 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
451 ($contacts[$message->useridfrom]->blocked == 0) );
452 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
453 ($contacts[$message->useridfrom]->blocked == 1) );
454 } else {
455 $userfrom = false;
456 $fromcontact = false;
457 $fromblocked = false;
458 }
459
e520509a 460 /// find date string for this message
461 $date = usergetdate($message->timecreated);
462 $datestring = $date['year'].$date['mon'].$date['mday'];
463
082864f9 464 /// print out message row
465 echo '<tr valign="top">';
466 echo '<td class="message_contact">';
b9ee0638 467 message_print_user($userfrom, $fromcontact, $fromblocked);
e8e2d7f1 468 echo '</td>';
469 echo '<td class="message_contact">';
b9ee0638 470 message_print_user($userto, $tocontact, $toblocked);
e8e2d7f1 471 echo '</td>';
e520509a 472 echo '<td class="message_summary">'.message_shorten_message($message->message, 20);
fd7006f6 473 echo ' ...('.message_history_link($message->useridto, $message->useridfrom, true, $datestring,
474 $strmore.'&nbsp;<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">').')';
e520509a 475 echo '</td>';
476 echo '<td class="message_date">'.userdate($message->timecreated, $dateformat).'</td>';
082864f9 477 echo "</tr>\n";
478 }
479
e8e2d7f1 480
e520509a 481 if ($blockedcount > 0) {
482 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
483 }
e8e2d7f1 484 echo '</table>';
485
486 } else {
487 notify(get_string('nosearchresults', 'message'));
488 }
489
490
491 /// what the ????, probably an empty search string, duh!
492 } else {
493 notify(get_string('emptysearchstring', 'message'));
494 }
495
082864f9 496 echo '<br />';
e8e2d7f1 497 print_single_button($ME, array( 'tab' => 'search'), get_string('newsearch', 'message') );
498
499 echo '</div>';
500}
501
502
082864f9 503function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
504 global $USER;
505 if ($user === false) {
e520509a 506 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
082864f9 507 } else {
e520509a 508 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
509 echo '&nbsp;';
082864f9 510 if ($iscontact) {
511 message_contact_link($user->id, 'remove');
512 } else {
513 message_contact_link($user->id, 'add');
514 }
515 echo '&nbsp;';
516 if ($isblocked) {
517 message_contact_link($user->id, 'unblock');
518 } else {
519 message_contact_link($user->id, 'block');
520 }
e520509a 521 echo '<br />';
405f01ee 522 link_to_popup_window("/message/user.php?id=$user->id", "message_$user->id",
523 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
524 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
082864f9 525 }
526}
527
528
529/// linktype can be: add, remove, block, unblock
e520509a 530function message_contact_link($userid, $linktype='add', $return=false) {
531 global $USER, $CFG;
532
533 static $str;
534
535 if (empty($str->blockcontact)) {
536 $str->blockcontact = get_string('blockcontact', 'message');
537 $str->unblockcontact = get_string('unblockcontact', 'message');
538 $str->removecontact = get_string('removecontact', 'message');
539 $str->addcontact = get_string('addcontact', 'message');
ce2d60ad 540 $str->messagehistory = get_string('messagehistory', 'message');
e520509a 541 }
542
082864f9 543 switch ($linktype) {
ce2d60ad 544 case 'history':
545 $output = '<a target="message_history_'.$userid.'" title="'.$str->messagehistory.'" href="'.$CFG->wwwroot.'/message/history.php?user1='.$userid.'" onclick="return openpopup(\'/message/history.php?user1='.$userid.'\', \'message_history_'.$userid.'\', \'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500\', 0);"><img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0"></a>';
546 break;
082864f9 547 case 'block':
e520509a 548 $output = '<a href="index.php?tab=contacts&amp;blockcontact='.$userid.
549 '&amp;sesskey='.$USER->sesskey.'" title="'.$str->blockcontact.'">'.
550 '<img src="'.$CFG->pixpath.'/t/go.gif" height="11" width="11" border="0"></a>';
082864f9 551 break;
552 case 'unblock':
e520509a 553 $output = '<a href="index.php?tab=contacts&amp;unblockcontact='.$userid.
554 '&amp;sesskey='.$USER->sesskey.'" title="'.$str->unblockcontact.'">'.
555 '<img src="'.$CFG->pixpath.'/t/stop.gif" height="11" width="11" border="0"></a>';
082864f9 556 break;
557 case 'remove':
e520509a 558 $output = '<a href="index.php?tab=contacts&amp;removecontact='.$userid.
559 '&amp;sesskey='.$USER->sesskey.'" title="'.$str->removecontact.'">'.
560 '<img src="'.$CFG->pixpath.'/t/user.gif" height="11" width="11" border="0"></a>';
082864f9 561 break;
562 case 'add':
563 default:
e520509a 564 $output = '<a href="index.php?tab=contacts&amp;addcontact='.$userid.
565 '&amp;sesskey='.$USER->sesskey.'" title="'.$str->addcontact.'">'.
566 '<img src="'.$CFG->pixpath.'/t/usernot.gif" height="11" width="11" border="0"></a>';
082864f9 567
568 }
e520509a 569 if ($return) {
570 return $output;
082864f9 571 } else {
e520509a 572 echo $output;
082864f9 573 return true;
574 }
575}
576
fd7006f6 577function message_history_link ($userid1, $userid2=0, $returnstr=false, $position='', $linktext='') {
578 global $USER, $CFG;
62119d65 579
580 if (!$userid2) {
581 $userid2 = $USER->id;
582 }
e520509a 583 if ($position) {
584 $position = "#$position";
585 }
62119d65 586
fd7006f6 587 if ($linktext == 'icon') {
588 $linktext = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">';
589 } else if ($linktext == '') {
590 $linktext = get_string('messagehistory', 'message');
591 }
592
e520509a 593 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$position",
fd7006f6 594 "message_history_$user->id", $linktext, 500, 500, '',
5fb86983 595 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
62119d65 596
597 if ($returnstr) {
598 return $str;
599 } else {
600 echo $str;
601 return true;
602 }
603}
e8e2d7f1 604
605
606/**
607 * Search through course users
608 *
609 * If $coursid specifies the site course then this function searches
610 * through all undeleted and confirmed users
611 *
612 * @uses $CFG
613 * @uses SITEID
614 * @param int $courseid The course in question.
615 * @param string $searchtext ?
616 * @param string $sort ?
617 * @param string $exceptions ?
618 * @return array An array of {@link $USER} records.
619 * @todo Finish documenting this function
620 */
621function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
622 global $CFG;
623
624 switch ($CFG->dbtype) {
625 case 'mysql':
626 $fullname = ' CONCAT(u.firstname," ",u.lastname) ';
627 $LIKE = 'LIKE';
628 break;
629 case 'postgres7':
630 $fullname = " u.firstname||' '||u.lastname ";
631 $LIKE = 'ILIKE';
632 break;
633 default:
634 $fullname = ' u.firstname||" "||u.lastname ';
635 $LIKE = 'ILIKE';
636 }
637
638 if (!empty($exceptions)) {
639 $except = ' AND u.id NOT IN ('. $exceptions .') ';
640 } else {
641 $except = '';
642 }
643
644 if (!empty($sort)) {
645 $order = ' ORDER BY '. $sort;
646 } else {
647 $order = '';
648 }
649
650 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
444f6252 651 $fields = 'u.id, u.firstname, u.lastname, u.picture';
e8e2d7f1 652
653 if (!$courseid or $courseid == SITEID) {
444f6252 654 return get_records_sql("SELECT $fields
e8e2d7f1 655 FROM {$CFG->prefix}user u
656 WHERE $select
657 AND ($fullname $LIKE '%$searchtext%')
658 $except $order");
659 } else {
660
661
444f6252 662 if (!$teachers = get_records_sql("SELECT $fields
e8e2d7f1 663 FROM {$CFG->prefix}user u,
664 {$CFG->prefix}user_teachers s
665 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
666 AND ($fullname $LIKE '%$searchtext%')
667 $except $order")) {
668 $teachers = array();
669 }
444f6252 670 if (!$students = get_records_sql("SELECT $fields
e8e2d7f1 671 FROM {$CFG->prefix}user u,
672 {$CFG->prefix}user_students s
673 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
674 AND ($fullname $LIKE '%$searchtext%')
675 $except $order")) {
676 $students = array();
677 }
678 return $teachers + $students;
679 }
680}
681
682
683
684
082864f9 685function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
e8e2d7f1 686/// Returns a list of posts found using an array of search terms
687/// eg word +word -word
688///
689
690 global $CFG, $USER;
691
082864f9 692 /// If no userid sent then assume current user
693 if ($userid == 0) $userid = $USER->id;
694
e8e2d7f1 695 /// Some differences in syntax for PostgreSQL
696 if ($CFG->dbtype == "postgres7") {
697 $LIKE = "ILIKE"; // case-insensitive
698 $NOTLIKE = "NOT ILIKE"; // case-insensitive
699 $REGEXP = "~*";
700 $NOTREGEXP = "!~*";
701 } else {
702 $LIKE = "LIKE";
703 $NOTLIKE = "NOT LIKE";
704 $REGEXP = "REGEXP";
705 $NOTREGEXP = "NOT REGEXP";
706 }
707
708 $messagesearch = "";
709
710 foreach ($searchterms as $searchterm) {
711 if (strlen($searchterm) < 2) {
712 continue;
713 }
714 if ($messagesearch) {
715 $messagesearch .= " AND ";
716 }
717
718 if (substr($searchterm,0,1) == "+") {
719 $searchterm = substr($searchterm,1);
720 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
721 } else if (substr($searchterm,0,1) == "-") {
722 $searchterm = substr($searchterm,1);
723 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
724 } else {
725 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
726 }
172186b8 727 }
728
e8e2d7f1 729
730 $messagesearch = "($messagesearch) ";
731
732
082864f9 733 /// There are several possibilities
734 /// 1. courseid = SITEID : The admin is searching messages by all users
735 /// 2. courseid = ?? : A teacher is searching messages by users in
736 /// one of their courses - currently disabled
737 /// 3. courseid = none : User is searching their own messages;
738 /// a. Messages from user
739 /// b. Messages to user
740 /// c. Messages to and from user
741
742 if ($courseid == SITEID) { /// admin is searching all messages
743 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
744 FROM {$CFG->prefix}message_read m
745 WHERE $messagesearch");
746 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
747 FROM {$CFG->prefix}message m
748 WHERE $messagesearch");
749
750 if ($m_read === false) $m_read = array();
751 if ($m_unread === false) $m_unread = array();
e8e2d7f1 752
082864f9 753 } elseif ($courseid !== 'none') {
754 /// This has not been implemented due to security concerns
e8e2d7f1 755
082864f9 756 } else {
757
758 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
759 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
760 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
761
762 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
763 FROM {$CFG->prefix}message_read m
764 WHERE $messagesearch");
765 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
766 FROM {$CFG->prefix}message m
767 WHERE $messagesearch");
768
769 if ($m_read === false) $m_read = array();
770 if ($m_unread === false) $m_unread = array();
771
e8e2d7f1 772 }
773
082864f9 774 /// The keys may be duplicated in $m_read and $m_unread so we can't
775 /// do a simple concatenation
776 $message = array();
777 foreach ($m_read as $m) $messages[] = $m;
778 foreach ($m_unread as $m) $messages[] = $m;
e8e2d7f1 779
e8e2d7f1 780
781 return (empty($messages)) ? false : $messages;
172186b8 782}
783
e8e2d7f1 784
785
786/// Borrowed with changes from mod/forum/lib.php
787function message_shorten_message($message, $minlength=0) {
788// Given a post object that we already know has a long message
789// this function truncates the message nicely to the first
790// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
791
792 $i = 0;
793 $tag = false;
794 $length = strlen($message);
795 $count = 0;
796 $stopzone = false;
797 $truncate = 0;
798 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
799
800
801 for ($i=0; $i<$length; $i++) {
802 $char = $message[$i];
803
804 switch ($char) {
805 case "<":
806 $tag = true;
807 break;
808 case ">":
809 $tag = false;
810 break;
811 default:
812 if (!$tag) {
813 if ($stopzone) {
814 if ($char == '.' or $char == ' ') {
815 $truncate = $i+1;
816 break 2;
817 }
818 }
819 $count++;
820 }
821 break;
822 }
823 if (!$stopzone) {
824 if ($count > $minlength) {
825 $stopzone = true;
826 }
827 }
828 }
829
830 if (!$truncate) {
831 $truncate = $i;
832 }
833
834 return substr($message, 0, $truncate);
835}
836
b9ee0638 837function message_get_history($user1, $user2) {
838 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
839 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
840 'timecreated');
841 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
842 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
843 'timecreated')) {
844 foreach ($messages_new as $message) {
845 $messages[] = $message;
846 }
847 }
848 return $messages;
849}
850
851function message_format_message(&$message, &$user, $format='') {
852 if (empty($format)) {
405f01ee 853 $format = get_string('strftimedaytime');
b9ee0638 854 }
855 $time = userdate($message->timecreated, $format);
405f01ee 856 return '<p><font size="-1"><strong>'.s($user->firstname).'</strong> ['.$time.']: '.
857 format_text($message->message, $message->format).'</font></p>';
b9ee0638 858}
e8e2d7f1 859
405f01ee 860/*
861 * Inserts a message into the database, but also forwards it
862 * via other means if appropriate.
863 */
864function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
865
866 global $CFG, $SITE;
867
868/// Save the new message in the database
869
870 $savemessage = NULL;
871 $savemessage->useridfrom = $userfrom->id;
872 $savemessage->useridto = $userto->id;
873 $savemessage->message = $message;
874 $savemessage->format = $format;
875 $savemessage->timecreated = time();
876 $savemessage->messagetype = 'direct';
877
878 if (!insert_record('message', $savemessage)) {
879 return false;
880 }
881
882
883/// Check to see if anything else needs to be done with it
884
885 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
886
887 if (!empty($preference->message_emailmessages)) { // Receiver wants mail forwarding
888 if ((time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
889
890 $message = stripslashes_safe($message);
891 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
892
893 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
894
895 $messagetext = format_text_email($message, $format).
896 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
897
898 if ($preference->message_emailformat == FORMAT_HTML) {
899 $messagehtml = format_text($message, $format);
900 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
901 } else {
902 $messagehtml = NULL;
903 }
904
905 $userto->email = $preference->message_emailaddress; // Use custom messaging address
906 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
907 }
908 }
909
910 return true;
911}
e8e2d7f1 912
172186b8 913?>