a6dd9d883d7846c9eedcfc873baa67eb190fdbde
[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." (\$Id$)\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 $nomoodlecookie = true;
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 if(ini_get('allow_call_time_pass_reference') == '0') {
48     die("Error: Cannot run with PHP allow_call_time_pass_reference = Off. Turn on allow_call_time_pass_reference in php.ini.\n");
49 }
51 @set_time_limit (0);
52 set_magic_quotes_runtime(0);
53 error_reporting(E_ALL);
55 function chat_empty_connection() {
56     return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL);
57 }
59 class ChatConnection {
60     // Chat-related info
61     var $sid    = NULL;
62     var $type   = NULL;
63     //var $groupid        = NULL;
65     // PHP-level info
66     var $handle = NULL;
68     // TCP/IP
69     var $ip     = NULL;
70     var $port   = NULL;
72     function ChatConnection($resource) {
73         $this->handle = $resource;
74         @socket_getpeername($this->handle, &$this->ip, &$this->port);
75     }
76 }
78 class ChatDaemon {
79     var $_resetsocket       = false;
80     var $_readytogo         = false;
81     var $_logfile           = false;
82     var $_trace_to_console  = true;
83     var $_trace_to_stdout   = true;
84     var $_logfile_name      = 'chatd.log';
85     var $_last_idle_poll    = 0;
87     var $conn_ufo  = array();    // Connections not identified yet
88     var $conn_side = array();    // Sessions with sidekicks waiting for the main connection to be processed
89     var $conn_half = array();    // Sessions that have valid connections but not all of them
90     var $conn_sets = array();    // Sessions with complete connection sets sets
91     var $sets_info = array();    // Keyed by sessionid exactly like conn_sets, one of these for each of those
92     var $chatrooms = array();    // Keyed by chatid, holding arrays of data
94     // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized!
95     //            Pay extra attention when you write code that affects any of them!
97     function ChatDaemon() {
98         $this->_trace_level         = E_ALL ^ E_USER_NOTICE;
99         $this->_pcntl_exists        = function_exists('pcntl_fork');
100         $this->_time_rest_socket    = 20;
101         $this->_beepsoundsrc        = $GLOBALS['CFG']->wwwroot.'/mod/chat/beep.wav';
102         $this->_freq_update_records = 20;
103         $this->_freq_poll_idle_chat = $GLOBALS['CFG']->chat_old_ping;
104         $this->_stdout = fopen('php://stdout', 'w');
105         if($this->_stdout) {
106             // Avoid double traces for everything
107             $this->_trace_to_console = false;
108         }
109     }
111     function error_handler ($errno, $errmsg, $filename, $linenum, $vars) {
112         // Checks if an error needs to be suppressed due to @
113         if(error_reporting() != 0) {
114             $this->trace($errmsg.' on line '.$linenum, $errno);
115         }
116         return true;
117     }
119     function poll_idle_chats($now) {
120         $this->trace('Polling chats to detect disconnected users');
121         if(!empty($this->chatrooms)) {
122             foreach($this->chatrooms as $chatid => $chatroom) {
123                 if(!empty($chatroom['users'])) {
124                     foreach($chatroom['users'] as $sessionid => $userid) {
125                         // We will be polling each user as required
126                         $this->trace('...shall we poll '.$sessionid.'?');
127                         if($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) {
128                             $this->trace('YES!');
129                             // This user hasn't been polled since his last message
130                             if($this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<!-- poll -->') === false) {
131                                 // User appears to have disconnected
132                                 $this->disconnect_session($sessionid);
133                             }
134                         }
135                     }
136                 }
137             }
138         }
139         $this->_last_idle_poll = $now;
140     }
142     function query_start() {
143         return $this->_readytogo;
144     }
146     function trace($message, $level = E_USER_NOTICE) {
147         $severity = '';
149         switch($level) {
150             case E_USER_WARNING: $severity = '*IMPORTANT* '; break;
151             case E_USER_ERROR:   $severity = ' *CRITICAL* '; break;
152             case E_NOTICE:
153             case E_WARNING:      $severity = ' *CRITICAL* [php] '; break;
154         }
156         $date = date('[Y-m-d H:i:s] ');
157         $message = $date.$severity.$message."\n";
159         if ($this->_trace_level & $level) {
160             // It is accepted for output
162             // Error-class traces go to STDERR too
163             if($level & E_USER_ERROR) {
164                 fwrite(STDERR, $message);
165             }
167             // Emit the message to wherever we should
168             if($this->_trace_to_stdout) {
169                 fwrite($this->_stdout, $message);
170                 fflush($this->_stdout);
171             }
172             if($this->_trace_to_console) {
173                 echo $message;
174                 flush();
175             }
176             if($this->_logfile) {
177                 fwrite($this->_logfile, $message);
178                 fflush($this->_logfile);
179             }
180         }
181     }
183     function write_data($connection, $text) {
184         $written = @socket_write($connection, $text, strlen($text));
185         if($written === false) {
186             // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)));
187             return false;
188         }
189         return true;
191         // Enclosing the above code inside this blocks makes sure that
192         // "a socket write operation will not block". I 'm not so sure
193         // if this is needed, as we have a nonblocking socket anyway.
194         // If trouble starts to creep up, we 'll restore this.
195 //        $check_socket = array($connection);
196 //        $socket_changed = socket_select($read = NULL, $check_socket, $except = NULL, 0, 0);
197 //        if($socket_changed > 0) {
198 //
199 //            // ABOVE CODE GOES HERE
200 //
201 //        }
202 //        return false;
203     }
205     function user_lazy_update($sessionid) {
206         // TODO: this can and should be written as a single UPDATE query
207         if(empty($this->sets_info[$sessionid])) {
208             $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING);
209             return false;
210         }
212         $now = time();
214         // We 'll be cheating a little, and NOT updating the record data as
215         // often as we can, so that we save on DB queries (imagine MANY users)
216         if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) {
217             // commit to permanent storage
218             $this->sets_info[$sessionid]['lastinfocommit'] = $now;
219             update_record('chat_users', $this->sets_info[$sessionid]['chatuser']);
220         }
221         return true;
222     }
224     function get_user_window($sessionid) {
226         global $CFG;
228         static $str;
230         $info = &$this->sets_info[$sessionid];
231         chat_force_language($info['lang']);
233         $timenow = time();
235         if (empty($str)) {
236             $str->idle  = get_string("idle", "chat");
237             $str->beep  = get_string("beep", "chat");
238             $str->day   = get_string("day");
239             $str->days  = get_string("days");
240             $str->hour  = get_string("hour");
241             $str->hours = get_string("hours");
242             $str->min   = get_string("min");
243             $str->mins  = get_string("mins");
244             $str->sec   = get_string("sec");
245             $str->secs  = get_string("secs");
246         }
248         ob_start();
249         echo '<html><head>';
250         echo '<script text="text/javascript">';
251         echo "//<![CDATA[\n";
253         echo 'function openpopup(url,name,options,fullscreen) {';
254         echo 'fullurl = "'.$CFG->wwwroot.'" + url;';
255         echo 'windowobj = window.open(fullurl,name,options);';
256         echo 'if (fullscreen) {';
257         echo '  windowobj.moveTo(0,0);';
258         echo '  windowobj.resizeTo(screen.availWidth,screen.availHeight); ';
259         echo '}';
260         echo 'windowobj.focus();';
261         echo 'return false;';
262         echo "}\n//]]>\n";
263         echo '</script></head><body style="font-face: serif;" bgcolor="#FFFFFF">';
265         echo '<table style="width: 100%;"><tbody>';
267         // Get the users from that chatroom
268         $users = $this->chatrooms[$info['chatid']]['users'];
270         foreach ($users as $usersessionid => $userid) {
271             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
272             $userinfo = $this->sets_info[$usersessionid];
274             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
275             $popuppar = '\'/user/view.php?id='.$userinfo['user']->id.'&amp;course='.$userinfo['courseid'].'\',\'user'.$userinfo['chatuser']->id.'\',\'\'';
276             echo '<tr><td width="35">';
277             echo '<a target="_new" onclick="return openpopup('.$popuppar.');" href="'.$CFG->wwwroot.'/user/view.php?id='.$userinfo['chatuser']->id.'&amp;course='.$userinfo['courseid'].'">';
278             print_user_picture($userinfo['user']->id, 0, $userinfo['user']->picture, false, false, false);
279             echo "</a></td><td valign=\"center\">";
280             echo "<p><font size=\"1\">";
281             echo fullname($userinfo['user'])."<br />";
282             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
283             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
284                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
285             echo "</font></p>";
286             echo "<td></tr>";
287         }
289         echo '</tbody></table>';
291         // About 2K of HTML comments to force browsers to render the HTML
292         // echo $GLOBALS['CHAT_DUMMY_DATA'];
294         echo "</body>\n</html>\n";
296         return ob_get_clean();
298     }
300     function new_ufo_id() {
301         static $id = 0;
302         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
303             $id = 0;
304         }
305         return $id;
306     }
308     function process_sidekicks($sessionid) {
309         if(empty($this->conn_side[$sessionid])) {
310             return true;
311         }
312         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
313             // TODO: is this late-dispatch working correctly?
314             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
315             unset($this->conn_side[$sessionid][$sideid]);
316         }
317         return true;
318     }
320     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
321         global $CFG;
323         switch($type) {
324             case CHAT_SIDEKICK_BEEP:
325                 // Incoming beep
326                 $msg = &New stdClass;
327                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
328                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
329                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
330                 $msg->system    = 0;
331                 $msg->message   = 'beep '.$customdata['beep'];
332                 $msg->timestamp = time();
334                 // Commit to DB
335                 insert_record('chat_messages', $msg, false);
337                 // OK, now push it out to all users
338                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
340                 // Update that user's lastmessageping
341                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
342                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
343                 $this->user_lazy_update($sessionid);
345                 // We did our work, but before slamming the door on the poor browser
346                 // show the courtesy of responding to the HTTP request. Otherwise, some
347                 // browsers decide to get vengeance by flooding us with repeat requests.
349                 $header  = "HTTP/1.1 200 OK\n";
350                 $header .= "Connection: close\n";
351                 $header .= "Date: ".date('r')."\n";
352                 $header .= "Server: Moodle\n";
353                 $header .= "Content-Type: text/html\n";
354                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
355                 $header .= "Cache-Control: no-cache, must-revalidate\n";
356                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
357                 $header .= "\n";
359                 // That's enough headers for one lousy dummy response
360                 $this->write_data($handle, $header);
361                 // All done
362             break;
364             case CHAT_SIDEKICK_USERS:
365                 // A request to paint a user window
367                 $content = $this->get_user_window($sessionid);
369                 $header  = "HTTP/1.1 200 OK\n";
370                 $header .= "Connection: close\n";
371                 $header .= "Date: ".date('r')."\n";
372                 $header .= "Server: Moodle\n";
373                 $header .= "Content-Type: text/html\n";
374                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
375                 $header .= "Cache-Control: no-cache, must-revalidate\n";
376                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
377                 $header .= "Content-Length: ".strlen($content)."\n";
379                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
380                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
381                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
382                            "chat_sid=".$sessionid."\n";
383                 $header .= "\n";
385                 // That's enough headers for one lousy dummy response
386                 $this->trace('writing users http response to handle '.$handle);
387                 $this->write_data($handle, $header . $content);
389                 // Update that user's lastping
390                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
391                 $this->user_lazy_update($sessionid);
393             break;
395             case CHAT_SIDEKICK_MESSAGE:
396                 // Incoming message
398                 // Browser stupidity protection from duplicate messages:
399                 $messageindex = intval($customdata['index']);
401                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
402                     // We have already broadcasted that!
403                     // $this->trace('discarding message with stale index');
404                     break;
405                 }
406                 else {
407                     // Update our info
408                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
409                 }
411                 $msg = &New stdClass;
412                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
413                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
414                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
415                 $msg->system    = 0;
416                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
417                 $msg->timestamp = time();
419                 if(empty($msg->message)) {
420                     // Someone just hit ENTER, send them on their way
421                     break;
422                 }
424                 // A slight hack to prevent malformed SQL inserts
425                 $origmsg = $msg->message;
426                 $msg->message = addslashes($msg->message);
428                 // Commit to DB
429                 insert_record('chat_messages', $msg, false);
431                 // Undo the hack
432                 $msg->message = $origmsg;
434                 // OK, now push it out to all users
435                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
437                 // Update that user's lastmessageping
438                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
439                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
440                 $this->user_lazy_update($sessionid);
442                 // We did our work, but before slamming the door on the poor browser
443                 // show the courtesy of responding to the HTTP request. Otherwise, some
444                 // browsers decide to get vengeance by flooding us with repeat requests.
446                 $header  = "HTTP/1.1 200 OK\n";
447                 $header .= "Connection: close\n";
448                 $header .= "Date: ".date('r')."\n";
449                 $header .= "Server: Moodle\n";
450                 $header .= "Content-Type: text/html\n";
451                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
452                 $header .= "Cache-Control: no-cache, must-revalidate\n";
453                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
454                 $header .= "\n";
456                 // That's enough headers for one lousy dummy response
457                 $this->write_data($handle, $header);
459                 // All done
460             break;
461         }
463         socket_shutdown($handle);
464         socket_close($handle);
465     }
467     function promote_final($sessionid, $customdata) {
468         if(isset($this->conn_sets[$sessionid])) {
469             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
470             return false;
471         }
473         $chatuser = get_record('chat_users', 'sid', $sessionid);
474         if($chatuser === false) {
475             $this->dismiss_half($sessionid);
476             return false;
477         }
478         $chat = get_record('chat', 'id', $chatuser->chatid);
479         if($chat === false) {
480             $this->dismiss_half($sessionid);
481             return false;
482         }
483         $user = get_record('user', 'id', $chatuser->userid);
484         if($user === false) {
485             $this->dismiss_half($sessionid);
486             return false;
487         }
488         $course = get_record('course', 'id', $chat->course); {
489        if($course === false) {
490             $this->dismiss_half($sessionid);
491             return false;
492             }
493         }
495         global $CHAT_HTMLHEAD_JS, $CFG;
497         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
499         // This whole thing needs to be purged of redundant info, and the
500         // code base to follow suit. But AFTER development is done.
501         $this->sets_info[$sessionid] = array(
502             'lastinfocommit' => 0,
503             'lastmessageindex' => 0,
504             'courseid'  => $course->id,
505             'chatuser'  => $chatuser,
506             'chatid'    => $chat->id,
507             'user'      => $user,
508             'userid'    => $user->id,
509             'groupid'   => $chatuser->groupid,
510             'lang'      => $chatuser->lang,
511             'quirks'    => $customdata['quirks']
512         );
514         // If we know nothing about this chatroom, initialize it and add the user
515         if(!isset($this->chatrooms[$chat->id]['users'])) {
516             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
517         }
518         else {
519             // Otherwise just add the user
520             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
521         }
523         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
525         $this->dismiss_half($sessionid, false);
526         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
527         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
529         // Finally, broadcast the "entered the chat" message
531         $msg = &New stdClass;
532         $msg->chatid = $chatuser->chatid;
533         $msg->userid = $chatuser->userid;
534         $msg->groupid = $chatuser->groupid;
535         $msg->system = 1;
536         $msg->message = 'enter';
537         $msg->timestamp = time();
539         insert_record('chat_messages', $msg, false);
540         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
542         return true;
543     }
545     function promote_ufo($handle, $type, $sessionid, $customdata) {
546         if(empty($this->conn_ufo)) {
547             return false;
548         }
549         foreach($this->conn_ufo as $id => $ufo) {
550             if($ufo->handle == $handle) {
551                 // OK, got the id of the UFO, but what is it?
553                 if($type & CHAT_SIDEKICK) {
554                     // Is the main connection ready?
555                     if(isset($this->conn_sets[$sessionid])) {
556                         // Yes, so dispatch this sidekick now and be done with it
557                         //$this->trace('Dispatching sidekick immediately');
558                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
559                         $this->dismiss_ufo($handle, false);
560                     }
561                     else {
562                         // No, so put it in the waiting list
563                         $this->trace('sidekick waiting');
564                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
565                     }
566                     return true;
567                 }
569                 // If it's not a sidekick, at this point it can only be da man
571                 if($type & CHAT_CONNECTION) {
572                     // This forces a new connection right now...
573                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
575                     // Do we have such a connection active?
576                     if(isset($this->conn_sets[$sessionid])) {
577                         // Yes, so regrettably we cannot promote you
578                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
579                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
580                         return false;
581                     }
583                     // Join this with what we may have already
584                     $this->conn_half[$sessionid][$type] = $handle;
586                     // Do the bookkeeping
587                     $this->promote_final($sessionid, $customdata);
589                     // It's not an UFO anymore
590                     $this->dismiss_ufo($handle, false);
592                     // Dispatch waiting sidekicks
593                     $this->process_sidekicks($sessionid);
595                     return true;
596                 }
597             }
598         }
599         return false;
600     }
602     function dismiss_half($sessionid, $disconnect = true) {
603         if(!isset($this->conn_half[$sessionid])) {
604             return false;
605         }
606         if($disconnect) {
607             foreach($this->conn_half[$sessionid] as $handle) {
608                 @socket_shutdown($handle);
609                 @socket_close($handle);
610             }
611         }
612         unset($this->conn_half[$sessionid]);
613         return true;
614     }
616     function dismiss_set($sessionid) {
617         if(!empty($this->conn_sets[$sessionid])) {
618             foreach($this->conn_sets[$sessionid] as $handle) {
619                 // Since we want to dismiss this, don't generate any errors if it's dead already
620                 @socket_shutdown($handle);
621                 @socket_close($handle);
622             }
623         }
624         $chatroom = $this->sets_info[$sessionid]['chatid'];
625         $userid   = $this->sets_info[$sessionid]['userid'];
626         unset($this->conn_sets[$sessionid]);
627         unset($this->sets_info[$sessionid]);
628         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
629         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
630         return true;
631     }
634     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
635         if(empty($this->conn_ufo)) {
636             return false;
637         }
638         foreach($this->conn_ufo as $id => $ufo) {
639             if($ufo->handle == $handle) {
640                 unset($this->conn_ufo[$id]);
641                 if($disconnect) {
642                     if(!empty($message)) {
643                         $this->write_data($handle, $message."\n\n");
644                     }
645                     socket_shutdown($handle);
646                     socket_close($handle);
647                 }
648                 return true;
649             }
650         }
651         return false;
652     }
654     function conn_accept() {
655         $read_socket = array($this->listen_socket);
656         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
658         if(!$changed) {
659             return false;
660         }
661         $handle = socket_accept($this->listen_socket);
662         if(!$handle) {
663             return false;
664         }
666         $newconn = &New ChatConnection($handle);
667         $id = $this->new_ufo_id();
668         $this->conn_ufo[$id] = $newconn;
670         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
671     }
673     function conn_activity_ufo (&$handles) {
674         $monitor = array();
675         if(!empty($this->conn_ufo)) {
676             foreach($this->conn_ufo as $ufoid => $ufo) {
677                 $monitor[$ufoid] = $ufo->handle;
678             }
679         }
681         if(empty($monitor)) {
682             $handles = array();
683             return 0;
684         }
686         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
687         $handles = $monitor;
689         return $retval;
690     }
692     function message_broadcast($message, $sender) {
693         if(empty($this->conn_sets)) {
694             return true;
695         }
697         $now = time();
699         // First of all, mark this chatroom as having had activity now
700         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
702         foreach($this->sets_info as $sessionid => $info) {
703             // We need to get handles from users that are in the same chatroom, same group
704             if($info['chatid'] == $message->chatid &&
705               ($info['groupid'] == $message->groupid || $message->groupid == 0))
706             {
708                 // Simply give them the message
709                 chat_force_language($info['lang']);
710                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
711                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
713                 if($output->beep) {
714                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
715                 }
717                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
718                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
719                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
720                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
721                 }
723                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
724                     $this->disconnect_session($sessionid);
725                 }
726                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
727             }
728         }
729     }
731     function disconnect_session($sessionid) {
732         $info = $this->sets_info[$sessionid];
734         delete_records('chat_users', 'sid', $sessionid);
735         $msg = &New stdClass;
736         $msg->chatid = $info['chatid'];
737         $msg->userid = $info['userid'];
738         $msg->groupid = $info['groupid'];
739         $msg->system = 1;
740         $msg->message = 'exit';
741         $msg->timestamp = time();
743         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
744         insert_record('chat_messages', $msg, false);
746         // *************************** IMPORTANT
747         //
748         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
749         //
750         // **********************************************************************
751         $latesender = $info['user'];
752         $this->dismiss_set($sessionid);
753         $this->message_broadcast($msg, $latesender);
754     }
756     function fatal($message) {
757         $message .= "\n";
758         if($this->_logfile) {
759             $this->trace($message, E_USER_ERROR);
760         }
761         echo "FATAL ERROR:: $message\n";
762         die();
763     }
765     function init_sockets() {
766         global $CFG;
768         $this->trace('Setting up sockets');
770         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
771             // Failed to create socket
772             $lasterr = socket_last_error();
773             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
774         }
776         //socket_close($DAEMON->listen_socket);
777         //die();
779         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
780             // Failed to bind socket
781             $lasterr = socket_last_error();
782             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
783         }
785         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
786             // Failed to get socket to listen
787             $lasterr = socket_last_error();
788             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
789         }
791         // Socket has been initialized and is ready
792         $this->trace('Socket opened on port '.$CFG->chat_serverport);
794         // [pj]: I really must have a good read on sockets. What exactly does this do?
795         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
796         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
797         socket_set_nonblock($this->listen_socket);
798     }
800     function cli_switch($switch, $param = NULL) {
801         switch($switch) { //LOL
802             case 'reset':
803                 // Reset sockets
804                 $this->_resetsocket = true;
805                 return false;
806             case 'start':
807                 // Start the daemon
808                 $this->_readytogo = true;
809                 return false;
810             break;
811             case 'v':
812                 // Verbose mode
813                 $this->_trace_level = E_ALL;
814                 return false;
815             break;
816             case 'l':
817                 // Use logfile
818                 if(!empty($param)) {
819                     $this->_logfile_name = $param;
820                 }
821                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
822                 if($this->_logfile == false) {
823                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
824                 }
825                 return false;
826             default:
827                 // Unrecognized
828                 $this->fatal('Unrecognized command line switch: '.$switch);
829             break;
830         }
831         return false;
832     }
836 $DAEMON = New ChatDaemon;
837 set_error_handler(array($DAEMON, 'error_handler'));
839 /// Check the parameters //////////////////////////////////////////////////////
841 unset($argv[0]);
842 $commandline = implode(' ', $argv);
843 if(strpos($commandline, '-') === false) {
844     if(!empty($commandline)) {
845         // We cannot have received any meaningful parameters
846         $DAEMON->fatal('Garbage in command line');
847     }
849 else {
850     // Parse command line
851     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
853     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
854     // We will be using that to pass additional information to those switches who need it
855     $numswitches = count($switches);
857     // Fancy way to give a "hyphen" boolean flag to each "switch"
858     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
860     for($i = 0; $i < $numswitches; ++$i) {
862         $switch = $switches[$i]['str'];
863         $params = ($i == $numswitches - 1 ? NULL :
864                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
865                   );
867         if(substr($switch, 0, 2) == '--') {
868             // Double-hyphen switch
869             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
870         }
871         else if(substr($switch, 0, 1) == '-') {
872             // Single-hyphen switch(es), may be more than one run together
873             $switch = substr($switch, 1); // Get rid of the -
874             $len = strlen($switch);
875             for($j = 0; $j < $len; ++$j) {
876                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
877             }
878         }
879     }
882 if(!$DAEMON->query_start()) {
883     // For some reason we didn't start, so print out some info
884     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
885     echo "\n\n";
886     echo "Usage: chatd.php [parameters]\n\n";
887     echo "Parameters:\n";
888     echo "  --start         Starts the daemon\n";
889     echo "  -v              Verbose mode (prints trivial information messages)\n";
890     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
891     echo "Example:\n";
892     echo "  chatd.php --start -l\n\n";
893     die();
896 if (!function_exists('socket_setopt')) {
897     echo "Error: Function socket_setopt() does not exist.\n";
898     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
899     die();
902 $DAEMON->init_sockets();
904 /*
905 declare(ticks=1);
907 $pid = pcntl_fork();
908 if ($pid == -1) {
909      die("could not fork");
910 } else if ($pid) {
911      exit(); // we are the parent
912 } else {
913      // we are the child
916 // detatch from the controlling terminal
917 if (!posix_setsid()) {
918    die("could not detach from terminal");
921 // setup signal handlers
922 pcntl_signal(SIGTERM, "sig_handler");
923 pcntl_signal(SIGHUP, "sig_handler");
925 if($DAEMON->_pcntl_exists && false) {
926     $DAEMON->trace('Unholy spirit possession: daemonizing');
927     $DAEMON->pid = pcntl_fork();
928     if($pid == -1) {
929         $DAEMON->trace('Process fork failed, terminating');
930         die();
931     }
932     else if($pid) {
933         // We are the parent
934         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
935         die();
936     }
937     else {
938         // We are the daemon! :P
939     }
941     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
943     // Detach from controlling terminal
944     if(!posix_setsid()) {
945         $DAEMON->trace('Could not detach daemon process from terminal!');
946     }
948 else {
949     // Cannot go demonic
950     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
952 */
954 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
956 /// Clear the decks of old stuff
957 delete_records('chat_users', 'version', 'sockets');
959 while(true) {
960     $active = array();
962     // First of all, let's see if any of our UFOs has identified itself
963     if($DAEMON->conn_activity_ufo($active)) {
964         foreach($active as $handle) {
965             $read_socket = array($handle);
966             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
968             if($changed > 0) {
969                 // Let's see what it has to say
971                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
972                 if(empty($data)) {
973                     continue;
974                 }
976                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
977                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
978                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
979                     continue;
980                 }
982                 if(!ereg('win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP', $data, $info)) {
983                     // Malformed data
984                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
985                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
986                     continue;
987                 }
989                 $type      = $info[1];
990                 $sessionid = $info[2];
992                 $customdata = array();
994                 switch($type) {
995                     case 'chat':
996                        $type = CHAT_CONNECTION_CHANNEL;
997                         $customdata['quirks'] = 0;
998                         if(strpos($data, 'Safari')) {
999                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1000                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1001                         }
1002                     break;
1003                     case 'users':
1004                         $type = CHAT_SIDEKICK_USERS;
1005                     break;
1006                     case 'beep':
1007                         $type = CHAT_SIDEKICK_BEEP;
1008                         if(!ereg('beep=([^&]*)[& ]', $data, $info)) {
1009                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1010                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1011                             continue;
1012                         }
1013                         else {
1014                             $customdata = array('beep' => intval($info[1]));
1015                         }
1016                     break;
1017                     case 'message':
1018                         $type = CHAT_SIDEKICK_MESSAGE;
1019                         if(!ereg('chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]', $data, $info)) {
1020                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1021                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1022                             continue;
1023                         }
1024                         else {
1025                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1026                         }
1027                     break;
1028                     default:
1029                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1030                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1031                         continue;
1032                     break;
1033                 }
1035                 // OK, now we know it's something good... promote it and pass it all the data it needs
1036                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1037                 continue;
1038             }
1039         }
1040     }
1042     $now = time();
1044     // Clean up chatrooms with no activity as required
1045     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1046         $DAEMON->poll_idle_chats($now);
1047     }
1049     // Finally, accept new connections
1050     $DAEMON->conn_accept();
1052     usleep($DAEMON->_time_rest_socket);
1055 @socket_shutdown($DAEMON->listen_socket, 0);
1056 die("\n\n-- terminated --\n");
1058 ?>