9a98185f9708fa8cf9a6d42c78f81985ef2bd73a
[moodle.git] / mod / chat / gui_header_js / jsupdated.php
1 <?php
3 /** jsupdated.php - notes by Martin Langhoff <martin@catalyst.net.nz>
4  **
5  ** This is an alternative version of jsupdate.php that acts
6  ** as a long-running daemon. It will feed/stall/feed JS updates
7  ** to the client. From the module configuration select "Stream"
8  ** updates.
9  **
10  ** The client connection is not forever though. Once we reach
11  ** CHAT_MAX_CLIENT_UPDATES, it will force the client to re-fetch it.
12  **
13  ** This buys us all the benefits that chatd has, minus the setup,
14  ** as we are using apache to do the daemon handling.
15  **
16  **/
19 define('CHAT_MAX_CLIENT_UPDATES', 1000);
20 define('NO_MOODLE_COOKIES', true); // session not used here
21 define('NO_OUTPUT_BUFFERING', true);
23 require('../../../config.php');
24 require('../lib.php');
26 // we are going to run for a long time
27 // avoid being terminated by php
28 @set_time_limit(0);
30 $chat_sid      = required_param('chat_sid',          PARAM_ALPHANUM);
31 $chat_lasttime = optional_param('chat_lasttime',  0, PARAM_INT);
32 $chat_lastrow  = optional_param('chat_lastrow',   1, PARAM_INT);
33 $chat_lastid   = optional_param('chat_lastid',    0, PARAM_INT);
35 $url = new moodle_url('/mod/chat/gui_header_js/jsupdated.php', array('chat_sid'=>$chat_sid));
36 if ($chat_lasttime !== 0) {
37     $url->param('chat_lasttime', $chat_lasttime);
38 }
39 if ($chat_lastrow !== 1) {
40     $url->param('chat_lastrow', $chat_lastrow);
41 }
42 if ($chat_lastid !== 1) {
43     $url->param('chat_lastid', $chat_lastid);
44 }
45 $PAGE->set_url($url);
47 if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) {
48     print_error('notlogged', 'chat');
49 }
51 //Get the minimal course
52 if (!$course = $DB->get_record('course', array('id'=>$chatuser->course))) {
53     print_error('invalidcourseid');
54 }
56 //Get the user theme and enough info to be used in chat_format_message() which passes it along to
57 // chat_format_message_manually() -- and only id and timezone are used.
58 if (!$USER = $DB->get_record('user', array('id'=>$chatuser->userid))) { // no optimisation here, it would break again in future!
59     print_error('invaliduser');
60 }
61 $USER->description = '';
63 //Setup course, lang and theme
64 $PAGE->set_course($course);
66 // force deleting of timed out users if there is a silence in room or just entering
67 if ((time() - $chat_lasttime) > $CFG->chat_old_ping) {
68     // must be done before chat_get_latest_message!!!
69     chat_delete_old_users();
70 }
72 //
73 // Time to send headers, and lay out the basic JS updater page
74 //
75 header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
76 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
77 header('Cache-Control: no-cache, must-revalidate');
78 header('Pragma: no-cache');
79 header('Content-Type: text/html; charset=utf-8');
81 /// required stylesheets
82 $stylesheetshtml = '';
83 /*foreach ($CFG->stylesheets as $stylesheet) {
84     //TODO: MDL-21120
85     $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />';
86 }*/
88 $refreshurl = "{$CFG->wwwroot}/mod/chat/gui_header_js/jsupdated.php?chat_sid=$chat_sid&chat_lasttime=$chat_lasttime&chat_lastrow=$chat_newrow&chat_lastid=$chat_lastid";
89 ?>
90 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
91 <html>
92     <head>
93         <meta http-equiv="content-type" content="text/html; charset=utf-8" />
94         <script type="text/javascript">
95         //<![CDATA[
96         function safari_refresh() {
97             self.location.href= '<?php echo $refreshurl;?>';
98         }
99         var issafari = false;
100         if(window.devicePixelRatio){
101             issafari = true;
102             setTimeout('safari_refresh()', <?php echo $CFG->chat_refresh_room*1000;?>);
103         }
104         if (parent.msg.document.getElementById("msgStarted") == null) {
105             parent.msg.document.close();
106             parent.msg.document.open("text/html","replace");
107             parent.msg.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
108             parent.msg.document.write("<html><head>");
109             parent.msg.document.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />");
110             parent.msg.document.write("<base target=\"_blank\" />");
111             parent.msg.document.write("<?php echo addslashes_js($stylesheetshtml) ?>");
112             parent.msg.document.write("</head><body class=\"mod-chat-gui_header_js course-<?php echo $chatuser->course ?>\" id=\"mod-chat-gui_header_js-jsupdate\"><div style=\"display: none\" id=\"msgStarted\">&nbsp;</div>");
113         }
114         //]]>
115         </script>
116     </head>
117     <body>
119 <?php
121     // Ensure the HTML head makes it out there
122     echo $CHAT_DUMMY_DATA;
124     for ($n=0; $n <= CHAT_MAX_CLIENT_UPDATES; $n++) {
126         // ping first so we can later shortcut as needed.
127         $chatuser->lastping = time();
128         $DB->set_field('chat_users', 'lastping', $chatuser->lastping, array('id'=>$chatuser->id));
130         if ($message = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
131             $chat_newlasttime = $message->timestamp;
132             $chat_newlastid   = $message->id;
133         } else {
134             $chat_newlasttime = 0;
135             $chat_newlastid   = 0;
136             print " \n";
137             print $CHAT_DUMMY_DATA;
138             sleep($CFG->chat_refresh_room);
139             continue;
140         }
142         $timenow    = time();
144         $params = array('groupid'=>$chatuser->groupid, 'lastid'=>$chat_lastid, 'lasttime'=>$chat_lasttime, 'chatid'=>$chatuser->chatid);
145         $groupselect = $chatuser->groupid ? " AND (groupid=:groupid OR groupid=0) " : "";
147         $newcriteria = '';
148         if ($chat_lastid > 0) {
149             $newcriteria = "id > :lastid";
150         } else {
151             if ($chat_lasttime == 0) { //display some previous messages
152                 $chat_lasttime = $timenow - $CFG->chat_old_ping; //TO DO - any better value??
153             }
154             $newcriteria = "timestamp > :lasttime";
155         }
157         $messages = $DB->get_records_select("chat_messages_current",
158                                        "chatid = :chatid AND $newcriteria $groupselect", $params,
159                                        "timestamp ASC");
161         if ($messages) {
162             $num = count($messages);
163         } else {
164             print " \n";
165             print $CHAT_DUMMY_DATA;
166             sleep($CFG->chat_refresh_room);
167             continue;
168             $num = 0;
169         }
171         print '<script type="text/javascript">' . "\n";
172         print "//<![CDATA[\n\n";
174         $chat_newrow = ($chat_lastrow + $num) % 2;
176         $refreshusers = false;
177         $us = array ();
178         if (($chat_lasttime != $chat_newlasttime) and $messages) {
180             $beep         = false;
181             $refreshusers = false;
182             foreach ($messages as $message) {
183                 $chat_lastrow = ($chat_lastrow + 1) % 2;
184                 $formatmessage = chat_format_message($message, $chatuser->course, $USER, $chat_lastrow);
185                 if ($formatmessage->beep) {
186                     $beep = true;
187                 }
188                 if ($formatmessage->refreshusers) {
189                     $refreshusers = true;
190                 }
191                 $us[$message->userid] = $timenow - $message->timestamp;
192                 echo "parent.msg.document.write('".addslashes_js($formatmessage->html )."\\n');\n";
194             }
195             // from the last message printed...
196             // a strange case where lack of closures is useful!
197             $chat_lasttime = $message->timestamp;
198             $chat_lastid   = $message->id;
199         }
201         if ($refreshusers) {
202             echo "if (parent.users.document.anchors[0] != null) {" .
203                 "parent.users.location.href = parent.users.document.anchors[0].href;}\n";
204         } else {
205             foreach($us as $uid=>$lastping) {
206                 $min = (int) ($lastping/60);
207                 $sec = $lastping - ($min*60);
208                 $min = $min < 10 ? '0'.$min : $min;
209                 $sec = $sec < 10 ? '0'.$sec : $sec;
210                 $idle = $min.':'.$sec;
211                 echo "if (parent.users.document.getElementById('uidle{$uid}') != null) {".
212                         "parent.users.document.getElementById('uidle{$uid}').innerHTML = '$idle';}\n";
213             }
214         }
216         print <<<EOD
217         if(parent.input){
218             var autoscroll = parent.input.document.getElementById('auto');
219             if(parent.msg && autoscroll && autoscroll.checked){
220                 parent.msg.scroll(1,5000000);
221             }
222         }
223 EOD;
224         print "//]]>\n";
225         print '</script>' . "\n\n";
226         if ($beep) {
227             print '<embed src="../beep.wav" autostart="true" hidden="true" name="beep" />';
228         }
229         print $CHAT_DUMMY_DATA;
230         sleep($CFG->chat_refresh_room);
231     } // here ends the for() loop
233     // here & should be written & :-D
234     $refreshurl = "{$CFG->wwwroot}/mod/chat/gui_header_js/jsupdated.php?chat_sid=$chat_sid&chat_lasttime=$chat_lasttime&chat_lastrow=$chat_newrow&chat_lastid=$chat_lastid";
235     print '<script type="text/javascript">' . "\n";
236     print "//<![CDATA[ \n\n";
237     print "location.href = '$refreshurl';\n";
238     print "//]]>\n";
239     print '</script>' . "\n\n";
241 ?>
243     </body>
244 </html>