Bumped to 1.6.8
[moodle.git] / message / lib.php
blob93d82b510dbbc562dedde83f7238360cedff7581
1 <?php
2 /// library functions for messaging
5 define ('MESSAGE_SHORTLENGTH', 300);
6 define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
8 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
9 $CFG->message_contacts_refresh = 60;
11 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
12 $CFG->message_chat_refresh = 5;
14 if (!isset($CFG->message_offline_time)) {
15 $CFG->message_offline_time = 300;
19 function message_print_contacts() {
20 global $USER, $CFG;
22 $timetoshowusers = 300; //Seconds default
23 if (isset($CFG->block_online_users_timetosee)) {
24 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
26 $timefrom = time()-$timetoshowusers;
29 /// get lists of contacts and unread messages
30 $onlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
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'
34 ORDER BY u.firstname ASC");
36 $offlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture, mc.blocked
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'
40 ORDER BY u.firstname ASC");
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");
46 $blockedcontacts = get_records_select('message_contacts', "userid='$USER->id' AND blocked='1'", '', 'contactid, id');
49 $countonlinecontacts = (is_array($onlinecontacts)) ? count($onlinecontacts) : 0;
50 $countofflinecontacts = (is_array($offlinecontacts)) ? count($offlinecontacts) : 0;
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;
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++;
79 if ($countonlinecontacts + $countofflinecontacts == 0) {
80 echo '<div class="heading">';
81 print_string('contactlistempty', 'message');
82 echo '</div>';
83 echo '<div class="note">';
84 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
85 echo '</div>';
88 if(!empty($onlinecontacts) || !empty($offlinecontacts) || !empty($unknownmessages)) {
90 echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0" border="0">';
92 if(!empty($onlinecontacts)) {
93 /// print out list of online contacts
95 echo '<tr><td colspan="3" class="heading">';
96 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
97 echo '</td></tr>';
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>';
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');
112 echo '<tr><td class="pix">';
113 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
114 echo '</td>';
115 echo '<td class="contact">';
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>';
120 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
121 echo '</tr>';
124 echo '<tr><td colspan="3">&nbsp;</td></tr>';
127 if (!empty($offlinecontacts)) {
128 /// print out list of offline contacts
130 echo '<tr><td colspan="3" class="heading">';
131 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
132 echo '</td></tr>';
134 foreach ($offlinecontacts as $contact) {
135 if ($contact->blocked == 1) continue;
136 $fullname = fullname($contact);
137 $fullnamelink = $fullname;
138 /// are there any unread messages for this contact?
139 if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
140 $fullnamelink = '<strong>'.$fullnamelink.' ('.$unread.')</strong>';
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');
146 echo '<tr><td class="pix">';
147 print_user_picture($contact->id, SITEID, $contact->picture, 20, false, true, 'userwindow');
148 echo '</td>';
149 echo '<td class="contact">';
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>';
154 echo '<td class="link">'.$strcontact.'&nbsp;'.$strhistory.'</td>';
155 echo '</tr>';
157 echo '<tr><td colspan="3">&nbsp;</td></tr>';
161 /// print out list of incoming contacts
162 if (!empty($unknownmessages)) {
163 echo '<tr><td colspan="3" class="heading">';
164 echo get_string('incomingcontacts', 'message', count($unknownmessages));
165 echo '</td></tr>';
167 foreach ($unknownmessages as $messageuser) {
168 $fullname = fullname($messageuser);
169 $fullnamelink = $fullname;
170 if ($messageuser->count) {
171 $fullnamelink = '<strong>'.$fullnamelink.' ('.$messageuser->count.')</strong>';
173 /// link to add to contact list
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');
179 echo '<tr><td class="pix">';
180 print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, true, 'userwindow');
181 echo '</td>';
182 echo '<td class="contact">';
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>';
187 echo '<td class="link">&nbsp;'.$strcontact.'&nbsp;'.$strblock.'&nbsp;'.$strhistory.'</td>';
188 echo '</tr>';
192 echo '</table>';
194 if (!empty($unknownmessages) && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
195 echo '<div class="note">(';
196 print_string('addsomecontactsincoming', 'message');
197 echo ')</div>';
203 echo '<br /><p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh).'</p>';
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;
215 function message_count_messages($messagearray, $field='', $value='') {
216 if (!is_array($messagearray)) return 0;
217 if ($field == '' or empty($messagearray)) return count($messagearray);
219 $count = 0;
220 foreach ($messagearray as $message) {
221 $count += ($message->$field == $value) ? 1 : 0;
223 return $count;
227 function message_print_search() {
228 global $USER;
230 if ($frm = data_submitted()) {
232 message_print_search_results($frm);
234 } else {
235 if ($teachers = get_records('user_teachers', 'userid', $USER->id, '', 'id, course')) {
237 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
238 $cs = '<select name="courseselect">';
239 foreach ($teachers as $tcourse) {
240 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->course]->shortname."</option>\n";
242 $cs .= '</select>';
245 include('search.html');
249 function message_print_settings() {
250 global $USER;
252 if ($frm = data_submitted() and confirm_sesskey()) {
254 $pref = array();
255 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
256 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
257 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
258 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
259 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
260 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
261 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
262 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
264 set_user_preferences($pref);
266 redirect('index.php', get_string('settingssaved', 'message'), 1);
269 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
270 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
271 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
272 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
273 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
274 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
275 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
276 $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
277 FORMAT_HTML => get_string('formathtml')),
278 'emailformat',
279 get_user_preferences('message_emailformat', FORMAT_PLAIN),
280 false, '', '0', true );
282 include('settings.html');
287 function message_add_contact($contactid, $blocked=0) {
288 global $USER;
290 if (!record_exists('user', 'id', $contactid)) { // invalid userid
291 return false;
294 if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
295 /// record already exists - we may be changing blocking status
297 if ($contact->blocked !== $blocked) {
298 /// change to blocking status
299 $contact->blocked = $blocked;
300 return update_record('message_contacts', $contact);
301 } else {
302 /// no changes to blocking status
303 return true;
306 } else {
307 /// new contact record
308 unset($contact);
309 $contact->userid = $USER->id;
310 $contact->contactid = $contactid;
311 $contact->blocked = $blocked;
312 return insert_record('message_contacts', $contact, false);
316 function message_remove_contact($contactid) {
317 global $USER;
318 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
321 function message_unblock_contact($contactid) {
322 global $USER;
323 return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
326 function message_block_contact($contactid) {
327 return message_add_contact($contactid, 1);
330 function message_get_contact($contactid) {
331 global $USER;
332 return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
337 function message_print_search_results($frm) {
338 global $USER, $CFG;
340 echo '<div align="center">';
342 /// search for person
343 if (!empty($frm->personsubmit) and !empty($frm->name)) {
345 if ($frm->mycourses) {
346 $users = array();
347 $mycourses = get_my_courses($USER->id);
348 foreach ($mycourses as $mycourse) {
349 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
350 foreach ($susers as $suser) $users[$suser->id] = $suser;
353 } else {
354 $users = message_search_users(SITEID, $frm->name);
357 if (!empty($users)) {
358 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
359 echo '<table class="message_users">';
360 foreach ($users as $user) {
362 if (($contact = message_get_contact($user->id)) !== false) {
363 if ($contact->blocked == 0) { /// not blocked
364 $strcontact = message_contact_link($user->id, 'remove', true);
365 $strblock = message_contact_link($user->id, 'block', true);
366 } else { // blocked
367 $strcontact = message_contact_link($user->id, 'add', true);
368 $strblock = message_contact_link($user->id, 'unblock', true);
370 } else {
371 $strcontact = message_contact_link($user->id, 'add', true);
372 $strblock = message_contact_link($user->id, 'block', true);
374 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
376 echo '<tr><td class="pix">';
377 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
378 echo '</td>';
379 echo '<td class="contact">';
380 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
381 500, 500, get_string('sendmessageto', 'message', fullname($user)),
382 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
383 echo '</td>';
385 echo '<td class="link">'.$strcontact.'</td>';
386 echo '<td class="link">'.$strblock.'</td>';
387 echo '<td class="link">'.$strhistory.'</td>';
388 echo '</tr>';
390 echo '</table>';
392 } else {
393 notify(get_string('nosearchresults', 'message'));
397 /// search messages for keywords
398 } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
399 $keywordstring = clean_text(trim($frm->keywords));
400 $keywords = explode(' ', $keywordstring);
401 $tome = false;
402 $fromme = false;
403 $courseid = 'none';
405 switch ($frm->keywordsoption) {
406 case 'tome':
407 $tome = true;
408 break;
409 case 'fromme':
410 $fromme = true;
411 break;
412 case 'allmine':
413 $tome = true;
414 $fromme = true;
415 break;
416 case 'allusers':
417 $courseid = SITEID;
418 break;
419 case 'courseusers':
420 $courseid = $frm->courseid;
421 break;
422 default:
423 $tome = true;
424 $fromme = true;
427 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
429 /// get a list of contacts
430 if (($contacts = get_records('message_contacts', 'userid', $USER->id, '', 'contactid, blocked') ) === false) {
431 $contacts = array();
434 /// print heading with number of results
435 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
437 /// print table headings
438 echo '<table class="searchresults" cellspacing="0">';
439 echo '<tr>';
440 echo '<td><strong>'.get_string('from').'</strong></td>';
441 echo '<td><strong>'.get_string('to').'</strong></td>';
442 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
443 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
444 echo "</tr>\n";
446 $blockedcount = 0;
447 $dateformat = get_string('strftimedatetime');
448 $strcontext = get_string('context', 'message');
449 foreach ($messages as $message) {
451 /// ignore messages to and from blocked users unless $frm->includeblocked is set
452 if ((!$frm->includeblocked) and (
453 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
454 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
457 $blockedcount ++;
458 continue;
461 /// load up user to record
462 if ($message->useridto !== $USER->id) {
463 $userto = get_record('user', 'id', $message->useridto);
464 $tocontact = (array_key_exists($message->useridto, $contacts) and
465 ($contacts[$message->useridto]->blocked == 0) );
466 $toblocked = (array_key_exists($message->useridto, $contacts) and
467 ($contacts[$message->useridto]->blocked == 1) );
468 } else {
469 $userto = false;
470 $tocontact = false;
471 $toblocked = false;
474 /// load up user from record
475 if ($message->useridfrom !== $USER->id) {
476 $userfrom = get_record('user', 'id', $message->useridfrom);
477 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
478 ($contacts[$message->useridfrom]->blocked == 0) );
479 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
480 ($contacts[$message->useridfrom]->blocked == 1) );
481 } else {
482 $userfrom = false;
483 $fromcontact = false;
484 $fromblocked = false;
487 /// find date string for this message
488 $date = usergetdate($message->timecreated);
489 $datestring = $date['year'].$date['mon'].$date['mday'];
491 /// print out message row
492 echo '<tr valign="top">';
493 echo '<td class="contact">';
494 message_print_user($userfrom, $fromcontact, $fromblocked);
495 echo '</td>';
496 echo '<td class="contact">';
497 message_print_user($userto, $tocontact, $toblocked);
498 echo '</td>';
499 echo '<td class="summary">'.message_get_fragment($message->message, $keywords);
500 echo '<br /><div class="link">';
501 message_history_link($message->useridto, $message->useridfrom, false,
502 $keywordstring, 'm'.$message->id, $strcontext);
503 echo '</div>';
504 echo '</td>';
505 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
506 echo "</tr>\n";
510 if ($blockedcount > 0) {
511 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
513 echo '</table>';
515 } else {
516 notify(get_string('nosearchresults', 'message'));
520 /// what the ????, probably an empty search string, duh!
521 } else {
522 notify(get_string('emptysearchstring', 'message'));
525 echo '<br />';
526 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
528 echo '</div>';
532 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
533 global $USER;
534 if ($user === false) {
535 print_user_picture($USER->id, SITEID, $USER->picture, 20, false, true, 'userwindow');
536 } else {
537 print_user_picture($user->id, SITEID, $user->picture, 20, false, true, 'userwindow');
538 echo '&nbsp;';
539 if ($iscontact) {
540 message_contact_link($user->id, 'remove');
541 } else {
542 message_contact_link($user->id, 'add');
544 echo '&nbsp;';
545 if ($isblocked) {
546 message_contact_link($user->id, 'unblock');
547 } else {
548 message_contact_link($user->id, 'block');
550 echo '<br />';
551 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
552 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
553 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
558 /// linktype can be: add, remove, block, unblock
559 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
560 global $USER, $CFG;
562 static $str;
564 if (empty($str->blockcontact)) {
565 $str->blockcontact = get_string('blockcontact', 'message');
566 $str->unblockcontact = get_string('unblockcontact', 'message');
567 $str->removecontact = get_string('removecontact', 'message');
568 $str->addcontact = get_string('addcontact', 'message');
571 $command = $linktype.'contact';
572 $string = $str->{$command};
573 $text = $text ? '&nbsp;'.$string : '';
575 switch ($linktype) {
576 case 'block':
577 $icon = '/t/go.gif';
578 break;
579 case 'unblock':
580 $icon = '/t/stop.gif';
581 break;
582 case 'remove':
583 $icon = '/t/user.gif';
584 break;
585 case 'add':
586 default:
587 $icon = '/t/usernot.gif';
590 $output = '<span class="'.$linktype.'">'.
591 '<a href="'.$script.'&amp;'.$command.'='.$userid.
592 '&amp;sesskey='.sesskey().'" title="'.$string.'">'.
593 '<img src="'.$CFG->pixpath.$icon.'" height="11" width="11" border="0">'.
594 $text.'</a></span>';
596 if ($return) {
597 return $output;
598 } else {
599 echo $output;
600 return true;
604 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
605 global $USER, $CFG;
607 static $strmessagehistory;
609 if (empty($strmessagehistory)) {
610 $strmessagehistory = get_string('messagehistory', 'message');
613 if (!$userid2) {
614 $userid2 = $USER->id;
616 if ($position) {
617 $position = "#$position";
619 if ($keywords) {
620 $keywords = "&search=".urlencode($keywords);
623 if ($linktext == 'icon') { // Icon only
624 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">';
625 } else if ($linktext == 'both') { // Icon and standard name
626 $fulllink = '<img src="'.$CFG->pixpath.'/t/log.gif" height="11" width="11" border="0">';
627 $fulllink .= '&nbsp;'.$strmessagehistory;
628 } else if ($linktext) { // Custom name
629 $fulllink = $linktext;
630 } else { // Standard name only
631 $fulllink = $strmessagehistory;
634 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$keywords$position",
635 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
636 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
638 $str = '<span class="history">'.$str.'</span>';
640 if ($returnstr) {
641 return $str;
642 } else {
643 echo $str;
644 return true;
650 * Search through course users
652 * If $coursid specifies the site course then this function searches
653 * through all undeleted and confirmed users
655 * @uses $CFG
656 * @uses SITEID
657 * @param int $courseid The course in question.
658 * @param string $searchtext ?
659 * @param string $sort ?
660 * @param string $exceptions ?
661 * @return array An array of {@link $USER} records.
662 * @todo Finish documenting this function
664 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
665 global $CFG;
667 switch ($CFG->dbtype) {
668 case 'mysql':
669 $fullname = ' CONCAT(u.firstname," ",u.lastname) ';
670 $LIKE = 'LIKE';
671 break;
672 case 'postgres7':
673 $fullname = " u.firstname||' '||u.lastname ";
674 $LIKE = 'ILIKE';
675 break;
676 default:
677 $fullname = ' u.firstname||" "||u.lastname ';
678 $LIKE = 'ILIKE';
681 if (!empty($exceptions)) {
682 $except = ' AND u.id NOT IN ('. $exceptions .') ';
683 } else {
684 $except = '';
687 if (!empty($sort)) {
688 $order = ' ORDER BY '. $sort;
689 } else {
690 $order = '';
693 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
694 $fields = 'u.id, u.firstname, u.lastname, u.picture';
696 if (!$courseid or $courseid == SITEID) {
697 return get_records_sql("SELECT $fields
698 FROM {$CFG->prefix}user u
699 WHERE $select
700 AND ($fullname $LIKE '%$searchtext%')
701 $except $order");
702 } else {
705 if (!$teachers = get_records_sql("SELECT $fields
706 FROM {$CFG->prefix}user u,
707 {$CFG->prefix}user_teachers s
708 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
709 AND ($fullname $LIKE '%$searchtext%')
710 $except $order")) {
711 $teachers = array();
713 if (!$students = get_records_sql("SELECT $fields
714 FROM {$CFG->prefix}user u,
715 {$CFG->prefix}user_students s
716 WHERE $select AND s.course = '$courseid' AND s.userid = u.id
717 AND ($fullname $LIKE '%$searchtext%')
718 $except $order")) {
719 $students = array();
721 return $teachers + $students;
728 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
729 /// Returns a list of posts found using an array of search terms
730 /// eg word +word -word
733 global $CFG, $USER;
735 /// If no userid sent then assume current user
736 if ($userid == 0) $userid = $USER->id;
738 /// Some differences in syntax for PostgreSQL
739 if ($CFG->dbtype == "postgres7") {
740 $LIKE = "ILIKE"; // case-insensitive
741 $NOTLIKE = "NOT ILIKE"; // case-insensitive
742 $REGEXP = "~*";
743 $NOTREGEXP = "!~*";
744 } else {
745 $LIKE = "LIKE";
746 $NOTLIKE = "NOT LIKE";
747 $REGEXP = "REGEXP";
748 $NOTREGEXP = "NOT REGEXP";
751 $messagesearch = "";
753 foreach ($searchterms as $searchterm) {
754 if (strlen($searchterm) < 2) {
755 continue;
757 if ($messagesearch) {
758 $messagesearch .= " AND ";
761 if (substr($searchterm,0,1) == "+") {
762 $searchterm = substr($searchterm,1);
763 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
764 } else if (substr($searchterm,0,1) == "-") {
765 $searchterm = substr($searchterm,1);
766 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
767 } else {
768 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
773 $messagesearch = "($messagesearch) ";
776 /// There are several possibilities
777 /// 1. courseid = SITEID : The admin is searching messages by all users
778 /// 2. courseid = ?? : A teacher is searching messages by users in
779 /// one of their courses - currently disabled
780 /// 3. courseid = none : User is searching their own messages;
781 /// a. Messages from user
782 /// b. Messages to user
783 /// c. Messages to and from user
785 if ($courseid == SITEID) { /// admin is searching all messages
786 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
787 FROM {$CFG->prefix}message_read m
788 WHERE $messagesearch");
789 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
790 FROM {$CFG->prefix}message m
791 WHERE $messagesearch");
793 if ($m_read === false) $m_read = array();
794 if ($m_unread === false) $m_unread = array();
796 } elseif ($courseid !== 'none') {
797 /// This has not been implemented due to security concerns
799 } else {
801 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
802 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
803 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
805 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
806 FROM {$CFG->prefix}message_read m
807 WHERE $messagesearch");
808 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
809 FROM {$CFG->prefix}message m
810 WHERE $messagesearch");
812 if ($m_read === false) $m_read = array();
813 if ($m_unread === false) $m_unread = array();
817 /// The keys may be duplicated in $m_read and $m_unread so we can't
818 /// do a simple concatenation
819 $message = array();
820 foreach ($m_read as $m) $messages[] = $m;
821 foreach ($m_unread as $m) $messages[] = $m;
824 return (empty($messages)) ? false : $messages;
829 /// Borrowed with changes from mod/forum/lib.php
830 function message_shorten_message($message, $minlength=0) {
831 // Given a post object that we already know has a long message
832 // this function truncates the message nicely to the first
833 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
835 $i = 0;
836 $tag = false;
837 $length = strlen($message);
838 $count = 0;
839 $stopzone = false;
840 $truncate = 0;
841 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
844 for ($i=0; $i<$length; $i++) {
845 $char = $message[$i];
847 switch ($char) {
848 case "<":
849 $tag = true;
850 break;
851 case ">":
852 $tag = false;
853 break;
854 default:
855 if (!$tag) {
856 if ($stopzone) {
857 if ($char == '.' or $char == ' ') {
858 $truncate = $i+1;
859 break 2;
862 $count++;
864 break;
866 if (!$stopzone) {
867 if ($count > $minlength) {
868 $stopzone = true;
873 if (!$truncate) {
874 $truncate = $i;
877 return substr($message, 0, $truncate);
882 * Given a string and an array of keywords, this function looks
883 * for the first keyword in the string, and then chops out a
884 * small section from the text that shows that word in context.
886 function message_get_fragment($message, $keywords) {
888 $fullsize = 120;
889 $halfsize = (int)($fullsize/2);
891 $message = strip_tags($message);
893 foreach ($keywords as $keyword) { // Just get the first one
894 if ($keyword !== '') {
895 break;
898 if (empty($keyword)) { // None found, so just return start of message
899 return message_shorten_message($message, 30);
902 $leadin = $leadout = '';
904 /// Find the start of the fragment
905 $start = 0;
906 $length = strlen($message);
908 $pos = strpos($message, $keyword);
909 if ($pos > $halfsize) {
910 $start = $pos - $halfsize;
911 $leadin = '...';
913 /// Find the end of the fragment
914 $end = $start + $fullsize;
915 if ($end > $length) {
916 $end = $length;
917 } else {
918 $leadout = '...';
921 /// Pull out the fragment and format it
923 $fragment = substr($message, $start, $end - $start);
924 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
925 return $fragment;
929 function message_get_history($user1, $user2) {
930 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
931 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
932 'timecreated');
933 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
934 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
935 'timecreated')) {
936 foreach ($messages_new as $message) {
937 $messages[] = $message;
940 return $messages;
943 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
945 static $dateformat;
947 if (empty($dateformat)) {
948 if ($format) {
949 $dateformat = $format;
950 } else {
951 $format = get_string('strftimedaytime');
954 $time = userdate($message->timecreated, $dateformat);
955 $options->para = false;
956 $messagetext = format_text($message->message, $message->format, $options);
957 if ($keywords) {
958 $messagetext = highlight($keywords, $messagetext);
960 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>';
964 * Inserts a message into the database, but also forwards it
965 * via other means if appropriate.
967 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
969 global $CFG, $SITE;
971 /// Save the new message in the database
973 $savemessage = NULL;
974 $savemessage->useridfrom = $userfrom->id;
975 $savemessage->useridto = $userto->id;
976 $savemessage->message = $message;
977 $savemessage->format = $format;
978 $savemessage->timecreated = time();
979 $savemessage->messagetype = 'direct';
981 if (!$savemessage->id = insert_record('message', $savemessage)) {
982 return false;
986 /// Check to see if anything else needs to be done with it
988 $preference = (object)get_user_preferences(NULL, NULL, $userto->id);
990 if (!isset($preference->message_emailmessages) or $preference->message_emailmessages) { // Receiver wants mail forwarding
991 if (!isset($preference->message_emailtimenosee)) {
992 $preference->message_emailtimenosee = 10;
994 if (!isset($preference->message_emailformat)) {
995 $preference->message_emailformat = FORMAT_HTML;
997 if ((time() - $userto->lastaccess) > ((int)$preference->message_emailtimenosee * 60)) { // Long enough
999 $message = stripslashes_safe($message);
1000 $tagline = get_string('emailtagline', 'message', $SITE->shortname);
1002 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
1003 $messagesubject = str_replace("\n", ' ', $messagesubject); // make sure it's all on one line
1005 $messagetext = format_text_email($message, $format).
1006 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1008 if (isset($preference->message_emailformat) and $preference->message_emailformat == FORMAT_HTML) {
1009 $messagehtml = format_text($message, $format);
1010 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1011 } else {
1012 $messagehtml = NULL;
1015 if (!empty($preference->message_emailaddress)) {
1016 $userto->email = $preference->message_emailaddress; // Use custom messaging address
1018 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
1022 return $savemessage->id;
1027 * Returns a list of all user ids who have used messaging in the site
1028 * This was the simple way to code the SQL ... is it going to blow up
1029 * on large datasets?
1031 function message_get_participants() {
1033 global $CFG;
1035 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1036 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1037 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1038 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1039 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1040 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");