3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library functions for messaging
21 * @copyright Luis Rodrigues
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->libdir.'/eventslib.php');
29 define ('MESSAGE_SHORTLENGTH', 300);
30 define ('MESSAGE_WINDOW', true); // We are in a message window (so don't pop up a new one!)
32 if (!isset($CFG->message_contacts_refresh)) { // Refresh the contacts list every 60 seconds
33 $CFG->message_contacts_refresh = 60;
35 if (!isset($CFG->message_chat_refresh)) { // Look for new comments every 5 seconds
36 $CFG->message_chat_refresh = 5;
38 if (!isset($CFG->message_offline_time)) {
39 $CFG->message_offline_time = 300;
43 function message_print_contacts() {
44 global $USER, $CFG, $DB, $PAGE, $OUTPUT;
46 $timetoshowusers = 300; //Seconds default
47 if (isset($CFG->block_online_users_timetosee)) {
48 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
51 // time which a user is counting as being active since
52 $timefrom = time()-$timetoshowusers;
54 // people in our contactlist who are online
55 $onlinecontacts = array();
56 // people in our contactlist who are offline
57 $offlinecontacts = array();
58 // people who are not in our contactlist but have sent us a message
62 // get all in our contactlist who are not blocked in our contact list
63 // and count messages we have waiting from each of them
64 $contactsql = "SELECT u.id, u.firstname, u.lastname, u.picture,
65 u.imagealt, u.lastaccess, count(m.id) as messagecount
66 FROM {message_contacts} mc
67 JOIN {user} u ON u.id = mc.contactid
68 LEFT OUTER JOIN {message} m ON m.useridfrom = mc.contactid AND m.useridto = ?
69 WHERE mc.userid = ? AND mc.blocked = 0
70 GROUP BY u.id, u.firstname, u.lastname, u.picture,
71 u.imagealt, u.lastaccess
72 ORDER BY u.firstname ASC";
74 if ($rs = $DB->get_recordset_sql($contactsql, array($USER->id, $USER->id))){
77 if($rd->lastaccess >= $timefrom){
78 // they have been active recently, so are counted online
79 $onlinecontacts[] = $rd;
81 $offlinecontacts[] = $rd;
89 // get messages from anyone who isn't in our contact list and count the number
90 // of messages we have from each of them
91 $strangersql = "SELECT u.id, u.firstname, u.lastname, u.picture,
92 u.imagealt, u.lastaccess, count(m.id) as messagecount
94 JOIN {user} u ON u.id = m.useridfrom
95 LEFT OUTER JOIN {message_contacts} mc ON mc.contactid = m.useridfrom AND mc.userid = m.useridto
96 WHERE mc.id IS NULL AND m.useridto = ?
97 GROUP BY u.id, u.firstname, u.lastname, u.picture,
98 u.imagealt, u.lastaccess
99 ORDER BY u.firstname ASC";
101 if($rs = $DB->get_recordset_sql($strangersql, array($USER->id))){
109 $countonlinecontacts = count($onlinecontacts);
110 $countofflinecontacts = count($offlinecontacts);
111 $countstrangers = count($strangers);
113 if ($countonlinecontacts + $countofflinecontacts == 0) {
114 echo '<div class="heading">';
115 print_string('contactlistempty', 'message');
117 echo '<div class="note">';
118 print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
122 echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
124 if($countonlinecontacts) {
125 /// print out list of online contacts
127 echo '<tr><td colspan="3" class="heading">';
128 echo get_string('onlinecontacts', 'message', $countonlinecontacts);
131 foreach ($onlinecontacts as $contact) {
132 message_print_contactlist_user($contact);
135 echo '<tr><td colspan="3"> </td></tr>';
137 if ($countofflinecontacts) {
138 /// print out list of offline contacts
140 echo '<tr><td colspan="3" class="heading">';
141 echo get_string('offlinecontacts', 'message', $countofflinecontacts);
144 foreach ($offlinecontacts as $contact) {
145 message_print_contactlist_user($contact);
147 echo '<tr><td colspan="3"> </td></tr>';
150 /// print out list of incoming contacts
151 if ($countstrangers) {
152 echo '<tr><td colspan="3" class="heading">';
153 echo get_string('incomingcontacts', 'message', $countstrangers);
156 foreach ($strangers as $stranger) {
157 message_print_contactlist_user($stranger, false);
163 if ($countstrangers && ($countonlinecontacts + $countofflinecontacts == 0)) { // Extra help
164 echo '<div class="note">(';
165 print_string('addsomecontactsincoming', 'message');
171 $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
173 echo $OUTPUT->container_start('messagejsautorefresh note center');
174 echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
175 echo $OUTPUT->container_end();
177 echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
178 echo $OUTPUT->single_button('index.php', get_string('refresh'));
179 echo $OUTPUT->container_end();
183 /// $messagearray is an array of objects
184 /// $field is a valid property of object
185 /// $value is the value $field should equal to be counted
186 /// if $field is empty then return count of the whole array
187 /// if $field is non-existent then return 0;
188 function message_count_messages($messagearray, $field='', $value='') {
189 if (!is_array($messagearray)) return 0;
190 if ($field == '' or empty($messagearray)) return count($messagearray);
193 foreach ($messagearray as $message) {
194 $count += ($message->$field == $value) ? 1 : 0;
200 function message_print_search() {
201 global $USER, $OUTPUT;
203 if ($frm = data_submitted()) {
205 message_print_search_results($frm);
209 /// unfinished buggy code disabled in search.html anyway
210 // find all courses this use has readallmessages capabilities in
211 if ($teachers = get_user_capability_course('moodle/site:readallmessages')) {
212 $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
213 $cs = '<select name="courseselect">';
214 foreach ($teachers as $tcourse) {
215 $cs .= "<option value=\"$tcourse->course\">".$courses[$tcourse->id]->shortname."</option>\n";
220 include('search.html');
224 function message_print_settings() {
225 global $USER, $OUTPUT;
227 if ($frm = data_submitted() and confirm_sesskey()) {
230 $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
231 $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
232 $pref['message_blocknoncontacts'] = (isset($frm->blocknoncontacts)) ? '1' : '0';
233 $pref['message_usehtmleditor'] = (isset($frm->usehtmleditor)) ? '1' : '0';
234 $pref['message_noframesjs'] = (isset($frm->noframesjs)) ? '1' : '0';
235 $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
236 $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
237 $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
238 $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
240 set_user_preferences($pref);
242 redirect('index.php', get_string('settingssaved', 'message'), 1);
245 $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
246 $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 0) == '1') ? 'checked="checked"' : '';
247 $cbblocknoncontacts = (get_user_preferences('message_blocknoncontacts', 0) == '1') ? 'checked="checked"' : '';
248 $cbusehtmleditor = (get_user_preferences('message_usehtmleditor', 0) == '1') ? 'checked="checked"' : '';
249 $cbnoframesjs = (get_user_preferences('message_noframesjs', 0) == '1') ? 'checked="checked"' : '';
250 $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
251 $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
252 $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
253 $format_select = html_writer::select(array(FORMAT_PLAIN => get_string('formatplain'),
254 FORMAT_HTML => get_string('formathtml')),
255 'emailformat', get_user_preferences('message_emailformat', FORMAT_PLAIN));
257 include('settings.html');
262 function message_add_contact($contactid, $blocked=0) {
265 if (!$DB->record_exists('user', array('id'=>$contactid))) { // invalid userid
269 if (($contact = $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid))) !== false) {
270 /// record already exists - we may be changing blocking status
272 if ($contact->blocked !== $blocked) {
273 /// change to blocking status
274 $contact->blocked = $blocked;
275 return $DB->update_record('message_contacts', $contact);
277 /// no changes to blocking status
282 /// new contact record
284 $contact->userid = $USER->id;
285 $contact->contactid = $contactid;
286 $contact->blocked = $blocked;
287 return $DB->insert_record('message_contacts', $contact, false);
291 function message_remove_contact($contactid) {
293 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
296 function message_unblock_contact($contactid) {
298 return $DB->delete_records('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
301 function message_block_contact($contactid) {
302 return message_add_contact($contactid, 1);
305 function message_get_contact($contactid) {
307 return $DB->get_record('message_contacts', array('userid'=>$USER->id, 'contactid'=>$contactid));
312 function message_print_search_results($frm) {
313 global $USER, $CFG, $DB, $OUTPUT;
315 echo '<div class="mdl-align">';
317 /// search for person
318 if (!empty($frm->personsubmit) and !empty($frm->name)) {
320 if (optional_param('mycourses', 0, PARAM_BOOL)) {
322 $mycourses = get_my_courses($USER->id);
323 foreach ($mycourses as $mycourse) {
324 if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
325 foreach ($susers as $suser) $users[$suser->id] = $suser;
329 $users = message_search_users(SITEID, $frm->name);
332 if (!empty($users)) {
333 echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
334 echo '<table class="message_users">';
335 foreach ($users as $user) {
337 if ( $user->contactlistid ) {
338 if ($user->blocked == 0) { /// not blocked
339 $strcontact = message_contact_link($user->id, 'remove', true);
340 $strblock = message_contact_link($user->id, 'block', true);
342 $strcontact = message_contact_link($user->id, 'add', true);
343 $strblock = message_contact_link($user->id, 'unblock', true);
346 $strcontact = message_contact_link($user->id, 'add', true);
347 $strblock = message_contact_link($user->id, 'block', true);
349 $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
351 echo '<tr><td class="pix">';
352 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
354 echo '<td class="contact">';
355 $popupoptions = array(
361 'scrollbars' => true,
362 'resizable' => true);
364 $link = new moodle_url("/message/discussion.php?id=$user->id");
365 $action = new popup_action('click', $link, "message_$user->id", $popupoptions);
366 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
370 echo '<td class="link">'.$strcontact.'</td>';
371 echo '<td class="link">'.$strblock.'</td>';
372 echo '<td class="link">'.$strhistory.'</td>';
378 echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
382 /// search messages for keywords
383 } else if (!empty($frm->keywordssubmit)) {
384 $keywordstring = clean_text(trim($frm->keywords));
385 if ($keywordstring) {
386 $keywords = explode(' ', $keywordstring);
394 switch ($frm->keywordsoption) {
409 $courseid = $frm->courseid;
416 if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
418 /// get a list of contacts
419 if (($contacts = $DB->get_records('message_contacts', array('userid'=>$USER->id), '', 'contactid, blocked') ) === false) {
423 /// print heading with number of results
424 echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
426 /// print table headings
427 echo '<table class="searchresults" cellspacing="0">';
429 echo '<td><strong>'.get_string('from').'</strong></td>';
430 echo '<td><strong>'.get_string('to').'</strong></td>';
431 echo '<td><strong>'.get_string('message', 'message').'</strong></td>';
432 echo '<td><strong>'.get_string('timesent', 'message').'</strong></td>';
436 $dateformat = get_string('strftimedatetimeshort');
437 $strcontext = get_string('context', 'message');
438 foreach ($messages as $message) {
440 /// ignore messages to and from blocked users unless $frm->includeblocked is set
441 if (!optional_param('includeblocked', 0, PARAM_BOOL) and (
442 ( isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) or
443 ( isset($contacts[$message->useridto] ) and ($contacts[$message->useridto]->blocked == 1))
450 /// load up user to record
451 if ($message->useridto !== $USER->id) {
452 $userto = $DB->get_record('user', array('id'=>$message->useridto));
453 $tocontact = (array_key_exists($message->useridto, $contacts) and
454 ($contacts[$message->useridto]->blocked == 0) );
455 $toblocked = (array_key_exists($message->useridto, $contacts) and
456 ($contacts[$message->useridto]->blocked == 1) );
463 /// load up user from record
464 if ($message->useridfrom !== $USER->id) {
465 $userfrom = $DB->get_record('user', array('id'=>$message->useridfrom));
466 $fromcontact = (array_key_exists($message->useridfrom, $contacts) and
467 ($contacts[$message->useridfrom]->blocked == 0) );
468 $fromblocked = (array_key_exists($message->useridfrom, $contacts) and
469 ($contacts[$message->useridfrom]->blocked == 1) );
472 $fromcontact = false;
473 $fromblocked = false;
476 /// find date string for this message
477 $date = usergetdate($message->timecreated);
478 $datestring = $date['year'].$date['mon'].$date['mday'];
480 /// print out message row
481 echo '<tr valign="top">';
482 echo '<td class="contact">';
483 message_print_user($userfrom, $fromcontact, $fromblocked);
485 echo '<td class="contact">';
486 message_print_user($userto, $tocontact, $toblocked);
488 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
489 echo '<br /><div class="link">';
490 message_history_link($message->useridto, $message->useridfrom, false,
491 $keywordstring, 'm'.$message->id, $strcontext);
494 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
499 if ($blockedcount > 0) {
500 echo '<tr><td colspan="4" align="center">'.get_string('blockedmessages', 'message', $blockedcount).'</td></tr>';
505 echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
509 /// what the ????, probably an empty search string, duh!
511 echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
515 echo $OUTPUT->single_button(new moodle_url('index.php', array('tab' => 'search')), get_string('newsearch', 'message'));
521 function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
522 global $USER, $OUTPUT;
524 if ($user === false) {
525 echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
527 echo $OUTPUT->user_picture($USE, array('size'=>20, 'courseid'=>SITEID));
530 message_contact_link($user->id, 'remove');
532 message_contact_link($user->id, 'add');
536 message_contact_link($user->id, 'unblock');
538 message_contact_link($user->id, 'block');
542 $popupoptions = array(
548 'scrollbars' => true,
549 'resizable' => true);
551 $link = new moodle_url("/message/discussion.php?id=$user->id");
552 $action = new popup_action('click', $link, "message_$user->id", $popupoptions);
553 echo $OUTPUT->action_link($link, fullname($user), $action, array('title'=>get_string('sendmessageto', 'message', fullname($user))));
559 /// linktype can be: add, remove, block, unblock
560 function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
561 global $USER, $CFG, $OUTPUT;
565 if (empty($str->blockcontact)) {
566 $str->blockcontact = get_string('blockcontact', 'message');
567 $str->unblockcontact = get_string('unblockcontact', 'message');
568 $str->removecontact = get_string('removecontact', 'message');
569 $str->addcontact = get_string('addcontact', 'message');
572 $command = $linktype.'contact';
573 $string = $str->{$command};
574 $alttext = $text ? '' : $string;
575 $text = $text ? ' '.$string : '';
592 $output = '<span class="'.$linktype.'">'.
593 '<a href="'.$script.'&'.$command.'='.$userid.
594 '&sesskey='.sesskey().'" title="'.s($string).'">'.
595 '<img src="'.$OUTPUT->pix_url($icon).'" class="iconsmall" alt="'.s($alttext).'" />'.
606 function message_history_link($userid1, $userid2=0, $returnstr=false, $keywords='', $position='', $linktext='') {
607 global $USER, $CFG, $OUTPUT;
609 static $strmessagehistory;
611 if (empty($strmessagehistory)) {
612 $strmessagehistory = get_string('messagehistory', 'message');
616 $userid2 = $USER->id;
619 $position = "#$position";
622 $keywords = "&search=".urlencode($keywords);
625 if ($linktext == 'icon') { // Icon only
626 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="'.$strmessagehistory.'" />';
627 } else if ($linktext == 'both') { // Icon and standard name
628 $fulllink = '<img src="'.$OUTPUT->pix_url('t/log') . '" class="iconsmall" alt="" />';
629 $fulllink .= ' '.$strmessagehistory;
630 } else if ($linktext) { // Custom name
631 $fulllink = $linktext;
632 } else { // Standard name only
633 $fulllink = $strmessagehistory;
636 $popupoptions = array(
642 'scrollbars' => true,
643 'resizable' => true);
645 $link = html_link::make("/message/history.php?user1=$userid1&user2=$userid2$keywords$position");
646 $action = new popup_action('click', $link->url, "message_history_$userid1", $popupoptions);
647 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
649 $str = '<span class="history">'.$str.'</span>';
661 * Search through course users
663 * If $coursid specifies the site course then this function searches
664 * through all undeleted and confirmed users
668 * @param int $courseid The course in question.
669 * @param string $searchtext ?
670 * @param string $sort ?
671 * @param string $exceptions ?
672 * @return array An array of {@link $USER} records.
673 * @todo Finish documenting this function
675 function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
676 global $CFG, $USER, $DB;
678 $fullname = $DB->sql_fullname();
679 $LIKE = $DB->sql_ilike();
681 if (!empty($exceptions)) {
682 $except = ' AND u.id NOT IN ('. $exceptions .') ';
688 $order = ' ORDER BY '. $sort;
693 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
694 $fields = 'u.id, u.firstname, u.lastname, u.picture, u.imagealt, mc.id as contactlistid, mc.blocked';
696 if (!$courseid or $courseid == SITEID) {
697 $params = array($USER->id, "%$searchtext%");
698 return $DB->get_records_sql("SELECT $fields
700 LEFT JOIN {message_contacts} mc
701 ON mc.contactid = u.id AND mc.userid = ?
703 AND ($fullname $LIKE ?)
708 $context = get_context_instance(CONTEXT_COURSE, $courseid);
709 $contextlists = get_related_contexts_string($context);
711 // everyone who has a role assignement in this course or higher
712 $params = array($USER->id, "%$searchtext%");
713 $users = $DB->get_records_sql("SELECT $fields
715 JOIN {role_assignments} ra ON ra.userid = u.id
716 LEFT JOIN {message_contacts} mc
717 ON mc.contactid = u.id AND mc.userid = ?
719 AND ra.contextid $contextlists
720 AND ($fullname $LIKE ?)
731 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
732 /// Returns a list of posts found using an array of search terms
733 /// eg word +word -word
735 global $CFG, $USER, $DB;
737 /// If no userid sent then assume current user
738 if ($userid == 0) $userid = $USER->id;
740 /// Some differences in SQL syntax
741 if ($DB->sql_regex_supported()) {
742 $REGEXP = $DB->sql_regex(true);
743 $NOTREGEXP = $DB->sql_regex(false);
746 $LIKE = $DB->sql_ilike();
748 $searchcond = array();
752 foreach ($searchterms as $searchterm) {
755 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
757 if (strlen($searchterm) < 2) {
760 /// Under Oracle and MSSQL, trim the + and - operators and perform
761 /// simpler LIKE search
762 if (!$DB->sql_regex_supported()) {
763 if (substr($searchterm, 0, 1) == '-') {
766 $searchterm = trim($searchterm, '+-');
769 if (substr($searchterm,0,1) == "+") {
770 $searchterm = substr($searchterm,1);
771 $searchterm = preg_quote($searchterm, '|');
772 $searchcond[] = "m.fullmessage $REGEXP :ss$i";
773 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
775 } else if (substr($searchterm,0,1) == "-") {
776 $searchterm = substr($searchterm,1);
777 $searchterm = preg_quote($searchterm, '|');
778 $searchcond[] = "m.fullmessage $NOTREGEXP :ss$i";
779 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
782 $searchcond[] = "m.fullmessage $NOT $LIKE :ss$i";
783 $params['ss'.$i] = "%$searchterm%";
787 if (empty($searchcond)) {
788 $searchcond = " m.fullmessage $LIKE :ss1";
789 $params['ss1'] = "%";
791 $searchcond = implode(" AND ", $searchcond);
795 /// There are several possibilities
796 /// 1. courseid = SITEID : The admin is searching messages by all users
797 /// 2. courseid = ?? : A teacher is searching messages by users in
798 /// one of their courses - currently disabled
799 /// 3. courseid = none : User is searching their own messages;
800 /// a. Messages from user
801 /// b. Messages to user
802 /// c. Messages to and from user
804 if ($courseid == SITEID) { /// admin is searching all messages
805 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
806 FROM {message_read} m
807 WHERE $searchcond", $params);
808 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
810 WHERE $searchcond", $params);
812 } else if ($courseid !== 'none') {
813 /// This has not been implemented due to security concerns
819 if ($fromme and $tome) {
820 $searchcond .= " AND (m.useridfrom=:userid1 OR m.useridto=:userid2)";
821 $params['userid1'] = $userid;
822 $params['userid2'] = $userid;
824 } else if ($fromme) {
825 $searchcond .= " AND m.useridfrom=:userid";
826 $params['userid'] = $userid;
829 $searchcond .= " AND m.useridto=:userid";
830 $params['userid'] = $userid;
833 $m_read = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
834 FROM {message_read} m
835 WHERE $searchcond", $params);
836 $m_unread = $DB->get_records_sql("SELECT m.id, m.useridto, m.useridfrom, m.fullmessage, m.timecreated
838 WHERE $searchcond", $params);
842 /// The keys may be duplicated in $m_read and $m_unread so we can't
843 /// do a simple concatenation
845 foreach ($m_read as $m) {
848 foreach ($m_unread as $m) {
852 return (empty($messages)) ? false : $messages;
857 /// Borrowed with changes from mod/forum/lib.php
858 function message_shorten_message($message, $minlength=0) {
859 // Given a post object that we already know has a long message
860 // this function truncates the message nicely to the first
861 // sane place between $CFG->forum_longpost and $CFG->forum_shortpost
865 $length = strlen($message);
869 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
872 for ($i=0; $i<$length; $i++) {
873 $char = $message[$i];
885 if ($char == '.' or $char == ' ') {
895 if ($count > $minlength) {
905 return substr($message, 0, $truncate);
910 * Given a string and an array of keywords, this function looks
911 * for the first keyword in the string, and then chops out a
912 * small section from the text that shows that word in context.
914 function message_get_fragment($message, $keywords) {
917 $halfsize = (int)($fullsize/2);
919 $message = strip_tags($message);
921 foreach ($keywords as $keyword) { // Just get the first one
922 if ($keyword !== '') {
926 if (empty($keyword)) { // None found, so just return start of message
927 return message_shorten_message($message, 30);
930 $leadin = $leadout = '';
932 /// Find the start of the fragment
934 $length = strlen($message);
936 $pos = strpos($message, $keyword);
937 if ($pos > $halfsize) {
938 $start = $pos - $halfsize;
941 /// Find the end of the fragment
942 $end = $start + $fullsize;
943 if ($end > $length) {
949 /// Pull out the fragment and format it
951 $fragment = substr($message, $start, $end - $start);
952 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
957 function message_get_history($user1, $user2) {
960 $messages = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
961 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
963 if ($messages_new = $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
964 (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
966 foreach ($messages_new as $message) {
967 $messages[] = $message;
973 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
977 if (empty($dateformat)) {
979 $dateformat = $format;
981 $format = get_string('strftimedatetimeshort');
984 $time = userdate($message->timecreated, $dateformat);
985 $options = new object();
986 $options->para = false;
987 $messagetext = format_text($message->fullmessage, $message->fullmessageformat, $options);
989 $messagetext = highlight($keywords, $messagetext);
991 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>';
995 * Inserts a message into the database, but also forwards it
996 * via other means if appropriate.
998 function message_post_message($userfrom, $userto, $message, $format, $messagetype) {
999 global $CFG, $SITE, $USER, $DB;
1001 $eventdata = new object();
1002 $eventdata->component = 'message';
1003 $eventdata->name = 'instantmessage';
1004 $eventdata->userfrom = $userfrom;
1005 $eventdata->userto = $userto;
1006 $eventdata->subject = "IM";
1007 $eventdata->fullmessage = $message;
1008 $eventdata->fullmessageformat = FORMAT_PLAIN;
1009 $eventdata->fullmessagehtml = '';
1010 $eventdata->smallmessage = '';
1011 $eventdata->timecreated = time();
1012 return message_send($eventdata);
1018 * Returns a list of all user ids who have used messaging in the site
1019 * This was the simple way to code the SQL ... is it going to blow up
1020 * on large datasets?
1022 function message_get_participants() {
1025 return $DB->get_records_sql("SELECT useridfrom as id,1 FROM {message}
1026 UNION SELECT useridto as id,1 FROM {message}
1027 UNION SELECT useridfrom as id,1 FROM {message_read}
1028 UNION SELECT useridto as id,1 FROM {message_read}
1029 UNION SELECT userid as id,1 FROM {message_contacts}
1030 UNION SELECT contactid as id,1 from {message_contacts}");
1034 * Print a row of contactlist displaying user picture, messages waiting and
1036 * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
1037 * @param $incontactlist is the user a contact of ours?
1039 function message_print_contactlist_user($contact, $incontactlist = true){
1041 $fullname = fullname($contact);
1042 $fullnamelink = $fullname;
1044 /// are there any unread messages for this contact?
1045 if ($contact->messagecount > 0 ){
1046 $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
1051 $strcontact = message_contact_link($contact->id, 'remove', true);
1054 $strcontact = message_contact_link($contact->id, 'add', true);
1055 $strblock = ' '. message_contact_link($contact->id, 'block', true);
1058 $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
1060 echo '<tr><td class="pix">';
1061 echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
1063 echo '<td class="contact">';
1065 $popupoptions = array(
1069 'location' => false,
1071 'scrollbars' => true,
1072 'resizable' => true);
1074 $link = html_link::make("/message/discussion.php?id=$contact->id");
1075 $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
1076 echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
1079 echo '<td class="link"> '.$strcontact.$strblock.' '.$strhistory.'</td>';
1084 * Moves unread messages from message table to message_read for a given from user
1085 * @param object $userid User id
1086 * @return boolean success
1088 function message_move_userfrom_unread2read($userid) {
1092 // move all unread messages from message table to messasge_read
1093 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
1094 foreach ($messages as $message) {
1095 $message->timeread = 0; //the message was never read
1096 $messageid = $message->id;
1097 unset($message->id);
1098 if ($DB->insert_record('message_read', $message)) {
1099 $DB->delete_records('message', array('id' => $messageid));
1100 $DB->delete_records('message_working', array('unreadmessageid' => $messageid));
1109 function message_get_popup_messages($destuserid, $fromuserid=NULL){
1112 $processor = $DB->get_record('message_processors', array('name' => 'popup'));
1114 $messagesproc = $DB->get_records('message_working', array('processorid'=>$processor->id), 'id ASC');
1116 //for every message to process check if it's for current user and process
1117 $messages = array();
1118 foreach ($messagesproc as $msgp){
1119 $query = array('id'=>$msgp->unreadmessageid, 'useridto'=>$destuserid);
1121 $query['useridfrom'] = $fromuserid;
1123 if ($message = $DB->get_record('message', $query)){
1124 $messages[] = $message;
1125 /// Move the entry to the other table
1126 $message->timeread = time();
1127 $messageid = $message->id;
1128 unset($message->id);
1130 //delete what we've processed and check if can move message
1131 $DB->delete_records('message_working', array('id' => $msgp->id));
1132 if ( $DB->count_records('message_working', array('unreadmessageid'=>$messageid)) == 0){
1133 if ($DB->insert_record('message_read', $message)) {
1134 $DB->delete_records('message', array('id' => $messageid));