Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / mod / chat / chatd.php
blobd8d34fa483a4ee0ecb7efb990d040f11a874d918
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");
43 if(!empty($safemode)) {
44 die("Error: Cannot run with PHP safe_mode = On. Turn off safe_mode in php.ini.\n");
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");
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);
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);
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;
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);
117 return true;
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);
140 $this->_last_idle_poll = $now;
143 function query_start() {
144 return $this->_readytogo;
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;
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);
168 // Emit the message to wherever we should
169 if($this->_trace_to_stdout) {
170 fwrite($this->_stdout, $message);
171 fflush($this->_stdout);
173 if($this->_trace_to_console) {
174 echo $message;
175 flush();
177 if($this->_logfile) {
178 fwrite($this->_logfile, $message);
179 fflush($this->_logfile);
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;
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) {
200 // // ABOVE CODE GOES HERE
202 // }
203 // return false;
206 function user_lazy_update($sessionid) {
207 // TODO: this can and should be written as a single UPDATE query
208 if(empty($this->sets_info[$sessionid])) {
209 $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING);
210 return false;
213 $now = time();
215 // We 'll be cheating a little, and NOT updating the record data as
216 // often as we can, so that we save on DB queries (imagine MANY users)
217 if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) {
218 // commit to permanent storage
219 $this->sets_info[$sessionid]['lastinfocommit'] = $now;
220 update_record('chat_users', $this->sets_info[$sessionid]['chatuser']);
222 return true;
225 function get_user_window($sessionid) {
227 global $CFG;
229 static $str;
231 $info = &$this->sets_info[$sessionid];
232 course_setup($info['course'], $info['user']);
234 $timenow = time();
236 if (empty($str)) {
237 $str->idle = get_string("idle", "chat");
238 $str->beep = get_string("beep", "chat");
239 $str->day = get_string("day");
240 $str->days = get_string("days");
241 $str->hour = get_string("hour");
242 $str->hours = get_string("hours");
243 $str->min = get_string("min");
244 $str->mins = get_string("mins");
245 $str->sec = get_string("sec");
246 $str->secs = get_string("secs");
247 $str->years = get_string('years');
250 ob_start();
251 echo '<html><head>';
252 echo '<script text="text/javascript">';
253 echo "//<![CDATA[\n";
255 echo 'function openpopup(url,name,options,fullscreen) {';
256 echo 'fullurl = "'.$CFG->wwwroot.'" + url;';
257 echo 'windowobj = window.open(fullurl,name,options);';
258 echo 'if (fullscreen) {';
259 echo ' windowobj.moveTo(0,0);';
260 echo ' windowobj.resizeTo(screen.availWidth,screen.availHeight); ';
261 echo '}';
262 echo 'windowobj.focus();';
263 echo 'return false;';
264 echo "}\n//]]>\n";
265 echo '</script></head><body style="font-face: serif;" bgcolor="#FFFFFF">';
267 echo '<table style="width: 100%;"><tbody>';
269 // Get the users from that chatroom
270 $users = $this->chatrooms[$info['chatid']]['users'];
272 foreach ($users as $usersessionid => $userid) {
273 // Fetch each user's sessionid and then the rest of his data from $this->sets_info
274 $userinfo = $this->sets_info[$usersessionid];
276 $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
277 $popuppar = '\'/user/view.php?id='.$userinfo['user']->id.'&amp;course='.$userinfo['courseid'].'\',\'user'.$userinfo['chatuser']->id.'\',\'\'';
278 echo '<tr><td width="35">';
279 echo '<a target="_new" onclick="return openpopup('.$popuppar.');" href="'.$CFG->wwwroot.'/user/view.php?id='.$userinfo['chatuser']->id.'&amp;course='.$userinfo['courseid'].'">';
280 print_user_picture($userinfo['user']->id, 0, $userinfo['user']->picture, false, false, false);
281 echo "</a></td><td valign=\"center\">";
282 echo "<p><font size=\"1\">";
283 echo fullname($userinfo['user'])."<br />";
284 echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
285 echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
286 '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
287 echo "</font></p>";
288 echo "<td></tr>";
291 echo '</tbody></table>';
293 // About 2K of HTML comments to force browsers to render the HTML
294 // echo $GLOBALS['CHAT_DUMMY_DATA'];
296 echo "</body>\n</html>\n";
298 return ob_get_clean();
302 function new_ufo_id() {
303 static $id = 0;
304 if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
305 $id = 0;
307 return $id;
310 function process_sidekicks($sessionid) {
311 if(empty($this->conn_side[$sessionid])) {
312 return true;
314 foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
315 // TODO: is this late-dispatch working correctly?
316 $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
317 unset($this->conn_side[$sessionid][$sideid]);
319 return true;
322 function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
323 global $CFG;
325 switch($type) {
326 case CHAT_SIDEKICK_BEEP:
327 // Incoming beep
328 $msg = &New stdClass;
329 $msg->chatid = $this->sets_info[$sessionid]['chatid'];
330 $msg->userid = $this->sets_info[$sessionid]['userid'];
331 $msg->groupid = $this->sets_info[$sessionid]['groupid'];
332 $msg->system = 0;
333 $msg->message = 'beep '.$customdata['beep'];
334 $msg->timestamp = time();
336 // Commit to DB
337 insert_record('chat_messages', $msg, false);
339 // OK, now push it out to all users
340 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
342 // Update that user's lastmessageping
343 $this->sets_info[$sessionid]['chatuser']->lastping = $msg->timestamp;
344 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
345 $this->user_lazy_update($sessionid);
347 // We did our work, but before slamming the door on the poor browser
348 // show the courtesy of responding to the HTTP request. Otherwise, some
349 // browsers decide to get vengeance by flooding us with repeat requests.
351 $header = "HTTP/1.1 200 OK\n";
352 $header .= "Connection: close\n";
353 $header .= "Date: ".date('r')."\n";
354 $header .= "Server: Moodle\n";
355 $header .= "Content-Type: text/html\n";
356 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
357 $header .= "Cache-Control: no-cache, must-revalidate\n";
358 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
359 $header .= "\n";
361 // That's enough headers for one lousy dummy response
362 $this->write_data($handle, $header);
363 // All done
364 break;
366 case CHAT_SIDEKICK_USERS:
367 // A request to paint a user window
369 $content = $this->get_user_window($sessionid);
371 $header = "HTTP/1.1 200 OK\n";
372 $header .= "Connection: close\n";
373 $header .= "Date: ".date('r')."\n";
374 $header .= "Server: Moodle\n";
375 $header .= "Content-Type: text/html\n";
376 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
377 $header .= "Cache-Control: no-cache, must-revalidate\n";
378 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
379 $header .= "Content-Length: ".strlen($content)."\n";
381 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
382 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
383 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
384 "chat_sid=".$sessionid."\n";
385 $header .= "\n";
387 // That's enough headers for one lousy dummy response
388 $this->trace('writing users http response to handle '.$handle);
389 $this->write_data($handle, $header . $content);
391 // Update that user's lastping
392 $this->sets_info[$sessionid]['chatuser']->lastping = time();
393 $this->user_lazy_update($sessionid);
395 break;
397 case CHAT_SIDEKICK_MESSAGE:
398 // Incoming message
400 // Browser stupidity protection from duplicate messages:
401 $messageindex = intval($customdata['index']);
403 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
404 // We have already broadcasted that!
405 // $this->trace('discarding message with stale index');
406 break;
408 else {
409 // Update our info
410 $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
413 $msg = &New stdClass;
414 $msg->chatid = $this->sets_info[$sessionid]['chatid'];
415 $msg->userid = $this->sets_info[$sessionid]['userid'];
416 $msg->groupid = $this->sets_info[$sessionid]['groupid'];
417 $msg->system = 0;
418 $msg->message = urldecode($customdata['message']); // have to undo the browser's encoding
419 $msg->timestamp = time();
421 if(empty($msg->message)) {
422 // Someone just hit ENTER, send them on their way
423 break;
426 // A slight hack to prevent malformed SQL inserts
427 $origmsg = $msg->message;
428 $msg->message = addslashes($msg->message);
430 // Commit to DB
431 insert_record('chat_messages', $msg, false);
433 // Undo the hack
434 $msg->message = $origmsg;
436 // OK, now push it out to all users
437 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
439 // Update that user's lastmessageping
440 $this->sets_info[$sessionid]['chatuser']->lastping = $msg->timestamp;
441 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
442 $this->user_lazy_update($sessionid);
444 // We did our work, but before slamming the door on the poor browser
445 // show the courtesy of responding to the HTTP request. Otherwise, some
446 // browsers decide to get vengeance by flooding us with repeat requests.
448 $header = "HTTP/1.1 200 OK\n";
449 $header .= "Connection: close\n";
450 $header .= "Date: ".date('r')."\n";
451 $header .= "Server: Moodle\n";
452 $header .= "Content-Type: text/html\n";
453 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
454 $header .= "Cache-Control: no-cache, must-revalidate\n";
455 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
456 $header .= "\n";
458 // That's enough headers for one lousy dummy response
459 $this->write_data($handle, $header);
461 // All done
462 break;
465 socket_shutdown($handle);
466 socket_close($handle);
469 function promote_final($sessionid, $customdata) {
470 if(isset($this->conn_sets[$sessionid])) {
471 $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
472 return false;
475 $chatuser = get_record('chat_users', 'sid', $sessionid);
476 if($chatuser === false) {
477 $this->dismiss_half($sessionid);
478 return false;
480 $chat = get_record('chat', 'id', $chatuser->chatid);
481 if($chat === false) {
482 $this->dismiss_half($sessionid);
483 return false;
485 $user = get_record('user', 'id', $chatuser->userid);
486 if($user === false) {
487 $this->dismiss_half($sessionid);
488 return false;
490 $course = get_record('course', 'id', $chat->course); {
491 if($course === false) {
492 $this->dismiss_half($sessionid);
493 return false;
497 global $CHAT_HTMLHEAD_JS, $CFG;
499 $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
501 // This whole thing needs to be purged of redundant info, and the
502 // code base to follow suit. But AFTER development is done.
503 $this->sets_info[$sessionid] = array(
504 'lastinfocommit' => 0,
505 'lastmessageindex' => 0,
506 'course' => $course,
507 'courseid' => $course->id,
508 'chatuser' => $chatuser,
509 'chatid' => $chat->id,
510 'user' => $user,
511 'userid' => $user->id,
512 'groupid' => $chatuser->groupid,
513 'lang' => $chatuser->lang,
514 'quirks' => $customdata['quirks']
517 // If we know nothing about this chatroom, initialize it and add the user
518 if(!isset($this->chatrooms[$chat->id]['users'])) {
519 $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
521 else {
522 // Otherwise just add the user
523 $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
526 // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
528 $this->dismiss_half($sessionid, false);
529 $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
530 $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
532 // Finally, broadcast the "entered the chat" message
534 $msg = &New stdClass;
535 $msg->chatid = $chatuser->chatid;
536 $msg->userid = $chatuser->userid;
537 $msg->groupid = $chatuser->groupid;
538 $msg->system = 1;
539 $msg->message = 'enter';
540 $msg->timestamp = time();
542 insert_record('chat_messages', $msg, false);
543 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
545 return true;
548 function promote_ufo($handle, $type, $sessionid, $customdata) {
549 if(empty($this->conn_ufo)) {
550 return false;
552 foreach($this->conn_ufo as $id => $ufo) {
553 if($ufo->handle == $handle) {
554 // OK, got the id of the UFO, but what is it?
556 if($type & CHAT_SIDEKICK) {
557 // Is the main connection ready?
558 if(isset($this->conn_sets[$sessionid])) {
559 // Yes, so dispatch this sidekick now and be done with it
560 //$this->trace('Dispatching sidekick immediately');
561 $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
562 $this->dismiss_ufo($handle, false);
564 else {
565 // No, so put it in the waiting list
566 $this->trace('sidekick waiting');
567 $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
569 return true;
572 // If it's not a sidekick, at this point it can only be da man
574 if($type & CHAT_CONNECTION) {
575 // This forces a new connection right now...
576 $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
578 // Do we have such a connection active?
579 if(isset($this->conn_sets[$sessionid])) {
580 // Yes, so regrettably we cannot promote you
581 $this->trace('Connection rejected: session '.$sessionid.' is already final');
582 $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
583 return false;
586 // Join this with what we may have already
587 $this->conn_half[$sessionid][$type] = $handle;
589 // Do the bookkeeping
590 $this->promote_final($sessionid, $customdata);
592 // It's not an UFO anymore
593 $this->dismiss_ufo($handle, false);
595 // Dispatch waiting sidekicks
596 $this->process_sidekicks($sessionid);
598 return true;
602 return false;
605 function dismiss_half($sessionid, $disconnect = true) {
606 if(!isset($this->conn_half[$sessionid])) {
607 return false;
609 if($disconnect) {
610 foreach($this->conn_half[$sessionid] as $handle) {
611 @socket_shutdown($handle);
612 @socket_close($handle);
615 unset($this->conn_half[$sessionid]);
616 return true;
619 function dismiss_set($sessionid) {
620 if(!empty($this->conn_sets[$sessionid])) {
621 foreach($this->conn_sets[$sessionid] as $handle) {
622 // Since we want to dismiss this, don't generate any errors if it's dead already
623 @socket_shutdown($handle);
624 @socket_close($handle);
627 $chatroom = $this->sets_info[$sessionid]['chatid'];
628 $userid = $this->sets_info[$sessionid]['userid'];
629 unset($this->conn_sets[$sessionid]);
630 unset($this->sets_info[$sessionid]);
631 unset($this->chatrooms[$chatroom]['users'][$sessionid]);
632 $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
633 return true;
637 function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
638 if(empty($this->conn_ufo)) {
639 return false;
641 foreach($this->conn_ufo as $id => $ufo) {
642 if($ufo->handle == $handle) {
643 unset($this->conn_ufo[$id]);
644 if($disconnect) {
645 if(!empty($message)) {
646 $this->write_data($handle, $message."\n\n");
648 socket_shutdown($handle);
649 socket_close($handle);
651 return true;
654 return false;
657 function conn_accept() {
658 $read_socket = array($this->listen_socket);
659 $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
661 if(!$changed) {
662 return false;
664 $handle = socket_accept($this->listen_socket);
665 if(!$handle) {
666 return false;
669 $newconn = &New ChatConnection($handle);
670 $id = $this->new_ufo_id();
671 $this->conn_ufo[$id] = $newconn;
673 //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
676 function conn_activity_ufo (&$handles) {
677 $monitor = array();
678 if(!empty($this->conn_ufo)) {
679 foreach($this->conn_ufo as $ufoid => $ufo) {
680 $monitor[$ufoid] = $ufo->handle;
684 if(empty($monitor)) {
685 $handles = array();
686 return 0;
689 $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
690 $handles = $monitor;
692 return $retval;
695 function message_broadcast($message, $sender) {
696 if(empty($this->conn_sets)) {
697 return true;
700 $now = time();
702 // First of all, mark this chatroom as having had activity now
703 $this->chatrooms[$message->chatid]['lastactivity'] = $now;
705 foreach($this->sets_info as $sessionid => $info) {
706 // We need to get handles from users that are in the same chatroom, same group
707 if($info['chatid'] == $message->chatid &&
708 ($info['groupid'] == $message->groupid || $message->groupid == 0))
711 // Simply give them the message
712 course_setup($info['course'], $info['user']);
713 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
714 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
716 if($output->beep) {
717 $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
720 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
721 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
722 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
723 $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
726 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
727 $this->disconnect_session($sessionid);
729 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
734 function disconnect_session($sessionid) {
735 $info = $this->sets_info[$sessionid];
737 delete_records('chat_users', 'sid', $sessionid);
738 $msg = &New stdClass;
739 $msg->chatid = $info['chatid'];
740 $msg->userid = $info['userid'];
741 $msg->groupid = $info['groupid'];
742 $msg->system = 1;
743 $msg->message = 'exit';
744 $msg->timestamp = time();
746 $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
747 insert_record('chat_messages', $msg, false);
749 // *************************** IMPORTANT
751 // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
753 // **********************************************************************
754 $latesender = $info['user'];
755 $this->dismiss_set($sessionid);
756 $this->message_broadcast($msg, $latesender);
759 function fatal($message) {
760 $message .= "\n";
761 if($this->_logfile) {
762 $this->trace($message, E_USER_ERROR);
764 echo "FATAL ERROR:: $message\n";
765 die();
768 function init_sockets() {
769 global $CFG;
771 $this->trace('Setting up sockets');
773 if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
774 // Failed to create socket
775 $lasterr = socket_last_error();
776 $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
779 //socket_close($DAEMON->listen_socket);
780 //die();
782 if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
783 // Failed to bind socket
784 $lasterr = socket_last_error();
785 $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
788 if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
789 // Failed to get socket to listen
790 $lasterr = socket_last_error();
791 $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
794 // Socket has been initialized and is ready
795 $this->trace('Socket opened on port '.$CFG->chat_serverport);
797 // [pj]: I really must have a good read on sockets. What exactly does this do?
798 // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
799 socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
800 socket_set_nonblock($this->listen_socket);
803 function cli_switch($switch, $param = NULL) {
804 switch($switch) { //LOL
805 case 'reset':
806 // Reset sockets
807 $this->_resetsocket = true;
808 return false;
809 case 'start':
810 // Start the daemon
811 $this->_readytogo = true;
812 return false;
813 break;
814 case 'v':
815 // Verbose mode
816 $this->_trace_level = E_ALL;
817 return false;
818 break;
819 case 'l':
820 // Use logfile
821 if(!empty($param)) {
822 $this->_logfile_name = $param;
824 $this->_logfile = @fopen($this->_logfile_name, 'a+');
825 if($this->_logfile == false) {
826 $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
828 return false;
829 default:
830 // Unrecognized
831 $this->fatal('Unrecognized command line switch: '.$switch);
832 break;
834 return false;
839 $DAEMON = New ChatDaemon;
840 set_error_handler(array($DAEMON, 'error_handler'));
842 /// Check the parameters //////////////////////////////////////////////////////
844 unset($argv[0]);
845 $commandline = implode(' ', $argv);
846 if(strpos($commandline, '-') === false) {
847 if(!empty($commandline)) {
848 // We cannot have received any meaningful parameters
849 $DAEMON->fatal('Garbage in command line');
852 else {
853 // Parse command line
854 $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
856 // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
857 // We will be using that to pass additional information to those switches who need it
858 $numswitches = count($switches);
860 // Fancy way to give a "hyphen" boolean flag to each "switch"
861 $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
863 for($i = 0; $i < $numswitches; ++$i) {
865 $switch = $switches[$i]['str'];
866 $params = ($i == $numswitches - 1 ? NULL :
867 ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
870 if(substr($switch, 0, 2) == '--') {
871 // Double-hyphen switch
872 $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
874 else if(substr($switch, 0, 1) == '-') {
875 // Single-hyphen switch(es), may be more than one run together
876 $switch = substr($switch, 1); // Get rid of the -
877 $len = strlen($switch);
878 for($j = 0; $j < $len; ++$j) {
879 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
885 if(!$DAEMON->query_start()) {
886 // For some reason we didn't start, so print out some info
887 echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
888 echo "\n\n";
889 echo "Usage: chatd.php [parameters]\n\n";
890 echo "Parameters:\n";
891 echo " --start Starts the daemon\n";
892 echo " -v Verbose mode (prints trivial information messages)\n";
893 echo " -l [logfile] Log all messages to logfile (if not specified, chatd.log)\n";
894 echo "Example:\n";
895 echo " chatd.php --start -l\n\n";
896 die();
899 if (!function_exists('socket_setopt')) {
900 echo "Error: Function socket_setopt() does not exist.\n";
901 echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
902 die();
905 $DAEMON->init_sockets();
908 declare(ticks=1);
910 $pid = pcntl_fork();
911 if ($pid == -1) {
912 die("could not fork");
913 } else if ($pid) {
914 exit(); // we are the parent
915 } else {
916 // we are the child
919 // detatch from the controlling terminal
920 if (!posix_setsid()) {
921 die("could not detach from terminal");
924 // setup signal handlers
925 pcntl_signal(SIGTERM, "sig_handler");
926 pcntl_signal(SIGHUP, "sig_handler");
928 if($DAEMON->_pcntl_exists && false) {
929 $DAEMON->trace('Unholy spirit possession: daemonizing');
930 $DAEMON->pid = pcntl_fork();
931 if($pid == -1) {
932 $DAEMON->trace('Process fork failed, terminating');
933 die();
935 else if($pid) {
936 // We are the parent
937 $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
938 die();
940 else {
941 // We are the daemon! :P
944 // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
946 // Detach from controlling terminal
947 if(!posix_setsid()) {
948 $DAEMON->trace('Could not detach daemon process from terminal!');
951 else {
952 // Cannot go demonic
953 $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
957 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
959 /// Clear the decks of old stuff
960 delete_records('chat_users', 'version', 'sockets');
962 while(true) {
963 $active = array();
965 // First of all, let's see if any of our UFOs has identified itself
966 if($DAEMON->conn_activity_ufo($active)) {
967 foreach($active as $handle) {
968 $read_socket = array($handle);
969 $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
971 if($changed > 0) {
972 // Let's see what it has to say
974 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
975 if(empty($data)) {
976 continue;
979 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
980 $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
981 $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
982 continue;
985 if(!ereg('win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP', $data, $info)) {
986 // Malformed data
987 $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
988 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
989 continue;
992 $type = $info[1];
993 $sessionid = $info[2];
995 $customdata = array();
997 switch($type) {
998 case 'chat':
999 $type = CHAT_CONNECTION_CHANNEL;
1000 $customdata['quirks'] = 0;
1001 if(strpos($data, 'Safari')) {
1002 $DAEMON->trace('Safari identified...', E_USER_WARNING);
1003 $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1005 break;
1006 case 'users':
1007 $type = CHAT_SIDEKICK_USERS;
1008 break;
1009 case 'beep':
1010 $type = CHAT_SIDEKICK_BEEP;
1011 if(!ereg('beep=([^&]*)[& ]', $data, $info)) {
1012 $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1013 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1014 continue;
1016 else {
1017 $customdata = array('beep' => intval($info[1]));
1019 break;
1020 case 'message':
1021 $type = CHAT_SIDEKICK_MESSAGE;
1022 if(!ereg('chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]', $data, $info)) {
1023 $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1024 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1025 continue;
1027 else {
1028 $customdata = array('message' => $info[1], 'index' => $info[2]);
1030 break;
1031 default:
1032 $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1033 $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1034 continue;
1035 break;
1038 // OK, now we know it's something good... promote it and pass it all the data it needs
1039 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1040 continue;
1045 $now = time();
1047 // Clean up chatrooms with no activity as required
1048 if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1049 $DAEMON->poll_idle_chats($now);
1052 // Finally, accept new connections
1053 $DAEMON->conn_accept();
1055 usleep($DAEMON->_time_rest_socket);
1058 @socket_shutdown($DAEMON->listen_socket, 0);
1059 die("\n\n-- terminated --\n");