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() {
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
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
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) ) {
69 if (!isset($unknownmessages[$unreadmessage->useridfrom
])) {
70 $message = $unreadmessage;
72 $unknownmessages[$unreadmessage->useridfrom
] = $message;
74 $unknownmessages[$unreadmessage->useridfrom
]->count++
;
79 if ($countonlinecontacts +
$countofflinecontacts == 0) {
80 echo '<div class="heading">';
81 print_string('contactlistempty', 'message');
83 echo '<div class="note">';
84 print_string('addsomecontacts', 'message', $CFG->wwwroot
.'/message/index.php?tab=search');
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);
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');
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');
120 echo '<td class="link">'.$strcontact.' '.$strhistory.'</td>';
124 echo '<tr><td colspan="3"> </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);
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');
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');
154 echo '<td class="link">'.$strcontact.' '.$strhistory.'</td>';
157 echo '<tr><td colspan="3"> </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));
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');
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');
187 echo '<td class="link"> '.$strcontact.' '.$strblock.' '.$strhistory.'</td>';
194 if (!empty($unknownmessages) && ($countonlinecontacts +
$countofflinecontacts == 0)) { // Extra help
195 echo '<div class="note">(';
196 print_string('addsomecontactsincoming', 'message');
205 $autorefresh = '<p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh
).'</p>';
206 $autorefresh = addslashes_js($autorefresh); // js escaping
208 // gracefully degrade JS autorefresh
209 echo '<script type="text/javascript">
211 document.write("'.$autorefresh.'")
214 echo '<noscript><div align="center">';
215 echo print_single_button('index.php', false, get_string('refresh'));
216 echo '</div></noscript>';
222 /// $messagearray is an array of objects
223 /// $field is a valid property of object
224 /// $value is the value $field should equal to be counted
225 /// if $field is empty then return count of the whole array
226 /// if $field is non-existent then return 0;
227 function message_count_messages($messagearray, $field='', $value='') {
228 if (!is_array($messagearray)) return 0;
229 if ($field == '' or empty($messagearray)) return count($messagearray);
232 foreach ($messagearray as $message) {
233 $count +
= ($message->$field == $value) ?
1 : 0;
239 function message_print_search() {
242 if ($frm = data_submitted()) {
244 message_print_search_results($frm);
248 /// unfinished buggy code disabled in search.html anyway
249 // find all courses this use has readallmessages capabilities in
250 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
251 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
252 $cs = '<select name="courseselect">';
253 foreach ($teachers as $tcourse) {
254 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
259 include('search.html');
263 function message_print_settings() {
266 if ($frm = data_submitted()) {
269 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow
)) ?
'1' : '0';
270 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage
)) ?
'1' : '0';
271 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts
)) ?
'1' : '0';
272 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor
)) ?
'1' : '0';
273 $pref['message_noframesjs'] = (isset($frm->noframesjs
)) ?
'1' : '0';
274 $pref['message_emailmessages'] = (isset($frm->emailmessages
)) ?
'1' : '0';
275 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee
> 0) ?
(int)$frm->emailtimenosee
: '10';
276 $pref['message_emailaddress'] = (!empty($frm->emailaddress
)) ?
$frm->emailaddress
: $USER->email
;
277 $pref['message_emailformat'] = (isset($frm->emailformat
)) ?
$frm->emailformat
: FORMAT_PLAIN
;
279 set_user_preferences($pref);
281 redirect('index.php', get_string('settingssaved', 'message'), 1);
284 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ?
'checked="checked"' : '';
285 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ?
'checked="checked"' : '';
286 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ?
'checked="checked"' : '';
287 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ?
'checked="checked"' : '';
288 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ?
'checked="checked"' : '';
289 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ?
'checked="checked"' : '';
290 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email
);
291 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
292 $format_select = choose_from_menu( array(FORMAT_PLAIN
=> get_string('formatplain'),
293 FORMAT_HTML
=> get_string('formathtml')),
295 get_user_preferences('message_emailformat', FORMAT_PLAIN
),
296 false, '', '0', true );
298 include('settings.html');
303 function message_add_contact($contactid, $blocked=0) {
306 if (!record_exists('user', 'id', $contactid)) { // invalid userid
310 if (($contact = get_record('message_contacts', 'userid', $USER->id
, 'contactid', $contactid)) !== false) {
311 /// record already exists - we may be changing blocking status
313 if ($contact->blocked
!== $blocked) {
314 /// change to blocking status
315 $contact->blocked
= $blocked;
316 return update_record('message_contacts', $contact);
318 /// no changes to blocking status
323 /// new contact record
325 $contact->userid
= $USER->id
;
326 $contact->contactid
= $contactid;
327 $contact->blocked
= $blocked;
328 return insert_record('message_contacts', $contact, false);
332 function message_remove_contact($contactid) {
334 return delete_records('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
337 function message_unblock_contact($contactid) {
339 return delete_records('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
342 function message_block_contact($contactid) {
343 return message_add_contact($contactid, 1);
346 function message_get_contact($contactid) {
348 return get_record('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
353 function message_print_search_results($frm) {
356 echo '<div align="center">';
358 /// search for person
359 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
361 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
363 $mycourses = get_my_courses($USER->id
);
364 foreach ($mycourses as $mycourse) {
365 if (is_array($susers = message_search_users($mycourse->id
, $frm->name
))) {
366 foreach ($susers as $suser) $users[$suser->id
] = $suser;
370 $users = message_search_users(SITEID
, $frm->name
);
373 if (!empty($users)) {
374 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
375 echo '<table class="message_users">';
376 foreach ($users as $user) {
378 if (($contact = message_get_contact($user->id
)) !== false) {
379 if ($contact->blocked
== 0) { /// not blocked
380 $strcontact = message_contact_link($user->id
, 'remove', true);
381 $strblock = message_contact_link($user->id
, 'block', true);
383 $strcontact = message_contact_link($user->id
, 'add', true);
384 $strblock = message_contact_link($user->id
, 'unblock', true);
387 $strcontact = message_contact_link($user->id
, 'add', true);
388 $strblock = message_contact_link($user->id
, 'block', true);
390 $strhistory = message_history_link($user->id
, 0, true, '', '', 'icon');
392 echo '<tr><td class="pix">';
393 print_user_picture($user->id
, SITEID
, $user->picture
, 20, false, true, 'userwindow');
395 echo '<td class="contact">';
396 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
397 500, 500, get_string('sendmessageto', 'message', fullname($user)),
398 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
401 echo '<td class="link">'.$strcontact.'</td>';
402 echo '<td class="link">'.$strblock.'</td>';
403 echo '<td class="link">'.$strhistory.'</td>';
409 notify(get_string('nosearchresults', 'message'));
413 /// search messages for keywords
414 } else if (!empty($frm->keywordssubmit
) and !empty($frm->keywords
)) {
415 $keywordstring = clean_text(trim($frm->keywords
));
416 $keywords = explode(' ', $keywordstring);
421 switch ($frm->keywordsoption
) {
436 $courseid = $frm->courseid
;
443 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
445 /// get a list of contacts
446 if (($contacts = get_records('message_contacts', 'userid', $USER->id
, '', 'contactid, blocked') ) === false) {
450 /// print heading with number of results
451 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
453 /// print table headings
454 echo '<table class="searchresults" cellspacing="0">';
456 echo '<td><strong>'.get_string('from').'</strong></td>';
457 echo '<td><strong>'.get_string('to').'</strong></td>';
458 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
459 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
463 $dateformat = get_string('strftimedatetime');
464 $strcontext = get_string('context', 'message');
465 foreach ($messages as $message) {
467 /// ignore messages to and from blocked users unless $frm->includeblocked is set
468 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
469 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
470 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
477 /// load up user to record
478 if ($message->useridto
!== $USER->id
) {
479 $userto = get_record('user', 'id', $message->useridto
);
480 $tocontact = (array_key_exists($message->useridto
, $contacts) and
481 ($contacts[$message->useridto
]->blocked
== 0) );
482 $toblocked = (array_key_exists($message->useridto
, $contacts) and
483 ($contacts[$message->useridto
]->blocked
== 1) );
490 /// load up user from record
491 if ($message->useridfrom
!== $USER->id
) {
492 $userfrom = get_record('user', 'id', $message->useridfrom
);
493 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
494 ($contacts[$message->useridfrom
]->blocked
== 0) );
495 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
496 ($contacts[$message->useridfrom
]->blocked
== 1) );
499 $fromcontact = false;
500 $fromblocked = false;
503 /// find date string for this message
504 $date = usergetdate($message->timecreated
);
505 $datestring = $date['year'].$date['mon'].$date['mday'];
507 /// print out message row
508 echo '<tr valign="top">';
509 echo '<td class="contact">';
510 message_print_user($userfrom, $fromcontact, $fromblocked);
512 echo '<td class="contact">';
513 message_print_user($userto, $tocontact, $toblocked);
515 echo '<td class="summary">'.message_get_fragment($message->message
, $keywords);
516 echo '<br /><div class="link">';
517 message_history_link($message->useridto
, $message->useridfrom
, false,
518 $keywordstring, 'm'.$message->id
, $strcontext);
521 echo '<td class="date">'.userdate($message->timecreated
, $dateformat).'</td>';
526 if ($blockedcount > 0) {
527 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
532 notify(get_string('nosearchresults', 'message'));
536 /// what the ????, probably an empty search string, duh!
538 notify(get_string('emptysearchstring', 'message'));
542 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
548 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
550 if ($user === false) {
551 print_user_picture($USER->id
, SITEID
, $USER->picture
, 20, false, true, 'userwindow');
553 print_user_picture($user->id
, SITEID
, $user->picture
, 20, false, true, 'userwindow');
556 message_contact_link($user->id
, 'remove');
558 message_contact_link($user->id
, 'add');
562 message_contact_link($user->id
, 'unblock');
564 message_contact_link($user->id
, 'block');
567 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
568 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
569 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
574 /// linktype can be: add, remove, block, unblock
575 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
580 if (empty($str->blockcontact
)) {
581 $str->blockcontact
= get_string('blockcontact', 'message');
582 $str->unblockcontact
= get_string('unblockcontact', 'message');
583 $str->removecontact
= get_string('removecontact', 'message');
584 $str->addcontact
= get_string('addcontact', 'message');
587 $command = $linktype.'contact';
588 $string = $str->{$command};
589 $alttext = $text ?
'' : $string;
590 $text = $text ?
' '.$string : '';
597 $icon = '/t/stop.gif';
600 $icon = '/t/user.gif';
604 $icon = '/t/usernot.gif';
607 $output = '<span class="'.$linktype.'">'.
608 '<a href="'.$script.'&'.$command.'='.$userid.
609 '&sesskey='.sesskey().'" title="'.s($string).'">'.
610 '<img src="'.$CFG->pixpath
.$icon.'" class="iconsmall" alt="'.s($alttext).'" />'.
621 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
624 static $strmessagehistory;
626 if (empty($strmessagehistory)) {
627 $strmessagehistory = get_string('messagehistory', 'message');
631 $userid2 = $USER->id
;
634 $position = "#$position";
637 $keywords = "&search=".urlencode($keywords);
640 if ($linktext == 'icon') { // Icon only
641 $fulllink = '<img src="'.$CFG->pixpath
.'/t/log.gif" class="iconsmall" alt="'.$strmessagehistory.'" />';
642 } else if ($linktext == 'both') { // Icon and standard name
643 $fulllink = '<img src="'.$CFG->pixpath
.'/t/log.gif" class="iconsmall" alt="" />';
644 $fulllink .= ' '.$strmessagehistory;
645 } else if ($linktext) { // Custom name
646 $fulllink = $linktext;
647 } else { // Standard name only
648 $fulllink = $strmessagehistory;
651 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$keywords$position",
652 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
653 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
655 $str = '<span class="history">'.$str.'</span>';
667 * Search through course users
669 * If $coursid specifies the site course then this function searches
670 * through all undeleted and confirmed users
674 * @param int $courseid The course in question.
675 * @param string $searchtext ?
676 * @param string $sort ?
677 * @param string $exceptions ?
678 * @return array An array of {@link $USER} records.
679 * @todo Finish documenting this function
681 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
684 $fullname = sql_fullname();
687 if (!empty($exceptions)) {
688 $except = ' AND u.id NOT IN ('. $exceptions .') ';
694 $order = ' ORDER BY '. $sort;
699 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
700 $fields = 'u.id, u.firstname, u.lastname, u.picture';
702 if (!$courseid or $courseid == SITEID
) {
703 return get_records_sql("SELECT $fields
704 FROM {$CFG->prefix}user u
706 AND ($fullname $LIKE '%$searchtext%')
710 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
711 $contextlists = get_related_contexts_string($context);
713 // everyone who has a role assignement in this course or higher
714 $users = get_records_sql("SELECT $fields
715 FROM {$CFG->prefix}user u,
716 {$CFG->prefix}role_assignments ra
718 AND ra.contextid $contextlists
720 AND ($fullname $LIKE '%$searchtext%')
730 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
731 /// Returns a list of posts found using an array of search terms
732 /// eg word +word -word
737 /// If no userid sent then assume current user
738 if ($userid == 0) $userid = $USER->id
;
740 /// Some differences in SQL syntax
742 $NOTLIKE = 'NOT ' . $LIKE;
743 if ($CFG->dbfamily
== "postgres") {
748 $NOTREGEXP = "NOT REGEXP";
753 foreach ($searchterms as $searchterm) {
754 if (strlen($searchterm) < 2) {
757 /// Under Oracle and MSSQL, trim the + and - operators and perform
758 /// simpler LIKE search
759 if ($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql') {
760 $searchterm = trim($searchterm, '+-');
763 if ($messagesearch) {
764 $messagesearch .= " AND ";
767 if (substr($searchterm,0,1) == "+") {
768 $searchterm = substr($searchterm,1);
769 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
770 } else if (substr($searchterm,0,1) == "-") {
771 $searchterm = substr($searchterm,1);
772 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
774 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
778 if ($messagesearch == '') { // if only 1 letter words searched
782 $messagesearch = "($messagesearch) ";
785 /// There are several possibilities
786 /// 1. courseid = SITEID : The admin is searching messages by all users
787 /// 2. courseid = ?? : A teacher is searching messages by users in
788 /// one of their courses - currently disabled
789 /// 3. courseid = none : User is searching their own messages;
790 /// a. Messages from user
791 /// b. Messages to user
792 /// c. Messages to and from user
794 if ($courseid == SITEID
) { /// admin is searching all messages
795 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
796 FROM {$CFG->prefix}message_read m
797 WHERE $messagesearch");
798 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
799 FROM {$CFG->prefix}message m
800 WHERE $messagesearch");
802 if ($m_read === false) $m_read = array();
803 if ($m_unread === false) $m_unread = array();
805 } elseif ($courseid !== 'none') {
806 /// This has not been implemented due to security concerns
810 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
811 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
812 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
814 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
815 FROM {$CFG->prefix}message_read m
816 WHERE $messagesearch");
817 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
818 FROM {$CFG->prefix}message m
819 WHERE $messagesearch");
821 if ($m_read === false) $m_read = array();
822 if ($m_unread === false) $m_unread = array();
826 /// The keys may be duplicated in $m_read and $m_unread so we can't
827 /// do a simple concatenation
829 foreach ($m_read as $m) $messages[] = $m;
830 foreach ($m_unread as $m) $messages[] = $m;
833 return (empty($messages)) ?
false : $messages;
838 /// Borrowed with changes from mod/forum/lib.php
839 function message_shorten_message($message, $minlength=0) {
840 // Given a post object that we already know has a long message
841 // this function truncates the message nicely to the first
842 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
846 $length = strlen($message);
850 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
853 for ($i=0; $i<$length; $i++
) {
854 $char = $message[$i];
866 if ($char == '.' or $char == ' ') {
876 if ($count > $minlength) {
886 return substr($message, 0, $truncate);
891 * Given a string and an array of keywords, this function looks
892 * for the first keyword in the string, and then chops out a
893 * small section from the text that shows that word in context.
895 function message_get_fragment($message, $keywords) {
898 $halfsize = (int)($fullsize/2);
900 $message = strip_tags($message);
902 foreach ($keywords as $keyword) { // Just get the first one
903 if ($keyword !== '') {
907 if (empty($keyword)) { // None found, so just return start of message
908 return message_shorten_message($message, 30);
911 $leadin = $leadout = '';
913 /// Find the start of the fragment
915 $length = strlen($message);
917 $pos = strpos($message, $keyword);
918 if ($pos > $halfsize) {
919 $start = $pos - $halfsize;
922 /// Find the end of the fragment
923 $end = $start +
$fullsize;
924 if ($end > $length) {
930 /// Pull out the fragment and format it
932 $fragment = substr($message, $start, $end - $start);
933 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
938 function message_get_history($user1, $user2) {
939 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
940 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
942 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
943 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
945 foreach ($messages_new as $message) {
946 $messages[] = $message;
952 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
956 if (empty($dateformat)) {
958 $dateformat = $format;
960 $format = get_string('strftimedaytime');
963 $time = userdate($message->timecreated
, $dateformat);
964 $options->para
= false;
965 $messagetext = format_text($message->message
, $message->format
, $options);
967 $messagetext = highlight($keywords, $messagetext);
969 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>';
973 * Inserts a message into the database, but also forwards it
974 * via other means if appropriate.
976 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
980 /// Save the new message in the database
983 $savemessage->useridfrom
= $userfrom->id
;
984 $savemessage->useridto
= $userto->id
;
985 $savemessage->message
= $message;
986 $savemessage->format
= $format;
987 $savemessage->timecreated
= time();
988 $savemessage->messagetype
= 'direct';
990 if (!$savemessage->id
= insert_record('message', $savemessage)) {
995 /// Check to see if anything else needs to be done with it
997 $preference = (object)get_user_preferences(NULL, NULL, $userto->id
);
999 if (!isset($preference->message_emailmessages
) or $preference->message_emailmessages
) { // Receiver wants mail forwarding
1000 if (!isset($preference->message_emailtimenosee
)) {
1001 $preference->message_emailtimenosee
= 10;
1003 if (!isset($preference->message_emailformat
)) {
1004 $preference->message_emailformat
= FORMAT_HTML
;
1006 if ((time() - $userto->lastaccess
) > ((int)$preference->message_emailtimenosee
* 60)) { // Long enough
1008 $message = stripslashes_safe($message);
1009 $tagline = get_string('emailtagline', 'message', $SITE->shortname
);
1011 $messagesubject = message_shorten_message(strip_tags($message), 30).'...';
1013 $messagetext = format_text_email($message, $format).
1014 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
1016 if (isset($preference->message_emailformat
) and $preference->message_emailformat
== FORMAT_HTML
) {
1017 $messagehtml = format_text($message, $format);
1018 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot
.'/message/index.php?popup=1">'.$tagline.'</a></p>';
1020 $messagehtml = NULL;
1023 if (!empty($preference->message_emailaddress
)) {
1024 $userto->email
= $preference->message_emailaddress
; // Use custom messaging address
1026 email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml);
1030 return $savemessage->id
;
1035 * Returns a list of all user ids who have used messaging in the site
1036 * This was the simple way to code the SQL ... is it going to blow up
1037 * on large datasets?
1039 function message_get_participants() {
1043 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1044 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1045 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1046 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1047 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1048 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");