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