f255c17dfd200d9375fed79769f748c90bf11e2d
[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         $this->dismiss_half($sessionid, false);
542         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
543         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
545         // Finally, broadcast the "entered the chat" message
547         $msg = new stdClass;
548         $msg->chatid = $chatuser->chatid;
549         $msg->userid = $chatuser->userid;
550         $msg->groupid = $chatuser->groupid;
551         $msg->system = 1;
552         $msg->message = 'enter';
553         $msg->timestamp = time();
555         $DB->insert_record('chat_messages', $msg, false);
556         $DB->insert_record('chat_messages_current', $msg, false);
557         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
559         return true;
560     }
562     function promote_ufo($handle, $type, $sessionid, $customdata) {
563         if(empty($this->conn_ufo)) {
564             return false;
565         }
566         foreach($this->conn_ufo as $id => $ufo) {
567             if($ufo->handle == $handle) {
568                 // OK, got the id of the UFO, but what is it?
570                 if($type & CHAT_SIDEKICK) {
571                     // Is the main connection ready?
572                     if(isset($this->conn_sets[$sessionid])) {
573                         // Yes, so dispatch this sidekick now and be done with it
574                         //$this->trace('Dispatching sidekick immediately');
575                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
576                         $this->dismiss_ufo($handle, false);
577                     }
578                     else {
579                         // No, so put it in the waiting list
580                         $this->trace('sidekick waiting');
581                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
582                     }
583                     return true;
584                 }
586                 // If it's not a sidekick, at this point it can only be da man
588                 if($type & CHAT_CONNECTION) {
589                     // This forces a new connection right now...
590                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
592                     // Do we have such a connection active?
593                     if(isset($this->conn_sets[$sessionid])) {
594                         // Yes, so regrettably we cannot promote you
595                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
596                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
597                         return false;
598                     }
600                     // Join this with what we may have already
601                     $this->conn_half[$sessionid][$type] = $handle;
603                     // Do the bookkeeping
604                     $this->promote_final($sessionid, $customdata);
606                     // It's not an UFO anymore
607                     $this->dismiss_ufo($handle, false);
609                     // Dispatch waiting sidekicks
610                     $this->process_sidekicks($sessionid);
612                     return true;
613                 }
614             }
615         }
616         return false;
617     }
619     function dismiss_half($sessionid, $disconnect = true) {
620         if(!isset($this->conn_half[$sessionid])) {
621             return false;
622         }
623         if($disconnect) {
624             foreach($this->conn_half[$sessionid] as $handle) {
625                 @socket_shutdown($handle);
626                 @socket_close($handle);
627             }
628         }
629         unset($this->conn_half[$sessionid]);
630         return true;
631     }
633     function dismiss_set($sessionid) {
634         if(!empty($this->conn_sets[$sessionid])) {
635             foreach($this->conn_sets[$sessionid] as $handle) {
636                 // Since we want to dismiss this, don't generate any errors if it's dead already
637                 @socket_shutdown($handle);
638                 @socket_close($handle);
639             }
640         }
641         $chatroom = $this->sets_info[$sessionid]['chatid'];
642         $userid   = $this->sets_info[$sessionid]['userid'];
643         unset($this->conn_sets[$sessionid]);
644         unset($this->sets_info[$sessionid]);
645         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
646         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
647         return true;
648     }
651     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
652         if(empty($this->conn_ufo)) {
653             return false;
654         }
655         foreach($this->conn_ufo as $id => $ufo) {
656             if($ufo->handle == $handle) {
657                 unset($this->conn_ufo[$id]);
658                 if($disconnect) {
659                     if(!empty($message)) {
660                         $this->write_data($handle, $message."\n\n");
661                     }
662                     socket_shutdown($handle);
663                     socket_close($handle);
664                 }
665                 return true;
666             }
667         }
668         return false;
669     }
671     function conn_accept() {
672         $read_socket = array($this->listen_socket);
673         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
675         if(!$changed) {
676             return false;
677         }
678         $handle = socket_accept($this->listen_socket);
679         if(!$handle) {
680             return false;
681         }
683         $newconn = New ChatConnection($handle);
684         $id = $this->new_ufo_id();
685         $this->conn_ufo[$id] = $newconn;
687         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
688     }
690     function conn_activity_ufo (&$handles) {
691         $monitor = array();
692         if(!empty($this->conn_ufo)) {
693             foreach($this->conn_ufo as $ufoid => $ufo) {
694                 $monitor[$ufoid] = $ufo->handle;
695             }
696         }
698         if(empty($monitor)) {
699             $handles = array();
700             return 0;
701         }
703         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
704         $handles = $monitor;
706         return $retval;
707     }
709     function message_broadcast($message, $sender) {
710         global $PAGE;
712         if(empty($this->conn_sets)) {
713             return true;
714         }
716         $now = time();
718         // First of all, mark this chatroom as having had activity now
719         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
721         foreach($this->sets_info as $sessionid => $info) {
722             // We need to get handles from users that are in the same chatroom, same group
723             if($info['chatid'] == $message->chatid &&
724               ($info['groupid'] == $message->groupid || $message->groupid == 0))
725             {
727                 // Simply give them the message
728                 $PAGE->set_course($info['course']);
729                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
730                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
732                 if($output->beep) {
733                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
734                 }
736                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
737                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
738                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
739                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
740                 }
742                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
743                     $this->disconnect_session($sessionid);
744                 }
745                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
746             }
747         }
748     }
750     function disconnect_session($sessionid) {
751         global $DB;
753         $info = $this->sets_info[$sessionid];
755         $DB->delete_records('chat_users', array('sid'=>$sessionid));
756         $msg = New stdClass;
757         $msg->chatid = $info['chatid'];
758         $msg->userid = $info['userid'];
759         $msg->groupid = $info['groupid'];
760         $msg->system = 1;
761         $msg->message = 'exit';
762         $msg->timestamp = time();
764         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
765         $DB->insert_record('chat_messages', $msg, false);
766         $DB->insert_record('chat_messages_current', $msg, false);
768         // *************************** IMPORTANT
769         //
770         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
771         //
772         // **********************************************************************
773         $latesender = $info['user'];
774         $this->dismiss_set($sessionid);
775         $this->message_broadcast($msg, $latesender);
776     }
778     function fatal($message) {
779         $message .= "\n";
780         if($this->_logfile) {
781             $this->trace($message, E_USER_ERROR);
782         }
783         echo "FATAL ERROR:: $message\n";
784         die();
785     }
787     function init_sockets() {
788         global $CFG;
790         $this->trace('Setting up sockets');
792         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
793             // Failed to create socket
794             $lasterr = socket_last_error();
795             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
796         }
798         //socket_close($DAEMON->listen_socket);
799         //die();
801         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
802             // Failed to bind socket
803             $lasterr = socket_last_error();
804             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
805         }
807         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
808             // Failed to get socket to listen
809             $lasterr = socket_last_error();
810             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
811         }
813         // Socket has been initialized and is ready
814         $this->trace('Socket opened on port '.$CFG->chat_serverport);
816         // [pj]: I really must have a good read on sockets. What exactly does this do?
817         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
818         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
819         socket_set_nonblock($this->listen_socket);
820     }
822     function cli_switch($switch, $param = NULL) {
823         switch($switch) { //LOL
824             case 'reset':
825                 // Reset sockets
826                 $this->_resetsocket = true;
827                 return false;
828             case 'start':
829                 // Start the daemon
830                 $this->_readytogo = true;
831                 return false;
832             break;
833             case 'v':
834                 // Verbose mode
835                 $this->_trace_level = E_ALL;
836                 return false;
837             break;
838             case 'l':
839                 // Use logfile
840                 if(!empty($param)) {
841                     $this->_logfile_name = $param;
842                 }
843                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
844                 if($this->_logfile == false) {
845                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
846                 }
847                 return false;
848             default:
849                 // Unrecognized
850                 $this->fatal('Unrecognized command line switch: '.$switch);
851             break;
852         }
853         return false;
854     }
858 $DAEMON = New ChatDaemon;
859 set_error_handler(array($DAEMON, 'error_handler'));
861 /// Check the parameters //////////////////////////////////////////////////////
863 unset($argv[0]);
864 $commandline = implode(' ', $argv);
865 if(strpos($commandline, '-') === false) {
866     if(!empty($commandline)) {
867         // We cannot have received any meaningful parameters
868         $DAEMON->fatal('Garbage in command line');
869     }
871 else {
872     // Parse command line
873     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
875     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
876     // We will be using that to pass additional information to those switches who need it
877     $numswitches = count($switches);
879     // Fancy way to give a "hyphen" boolean flag to each "switch"
880     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
882     for($i = 0; $i < $numswitches; ++$i) {
884         $switch = $switches[$i]['str'];
885         $params = ($i == $numswitches - 1 ? NULL :
886                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
887                   );
889         if(substr($switch, 0, 2) == '--') {
890             // Double-hyphen switch
891             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
892         }
893         else if(substr($switch, 0, 1) == '-') {
894             // Single-hyphen switch(es), may be more than one run together
895             $switch = substr($switch, 1); // Get rid of the -
896             $len = strlen($switch);
897             for($j = 0; $j < $len; ++$j) {
898                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
899             }
900         }
901     }
904 if(!$DAEMON->query_start()) {
905     // For some reason we didn't start, so print out some info
906     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
907     echo "\n\n";
908     echo "Usage: chatd.php [parameters]\n\n";
909     echo "Parameters:\n";
910     echo "  --start         Starts the daemon\n";
911     echo "  -v              Verbose mode (prints trivial information messages)\n";
912     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
913     echo "Example:\n";
914     echo "  chatd.php --start -l\n\n";
915     die();
918 if (!function_exists('socket_setopt')) {
919     echo "Error: Function socket_setopt() does not exist.\n";
920     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
921     die();
924 $DAEMON->init_sockets();
926 /*
927 declare(ticks=1);
929 $pid = pcntl_fork();
930 if ($pid == -1) {
931      die("could not fork");
932 } else if ($pid) {
933      exit(); // we are the parent
934 } else {
935      // we are the child
938 // detatch from the controlling terminal
939 if (!posix_setsid()) {
940    die("could not detach from terminal");
943 // setup signal handlers
944 pcntl_signal(SIGTERM, "sig_handler");
945 pcntl_signal(SIGHUP, "sig_handler");
947 if($DAEMON->_pcntl_exists && false) {
948     $DAEMON->trace('Unholy spirit possession: daemonizing');
949     $DAEMON->pid = pcntl_fork();
950     if($pid == -1) {
951         $DAEMON->trace('Process fork failed, terminating');
952         die();
953     }
954     else if($pid) {
955         // We are the parent
956         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
957         die();
958     }
959     else {
960         // We are the daemon! :P
961     }
963     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
965     // Detach from controlling terminal
966     if(!posix_setsid()) {
967         $DAEMON->trace('Could not detach daemon process from terminal!');
968     }
970 else {
971     // Cannot go demonic
972     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
974 */
976 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
978 /// Clear the decks of old stuff
979 $DB->delete_records('chat_users', array('version'=>'sockets'));
981 while(true) {
982     $active = array();
984     // First of all, let's see if any of our UFOs has identified itself
985     if($DAEMON->conn_activity_ufo($active)) {
986         foreach($active as $handle) {
987             $read_socket = array($handle);
988             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
990             if($changed > 0) {
991                 // Let's see what it has to say
993                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
994                 if(empty($data)) {
995                     continue;
996                 }
998                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
999                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1000                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1001                     continue;
1002                 }
1004                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1005                     // Malformed data
1006                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1007                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1008                     continue;
1009                 }
1011                 $type      = $info[1];
1012                 $sessionid = $info[2];
1014                 $customdata = array();
1016                 switch($type) {
1017                     case 'chat':
1018                        $type = CHAT_CONNECTION_CHANNEL;
1019                         $customdata['quirks'] = 0;
1020                         if(strpos($data, 'Safari')) {
1021                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1022                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1023                         }
1024                     break;
1025                     case 'users':
1026                         $type = CHAT_SIDEKICK_USERS;
1027                     break;
1028                     case 'beep':
1029                         $type = CHAT_SIDEKICK_BEEP;
1030                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1031                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1032                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1033                             continue;
1034                         }
1035                         else {
1036                             $customdata = array('beep' => intval($info[1]));
1037                         }
1038                     break;
1039                     case 'message':
1040                         $type = CHAT_SIDEKICK_MESSAGE;
1041                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1042                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1043                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1044                             continue;
1045                         }
1046                         else {
1047                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1048                         }
1049                     break;
1050                     default:
1051                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1052                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1053                         continue;
1054                     break;
1055                 }
1057                 // OK, now we know it's something good... promote it and pass it all the data it needs
1058                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1059                 continue;
1060             }
1061         }
1062     }
1064     $now = time();
1066     // Clean up chatrooms with no activity as required
1067     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1068         $DAEMON->poll_idle_chats($now);
1069     }
1071     // Finally, accept new connections
1072     $DAEMON->conn_accept();
1074     usleep($DAEMON->_time_rest_socket);
1077 @socket_shutdown($DAEMON->listen_socket, 0);
1078 die("\n\n-- terminated --\n");