MDL-20700 coding style cleanup - cvs keywords removed, closign php tag removed, trail...
[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
22 require('../../../config.php');
23 require('../lib.php');
25 // we are going to run for a long time
26 // avoid being terminated by php
27 @set_time_limit(0);
29 $chat_sid      = required_param('chat_sid',          PARAM_ALPHANUM);
30 $chat_lasttime = optional_param('chat_lasttime',  0, PARAM_INT);
31 $chat_lastrow  = optional_param('chat_lastrow',   1, PARAM_INT);
32 $chat_lastid   = optional_param('chat_lastid',    0, PARAM_INT);
34 $url = new moodle_url($CFG->wwwroot.'/mod/chat/gui_header_js/jsupdated.php', array('chat_sid'=>$chat_sid));
35 if ($chat_lasttime !== 0) {
36     $url->param('chat_lasttime', $chat_lasttime);
37 }
38 if ($chat_lastrow !== 1) {
39     $url->param('chat_lastrow', $chat_lastrow);
40 }
41 if ($chat_lastid !== 1) {
42     $url->param('chat_lastid', $chat_lastid);
43 }
44 $PAGE->set_url($url);
46 if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) {
47     print_error('notlogged', 'chat');
48 }
50 //Get the minimal course
51 if (!$course = $DB->get_record('course', array('id'=>$chatuser->course))) {
52     print_error('invalidcourseid');
53 }
55 //Get the user theme and enough info to be used in chat_format_message() which passes it along to
56 // chat_format_message_manually() -- and only id and timezone are used.
57 if (!$USER = $DB->get_record('user', array('id'=>$chatuser->userid))) { // no optimisation here, it would break again in future!
58     print_error('invaliduser');
59 }
60 $USER->description = '';
62 //Setup course, lang and theme
63 $PAGE->set_course($course);
65 // force deleting of timed out users if there is a silence in room or just entering
66 if ((time() - $chat_lasttime) > $CFG->chat_old_ping) {
67     // must be done before chat_get_latest_message!!!
68     chat_delete_old_users();
69 }
71 //
72 // Time to send headers, and lay out the basic JS updater page
73 //
74 header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
75 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
76 header('Cache-Control: no-cache, must-revalidate');
77 header('Pragma: no-cache');
78 header('Content-Type: text/html; charset=utf-8');
80 /// required stylesheets
81 $stylesheetshtml = '';
82 foreach ($CFG->stylesheets as $stylesheet) {
83     $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />';
84 }
86 ?>
87 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
88 <html>
89     <head>
90         <meta http-equiv="content-type" content="text/html; charset=utf-8" />
91         <script type="text/javascript">
92         //<![CDATA[
93         function safari_refresh() {
94             self.location.href= '<?php echo $refreshurl;?>';
95         }
96         var issafari = false;
97         if(window.devicePixelRatio){
98             issafari = true;
99             setTimeout('safari_refresh()', <?php echo $CFG->chat_refresh_room*1000;?>);
100         }
101         if (parent.msg.document.getElementById("msgStarted") == null) {
102             parent.msg.document.close();
103             parent.msg.document.open("text/html","replace");
104             parent.msg.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
105             parent.msg.document.write("<html><head>");
106             parent.msg.document.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />");
107             parent.msg.document.write("<base target=\"_blank\" />");
108             parent.msg.document.write("<?php echo addslashes_js($stylesheetshtml) ?>");
109             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>");
110         }
111         //]]>
112         </script>
113    </head>
114    <body>
116 <?php
118     // Ensure the HTML head makes it out there
119     echo $CHAT_DUMMY_DATA;
120     @ob_end_flush();
122     for ($n=0; $n <= CHAT_MAX_CLIENT_UPDATES; $n++) {
124         // ping first so we can later shortcut as needed.
125         $chatuser->lastping = time();
126         $DB->set_field('chat_users', 'lastping', $chatuser->lastping, array('id'=>$chatuser->id));
128         if ($message = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
129             $chat_newlasttime = $message->timestamp;
130             $chat_newlastid   = $message->id;
131         } else {
132             $chat_newlasttime = 0;
133             $chat_newlastid   = 0;
134             print " \n";
135             print $CHAT_DUMMY_DATA;
136             @ob_end_flush();
137             sleep($CFG->chat_refresh_room);
138             continue;
139         }
141         $timenow    = time();
143         $params = array('groupid'=>$chatuser->groupid, 'lastid'=>$chat_lastid, 'lasttime'=>$chat_lasttime, 'chatid'=>$chatuser->chatid);
144         $groupselect = $chatuser->groupid ? " AND (groupid=:groupid OR groupid=0) " : "";
146         $newcriteria = '';
147         if ($chat_lastid > 0) {
148             $newcriteria = "id > :lastid";
149         } else {
150             if ($chat_lasttime == 0) { //display some previous messages
151                 $chat_lasttime = $timenow - $CFG->chat_old_ping; //TO DO - any better value??
152             }
153             $newcriteria = "timestamp > :lasttime";
154         }
156         $messages = $DB->get_records_select("chat_messages_current",
157                                        "chatid = :chatid AND $newcriteria $groupselect", $params,
158                                        "timestamp ASC");
160         if ($messages) {
161             $num = count($messages);
162         } else {
163             print " \n";
164             print $CHAT_DUMMY_DATA;
165             @ob_end_flush();
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         @ob_end_flush();
231         sleep($CFG->chat_refresh_room);
232     } // here ends the for() loop
234     // here & should be written & :-D
235     $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";
236     print '<script type="text/javascript">' . "\n";
237     print "//<![CDATA[ \n\n";
238     print "location.href = '$refreshurl';\n";
239     print "//]]>\n";
240     print '</script>' . "\n\n";
242 ?>
244     </body>
245 </html>