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 block_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 if (!$modinfo->cms[$cm->id]->uservisible) {
281 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
282 or has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
283 if ($timeout > time() - $mcm->lasttime) {
292 if (is_null($modinfo->groups)) {
293 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
296 // verify groups in separate mode
297 if (!$mygroupids = $modinfo->groups[$cm->groupingid]) {
301 // ok, last post was not for my group - we have to query db to get last message from one of my groups
302 // only minor problem is that the order will not be correct
303 $mygroupids = implode(',', $mygroupids);
304 $cm->mygroupids = $mygroupids;
306 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
307 FROM {course_modules} cm
308 JOIN {chat} ch ON ch.id = cm.instance
309 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
310 WHERE chm.timestamp > ? AND cm.id = ? AND
311 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
312 GROUP BY cm.id", array($timestart, $cm->id))) {
316 $mcms[$cmid]->lasttime = $mcm->lasttime;
317 if ($timeout > time() - $mcm->lasttime) {
324 if (!$past and !$current) {
328 $strftimerecent = get_string('strftimerecent');
331 echo $OUTPUT->heading(get_string("pastchats", 'chat').':');
333 foreach ($past as $cm) {
334 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
335 $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
336 echo '<div class="head"><div class="date">'.$date.'</div></div>';
337 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
342 echo $OUTPUT->heading(get_string("currentchats", 'chat').':');
344 $oldest = floor((time()-$CFG->chat_old_ping)/10)*10; // better db caching
346 $timeold = time() - $CFG->chat_old_ping;
347 $timeold = floor($timeold/10)*10; // better db caching
348 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
349 $timeoldext = floor($timeoldext/10)*10; // better db caching
351 $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id);
353 $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
355 foreach ($current as $cm) {
357 if (isset($cm->mygroupids)) {
358 $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
363 $userfields = user_picture::fields('u');
364 if (!$users = $DB->get_records_sql("SELECT $userfields
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($mcms[$cm->id]->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 * This standard function will check all instances of this module
431 * and make sure there are up-to-date events created for each of them.
432 * If courseid = 0, then every chat event in the site is checked, else
433 * only chat events belonging to the course specified are checked.
434 * This function is used, in its new format, by restore_refresh_events()
437 * @param int $courseid
440 function chat_refresh_events($courseid = 0) {
444 if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
448 if (! $chats = $DB->get_records("chat")) {
452 $moduleid = $DB->get_field('modules', 'id', array('name'=>'chat'));
454 foreach ($chats as $chat) {
455 $cm = get_coursemodule_from_id('chat', $chat->id);
456 $event = new stdClass();
457 $event->name = $chat->name;
458 $event->description = format_module_intro('chat', $chat, $cm->id);
459 $event->timestart = $chat->chattime;
461 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
462 $calendarevent = calendar_event::load($event->id);
463 $calendarevent->update($event);
465 $event->courseid = $chat->course;
468 $event->modulename = 'chat';
469 $event->instance = $chat->id;
470 $event->eventtype = 'chattime';
471 $event->timeduration = 0;
472 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$chat->id));
474 calendar_event::create($event);
481 //////////////////////////////////////////////////////////////////////
482 /// Functions that require some SQL
487 * @param int $groupid
488 * @param int $groupingid
491 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
494 $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
497 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
502 if (!empty($groupingid)) {
503 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
504 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
510 $ufields = user_picture::fields('u');
511 return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
513 JOIN {user} u ON u.id = c.userid $groupingjoin
514 WHERE c.chatid = :chatid $groupselect
515 ORDER BY c.firstping ASC", $params);
521 * @param int $groupid
524 function chat_get_latest_message($chatid, $groupid=0) {
527 $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
530 $groupselect = "AND (groupid=:groupid OR groupid=0)";
536 FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
537 ORDER BY timestamp DESC";
539 // return the lastest one message
540 return $DB->get_record_sql($sql, $params, true);
544 //////////////////////////////////////////////////////////////////////
545 // login if not already logged in
548 * login if not already logged in
553 * @param string $version
554 * @param int $groupid
555 * @param object $course
556 * @return bool|int Returns the chat users sid or false
558 function chat_login_user($chatid, $version, $groupid, $course) {
561 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid'=>$chatid, 'userid'=>$USER->id, 'groupid'=>$groupid))) {
562 // this will update logged user information
563 $chatuser->version = $version;
564 $chatuser->ip = $USER->lastip;
565 $chatuser->lastping = time();
566 $chatuser->lang = current_language();
568 // Sometimes $USER->lastip is not setup properly
569 // during login. Update with current value if possible
570 // or provide a dummy value for the db
571 if (empty($chatuser->ip)) {
572 $chatuser->ip = getremoteaddr();
575 if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
578 $DB->update_record('chat_users', $chatuser);
581 $chatuser = new stdClass();
582 $chatuser->chatid = $chatid;
583 $chatuser->userid = $USER->id;
584 $chatuser->groupid = $groupid;
585 $chatuser->version = $version;
586 $chatuser->ip = $USER->lastip;
587 $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
588 $chatuser->sid = random_string(32);
589 $chatuser->course = $course->id; //caching - needed for current_language too
590 $chatuser->lang = current_language(); //caching - to resource intensive to find out later
592 // Sometimes $USER->lastip is not setup properly
593 // during login. Update with current value if possible
594 // or provide a dummy value for the db
595 if (empty($chatuser->ip)) {
596 $chatuser->ip = getremoteaddr();
600 $DB->insert_record('chat_users', $chatuser);
602 if ($version == 'sockets') {
603 // do not send 'enter' message, chatd will do it
605 chat_send_chatmessage($chatuser, 'enter', true);
609 return $chatuser->sid;
613 * Delete the old and in the way
618 function chat_delete_old_users() {
619 // Delete the old and in the way
622 $timeold = time() - $CFG->chat_old_ping;
623 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
625 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
626 $params = array($timeold, $timeoldext);
628 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
629 $DB->delete_records_select('chat_users', $query, $params);
630 foreach ($oldusers as $olduser) {
631 chat_send_chatmessage($olduser, 'exit', true);
637 * Updates chat records so that the next chat time is correct
643 function chat_update_chat_times($chatid=0) {
644 /// Updates chat records so that the next chat time is correct
649 $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
652 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
656 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
661 foreach ($chats as $chat) {
662 switch ($chat->schedule) {
663 case 1: // Single event - turn off schedule and disable
667 case 2: // Repeat daily
668 while ($chat->chattime <= $timenow) {
669 $chat->chattime += 24 * 3600;
672 case 3: // Repeat weekly
673 while ($chat->chattime <= $timenow) {
674 $chat->chattime += 7 * 24 * 3600;
678 $DB->update_record("chat", $chat);
680 $event = new stdClass(); // Update calendar too
682 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
683 $params = array('chattime'=>$chat->chattime, 'chatid'=>$chatid);
685 if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
686 $event->timestart = $chat->chattime;
687 $calendarevent = calendar_event::load($event->id);
688 $calendarevent->update($event, false);
694 * Send a message on the chat.
696 * @param object $chatuser The chat user record.
697 * @param string $messagetext The message to be sent.
698 * @param bool $system False for non-system messages, true for system messages.
699 * @param object $cm The course module object, pass it to save a database query when we trigger the event.
700 * @return int The message ID.
703 function chat_send_chatmessage($chatuser, $messagetext, $system = false, $cm = null) {
706 $message = new stdClass();
707 $message->chatid = $chatuser->chatid;
708 $message->userid = $chatuser->userid;
709 $message->groupid = $chatuser->groupid;
710 $message->message = $messagetext;
711 $message->system = $system ? 1 : 0;
712 $message->timestamp = time();
714 $messageid = $DB->insert_record('chat_messages', $message);
715 $DB->insert_record('chat_messages_current', $message);
716 $message->id = $messageid;
721 $cm = get_coursemodule_from_instance('chat', $chatuser->chatid, $chatuser->course);
725 'context' => context_module::instance($cm->id),
726 'objectid' => $message->id,
727 // We set relateduserid, because when triggered from the chat daemon, the event userid is null.
728 'relateduserid' => $chatuser->userid
730 $event = \mod_chat\event\message_sent::create($params);
731 $event->add_record_snapshot('chat_messages', $message);
741 * @param object $message
742 * @param int $courseid
743 * @param object $sender
744 * @param object $currentuser
745 * @param string $chat_lastrow
746 * @return bool|string Returns HTML or false
748 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
749 global $CFG, $USER, $OUTPUT;
751 $output = new stdClass();
752 $output->beep = false; // by default
753 $output->refreshusers = false; // by default
755 // Use get_user_timezone() to find the correct timezone for displaying this message:
756 // It's either the current user's timezone or else decided by some Moodle config setting
757 // First, "reset" $USER->timezone (which could have been set by a previous call to here)
758 // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
759 $USER->timezone = 99;
760 $tz = get_user_timezone($currentuser->timezone);
762 // Before formatting the message time string, set $USER->timezone to the above.
763 // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
764 // message times appear off because DST is not taken into account when it should be.
765 $USER->timezone = $tz;
766 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
768 $message->picture = $OUTPUT->user_picture($sender, array('size'=>false, 'courseid'=>$courseid, 'link'=>false));
771 $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>";
774 //Calculate the row class
775 if ($chat_lastrow !== NULL) {
776 $rowclass = ' class="r'.$chat_lastrow.'" ';
781 // Start processing the message
783 if(!empty($message->system)) {
785 $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
786 $output->html = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
787 $output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
788 $output->basic = '<tr class="r1">
789 <th scope="row" class="cell c1 title"></th>
790 <td class="cell c2 text">' . get_string('message'.$message->message, 'chat', fullname($sender)) . '</td>
791 <td class="cell c3">' . $message->strtime . '</td>
793 if($message->message == 'exit' or $message->message == 'enter') {
794 $output->refreshusers = true; //force user panel refresh ASAP
799 // It's not a system event
800 $text = trim($message->message);
802 /// Parse the text to clean and filter it
803 $options = new stdClass();
804 $options->para = false;
805 $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
807 // And now check for special cases
808 $patternTo = '#^\s*To\s([^:]+):(.*)#';
811 if (substr($text, 0, 5) == 'beep ') {
814 $beepwho = trim(substr($text, 5));
816 if ($beepwho == 'all') { // everyone
817 $outinfobasic = get_string('messagebeepseveryone', 'chat', fullname($sender));
818 $outinfo = $message->strtime . ': ' . $outinfobasic;
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 $outinfobasic = get_string('messagebeepsyou', 'chat', fullname($sender));
826 $outinfo = $message->strtime . ': ' . $outinfobasic;
828 $output->beep = true;
830 } else { //something is not caught?
833 } else if (substr($text, 0, 1) == '/') { /// It's a user command
835 $pattern = '#(^\/)(\w+).*#';
836 preg_match($pattern, $text, $matches);
837 $command = isset($matches[2]) ? $matches[2] : false;
838 // Support some IRC commands.
841 $outinfo = $message->strtime;
842 $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
845 // Error, we set special back to false to use the classic message output.
849 } else if (preg_match($patternTo, $text)) {
852 preg_match($patternTo, $text, $matches);
853 if (isset($matches[1]) && isset($matches[2])) {
854 $outinfo = $message->strtime;
855 $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
857 // Error, we set special back to false to use the classic message output.
863 $outinfo = $message->strtime.' '.$sender->firstname;
867 /// Format the message as a small table
869 $output->text = strip_tags($outinfo.': '.$outmain);
871 $output->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
872 $output->html .= "<span class=\"title\">$outinfo</span>";
874 $output->html .= ": $outmain";
875 $output->basic = '<tr class="r0">
876 <th scope="row" class="cell c1 title">' . $sender->firstname . '</th>
877 <td class="cell c2 text">' . $outmain . '</td>
878 <td class="cell c3">' . $message->strtime . '</td>
881 $output->basic = '<tr class="r1">
882 <th scope="row" class="cell c1 title"></th>
883 <td class="cell c2 text">' . $outinfobasic . '</td>
884 <td class="cell c3">' . $message->strtime . '</td>
887 $output->html .= "</td></tr></table>";
893 * @param object $message
894 * @param int $courseid
895 * @param object $currentuser
896 * @param string $chat_lastrow
897 * @return bool|string Returns HTML or false
899 function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
900 /// Given a message object full of information, this function
901 /// formats it appropriately into text and html, then
902 /// returns the formatted data.
905 static $users; // Cache user lookups
907 if (isset($users[$message->userid])) {
908 $user = $users[$message->userid];
909 } else if ($user = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
910 $users[$message->userid] = $user;
914 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
919 * @param object $message message to be displayed.
920 * @param mixed $chatuser user chat data
921 * @param object $currentuser current user for whom the message should be displayed.
922 * @param int $groupingid course module grouping id
923 * @param string $theme name of the chat theme.
924 * @return bool|string Returns HTML or false
926 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
927 global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
928 require_once($CFG->dirroot.'/mod/chat/locallib.php');
930 static $users; // Cache user lookups
932 $result = new stdClass();
934 if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
935 include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
938 if (isset($users[$message->userid])) {
939 $sender = $users[$message->userid];
940 } else if ($sender = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
941 $users[$message->userid] = $sender;
946 $USER->timezone = 99;
947 $tz = get_user_timezone($currentuser->timezone);
948 $USER->timezone = $tz;
950 if (empty($chatuser->course)) {
951 $courseid = $COURSE->id;
953 $courseid = $chatuser->course;
956 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
957 $message->picture = $OUTPUT->user_picture($sender, array('courseid'=>$courseid));
959 $message->picture = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture</a>";
961 // Start processing the message
962 if(!empty($message->system)) {
963 $result->type = 'system';
965 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&course='.$courseid;
966 $event = get_string('message'.$message->message, 'chat', fullname($sender));
967 $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
969 $output = $PAGE->get_renderer('mod_chat');
970 $result->html = $output->render($eventmessage);
975 // It's not a system event
976 $text = trim($message->message);
978 /// Parse the text to clean and filter it
979 $options = new stdClass();
980 $options->para = false;
981 $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
983 // And now check for special cases
985 $outtime = $message->strtime;
987 // Initialise variables.
989 $patternTo = '#^\s*To\s([^:]+):(.*)#';
991 if (substr($text, 0, 5) == 'beep ') {
994 $result->type = 'beep';
995 $beepwho = trim(substr($text, 5));
997 if ($beepwho == 'all') { // everyone
998 $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
999 } else if ($beepwho == $currentuser->id) { // current user
1000 $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
1001 } else if ($sender->id == $currentuser->id) { //something is not caught?
1002 //allow beep for a active chat user only, else user can beep anyone and get fullname
1003 if (!empty($chatuser) && is_numeric($beepwho)) {
1004 $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
1005 if (array_key_exists($beepwho, $chatusers)) {
1006 $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
1008 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1011 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1014 } else if (substr($text, 0, 1) == '/') { /// It's a user command
1016 $result->type = 'command';
1017 $pattern = '#(^\/)(\w+).*#';
1018 preg_match($pattern, $text, $matches);
1019 $command = isset($matches[2]) ? $matches[2] : false;
1020 // Support some IRC commands.
1023 $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
1026 // Error, we set special back to false to use the classic message output.
1030 } else if (preg_match($patternTo, $text)) {
1032 $result->type = 'dialogue';
1034 preg_match($patternTo, $text, $matches);
1035 if (isset($matches[1]) && isset($matches[2])) {
1036 $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
1038 // Error, we set special back to false to use the classic message output.
1047 $result->text = strip_tags($outtime.': '.$outmain);
1049 $mymessageclass = '';
1050 if ($sender->id == $USER->id) {
1051 $mymessageclass = 'chat-message-mymessage';
1054 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&course='.$courseid;
1055 $usermessage = new user_message($senderprofile, fullname($sender), $message->picture, $mymessageclass, $outtime, $outmain, $theme);
1057 $output = $PAGE->get_renderer('mod_chat');
1058 $result->html = $output->render($usermessage);
1060 //When user beeps other user, then don't show any timestamp to other users in chat.
1061 if (('' === $outmain) && $special) {
1069 * @global object $DB
1070 * @global object $CFG
1071 * @global object $COURSE
1072 * @global object $OUTPUT
1073 * @param object $users
1074 * @param object $course
1075 * @return array return formatted user list
1077 function chat_format_userlist($users, $course) {
1078 global $CFG, $DB, $COURSE, $OUTPUT;
1080 foreach($users as $user){
1082 $item['name'] = fullname($user);
1083 $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&course='.$course->id;
1084 $item['picture'] = $OUTPUT->user_picture($user);
1085 $item['id'] = $user->id;
1092 * Print json format error
1093 * @param string $level
1094 * @param string $msg
1096 function chat_print_error($level, $msg) {
1097 header('Content-Length: ' . ob_get_length() );
1098 $error = new stdClass();
1099 $error->level = $level;
1101 $response['error'] = $error;
1102 echo json_encode($response);
1110 function chat_get_view_actions() {
1111 return array('view','view all','report');
1117 function chat_get_post_actions() {
1118 return array('talk');
1124 * @param array $courses
1125 * @param array $htmlarray Passed by reference
1127 function chat_print_overview($courses, &$htmlarray) {
1130 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1134 if (!$chats = get_all_instances_in_courses('chat',$courses)) {
1138 $strchat = get_string('modulename', 'chat');
1139 $strnextsession = get_string('nextsession', 'chat');
1141 foreach ($chats as $chat) {
1142 if ($chat->chattime and $chat->schedule) { // A chat is scheduled
1143 $str = '<div class="chat overview"><div class="name">'.
1144 $strchat.': <a '.($chat->visible?'':' class="dimmed"').
1145 ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
1146 $chat->name.'</a></div>';
1147 $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
1149 if (empty($htmlarray[$chat->course]['chat'])) {
1150 $htmlarray[$chat->course]['chat'] = $str;
1152 $htmlarray[$chat->course]['chat'] .= $str;
1160 * Implementation of the function for printing the form elements that control
1161 * whether the course reset functionality affects the chat.
1163 * @param object $mform form passed by reference
1165 function chat_reset_course_form_definition(&$mform) {
1166 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1167 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
1171 * Course reset form defaults.
1173 * @param object $course
1176 function chat_reset_course_form_defaults($course) {
1177 return array('reset_chat'=>1);
1181 * Actual implementation of the reset course functionality, delete all the
1182 * chat messages for course $data->courseid.
1186 * @param object $data the data submitted from the reset course.
1187 * @return array status array
1189 function chat_reset_userdata($data) {
1192 $componentstr = get_string('modulenameplural', 'chat');
1195 if (!empty($data->reset_chat)) {
1196 $chatessql = "SELECT ch.id
1199 $params = array($data->courseid);
1201 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1202 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1203 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1204 $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
1207 /// updating dates - shift may be negative too
1208 if ($data->timeshift) {
1209 shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
1210 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1217 * Returns all other caps used in module
1221 function chat_get_extra_capabilities() {
1222 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
1227 * @param string $feature FEATURE_xx constant for requested feature
1228 * @return mixed True if module supports feature, null if doesn't know
1230 function chat_supports($feature) {
1232 case FEATURE_GROUPS: return true;
1233 case FEATURE_GROUPINGS: return true;
1234 case FEATURE_GROUPMEMBERSONLY: return true;
1235 case FEATURE_MOD_INTRO: return true;
1236 case FEATURE_BACKUP_MOODLE2: return true;
1237 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1238 case FEATURE_GRADE_HAS_GRADE: return false;
1239 case FEATURE_GRADE_OUTCOMES: return true;
1240 case FEATURE_SHOW_DESCRIPTION: return true;
1242 default: return null;
1246 function chat_extend_navigation($navigation, $course, $module, $cm) {
1249 $currentgroup = groups_get_activity_group($cm, true);
1251 if (has_capability('mod/chat:chat', context_module::instance($cm->id))) {
1252 $strenterchat = get_string('enterchat', 'chat');
1254 $target = $CFG->wwwroot.'/mod/chat/';
1255 $params = array('id'=>$cm->instance);
1257 if ($currentgroup) {
1258 $params['groupid'] = $currentgroup;
1263 $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
1264 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1265 $links[] = new action_link($url, $strenterchat, $action);
1267 $url = new moodle_url($target.'gui_basic/index.php', $params);
1268 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1269 $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1271 foreach ($links as $link) {
1272 $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null ,null, new pix_icon('i/group' , ''));
1276 $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
1277 if (is_array($chatusers) && count($chatusers)>0) {
1278 $users = $navigation->add(get_string('currentusers', 'chat'));
1279 foreach ($chatusers as $chatuser) {
1280 $userlink = new moodle_url('/user/view.php', array('id'=>$chatuser->id,'course'=>$course->id));
1281 $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping), $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('i/user', ''));
1287 * Adds module specific settings to the settings block
1289 * @param settings_navigation $settings The settings navigation object
1290 * @param navigation_node $chatnode The node to add module settings to
1292 function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
1293 global $DB, $PAGE, $USER;
1294 $chat = $DB->get_record("chat", array("id" => $PAGE->cm->instance));
1296 if ($chat->chattime && $chat->schedule) {
1297 $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').': '.userdate($chat->chattime).' ('.usertimezone($USER->timezone));
1298 $nextsessionnode->add_class('note');
1301 $currentgroup = groups_get_activity_group($PAGE->cm, true);
1302 if ($currentgroup) {
1303 $groupselect = " AND groupid = '$currentgroup'";
1308 if ($chat->studentlogs || has_capability('mod/chat:readlog',$PAGE->cm->context)) {
1309 if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
1310 $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id'=>$PAGE->cm->id)));
1316 * user logout event handler
1318 * @param \core\event\user_loggedout $event The event.
1321 function chat_user_logout(\core\event\user_loggedout $event) {
1323 $DB->delete_records('chat_users', array('userid' => $event->objectid));
1327 * Return a list of page types
1328 * @param string $pagetype current page type
1329 * @param stdClass $parentcontext Block's parent context
1330 * @param stdClass $currentcontext Current context of block
1332 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1333 $module_pagetype = array('mod-chat-*'=>get_string('page-mod-chat-x', 'chat'));
1334 return $module_pagetype;