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;
27 // time which a user is counting as being active since
28 $timefrom = time()-$timetoshowusers;
30 // people in our contactlist who are online
31 $onlinecontacts = array();
32 // people in our contactlist who are offline
33 $offlinecontacts = array();
34 // people who are not in our contactlist but have sent us a message
38 // get all in our contactlist who are not blocked in our contact list
39 // and count messages we have waiting from each of them
40 $contactsql = "SELECT u.id, u.firstname, u.lastname, u.picture,
41 u.imagealt, u.lastaccess, count(m.id) as messagecount
42 FROM {$CFG->prefix}message_contacts mc
43 JOIN {$CFG->prefix}user u
44 ON u.id = mc.contactid
45 LEFT OUTER JOIN {$CFG->prefix}message m
46 ON m.useridfrom = mc.contactid
47 AND m.useridto = {$USER->id}
48 WHERE mc.userid = {$USER->id}
50 GROUP BY u.id, u.firstname, u.lastname, u.picture,
51 u.imagealt, u.lastaccess
52 ORDER BY u.firstname ASC;";
54 if($rs = get_recordset_sql($contactsql)){
55 while($rd = rs_fetch_next_record($rs)){
57 if($rd->lastaccess
>= $timefrom){
58 // they have been active recently, so are counted online
59 $onlinecontacts[] = $rd;
61 $offlinecontacts[] = $rd;
69 // get messages from anyone who isn't in our contact list and count the number
70 // of messages we have from each of them
71 $strangersql = "SELECT u.id, u.firstname, u.lastname, u.picture,
72 u.imagealt, u.lastaccess, count(m.id) as messagecount
73 FROM {$CFG->prefix}message m
74 JOIN {$CFG->prefix}user u
75 ON u.id = m.useridfrom
76 LEFT OUTER JOIN {$CFG->prefix}message_contacts mc
77 ON mc.contactid = m.useridfrom AND
78 mc.userid = m.useridto
79 WHERE mc.id IS NULL AND m.useridto = {$USER->id}
80 GROUP BY u.id, u.firstname, u.lastname, u.picture,
81 u.imagealt, u.lastaccess
82 ORDER BY u.firstname ASC;";
84 if($rs = get_recordset_sql($strangersql)){
85 while($rd= rs_fetch_next_record($rs)){
92 $countonlinecontacts = count($onlinecontacts);
93 $countofflinecontacts = count($offlinecontacts);
94 $countstrangers = count($strangers);
96 if ($countonlinecontacts +
$countofflinecontacts == 0) {
97 echo '<div class="heading">';
98 print_string('contactlistempty', 'message');
100 echo '<div class="note">';
101 print_string('addsomecontacts', 'message', $CFG->wwwroot
.'/message/index.php?tab=search');
105 echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0" border="0">';
107 if($countonlinecontacts) {
108 /// print out list of online contacts
110 echo '<tr><td colspan="3" class="heading">';
111 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
114 foreach ($onlinecontacts as $contact) {
115 message_print_contactlist_user($contact);
118 echo '<tr><td colspan="3"> </td></tr>';
120 if ($countofflinecontacts) {
121 /// print out list of offline contacts
123 echo '<tr><td colspan="3" class="heading">';
124 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
127 foreach ($offlinecontacts as $contact) {
128 message_print_contactlist_user($contact);
130 echo '<tr><td colspan="3"> </td></tr>';
133 /// print out list of incoming contacts
134 if ($countstrangers) {
135 echo '<tr><td colspan="3" class="heading">';
136 echo get_string('incomingcontacts', 'message', $countstrangers);
139 foreach ($strangers as $stranger) {
140 message_print_contactlist_user($stranger, false);
146 if ($countstrangers && ($countonlinecontacts +
$countofflinecontacts == 0)) { // Extra help
147 echo '<div class="note">(';
148 print_string('addsomecontactsincoming', 'message');
154 $autorefresh = '<p align="center" class="note">'.get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh
).'</p>';
155 $autorefresh = addslashes_js($autorefresh); // js escaping
157 // gracefully degrade JS autorefresh
158 echo '<script type="text/javascript">
160 document.write("'.$autorefresh.'")
163 echo '<noscript><div align="center">';
164 echo print_single_button('index.php', false, get_string('refresh'));
165 echo '</div></noscript>';
169 /// $messagearray is an array of objects
170 /// $field is a valid property of object
171 /// $value is the value $field should equal to be counted
172 /// if $field is empty then return count of the whole array
173 /// if $field is non-existent then return 0;
174 function message_count_messages($messagearray, $field='', $value='') {
175 if (!is_array($messagearray)) return 0;
176 if ($field == '' or empty($messagearray)) return count($messagearray);
179 foreach ($messagearray as $message) {
180 $count +
= ($message->$field == $value) ?
1 : 0;
186 function message_print_search() {
189 if ($frm = data_submitted()) {
191 message_print_search_results($frm);
195 /// unfinished buggy code disabled in search.html anyway
196 // find all courses this use has readallmessages capabilities in
197 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
198 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
199 $cs = '<select name="courseselect">';
200 foreach ($teachers as $tcourse) {
201 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
206 include('search.html');
210 function message_print_settings() {
213 if ($frm = data_submitted()) {
216 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow
)) ?
'1' : '0';
217 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage
)) ?
'1' : '0';
218 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts
)) ?
'1' : '0';
219 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor
)) ?
'1' : '0';
220 $pref['message_noframesjs'] = (isset($frm->noframesjs
)) ?
'1' : '0';
221 $pref['message_emailmessages'] = (isset($frm->emailmessages
)) ?
'1' : '0';
222 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee
> 0) ?
(int)$frm->emailtimenosee
: '10';
223 $pref['message_emailaddress'] = (!empty($frm->emailaddress
)) ?
$frm->emailaddress
: $USER->email
;
224 $pref['message_emailformat'] = (isset($frm->emailformat
)) ?
$frm->emailformat
: FORMAT_PLAIN
;
226 set_user_preferences($pref);
228 redirect('index.php', get_string('settingssaved', 'message'), 1);
231 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ?
'checked="checked"' : '';
232 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ?
'checked="checked"' : '';
233 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ?
'checked="checked"' : '';
234 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ?
'checked="checked"' : '';
235 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ?
'checked="checked"' : '';
236 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ?
'checked="checked"' : '';
237 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email
);
238 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
239 $format_select = choose_from_menu( array(FORMAT_PLAIN
=> get_string('formatplain'),
240 FORMAT_HTML
=> get_string('formathtml')),
242 get_user_preferences('message_emailformat', FORMAT_PLAIN
),
243 false, '', '0', true );
245 include('settings.html');
250 function message_add_contact($contactid, $blocked=0) {
253 if (!record_exists('user', 'id', $contactid)) { // invalid userid
257 if (($contact = get_record('message_contacts', 'userid', $USER->id
, 'contactid', $contactid)) !== false) {
258 /// record already exists - we may be changing blocking status
260 if ($contact->blocked
!== $blocked) {
261 /// change to blocking status
262 $contact->blocked
= $blocked;
263 return update_record('message_contacts', $contact);
265 /// no changes to blocking status
270 /// new contact record
272 $contact->userid
= $USER->id
;
273 $contact->contactid
= $contactid;
274 $contact->blocked
= $blocked;
275 return insert_record('message_contacts', $contact, false);
279 function message_remove_contact($contactid) {
281 return delete_records('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
284 function message_unblock_contact($contactid) {
286 return delete_records('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
289 function message_block_contact($contactid) {
290 return message_add_contact($contactid, 1);
293 function message_get_contact($contactid) {
295 return get_record('message_contacts', 'userid', $USER->id
, 'contactid', $contactid);
300 function message_print_search_results($frm) {
303 echo '<div align="center">';
305 /// search for person
306 if (!empty($frm->personsubmit
) and !empty($frm->name
)) {
308 if (optional_param('mycourses', 0, PARAM_BOOL
)) {
310 $mycourses = get_my_courses($USER->id
);
311 foreach ($mycourses as $mycourse) {
312 if (is_array($susers = message_search_users($mycourse->id
, $frm->name
))) {
313 foreach ($susers as $suser) $users[$suser->id
] = $suser;
317 $users = message_search_users(SITEID
, $frm->name
);
320 if (!empty($users)) {
321 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
322 echo '<table class="message_users">';
323 foreach ($users as $user) {
325 if ( $user->contactlistid
) {
326 if ($user->blocked
== 0) { /// not blocked
327 $strcontact = message_contact_link($user->id
, 'remove', true);
328 $strblock = message_contact_link($user->id
, 'block', true);
330 $strcontact = message_contact_link($user->id
, 'add', true);
331 $strblock = message_contact_link($user->id
, 'unblock', true);
334 $strcontact = message_contact_link($user->id
, 'add', true);
335 $strblock = message_contact_link($user->id
, 'block', true);
337 $strhistory = message_history_link($user->id
, 0, true, '', '', 'icon');
339 echo '<tr><td class="pix">';
340 print_user_picture($user, SITEID
, $user->picture
, 20, false, true, 'userwindow');
342 echo '<td class="contact">';
343 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id", fullname($user),
344 500, 500, get_string('sendmessageto', 'message', fullname($user)),
345 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
349 echo '<td class="link">'.$strcontact.'</td>';
350 echo '<td class="link">'.$strblock.'</td>';
351 echo '<td class="link">'.$strhistory.'</td>';
357 notify(get_string('nosearchresults', 'message'));
361 /// search messages for keywords
362 } else if (!empty($frm->keywordssubmit
) and !empty($frm->keywords
)) {
363 $keywordstring = clean_text(trim($frm->keywords
));
364 $keywords = explode(' ', $keywordstring);
369 switch ($frm->keywordsoption
) {
384 $courseid = $frm->courseid
;
391 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
393 /// get a list of contacts
394 if (($contacts = get_records('message_contacts', 'userid', $USER->id
, '', 'contactid, blocked') ) === false) {
398 /// print heading with number of results
399 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
401 /// print table headings
402 echo '<table class="searchresults" cellspacing="0">';
404 echo '<td><strong>'.get_string('from').'</strong></td>';
405 echo '<td><strong>'.get_string('to').'</strong></td>';
406 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
407 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
411 $dateformat = get_string('strftimedatetime');
412 $strcontext = get_string('context', 'message');
413 foreach ($messages as $message) {
415 /// ignore messages to and from blocked users unless $frm->includeblocked is set
416 if (!optional_param('includeblocked', 0, PARAM_BOOL
) and (
417 ( isset($contacts[$message->useridfrom
]) and ($contacts[$message->useridfrom
]->blocked
== 1)) or
418 ( isset($contacts[$message->useridto
] ) and ($contacts[$message->useridto
]->blocked
== 1))
425 /// load up user to record
426 if ($message->useridto
!== $USER->id
) {
427 $userto = get_record('user', 'id', $message->useridto
);
428 $tocontact = (array_key_exists($message->useridto
, $contacts) and
429 ($contacts[$message->useridto
]->blocked
== 0) );
430 $toblocked = (array_key_exists($message->useridto
, $contacts) and
431 ($contacts[$message->useridto
]->blocked
== 1) );
438 /// load up user from record
439 if ($message->useridfrom
!== $USER->id
) {
440 $userfrom = get_record('user', 'id', $message->useridfrom
);
441 $fromcontact = (array_key_exists($message->useridfrom
, $contacts) and
442 ($contacts[$message->useridfrom
]->blocked
== 0) );
443 $fromblocked = (array_key_exists($message->useridfrom
, $contacts) and
444 ($contacts[$message->useridfrom
]->blocked
== 1) );
447 $fromcontact = false;
448 $fromblocked = false;
451 /// find date string for this message
452 $date = usergetdate($message->timecreated
);
453 $datestring = $date['year'].$date['mon'].$date['mday'];
455 /// print out message row
456 echo '<tr valign="top">';
457 echo '<td class="contact">';
458 message_print_user($userfrom, $fromcontact, $fromblocked);
460 echo '<td class="contact">';
461 message_print_user($userto, $tocontact, $toblocked);
463 echo '<td class="summary">'.message_get_fragment($message->message
, $keywords);
464 echo '<br /><div class="link">';
465 message_history_link($message->useridto
, $message->useridfrom
, false,
466 $keywordstring, 'm'.$message->id
, $strcontext);
469 echo '<td class="date">'.userdate($message->timecreated
, $dateformat).'</td>';
474 if ($blockedcount > 0) {
475 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
480 notify(get_string('nosearchresults', 'message'));
484 /// what the ????, probably an empty search string, duh!
486 notify(get_string('emptysearchstring', 'message'));
490 print_single_button('index.php', array( 'tab' => 'search'), get_string('newsearch', 'message') );
496 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
498 if ($user === false) {
499 print_user_picture($USER, SITEID
, $USER->picture
, 20, false, true, 'userwindow');
501 print_user_picture($user, SITEID
, $user->picture
, 20, false, true, 'userwindow');
504 message_contact_link($user->id
, 'remove');
506 message_contact_link($user->id
, 'add');
510 message_contact_link($user->id
, 'unblock');
512 message_contact_link($user->id
, 'block');
516 link_to_popup_window("/message/discussion.php?id=$user->id", "message_$user->id",
517 fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)),
518 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
523 /// linktype can be: add, remove, block, unblock
524 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
529 if (empty($str->blockcontact
)) {
530 $str->blockcontact
= get_string('blockcontact', 'message');
531 $str->unblockcontact
= get_string('unblockcontact', 'message');
532 $str->removecontact
= get_string('removecontact', 'message');
533 $str->addcontact
= get_string('addcontact', 'message');
536 $command = $linktype.'contact';
537 $string = $str->{$command};
538 $alttext = $text ?
'' : $string;
539 $text = $text ?
' '.$string : '';
546 $icon = '/t/stop.gif';
549 $icon = '/t/user.gif';
553 $icon = '/t/usernot.gif';
556 $output = '<span class="'.$linktype.'">'.
557 '<a href="'.$script.'&'.$command.'='.$userid.
558 '&sesskey='.sesskey().'" title="'.s($string).'">'.
559 '<img src="'.$CFG->pixpath
.$icon.'" class="iconsmall" alt="'.s($alttext).'" />'.
570 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
573 static $strmessagehistory;
575 if (empty($strmessagehistory)) {
576 $strmessagehistory = get_string('messagehistory', 'message');
580 $userid2 = $USER->id
;
583 $position = "#$position";
586 $keywords = "&search=".urlencode($keywords);
589 if ($linktext == 'icon') { // Icon only
590 $fulllink = '<img src="'.$CFG->pixpath
.'/t/log.gif" class="iconsmall" alt="'.$strmessagehistory.'" />';
591 } else if ($linktext == 'both') { // Icon and standard name
592 $fulllink = '<img src="'.$CFG->pixpath
.'/t/log.gif" class="iconsmall" alt="" />';
593 $fulllink .= ' '.$strmessagehistory;
594 } else if ($linktext) { // Custom name
595 $fulllink = $linktext;
596 } else { // Standard name only
597 $fulllink = $strmessagehistory;
600 $str = link_to_popup_window("/message/history.php?user1=$userid1&user2=$userid2$keywords$position",
601 "message_history_$userid1", $fulllink, 500, 500, $strmessagehistory,
602 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500', true);
604 $str = '<span class="history">'.$str.'</span>';
616 * Search through course users
618 * If $coursid specifies the site course then this function searches
619 * through all undeleted and confirmed users
623 * @param int $courseid The course in question.
624 * @param string $searchtext ?
625 * @param string $sort ?
626 * @param string $exceptions ?
627 * @return array An array of {@link $USER} records.
628 * @todo Finish documenting this function
630 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
633 $fullname = sql_fullname();
636 if (!empty($exceptions)) {
637 $except = ' AND u.id NOT IN ('. $exceptions .') ';
643 $order = ' ORDER BY '. $sort;
648 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
649 $fields = 'u.id, u.firstname, u.lastname, u.picture, u.imagealt, mc.id as contactlistid, mc.blocked';
651 if (!$courseid or $courseid == SITEID
) {
652 return get_records_sql("SELECT $fields
653 FROM {$CFG->prefix}user u
654 LEFT OUTER JOIN {$CFG->prefix}message_contacts mc
655 ON mc.contactid = u.id AND mc.userid = {$USER->id}
657 AND ($fullname $LIKE '%$searchtext%')
661 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
662 $contextlists = get_related_contexts_string($context);
664 // everyone who has a role assignement in this course or higher
665 $users = get_records_sql("SELECT $fields
666 FROM {$CFG->prefix}user u
667 JOIN {$CFG->prefix}role_assignments ra
669 LEFT OUTER JOIN {$CFG->prefix}message_contacts mc
670 ON mc.contactid = u.id AND mc.userid = {$USER->id}
672 AND ra.contextid $contextlists
673 AND ($fullname $LIKE '%$searchtext%')
683 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
684 /// Returns a list of posts found using an array of search terms
685 /// eg word +word -word
690 /// If no userid sent then assume current user
691 if ($userid == 0) $userid = $USER->id
;
693 /// Some differences in SQL syntax
695 $NOTLIKE = 'NOT ' . $LIKE;
696 if ($CFG->dbfamily
== "postgres") {
701 $NOTREGEXP = "NOT REGEXP";
706 foreach ($searchterms as $searchterm) {
707 if (strlen($searchterm) < 2) {
710 /// Under Oracle and MSSQL, trim the + and - operators and perform
711 /// simpler LIKE search
712 if ($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql') {
713 $searchterm = trim($searchterm, '+-');
716 if ($messagesearch) {
717 $messagesearch .= " AND ";
720 if (substr($searchterm,0,1) == "+") {
721 $searchterm = substr($searchterm,1);
722 $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
723 } else if (substr($searchterm,0,1) == "-") {
724 $searchterm = substr($searchterm,1);
725 $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
727 $messagesearch .= " m.message $LIKE '%$searchterm%' ";
731 if ($messagesearch == '') { // if only 1 letter words searched
735 $messagesearch = "($messagesearch) ";
738 /// There are several possibilities
739 /// 1. courseid = SITEID : The admin is searching messages by all users
740 /// 2. courseid = ?? : A teacher is searching messages by users in
741 /// one of their courses - currently disabled
742 /// 3. courseid = none : User is searching their own messages;
743 /// a. Messages from user
744 /// b. Messages to user
745 /// c. Messages to and from user
747 if ($courseid == SITEID
) { /// admin is searching all messages
748 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
749 FROM {$CFG->prefix}message_read m
750 WHERE $messagesearch");
751 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
752 FROM {$CFG->prefix}message m
753 WHERE $messagesearch");
755 if ($m_read === false) $m_read = array();
756 if ($m_unread === false) $m_unread = array();
758 } elseif ($courseid !== 'none') {
759 /// This has not been implemented due to security concerns
763 if ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$userid' OR m.useridto='$userid') ";
764 elseif ($fromme) $messagesearch .= "AND m.useridfrom='$userid' ";
765 elseif ($tome) $messagesearch .= "AND m.useridto='$userid' ";
767 $m_read = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
768 FROM {$CFG->prefix}message_read m
769 WHERE $messagesearch");
770 $m_unread = get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.message, m.timecreated
771 FROM {$CFG->prefix}message m
772 WHERE $messagesearch");
774 if ($m_read === false) $m_read = array();
775 if ($m_unread === false) $m_unread = array();
779 /// The keys may be duplicated in $m_read and $m_unread so we can't
780 /// do a simple concatenation
782 foreach ($m_read as $m) $messages[] = $m;
783 foreach ($m_unread as $m) $messages[] = $m;
786 return (empty($messages)) ?
false : $messages;
791 /// Borrowed with changes from mod/forum/lib.php
792 function message_shorten_message($message, $minlength=0) {
793 // Given a post object that we already know has a long message
794 // this function truncates the message nicely to the first
795 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
799 $length = strlen($message);
803 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH
;
806 for ($i=0; $i<$length; $i++
) {
807 $char = $message[$i];
819 if ($char == '.' or $char == ' ') {
829 if ($count > $minlength) {
839 return substr($message, 0, $truncate);
844 * Given a string and an array of keywords, this function looks
845 * for the first keyword in the string, and then chops out a
846 * small section from the text that shows that word in context.
848 function message_get_fragment($message, $keywords) {
851 $halfsize = (int)($fullsize/2);
853 $message = strip_tags($message);
855 foreach ($keywords as $keyword) { // Just get the first one
856 if ($keyword !== '') {
860 if (empty($keyword)) { // None found, so just return start of message
861 return message_shorten_message($message, 30);
864 $leadin = $leadout = '';
866 /// Find the start of the fragment
868 $length = strlen($message);
870 $pos = strpos($message, $keyword);
871 if ($pos > $halfsize) {
872 $start = $pos - $halfsize;
875 /// Find the end of the fragment
876 $end = $start +
$fullsize;
877 if ($end > $length) {
883 /// Pull out the fragment and format it
885 $fragment = substr($message, $start, $end - $start);
886 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
891 function message_get_history($user1, $user2) {
892 $messages = get_records_select('message_read', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
893 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
895 if ($messages_new = get_records_select('message', "(useridto = '$user1->id' AND useridfrom = '$user2->id') OR
896 (useridto = '$user2->id' AND useridfrom = '$user1->id')",
898 foreach ($messages_new as $message) {
899 $messages[] = $message;
905 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
909 if (empty($dateformat)) {
911 $dateformat = $format;
913 $format = get_string('strftimedaytime');
916 $time = userdate($message->timecreated
, $dateformat);
917 $options->para
= false;
918 $messagetext = format_text($message->message
, $message->format
, $options);
920 $messagetext = highlight($keywords, $messagetext);
922 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>';
926 * Inserts a message into the database, but also forwards it
927 * via other means if appropriate.
929 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
933 /// Save the new message in the database
936 $savemessage->useridfrom
= $userfrom->id
;
937 $savemessage->useridto
= $userto->id
;
938 $savemessage->message
= $message;
939 $savemessage->format
= $format;
940 $savemessage->timecreated
= time();
941 $savemessage->messagetype
= 'direct';
943 if ($CFG->messaging
) {
944 if (!$savemessage->id
= insert_record('message', $savemessage)) {
947 $emailforced = false;
948 } else { // $CFG->messaging is not on, we need to force sending of emails
950 $savemessage->id
= true;
953 /// Check to see if anything else needs to be done with it
955 $preference = (object)get_user_preferences(NULL, NULL, $userto->id
);
957 if ($emailforced ||
(!isset($preference->message_emailmessages
) ||
$preference->message_emailmessages
)) { // Receiver wants mail forwarding
958 if (!isset($preference->message_emailtimenosee
)) {
959 $preference->message_emailtimenosee
= 10;
961 if (!isset($preference->message_emailformat
)) {
962 $preference->message_emailformat
= FORMAT_HTML
;
964 if ($emailforced ||
(time() - $userto->lastaccess
) > ((int)$preference->message_emailtimenosee
* 60)) { // Long enough
966 $message = stripslashes_safe($message);
967 $tagline = get_string('emailtagline', 'message', $SITE->shortname
);
969 $messagesubject = preg_replace('/\s+/', ' ', strip_tags($message)); // make sure it's all on one line
970 $messagesubject = message_shorten_message($messagesubject, 30).'...';
972 $messagetext = format_text_email($message, $format).
973 "\n\n--\n".$tagline."\n"."$CFG->wwwroot/message/index.php?popup=1";
975 if (isset($preference->message_emailformat
) and $preference->message_emailformat
== FORMAT_HTML
) {
976 $messagehtml = format_text($message, $format);
977 // MDL-10294, do not print link if messaging is disabled
978 if ($CFG->messaging
) {
979 $messagehtml .= '<hr /><p><a href="'.$CFG->wwwroot
.'/message/index.php?popup=1">'.$tagline.'</a></p>';
985 if (!empty($preference->message_emailaddress
)) {
986 $userto->email
= $preference->message_emailaddress
; // Use custom messaging address
989 if (email_to_user($userto, $userfrom, $messagesubject, $messagetext, $messagehtml)) {
990 $CFG->messagewasjustemailed
= true;
997 return $savemessage->id
;
1002 * Returns a list of all user ids who have used messaging in the site
1003 * This was the simple way to code the SQL ... is it going to blow up
1004 * on large datasets?
1006 function message_get_participants() {
1010 return get_records_sql("SELECT useridfrom as id,1 FROM {$CFG->prefix}message
1011 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message
1012 UNION SELECT useridfrom as id,1 FROM {$CFG->prefix}message_read
1013 UNION SELECT useridto as id,1 FROM {$CFG->prefix}message_read
1014 UNION SELECT userid as id,1 FROM {$CFG->prefix}message_contacts
1015 UNION SELECT contactid as id,1 from {$CFG->prefix}message_contacts");
1019 * Print a row of contactlist displaying user picture, messages waiting and
1021 * @param $contact contact object containing all fields required for print_user_picture()
1022 * @param $incontactlist is the user a contact of ours?
1024 function message_print_contactlist_user($contact, $incontactlist = true){
1025 $fullname = fullname($contact);
1026 $fullnamelink = $fullname;
1028 /// are there any unread messages for this contact?
1029 if ($contact->messagecount
> 0 ){
1030 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount
.')</strong>';
1035 $strcontact = message_contact_link($contact->id
, 'remove', true);
1038 $strcontact = message_contact_link($contact->id
, 'add', true);
1039 $strblock = ' '. message_contact_link($contact->id
, 'block', true);
1042 $strhistory = message_history_link($contact->id
, 0, true, '', '', 'icon');
1044 echo '<tr><td class="pix">';
1045 print_user_picture($contact, SITEID
, $contact->picture
, 20, false, true, 'userwindow');
1047 echo '<td class="contact">';
1049 link_to_popup_window("/message/discussion.php?id=$contact->id", "message_$contact->id",
1050 $fullnamelink, 500, 500, get_string('sendmessageto', 'message', $fullname),
1051 'menubar=0,location=0,status,scrollbars,resizable,width=500,height=500');
1054 echo '<td class="link"> '.$strcontact.$strblock.' '.$strhistory.'</td>';