Merge branch 'MDL-48753_m27' of git://github.com/markn86/moodle into MOODLE_27_STABLE
[moodle.git] / mod / chat / lib.php
blobb68ec8b116bb4f29c9305c47106e9c4a17e498ab
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Library of functions and constants for module chat
21 * @package mod_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">
37 //<![CDATA[
38 function move(){
39 if (scroll_active)
40 window.scroll(1,400000);
41 window.setTimeout("move()",100);
43 var scroll_active = true;
44 move();
45 //]]>
46 </script>
47 </head>
48 <body onBlur="scroll_active = true" onFocus="scroll_active = false">
49 EOD;
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">
65 <html>
66 <head><title>Message Input</title>
67 <script type="text/javascript">
68 //<![CDATA[
69 scroll_active = true;
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();
75 return false;
77 //]]>
78 </script>
79 </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
80 EOD;
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);
86 /**
87 * @param int $n
88 * @return string
90 function padding($n){
91 $str = '';
92 for($i=0; $i<$n; $i++){
93 $str.="<!-- nix -->\n";
95 return $str;
98 /**
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.
104 * @global object
105 * @param object $chat
106 * @return int
108 function chat_add_instance($chat) {
109 global $DB;
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;
119 $event->groupid = 0;
120 $event->userid = 0;
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);
129 return $returnid;
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.
137 * @global object
138 * @param object $chat
139 * @return bool
141 function chat_update_instance($chat) {
142 global $DB;
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);
162 return true;
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.
170 * @global object
171 * @param int $id
172 * @return bool
174 function chat_delete_instance($id) {
175 global $DB;
178 if (! $chat = $DB->get_record('chat', array('id'=>$id))) {
179 return false;
182 $result = true;
184 // Delete any dependent records here
186 if (! $DB->delete_records('chat', array('id'=>$chat->id))) {
187 $result = false;
189 if (! $DB->delete_records('chat_messages', array('chatid'=>$chat->id))) {
190 $result = false;
192 if (! $DB->delete_records('chat_messages_current', array('chatid'=>$chat->id))) {
193 $result = false;
195 if (! $DB->delete_records('chat_users', array('chatid'=>$chat->id))) {
196 $result = false;
199 if (! $DB->delete_records('event', array('modulename'=>'chat', 'instance'=>$chat->id))) {
200 $result = false;
203 return $result;
207 * Given a course and a date, prints a summary of all chat rooms past and present
208 * This function is called from block_recent_activity
210 * @global object
211 * @global object
212 * @global object
213 * @param object $course
214 * @param bool $viewfullnames
215 * @param int|string $timestart Timestamp
216 * @return bool
218 function chat_print_recent_activity($course, $viewfullnames, $timestart) {
219 global $CFG, $USER, $DB, $OUTPUT;
221 // this is approximate only, but it is really fast ;-)
222 $timeout = $CFG->chat_old_ping * 10;
224 if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
225 FROM {course_modules} cm
226 JOIN {modules} md ON md.id = cm.module
227 JOIN {chat} ch ON ch.id = cm.instance
228 JOIN {chat_messages} chm ON chm.chatid = ch.id
229 WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
230 GROUP BY cm.id
231 ORDER BY lasttime ASC", array($timestart, $course->id))) {
232 return false;
235 $past = array();
236 $current = array();
237 $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
239 foreach ($mcms as $cmid=>$mcm) {
240 if (!array_key_exists($cmid, $modinfo->cms)) {
241 continue;
243 $cm = $modinfo->cms[$cmid];
244 if (!$modinfo->cms[$cm->id]->uservisible) {
245 continue;
248 if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
249 or has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
250 if ($timeout > time() - $mcm->lasttime) {
251 $current[] = $cm;
252 } else {
253 $past[] = $cm;
256 continue;
259 // verify groups in separate mode
260 if (!$mygroupids = $modinfo->get_groups($cm->groupingid)) {
261 continue;
264 // ok, last post was not for my group - we have to query db to get last message from one of my groups
265 // only minor problem is that the order will not be correct
266 $mygroupids = implode(',', $mygroupids);
268 if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
269 FROM {course_modules} cm
270 JOIN {chat} ch ON ch.id = cm.instance
271 JOIN {chat_messages_current} chm ON chm.chatid = ch.id
272 WHERE chm.timestamp > ? AND cm.id = ? AND
273 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
274 GROUP BY cm.id", array($timestart, $cm->id))) {
275 continue;
278 $mcms[$cmid]->lasttime = $mcm->lasttime;
279 if ($timeout > time() - $mcm->lasttime) {
280 $current[] = $cm;
281 } else {
282 $past[] = $cm;
286 if (!$past and !$current) {
287 return false;
290 $strftimerecent = get_string('strftimerecent');
292 if ($past) {
293 echo $OUTPUT->heading(get_string("pastchats", 'chat').':', 3);
295 foreach ($past as $cm) {
296 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
297 $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
298 echo '<div class="head"><div class="date">'.$date.'</div></div>';
299 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
303 if ($current) {
304 echo $OUTPUT->heading(get_string("currentchats", 'chat').':', 3);
306 $oldest = floor((time()-$CFG->chat_old_ping)/10)*10; // better db caching
308 $timeold = time() - $CFG->chat_old_ping;
309 $timeold = floor($timeold/10)*10; // better db caching
310 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
311 $timeoldext = floor($timeoldext/10)*10; // better db caching
313 $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id);
315 $timeout = "AND ((chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext))";
317 foreach ($current as $cm) {
318 //count users first
319 $mygroupids = $modinfo->groups[$cm->groupingid];
320 if (!empty($mygroupids)) {
321 list($subquery, $subparams) = $DB->get_in_or_equal($mygroupids, SQL_PARAMS_NAMED, 'gid');
322 $params += $subparams;
323 $groupselect = "AND (chu.groupid $subquery OR chu.groupid = 0)";
324 } else {
325 $groupselect = "";
328 $userfields = user_picture::fields('u');
329 if (!$users = $DB->get_records_sql("SELECT $userfields
330 FROM {course_modules} cm
331 JOIN {chat} ch ON ch.id = cm.instance
332 JOIN {chat_users} chu ON chu.chatid = ch.id
333 JOIN {user} u ON u.id = chu.userid
334 WHERE cm.id = :cmid $timeout $groupselect
335 GROUP BY $userfields", $params)) {
338 $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
339 $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
341 echo '<div class="head"><div class="date">'.$date.'</div></div>';
342 echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
343 echo '<div class="userlist">';
344 if ($users) {
345 echo '<ul>';
346 foreach ($users as $user) {
347 echo '<li>'.fullname($user, $viewfullnames).'</li>';
349 echo '</ul>';
351 echo '</div>';
355 return true;
359 * Function to be run periodically according to the moodle cron
360 * This function searches for things that need to be done, such
361 * as sending out mail, toggling flags etc ...
363 * @global object
364 * @return bool
366 function chat_cron () {
367 global $DB;
369 chat_update_chat_times();
371 chat_delete_old_users();
373 /// Delete old messages with a
374 /// single SQL query.
375 $subselect = "SELECT c.keepdays
376 FROM {chat} c
377 WHERE c.id = {chat_messages}.chatid";
379 $sql = "DELETE
380 FROM {chat_messages}
381 WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
383 $DB->execute($sql);
385 $sql = "DELETE
386 FROM {chat_messages_current}
387 WHERE timestamp < ( ".time()." - 8 * 3600)";
389 $DB->execute($sql);
391 return true;
395 * This standard function will check all instances of this module
396 * and make sure there are up-to-date events created for each of them.
397 * If courseid = 0, then every chat event in the site is checked, else
398 * only chat events belonging to the course specified are checked.
399 * This function is used, in its new format, by restore_refresh_events()
401 * @global object
402 * @param int $courseid
403 * @return bool
405 function chat_refresh_events($courseid = 0) {
406 global $DB;
408 if ($courseid) {
409 if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
410 return true;
412 } else {
413 if (! $chats = $DB->get_records("chat")) {
414 return true;
417 $moduleid = $DB->get_field('modules', 'id', array('name'=>'chat'));
419 foreach ($chats as $chat) {
420 $cm = get_coursemodule_from_id('chat', $chat->id);
421 $event = new stdClass();
422 $event->name = $chat->name;
423 $event->description = format_module_intro('chat', $chat, $cm->id);
424 $event->timestart = $chat->chattime;
426 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'chat', 'instance'=>$chat->id))) {
427 $calendarevent = calendar_event::load($event->id);
428 $calendarevent->update($event);
429 } else {
430 $event->courseid = $chat->course;
431 $event->groupid = 0;
432 $event->userid = 0;
433 $event->modulename = 'chat';
434 $event->instance = $chat->id;
435 $event->eventtype = 'chattime';
436 $event->timeduration = 0;
437 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$chat->id));
439 calendar_event::create($event);
442 return true;
446 //////////////////////////////////////////////////////////////////////
447 /// Functions that require some SQL
450 * @global object
451 * @param int $chatid
452 * @param int $groupid
453 * @param int $groupingid
454 * @return array
456 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
457 global $DB;
459 $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
461 if ($groupid) {
462 $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
463 } else {
464 $groupselect = "";
467 if (!empty($groupingid)) {
468 $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
469 JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
471 } else {
472 $groupingjoin = '';
475 $ufields = user_picture::fields('u');
476 return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
477 FROM {chat_users} c
478 JOIN {user} u ON u.id = c.userid $groupingjoin
479 WHERE c.chatid = :chatid $groupselect
480 ORDER BY c.firstping ASC", $params);
484 * @global object
485 * @param int $chatid
486 * @param int $groupid
487 * @return array
489 function chat_get_latest_message($chatid, $groupid=0) {
490 global $DB;
492 $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
494 if ($groupid) {
495 $groupselect = "AND (groupid=:groupid OR groupid=0)";
496 } else {
497 $groupselect = "";
500 $sql = "SELECT *
501 FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
502 ORDER BY timestamp DESC";
504 // return the lastest one message
505 return $DB->get_record_sql($sql, $params, true);
509 //////////////////////////////////////////////////////////////////////
510 // login if not already logged in
513 * login if not already logged in
515 * @global object
516 * @global object
517 * @param int $chatid
518 * @param string $version
519 * @param int $groupid
520 * @param object $course
521 * @return bool|int Returns the chat users sid or false
523 function chat_login_user($chatid, $version, $groupid, $course) {
524 global $USER, $DB;
526 if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid'=>$chatid, 'userid'=>$USER->id, 'groupid'=>$groupid))) {
527 // this will update logged user information
528 $chatuser->version = $version;
529 $chatuser->ip = $USER->lastip;
530 $chatuser->lastping = time();
531 $chatuser->lang = current_language();
533 // Sometimes $USER->lastip is not setup properly
534 // during login. Update with current value if possible
535 // or provide a dummy value for the db
536 if (empty($chatuser->ip)) {
537 $chatuser->ip = getremoteaddr();
540 if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
541 return false;
543 $DB->update_record('chat_users', $chatuser);
545 } else {
546 $chatuser = new stdClass();
547 $chatuser->chatid = $chatid;
548 $chatuser->userid = $USER->id;
549 $chatuser->groupid = $groupid;
550 $chatuser->version = $version;
551 $chatuser->ip = $USER->lastip;
552 $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
553 $chatuser->sid = random_string(32);
554 $chatuser->course = $course->id; //caching - needed for current_language too
555 $chatuser->lang = current_language(); //caching - to resource intensive to find out later
557 // Sometimes $USER->lastip is not setup properly
558 // during login. Update with current value if possible
559 // or provide a dummy value for the db
560 if (empty($chatuser->ip)) {
561 $chatuser->ip = getremoteaddr();
565 $DB->insert_record('chat_users', $chatuser);
567 if ($version == 'sockets') {
568 // do not send 'enter' message, chatd will do it
569 } else {
570 chat_send_chatmessage($chatuser, 'enter', true);
574 return $chatuser->sid;
578 * Delete the old and in the way
580 * @global object
581 * @global object
583 function chat_delete_old_users() {
584 // Delete the old and in the way
585 global $CFG, $DB;
587 $timeold = time() - $CFG->chat_old_ping;
588 $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
590 $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
591 $params = array($timeold, $timeoldext);
593 if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
594 $DB->delete_records_select('chat_users', $query, $params);
595 foreach ($oldusers as $olduser) {
596 chat_send_chatmessage($olduser, 'exit', true);
602 * Updates chat records so that the next chat time is correct
604 * @global object
605 * @param int $chatid
606 * @return void
608 function chat_update_chat_times($chatid=0) {
609 /// Updates chat records so that the next chat time is correct
610 global $DB;
612 $timenow = time();
614 $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
616 if ($chatid) {
617 if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
618 return;
620 } else {
621 if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
622 return;
626 foreach ($chats as $chat) {
627 switch ($chat->schedule) {
628 case 1: // Single event - turn off schedule and disable
629 $chat->chattime = 0;
630 $chat->schedule = 0;
631 break;
632 case 2: // Repeat daily
633 while ($chat->chattime <= $timenow) {
634 $chat->chattime += 24 * 3600;
636 break;
637 case 3: // Repeat weekly
638 while ($chat->chattime <= $timenow) {
639 $chat->chattime += 7 * 24 * 3600;
641 break;
643 $DB->update_record("chat", $chat);
645 $event = new stdClass(); // Update calendar too
647 $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
648 $params = array('chattime'=>$chat->chattime, 'chatid'=>$chatid);
650 if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
651 $event->timestart = $chat->chattime;
652 $calendarevent = calendar_event::load($event->id);
653 $calendarevent->update($event, false);
659 * Send a message on the chat.
661 * @param object $chatuser The chat user record.
662 * @param string $messagetext The message to be sent.
663 * @param bool $system False for non-system messages, true for system messages.
664 * @param object $cm The course module object, pass it to save a database query when we trigger the event.
665 * @return int The message ID.
666 * @since Moodle 2.6
668 function chat_send_chatmessage($chatuser, $messagetext, $system = false, $cm = null) {
669 global $DB;
671 $message = new stdClass();
672 $message->chatid = $chatuser->chatid;
673 $message->userid = $chatuser->userid;
674 $message->groupid = $chatuser->groupid;
675 $message->message = $messagetext;
676 $message->system = $system ? 1 : 0;
677 $message->timestamp = time();
679 $messageid = $DB->insert_record('chat_messages', $message);
680 $DB->insert_record('chat_messages_current', $message);
681 $message->id = $messageid;
683 if (!$system) {
685 if (empty($cm)) {
686 $cm = get_coursemodule_from_instance('chat', $chatuser->chatid, $chatuser->course);
689 $params = array(
690 'context' => context_module::instance($cm->id),
691 'objectid' => $message->id,
692 // We set relateduserid, because when triggered from the chat daemon, the event userid is null.
693 'relateduserid' => $chatuser->userid
695 $event = \mod_chat\event\message_sent::create($params);
696 $event->add_record_snapshot('chat_messages', $message);
697 $event->trigger();
700 return $message->id;
704 * @global object
705 * @global object
706 * @param object $message
707 * @param int $courseid
708 * @param object $sender
709 * @param object $currentuser
710 * @param string $chat_lastrow
711 * @return bool|string Returns HTML or false
713 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
714 global $CFG, $USER, $OUTPUT;
716 $output = new stdClass();
717 $output->beep = false; // by default
718 $output->refreshusers = false; // by default
720 // Use get_user_timezone() to find the correct timezone for displaying this message:
721 // It's either the current user's timezone or else decided by some Moodle config setting
722 // First, "reset" $USER->timezone (which could have been set by a previous call to here)
723 // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
724 $USER->timezone = 99;
725 $tz = get_user_timezone($currentuser->timezone);
727 // Before formatting the message time string, set $USER->timezone to the above.
728 // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
729 // message times appear off because DST is not taken into account when it should be.
730 $USER->timezone = $tz;
731 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
733 $message->picture = $OUTPUT->user_picture($sender, array('size'=>false, 'courseid'=>$courseid, 'link'=>false));
735 if ($courseid) {
736 $message->picture = "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid')\" href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
739 //Calculate the row class
740 if ($chat_lastrow !== NULL) {
741 $rowclass = ' class="r'.$chat_lastrow.'" ';
742 } else {
743 $rowclass = '';
746 // Start processing the message
748 if(!empty($message->system)) {
749 // System event
750 $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
751 $output->html = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
752 $output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
753 $output->basic = '<tr class="r1">
754 <th scope="row" class="cell c1 title"></th>
755 <td class="cell c2 text">' . get_string('message'.$message->message, 'chat', fullname($sender)) . '</td>
756 <td class="cell c3">' . $message->strtime . '</td>
757 </tr>';
758 if($message->message == 'exit' or $message->message == 'enter') {
759 $output->refreshusers = true; //force user panel refresh ASAP
761 return $output;
764 // It's not a system event
765 $text = trim($message->message);
767 /// Parse the text to clean and filter it
768 $options = new stdClass();
769 $options->para = false;
770 $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
772 // And now check for special cases
773 $patternTo = '#^\s*To\s([^:]+):(.*)#';
774 $special = false;
776 if (substr($text, 0, 5) == 'beep ') {
777 /// It's a beep!
778 $special = true;
779 $beepwho = trim(substr($text, 5));
781 if ($beepwho == 'all') { // everyone
782 $outinfobasic = get_string('messagebeepseveryone', 'chat', fullname($sender));
783 $outinfo = $message->strtime . ': ' . $outinfobasic;
784 $outmain = '';
786 $output->beep = true; // (eventually this should be set to
787 // to a filename uploaded by the user)
789 } else if ($beepwho == $currentuser->id) { // current user
790 $outinfobasic = get_string('messagebeepsyou', 'chat', fullname($sender));
791 $outinfo = $message->strtime . ': ' . $outinfobasic;
792 $outmain = '';
793 $output->beep = true;
795 } else { //something is not caught?
796 return false;
798 } else if (substr($text, 0, 1) == '/') { /// It's a user command
799 $special = true;
800 $pattern = '#(^\/)(\w+).*#';
801 preg_match($pattern, $text, $matches);
802 $command = isset($matches[2]) ? $matches[2] : false;
803 // Support some IRC commands.
804 switch ($command){
805 case 'me':
806 $outinfo = $message->strtime;
807 $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
808 break;
809 default:
810 // Error, we set special back to false to use the classic message output.
811 $special = false;
812 break;
814 } else if (preg_match($patternTo, $text)) {
815 $special = true;
816 $matches = array();
817 preg_match($patternTo, $text, $matches);
818 if (isset($matches[1]) && isset($matches[2])) {
819 $outinfo = $message->strtime;
820 $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
821 } else {
822 // Error, we set special back to false to use the classic message output.
823 $special = false;
827 if(!$special) {
828 $outinfo = $message->strtime.' '.$sender->firstname;
829 $outmain = $text;
832 /// Format the message as a small table
834 $output->text = strip_tags($outinfo.': '.$outmain);
836 $output->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
837 $output->html .= "<span class=\"title\">$outinfo</span>";
838 if ($outmain) {
839 $output->html .= ": $outmain";
840 $output->basic = '<tr class="r0">
841 <th scope="row" class="cell c1 title">' . $sender->firstname . '</th>
842 <td class="cell c2 text">' . $outmain . '</td>
843 <td class="cell c3">' . $message->strtime . '</td>
844 </tr>';
845 } else {
846 $output->basic = '<tr class="r1">
847 <th scope="row" class="cell c1 title"></th>
848 <td class="cell c2 text">' . $outinfobasic . '</td>
849 <td class="cell c3">' . $message->strtime . '</td>
850 </tr>';
852 $output->html .= "</td></tr></table>";
853 return $output;
857 * @global object
858 * @param object $message
859 * @param int $courseid
860 * @param object $currentuser
861 * @param string $chat_lastrow
862 * @return bool|string Returns HTML or false
864 function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
865 /// Given a message object full of information, this function
866 /// formats it appropriately into text and html, then
867 /// returns the formatted data.
868 global $DB;
870 static $users; // Cache user lookups
872 if (isset($users[$message->userid])) {
873 $user = $users[$message->userid];
874 } else if ($user = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
875 $users[$message->userid] = $user;
876 } else {
877 return NULL;
879 return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
883 * @global object
884 * @param object $message message to be displayed.
885 * @param mixed $chatuser user chat data
886 * @param object $currentuser current user for whom the message should be displayed.
887 * @param int $groupingid course module grouping id
888 * @param string $theme name of the chat theme.
889 * @return bool|string Returns HTML or false
891 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
892 global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
893 require_once($CFG->dirroot.'/mod/chat/locallib.php');
895 static $users; // Cache user lookups
897 $result = new stdClass();
899 if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
900 include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
903 if (isset($users[$message->userid])) {
904 $sender = $users[$message->userid];
905 } else if ($sender = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
906 $users[$message->userid] = $sender;
907 } else {
908 return NULL;
911 $USER->timezone = 99;
912 $tz = get_user_timezone($currentuser->timezone);
913 $USER->timezone = $tz;
915 if (empty($chatuser->course)) {
916 $courseid = $COURSE->id;
917 } else {
918 $courseid = $chatuser->course;
921 $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
922 $message->picture = $OUTPUT->user_picture($sender, array('courseid'=>$courseid));
924 $message->picture = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
926 // Start processing the message
927 if(!empty($message->system)) {
928 $result->type = 'system';
930 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
931 $event = get_string('message'.$message->message, 'chat', fullname($sender));
932 $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
934 $output = $PAGE->get_renderer('mod_chat');
935 $result->html = $output->render($eventmessage);
937 return $result;
940 // It's not a system event
941 $text = trim($message->message);
943 /// Parse the text to clean and filter it
944 $options = new stdClass();
945 $options->para = false;
946 $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
948 // And now check for special cases
949 $special = false;
950 $outtime = $message->strtime;
952 // Initialise variables.
953 $outmain = '';
954 $patternTo = '#^\s*To\s([^:]+):(.*)#';
956 if (substr($text, 0, 5) == 'beep ') {
957 $special = true;
958 /// It's a beep!
959 $result->type = 'beep';
960 $beepwho = trim(substr($text, 5));
962 if ($beepwho == 'all') { // everyone
963 $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
964 } else if ($beepwho == $currentuser->id) { // current user
965 $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
966 } else if ($sender->id == $currentuser->id) { //something is not caught?
967 //allow beep for a active chat user only, else user can beep anyone and get fullname
968 if (!empty($chatuser) && is_numeric($beepwho)) {
969 $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
970 if (array_key_exists($beepwho, $chatusers)) {
971 $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
972 } else {
973 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
975 } else {
976 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
979 } else if (substr($text, 0, 1) == '/') { /// It's a user command
980 $special = true;
981 $result->type = 'command';
982 $pattern = '#(^\/)(\w+).*#';
983 preg_match($pattern, $text, $matches);
984 $command = isset($matches[2]) ? $matches[2] : false;
985 // Support some IRC commands.
986 switch ($command){
987 case 'me':
988 $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
989 break;
990 default:
991 // Error, we set special back to false to use the classic message output.
992 $special = false;
993 break;
995 } else if (preg_match($patternTo, $text)) {
996 $special = true;
997 $result->type = 'dialogue';
998 $matches = array();
999 preg_match($patternTo, $text, $matches);
1000 if (isset($matches[1]) && isset($matches[2])) {
1001 $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
1002 } else {
1003 // Error, we set special back to false to use the classic message output.
1004 $special = false;
1008 if (!$special) {
1009 $outmain = $text;
1012 $result->text = strip_tags($outtime.': '.$outmain);
1014 $mymessageclass = '';
1015 if ($sender->id == $USER->id) {
1016 $mymessageclass = 'chat-message-mymessage';
1019 $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
1020 $usermessage = new user_message($senderprofile, fullname($sender), $message->picture, $mymessageclass, $outtime, $outmain, $theme);
1022 $output = $PAGE->get_renderer('mod_chat');
1023 $result->html = $output->render($usermessage);
1025 //When user beeps other user, then don't show any timestamp to other users in chat.
1026 if (('' === $outmain) && $special) {
1027 return false;
1028 } else {
1029 return $result;
1034 * @global object $DB
1035 * @global object $CFG
1036 * @global object $COURSE
1037 * @global object $OUTPUT
1038 * @param object $users
1039 * @param object $course
1040 * @return array return formatted user list
1042 function chat_format_userlist($users, $course) {
1043 global $CFG, $DB, $COURSE, $OUTPUT;
1044 $result = array();
1045 foreach($users as $user){
1046 $item = array();
1047 $item['name'] = fullname($user);
1048 $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id;
1049 $item['picture'] = $OUTPUT->user_picture($user);
1050 $item['id'] = $user->id;
1051 $result[] = $item;
1053 return $result;
1057 * Print json format error
1058 * @param string $level
1059 * @param string $msg
1061 function chat_print_error($level, $msg) {
1062 header('Content-Length: ' . ob_get_length() );
1063 $error = new stdClass();
1064 $error->level = $level;
1065 $error->msg = $msg;
1066 $response['error'] = $error;
1067 echo json_encode($response);
1068 ob_end_flush();
1069 exit;
1073 * List the actions that correspond to a view of this module.
1074 * This is used by the participation report.
1076 * Note: This is not used by new logging system. Event with
1077 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1078 * be considered as view action.
1080 * @return array
1082 function chat_get_view_actions() {
1083 return array('view','view all','report');
1087 * List the actions that correspond to a post of this module.
1088 * This is used by the participation report.
1090 * Note: This is not used by new logging system. Event with
1091 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1092 * will be considered as post action.
1094 * @return array
1096 function chat_get_post_actions() {
1097 return array('talk');
1101 * @global object
1102 * @global object
1103 * @param array $courses
1104 * @param array $htmlarray Passed by reference
1106 function chat_print_overview($courses, &$htmlarray) {
1107 global $USER, $CFG;
1109 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1110 return array();
1113 if (!$chats = get_all_instances_in_courses('chat',$courses)) {
1114 return;
1117 $strchat = get_string('modulename', 'chat');
1118 $strnextsession = get_string('nextsession', 'chat');
1120 foreach ($chats as $chat) {
1121 if ($chat->chattime and $chat->schedule) { // A chat is scheduled
1122 $str = '<div class="chat overview"><div class="name">'.
1123 $strchat.': <a '.($chat->visible?'':' class="dimmed"').
1124 ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
1125 $chat->name.'</a></div>';
1126 $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
1128 if (empty($htmlarray[$chat->course]['chat'])) {
1129 $htmlarray[$chat->course]['chat'] = $str;
1130 } else {
1131 $htmlarray[$chat->course]['chat'] .= $str;
1139 * Implementation of the function for printing the form elements that control
1140 * whether the course reset functionality affects the chat.
1142 * @param object $mform form passed by reference
1144 function chat_reset_course_form_definition(&$mform) {
1145 $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1146 $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
1150 * Course reset form defaults.
1152 * @param object $course
1153 * @return array
1155 function chat_reset_course_form_defaults($course) {
1156 return array('reset_chat'=>1);
1160 * Actual implementation of the reset course functionality, delete all the
1161 * chat messages for course $data->courseid.
1163 * @global object
1164 * @global object
1165 * @param object $data the data submitted from the reset course.
1166 * @return array status array
1168 function chat_reset_userdata($data) {
1169 global $CFG, $DB;
1171 $componentstr = get_string('modulenameplural', 'chat');
1172 $status = array();
1174 if (!empty($data->reset_chat)) {
1175 $chatessql = "SELECT ch.id
1176 FROM {chat} ch
1177 WHERE ch.course=?";
1178 $params = array($data->courseid);
1180 $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1181 $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1182 $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1183 $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
1186 /// updating dates - shift may be negative too
1187 if ($data->timeshift) {
1188 shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
1189 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1192 return $status;
1196 * Returns all other caps used in module
1198 * @return array
1200 function chat_get_extra_capabilities() {
1201 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
1206 * @param string $feature FEATURE_xx constant for requested feature
1207 * @return mixed True if module supports feature, null if doesn't know
1209 function chat_supports($feature) {
1210 switch($feature) {
1211 case FEATURE_GROUPS: return true;
1212 case FEATURE_GROUPINGS: return true;
1213 case FEATURE_GROUPMEMBERSONLY: return true;
1214 case FEATURE_MOD_INTRO: return true;
1215 case FEATURE_BACKUP_MOODLE2: return true;
1216 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1217 case FEATURE_GRADE_HAS_GRADE: return false;
1218 case FEATURE_GRADE_OUTCOMES: return true;
1219 case FEATURE_SHOW_DESCRIPTION: return true;
1221 default: return null;
1225 function chat_extend_navigation($navigation, $course, $module, $cm) {
1226 global $CFG;
1228 $currentgroup = groups_get_activity_group($cm, true);
1230 if (has_capability('mod/chat:chat', context_module::instance($cm->id))) {
1231 $strenterchat = get_string('enterchat', 'chat');
1233 $target = $CFG->wwwroot.'/mod/chat/';
1234 $params = array('id'=>$cm->instance);
1236 if ($currentgroup) {
1237 $params['groupid'] = $currentgroup;
1240 $links = array();
1242 $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
1243 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1244 $links[] = new action_link($url, $strenterchat, $action);
1246 $url = new moodle_url($target.'gui_basic/index.php', $params);
1247 $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1248 $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1250 foreach ($links as $link) {
1251 $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null ,null, new pix_icon('i/group' , ''));
1255 $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
1256 if (is_array($chatusers) && count($chatusers)>0) {
1257 $users = $navigation->add(get_string('currentusers', 'chat'));
1258 foreach ($chatusers as $chatuser) {
1259 $userlink = new moodle_url('/user/view.php', array('id'=>$chatuser->id,'course'=>$course->id));
1260 $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping), $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('i/user', ''));
1266 * Adds module specific settings to the settings block
1268 * @param settings_navigation $settings The settings navigation object
1269 * @param navigation_node $chatnode The node to add module settings to
1271 function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
1272 global $DB, $PAGE, $USER;
1273 $chat = $DB->get_record("chat", array("id" => $PAGE->cm->instance));
1275 if ($chat->chattime && $chat->schedule) {
1276 $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').': '.userdate($chat->chattime).' ('.usertimezone($USER->timezone));
1277 $nextsessionnode->add_class('note');
1280 $currentgroup = groups_get_activity_group($PAGE->cm, true);
1281 if ($currentgroup) {
1282 $groupselect = " AND groupid = '$currentgroup'";
1283 } else {
1284 $groupselect = '';
1287 if ($chat->studentlogs || has_capability('mod/chat:readlog',$PAGE->cm->context)) {
1288 if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
1289 $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id'=>$PAGE->cm->id)));
1295 * user logout event handler
1297 * @param \core\event\user_loggedout $event The event.
1298 * @return void
1300 function chat_user_logout(\core\event\user_loggedout $event) {
1301 global $DB;
1302 $DB->delete_records('chat_users', array('userid' => $event->objectid));
1306 * Return a list of page types
1307 * @param string $pagetype current page type
1308 * @param stdClass $parentcontext Block's parent context
1309 * @param stdClass $currentcontext Current context of block
1311 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1312 $module_pagetype = array('mod-chat-*'=>get_string('page-mod-chat-x', 'chat'));
1313 return $module_pagetype;