3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 define('CLI_SCRIPT', true);
28 require(dirname(dirname(dirname(__FILE__
))).'/config.php');
29 require_once($CFG->dirroot
. '/mod/chat/lib.php');
32 define('QUIRK_CHUNK_UPDATE', 0x0001);
34 // Connection telltale
35 define('CHAT_CONNECTION', 0x10);
36 // Connections: Incrementing sequence, 0x10 to 0x1f
37 define('CHAT_CONNECTION_CHANNEL', 0x11);
40 define('CHAT_SIDEKICK', 0x20);
41 // Sidekicks: Incrementing sequence, 0x21 to 0x2f
42 define('CHAT_SIDEKICK_USERS', 0x21);
43 define('CHAT_SIDEKICK_MESSAGE', 0x22);
44 define('CHAT_SIDEKICK_BEEP', 0x23);
46 $phpversion = phpversion();
47 echo 'Moodle chat daemon v1.0 on PHP '.$phpversion."\n\n";
49 /// Set up all the variables we need /////////////////////////////////////
51 /// $CFG variables are now defined in database by chat/lib.php
53 $_SERVER['PHP_SELF'] = 'dummy';
54 $_SERVER['SERVER_NAME'] = 'dummy';
55 $_SERVER['HTTP_USER_AGENT'] = 'dummy';
57 $_SERVER['SERVER_NAME'] = $CFG->chat_serverhost
;
58 $_SERVER['PHP_SELF'] = "http://$CFG->chat_serverhost:$CFG->chat_serverport/mod/chat/chatd.php";
60 $safemode = ini_get('safe_mode');
61 if(!empty($safemode)) {
62 die("Error: Cannot run with PHP safe_mode = On. Turn off safe_mode in php.ini.\n");
66 error_reporting(E_ALL
);
68 function chat_empty_connection() {
69 return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL);
72 class ChatConnection
{
76 //var $groupid = NULL;
85 function ChatConnection($resource) {
86 $this->handle
= $resource;
87 @socket_getpeername
($this->handle
, $this->ip
, $this->port
);
92 var $_resetsocket = false;
93 var $_readytogo = false;
94 var $_logfile = false;
95 var $_trace_to_console = true;
96 var $_trace_to_stdout = true;
97 var $_logfile_name = 'chatd.log';
98 var $_last_idle_poll = 0;
100 var $conn_ufo = array(); // Connections not identified yet
101 var $conn_side = array(); // Sessions with sidekicks waiting for the main connection to be processed
102 var $conn_half = array(); // Sessions that have valid connections but not all of them
103 var $conn_sets = array(); // Sessions with complete connection sets sets
104 var $sets_info = array(); // Keyed by sessionid exactly like conn_sets, one of these for each of those
105 var $chatrooms = array(); // Keyed by chatid, holding arrays of data
107 // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized!
108 // Pay extra attention when you write code that affects any of them!
110 function ChatDaemon() {
111 $this->_trace_level
= E_ALL ^ E_USER_NOTICE
;
112 $this->_pcntl_exists
= function_exists('pcntl_fork');
113 $this->_time_rest_socket
= 20;
114 $this->_beepsoundsrc
= $GLOBALS['CFG']->wwwroot
.'/mod/chat/beep.wav';
115 $this->_freq_update_records
= 20;
116 $this->_freq_poll_idle_chat
= $GLOBALS['CFG']->chat_old_ping
;
117 $this->_stdout
= fopen('php://stdout', 'w');
119 // Avoid double traces for everything
120 $this->_trace_to_console
= false;
124 function error_handler ($errno, $errmsg, $filename, $linenum, $vars) {
125 // Checks if an error needs to be suppressed due to @
126 if(error_reporting() != 0) {
127 $this->trace($errmsg.' on line '.$linenum, $errno);
132 function poll_idle_chats($now) {
133 $this->trace('Polling chats to detect disconnected users');
134 if(!empty($this->chatrooms
)) {
135 foreach($this->chatrooms
as $chatid => $chatroom) {
136 if(!empty($chatroom['users'])) {
137 foreach($chatroom['users'] as $sessionid => $userid) {
138 // We will be polling each user as required
139 $this->trace('...shall we poll '.$sessionid.'?');
140 if($this->sets_info
[$sessionid]['chatuser']->lastmessageping
< $this->_last_idle_poll
) {
141 $this->trace('YES!');
142 // This user hasn't been polled since his last message
143 if($this->write_data($this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
], '<!-- poll -->') === false) {
144 // User appears to have disconnected
145 $this->disconnect_session($sessionid);
152 $this->_last_idle_poll
= $now;
155 function query_start() {
156 return $this->_readytogo
;
159 function trace($message, $level = E_USER_NOTICE
) {
163 case E_USER_WARNING
: $severity = '*IMPORTANT* '; break;
164 case E_USER_ERROR
: $severity = ' *CRITICAL* '; break;
166 case E_WARNING
: $severity = ' *CRITICAL* [php] '; break;
169 $date = date('[Y-m-d H:i:s] ');
170 $message = $date.$severity.$message."\n";
172 if ($this->_trace_level
& $level) {
173 // It is accepted for output
175 // Error-class traces go to STDERR too
176 if($level & E_USER_ERROR
) {
177 fwrite(STDERR
, $message);
180 // Emit the message to wherever we should
181 if($this->_trace_to_stdout
) {
182 fwrite($this->_stdout
, $message);
183 fflush($this->_stdout
);
185 if($this->_trace_to_console
) {
189 if($this->_logfile
) {
190 fwrite($this->_logfile
, $message);
191 fflush($this->_logfile
);
196 function write_data($connection, $text) {
197 $written = @socket_write
($connection, $text, strlen($text));
198 if($written === false) {
199 // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)));
204 // Enclosing the above code inside this blocks makes sure that
205 // "a socket write operation will not block". I 'm not so sure
206 // if this is needed, as we have a nonblocking socket anyway.
207 // If trouble starts to creep up, we 'll restore this.
208 // $check_socket = array($connection);
209 // $socket_changed = socket_select($read = NULL, $check_socket, $except = NULL, 0, 0);
210 // if($socket_changed > 0) {
212 // // ABOVE CODE GOES HERE
218 function user_lazy_update($sessionid) {
221 // TODO: this can and should be written as a single UPDATE query
222 if(empty($this->sets_info
[$sessionid])) {
223 $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING
);
229 // We 'll be cheating a little, and NOT updating the record data as
230 // often as we can, so that we save on DB queries (imagine MANY users)
231 if($now - $this->sets_info
[$sessionid]['lastinfocommit'] > $this->_freq_update_records
) {
232 // commit to permanent storage
233 $this->sets_info
[$sessionid]['lastinfocommit'] = $now;
234 $DB->update_record('chat_users', $this->sets_info
[$sessionid]['chatuser']);
239 function get_user_window($sessionid) {
240 global $CFG, $OUTPUT;
244 $info = &$this->sets_info
[$sessionid];
249 $str->idle
= get_string("idle", "chat");
250 $str->beep
= get_string("beep", "chat");
251 $str->day
= get_string("day");
252 $str->days
= get_string("days");
253 $str->hour
= get_string("hour");
254 $str->hours
= get_string("hours");
255 $str->min
= get_string("min");
256 $str->mins
= get_string("mins");
257 $str->sec
= get_string("sec");
258 $str->secs
= get_string("secs");
259 $str->years
= get_string('years');
263 $refresh_inval = $CFG->chat_refresh_userlist
* 1000;
266 <meta http-equiv="refresh" content="$refresh_inval">
267 <style type="text/css"> img{border:0} </style>
268 <script type="text/javascript">
270 function openpopup(url,name,options,fullscreen) {
271 fullurl = "$CFG->wwwroot" + url;
272 windowobj = window.open(fullurl,name,options);
274 windowobj.moveTo(0,0);
275 windowobj.resizeTo(screen.availWidth,screen.availHeight);
281 </script></head><body><table><tbody>
284 // Get the users from that chatroom
285 $users = $this->chatrooms
[$info['chatid']]['users'];
287 foreach ($users as $usersessionid => $userid) {
288 // Fetch each user's sessionid and then the rest of his data from $this->sets_info
289 $userinfo = $this->sets_info
[$usersessionid];
291 $lastping = $timenow - $userinfo['chatuser']->lastmessageping
;
293 echo '<tr><td width="35">';
295 $link = '/user/view.php?id='.$userinfo['user']->id
.'&course='.$userinfo['courseid'];
296 $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
298 $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id
);
299 $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
302 echo "</td><td valign=\"center\">";
303 echo "<p><font size=\"1\">";
304 echo fullname($userinfo['user'])."<br />";
305 echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
306 echo '<a target="empty" href="http://'.$CFG->chat_serverhost
.':'.$CFG->chat_serverport
.'/?win=beep&beep='.$userinfo['user']->id
.
307 '&chat_sid='.$sessionid.'">'.$str->beep
."</a>\n";
312 echo '</tbody></table>';
314 // About 2K of HTML comments to force browsers to render the HTML
315 // echo $GLOBALS['CHAT_DUMMY_DATA'];
317 echo "</body>\n</html>\n";
319 return ob_get_clean();
323 function new_ufo_id() {
325 if($id++
=== 0x1000000) { // Cycling very very slowly to prevent overflow
331 function process_sidekicks($sessionid) {
332 if(empty($this->conn_side
[$sessionid])) {
335 foreach($this->conn_side
[$sessionid] as $sideid => $sidekick) {
336 // TODO: is this late-dispatch working correctly?
337 $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
338 unset($this->conn_side
[$sessionid][$sideid]);
343 function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
347 case CHAT_SIDEKICK_BEEP
:
350 $msg->chatid
= $this->sets_info
[$sessionid]['chatid'];
351 $msg->userid
= $this->sets_info
[$sessionid]['userid'];
352 $msg->groupid
= $this->sets_info
[$sessionid]['groupid'];
354 $msg->message
= 'beep '.$customdata['beep'];
355 $msg->timestamp
= time();
358 $DB->insert_record('chat_messages', $msg, false);
359 $DB->insert_record('chat_messages_current', $msg, false);
361 // OK, now push it out to all users
362 $this->message_broadcast($msg, $this->sets_info
[$sessionid]['user']);
364 // Update that user's lastmessageping
365 $this->sets_info
[$sessionid]['chatuser']->lastping
= $msg->timestamp
;
366 $this->sets_info
[$sessionid]['chatuser']->lastmessageping
= $msg->timestamp
;
367 $this->user_lazy_update($sessionid);
369 // We did our work, but before slamming the door on the poor browser
370 // show the courtesy of responding to the HTTP request. Otherwise, some
371 // browsers decide to get vengeance by flooding us with repeat requests.
373 $header = "HTTP/1.1 200 OK\n";
374 $header .= "Connection: close\n";
375 $header .= "Date: ".date('r')."\n";
376 $header .= "Server: Moodle\n";
377 $header .= "Content-Type: text/html; charset=utf-8\n";
378 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
379 $header .= "Cache-Control: no-cache, must-revalidate\n";
380 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
383 // That's enough headers for one lousy dummy response
384 $this->write_data($handle, $header);
388 case CHAT_SIDEKICK_USERS
:
389 // A request to paint a user window
391 $content = $this->get_user_window($sessionid);
393 $header = "HTTP/1.1 200 OK\n";
394 $header .= "Connection: close\n";
395 $header .= "Date: ".date('r')."\n";
396 $header .= "Server: Moodle\n";
397 $header .= "Content-Type: text/html; charset=utf-8\n";
398 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
399 $header .= "Cache-Control: no-cache, must-revalidate\n";
400 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
401 $header .= "Content-Length: ".strlen($content)."\n";
403 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
404 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
405 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist
) +
2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
406 "chat_sid=".$sessionid."\n";
409 // That's enough headers for one lousy dummy response
410 $this->trace('writing users http response to handle '.$handle);
411 $this->write_data($handle, $header . $content);
413 // Update that user's lastping
414 $this->sets_info
[$sessionid]['chatuser']->lastping
= time();
415 $this->user_lazy_update($sessionid);
419 case CHAT_SIDEKICK_MESSAGE
:
422 // Browser stupidity protection from duplicate messages:
423 $messageindex = intval($customdata['index']);
425 if($this->sets_info
[$sessionid]['lastmessageindex'] >= $messageindex) {
426 // We have already broadcasted that!
427 // $this->trace('discarding message with stale index');
432 $this->sets_info
[$sessionid]['lastmessageindex'] = $messageindex;
436 $msg->chatid
= $this->sets_info
[$sessionid]['chatid'];
437 $msg->userid
= $this->sets_info
[$sessionid]['userid'];
438 $msg->groupid
= $this->sets_info
[$sessionid]['groupid'];
440 $msg->message
= urldecode($customdata['message']); // have to undo the browser's encoding
441 $msg->timestamp
= time();
443 if(empty($msg->message
)) {
444 // Someone just hit ENTER, send them on their way
448 // A slight hack to prevent malformed SQL inserts
449 $origmsg = $msg->message
;
450 $msg->message
= $msg->message
;
453 $DB->insert_record('chat_messages', $msg, false);
454 $DB->insert_record('chat_messages_current', $msg, false);
457 $msg->message
= $origmsg;
459 // OK, now push it out to all users
460 $this->message_broadcast($msg, $this->sets_info
[$sessionid]['user']);
462 // Update that user's lastmessageping
463 $this->sets_info
[$sessionid]['chatuser']->lastping
= $msg->timestamp
;
464 $this->sets_info
[$sessionid]['chatuser']->lastmessageping
= $msg->timestamp
;
465 $this->user_lazy_update($sessionid);
467 // We did our work, but before slamming the door on the poor browser
468 // show the courtesy of responding to the HTTP request. Otherwise, some
469 // browsers decide to get vengeance by flooding us with repeat requests.
471 $header = "HTTP/1.1 200 OK\n";
472 $header .= "Connection: close\n";
473 $header .= "Date: ".date('r')."\n";
474 $header .= "Server: Moodle\n";
475 $header .= "Content-Type: text/html; charset=utf-8\n";
476 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
477 $header .= "Cache-Control: no-cache, must-revalidate\n";
478 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
481 // That's enough headers for one lousy dummy response
482 $this->write_data($handle, $header);
488 socket_shutdown($handle);
489 socket_close($handle);
492 function promote_final($sessionid, $customdata) {
495 if(isset($this->conn_sets
[$sessionid])) {
496 $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
500 $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
501 if($chatuser === false) {
502 $this->dismiss_half($sessionid);
505 $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid
));
506 if($chat === false) {
507 $this->dismiss_half($sessionid);
510 $user = $DB->get_record('user', array('id'=>$chatuser->userid
));
511 if($user === false) {
512 $this->dismiss_half($sessionid);
515 $course = $DB->get_record('course', array('id'=>$chat->course
));
516 if($course === false) {
517 $this->dismiss_half($sessionid);
521 global $CHAT_HTMLHEAD_JS, $CFG;
523 $this->conn_sets
[$sessionid] = $this->conn_half
[$sessionid];
525 // This whole thing needs to be purged of redundant info, and the
526 // code base to follow suit. But AFTER development is done.
527 $this->sets_info
[$sessionid] = array(
528 'lastinfocommit' => 0,
529 'lastmessageindex' => 0,
531 'courseid' => $course->id
,
532 'chatuser' => $chatuser,
533 'chatid' => $chat->id
,
535 'userid' => $user->id
,
536 'groupid' => $chatuser->groupid
,
537 'lang' => $chatuser->lang
,
538 'quirks' => $customdata['quirks']
541 // If we know nothing about this chatroom, initialize it and add the user
542 if(!isset($this->chatrooms
[$chat->id
]['users'])) {
543 $this->chatrooms
[$chat->id
]['users'] = array($sessionid => $user->id
);
546 // Otherwise just add the user
547 $this->chatrooms
[$chat->id
]['users'][$sessionid] = $user->id
;
550 // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
552 $header = "HTTP/1.1 200 OK\n";
553 $header .= "Connection: close\n";
554 $header .= "Date: ".date('r')."\n";
555 $header .= "Server: Moodle\n";
556 $header .= "Content-Type: text/html; charset=utf-8\n";
557 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
558 $header .= "Cache-Control: no-cache, must-revalidate\n";
559 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
562 $this->dismiss_half($sessionid, false);
563 $this->write_data($this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
], $header . $CHAT_HTMLHEAD_JS);
564 $this->trace('Connection accepted: '.$this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
].', SID: '.$sessionid.' UID: '.$chatuser->userid
.' GID: '.$chatuser->groupid
, E_USER_WARNING
);
566 // Finally, broadcast the "entered the chat" message
569 $msg->chatid
= $chatuser->chatid
;
570 $msg->userid
= $chatuser->userid
;
571 $msg->groupid
= $chatuser->groupid
;
573 $msg->message
= 'enter';
574 $msg->timestamp
= time();
576 $DB->insert_record('chat_messages', $msg, false);
577 $DB->insert_record('chat_messages_current', $msg, false);
578 $this->message_broadcast($msg, $this->sets_info
[$sessionid]['user']);
583 function promote_ufo($handle, $type, $sessionid, $customdata) {
584 if(empty($this->conn_ufo
)) {
587 foreach($this->conn_ufo
as $id => $ufo) {
588 if($ufo->handle
== $handle) {
589 // OK, got the id of the UFO, but what is it?
591 if($type & CHAT_SIDEKICK
) {
592 // Is the main connection ready?
593 if(isset($this->conn_sets
[$sessionid])) {
594 // Yes, so dispatch this sidekick now and be done with it
595 //$this->trace('Dispatching sidekick immediately');
596 $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
597 $this->dismiss_ufo($handle, false);
600 // No, so put it in the waiting list
601 $this->trace('sidekick waiting');
602 $this->conn_side
[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
607 // If it's not a sidekick, at this point it can only be da man
609 if($type & CHAT_CONNECTION
) {
610 // This forces a new connection right now...
611 $this->trace('Incoming connection from '.$ufo->ip
.':'.$ufo->port
);
613 // Do we have such a connection active?
614 if(isset($this->conn_sets
[$sessionid])) {
615 // Yes, so regrettably we cannot promote you
616 $this->trace('Connection rejected: session '.$sessionid.' is already final');
617 $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
621 // Join this with what we may have already
622 $this->conn_half
[$sessionid][$type] = $handle;
624 // Do the bookkeeping
625 $this->promote_final($sessionid, $customdata);
627 // It's not an UFO anymore
628 $this->dismiss_ufo($handle, false);
630 // Dispatch waiting sidekicks
631 $this->process_sidekicks($sessionid);
640 function dismiss_half($sessionid, $disconnect = true) {
641 if(!isset($this->conn_half
[$sessionid])) {
645 foreach($this->conn_half
[$sessionid] as $handle) {
646 @socket_shutdown
($handle);
647 @socket_close
($handle);
650 unset($this->conn_half
[$sessionid]);
654 function dismiss_set($sessionid) {
655 if(!empty($this->conn_sets
[$sessionid])) {
656 foreach($this->conn_sets
[$sessionid] as $handle) {
657 // Since we want to dismiss this, don't generate any errors if it's dead already
658 @socket_shutdown
($handle);
659 @socket_close
($handle);
662 $chatroom = $this->sets_info
[$sessionid]['chatid'];
663 $userid = $this->sets_info
[$sessionid]['userid'];
664 unset($this->conn_sets
[$sessionid]);
665 unset($this->sets_info
[$sessionid]);
666 unset($this->chatrooms
[$chatroom]['users'][$sessionid]);
667 $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE
);
672 function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
673 if(empty($this->conn_ufo
)) {
676 foreach($this->conn_ufo
as $id => $ufo) {
677 if($ufo->handle
== $handle) {
678 unset($this->conn_ufo
[$id]);
680 if(!empty($message)) {
681 $this->write_data($handle, $message."\n\n");
683 socket_shutdown($handle);
684 socket_close($handle);
692 function conn_accept() {
693 $read_socket = array($this->listen_socket
);
694 $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
699 $handle = socket_accept($this->listen_socket
);
704 $newconn = New ChatConnection($handle);
705 $id = $this->new_ufo_id();
706 $this->conn_ufo
[$id] = $newconn;
708 //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
711 function conn_activity_ufo (&$handles) {
713 if(!empty($this->conn_ufo
)) {
714 foreach($this->conn_ufo
as $ufoid => $ufo) {
715 $monitor[$ufoid] = $ufo->handle
;
719 if(empty($monitor)) {
724 $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
730 function message_broadcast($message, $sender) {
732 if(empty($this->conn_sets
)) {
738 // First of all, mark this chatroom as having had activity now
739 $this->chatrooms
[$message->chatid
]['lastactivity'] = $now;
741 foreach($this->sets_info
as $sessionid => $info) {
742 // We need to get handles from users that are in the same chatroom, same group
743 if($info['chatid'] == $message->chatid
&&
744 ($info['groupid'] == $message->groupid ||
$message->groupid
== 0))
747 // Simply give them the message
748 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
749 $this->trace('Delivering message "'.$output->text
.'" to '.$this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
]);
752 $this->write_data($this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
], '<embed src="'.$this->_beepsoundsrc
.'" autostart="true" hidden="true" />');
755 if($info['quirks'] & QUIRK_CHUNK_UPDATE
) {
756 $output->html
.= $GLOBALS['CHAT_DUMMY_DATA'];
757 $output->html
.= $GLOBALS['CHAT_DUMMY_DATA'];
758 $output->html
.= $GLOBALS['CHAT_DUMMY_DATA'];
761 if(!$this->write_data($this->conn_sets
[$sessionid][CHAT_CONNECTION_CHANNEL
], $output->html
)) {
762 $this->disconnect_session($sessionid);
764 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
769 function disconnect_session($sessionid) {
772 $info = $this->sets_info
[$sessionid];
774 $DB->delete_records('chat_users', array('sid'=>$sessionid));
776 $msg->chatid
= $info['chatid'];
777 $msg->userid
= $info['userid'];
778 $msg->groupid
= $info['groupid'];
780 $msg->message
= 'exit';
781 $msg->timestamp
= time();
783 $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING
);
784 $DB->insert_record('chat_messages', $msg, false);
785 $DB->insert_record('chat_messages_current', $msg, false);
787 // *************************** IMPORTANT
789 // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
791 // **********************************************************************
792 $latesender = $info['user'];
793 $this->dismiss_set($sessionid);
794 $this->message_broadcast($msg, $latesender);
797 function fatal($message) {
799 if($this->_logfile
) {
800 $this->trace($message, E_USER_ERROR
);
802 echo "FATAL ERROR:: $message\n";
806 function init_sockets() {
809 $this->trace('Setting up sockets');
811 if(false === ($this->listen_socket
= socket_create(AF_INET
, SOCK_STREAM
, 0))) {
812 // Failed to create socket
813 $lasterr = socket_last_error();
814 $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
817 //socket_close($DAEMON->listen_socket);
820 if(!socket_bind($this->listen_socket
, $CFG->chat_serverip
, $CFG->chat_serverport
)) {
821 // Failed to bind socket
822 $lasterr = socket_last_error();
823 $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
826 if(!socket_listen($this->listen_socket
, $CFG->chat_servermax
)) {
827 // Failed to get socket to listen
828 $lasterr = socket_last_error();
829 $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
832 // Socket has been initialized and is ready
833 $this->trace('Socket opened on port '.$CFG->chat_serverport
);
835 // [pj]: I really must have a good read on sockets. What exactly does this do?
836 // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
837 socket_set_option($this->listen_socket
, SOL_SOCKET
, SO_REUSEADDR
, 1);
838 socket_set_nonblock($this->listen_socket
);
841 function cli_switch($switch, $param = NULL) {
842 switch($switch) { //LOL
845 $this->_resetsocket
= true;
849 $this->_readytogo
= true;
854 $this->_trace_level
= E_ALL
;
860 $this->_logfile_name
= $param;
862 $this->_logfile
= @fopen
($this->_logfile_name
, 'a+');
863 if($this->_logfile
== false) {
864 $this->fatal('Failed to open '.$this->_logfile_name
.' for writing');
869 $this->fatal('Unrecognized command line switch: '.$switch);
877 $DAEMON = New ChatDaemon
;
878 set_error_handler(array($DAEMON, 'error_handler'));
880 /// Check the parameters //////////////////////////////////////////////////////
883 $commandline = implode(' ', $argv);
884 if(strpos($commandline, '-') === false) {
885 if(!empty($commandline)) {
886 // We cannot have received any meaningful parameters
887 $DAEMON->fatal('Garbage in command line');
891 // Parse command line
892 $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
894 // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
895 // We will be using that to pass additional information to those switches who need it
896 $numswitches = count($switches);
898 // Fancy way to give a "hyphen" boolean flag to each "switch"
899 $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
901 for($i = 0; $i < $numswitches; ++
$i) {
903 $switch = $switches[$i]['str'];
904 $params = ($i == $numswitches - 1 ?
NULL :
905 ($switches[$i +
1]['hyphen'] ?
NULL : trim($switches[$i +
1]['str']))
908 if(substr($switch, 0, 2) == '--') {
909 // Double-hyphen switch
910 $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
912 else if(substr($switch, 0, 1) == '-') {
913 // Single-hyphen switch(es), may be more than one run together
914 $switch = substr($switch, 1); // Get rid of the -
915 $len = strlen($switch);
916 for($j = 0; $j < $len; ++
$j) {
917 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
923 if(!$DAEMON->query_start()) {
924 // For some reason we didn't start, so print out some info
925 echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport
;
927 echo "Usage: chatd.php [parameters]\n\n";
928 echo "Parameters:\n";
929 echo " --start Starts the daemon\n";
930 echo " -v Verbose mode (prints trivial information messages)\n";
931 echo " -l [logfile] Log all messages to logfile (if not specified, chatd.log)\n";
933 echo " chatd.php --start -l\n\n";
937 if (!function_exists('socket_set_option')) {
938 echo "Error: Function socket_set_option() does not exist.\n";
939 echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
943 $DAEMON->init_sockets();
950 die("could not fork");
952 exit(); // we are the parent
957 // detatch from the controlling terminal
958 if (!posix_setsid()) {
959 die("could not detach from terminal");
962 // setup signal handlers
963 pcntl_signal(SIGTERM, "sig_handler");
964 pcntl_signal(SIGHUP, "sig_handler");
966 if($DAEMON->_pcntl_exists && false) {
967 $DAEMON->trace('Unholy spirit possession: daemonizing');
968 $DAEMON->pid = pcntl_fork();
970 $DAEMON->trace('Process fork failed, terminating');
975 $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
979 // We are the daemon! :P
982 // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
984 // Detach from controlling terminal
985 if(!posix_setsid()) {
986 $DAEMON->trace('Could not detach daemon process from terminal!');
991 $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
995 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport
.', listening socket '.$DAEMON->listen_socket
, E_USER_WARNING
);
997 /// Clear the decks of old stuff
998 $DB->delete_records('chat_users', array('version'=>'sockets'));
1003 // First of all, let's see if any of our UFOs has identified itself
1004 if($DAEMON->conn_activity_ufo($active)) {
1005 foreach($active as $handle) {
1006 $read_socket = array($handle);
1007 $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
1010 // Let's see what it has to say
1012 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
1017 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1018 $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING
);
1019 $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1023 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1025 $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING
);
1026 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1031 $sessionid = $info[2];
1033 $customdata = array();
1037 $type = CHAT_CONNECTION_CHANNEL
;
1038 $customdata['quirks'] = 0;
1039 if(strpos($data, 'Safari')) {
1040 $DAEMON->trace('Safari identified...', E_USER_WARNING
);
1041 $customdata['quirks'] +
= QUIRK_CHUNK_UPDATE
;
1045 $type = CHAT_SIDEKICK_USERS
;
1048 $type = CHAT_SIDEKICK_BEEP
;
1049 if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1050 $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING
);
1051 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1055 $customdata = array('beep' => intval($info[1]));
1059 $type = CHAT_SIDEKICK_MESSAGE
;
1060 if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1061 $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING
);
1062 $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1066 $customdata = array('message' => $info[1], 'index' => $info[2]);
1070 $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING
);
1071 $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1076 // OK, now we know it's something good... promote it and pass it all the data it needs
1077 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1085 // Clean up chatrooms with no activity as required
1086 if($now - $DAEMON->_last_idle_poll
>= $DAEMON->_freq_poll_idle_chat
) {
1087 $DAEMON->poll_idle_chats($now);
1090 // Finally, accept new connections
1091 $DAEMON->conn_accept();
1093 usleep($DAEMON->_time_rest_socket
);
1096 @socket_shutdown
($DAEMON->listen_socket
, 0);
1097 die("\n\n-- terminated --\n");