bf2d40571d84597d2bc3a27ab759ae4692ec5f97
[moodle.git] / mod / chat / lib.php
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.
14 //
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
20  *
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
24  */
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);
42 }
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;
76     }
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
89  */
90 function padding($n){
91     $str = '';
92     for($i=0; $i<$n; $i++){
93         $str.="<!-- nix -->\n";
94     }
95     return $str;
96 }
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.
103  *
104  * @global object
105  * @param object $chat
106  * @return int
107  */
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;
132 /**
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.
136  *
137  * @global object
138  * @param object $chat
139  * @return bool
140  */
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);
160     }
162     return true;
165 /**
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.
169  *
170  * @global object
171  * @param int $id
172  * @return bool
173  */
174 function chat_delete_instance($id) {
175     global $DB;
178     if (! $chat = $DB->get_record('chat', array('id'=>$id))) {
179         return false;
180     }
182     $result = true;
184     // Delete any dependent records here
186     if (! $DB->delete_records('chat', array('id'=>$chat->id))) {
187         $result = false;
188     }
189     if (! $DB->delete_records('chat_messages', array('chatid'=>$chat->id))) {
190         $result = false;
191     }
192     if (! $DB->delete_records('chat_messages_current', array('chatid'=>$chat->id))) {
193         $result = false;
194     }
195     if (! $DB->delete_records('chat_users', array('chatid'=>$chat->id))) {
196         $result = false;
197     }
199     if (! $DB->delete_records('event', array('modulename'=>'chat', 'instance'=>$chat->id))) {
200         $result = false;
201     }
203     return $result;
206 /**
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.
210  * <code>
211  * $return->time = the time they did it
212  * $return->info = a short text description
213  * </code>
214  *
215  * @param object $course
216  * @param object $user
217  * @param object $mod
218  * @param object $chat
219  * @return void
220  */
221 function chat_user_outline($course, $user, $mod, $chat) {
222     return NULL;
225 /**
226  * Print a detailed representation of what a  user has done with
227  * a given particular instance of this module, for user activity reports.
228  *
229  * @param object $course
230  * @param object $user
231  * @param object $mod
232  * @param object $chat
233  * @return bool
234  */
235 function chat_user_complete($course, $user, $mod, $chat) {
236     return true;
239 /**
240  * Given a course and a date, prints a summary of all chat rooms past and present
241  * This function is called from course/lib.php: print_recent_activity()
242  *
243  * @global object
244  * @global object
245  * @global object
246  * @param object $course
247  * @param bool $viewfullnames
248  * @param int|string $timestart Timestamp
249  * @return bool
250  */
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'
263                                      GROUP BY cm.id
264                                      ORDER BY lasttime ASC", array($timestart, $course->id))) {
265          return false;
266     }
268     $past     = array();
269     $current  = array();
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)) {
274             continue;
275         }
276         $cm = $modinfo->cms[$cmid];
277         $cm->lasttime = $mcm->lasttime;
278         if (!$modinfo->cms[$cm->id]->uservisible) {
279             continue;
280         }
282         if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
283          or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
284             if ($timeout > time() - $cm->lasttime) {
285                 $current[] = $cm;
286             } else {
287                 $past[] = $cm;
288             }
290             continue;
291         }
293         if (is_null($modinfo->groups)) {
294             $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
295         }
297         // verify groups in separate mode
298         if (!$mygroupids = $modinfo->groups[$cm->groupingid]) {
299             continue;
300         }
302         // ok, last post was not for my group - we have to query db to get last message from one of my groups
303         // only minor problem is that the order will not be correct
304         $mygroupids = implode(',', $mygroupids);
305         $cm->mygroupids = $mygroupids;
307         if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
308                                            FROM {course_modules} cm
309                                            JOIN {chat} ch           ON ch.id = cm.instance
310                                            JOIN {chat_messages_current} chm ON chm.chatid = ch.id
311                                           WHERE chm.timestamp > ? AND cm.id = ? AND
312                                                 (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
313                                        GROUP BY cm.id", array($timestart, $cm->id))) {
314              continue;
315         }
317         $cm->lasttime = $mcm->lasttime;
318         if ($timeout > time() - $cm->lasttime) {
319             $current[] = $cm;
320         } else {
321             $past[] = $cm;
322         }
323     }
325     if (!$past and !$current) {
326         return false;
327     }
329     $strftimerecent = get_string('strftimerecent');
331     if ($past) {
332         echo $OUTPUT->heading(get_string("pastchats", 'chat').':');
334         foreach ($past as $cm) {
335             $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
336             $date = userdate($cm->lasttime, $strftimerecent);
337             echo '<div class="head"><div class="date">'.$date.'</div></div>';
338             echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
339         }
340     }
342     if ($current) {
343         echo $OUTPUT->heading(get_string("currentchats", 'chat').':');
345         $oldest = floor((time()-$CFG->chat_old_ping)/10)*10;  // better db caching
347         $timeold    = time() - $CFG->chat_old_ping;
348         $timeold    = floor($timeold/10)*10;  // better db caching
349         $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
350         $timeoldext = floor($timeoldext/10)*10;  // better db caching
352         $params = array('timeold'=>$timeold, 'timeoldext'=>$timeoldext, 'cmid'=>$cm->id);
354         $timeout = "AND (chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext)";
356         foreach ($current as $cm) {
357             //count users first
358             if (isset($cm->mygroupids)) {
359                 $groupselect = "AND (chu.groupid IN ({$cm->mygroupids}) OR chu.groupid = 0)";
360             } else {
361                 $groupselect = "";
362             }
364             if (!$users = $DB->get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email, u.picture
365                                                   FROM {course_modules} cm
366                                                   JOIN {chat} ch        ON ch.id = cm.instance
367                                                   JOIN {chat_users} chu ON chu.chatid = ch.id
368                                                   JOIN {user} u         ON u.id = chu.userid
369                                                  WHERE cm.id = :cmid $timeout $groupselect
370                                               GROUP BY u.id, u.firstname, u.lastname, u.email, u.picture", $params)) {
371             }
373             $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
374             $date = userdate($cm->lasttime, $strftimerecent);
376             echo '<div class="head"><div class="date">'.$date.'</div></div>';
377             echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name,true).'</a></div>';
378             echo '<div class="userlist">';
379             if ($users) {
380                 echo '<ul>';
381                     foreach ($users as $user) {
382                         echo '<li>'.fullname($user, $viewfullnames).'</li>';
383                     }
384                 echo '</ul>';
385             }
386             echo '</div>';
387         }
388     }
390     return true;
393 /**
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 ...
397  *
398  * @global object
399  * @return bool
400  */
401 function chat_cron () {
402     global $DB;
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
411                     FROM {chat} c
412                    WHERE c.id = {chat_messages}.chatid";
414     $sql = "DELETE
415               FROM {chat_messages}
416              WHERE ($subselect) > 0 AND timestamp < ( ".time()." -($subselect) * 24 * 3600)";
418     $DB->execute($sql);
420     $sql = "DELETE
421               FROM {chat_messages_current}
422              WHERE timestamp < ( ".time()." - 8 * 3600)";
424     $DB->execute($sql);
426     return true;
429 /**
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()
435  *
436  * @global object
437  * @param int $courseid
438  * @return bool
439  */
440 function chat_refresh_events($courseid = 0) {
441     global $DB;
443     if ($courseid) {
444         if (! $chats = $DB->get_records("chat", array("course"=>$courseid))) {
445             return true;
446         }
447     } else {
448         if (! $chats = $DB->get_records("chat")) {
449             return true;
450         }
451     }
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);
464         } else {
465             $event->courseid    = $chat->course;
466             $event->groupid     = 0;
467             $event->userid      = 0;
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);
475         }
476     }
477     return true;
481 //////////////////////////////////////////////////////////////////////
482 /// Functions that require some SQL
484 /**
485  * @global object
486  * @param int $chatid
487  * @param int $groupid
488  * @param int $groupingid
489  * @return array
490  */
491 function chat_get_users($chatid, $groupid=0, $groupingid=0) {
492     global $DB;
494     $params = array('chatid'=>$chatid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
496     if ($groupid) {
497         $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
498     } else {
499         $groupselect = "";
500     }
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 ";
506     } else {
507         $groupingjoin = '';
508     }
510     $ufields = user_picture::fields('u');
511     return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
512                                    FROM {chat_users} c
513                                    JOIN {user} u ON u.id = c.userid $groupingjoin
514                                   WHERE c.chatid = :chatid $groupselect
515                                ORDER BY c.firstping ASC", $params);
518 /**
519  * @global object
520  * @param int $chatid
521  * @param int $groupid
522  * @return array
523  */
524 function chat_get_latest_message($chatid, $groupid=0) {
525     global $DB;
527     $params = array('chatid'=>$chatid, 'groupid'=>$groupid);
529     if ($groupid) {
530         $groupselect = "AND (groupid=:groupid OR groupid=0)";
531     } else {
532         $groupselect = "";
533     }
535     $sql = "SELECT *
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
547 /**
548  * login if not already logged in
549  *
550  * @global object
551  * @global object
552  * @param int $chatid
553  * @param string $version
554  * @param int $groupid
555  * @param object $course
556  * @return bool|int Returns the chat users sid or false
557  */
558 function chat_login_user($chatid, $version, $groupid, $course) {
559     global $USER, $DB;
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();
573         }
575         if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
576             return false;
577         }
578         $DB->update_record('chat_users', $chatuser);
580     } else {
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();
597         }
600         $DB->insert_record('chat_users', $chatuser);
602         if ($version == 'sockets') {
603             // do not send 'enter' message, chatd will do it
604         } else {
605             $message = new stdClass();
606             $message->chatid    = $chatuser->chatid;
607             $message->userid    = $chatuser->userid;
608             $message->groupid   = $groupid;
609             $message->message   = 'enter';
610             $message->system    = 1;
611             $message->timestamp = time();
613             $DB->insert_record('chat_messages', $message);
614             $DB->insert_record('chat_messages_current', $message);
615         }
616     }
618     return $chatuser->sid;
621 /**
622  * Delete the old and in the way
623  *
624  * @global object
625  * @global object
626  */
627 function chat_delete_old_users() {
628 // Delete the old and in the way
629     global $CFG, $DB;
631     $timeold = time() - $CFG->chat_old_ping;
632     $timeoldext = time() - ($CFG->chat_old_ping*10); // JSless gui_basic needs much longer timeouts
634     $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
635     $params = array($timeold, $timeoldext);
637     if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
638         $DB->delete_records_select('chat_users', $query, $params);
639         foreach ($oldusers as $olduser) {
640             $message = new stdClass();
641             $message->chatid    = $olduser->chatid;
642             $message->userid    = $olduser->userid;
643             $message->groupid   = $olduser->groupid;
644             $message->message   = 'exit';
645             $message->system    = 1;
646             $message->timestamp = time();
648             $DB->insert_record('chat_messages', $message);
649             $DB->insert_record('chat_messages_current', $message);
650         }
651     }
654 /**
655  * Updates chat records so that the next chat time is correct
656  *
657  * @global object
658  * @param int $chatid
659  * @return void
660  */
661 function chat_update_chat_times($chatid=0) {
662 /// Updates chat records so that the next chat time is correct
663     global $DB;
665     $timenow = time();
667     $params = array('timenow'=>$timenow, 'chatid'=>$chatid);
669     if ($chatid) {
670         if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
671             return;
672         }
673     } else {
674         if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
675             return;
676         }
677     }
679     foreach ($chats as $chat) {
680         switch ($chat->schedule) {
681             case 1: // Single event - turn off schedule and disable
682                     $chat->chattime = 0;
683                     $chat->schedule = 0;
684                     break;
685             case 2: // Repeat daily
686                     while ($chat->chattime <= $timenow) {
687                         $chat->chattime += 24 * 3600;
688                     }
689                     break;
690             case 3: // Repeat weekly
691                     while ($chat->chattime <= $timenow) {
692                         $chat->chattime += 7 * 24 * 3600;
693                     }
694                     break;
695         }
696         $DB->update_record("chat", $chat);
698         $event = new stdClass();           // Update calendar too
700         $cond = "modulename='chat' AND instance = :chatid AND timestart <> :chattime";
701         $params = array('chattime'=>$chat->chattime, 'chatid'=>$chatid);
703         if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
704             $event->timestart   = $chat->chattime;
705             $calendarevent = calendar_event::load($event->id);
706             $calendarevent->update($event, false);
707         }
708     }
711 /**
712  * @global object
713  * @global object
714  * @param object $message
715  * @param int $courseid
716  * @param object $sender
717  * @param object $currentuser
718  * @param string $chat_lastrow
719  * @return bool|string Returns HTML or false
720  */
721 function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
722     global $CFG, $USER, $OUTPUT;
724     $output = new stdClass();
725     $output->beep = false;       // by default
726     $output->refreshusers = false; // by default
728     // Use get_user_timezone() to find the correct timezone for displaying this message:
729     // It's either the current user's timezone or else decided by some Moodle config setting
730     // First, "reset" $USER->timezone (which could have been set by a previous call to here)
731     // because otherwise the value for the previous $currentuser will take precedence over $CFG->timezone
732     $USER->timezone = 99;
733     $tz = get_user_timezone($currentuser->timezone);
735     // Before formatting the message time string, set $USER->timezone to the above.
736     // This will allow dst_offset_on (called by userdate) to work correctly, otherwise the
737     // message times appear off because DST is not taken into account when it should be.
738     $USER->timezone = $tz;
739     $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
741     $message->picture = $OUTPUT->user_picture($sender, array('size'=>false, 'courseid'=>$courseid, 'link'=>false));
743     if ($courseid) {
744         $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>";
745     }
747     //Calculate the row class
748     if ($chat_lastrow !== NULL) {
749         $rowclass = ' class="r'.$chat_lastrow.'" ';
750     } else {
751         $rowclass = '';
752     }
754     // Start processing the message
756     if(!empty($message->system)) {
757         // System event
758         $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
759         $output->html  = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
760         $output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
761         $output->basic = '<dl><dt class="event">'.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'</dt></dl>';
763         if($message->message == 'exit' or $message->message == 'enter') {
764             $output->refreshusers = true; //force user panel refresh ASAP
765         }
766         return $output;
767     }
769     // It's not a system event
771     $text = $message->message;
773     /// Parse the text to clean and filter it
775     $options = new stdClass();
776     $options->para = false;
777     $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
779     // And now check for special cases
780     $special = false;
782     if (substr($text, 0, 5) == 'beep ') {
783         /// It's a beep!
784         $special = true;
785         $beepwho = trim(substr($text, 5));
787         if ($beepwho == 'all') {   // everyone
788             $outinfo = $message->strtime.': '.get_string('messagebeepseveryone', 'chat', fullname($sender));
789             $outmain = '';
790             $output->beep = true;  // (eventually this should be set to
791                                    //  to a filename uploaded by the user)
793         } else if ($beepwho == $currentuser->id) {  // current user
794             $outinfo = $message->strtime.': '.get_string('messagebeepsyou', 'chat', fullname($sender));
795             $outmain = '';
796             $output->beep = true;
798         } else {  //something is not caught?
799             return false;
800         }
801     } else if (substr($text, 0, 1) == '/') {     /// It's a user command
802         // support some IRC commands
803         $pattern = '#(^\/)(\w+).*#';
804         preg_match($pattern, trim($text), $matches);
805         $command = $matches[2];
806         switch ($command){
807         case 'me':
808             $special = true;
809             $outinfo = $message->strtime;
810             $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
811             break;
812         }
813     } elseif (substr($text, 0, 2) == 'To') {
814         $pattern = '#To[[:space:]](.*):(.*)#';
815         preg_match($pattern, trim($text), $matches);
816         $special = true;
817         $outinfo = $message->strtime;
818         $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
819     }
821     if(!$special) {
822         $outinfo = $message->strtime.' '.$sender->firstname;
823         $outmain = $text;
824     }
826     /// Format the message as a small table
828     $output->text  = strip_tags($outinfo.': '.$outmain);
830     $output->html  = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
831     $output->html .= "<span class=\"title\">$outinfo</span>";
832     if ($outmain) {
833         $output->html .= ": $outmain";
834         $output->basic = '<dl><dt class="title">'.$outinfo.':</dt><dd class="text">'.$outmain.'</dd></dl>';
835     } else {
836         $output->basic = '<dl><dt class="title">'.$outinfo.'</dt></dl>';
837     }
838     $output->html .= "</td></tr></table>";
839     return $output;
842 /**
843  * @global object
844  * @param object $message
845  * @param int $courseid
846  * @param object $currentuser
847  * @param string $chat_lastrow
848  * @return bool|string Returns HTML or false
849  */
850 function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NULL) {
851 /// Given a message object full of information, this function
852 /// formats it appropriately into text and html, then
853 /// returns the formatted data.
854     global $DB;
856     static $users;     // Cache user lookups
858     if (isset($users[$message->userid])) {
859         $user = $users[$message->userid];
860     } else if ($user = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
861         $users[$message->userid] = $user;
862     } else {
863         return NULL;
864     }
865     return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
868 /**
869  * @global object
870  * @param object $message message to be displayed.
871  * @param mixed $chatuser user chat data
872  * @param object $currentuser current user for whom the message should be displayed.
873  * @param int $groupingid course module grouping id
874  * @param string $theme name of the chat theme.
875  * @return bool|string Returns HTML or false
876  */
877 function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
878     global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
879     require_once($CFG->dirroot.'/mod/chat/locallib.php');
881     static $users;     // Cache user lookups
883     $result = new stdClass();
885     if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
886         include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
887     }
889     if (isset($users[$message->userid])) {
890         $sender = $users[$message->userid];
891     } else if ($sender = $DB->get_record('user', array('id'=>$message->userid), user_picture::fields())) {
892         $users[$message->userid] = $sender;
893     } else {
894         return NULL;
895     }
897     $USER->timezone = 99;
898     $tz = get_user_timezone($currentuser->timezone);
899     $USER->timezone = $tz;
901     if (empty($chatuser->course)) {
902         $courseid = $COURSE->id;
903     } else {
904         $courseid = $chatuser->course;
905     }
907     $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
908     $message->picture = $OUTPUT->user_picture($sender, array('courseid'=>$courseid));
910     $message->picture = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
912     // Start processing the message
913     if(!empty($message->system)) {
914         $result->type = 'system';
916         $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
917         $event = get_string('message'.$message->message, 'chat', fullname($sender));
918         $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
920         $output = $PAGE->get_renderer('mod_chat');
921         $result->html = $output->render($eventmessage);
923         return $result;
924     }
926     // It's not a system event
927     $text = $message->message;
929     /// Parse the text to clean and filter it
930     $options = new stdClass();
931     $options->para = false;
932     $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
934     // And now check for special cases
935     $special = false;
936     $outtime = $message->strtime;
938     //Initilise output variable.
939     $outmain = '';
941     if (substr($text, 0, 5) == 'beep ') {
942         $special = true;
943         /// It's a beep!
944         $result->type = 'beep';
945         $beepwho = trim(substr($text, 5));
947         if ($beepwho == 'all') {   // everyone
948             $outmain =  get_string('messagebeepseveryone', 'chat', fullname($sender));
949         } else if ($beepwho == $currentuser->id) {  // current user
950             $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
951         } else if ($sender->id == $currentuser->id) {  //something is not caught?
952             //allow beep for a active chat user only, else user can beep anyone and get fullname
953             if (!empty($chatuser) && is_numeric($beepwho)) {
954                $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
955                if (array_key_exists($beepwho, $chatusers)) {
956                    $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
957                } else {
958                    $outmain = get_string('messageyoubeep', 'chat', $beepwho);
959                }
960             } else {
961                 $outmain = get_string('messageyoubeep', 'chat', $beepwho);
962             }
963         }
964     } else if (substr($text, 0, 1) == '/') {     /// It's a user command
965         $special = true;
966         $result->type = 'command';
967         // support some IRC commands
968         $pattern = '#(^\/)(\w+).*#';
969         preg_match($pattern, trim($text), $matches);
970         $command = $matches[2];
971         $special = true;
972         switch ($command){
973         case 'me':
974             $outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
975             break;
976         }
977     } elseif (substr($text, 0, 2) == 'To') {
978         $special = true;
979         $result->type = 'dialogue';
980         $pattern = '#To[[:space:]](.*):(.*)#';
981         preg_match($pattern, trim($text), $matches);
982         $special = true;
983         $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
984     }
986     if(!$special) {
987         $outmain = $text;
988     }
990     $result->text = strip_tags($outtime.': '.$outmain);
992     $mymessageclass = '';
993     if ($sender->id == $USER->id) {
994         $mymessageclass = 'chat-message-mymessage';
995     }
997     $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
998     $usermessage = new user_message($senderprofile, fullname($sender), $message->picture, $mymessageclass, $outtime, $outmain, $theme);
1000     $output = $PAGE->get_renderer('mod_chat');
1001     $result->html = $output->render($usermessage);
1003     //When user beeps other user, then don't show any timestamp to other users in chat.
1004     if (('' === $outmain) && $special) {
1005         return false;
1006     } else {
1007         return $result;
1008     }
1012 /**
1013  * @global object $DB
1014  * @global object $CFG
1015  * @global object $COURSE
1016  * @global object $OUTPUT
1017  * @param object $users
1018  * @param object $course
1019  * @return array return formatted user list
1020  */
1021 function chat_format_userlist($users, $course) {
1022     global $CFG, $DB, $COURSE, $OUTPUT;
1023     $result = array();
1024     foreach($users as $user){
1025         $item = array();
1026         $item['name'] = fullname($user);
1027         $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id;
1028         $item['picture'] = $OUTPUT->user_picture($user);
1029         $item['id'] = $user->id;
1030         $result[] = $item;
1031     }
1032     return $result;
1035 /**
1036  * Print json format error
1037  * @param string $level
1038  * @param string $msg
1039  */
1040 function chat_print_error($level, $msg) {
1041     header('Content-Length: ' . ob_get_length() );
1042     $error = new stdClass();
1043     $error->level = $level;
1044     $error->msg   = $msg;
1045     $response['error'] = $error;
1046     echo json_encode($response);
1047     ob_end_flush();
1048     exit;
1051 /**
1052  * @return array
1053  */
1054 function chat_get_view_actions() {
1055     return array('view','view all','report');
1058 /**
1059  * @return array
1060  */
1061 function chat_get_post_actions() {
1062     return array('talk');
1065 /**
1066  * @global object
1067  * @global object
1068  * @param array $courses
1069  * @param array $htmlarray Passed by reference
1070  */
1071 function chat_print_overview($courses, &$htmlarray) {
1072     global $USER, $CFG;
1074     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1075         return array();
1076     }
1078     if (!$chats = get_all_instances_in_courses('chat',$courses)) {
1079         return;
1080     }
1082     $strchat = get_string('modulename', 'chat');
1083     $strnextsession  = get_string('nextsession', 'chat');
1085     foreach ($chats as $chat) {
1086         if ($chat->chattime and $chat->schedule) {  // A chat is scheduled
1087             $str = '<div class="chat overview"><div class="name">'.
1088                    $strchat.': <a '.($chat->visible?'':' class="dimmed"').
1089                    ' href="'.$CFG->wwwroot.'/mod/chat/view.php?id='.$chat->coursemodule.'">'.
1090                    $chat->name.'</a></div>';
1091             $str .= '<div class="info">'.$strnextsession.': '.userdate($chat->chattime).'</div></div>';
1093             if (empty($htmlarray[$chat->course]['chat'])) {
1094                 $htmlarray[$chat->course]['chat'] = $str;
1095             } else {
1096                 $htmlarray[$chat->course]['chat'] .= $str;
1097             }
1098         }
1099     }
1103 /**
1104  * Implementation of the function for printing the form elements that control
1105  * whether the course reset functionality affects the chat.
1106  *
1107  * @param object $mform form passed by reference
1108  */
1109 function chat_reset_course_form_definition(&$mform) {
1110     $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1111     $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages','chat'));
1114 /**
1115  * Course reset form defaults.
1116  *
1117  * @param object $course
1118  * @return array
1119  */
1120 function chat_reset_course_form_defaults($course) {
1121     return array('reset_chat'=>1);
1124 /**
1125  * Actual implementation of the reset course functionality, delete all the
1126  * chat messages for course $data->courseid.
1127  *
1128  * @global object
1129  * @global object
1130  * @param object $data the data submitted from the reset course.
1131  * @return array status array
1132  */
1133 function chat_reset_userdata($data) {
1134     global $CFG, $DB;
1136     $componentstr = get_string('modulenameplural', 'chat');
1137     $status = array();
1139     if (!empty($data->reset_chat)) {
1140         $chatessql = "SELECT ch.id
1141                         FROM {chat} ch
1142                        WHERE ch.course=?";
1143         $params = array($data->courseid);
1145         $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1146         $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1147         $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1148         $status[] = array('component'=>$componentstr, 'item'=>get_string('removemessages', 'chat'), 'error'=>false);
1149     }
1151     /// updating dates - shift may be negative too
1152     if ($data->timeshift) {
1153         shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
1154         $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1155     }
1157     return $status;
1160 /**
1161  * Returns all other caps used in module
1162  *
1163  * @return array
1164  */
1165 function chat_get_extra_capabilities() {
1166     return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');
1170 /**
1171  * @param string $feature FEATURE_xx constant for requested feature
1172  * @return mixed True if module supports feature, null if doesn't know
1173  */
1174 function chat_supports($feature) {
1175     switch($feature) {
1176         case FEATURE_GROUPS:                  return true;
1177         case FEATURE_GROUPINGS:               return true;
1178         case FEATURE_GROUPMEMBERSONLY:        return true;
1179         case FEATURE_MOD_INTRO:               return true;
1180         case FEATURE_BACKUP_MOODLE2:          return true;
1181         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1182         case FEATURE_GRADE_HAS_GRADE:         return false;
1183         case FEATURE_GRADE_OUTCOMES:          return true;
1184         case FEATURE_SHOW_DESCRIPTION:        return true;
1186         default: return null;
1187     }
1190 function chat_extend_navigation($navigation, $course, $module, $cm) {
1191     global $CFG, $USER, $PAGE, $OUTPUT;
1193     $currentgroup = groups_get_activity_group($cm, true);
1195     if (has_capability('mod/chat:chat', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1196         $strenterchat    = get_string('enterchat', 'chat');
1198         $target = $CFG->wwwroot.'/mod/chat/';
1199         $params = array('id'=>$cm->instance);
1201         if ($currentgroup) {
1202             $params['groupid'] = $currentgroup;
1203         }
1205         $links = array();
1207         // If user is using screenreader, display gui_basic gui link only
1208         if (empty($USER->screenreader)) {
1209             $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
1210             $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1211             $links[] = new action_link($url, $strenterchat, $action);
1212         }
1214         $url = new moodle_url($target.'gui_basic/index.php', $params);
1215         $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup, array('height' => 500, 'width' => 700));
1216         $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1218         foreach ($links as $link) {
1219             $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null ,null, new pix_icon('c/group' , ''));
1220         }
1221     }
1223     $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
1224     if (is_array($chatusers) && count($chatusers)>0) {
1225         $users = $navigation->add(get_string('currentusers', 'chat'));
1226         foreach ($chatusers as $chatuser) {
1227             $userlink = new moodle_url('/user/view.php', array('id'=>$chatuser->id,'course'=>$course->id));
1228             $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping), $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('c/user', ''));
1229         }
1230     }
1233 /**
1234  * Adds module specific settings to the settings block
1235  *
1236  * @param settings_navigation $settings The settings navigation object
1237  * @param navigation_node $chatnode The node to add module settings to
1238  */
1239 function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
1240     global $DB, $PAGE, $USER;
1241     $chat = $DB->get_record("chat", array("id" => $PAGE->cm->instance));
1243     if ($chat->chattime && $chat->schedule) {
1244         $nextsessionnode = $chatnode->add(get_string('nextsession', 'chat').': '.userdate($chat->chattime).' ('.usertimezone($USER->timezone));
1245         $nextsessionnode->add_class('note');
1246     }
1248     $currentgroup = groups_get_activity_group($PAGE->cm, true);
1249     if ($currentgroup) {
1250         $groupselect = " AND groupid = '$currentgroup'";
1251     } else {
1252         $groupselect = '';
1253     }
1255     if ($chat->studentlogs || has_capability('mod/chat:readlog',$PAGE->cm->context)) {
1256         if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
1257             $chatnode->add(get_string('viewreport', 'chat'), new moodle_url('/mod/chat/report.php', array('id'=>$PAGE->cm->id)));
1258         }
1259     }
1262 /**
1263  * user logout event handler
1264  *
1265  * @param object $user full $USER object
1266  */
1267 function chat_user_logout($user) {
1268     global $DB;
1269     $DB->delete_records('chat_users', array('userid'=>$user->id));
1272 /**
1273  * Return a list of page types
1274  * @param string $pagetype current page type
1275  * @param stdClass $parentcontext Block's parent context
1276  * @param stdClass $currentcontext Current context of block
1277  */
1278 function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1279     $module_pagetype = array('mod-chat-*'=>get_string('page-mod-chat-x', 'chat'));
1280     return $module_pagetype;