MDL-38243 mod_assessment: make assessment forms non-collapsible
[moodle.git] / mod / chat / chatd.php
bloba937b436852f145004ae66a9b1dc813ebdcbb840
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Chat daemon
21 * @package mod_chat
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');
31 // Browser quirks
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);
39 // Sidekick telltale
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");
65 @set_time_limit (0);
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 {
73 // Chat-related info
74 var $sid = NULL;
75 var $type = NULL;
76 //var $groupid = NULL;
78 // PHP-level info
79 var $handle = NULL;
81 // TCP/IP
82 var $ip = NULL;
83 var $port = NULL;
85 function ChatConnection($resource) {
86 $this->handle = $resource;
87 @socket_getpeername($this->handle, $this->ip, $this->port);
91 class ChatDaemon {
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');
118 if($this->_stdout) {
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);
129 return true;
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) {
160 $severity = '';
162 switch($level) {
163 case E_USER_WARNING: $severity = '*IMPORTANT* '; break;
164 case E_USER_ERROR: $severity = ' *CRITICAL* '; break;
165 case E_NOTICE:
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) {
186 echo $message;
187 flush();
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)));
200 return false;
202 return true;
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
214 // }
215 // return false;
218 function user_lazy_update($sessionid) {
219 global $DB;
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);
224 return false;
227 $now = time();
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']);
236 return true;
239 function get_user_window($sessionid) {
240 global $CFG, $OUTPUT;
242 static $str;
244 $info = &$this->sets_info[$sessionid];
246 $timenow = time();
248 if (empty($str)) {
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');
262 ob_start();
263 $refresh_inval = $CFG->chat_refresh_userlist * 1000;
264 echo <<<EOD
265 <html><head>
266 <meta http-equiv="refresh" content="$refresh_inval">
267 <style type="text/css"> img{border:0} </style>
268 <script type="text/javascript">
269 //<![CDATA[
270 function openpopup(url,name,options,fullscreen) {
271 fullurl = "$CFG->wwwroot" + url;
272 windowobj = window.open(fullurl,name,options);
273 if (fullscreen) {
274 windowobj.moveTo(0,0);
275 windowobj.resizeTo(screen.availWidth,screen.availHeight);
277 windowobj.focus();
278 return false;
280 //]]>
281 </script></head><body><table><tbody>
282 EOD;
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);
301 echo $anchortag;
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&amp;beep='.$userinfo['user']->id.
307 '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
308 echo "</font></p>";
309 echo "<td></tr>";
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() {
324 static $id = 0;
325 if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
326 $id = 0;
328 return $id;
331 function process_sidekicks($sessionid) {
332 if(empty($this->conn_side[$sessionid])) {
333 return true;
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]);
340 return true;
343 function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
344 global $CFG, $DB;
346 switch($type) {
347 case CHAT_SIDEKICK_BEEP:
348 // Incoming beep
349 $msg = New stdClass;
350 $msg->chatid = $this->sets_info[$sessionid]['chatid'];
351 $msg->userid = $this->sets_info[$sessionid]['userid'];
352 $msg->groupid = $this->sets_info[$sessionid]['groupid'];
353 $msg->system = 0;
354 $msg->message = 'beep '.$customdata['beep'];
355 $msg->timestamp = time();
357 // Commit to DB
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";
381 $header .= "\n";
383 // That's enough headers for one lousy dummy response
384 $this->write_data($handle, $header);
385 // All done
386 break;
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";
407 $header .= "\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);
417 break;
419 case CHAT_SIDEKICK_MESSAGE:
420 // Incoming 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');
428 break;
430 else {
431 // Update our info
432 $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
435 $msg = New stdClass;
436 $msg->chatid = $this->sets_info[$sessionid]['chatid'];
437 $msg->userid = $this->sets_info[$sessionid]['userid'];
438 $msg->groupid = $this->sets_info[$sessionid]['groupid'];
439 $msg->system = 0;
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
445 break;
448 // A slight hack to prevent malformed SQL inserts
449 $origmsg = $msg->message;
450 $msg->message = $msg->message;
452 // Commit to DB
453 $DB->insert_record('chat_messages', $msg, false);
454 $DB->insert_record('chat_messages_current', $msg, false);
456 // Undo the hack
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";
479 $header .= "\n";
481 // That's enough headers for one lousy dummy response
482 $this->write_data($handle, $header);
484 // All done
485 break;
488 socket_shutdown($handle);
489 socket_close($handle);
492 function promote_final($sessionid, $customdata) {
493 global $DB;
495 if(isset($this->conn_sets[$sessionid])) {
496 $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
497 return false;
500 $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
501 if($chatuser === false) {
502 $this->dismiss_half($sessionid);
503 return false;
505 $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
506 if($chat === false) {
507 $this->dismiss_half($sessionid);
508 return false;
510 $user = $DB->get_record('user', array('id'=>$chatuser->userid));
511 if($user === false) {
512 $this->dismiss_half($sessionid);
513 return false;
515 $course = $DB->get_record('course', array('id'=>$chat->course));
516 if($course === false) {
517 $this->dismiss_half($sessionid);
518 return false;
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,
530 'course' => $course,
531 'courseid' => $course->id,
532 'chatuser' => $chatuser,
533 'chatid' => $chat->id,
534 'user' => $user,
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);
545 else {
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";
560 $header .= "\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
568 $msg = new stdClass;
569 $msg->chatid = $chatuser->chatid;
570 $msg->userid = $chatuser->userid;
571 $msg->groupid = $chatuser->groupid;
572 $msg->system = 1;
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']);
580 return true;
583 function promote_ufo($handle, $type, $sessionid, $customdata) {
584 if(empty($this->conn_ufo)) {
585 return false;
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);
599 else {
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);
604 return true;
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.');
618 return false;
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);
633 return true;
637 return false;
640 function dismiss_half($sessionid, $disconnect = true) {
641 if(!isset($this->conn_half[$sessionid])) {
642 return false;
644 if($disconnect) {
645 foreach($this->conn_half[$sessionid] as $handle) {
646 @socket_shutdown($handle);
647 @socket_close($handle);
650 unset($this->conn_half[$sessionid]);
651 return true;
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);
668 return true;
672 function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
673 if(empty($this->conn_ufo)) {
674 return false;
676 foreach($this->conn_ufo as $id => $ufo) {
677 if($ufo->handle == $handle) {
678 unset($this->conn_ufo[$id]);
679 if($disconnect) {
680 if(!empty($message)) {
681 $this->write_data($handle, $message."\n\n");
683 socket_shutdown($handle);
684 socket_close($handle);
686 return true;
689 return false;
692 function conn_accept() {
693 $read_socket = array($this->listen_socket);
694 $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
696 if(!$changed) {
697 return false;
699 $handle = socket_accept($this->listen_socket);
700 if(!$handle) {
701 return false;
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) {
712 $monitor = array();
713 if(!empty($this->conn_ufo)) {
714 foreach($this->conn_ufo as $ufoid => $ufo) {
715 $monitor[$ufoid] = $ufo->handle;
719 if(empty($monitor)) {
720 $handles = array();
721 return 0;
724 $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
725 $handles = $monitor;
727 return $retval;
730 function message_broadcast($message, $sender) {
732 if(empty($this->conn_sets)) {
733 return true;
736 $now = time();
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]);
751 if($output->beep) {
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) {
770 global $DB;
772 $info = $this->sets_info[$sessionid];
774 $DB->delete_records('chat_users', array('sid'=>$sessionid));
775 $msg = New stdClass;
776 $msg->chatid = $info['chatid'];
777 $msg->userid = $info['userid'];
778 $msg->groupid = $info['groupid'];
779 $msg->system = 1;
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) {
798 $message .= "\n";
799 if($this->_logfile) {
800 $this->trace($message, E_USER_ERROR);
802 echo "FATAL ERROR:: $message\n";
803 die();
806 function init_sockets() {
807 global $CFG;
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);
818 //die();
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
843 case 'reset':
844 // Reset sockets
845 $this->_resetsocket = true;
846 return false;
847 case 'start':
848 // Start the daemon
849 $this->_readytogo = true;
850 return false;
851 break;
852 case 'v':
853 // Verbose mode
854 $this->_trace_level = E_ALL;
855 return false;
856 break;
857 case 'l':
858 // Use logfile
859 if(!empty($param)) {
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');
866 return false;
867 default:
868 // Unrecognized
869 $this->fatal('Unrecognized command line switch: '.$switch);
870 break;
872 return false;
877 $DAEMON = New ChatDaemon;
878 set_error_handler(array($DAEMON, 'error_handler'));
880 /// Check the parameters //////////////////////////////////////////////////////
882 unset($argv[0]);
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');
890 else {
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;
926 echo "\n\n";
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";
932 echo "Example:\n";
933 echo " chatd.php --start -l\n\n";
934 die();
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";
940 die();
943 $DAEMON->init_sockets();
946 declare(ticks=1);
948 $pid = pcntl_fork();
949 if ($pid == -1) {
950 die("could not fork");
951 } else if ($pid) {
952 exit(); // we are the parent
953 } else {
954 // we are the child
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();
969 if($pid == -1) {
970 $DAEMON->trace('Process fork failed, terminating');
971 die();
973 else if($pid) {
974 // We are the parent
975 $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
976 die();
978 else {
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!');
989 else {
990 // Cannot go demonic
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'));
1000 while(true) {
1001 $active = array();
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);
1009 if($changed > 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!!
1013 if(empty($data)) {
1014 continue;
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');
1020 continue;
1023 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1024 // Malformed data
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');
1027 continue;
1030 $type = $info[1];
1031 $sessionid = $info[2];
1033 $customdata = array();
1035 switch($type) {
1036 case 'chat':
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;
1043 break;
1044 case 'users':
1045 $type = CHAT_SIDEKICK_USERS;
1046 break;
1047 case 'beep':
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');
1052 continue;
1054 else {
1055 $customdata = array('beep' => intval($info[1]));
1057 break;
1058 case 'message':
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');
1063 continue;
1065 else {
1066 $customdata = array('message' => $info[1], 'index' => $info[2]);
1068 break;
1069 default:
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');
1072 continue;
1073 break;
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);
1078 continue;
1083 $now = time();
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");