MDL-34068 mod_chat Sending text/html headers when sending the messages frame output...
[moodle.git] / mod / chat / chatd.php
1 #!/usr/bin/php -q
2 <?php
4 // Browser quirks
5 define('QUIRK_CHUNK_UPDATE', 0x0001);
7 // Connection telltale
8 define('CHAT_CONNECTION',           0x10);
9 // Connections: Incrementing sequence, 0x10 to 0x1f
10 define('CHAT_CONNECTION_CHANNEL',   0x11);
12 // Sidekick telltale
13 define('CHAT_SIDEKICK',             0x20);
14 // Sidekicks: Incrementing sequence, 0x21 to 0x2f
15 define('CHAT_SIDEKICK_USERS',       0x21);
16 define('CHAT_SIDEKICK_MESSAGE',     0x22);
17 define('CHAT_SIDEKICK_BEEP',        0x23);
19 $phpversion = phpversion();
20 echo 'Moodle chat daemon v1.0 on PHP '.$phpversion."\n\n";
22 /// Set up all the variables we need   /////////////////////////////////////
24 /// $CFG variables are now defined in database by chat/lib.php
26 $_SERVER['PHP_SELF']        = 'dummy';
27 $_SERVER['SERVER_NAME']     = 'dummy';
28 $_SERVER['HTTP_USER_AGENT'] = 'dummy';
30 define('NO_MOODLE_COOKIES', true); // session not used here
32 include('../../config.php');
33 include('lib.php');
35 $_SERVER['SERVER_NAME'] = $CFG->chat_serverhost;
36 $_SERVER['PHP_SELF']    = "http://$CFG->chat_serverhost:$CFG->chat_serverport/mod/chat/chatd.php";
38 $safemode = ini_get('safe_mode');
40 if($phpversion < '4.3') {
41     die("Error: The Moodle chat daemon requires at least PHP version 4.3 to run.\n       Since your version is $phpversion, you have to upgrade.\n\n");
42 }
43 if(!empty($safemode)) {
44     die("Error: Cannot run with PHP safe_mode = On. Turn off safe_mode in php.ini.\n");
45 }
47 $passref = ini_get('allow_call_time_pass_reference');
48 if(empty($passref)) {
49     die("Error: Cannot run with PHP allow_call_time_pass_reference = Off. Turn on allow_call_time_pass_reference in php.ini.\n");
50 }
52 @set_time_limit (0);
53 set_magic_quotes_runtime(0);
54 error_reporting(E_ALL);
56 function chat_empty_connection() {
57     return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL);
58 }
60 class ChatConnection {
61     // Chat-related info
62     var $sid    = NULL;
63     var $type   = NULL;
64     //var $groupid        = NULL;
66     // PHP-level info
67     var $handle = NULL;
69     // TCP/IP
70     var $ip     = NULL;
71     var $port   = NULL;
73     function ChatConnection($resource) {
74         $this->handle = $resource;
75         @socket_getpeername($this->handle, $this->ip, $this->port);
76     }
77 }
79 class ChatDaemon {
80     var $_resetsocket       = false;
81     var $_readytogo         = false;
82     var $_logfile           = false;
83     var $_trace_to_console  = true;
84     var $_trace_to_stdout   = true;
85     var $_logfile_name      = 'chatd.log';
86     var $_last_idle_poll    = 0;
88     var $conn_ufo  = array();    // Connections not identified yet
89     var $conn_side = array();    // Sessions with sidekicks waiting for the main connection to be processed
90     var $conn_half = array();    // Sessions that have valid connections but not all of them
91     var $conn_sets = array();    // Sessions with complete connection sets sets
92     var $sets_info = array();    // Keyed by sessionid exactly like conn_sets, one of these for each of those
93     var $chatrooms = array();    // Keyed by chatid, holding arrays of data
95     // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized!
96     //            Pay extra attention when you write code that affects any of them!
98     function ChatDaemon() {
99         $this->_trace_level         = E_ALL ^ E_USER_NOTICE;
100         $this->_pcntl_exists        = function_exists('pcntl_fork');
101         $this->_time_rest_socket    = 20;
102         $this->_beepsoundsrc        = $GLOBALS['CFG']->wwwroot.'/mod/chat/beep.wav';
103         $this->_freq_update_records = 20;
104         $this->_freq_poll_idle_chat = $GLOBALS['CFG']->chat_old_ping;
105         $this->_stdout = fopen('php://stdout', 'w');
106         if($this->_stdout) {
107             // Avoid double traces for everything
108             $this->_trace_to_console = false;
109         }
110     }
112     function error_handler ($errno, $errmsg, $filename, $linenum, $vars) {
113         // Checks if an error needs to be suppressed due to @
114         if(error_reporting() != 0) {
115             $this->trace($errmsg.' on line '.$linenum, $errno);
116         }
117         return true;
118     }
120     function poll_idle_chats($now) {
121         $this->trace('Polling chats to detect disconnected users');
122         if(!empty($this->chatrooms)) {
123             foreach($this->chatrooms as $chatid => $chatroom) {
124                 if(!empty($chatroom['users'])) {
125                     foreach($chatroom['users'] as $sessionid => $userid) {
126                         // We will be polling each user as required
127                         $this->trace('...shall we poll '.$sessionid.'?');
128                         if($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) {
129                             $this->trace('YES!');
130                             // This user hasn't been polled since his last message
131                             if($this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<!-- poll -->') === false) {
132                                 // User appears to have disconnected
133                                 $this->disconnect_session($sessionid);
134                             }
135                         }
136                     }
137                 }
138             }
139         }
140         $this->_last_idle_poll = $now;
141     }
143     function query_start() {
144         return $this->_readytogo;
145     }
147     function trace($message, $level = E_USER_NOTICE) {
148         $severity = '';
150         switch($level) {
151             case E_USER_WARNING: $severity = '*IMPORTANT* '; break;
152             case E_USER_ERROR:   $severity = ' *CRITICAL* '; break;
153             case E_NOTICE:
154             case E_WARNING:      $severity = ' *CRITICAL* [php] '; break;
155         }
157         $date = date('[Y-m-d H:i:s] ');
158         $message = $date.$severity.$message."\n";
160         if ($this->_trace_level & $level) {
161             // It is accepted for output
163             // Error-class traces go to STDERR too
164             if($level & E_USER_ERROR) {
165                 fwrite(STDERR, $message);
166             }
168             // Emit the message to wherever we should
169             if($this->_trace_to_stdout) {
170                 fwrite($this->_stdout, $message);
171                 fflush($this->_stdout);
172             }
173             if($this->_trace_to_console) {
174                 echo $message;
175                 flush();
176             }
177             if($this->_logfile) {
178                 fwrite($this->_logfile, $message);
179                 fflush($this->_logfile);
180             }
181         }
182     }
184     function write_data($connection, $text) {
185         $written = @socket_write($connection, $text, strlen($text));
186         if($written === false) {
187             // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)));
188             return false;
189         }
190         return true;
192         // Enclosing the above code inside this blocks makes sure that
193         // "a socket write operation will not block". I 'm not so sure
194         // if this is needed, as we have a nonblocking socket anyway.
195         // If trouble starts to creep up, we 'll restore this.
196 //        $check_socket = array($connection);
197 //        $socket_changed = socket_select($read = NULL, $check_socket, $except = NULL, 0, 0);
198 //        if($socket_changed > 0) {
199 //
200 //            // ABOVE CODE GOES HERE
201 //
202 //        }
203 //        return false;
204     }
206     function user_lazy_update($sessionid) {
207         global $DB;
209         // TODO: this can and should be written as a single UPDATE query
210         if(empty($this->sets_info[$sessionid])) {
211             $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING);
212             return false;
213         }
215         $now = time();
217         // We 'll be cheating a little, and NOT updating the record data as
218         // often as we can, so that we save on DB queries (imagine MANY users)
219         if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) {
220             // commit to permanent storage
221             $this->sets_info[$sessionid]['lastinfocommit'] = $now;
222             $DB->update_record('chat_users', $this->sets_info[$sessionid]['chatuser']);
223         }
224         return true;
225     }
227     function get_user_window($sessionid) {
228         global $CFG, $PAGE, $OUTPUT;
230         static $str;
232         $info = &$this->sets_info[$sessionid];
233         $PAGE->set_course($info['course']);
235         $timenow = time();
237         if (empty($str)) {
238             $str->idle  = get_string("idle", "chat");
239             $str->beep  = get_string("beep", "chat");
240             $str->day   = get_string("day");
241             $str->days  = get_string("days");
242             $str->hour  = get_string("hour");
243             $str->hours = get_string("hours");
244             $str->min   = get_string("min");
245             $str->mins  = get_string("mins");
246             $str->sec   = get_string("sec");
247             $str->secs  = get_string("secs");
248             $str->years = get_string('years');
249         }
251         ob_start();
252         $refresh_inval = $CFG->chat_refresh_userlist * 1000;
253         echo <<<EOD
254         <html><head>
255         <meta http-equiv="refresh" content="$refresh_inval">
256         <style type="text/css"> img{border:0} </style>
257         <script type="text/javascript">
258         //<![CDATA[
259         function openpopup(url,name,options,fullscreen) {
260             fullurl = "$CFG->wwwroot" + url;
261             windowobj = window.open(fullurl,name,options);
262             if (fullscreen) {
263                 windowobj.moveTo(0,0);
264                 windowobj.resizeTo(screen.availWidth,screen.availHeight);
265             }
266             windowobj.focus();
267             return false;
268         }
269         //]]>
270         </script></head><body><table><tbody>
271 EOD;
273         // Get the users from that chatroom
274         $users = $this->chatrooms[$info['chatid']]['users'];
276         foreach ($users as $usersessionid => $userid) {
277             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
278             $userinfo = $this->sets_info[$usersessionid];
280             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
282             echo '<tr><td width="35">';
284             $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid'];
285             $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
287             $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id);
288             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
290             echo $anchortag;
291             echo "</td><td valign=\"center\">";
292             echo "<p><font size=\"1\">";
293             echo fullname($userinfo['user'])."<br />";
294             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
295             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
296                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
297             echo "</font></p>";
298             echo "<td></tr>";
299         }
301         echo '</tbody></table>';
303         // About 2K of HTML comments to force browsers to render the HTML
304         // echo $GLOBALS['CHAT_DUMMY_DATA'];
306         echo "</body>\n</html>\n";
308         return ob_get_clean();
310     }
312     function new_ufo_id() {
313         static $id = 0;
314         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
315             $id = 0;
316         }
317         return $id;
318     }
320     function process_sidekicks($sessionid) {
321         if(empty($this->conn_side[$sessionid])) {
322             return true;
323         }
324         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
325             // TODO: is this late-dispatch working correctly?
326             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
327             unset($this->conn_side[$sessionid][$sideid]);
328         }
329         return true;
330     }
332     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
333         global $CFG, $DB;
335         switch($type) {
336             case CHAT_SIDEKICK_BEEP:
337                 // Incoming beep
338                 $msg = New stdClass;
339                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
340                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
341                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
342                 $msg->system    = 0;
343                 $msg->message   = 'beep '.$customdata['beep'];
344                 $msg->timestamp = time();
346                 // Commit to DB
347                 $DB->insert_record('chat_messages', $msg, false);
348                 $DB->insert_record('chat_messages_current', $msg, false);
350                 // OK, now push it out to all users
351                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
353                 // Update that user's lastmessageping
354                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
355                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
356                 $this->user_lazy_update($sessionid);
358                 // We did our work, but before slamming the door on the poor browser
359                 // show the courtesy of responding to the HTTP request. Otherwise, some
360                 // browsers decide to get vengeance by flooding us with repeat requests.
362                 $header  = "HTTP/1.1 200 OK\n";
363                 $header .= "Connection: close\n";
364                 $header .= "Date: ".date('r')."\n";
365                 $header .= "Server: Moodle\n";
366                 $header .= "Content-Type: text/html; charset=utf-8\n";
367                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
368                 $header .= "Cache-Control: no-cache, must-revalidate\n";
369                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
370                 $header .= "\n";
372                 // That's enough headers for one lousy dummy response
373                 $this->write_data($handle, $header);
374                 // All done
375             break;
377             case CHAT_SIDEKICK_USERS:
378                 // A request to paint a user window
380                 $content = $this->get_user_window($sessionid);
382                 $header  = "HTTP/1.1 200 OK\n";
383                 $header .= "Connection: close\n";
384                 $header .= "Date: ".date('r')."\n";
385                 $header .= "Server: Moodle\n";
386                 $header .= "Content-Type: text/html; charset=utf-8\n";
387                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
388                 $header .= "Cache-Control: no-cache, must-revalidate\n";
389                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
390                 $header .= "Content-Length: ".strlen($content)."\n";
392                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
393                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
394                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
395                            "chat_sid=".$sessionid."\n";
396                 $header .= "\n";
398                 // That's enough headers for one lousy dummy response
399                 $this->trace('writing users http response to handle '.$handle);
400                 $this->write_data($handle, $header . $content);
402                 // Update that user's lastping
403                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
404                 $this->user_lazy_update($sessionid);
406             break;
408             case CHAT_SIDEKICK_MESSAGE:
409                 // Incoming message
411                 // Browser stupidity protection from duplicate messages:
412                 $messageindex = intval($customdata['index']);
414                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
415                     // We have already broadcasted that!
416                     // $this->trace('discarding message with stale index');
417                     break;
418                 }
419                 else {
420                     // Update our info
421                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
422                 }
424                 $msg = New stdClass;
425                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
426                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
427                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
428                 $msg->system    = 0;
429                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
430                 $msg->timestamp = time();
432                 if(empty($msg->message)) {
433                     // Someone just hit ENTER, send them on their way
434                     break;
435                 }
437                 // A slight hack to prevent malformed SQL inserts
438                 $origmsg = $msg->message;
439                 $msg->message = $msg->message;
441                 // Commit to DB
442                 $DB->insert_record('chat_messages', $msg, false);
443                 $DB->insert_record('chat_messages_current', $msg, false);
445                 // Undo the hack
446                 $msg->message = $origmsg;
448                 // OK, now push it out to all users
449                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
451                 // Update that user's lastmessageping
452                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
453                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
454                 $this->user_lazy_update($sessionid);
456                 // We did our work, but before slamming the door on the poor browser
457                 // show the courtesy of responding to the HTTP request. Otherwise, some
458                 // browsers decide to get vengeance by flooding us with repeat requests.
460                 $header  = "HTTP/1.1 200 OK\n";
461                 $header .= "Connection: close\n";
462                 $header .= "Date: ".date('r')."\n";
463                 $header .= "Server: Moodle\n";
464                 $header .= "Content-Type: text/html; charset=utf-8\n";
465                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
466                 $header .= "Cache-Control: no-cache, must-revalidate\n";
467                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
468                 $header .= "\n";
470                 // That's enough headers for one lousy dummy response
471                 $this->write_data($handle, $header);
473                 // All done
474             break;
475         }
477         socket_shutdown($handle);
478         socket_close($handle);
479     }
481     function promote_final($sessionid, $customdata) {
482         global $DB;
484         if(isset($this->conn_sets[$sessionid])) {
485             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
486             return false;
487         }
489         $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
490         if($chatuser === false) {
491             $this->dismiss_half($sessionid);
492             return false;
493         }
494         $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
495         if($chat === false) {
496             $this->dismiss_half($sessionid);
497             return false;
498         }
499         $user = $DB->get_record('user', array('id'=>$chatuser->userid));
500         if($user === false) {
501             $this->dismiss_half($sessionid);
502             return false;
503         }
504         $course = $DB->get_record('course', array('id'=>$chat->course));
505         if($course === false) {
506             $this->dismiss_half($sessionid);
507             return false;
508         }
510         global $CHAT_HTMLHEAD_JS, $CFG;
512         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
514         // This whole thing needs to be purged of redundant info, and the
515         // code base to follow suit. But AFTER development is done.
516         $this->sets_info[$sessionid] = array(
517             'lastinfocommit' => 0,
518             'lastmessageindex' => 0,
519             'course'    => $course,
520             'courseid'  => $course->id,
521             'chatuser'  => $chatuser,
522             'chatid'    => $chat->id,
523             'user'      => $user,
524             'userid'    => $user->id,
525             'groupid'   => $chatuser->groupid,
526             'lang'      => $chatuser->lang,
527             'quirks'    => $customdata['quirks']
528         );
530         // If we know nothing about this chatroom, initialize it and add the user
531         if(!isset($this->chatrooms[$chat->id]['users'])) {
532             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
533         }
534         else {
535             // Otherwise just add the user
536             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
537         }
539         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
541         $header  = "HTTP/1.1 200 OK\n";
542         $header .= "Connection: close\n";
543         $header .= "Date: ".date('r')."\n";
544         $header .= "Server: Moodle\n";
545         $header .= "Content-Type: text/html; charset=utf-8\n";
546         $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
547         $header .= "Cache-Control: no-cache, must-revalidate\n";
548         $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
549         $header .= "\n";
551         $this->dismiss_half($sessionid, false);
552         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $header . $CHAT_HTMLHEAD_JS);
553         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
555         // Finally, broadcast the "entered the chat" message
557         $msg = new stdClass;
558         $msg->chatid = $chatuser->chatid;
559         $msg->userid = $chatuser->userid;
560         $msg->groupid = $chatuser->groupid;
561         $msg->system = 1;
562         $msg->message = 'enter';
563         $msg->timestamp = time();
565         $DB->insert_record('chat_messages', $msg, false);
566         $DB->insert_record('chat_messages_current', $msg, false);
567         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
569         return true;
570     }
572     function promote_ufo($handle, $type, $sessionid, $customdata) {
573         if(empty($this->conn_ufo)) {
574             return false;
575         }
576         foreach($this->conn_ufo as $id => $ufo) {
577             if($ufo->handle == $handle) {
578                 // OK, got the id of the UFO, but what is it?
580                 if($type & CHAT_SIDEKICK) {
581                     // Is the main connection ready?
582                     if(isset($this->conn_sets[$sessionid])) {
583                         // Yes, so dispatch this sidekick now and be done with it
584                         //$this->trace('Dispatching sidekick immediately');
585                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
586                         $this->dismiss_ufo($handle, false);
587                     }
588                     else {
589                         // No, so put it in the waiting list
590                         $this->trace('sidekick waiting');
591                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
592                     }
593                     return true;
594                 }
596                 // If it's not a sidekick, at this point it can only be da man
598                 if($type & CHAT_CONNECTION) {
599                     // This forces a new connection right now...
600                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
602                     // Do we have such a connection active?
603                     if(isset($this->conn_sets[$sessionid])) {
604                         // Yes, so regrettably we cannot promote you
605                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
606                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
607                         return false;
608                     }
610                     // Join this with what we may have already
611                     $this->conn_half[$sessionid][$type] = $handle;
613                     // Do the bookkeeping
614                     $this->promote_final($sessionid, $customdata);
616                     // It's not an UFO anymore
617                     $this->dismiss_ufo($handle, false);
619                     // Dispatch waiting sidekicks
620                     $this->process_sidekicks($sessionid);
622                     return true;
623                 }
624             }
625         }
626         return false;
627     }
629     function dismiss_half($sessionid, $disconnect = true) {
630         if(!isset($this->conn_half[$sessionid])) {
631             return false;
632         }
633         if($disconnect) {
634             foreach($this->conn_half[$sessionid] as $handle) {
635                 @socket_shutdown($handle);
636                 @socket_close($handle);
637             }
638         }
639         unset($this->conn_half[$sessionid]);
640         return true;
641     }
643     function dismiss_set($sessionid) {
644         if(!empty($this->conn_sets[$sessionid])) {
645             foreach($this->conn_sets[$sessionid] as $handle) {
646                 // Since we want to dismiss this, don't generate any errors if it's dead already
647                 @socket_shutdown($handle);
648                 @socket_close($handle);
649             }
650         }
651         $chatroom = $this->sets_info[$sessionid]['chatid'];
652         $userid   = $this->sets_info[$sessionid]['userid'];
653         unset($this->conn_sets[$sessionid]);
654         unset($this->sets_info[$sessionid]);
655         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
656         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
657         return true;
658     }
661     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
662         if(empty($this->conn_ufo)) {
663             return false;
664         }
665         foreach($this->conn_ufo as $id => $ufo) {
666             if($ufo->handle == $handle) {
667                 unset($this->conn_ufo[$id]);
668                 if($disconnect) {
669                     if(!empty($message)) {
670                         $this->write_data($handle, $message."\n\n");
671                     }
672                     socket_shutdown($handle);
673                     socket_close($handle);
674                 }
675                 return true;
676             }
677         }
678         return false;
679     }
681     function conn_accept() {
682         $read_socket = array($this->listen_socket);
683         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
685         if(!$changed) {
686             return false;
687         }
688         $handle = socket_accept($this->listen_socket);
689         if(!$handle) {
690             return false;
691         }
693         $newconn = New ChatConnection($handle);
694         $id = $this->new_ufo_id();
695         $this->conn_ufo[$id] = $newconn;
697         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
698     }
700     function conn_activity_ufo (&$handles) {
701         $monitor = array();
702         if(!empty($this->conn_ufo)) {
703             foreach($this->conn_ufo as $ufoid => $ufo) {
704                 $monitor[$ufoid] = $ufo->handle;
705             }
706         }
708         if(empty($monitor)) {
709             $handles = array();
710             return 0;
711         }
713         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
714         $handles = $monitor;
716         return $retval;
717     }
719     function message_broadcast($message, $sender) {
720         global $PAGE;
722         if(empty($this->conn_sets)) {
723             return true;
724         }
726         $now = time();
728         // First of all, mark this chatroom as having had activity now
729         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
731         foreach($this->sets_info as $sessionid => $info) {
732             // We need to get handles from users that are in the same chatroom, same group
733             if($info['chatid'] == $message->chatid &&
734               ($info['groupid'] == $message->groupid || $message->groupid == 0))
735             {
737                 // Simply give them the message
738                 $PAGE->set_course($info['course']);
739                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
740                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
742                 if($output->beep) {
743                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
744                 }
746                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
747                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
748                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
749                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
750                 }
752                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
753                     $this->disconnect_session($sessionid);
754                 }
755                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
756             }
757         }
758     }
760     function disconnect_session($sessionid) {
761         global $DB;
763         $info = $this->sets_info[$sessionid];
765         $DB->delete_records('chat_users', array('sid'=>$sessionid));
766         $msg = New stdClass;
767         $msg->chatid = $info['chatid'];
768         $msg->userid = $info['userid'];
769         $msg->groupid = $info['groupid'];
770         $msg->system = 1;
771         $msg->message = 'exit';
772         $msg->timestamp = time();
774         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
775         $DB->insert_record('chat_messages', $msg, false);
776         $DB->insert_record('chat_messages_current', $msg, false);
778         // *************************** IMPORTANT
779         //
780         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
781         //
782         // **********************************************************************
783         $latesender = $info['user'];
784         $this->dismiss_set($sessionid);
785         $this->message_broadcast($msg, $latesender);
786     }
788     function fatal($message) {
789         $message .= "\n";
790         if($this->_logfile) {
791             $this->trace($message, E_USER_ERROR);
792         }
793         echo "FATAL ERROR:: $message\n";
794         die();
795     }
797     function init_sockets() {
798         global $CFG;
800         $this->trace('Setting up sockets');
802         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
803             // Failed to create socket
804             $lasterr = socket_last_error();
805             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
806         }
808         //socket_close($DAEMON->listen_socket);
809         //die();
811         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
812             // Failed to bind socket
813             $lasterr = socket_last_error();
814             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
815         }
817         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
818             // Failed to get socket to listen
819             $lasterr = socket_last_error();
820             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
821         }
823         // Socket has been initialized and is ready
824         $this->trace('Socket opened on port '.$CFG->chat_serverport);
826         // [pj]: I really must have a good read on sockets. What exactly does this do?
827         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
828         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
829         socket_set_nonblock($this->listen_socket);
830     }
832     function cli_switch($switch, $param = NULL) {
833         switch($switch) { //LOL
834             case 'reset':
835                 // Reset sockets
836                 $this->_resetsocket = true;
837                 return false;
838             case 'start':
839                 // Start the daemon
840                 $this->_readytogo = true;
841                 return false;
842             break;
843             case 'v':
844                 // Verbose mode
845                 $this->_trace_level = E_ALL;
846                 return false;
847             break;
848             case 'l':
849                 // Use logfile
850                 if(!empty($param)) {
851                     $this->_logfile_name = $param;
852                 }
853                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
854                 if($this->_logfile == false) {
855                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
856                 }
857                 return false;
858             default:
859                 // Unrecognized
860                 $this->fatal('Unrecognized command line switch: '.$switch);
861             break;
862         }
863         return false;
864     }
868 $DAEMON = New ChatDaemon;
869 set_error_handler(array($DAEMON, 'error_handler'));
871 /// Check the parameters //////////////////////////////////////////////////////
873 unset($argv[0]);
874 $commandline = implode(' ', $argv);
875 if(strpos($commandline, '-') === false) {
876     if(!empty($commandline)) {
877         // We cannot have received any meaningful parameters
878         $DAEMON->fatal('Garbage in command line');
879     }
881 else {
882     // Parse command line
883     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
885     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
886     // We will be using that to pass additional information to those switches who need it
887     $numswitches = count($switches);
889     // Fancy way to give a "hyphen" boolean flag to each "switch"
890     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
892     for($i = 0; $i < $numswitches; ++$i) {
894         $switch = $switches[$i]['str'];
895         $params = ($i == $numswitches - 1 ? NULL :
896                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
897                   );
899         if(substr($switch, 0, 2) == '--') {
900             // Double-hyphen switch
901             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
902         }
903         else if(substr($switch, 0, 1) == '-') {
904             // Single-hyphen switch(es), may be more than one run together
905             $switch = substr($switch, 1); // Get rid of the -
906             $len = strlen($switch);
907             for($j = 0; $j < $len; ++$j) {
908                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
909             }
910         }
911     }
914 if(!$DAEMON->query_start()) {
915     // For some reason we didn't start, so print out some info
916     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
917     echo "\n\n";
918     echo "Usage: chatd.php [parameters]\n\n";
919     echo "Parameters:\n";
920     echo "  --start         Starts the daemon\n";
921     echo "  -v              Verbose mode (prints trivial information messages)\n";
922     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
923     echo "Example:\n";
924     echo "  chatd.php --start -l\n\n";
925     die();
928 if (!function_exists('socket_setopt')) {
929     echo "Error: Function socket_setopt() does not exist.\n";
930     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
931     die();
934 $DAEMON->init_sockets();
936 /*
937 declare(ticks=1);
939 $pid = pcntl_fork();
940 if ($pid == -1) {
941      die("could not fork");
942 } else if ($pid) {
943      exit(); // we are the parent
944 } else {
945      // we are the child
948 // detatch from the controlling terminal
949 if (!posix_setsid()) {
950    die("could not detach from terminal");
953 // setup signal handlers
954 pcntl_signal(SIGTERM, "sig_handler");
955 pcntl_signal(SIGHUP, "sig_handler");
957 if($DAEMON->_pcntl_exists && false) {
958     $DAEMON->trace('Unholy spirit possession: daemonizing');
959     $DAEMON->pid = pcntl_fork();
960     if($pid == -1) {
961         $DAEMON->trace('Process fork failed, terminating');
962         die();
963     }
964     else if($pid) {
965         // We are the parent
966         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
967         die();
968     }
969     else {
970         // We are the daemon! :P
971     }
973     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
975     // Detach from controlling terminal
976     if(!posix_setsid()) {
977         $DAEMON->trace('Could not detach daemon process from terminal!');
978     }
980 else {
981     // Cannot go demonic
982     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
984 */
986 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
988 /// Clear the decks of old stuff
989 $DB->delete_records('chat_users', array('version'=>'sockets'));
991 while(true) {
992     $active = array();
994     // First of all, let's see if any of our UFOs has identified itself
995     if($DAEMON->conn_activity_ufo($active)) {
996         foreach($active as $handle) {
997             $read_socket = array($handle);
998             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
1000             if($changed > 0) {
1001                 // Let's see what it has to say
1003                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
1004                 if(empty($data)) {
1005                     continue;
1006                 }
1008                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1009                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1010                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1011                     continue;
1012                 }
1014                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1015                     // Malformed data
1016                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1017                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1018                     continue;
1019                 }
1021                 $type      = $info[1];
1022                 $sessionid = $info[2];
1024                 $customdata = array();
1026                 switch($type) {
1027                     case 'chat':
1028                        $type = CHAT_CONNECTION_CHANNEL;
1029                         $customdata['quirks'] = 0;
1030                         if(strpos($data, 'Safari')) {
1031                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1032                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1033                         }
1034                     break;
1035                     case 'users':
1036                         $type = CHAT_SIDEKICK_USERS;
1037                     break;
1038                     case 'beep':
1039                         $type = CHAT_SIDEKICK_BEEP;
1040                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1041                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1042                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1043                             continue;
1044                         }
1045                         else {
1046                             $customdata = array('beep' => intval($info[1]));
1047                         }
1048                     break;
1049                     case 'message':
1050                         $type = CHAT_SIDEKICK_MESSAGE;
1051                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1052                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1053                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1054                             continue;
1055                         }
1056                         else {
1057                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1058                         }
1059                     break;
1060                     default:
1061                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1062                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1063                         continue;
1064                     break;
1065                 }
1067                 // OK, now we know it's something good... promote it and pass it all the data it needs
1068                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1069                 continue;
1070             }
1071         }
1072     }
1074     $now = time();
1076     // Clean up chatrooms with no activity as required
1077     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1078         $DAEMON->poll_idle_chats($now);
1079     }
1081     // Finally, accept new connections
1082     $DAEMON->conn_accept();
1084     usleep($DAEMON->_time_rest_socket);
1087 @socket_shutdown($DAEMON->listen_socket, 0);
1088 die("\n\n-- terminated --\n");