2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions and constants for module chat
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
27 require_once($CFG->dirroot
.'/calendar/lib.php');
30 define('CHAT_EVENT_TYPE_CHATTIME', 'chattime');
32 // Gap between sessions. 5 minutes or more of idleness between messages in a chat means the messages belong in different sessions.
33 define('CHAT_SESSION_GAP', 300);
35 // The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output.
36 global $CHAT_HTMLHEAD;
37 $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);
39 // The HTML head for the message window to start with (with js scrolling).
40 global $CHAT_HTMLHEAD_JS;
41 $CHAT_HTMLHEAD_JS = <<<EOD
42 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
43 <html><head><script type="text/javascript">
47 window.scroll(1,400000);
48 window.setTimeout("move()",100);
50 var scroll_active = true;
55 <body onBlur="scroll_active = true" onFocus="scroll_active = false">
57 global $CHAT_HTMLHEAD_JS;
58 $CHAT_HTMLHEAD_JS .= padding(200);
60 // The HTML code for standard empty pages (e.g. if a user was kicked out).
61 global $CHAT_HTMLHEAD_OUT;
62 $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>";
64 // The HTML head for the message input page.
65 global $CHAT_HTMLHEAD_MSGINPUT;
66 $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>";
68 // The HTML code for the message input page, with JavaScript.
69 global $CHAT_HTMLHEAD_MSGINPUT_JS;
70 $CHAT_HTMLHEAD_MSGINPUT_JS = <<<EOD
71 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
73 <head><title>Message Input</title>
74 <script type="text/javascript">
77 function empty_field_and_submit() {
78 document.fdummy.arsc_message.value=document.f.arsc_message.value;
79 document.fdummy.submit();
80 document.f.arsc_message.focus();
81 document.f.arsc_message.select();
86 </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
89 // Dummy data that gets output to the browser as needed, in order to make it show output.
90 global $CHAT_DUMMY_DATA;
91 $CHAT_DUMMY_DATA = padding(200);
97 function padding($n) {
99 for ($i = 0; $i < $n; $i++
) {
100 $str .= "<!-- nix -->\n";
106 * Given an object containing all the necessary data,
107 * (defined by the form in mod_form.php) this function
108 * will create a new instance and return the id number
109 * of the new instance.
112 * @param object $chat
115 function chat_add_instance($chat) {
118 $chat->timemodified
= time();
120 $returnid = $DB->insert_record("chat", $chat);
122 if ($chat->schedule
> 0) {
123 $event = new stdClass();
124 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
125 $event->name
= $chat->name
;
126 $event->description
= format_module_intro('chat', $chat, $chat->coursemodule
, false);
127 $event->format
= FORMAT_HTML
;
128 $event->courseid
= $chat->course
;
131 $event->modulename
= 'chat';
132 $event->instance
= $returnid;
133 $event->eventtype
= CHAT_EVENT_TYPE_CHATTIME
;
134 $event->timestart
= $chat->chattime
;
135 $event->timesort
= $chat->chattime
;
136 $event->timeduration
= 0;
138 calendar_event
::create($event, false);
141 if (!empty($chat->completionexpected
)) {
142 \core_completion\api
::update_completion_date_event($chat->coursemodule
, 'chat', $returnid, $chat->completionexpected
);
149 * Given an object containing all the necessary data,
150 * (defined by the form in mod_form.php) this function
151 * will update an existing instance with new data.
154 * @param object $chat
157 function chat_update_instance($chat) {
160 $chat->timemodified
= time();
161 $chat->id
= $chat->instance
;
163 $DB->update_record("chat", $chat);
165 $event = new stdClass();
167 if ($event->id
= $DB->get_field('event', 'id', array('modulename' => 'chat',
168 'instance' => $chat->id
, 'eventtype' => CHAT_EVENT_TYPE_CHATTIME
))) {
170 if ($chat->schedule
> 0) {
171 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
172 $event->name
= $chat->name
;
173 $event->description
= format_module_intro('chat', $chat, $chat->coursemodule
, false);
174 $event->format
= FORMAT_HTML
;
175 $event->timestart
= $chat->chattime
;
176 $event->timesort
= $chat->chattime
;
178 $calendarevent = calendar_event
::load($event->id
);
179 $calendarevent->update($event, false);
181 // Do not publish this event, so delete it.
182 $calendarevent = calendar_event
::load($event->id
);
183 $calendarevent->delete();
186 // No event, do we need to create one?
187 if ($chat->schedule
> 0) {
188 $event = new stdClass();
189 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
190 $event->name
= $chat->name
;
191 $event->description
= format_module_intro('chat', $chat, $chat->coursemodule
, false);
192 $event->format
= FORMAT_HTML
;
193 $event->courseid
= $chat->course
;
196 $event->modulename
= 'chat';
197 $event->instance
= $chat->id
;
198 $event->eventtype
= CHAT_EVENT_TYPE_CHATTIME
;
199 $event->timestart
= $chat->chattime
;
200 $event->timesort
= $chat->chattime
;
201 $event->timeduration
= 0;
203 calendar_event
::create($event, false);
207 $completionexpected = (!empty($chat->completionexpected
)) ?
$chat->completionexpected
: null;
208 \core_completion\api
::update_completion_date_event($chat->coursemodule
, 'chat', $chat->id
, $completionexpected);
214 * Given an ID of an instance of this module,
215 * this function will permanently delete the instance
216 * and any data that depends on it.
222 function chat_delete_instance($id) {
225 if (! $chat = $DB->get_record('chat', array('id' => $id))) {
231 // Delete any dependent records here.
233 if (! $DB->delete_records('chat', array('id' => $chat->id
))) {
236 if (! $DB->delete_records('chat_messages', array('chatid' => $chat->id
))) {
239 if (! $DB->delete_records('chat_messages_current', array('chatid' => $chat->id
))) {
242 if (! $DB->delete_records('chat_users', array('chatid' => $chat->id
))) {
246 if (! $DB->delete_records('event', array('modulename' => 'chat', 'instance' => $chat->id
))) {
254 * Given a course and a date, prints a summary of all chat rooms past and present
255 * This function is called from block_recent_activity
260 * @param object $course
261 * @param bool $viewfullnames
262 * @param int|string $timestart Timestamp
265 function chat_print_recent_activity($course, $viewfullnames, $timestart) {
266 global $CFG, $USER, $DB, $OUTPUT;
268 // This is approximate only, but it is really fast.
269 $timeout = $CFG->chat_old_ping
* 10;
271 if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
272 FROM {course_modules} cm
273 JOIN {modules} md ON md.id = cm.module
274 JOIN {chat} ch ON ch.id = cm.instance
275 JOIN {chat_messages} chm ON chm.chatid = ch.id
276 WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
278 ORDER BY lasttime ASC", array($timestart, $course->id
))) {
284 $modinfo = get_fast_modinfo($course); // Reference needed because we might load the groups.
286 foreach ($mcms as $cmid => $mcm) {
287 if (!array_key_exists($cmid, $modinfo->cms
)) {
290 $cm = $modinfo->cms
[$cmid];
291 if (!$modinfo->cms
[$cm->id
]->uservisible
) {
295 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
296 or has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
297 if ($timeout > time() - $mcm->lasttime
) {
306 // Verify groups in separate mode.
307 if (!$mygroupids = $modinfo->get_groups($cm->groupingid
)) {
311 // Ok, last post was not for my group - we have to query db to get last message from one of my groups.
312 // The only minor problem is that the order will not be correct.
313 $mygroupids = implode(',', $mygroupids);
315 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
316 FROM {course_modules} cm
317 JOIN {chat} ch ON ch.id = cm.instance
318 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
319 WHERE chm.timestamp > ? AND cm.id = ? AND
320 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
321 GROUP BY cm.id", array($timestart, $cm->id
))) {
325 $mcms[$cmid]->lasttime
= $mcm->lasttime
;
326 if ($timeout > time() - $mcm->lasttime
) {
333 if (!$past and !$current) {
337 $strftimerecent = get_string('strftimerecent');
340 echo $OUTPUT->heading(get_string("pastchats", 'chat') . ':', 6);
342 foreach ($past as $cm) {
343 $link = $CFG->wwwroot
.'/mod/chat/view.php?id='.$cm->id
;
344 $date = userdate($mcms[$cm->id
]->lasttime
, $strftimerecent);
345 echo '<div class="head"><div class="date">'.$date.'</div></div>';
346 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name
, true).'</a></div>';
351 echo $OUTPUT->heading(get_string("currentchats", 'chat') . ':', 6);
353 $oldest = floor((time() - $CFG->chat_old_ping
) / 10) * 10; // Better db caching.
355 $timeold = time() - $CFG->chat_old_ping
;
356 $timeold = floor($timeold / 10) * 10; // Better db caching.
357 $timeoldext = time() - ($CFG->chat_old_ping
* 10); // JSless gui_basic needs much longer timeouts.
358 $timeoldext = floor($timeoldext / 10) * 10; // Better db caching.
360 $params = array('timeold' => $timeold, 'timeoldext' => $timeoldext, 'cmid' => $cm->id
);
362 $timeout = "AND ((chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext))";
364 foreach ($current as $cm) {
365 // Count users first.
366 $mygroupids = $modinfo->groups
[$cm->groupingid
];
367 if (!empty($mygroupids)) {
368 list($subquery, $subparams) = $DB->get_in_or_equal($mygroupids, SQL_PARAMS_NAMED
, 'gid');
369 $params +
= $subparams;
370 $groupselect = "AND (chu.groupid $subquery OR chu.groupid = 0)";
375 $userfields = user_picture
::fields('u');
376 if (!$users = $DB->get_records_sql("SELECT $userfields
377 FROM {course_modules} cm
378 JOIN {chat} ch ON ch.id = cm.instance
379 JOIN {chat_users} chu ON chu.chatid = ch.id
380 JOIN {user} u ON u.id = chu.userid
381 WHERE cm.id = :cmid $timeout $groupselect
382 GROUP BY $userfields", $params)) {
385 $link = $CFG->wwwroot
.'/mod/chat/view.php?id='.$cm->id
;
386 $date = userdate($mcms[$cm->id
]->lasttime
, $strftimerecent);
388 echo '<div class="head"><div class="date">'.$date.'</div></div>';
389 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name
, true).'</a></div>';
390 echo '<div class="userlist">';
393 foreach ($users as $user) {
394 echo '<li>'.fullname($user, $viewfullnames).'</li>';
406 * This standard function will check all instances of this module
407 * and make sure there are up-to-date events created for each of them.
408 * If courseid = 0, then every chat event in the site is checked, else
409 * only chat events belonging to the course specified are checked.
410 * This function is used, in its new format, by restore_refresh_events()
413 * @param int $courseid
414 * @param int|stdClass $instance Chat module instance or ID.
415 * @param int|stdClass $cm Course module object or ID.
418 function chat_refresh_events($courseid = 0, $instance = null, $cm = null) {
421 // If we have instance information then we can just update the one event instead of updating all events.
422 if (isset($instance)) {
423 if (!is_object($instance)) {
424 $instance = $DB->get_record('chat', array('id' => $instance), '*', MUST_EXIST
);
427 if (!is_object($cm)) {
428 chat_prepare_update_events($instance);
431 chat_prepare_update_events($instance, $cm);
438 if (! $chats = $DB->get_records("chat", array("course" => $courseid))) {
442 if (! $chats = $DB->get_records("chat")) {
446 foreach ($chats as $chat) {
447 chat_prepare_update_events($chat);
453 * Updates both the normal and completion calendar events for chat.
455 * @param stdClass $chat The chat object (from the DB)
456 * @param stdClass $cm The course module object.
458 function chat_prepare_update_events($chat, $cm = null) {
461 $cm = get_coursemodule_from_instance('chat', $chat->id
, $chat->course
);
463 $event = new stdClass();
464 $event->name
= $chat->name
;
465 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
466 $event->description
= format_module_intro('chat', $chat, $cm->id
, false);
467 $event->format
= FORMAT_HTML
;
468 $event->timestart
= $chat->chattime
;
469 $event->timesort
= $chat->chattime
;
470 if ($event->id
= $DB->get_field('event', 'id', array('modulename' => 'chat', 'instance' => $chat->id
,
471 'eventtype' => CHAT_EVENT_TYPE_CHATTIME
))) {
472 $calendarevent = calendar_event
::load($event->id
);
473 $calendarevent->update($event, false);
474 } else if ($chat->schedule
> 0) {
475 // The chat is scheduled and the event should be published.
476 $event->courseid
= $chat->course
;
479 $event->modulename
= 'chat';
480 $event->instance
= $chat->id
;
481 $event->eventtype
= CHAT_EVENT_TYPE_CHATTIME
;
482 $event->timeduration
= 0;
483 $event->visible
= $cm->visible
;
484 calendar_event
::create($event, false);
488 // Functions that require some SQL.
493 * @param int $groupid
494 * @param int $groupingid
497 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
500 $params = array('chatid' => $chatid, 'groupid' => $groupid, 'groupingid' => $groupingid);
503 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
508 if (!empty($groupingid)) {
509 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
510 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
516 $ufields = user_picture
::fields('u');
517 return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
519 JOIN {user} u ON u.id = c.userid $groupingjoin
520 WHERE c.chatid = :chatid $groupselect
521 ORDER BY c.firstping ASC", $params);
527 * @param int $groupid
530 function chat_get_latest_message($chatid, $groupid=0) {
533 $params = array('chatid' => $chatid, 'groupid' => $groupid);
536 $groupselect = "AND (groupid=:groupid OR groupid=0)";
542 FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
543 ORDER BY timestamp DESC, id DESC";
545 // Return the lastest one message.
546 return $DB->get_record_sql($sql, $params, true);
550 * login if not already logged in
555 * @param string $version
556 * @param int $groupid
557 * @param object $course
558 * @return bool|int Returns the chat users sid or false
560 function chat_login_user($chatid, $version, $groupid, $course) {
563 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid' => $chatid,
564 'userid' => $USER->id
,
565 'groupid' => $groupid))) {
566 // This will update logged user information.
567 $chatuser->version
= $version;
568 $chatuser->ip
= $USER->lastip
;
569 $chatuser->lastping
= time();
570 $chatuser->lang
= current_language();
572 // Sometimes $USER->lastip is not setup properly during login.
573 // Update with current value if possible or provide a dummy value for the db.
574 if (empty($chatuser->ip
)) {
575 $chatuser->ip
= getremoteaddr();
578 if (($chatuser->course
!= $course->id
) or ($chatuser->userid
!= $USER->id
)) {
581 $DB->update_record('chat_users', $chatuser);
584 $chatuser = new stdClass();
585 $chatuser->chatid
= $chatid;
586 $chatuser->userid
= $USER->id
;
587 $chatuser->groupid
= $groupid;
588 $chatuser->version
= $version;
589 $chatuser->ip
= $USER->lastip
;
590 $chatuser->lastping
= $chatuser->firstping
= $chatuser->lastmessageping
= time();
591 $chatuser->sid
= random_string(32);
592 $chatuser->course
= $course->id
; // Caching - needed for current_language too.
593 $chatuser->lang
= current_language(); // Caching - to resource intensive to find out later.
595 // Sometimes $USER->lastip is not setup properly during login.
596 // Update with current value if possible or provide a dummy value for the db.
597 if (empty($chatuser->ip
)) {
598 $chatuser->ip
= getremoteaddr();
601 $DB->insert_record('chat_users', $chatuser);
603 if ($version == 'sockets') {
604 // Do not send 'enter' message, chatd will do it.
606 chat_send_chatmessage($chatuser, 'enter', true);
610 return $chatuser->sid
;
614 * Delete the old and in the way
619 function chat_delete_old_users() {
620 // Delete the old and in the way.
623 $timeold = time() - $CFG->chat_old_ping
;
624 $timeoldext = time() - ($CFG->chat_old_ping
* 10); // JSless gui_basic needs much longer timeouts.
626 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
627 $params = array($timeold, $timeoldext);
629 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
630 $DB->delete_records_select('chat_users', $query, $params);
631 foreach ($oldusers as $olduser) {
632 chat_send_chatmessage($olduser, 'exit', true);
638 * Updates chat records so that the next chat time is correct
644 function chat_update_chat_times($chatid=0) {
645 // Updates chat records so that the next chat time is correct.
650 $params = array('timenow' => $timenow, 'chatid' => $chatid);
653 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
657 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
662 foreach ($chats as $chat) {
663 switch ($chat->schedule
) {
664 case 1: // Single event - turn off schedule and disable.
668 case 2: // Repeat daily.
669 while ($chat->chattime
<= $timenow) {
670 $chat->chattime +
= 24 * 3600;
673 case 3: // Repeat weekly.
674 while ($chat->chattime
<= $timenow) {
675 $chat->chattime +
= 7 * 24 * 3600;
679 $DB->update_record("chat", $chat);
681 $event = new stdClass(); // Update calendar too.
683 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
684 $params = array('chattime' => $chat->chattime
, 'chatid' => $chat->id
);
686 if ($event->id
= $DB->get_field_select('event', 'id', $cond, $params)) {
687 $event->timestart
= $chat->chattime
;
688 $event->timesort
= $chat->chattime
;
689 $calendarevent = calendar_event
::load($event->id
);
690 $calendarevent->update($event, false);
696 * Send a message on the chat.
698 * @param object $chatuser The chat user record.
699 * @param string $messagetext The message to be sent.
700 * @param bool $issystem False for non-system messages, true for system messages.
701 * @param object $cm The course module object, pass it to save a database query when we trigger the event.
702 * @return int The message ID.
705 function chat_send_chatmessage($chatuser, $messagetext, $issystem = false, $cm = null) {
708 $message = new stdClass();
709 $message->chatid
= $chatuser->chatid
;
710 $message->userid
= $chatuser->userid
;
711 $message->groupid
= $chatuser->groupid
;
712 $message->message
= $messagetext;
713 $message->issystem
= $issystem ?
1 : 0;
714 $message->timestamp
= time();
716 $messageid = $DB->insert_record('chat_messages', $message);
717 $DB->insert_record('chat_messages_current', $message);
718 $message->id
= $messageid;
723 $cm = get_coursemodule_from_instance('chat', $chatuser->chatid
, $chatuser->course
);
727 'context' => context_module
::instance($cm->id
),
728 'objectid' => $message->id
,
729 // We set relateduserid, because when triggered from the chat daemon, the event userid is null.
730 'relateduserid' => $chatuser->userid
732 $event = \mod_chat\event\message_sent
::create($params);
733 $event->add_record_snapshot('chat_messages', $message);
743 * @param object $message
744 * @param int $courseid
745 * @param object $sender
746 * @param object $currentuser
747 * @param string $chatlastrow
748 * @return bool|string Returns HTML or false
750 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chatlastrow = null) {
751 global $CFG, $USER, $OUTPUT;
753 $output = new stdClass();
754 $output->beep
= false; // By default.
755 $output->refreshusers
= false; // By default.
757 // Find the correct timezone for displaying this message.
758 $tz = core_date
::get_user_timezone($currentuser);
760 $message->strtime
= userdate($message->timestamp
, get_string('strftimemessage', 'chat'), $tz);
762 $message->picture
= $OUTPUT->user_picture($sender, array('size' => false, 'courseid' => $courseid, 'link' => false));
765 $message->picture
= "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid')\"".
766 " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture</a>";
769 // Calculate the row class.
770 if ($chatlastrow !== null) {
771 $rowclass = ' class="r'.$chatlastrow.'" ';
776 // Start processing the message.
778 if (!empty($message->issystem
)) {
780 $output->text
= $message->strtime
.': '.get_string('message'.$message->message
, 'chat', fullname($sender));
781 $output->html
= '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture
.'</td>';
782 $output->html
.= '<td class="text"><span class="event">'.$output->text
.'</span></td></tr></table>';
783 $output->basic
= '<tr class="r1">
784 <th scope="row" class="cell c1 title"></th>
785 <td class="cell c2 text">' . get_string('message'.$message->message
, 'chat', fullname($sender)) . '</td>
786 <td class="cell c3">' . $message->strtime
. '</td>
788 if ($message->message
== 'exit' or $message->message
== 'enter') {
789 $output->refreshusers
= true; // Force user panel refresh ASAP.
794 // It's not a system event.
795 $rawtext = trim($message->message
);
797 // Options for format_text, when we get to it...
798 // format_text call will parse the text to clean and filter it.
799 // It cannot be called here as HTML-isation interferes with special case
800 // recognition, but *must* be called on any user-sourced text to be inserted
802 $options = new stdClass();
803 $options->para
= false;
804 $options->blanktarget
= true;
806 // And now check for special cases.
807 $patternto = '#^\s*To\s([^:]+):(.*)#';
810 if (substr($rawtext, 0, 5) == 'beep ') {
813 $beepwho = trim(substr($rawtext, 5));
815 if ($beepwho == 'all') { // Everyone.
816 $outinfobasic = get_string('messagebeepseveryone', 'chat', fullname($sender));
817 $outinfo = $message->strtime
. ': ' . $outinfobasic;
820 $output->beep
= true; // Eventually this should be set to a filename uploaded by the user.
822 } else if ($beepwho == $currentuser->id
) { // Current user.
823 $outinfobasic = get_string('messagebeepsyou', 'chat', fullname($sender));
824 $outinfo = $message->strtime
. ': ' . $outinfobasic;
826 $output->beep
= true;
828 } else { // Something is not caught?
831 } else if (substr($rawtext, 0, 1) == '/') { // It's a user command.
833 $pattern = '#(^\/)(\w+).*#';
834 preg_match($pattern, $rawtext, $matches);
835 $command = isset($matches[2]) ?
$matches[2] : false;
836 // Support some IRC commands.
839 $outinfo = $message->strtime
;
840 $text = '*** <b>'.$sender->firstname
.' '.substr($rawtext, 4).'</b>';
841 $outmain = format_text($text, FORMAT_MOODLE
, $options, $courseid);
844 // Error, we set special back to false to use the classic message output.
848 } else if (preg_match($patternto, $rawtext)) {
851 preg_match($patternto, $rawtext, $matches);
852 if (isset($matches[1]) && isset($matches[2])) {
853 $text = format_text($matches[2], FORMAT_MOODLE
, $options, $courseid);
854 $outinfo = $message->strtime
;
855 $outmain = $sender->firstname
.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$text;
857 // Error, we set special back to false to use the classic message output.
863 $text = format_text($rawtext, FORMAT_MOODLE
, $options, $courseid);
864 $outinfo = $message->strtime
.' '.$sender->firstname
;
868 // Format the message as a small table.
870 $output->text
= strip_tags($outinfo.': '.$outmain);
872 $output->html
= "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td>";
873 $output->html
.= "<td class=\"text\"><span class=\"title\">$outinfo</span>";
875 $output->html
.= ": $outmain";
876 $output->basic
= '<tr class="r0">
877 <th scope="row" class="cell c1 title">' . $sender->firstname
. '</th>
878 <td class="cell c2 text">' . $outmain . '</td>
879 <td class="cell c3">' . $message->strtime
. '</td>
882 $output->basic
= '<tr class="r1">
883 <th scope="row" class="cell c1 title"></th>
884 <td class="cell c2 text">' . $outinfobasic . '</td>
885 <td class="cell c3">' . $message->strtime
. '</td>
888 $output->html
.= "</td></tr></table>";
893 * Given a message object this function formats it appropriately into text and html then returns the formatted data
895 * @param object $message
896 * @param int $courseid
897 * @param object $currentuser
898 * @param string $chatlastrow
899 * @return bool|string Returns HTML or false
901 function chat_format_message($message, $courseid, $currentuser, $chatlastrow=null) {
904 static $users; // Cache user lookups.
906 if (isset($users[$message->userid
])) {
907 $user = $users[$message->userid
];
908 } else if ($user = $DB->get_record('user', array('id' => $message->userid
), user_picture
::fields())) {
909 $users[$message->userid
] = $user;
913 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chatlastrow);
918 * @param object $message message to be displayed.
919 * @param mixed $chatuser user chat data
920 * @param object $currentuser current user for whom the message should be displayed.
921 * @param int $groupingid course module grouping id
922 * @param string $theme name of the chat theme.
923 * @return bool|string Returns HTML or false
925 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
926 global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
927 require_once($CFG->dirroot
.'/mod/chat/locallib.php');
929 static $users; // Cache user lookups.
931 $result = new stdClass();
933 if (file_exists($CFG->dirroot
. '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
934 include($CFG->dirroot
. '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
937 if (isset($users[$message->userid
])) {
938 $sender = $users[$message->userid
];
939 } else if ($sender = $DB->get_record('user', array('id' => $message->userid
), user_picture
::fields())) {
940 $users[$message->userid
] = $sender;
945 // Find the correct timezone for displaying this message.
946 $tz = core_date
::get_user_timezone($currentuser);
948 if (empty($chatuser->course
)) {
949 $courseid = $COURSE->id
;
951 $courseid = $chatuser->course
;
954 $message->strtime
= userdate($message->timestamp
, get_string('strftimemessage', 'chat'), $tz);
955 $message->picture
= $OUTPUT->user_picture($sender, array('courseid' => $courseid));
957 $message->picture
= "<a target='_blank'".
958 " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture</a>";
960 // Start processing the message.
961 if (!empty($message->issystem
)) {
962 $result->type
= 'system';
964 $senderprofile = $CFG->wwwroot
.'/user/view.php?id='.$sender->id
.'&course='.$courseid;
965 $event = get_string('message'.$message->message
, 'chat', fullname($sender));
966 $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime
, $event, $theme);
968 $output = $PAGE->get_renderer('mod_chat');
969 $result->html
= $output->render($eventmessage);
974 // It's not a system event.
975 $rawtext = trim($message->message
);
977 // Options for format_text, when we get to it...
978 // format_text call will parse the text to clean and filter it.
979 // It cannot be called here as HTML-isation interferes with special case
980 // recognition, but *must* be called on any user-sourced text to be inserted
982 $options = new stdClass();
983 $options->para
= false;
984 $options->blanktarget
= true;
986 // And now check for special cases.
988 $outtime = $message->strtime
;
990 // Initialise variables.
992 $patternto = '#^\s*To\s([^:]+):(.*)#';
994 if (substr($rawtext, 0, 5) == 'beep ') {
997 $result->type
= 'beep';
998 $beepwho = trim(substr($rawtext, 5));
1000 if ($beepwho == 'all') { // Everyone.
1001 $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
1002 } else if ($beepwho == $currentuser->id
) { // Current user.
1003 $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
1004 } else if ($sender->id
== $currentuser->id
) { // Something is not caught?
1005 // Allow beep for a active chat user only, else user can beep anyone and get fullname.
1006 if (!empty($chatuser) && is_numeric($beepwho)) {
1007 $chatusers = chat_get_users($chatuser->chatid
, $chatuser->groupid
, $groupingid);
1008 if (array_key_exists($beepwho, $chatusers)) {
1009 $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
1011 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1014 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1017 } else if (substr($rawtext, 0, 1) == '/') { // It's a user command.
1019 $result->type
= 'command';
1020 $pattern = '#(^\/)(\w+).*#';
1021 preg_match($pattern, $rawtext, $matches);
1022 $command = isset($matches[2]) ?
$matches[2] : false;
1023 // Support some IRC commands.
1026 $text = '*** <b>'.$sender->firstname
.' '.substr($rawtext, 4).'</b>';
1027 $outmain = format_text($text, FORMAT_MOODLE
, $options, $courseid);
1030 // Error, we set special back to false to use the classic message output.
1034 } else if (preg_match($patternto, $rawtext)) {
1036 $result->type
= 'dialogue';
1038 preg_match($patternto, $rawtext, $matches);
1039 if (isset($matches[1]) && isset($matches[2])) {
1040 $text = format_text($matches[2], FORMAT_MOODLE
, $options, $courseid);
1041 $outmain = $sender->firstname
.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$text;
1043 // Error, we set special back to false to use the classic message output.
1049 $text = format_text($rawtext, FORMAT_MOODLE
, $options, $courseid);
1053 $result->text
= strip_tags($outtime.': '.$outmain);
1055 $mymessageclass = '';
1056 if ($sender->id
== $USER->id
) {
1057 $mymessageclass = 'chat-message-mymessage';
1060 $senderprofile = $CFG->wwwroot
.'/user/view.php?id='.$sender->id
.'&course='.$courseid;
1061 $usermessage = new user_message($senderprofile, fullname($sender), $message->picture
,
1062 $mymessageclass, $outtime, $outmain, $theme);
1064 $output = $PAGE->get_renderer('mod_chat');
1065 $result->html
= $output->render($usermessage);
1067 // When user beeps other user, then don't show any timestamp to other users in chat.
1068 if (('' === $outmain) && $special) {
1076 * @global object $DB
1077 * @global object $CFG
1078 * @global object $COURSE
1079 * @global object $OUTPUT
1080 * @param object $users
1081 * @param object $course
1082 * @return array return formatted user list
1084 function chat_format_userlist($users, $course) {
1085 global $CFG, $DB, $COURSE, $OUTPUT;
1087 foreach ($users as $user) {
1089 $item['name'] = fullname($user);
1090 $item['url'] = $CFG->wwwroot
.'/user/view.php?id='.$user->id
.'&course='.$course->id
;
1091 $item['picture'] = $OUTPUT->user_picture($user);
1092 $item['id'] = $user->id
;
1099 * Print json format error
1100 * @param string $level
1101 * @param string $msg
1103 function chat_print_error($level, $msg) {
1104 header('Content-Length: ' . ob_get_length() );
1105 $error = new stdClass();
1106 $error->level
= $level;
1108 $response['error'] = $error;
1109 echo json_encode($response);
1115 * List the actions that correspond to a view of this module.
1116 * This is used by the participation report.
1118 * Note: This is not used by new logging system. Event with
1119 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1120 * be considered as view action.
1124 function chat_get_view_actions() {
1125 return array('view', 'view all', 'report');
1129 * List the actions that correspond to a post of this module.
1130 * This is used by the participation report.
1132 * Note: This is not used by new logging system. Event with
1133 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1134 * will be considered as post action.
1138 function chat_get_post_actions() {
1139 return array('talk');
1143 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
1145 function chat_print_overview() {
1146 throw new coding_exception('chat_print_overview() can not be used any more and is obsolete.');
1151 * Implementation of the function for printing the form elements that control
1152 * whether the course reset functionality affects the chat.
1154 * @param object $mform form passed by reference
1156 function chat_reset_course_form_definition(&$mform) {
1157 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1158 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages', 'chat'));
1162 * Course reset form defaults.
1164 * @param object $course
1167 function chat_reset_course_form_defaults($course) {
1168 return array('reset_chat' => 1);
1172 * Actual implementation of the reset course functionality, delete all the
1173 * chat messages for course $data->courseid.
1177 * @param object $data the data submitted from the reset course.
1178 * @return array status array
1180 function chat_reset_userdata($data) {
1183 $componentstr = get_string('modulenameplural', 'chat');
1186 if (!empty($data->reset_chat
)) {
1187 $chatessql = "SELECT ch.id
1190 $params = array($data->courseid
);
1192 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1193 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1194 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1195 $status[] = array('component' => $componentstr, 'item' => get_string('removemessages', 'chat'), 'error' => false);
1198 // Updating dates - shift may be negative too.
1199 if ($data->timeshift
) {
1200 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1202 shift_course_mod_dates('chat', array('chattime'), $data->timeshift
, $data->courseid
);
1203 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
1210 * @param string $feature FEATURE_xx constant for requested feature
1211 * @return mixed True if module supports feature, null if doesn't know
1213 function chat_supports($feature) {
1215 case FEATURE_GROUPS
:
1217 case FEATURE_GROUPINGS
:
1219 case FEATURE_MOD_INTRO
:
1221 case FEATURE_BACKUP_MOODLE2
:
1223 case FEATURE_COMPLETION_TRACKS_VIEWS
:
1225 case FEATURE_GRADE_HAS_GRADE
:
1227 case FEATURE_GRADE_OUTCOMES
:
1229 case FEATURE_SHOW_DESCRIPTION
:
1236 function chat_extend_navigation($navigation, $course, $module, $cm) {
1239 $currentgroup = groups_get_activity_group($cm, true);
1241 if (has_capability('mod/chat:chat', context_module
::instance($cm->id
))) {
1242 $strenterchat = get_string('enterchat', 'chat');
1244 $target = $CFG->wwwroot
.'/mod/chat/';
1245 $params = array('id' => $cm->instance
);
1247 if ($currentgroup) {
1248 $params['groupid'] = $currentgroup;
1253 $url = new moodle_url($target.'gui_'.$CFG->chat_method
.'/index.php', $params);
1254 $action = new popup_action('click', $url, 'chat'.$course->id
.$cm->instance
.$currentgroup,
1255 array('height' => 500, 'width' => 700));
1256 $links[] = new action_link($url, $strenterchat, $action);
1258 $url = new moodle_url($target.'gui_basic/index.php', $params);
1259 $action = new popup_action('click', $url, 'chat'.$course->id
.$cm->instance
.$currentgroup,
1260 array('height' => 500, 'width' => 700));
1261 $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1263 foreach ($links as $link) {
1264 $navigation->add($link->text
, $link, navigation_node
::TYPE_SETTING
, null , null, new pix_icon('i/group' , ''));
1268 $chatusers = chat_get_users($cm->instance
, $currentgroup, $cm->groupingid
);
1269 if (is_array($chatusers) && count($chatusers) > 0) {
1270 $users = $navigation->add(get_string('currentusers', 'chat'));
1271 foreach ($chatusers as $chatuser) {
1272 $userlink = new moodle_url('/user/view.php', array('id' => $chatuser->id
, 'course' => $course->id
));
1273 $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping
),
1274 $userlink, navigation_node
::TYPE_USER
, null, null, new pix_icon('i/user', ''));
1280 * Adds module specific settings to the settings block
1282 * @param settings_navigation $settings The settings navigation object
1283 * @param navigation_node $chatnode The node to add module settings to
1285 function chat_extend_settings_navigation(settings_navigation
$settings, navigation_node
$chatnode) {
1286 global $DB, $PAGE, $USER;
1287 $chat = $DB->get_record("chat", array("id" => $PAGE->cm
->instance
));
1289 if ($chat->chattime
&& $chat->schedule
) {
1290 $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').
1291 ': '.userdate($chat->chattime
).
1292 ' ('.usertimezone($USER->timezone
).')');
1293 $nextsessionnode->add_class('note');
1296 $currentgroup = groups_get_activity_group($PAGE->cm
, true);
1297 if ($currentgroup) {
1298 $groupselect = " AND groupid = '$currentgroup'";
1303 if ($chat->studentlogs ||
has_capability('mod/chat:readlog', $PAGE->cm
->context
)) {
1304 if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id
))) {
1305 $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id' => $PAGE->cm
->id
)));
1311 * user logout event handler
1313 * @param \core\event\user_loggedout $event The event.
1316 function chat_user_logout(\core\event\user_loggedout
$event) {
1318 $DB->delete_records('chat_users', array('userid' => $event->objectid
));
1322 * Return a list of page types
1323 * @param string $pagetype current page type
1324 * @param stdClass $parentcontext Block's parent context
1325 * @param stdClass $currentcontext Current context of block
1327 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1328 $modulepagetype = array('mod-chat-*' => get_string('page-mod-chat-x', 'chat'));
1329 return $modulepagetype;
1333 * Return a list of the latest messages in the given chat session.
1335 * @param stdClass $chatuser chat user session data
1336 * @param int $chatlasttime last time messages were retrieved
1337 * @return array list of messages
1340 function chat_get_latest_messages($chatuser, $chatlasttime) {
1343 $params = array('groupid' => $chatuser->groupid
, 'chatid' => $chatuser->chatid
, 'lasttime' => $chatlasttime);
1345 $groupselect = $chatuser->groupid ?
" AND (groupid=" . $chatuser->groupid
. " OR groupid=0) " : "";
1347 return $DB->get_records_select('chat_messages_current', 'chatid = :chatid AND timestamp > :lasttime ' . $groupselect,
1348 $params, 'timestamp ASC');
1352 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1354 * @param stdClass $chat chat object
1355 * @param stdClass $course course object
1356 * @param stdClass $cm course module object
1357 * @param stdClass $context context object
1360 function chat_view($chat, $course, $cm, $context) {
1362 // Trigger course_module_viewed event.
1364 'context' => $context,
1365 'objectid' => $chat->id
1368 $event = \mod_chat\event\course_module_viewed
::create($params);
1369 $event->add_record_snapshot('course_modules', $cm);
1370 $event->add_record_snapshot('course', $course);
1371 $event->add_record_snapshot('chat', $chat);
1375 $completion = new completion_info($course);
1376 $completion->set_module_viewed($cm);
1380 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1382 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1383 * is not displayed on the block.
1385 * @param calendar_event $event
1386 * @param \core_calendar\action_factory $factory
1387 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1388 * @return \core_calendar\local\event\entities\action_interface|null
1390 function mod_chat_core_calendar_provide_event_action(calendar_event
$event,
1391 \core_calendar\action_factory
$factory,
1396 $user = core_user
::get_user($userid, 'id, timezone');
1401 $cm = get_fast_modinfo($event->courseid
, $user->id
)->instances
['chat'][$event->instance
];
1403 if (!$cm->uservisible
) {
1404 // The module is not visible to the user for any reason.
1408 $completion = new \
completion_info($cm->get_course());
1410 $completiondata = $completion->get_data($cm, false, $userid);
1412 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
1416 $chattime = $DB->get_field('chat', 'chattime', array('id' => $event->instance
));
1417 $usertimezone = core_date
::get_user_timezone($user);
1418 $chattimemidnight = usergetmidnight($chattime, $usertimezone);
1419 $todaymidnight = usergetmidnight(time(), $usertimezone);
1421 if ($chattime < $todaymidnight) {
1422 // The chat is before today. Do not show at all.
1425 // The chat is actionable if it is at some point today.
1426 $actionable = $chattimemidnight == $todaymidnight;
1428 return $factory->create_instance(
1429 get_string('enterchat', 'chat'),
1430 new \
moodle_url('/mod/chat/view.php', array('id' => $cm->id
)),
1438 * Given a set of messages for a chat, return the completed chat sessions (including optionally not completed ones).
1440 * @param array $messages list of messages from a chat. It is assumed that these are sorted by timestamp in DESCENDING order.
1441 * @param bool $showall whether to include incomplete sessions or not
1442 * @return array the list of sessions
1445 function chat_get_sessions($messages, $showall = false) {
1451 // Group messages by session times.
1452 foreach ($messages as $message) {
1453 // Initialise values start-end times if necessary.
1454 if (empty($start)) {
1455 $start = $message->timestamp
;
1458 $end = $message->timestamp
;
1461 // If this message's timestamp has been more than the gap, it means it's been idle.
1462 if ($start - $message->timestamp
> CHAT_SESSION_GAP
) {
1463 // Mark this as the session end of the next session.
1464 $end = $message->timestamp
;
1466 // Use this time as the session's start (until it gets overwritten on the next iteration, if needed).
1467 $start = $message->timestamp
;
1469 // Set this start-end pair in our list of session times.
1470 $sessiontimes[$end]['sessionstart'] = $start;
1471 if (!isset($sessiontimes[$end]['sessionend'])) {
1472 $sessiontimes[$end]['sessionend'] = $end;
1474 if ($message->userid
&& !$message->issystem
) {
1475 if (!isset($sessiontimes[$end]['sessionusers'][$message->userid
])) {
1476 $sessiontimes[$end]['sessionusers'][$message->userid
] = 1;
1478 $sessiontimes[$end]['sessionusers'][$message->userid
]++
;
1483 // Go through each session time and prepare the session data to be returned.
1484 foreach ($sessiontimes as $sessionend => $sessiondata) {
1485 if (!isset($sessiondata['sessionusers'])) {
1486 $sessiondata['sessionusers'] = [];
1488 $sessionusers = $sessiondata['sessionusers'];
1489 $sessionstart = $sessiondata['sessionstart'];
1491 $iscomplete = $sessionend - $sessionstart > 60 && count($sessionusers) > 1;
1492 if ($showall ||
$iscomplete) {
1493 $sessions[] = (object) ($sessiondata +
['iscomplete' => $iscomplete]);
1501 * Return the messages of the given chat session.
1503 * @param int $chatid the chat id
1504 * @param mixed $group false if groups not used, int if groups used, 0 means all groups
1505 * @param int $start the session start timestamp (0 to not filter by time)
1506 * @param int $end the session end timestamp (0 to not filter by time)
1507 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter)
1508 * @return array session messages
1511 function chat_get_session_messages($chatid, $group = false, $start = 0, $end = 0, $sort = '') {
1514 $params = array('chatid' => $chatid);
1516 // If the user is allocated to a group, only show messages from people in the same group, or no group.
1518 $groupselect = " AND (groupid = :currentgroup OR groupid = 0)";
1519 $params['currentgroup'] = $group;
1524 $select = "chatid = :chatid $groupselect";
1525 if (!empty($start)) {
1526 $select .= ' AND timestamp >= :start';
1527 $params['start'] = $start;
1530 $select .= ' AND timestamp <= :end';
1531 $params['end'] = $end;
1534 return $DB->get_records_select('chat_messages', $select, $params, $sort);