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 of functions and constants for module chat
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once($CFG->dirroot
.'/calendar/lib.php');
28 // The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output
29 global $CHAT_HTMLHEAD;
30 $CHAT_HTMLHEAD = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head></head>\n<body>\n\n".padding(200);
32 // The HTML head for the message window to start with (with js scrolling)
33 global $CHAT_HTMLHEAD_JS;
34 $CHAT_HTMLHEAD_JS = <<<EOD
35 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
36 <html><head><script type="text/javascript">
40 window.scroll(1,400000);
41 window.setTimeout("move()",100);
43 var scroll_active = true;
48 <body onBlur="scroll_active = true" onFocus="scroll_active = false">
50 global $CHAT_HTMLHEAD_JS;
51 $CHAT_HTMLHEAD_JS .= padding(200);
53 // The HTML code for standard empty pages (e.g. if a user was kicked out)
54 global $CHAT_HTMLHEAD_OUT;
55 $CHAT_HTMLHEAD_OUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>You are out!</title></head><body></body></html>";
57 // The HTML head for the message input page
58 global $CHAT_HTMLHEAD_MSGINPUT;
59 $CHAT_HTMLHEAD_MSGINPUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>Message Input</title></head><body>";
61 // The HTML code for the message input page, with JavaScript
62 global $CHAT_HTMLHEAD_MSGINPUT_JS;
63 $CHAT_HTMLHEAD_MSGINPUT_JS = <<<EOD
64 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
66 <head><title>Message Input</title>
67 <script type="text/javascript">
70 function empty_field_and_submit(){
71 document.fdummy.arsc_message.value=document.f.arsc_message.value;
72 document.fdummy.submit();
73 document.f.arsc_message.focus();
74 document.f.arsc_message.select();
79 </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
82 // Dummy data that gets output to the browser as needed, in order to make it show output
83 global $CHAT_DUMMY_DATA;
84 $CHAT_DUMMY_DATA = padding(200);
92 for($i=0; $i<$n; $i++
){
93 $str.="<!-- nix -->\n";
99 * Given an object containing all the necessary data,
100 * (defined by the form in mod_form.php) this function
101 * will create a new instance and return the id number
102 * of the new instance.
105 * @param object $chat
108 function chat_add_instance($chat) {
111 $chat->timemodified
= time();
113 $returnid = $DB->insert_record("chat", $chat);
115 $event = new stdClass();
116 $event->name
= $chat->name
;
117 $event->description
= format_module_intro('chat', $chat, $chat->coursemodule
);
118 $event->courseid
= $chat->course
;
121 $event->modulename
= 'chat';
122 $event->instance
= $returnid;
123 $event->eventtype
= 'chattime';
124 $event->timestart
= $chat->chattime
;
125 $event->timeduration
= 0;
127 calendar_event
::create($event);
133 * Given an object containing all the necessary data,
134 * (defined by the form in mod_form.php) this function
135 * will update an existing instance with new data.
138 * @param object $chat
141 function chat_update_instance($chat) {
144 $chat->timemodified
= time();
145 $chat->id
= $chat->instance
;
148 $DB->update_record("chat", $chat);
150 $event = new stdClass();
152 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id
))) {
154 $event->name
= $chat->name
;
155 $event->description
= format_module_intro('chat', $chat, $chat->coursemodule
);
156 $event->timestart
= $chat->chattime
;
158 $calendarevent = calendar_event
::load($event->id
);
159 $calendarevent->update($event);
166 * Given an ID of an instance of this module,
167 * this function will permanently delete the instance
168 * and any data that depends on it.
174 function chat_delete_instance($id) {
178 if (! $chat = $DB->get_record('chat', array('id'=>$id))) {
184 // Delete any dependent records here
186 if (! $DB->delete_records('chat', array('id'=>$chat->id
))) {
189 if (! $DB->delete_records('chat_messages', array('chatid'=>$chat->id
))) {
192 if (! $DB->delete_records('chat_messages_current', array('chatid'=>$chat->id
))) {
195 if (! $DB->delete_records('chat_users', array('chatid'=>$chat->id
))) {
199 if (! $DB->delete_records('event', array('modulename'=>'chat', 'instance'=>$chat->id
))) {
207 * Return a small object with summary information about what a
208 * user has done with a given particular instance of this module
209 * Used for user activity reports.
211 * $return->time = the time they did it
212 * $return->info = a short text description
215 * @param object $course
216 * @param object $user
218 * @param object $chat
221 function chat_user_outline($course, $user, $mod, $chat) {
226 * Print a detailed representation of what a user has done with
227 * a given particular instance of this module, for user activity reports.
229 * @param object $course
230 * @param object $user
232 * @param object $chat
235 function chat_user_complete($course, $user, $mod, $chat) {
240 * Given a course and a date, prints a summary of all chat rooms past and present
241 * This function is called from course/lib.php: print_recent_activity()
246 * @param object $course
247 * @param bool $viewfullnames
248 * @param int|string $timestart Timestamp
251 function chat_print_recent_activity($course, $viewfullnames, $timestart) {
252 global $CFG, $USER, $DB, $OUTPUT;
254 // this is approximate only, but it is really fast ;-)
255 $timeout = $CFG->chat_old_ping
* 10;
257 if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
258 FROM {course_modules} cm
259 JOIN {modules} md ON md.id = cm.module
260 JOIN {chat} ch ON ch.id = cm.instance
261 JOIN {chat_messages} chm ON chm.chatid = ch.id
262 WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
264 ORDER BY lasttime ASC", array($timestart, $course->id
))) {
270 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
272 foreach ($mcms as $cmid=>$mcm) {
273 if (!array_key_exists($cmid, $modinfo->cms
)) {
276 $cm = $modinfo->cms
[$cmid];
277 $cm->lasttime
= $mcm->lasttime
;
278 if (!$modinfo->cms
[$cm->id
]->uservisible
) {
282 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
283 or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
284 if ($timeout > time() - $cm->lasttime
) {
293 if (is_null($modinfo->groups
)) {
294 $modinfo->groups
= groups_get_user_groups($course->id
); // load all my groups and cache it in modinfo
297 // verify groups in separate mode
298 if (!$mygroupids = $modinfo->groups
[$cm->groupingid
]) {
302 // ok, last post was not for my group - we have to query db to get last message from one of my groups
303 // only minor problem is that the order will not be correct
304 $mygroupids = implode(',', $mygroupids);
305 $cm->mygroupids
= $mygroupids;
307 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
308 FROM {course_modules} cm
309 JOIN {chat} ch ON ch.id = cm.instance
310 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
311 WHERE chm.timestamp > ? AND cm.id = ? AND
312 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
313 GROUP BY cm.id", array($timestart, $cm->id
))) {
317 $cm->lasttime
= $mcm->lasttime
;
318 if ($timeout > time() - $cm->lasttime
) {
325 if (!$past and !$current) {
329 $strftimerecent = get_string('strftimerecent');
332 echo $OUTPUT->heading(get_string("pastchats", 'chat').':');
334 foreach ($past as $cm) {
335 $link = $CFG->wwwroot
.'/mod/chat/view.php?id='.$cm->id
;
336 $date = userdate($cm->lasttime
, $strftimerecent);
337 echo '<div class="head"><div class="date">'.$date.'</div></div>';
338 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name
,true).'</a></div>';
343 echo $OUTPUT->heading(get_string("currentchats", 'chat').':');
345 $oldest = floor((time()-$CFG->chat_old_ping
)/10)*10; // better db caching
347 $timeold = time() - $CFG->chat_old_ping
;
348 $timeold = floor($timeold/10)*10; // better db caching
349 $timeoldext = time() - ($CFG->chat_old_ping
*10); // JSless gui_basic needs much longer timeouts
350 $timeoldext = floor($timeoldext/10)*10; // better db caching
352 $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id
);
354 $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
356 foreach ($current as $cm) {
358 if (isset($cm->mygroupids
)) {
359 $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
364 if (!$users = $DB->get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email, u.picture
365 FROM {course_modules} cm
366 JOIN {chat} ch ON ch.id = cm.instance
367 JOIN {chat_users} chu ON chu.chatid = ch.id
368 JOIN {user} u ON u.id = chu.userid
369 WHERE cm.id = :cmid $timeout $groupselect
370 GROUP BY u.id, u.firstname, u.lastname, u.email, u.picture", $params)) {
373 $link = $CFG->wwwroot
.'/mod/chat/view.php?id='.$cm->id
;
374 $date = userdate($cm->lasttime
, $strftimerecent);
376 echo '<div class="head"><div class="date">'.$date.'</div></div>';
377 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name
,true).'</a></div>';
378 echo '<div class="userlist">';
381 foreach ($users as $user) {
382 echo '<li>'.fullname($user, $viewfullnames).'</li>';
394 * Function to be run periodically according to the moodle cron
395 * This function searches for things that need to be done, such
396 * as sending out mail, toggling flags etc ...
401 function chat_cron () {
404 chat_update_chat_times();
406 chat_delete_old_users();
408 /// Delete old messages with a
409 /// single SQL query.
410 $subselect = "SELECT c.keepdays
412 WHERE c.id = {chat_messages}.chatid";
416 WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
421 FROM {chat_messages_current}
422 WHERE timestamp < ( ".time()." - 8 * 3600)";
430 * Returns the users with data in one chat
431 * (users with records in chat_messages, students)
433 * @todo: deprecated - to be deleted in 2.2
436 * @param int $groupid
439 function chat_get_participants($chatid, $groupid=0) {
442 $params = array('groupid'=>$groupid, 'chatid'=>$chatid);
445 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
451 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
452 FROM {user} u, {chat_messages} c
453 WHERE c.chatid = :chatid $groupselect
454 AND u.id = c.userid", $params);
456 //Return students array (it contains an array of unique users)
461 * This standard function will check all instances of this module
462 * and make sure there are up-to-date events created for each of them.
463 * If courseid = 0, then every chat event in the site is checked, else
464 * only chat events belonging to the course specified are checked.
465 * This function is used, in its new format, by restore_refresh_events()
468 * @param int $courseid
471 function chat_refresh_events($courseid = 0) {
475 if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
479 if (! $chats = $DB->get_records("chat")) {
483 $moduleid = $DB->get_field('modules', 'id', array('name'=>'chat'));
485 foreach ($chats as $chat) {
486 $cm = get_coursemodule_from_id('chat', $chat->id
);
487 $event = new stdClass();
488 $event->name
= $chat->name
;
489 $event->description
= format_module_intro('chat', $chat, $cm->id
);
490 $event->timestart
= $chat->chattime
;
492 if ($event->id
= $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id
))) {
493 $calendarevent = calendar_event
::load($event->id
);
494 $calendarevent->update($event);
496 $event->courseid
= $chat->course
;
499 $event->modulename
= 'chat';
500 $event->instance
= $chat->id
;
501 $event->eventtype
= 'chattime';
502 $event->timeduration
= 0;
503 $event->visible
= $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$chat->id
));
505 calendar_event
::create($event);
512 //////////////////////////////////////////////////////////////////////
513 /// Functions that require some SQL
518 * @param int $groupid
519 * @param int $groupingid
522 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
525 $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
528 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
533 if (!empty($groupingid)) {
534 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
535 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
541 $ufields = user_picture
::fields('u');
542 return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
544 JOIN {user} u ON u.id = c.userid $groupingjoin
545 WHERE c.chatid = :chatid $groupselect
546 ORDER BY c.firstping ASC", $params);
552 * @param int $groupid
555 function chat_get_latest_message($chatid, $groupid=0) {
558 $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
561 $groupselect = "AND (groupid=:groupid OR groupid=0)";
567 FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
568 ORDER BY timestamp DESC";
570 // return the lastest one message
571 return $DB->get_record_sql($sql, $params, true);
575 //////////////////////////////////////////////////////////////////////
576 // login if not already logged in
579 * login if not already logged in
584 * @param string $version
585 * @param int $groupid
586 * @param object $course
587 * @return bool|int Returns the chat users sid or false
589 function chat_login_user($chatid, $version, $groupid, $course) {
592 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid'=>$chatid, 'userid'=>$USER->id
, 'groupid'=>$groupid))) {
593 // this will update logged user information
594 $chatuser->version
= $version;
595 $chatuser->ip
= $USER->lastip
;
596 $chatuser->lastping
= time();
597 $chatuser->lang
= current_language();
599 // Sometimes $USER->lastip is not setup properly
600 // during login. Update with current value if possible
601 // or provide a dummy value for the db
602 if (empty($chatuser->ip
)) {
603 $chatuser->ip
= getremoteaddr();
606 if (($chatuser->course
!= $course->id
) or ($chatuser->userid
!= $USER->id
)) {
609 $DB->update_record('chat_users', $chatuser);
612 $chatuser = new stdClass();
613 $chatuser->chatid
= $chatid;
614 $chatuser->userid
= $USER->id
;
615 $chatuser->groupid
= $groupid;
616 $chatuser->version
= $version;
617 $chatuser->ip
= $USER->lastip
;
618 $chatuser->lastping
= $chatuser->firstping
= $chatuser->lastmessageping
= time();
619 $chatuser->sid
= random_string(32);
620 $chatuser->course
= $course->id
; //caching - needed for current_language too
621 $chatuser->lang
= current_language(); //caching - to resource intensive to find out later
623 // Sometimes $USER->lastip is not setup properly
624 // during login. Update with current value if possible
625 // or provide a dummy value for the db
626 if (empty($chatuser->ip
)) {
627 $chatuser->ip
= getremoteaddr();
631 $DB->insert_record('chat_users', $chatuser);
633 if ($version == 'sockets') {
634 // do not send 'enter' message, chatd will do it
636 $message = new stdClass();
637 $message->chatid
= $chatuser->chatid
;
638 $message->userid
= $chatuser->userid
;
639 $message->groupid
= $groupid;
640 $message->message
= 'enter';
641 $message->system
= 1;
642 $message->timestamp
= time();
644 $DB->insert_record('chat_messages', $message);
645 $DB->insert_record('chat_messages_current', $message);
649 return $chatuser->sid
;
653 * Delete the old and in the way
658 function chat_delete_old_users() {
659 // Delete the old and in the way
662 $timeold = time() - $CFG->chat_old_ping
;
663 $timeoldext = time() - ($CFG->chat_old_ping
*10); // JSless gui_basic needs much longer timeouts
665 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
666 $params = array($timeold, $timeoldext);
668 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
669 $DB->delete_records_select('chat_users', $query, $params);
670 foreach ($oldusers as $olduser) {
671 $message = new stdClass();
672 $message->chatid
= $olduser->chatid
;
673 $message->userid
= $olduser->userid
;
674 $message->groupid
= $olduser->groupid
;
675 $message->message
= 'exit';
676 $message->system
= 1;
677 $message->timestamp
= time();
679 $DB->insert_record('chat_messages', $message);
680 $DB->insert_record('chat_messages_current', $message);
686 * Updates chat records so that the next chat time is correct
692 function chat_update_chat_times($chatid=0) {
693 /// Updates chat records so that the next chat time is correct
698 $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
701 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
705 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
710 foreach ($chats as $chat) {
711 switch ($chat->schedule
) {
712 case 1: // Single event - turn off schedule and disable
716 case 2: // Repeat daily
717 while ($chat->chattime
<= $timenow) {
718 $chat->chattime +
= 24 * 3600;
721 case 3: // Repeat weekly
722 while ($chat->chattime
<= $timenow) {
723 $chat->chattime +
= 7 * 24 * 3600;
727 $DB->update_record("chat", $chat);
729 $event = new stdClass(); // Update calendar too
731 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
732 $params = array('chattime'=>$chat->chattime
, 'chatid'=>$chatid);
734 if ($event->id
= $DB->get_field_select('event', 'id', $cond, $params)) {
735 $event->timestart
= $chat->chattime
;
736 $calendarevent = calendar_event
::load($event->id
);
737 $calendarevent->update($event, false);
745 * @param object $message
746 * @param int $courseid
747 * @param object $sender
748 * @param object $currentuser
749 * @param string $chat_lastrow
750 * @return bool|string Returns HTML or false
752 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
753 global $CFG, $USER, $OUTPUT;
755 $output = new stdClass();
756 $output->beep
= false; // by default
757 $output->refreshusers
= false; // by default
759 // Use get_user_timezone() to find the correct timezone for displaying this message:
760 // It's either the current user's timezone or else decided by some Moodle config setting
761 // First, "reset" $USER->timezone (which could have been set by a previous call to here)
762 // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
763 $USER->timezone
= 99;
764 $tz = get_user_timezone($currentuser->timezone
);
766 // Before formatting the message time string, set $USER->timezone to the above.
767 // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
768 // message times appear off because DST is not taken into account when it should be.
769 $USER->timezone
= $tz;
770 $message->strtime
= userdate($message->timestamp
, get_string('strftimemessage', 'chat'), $tz);
772 $message->picture
= $OUTPUT->user_picture($sender, array('size'=>false, 'courseid'=>$courseid, 'link'=>false));
775 $message->picture
= "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid')\" href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture</a>";
778 //Calculate the row class
779 if ($chat_lastrow !== NULL) {
780 $rowclass = ' class="r'.$chat_lastrow.'" ';
785 // Start processing the message
787 if(!empty($message->system
)) {
789 $output->text
= $message->strtime
.': '.get_string('message'.$message->message
, 'chat', fullname($sender));
790 $output->html
= '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture
.'</td><td class="text">';
791 $output->html
.= '<span class="event">'.$output->text
.'</span></td></tr></table>';
792 $output->basic
= '<dl><dt class="event">'.$message->strtime
.': '.get_string('message'.$message->message
, 'chat', fullname($sender)).'</dt></dl>';
794 if($message->message
== 'exit' or $message->message
== 'enter') {
795 $output->refreshusers
= true; //force user panel refresh ASAP
800 // It's not a system event
802 $text = $message->message
;
804 /// Parse the text to clean and filter it
806 $options = new stdClass();
807 $options->para
= false;
808 $text = format_text($text, FORMAT_MOODLE
, $options, $courseid);
810 // And now check for special cases
813 if (substr($text, 0, 5) == 'beep ') {
816 $beepwho = trim(substr($text, 5));
818 if ($beepwho == 'all') { // everyone
819 $outinfo = $message->strtime
.': '.get_string('messagebeepseveryone', 'chat', fullname($sender));
821 $output->beep
= true; // (eventually this should be set to
822 // to a filename uploaded by the user)
824 } else if ($beepwho == $currentuser->id
) { // current user
825 $outinfo = $message->strtime
.': '.get_string('messagebeepsyou', 'chat', fullname($sender));
827 $output->beep
= true;
829 } else { //something is not caught?
832 } else if (substr($text, 0, 1) == '/') { /// It's a user command
833 // support some IRC commands
834 $pattern = '#(^\/)(\w+).*#';
835 preg_match($pattern, trim($text), $matches);
836 $command = $matches[2];
840 $outinfo = $message->strtime
;
841 $outmain = '*** <b>'.$sender->firstname
.' '.substr($text, 4).'</b>';
844 } elseif (substr($text, 0, 2) == 'To') {
845 $pattern = '#To[[:space:]](.*):(.*)#';
846 preg_match($pattern, trim($text), $matches);
848 $outinfo = $message->strtime
;
849 $outmain = $sender->firstname
.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
853 $outinfo = $message->strtime
.' '.$sender->firstname
;
857 /// Format the message as a small table
859 $output->text
= strip_tags($outinfo.': '.$outmain);
861 $output->html
= "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
862 $output->html
.= "<span class=\"title\">$outinfo</span>";
864 $output->html
.= ": $outmain";
865 $output->basic
= '<dl><dt class="title">'.$outinfo.':</dt><dd class="text">'.$outmain.'</dd></dl>';
867 $output->basic
= '<dl><dt class="title">'.$outinfo.'</dt></dl>';
869 $output->html
.= "</td></tr></table>";
875 * @param object $message
876 * @param int $courseid
877 * @param object $currentuser
878 * @param string $chat_lastrow
879 * @return bool|string Returns HTML or false
881 function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
882 /// Given a message object full of information, this function
883 /// formats it appropriately into text and html, then
884 /// returns the formatted data.
887 static $users; // Cache user lookups
889 if (isset($users[$message->userid
])) {
890 $user = $users[$message->userid
];
891 } else if ($user = $DB->get_record('user', array('id'=>$message->userid
), user_picture
::fields())) {
892 $users[$message->userid
] = $user;
896 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
901 * @param object $message message to be displayed.
902 * @param mixed $chatuser user chat data
903 * @param object $currentuser current user for whom the message should be displayed.
904 * @param int $groupingid course module grouping id
905 * @param string $theme name of the chat theme.
906 * @return bool|string Returns HTML or false
908 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
909 global $CFG, $USER, $OUTPUT, $COURSE, $DB;
911 static $users; // Cache user lookups
913 $result = new stdClass();
915 if (file_exists($CFG->dirroot
. '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
916 include($CFG->dirroot
. '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
919 if (isset($users[$message->userid
])) {
920 $sender = $users[$message->userid
];
921 } else if ($sender = $DB->get_record('user', array('id'=>$message->userid
), user_picture
::fields())) {
922 $users[$message->userid
] = $sender;
927 $USER->timezone
= 99;
928 $tz = get_user_timezone($currentuser->timezone
);
929 $USER->timezone
= $tz;
931 if (empty($chatuser->course
)) {
932 $courseid = $COURSE->id
;
934 $courseid = $chatuser->course
;
937 $message->strtime
= userdate($message->timestamp
, get_string('strftimemessage', 'chat'), $tz);
938 $message->picture
= $OUTPUT->user_picture($sender, array('courseid'=>$courseid));
940 $message->picture
= "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture</a>";
942 // Start processing the message
943 if(!empty($message->system
)) {
944 $result->type
= 'system';
946 $userlink = new moodle_url('/user/view.php', array('id'=>$message->userid
,'course'=>$courseid));
949 $replacements = array();
950 $patterns[] = '___senderprofile___';
951 $patterns[] = '___sender___';
952 $patterns[] = '___time___';
953 $patterns[] = '___event___';
954 $replacements[] = $CFG->wwwroot
.'/user/view.php?id='.$sender->id
.'&course='.$courseid;
955 $replacements[] = fullname($sender);
956 $replacements[] = $message->strtime
;
957 $replacements[] = get_string('message'.$message->message
, 'chat', fullname($sender));
958 $result->html
= str_replace($patterns, $replacements, $chattheme_cfg->event_message
);
962 // It's not a system event
963 $text = $message->message
;
965 /// Parse the text to clean and filter it
966 $options = new stdClass();
967 $options->para
= false;
968 $text = format_text($text, FORMAT_MOODLE
, $options, $courseid);
970 // And now check for special cases
972 $outtime = $message->strtime
;
974 //Initilise output variable.
977 if (substr($text, 0, 5) == 'beep ') {
980 $result->type
= 'beep';
981 $beepwho = trim(substr($text, 5));
983 if ($beepwho == 'all') { // everyone
984 $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
985 } else if ($beepwho == $currentuser->id
) { // current user
986 $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
987 } else if ($sender->id
== $currentuser->id
) { //something is not caught?
988 //allow beep for a active chat user only, else user can beep anyone and get fullname
989 if (!empty($chatuser) && is_numeric($beepwho)) {
990 $chatusers = chat_get_users($chatuser->chatid
, $chatuser->groupid
, $groupingid);
991 if (array_key_exists($beepwho, $chatusers)) {
992 $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
994 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
997 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1000 } else if (substr($text, 0, 1) == '/') { /// It's a user command
1002 $result->type
= 'command';
1003 // support some IRC commands
1004 $pattern = '#(^\/)(\w+).*#';
1005 preg_match($pattern, trim($text), $matches);
1006 $command = $matches[2];
1010 $outmain = '*** <b>'.$sender->firstname
.' '.substr($text, 4).'</b>';
1013 } elseif (substr($text, 0, 2) == 'To') {
1015 $result->type
= 'dialogue';
1016 $pattern = '#To[[:space:]](.*):(.*)#';
1017 preg_match($pattern, trim($text), $matches);
1019 $outmain = $sender->firstname
.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
1026 $result->text
= strip_tags($outtime.': '.$outmain);
1030 if ($sender->id
== $USER->id
) {
1031 $ismymessage = ' class="mymessage"';
1032 $rightalign = ' align="right"';
1034 $patterns = array();
1035 $replacements = array();
1036 $patterns[] = '___avatar___';
1037 $patterns[] = '___sender___';
1038 $patterns[] = '___senderprofile___';
1039 $patterns[] = '___time___';
1040 $patterns[] = '___message___';
1041 $patterns[] = '___mymessageclass___';
1042 $patterns[] = '___tablealign___';
1043 $replacements[] = $message->picture
;
1044 $replacements[] = fullname($sender);
1045 $replacements[] = $CFG->wwwroot
.'/user/view.php?id='.$sender->id
.'&course='.$courseid;
1046 $replacements[] = $outtime;
1047 $replacements[] = $outmain;
1048 $replacements[] = $ismymessage;
1049 $replacements[] = $rightalign;
1050 if (!empty($chattheme_cfg->avatar
) and !empty($chattheme_cfg->align
)) {
1051 if (!empty($ismymessage)) {
1052 $result->html
= str_replace($patterns, $replacements, $chattheme_cfg->user_message_right
);
1054 $result->html
= str_replace($patterns, $replacements, $chattheme_cfg->user_message_left
);
1057 $result->html
= str_replace($patterns, $replacements, $chattheme_cfg->user_message
);
1060 //When user beeps other user, then don't show any timestamp to other users in chat.
1061 if (('' === $outmain) && $special) {
1070 * @global object $DB
1071 * @global object $CFG
1072 * @global object $COURSE
1073 * @global object $OUTPUT
1074 * @param object $users
1075 * @param object $course
1076 * @return array return formatted user list
1078 function chat_format_userlist($users, $course) {
1079 global $CFG, $DB, $COURSE, $OUTPUT;
1081 foreach($users as $user){
1083 $item['name'] = fullname($user);
1084 $item['url'] = $CFG->wwwroot
.'/user/view.php?id='.$user->id
.'&course='.$course->id
;
1085 $item['picture'] = $OUTPUT->user_picture($user);
1086 $item['id'] = $user->id
;
1093 * Print json format error
1094 * @param string $level
1095 * @param string $msg
1097 function chat_print_error($level, $msg) {
1098 header('Content-Length: ' . ob_get_length() );
1099 $error = new stdClass();
1100 $error->level
= $level;
1102 $response['error'] = $error;
1103 echo json_encode($response);
1111 function chat_get_view_actions() {
1112 return array('view','view all','report');
1118 function chat_get_post_actions() {
1119 return array('talk');
1125 * @param array $courses
1126 * @param array $htmlarray Passed by reference
1128 function chat_print_overview($courses, &$htmlarray) {
1131 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1135 if (!$chats = get_all_instances_in_courses('chat',$courses)) {
1139 $strchat = get_string('modulename', 'chat');
1140 $strnextsession = get_string('nextsession', 'chat');
1142 foreach ($chats as $chat) {
1143 if ($chat->chattime
and $chat->schedule
) { // A chat is scheduled
1144 $str = '<div class="chat overview"><div class="name">'.
1145 $strchat.': <a '.($chat->visible?
'':' class="dimmed"').
1146 ' href="'.$CFG->wwwroot
.'/mod/chat/view.php?id='.$chat->coursemodule
.'">'.
1147 $chat->name
.'</a></div>';
1148 $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime
).'</div></div>';
1150 if (empty($htmlarray[$chat->course
]['chat'])) {
1151 $htmlarray[$chat->course
]['chat'] = $str;
1153 $htmlarray[$chat->course
]['chat'] .= $str;
1161 * Implementation of the function for printing the form elements that control
1162 * whether the course reset functionality affects the chat.
1164 * @param object $mform form passed by reference
1166 function chat_reset_course_form_definition(&$mform) {
1167 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1168 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
1172 * Course reset form defaults.
1174 * @param object $course
1177 function chat_reset_course_form_defaults($course) {
1178 return array('reset_chat'=>1);
1182 * Actual implementation of the reset course functionality, delete all the
1183 * chat messages for course $data->courseid.
1187 * @param object $data the data submitted from the reset course.
1188 * @return array status array
1190 function chat_reset_userdata($data) {
1193 $componentstr = get_string('modulenameplural', 'chat');
1196 if (!empty($data->reset_chat
)) {
1197 $chatessql = "SELECT ch.id
1200 $params = array($data->courseid
);
1202 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1203 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1204 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1205 $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
1208 /// updating dates - shift may be negative too
1209 if ($data->timeshift
) {
1210 shift_course_mod_dates('chat', array('chattime'), $data->timeshift
, $data->courseid
);
1211 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1218 * Returns all other caps used in module
1222 function chat_get_extra_capabilities() {
1223 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
1228 * @param string $feature FEATURE_xx constant for requested feature
1229 * @return mixed True if module supports feature, null if doesn't know
1231 function chat_supports($feature) {
1233 case FEATURE_GROUPS
: return true;
1234 case FEATURE_GROUPINGS
: return true;
1235 case FEATURE_GROUPMEMBERSONLY
: return true;
1236 case FEATURE_MOD_INTRO
: return true;
1237 case FEATURE_BACKUP_MOODLE2
: return true;
1238 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
1239 case FEATURE_GRADE_HAS_GRADE
: return false;
1240 case FEATURE_GRADE_OUTCOMES
: return true;
1241 case FEATURE_SHOW_DESCRIPTION
: return true;
1243 default: return null;
1247 function chat_extend_navigation($navigation, $course, $module, $cm) {
1248 global $CFG, $USER, $PAGE, $OUTPUT;
1250 $currentgroup = groups_get_activity_group($cm, true);
1252 if (has_capability('mod/chat:chat', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
1253 $strenterchat = get_string('enterchat', 'chat');
1255 $target = $CFG->wwwroot
.'/mod/chat/';
1256 $params = array('id'=>$cm->instance
);
1258 if ($currentgroup) {
1259 $params['groupid'] = $currentgroup;
1264 // If user is using screenreader, display gui_basic gui link only
1265 if (empty($USER->screenreader
)) {
1266 $url = new moodle_url($target.'gui_'.$CFG->chat_method
.'/index.php', $params);
1267 $action = new popup_action('click', $url, 'chat'.$course->id
.$cm->instance
.$currentgroup, array('height' => 500, 'width' => 700));
1268 $links[] = new action_link($url, $strenterchat, $action);
1271 $url = new moodle_url($target.'gui_basic/index.php', $params);
1272 $action = new popup_action('click', $url, 'chat'.$course->id
.$cm->instance
.$currentgroup, array('height' => 500, 'width' => 700));
1273 $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1275 foreach ($links as $link) {
1276 $navigation->add($link->text
, $link, navigation_node
::TYPE_SETTING
, null ,null, new pix_icon('c/group' , ''));
1280 $chatusers = chat_get_users($cm->instance
, $currentgroup, $cm->groupingid
);
1281 if (is_array($chatusers) && count($chatusers)>0) {
1282 $users = $navigation->add(get_string('currentusers', 'chat'));
1283 foreach ($chatusers as $chatuser) {
1284 $userlink = new moodle_url('/user/view.php', array('id'=>$chatuser->id
,'course'=>$course->id
));
1285 $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping
), $userlink, navigation_node
::TYPE_USER
, null, null, new pix_icon('c/user', ''));
1291 * Adds module specific settings to the settings block
1293 * @param settings_navigation $settings The settings navigation object
1294 * @param navigation_node $chatnode The node to add module settings to
1296 function chat_extend_settings_navigation(settings_navigation
$settings, navigation_node
$chatnode) {
1297 global $DB, $PAGE, $USER;
1298 $chat = $DB->get_record("chat", array("id" => $PAGE->cm
->instance
));
1300 if ($chat->chattime
&& $chat->schedule
) {
1301 $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').': '.userdate($chat->chattime
).' ('.usertimezone($USER->timezone
));
1302 $nextsessionnode->add_class('note');
1305 $currentgroup = groups_get_activity_group($PAGE->cm
, true);
1306 if ($currentgroup) {
1307 $groupselect = " AND groupid = '$currentgroup'";
1312 if ($chat->studentlogs ||
has_capability('mod/chat:readlog',$PAGE->cm
->context
)) {
1313 if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id
))) {
1314 $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id'=>$PAGE->cm
->id
)));
1320 * user logout event handler
1322 * @param object $user full $USER object
1324 function chat_user_logout($user) {
1326 $DB->delete_records('chat_users', array('userid'=>$user->id
));
1330 * Return a list of page types
1331 * @param string $pagetype current page type
1332 * @param stdClass $parentcontext Block's parent context
1333 * @param stdClass $currentcontext Current context of block
1335 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1336 $module_pagetype = array('mod-chat-*'=>get_string('page-mod-chat-x', 'chat'));
1337 return $module_pagetype;