MDL-27398 mod_chat Adding CLI_SCRIPT to chat daemon
[moodle.git] / mod / chat / chatd.php
1 #!/usr/bin/php -q
2 <?php
4 define('CLI_SCRIPT', true);
6 // Browser quirks
7 define('QUIRK_CHUNK_UPDATE', 0x0001);
9 // Connection telltale
10 define('CHAT_CONNECTION',           0x10);
11 // Connections: Incrementing sequence, 0x10 to 0x1f
12 define('CHAT_CONNECTION_CHANNEL',   0x11);
14 // Sidekick telltale
15 define('CHAT_SIDEKICK',             0x20);
16 // Sidekicks: Incrementing sequence, 0x21 to 0x2f
17 define('CHAT_SIDEKICK_USERS',       0x21);
18 define('CHAT_SIDEKICK_MESSAGE',     0x22);
19 define('CHAT_SIDEKICK_BEEP',        0x23);
21 $phpversion = phpversion();
22 echo 'Moodle chat daemon v1.0 on PHP '.$phpversion."\n\n";
24 /// Set up all the variables we need   /////////////////////////////////////
26 /// $CFG variables are now defined in database by chat/lib.php
28 $_SERVER['PHP_SELF']        = 'dummy';
29 $_SERVER['SERVER_NAME']     = 'dummy';
30 $_SERVER['HTTP_USER_AGENT'] = 'dummy';
32 define('NO_MOODLE_COOKIES', true); // session not used here
34 include('../../config.php');
35 include('lib.php');
37 $_SERVER['SERVER_NAME'] = $CFG->chat_serverhost;
38 $_SERVER['PHP_SELF']    = "http://$CFG->chat_serverhost:$CFG->chat_serverport/mod/chat/chatd.php";
40 $safemode = ini_get('safe_mode');
42 if($phpversion < '4.3') {
43     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");
44 }
45 if(!empty($safemode)) {
46     die("Error: Cannot run with PHP safe_mode = On. Turn off safe_mode in php.ini.\n");
47 }
49 $passref = ini_get('allow_call_time_pass_reference');
50 if(empty($passref)) {
51     die("Error: Cannot run with PHP allow_call_time_pass_reference = Off. Turn on allow_call_time_pass_reference in php.ini.\n");
52 }
54 @set_time_limit (0);
55 set_magic_quotes_runtime(0);
56 error_reporting(E_ALL);
58 function chat_empty_connection() {
59     return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL);
60 }
62 class ChatConnection {
63     // Chat-related info
64     var $sid    = NULL;
65     var $type   = NULL;
66     //var $groupid        = NULL;
68     // PHP-level info
69     var $handle = NULL;
71     // TCP/IP
72     var $ip     = NULL;
73     var $port   = NULL;
75     function ChatConnection($resource) {
76         $this->handle = $resource;
77         @socket_getpeername($this->handle, $this->ip, $this->port);
78     }
79 }
81 class ChatDaemon {
82     var $_resetsocket       = false;
83     var $_readytogo         = false;
84     var $_logfile           = false;
85     var $_trace_to_console  = true;
86     var $_trace_to_stdout   = true;
87     var $_logfile_name      = 'chatd.log';
88     var $_last_idle_poll    = 0;
90     var $conn_ufo  = array();    // Connections not identified yet
91     var $conn_side = array();    // Sessions with sidekicks waiting for the main connection to be processed
92     var $conn_half = array();    // Sessions that have valid connections but not all of them
93     var $conn_sets = array();    // Sessions with complete connection sets sets
94     var $sets_info = array();    // Keyed by sessionid exactly like conn_sets, one of these for each of those
95     var $chatrooms = array();    // Keyed by chatid, holding arrays of data
97     // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized!
98     //            Pay extra attention when you write code that affects any of them!
100     function ChatDaemon() {
101         $this->_trace_level         = E_ALL ^ E_USER_NOTICE;
102         $this->_pcntl_exists        = function_exists('pcntl_fork');
103         $this->_time_rest_socket    = 20;
104         $this->_beepsoundsrc        = $GLOBALS['CFG']->wwwroot.'/mod/chat/beep.wav';
105         $this->_freq_update_records = 20;
106         $this->_freq_poll_idle_chat = $GLOBALS['CFG']->chat_old_ping;
107         $this->_stdout = fopen('php://stdout', 'w');
108         if($this->_stdout) {
109             // Avoid double traces for everything
110             $this->_trace_to_console = false;
111         }
112     }
114     function error_handler ($errno, $errmsg, $filename, $linenum, $vars) {
115         // Checks if an error needs to be suppressed due to @
116         if(error_reporting() != 0) {
117             $this->trace($errmsg.' on line '.$linenum, $errno);
118         }
119         return true;
120     }
122     function poll_idle_chats($now) {
123         $this->trace('Polling chats to detect disconnected users');
124         if(!empty($this->chatrooms)) {
125             foreach($this->chatrooms as $chatid => $chatroom) {
126                 if(!empty($chatroom['users'])) {
127                     foreach($chatroom['users'] as $sessionid => $userid) {
128                         // We will be polling each user as required
129                         $this->trace('...shall we poll '.$sessionid.'?');
130                         if($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) {
131                             $this->trace('YES!');
132                             // This user hasn't been polled since his last message
133                             if($this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<!-- poll -->') === false) {
134                                 // User appears to have disconnected
135                                 $this->disconnect_session($sessionid);
136                             }
137                         }
138                     }
139                 }
140             }
141         }
142         $this->_last_idle_poll = $now;
143     }
145     function query_start() {
146         return $this->_readytogo;
147     }
149     function trace($message, $level = E_USER_NOTICE) {
150         $severity = '';
152         switch($level) {
153             case E_USER_WARNING: $severity = '*IMPORTANT* '; break;
154             case E_USER_ERROR:   $severity = ' *CRITICAL* '; break;
155             case E_NOTICE:
156             case E_WARNING:      $severity = ' *CRITICAL* [php] '; break;
157         }
159         $date = date('[Y-m-d H:i:s] ');
160         $message = $date.$severity.$message."\n";
162         if ($this->_trace_level & $level) {
163             // It is accepted for output
165             // Error-class traces go to STDERR too
166             if($level & E_USER_ERROR) {
167                 fwrite(STDERR, $message);
168             }
170             // Emit the message to wherever we should
171             if($this->_trace_to_stdout) {
172                 fwrite($this->_stdout, $message);
173                 fflush($this->_stdout);
174             }
175             if($this->_trace_to_console) {
176                 echo $message;
177                 flush();
178             }
179             if($this->_logfile) {
180                 fwrite($this->_logfile, $message);
181                 fflush($this->_logfile);
182             }
183         }
184     }
186     function write_data($connection, $text) {
187         $written = @socket_write($connection, $text, strlen($text));
188         if($written === false) {
189             // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)));
190             return false;
191         }
192         return true;
194         // Enclosing the above code inside this blocks makes sure that
195         // "a socket write operation will not block". I 'm not so sure
196         // if this is needed, as we have a nonblocking socket anyway.
197         // If trouble starts to creep up, we 'll restore this.
198 //        $check_socket = array($connection);
199 //        $socket_changed = socket_select($read = NULL, $check_socket, $except = NULL, 0, 0);
200 //        if($socket_changed > 0) {
201 //
202 //            // ABOVE CODE GOES HERE
203 //
204 //        }
205 //        return false;
206     }
208     function user_lazy_update($sessionid) {
209         global $DB;
211         // TODO: this can and should be written as a single UPDATE query
212         if(empty($this->sets_info[$sessionid])) {
213             $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING);
214             return false;
215         }
217         $now = time();
219         // We 'll be cheating a little, and NOT updating the record data as
220         // often as we can, so that we save on DB queries (imagine MANY users)
221         if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) {
222             // commit to permanent storage
223             $this->sets_info[$sessionid]['lastinfocommit'] = $now;
224             $DB->update_record('chat_users', $this->sets_info[$sessionid]['chatuser']);
225         }
226         return true;
227     }
229     function get_user_window($sessionid) {
230         global $CFG, $PAGE, $OUTPUT;
232         static $str;
234         $info = &$this->sets_info[$sessionid];
235         $PAGE->set_course($info['course']);
237         $timenow = time();
239         if (empty($str)) {
240             $str->idle  = get_string("idle", "chat");
241             $str->beep  = get_string("beep", "chat");
242             $str->day   = get_string("day");
243             $str->days  = get_string("days");
244             $str->hour  = get_string("hour");
245             $str->hours = get_string("hours");
246             $str->min   = get_string("min");
247             $str->mins  = get_string("mins");
248             $str->sec   = get_string("sec");
249             $str->secs  = get_string("secs");
250             $str->years = get_string('years');
251         }
253         ob_start();
254         $refresh_inval = $CFG->chat_refresh_userlist * 1000;
255         echo <<<EOD
256         <html><head>
257         <meta http-equiv="refresh" content="$refresh_inval">
258         <style type="text/css"> img{border:0} </style>
259         <script type="text/javascript">
260         //<![CDATA[
261         function openpopup(url,name,options,fullscreen) {
262             fullurl = "$CFG->wwwroot" + url;
263             windowobj = window.open(fullurl,name,options);
264             if (fullscreen) {
265                 windowobj.moveTo(0,0);
266                 windowobj.resizeTo(screen.availWidth,screen.availHeight);
267             }
268             windowobj.focus();
269             return false;
270         }
271         //]]>
272         </script></head><body><table><tbody>
273 EOD;
275         // Get the users from that chatroom
276         $users = $this->chatrooms[$info['chatid']]['users'];
278         foreach ($users as $usersessionid => $userid) {
279             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
280             $userinfo = $this->sets_info[$usersessionid];
282             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
284             echo '<tr><td width="35">';
286             $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid'];
287             $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
289             $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id);
290             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
292             echo $anchortag;
293             echo "</td><td valign=\"center\">";
294             echo "<p><font size=\"1\">";
295             echo fullname($userinfo['user'])."<br />";
296             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
297             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
298                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
299             echo "</font></p>";
300             echo "<td></tr>";
301         }
303         echo '</tbody></table>';
305         // About 2K of HTML comments to force browsers to render the HTML
306         // echo $GLOBALS['CHAT_DUMMY_DATA'];
308         echo "</body>\n</html>\n";
310         return ob_get_clean();
312     }
314     function new_ufo_id() {
315         static $id = 0;
316         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
317             $id = 0;
318         }
319         return $id;
320     }
322     function process_sidekicks($sessionid) {
323         if(empty($this->conn_side[$sessionid])) {
324             return true;
325         }
326         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
327             // TODO: is this late-dispatch working correctly?
328             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
329             unset($this->conn_side[$sessionid][$sideid]);
330         }
331         return true;
332     }
334     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
335         global $CFG, $DB;
337         switch($type) {
338             case CHAT_SIDEKICK_BEEP:
339                 // Incoming beep
340                 $msg = New stdClass;
341                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
342                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
343                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
344                 $msg->system    = 0;
345                 $msg->message   = 'beep '.$customdata['beep'];
346                 $msg->timestamp = time();
348                 // Commit to DB
349                 $DB->insert_record('chat_messages', $msg, false);
350                 $DB->insert_record('chat_messages_current', $msg, false);
352                 // OK, now push it out to all users
353                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
355                 // Update that user's lastmessageping
356                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
357                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
358                 $this->user_lazy_update($sessionid);
360                 // We did our work, but before slamming the door on the poor browser
361                 // show the courtesy of responding to the HTTP request. Otherwise, some
362                 // browsers decide to get vengeance by flooding us with repeat requests.
364                 $header  = "HTTP/1.1 200 OK\n";
365                 $header .= "Connection: close\n";
366                 $header .= "Date: ".date('r')."\n";
367                 $header .= "Server: Moodle\n";
368                 $header .= "Content-Type: text/html; charset=utf-8\n";
369                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
370                 $header .= "Cache-Control: no-cache, must-revalidate\n";
371                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
372                 $header .= "\n";
374                 // That's enough headers for one lousy dummy response
375                 $this->write_data($handle, $header);
376                 // All done
377             break;
379             case CHAT_SIDEKICK_USERS:
380                 // A request to paint a user window
382                 $content = $this->get_user_window($sessionid);
384                 $header  = "HTTP/1.1 200 OK\n";
385                 $header .= "Connection: close\n";
386                 $header .= "Date: ".date('r')."\n";
387                 $header .= "Server: Moodle\n";
388                 $header .= "Content-Type: text/html; charset=utf-8\n";
389                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
390                 $header .= "Cache-Control: no-cache, must-revalidate\n";
391                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
392                 $header .= "Content-Length: ".strlen($content)."\n";
394                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
395                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
396                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
397                            "chat_sid=".$sessionid."\n";
398                 $header .= "\n";
400                 // That's enough headers for one lousy dummy response
401                 $this->trace('writing users http response to handle '.$handle);
402                 $this->write_data($handle, $header . $content);
404                 // Update that user's lastping
405                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
406                 $this->user_lazy_update($sessionid);
408             break;
410             case CHAT_SIDEKICK_MESSAGE:
411                 // Incoming message
413                 // Browser stupidity protection from duplicate messages:
414                 $messageindex = intval($customdata['index']);
416                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
417                     // We have already broadcasted that!
418                     // $this->trace('discarding message with stale index');
419                     break;
420                 }
421                 else {
422                     // Update our info
423                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
424                 }
426                 $msg = New stdClass;
427                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
428                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
429                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
430                 $msg->system    = 0;
431                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
432                 $msg->timestamp = time();
434                 if(empty($msg->message)) {
435                     // Someone just hit ENTER, send them on their way
436                     break;
437                 }
439                 // A slight hack to prevent malformed SQL inserts
440                 $origmsg = $msg->message;
441                 $msg->message = $msg->message;
443                 // Commit to DB
444                 $DB->insert_record('chat_messages', $msg, false);
445                 $DB->insert_record('chat_messages_current', $msg, false);
447                 // Undo the hack
448                 $msg->message = $origmsg;
450                 // OK, now push it out to all users
451                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
453                 // Update that user's lastmessageping
454                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
455                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
456                 $this->user_lazy_update($sessionid);
458                 // We did our work, but before slamming the door on the poor browser
459                 // show the courtesy of responding to the HTTP request. Otherwise, some
460                 // browsers decide to get vengeance by flooding us with repeat requests.
462                 $header  = "HTTP/1.1 200 OK\n";
463                 $header .= "Connection: close\n";
464                 $header .= "Date: ".date('r')."\n";
465                 $header .= "Server: Moodle\n";
466                 $header .= "Content-Type: text/html; charset=utf-8\n";
467                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
468                 $header .= "Cache-Control: no-cache, must-revalidate\n";
469                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
470                 $header .= "\n";
472                 // That's enough headers for one lousy dummy response
473                 $this->write_data($handle, $header);
475                 // All done
476             break;
477         }
479         socket_shutdown($handle);
480         socket_close($handle);
481     }
483     function promote_final($sessionid, $customdata) {
484         global $DB;
486         if(isset($this->conn_sets[$sessionid])) {
487             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
488             return false;
489         }
491         $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
492         if($chatuser === false) {
493             $this->dismiss_half($sessionid);
494             return false;
495         }
496         $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
497         if($chat === false) {
498             $this->dismiss_half($sessionid);
499             return false;
500         }
501         $user = $DB->get_record('user', array('id'=>$chatuser->userid));
502         if($user === false) {
503             $this->dismiss_half($sessionid);
504             return false;
505         }
506         $course = $DB->get_record('course', array('id'=>$chat->course));
507         if($course === false) {
508             $this->dismiss_half($sessionid);
509             return false;
510         }
512         global $CHAT_HTMLHEAD_JS, $CFG;
514         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
516         // This whole thing needs to be purged of redundant info, and the
517         // code base to follow suit. But AFTER development is done.
518         $this->sets_info[$sessionid] = array(
519             'lastinfocommit' => 0,
520             'lastmessageindex' => 0,
521             'course'    => $course,
522             'courseid'  => $course->id,
523             'chatuser'  => $chatuser,
524             'chatid'    => $chat->id,
525             'user'      => $user,
526             'userid'    => $user->id,
527             'groupid'   => $chatuser->groupid,
528             'lang'      => $chatuser->lang,
529             'quirks'    => $customdata['quirks']
530         );
532         // If we know nothing about this chatroom, initialize it and add the user
533         if(!isset($this->chatrooms[$chat->id]['users'])) {
534             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
535         }
536         else {
537             // Otherwise just add the user
538             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
539         }
541         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
543         $this->dismiss_half($sessionid, false);
544         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
545         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
547         // Finally, broadcast the "entered the chat" message
549         $msg = new stdClass;
550         $msg->chatid = $chatuser->chatid;
551         $msg->userid = $chatuser->userid;
552         $msg->groupid = $chatuser->groupid;
553         $msg->system = 1;
554         $msg->message = 'enter';
555         $msg->timestamp = time();
557         $DB->insert_record('chat_messages', $msg, false);
558         $DB->insert_record('chat_messages_current', $msg, false);
559         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
561         return true;
562     }
564     function promote_ufo($handle, $type, $sessionid, $customdata) {
565         if(empty($this->conn_ufo)) {
566             return false;
567         }
568         foreach($this->conn_ufo as $id => $ufo) {
569             if($ufo->handle == $handle) {
570                 // OK, got the id of the UFO, but what is it?
572                 if($type & CHAT_SIDEKICK) {
573                     // Is the main connection ready?
574                     if(isset($this->conn_sets[$sessionid])) {
575                         // Yes, so dispatch this sidekick now and be done with it
576                         //$this->trace('Dispatching sidekick immediately');
577                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
578                         $this->dismiss_ufo($handle, false);
579                     }
580                     else {
581                         // No, so put it in the waiting list
582                         $this->trace('sidekick waiting');
583                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
584                     }
585                     return true;
586                 }
588                 // If it's not a sidekick, at this point it can only be da man
590                 if($type & CHAT_CONNECTION) {
591                     // This forces a new connection right now...
592                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
594                     // Do we have such a connection active?
595                     if(isset($this->conn_sets[$sessionid])) {
596                         // Yes, so regrettably we cannot promote you
597                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
598                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
599                         return false;
600                     }
602                     // Join this with what we may have already
603                     $this->conn_half[$sessionid][$type] = $handle;
605                     // Do the bookkeeping
606                     $this->promote_final($sessionid, $customdata);
608                     // It's not an UFO anymore
609                     $this->dismiss_ufo($handle, false);
611                     // Dispatch waiting sidekicks
612                     $this->process_sidekicks($sessionid);
614                     return true;
615                 }
616             }
617         }
618         return false;
619     }
621     function dismiss_half($sessionid, $disconnect = true) {
622         if(!isset($this->conn_half[$sessionid])) {
623             return false;
624         }
625         if($disconnect) {
626             foreach($this->conn_half[$sessionid] as $handle) {
627                 @socket_shutdown($handle);
628                 @socket_close($handle);
629             }
630         }
631         unset($this->conn_half[$sessionid]);
632         return true;
633     }
635     function dismiss_set($sessionid) {
636         if(!empty($this->conn_sets[$sessionid])) {
637             foreach($this->conn_sets[$sessionid] as $handle) {
638                 // Since we want to dismiss this, don't generate any errors if it's dead already
639                 @socket_shutdown($handle);
640                 @socket_close($handle);
641             }
642         }
643         $chatroom = $this->sets_info[$sessionid]['chatid'];
644         $userid   = $this->sets_info[$sessionid]['userid'];
645         unset($this->conn_sets[$sessionid]);
646         unset($this->sets_info[$sessionid]);
647         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
648         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
649         return true;
650     }
653     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
654         if(empty($this->conn_ufo)) {
655             return false;
656         }
657         foreach($this->conn_ufo as $id => $ufo) {
658             if($ufo->handle == $handle) {
659                 unset($this->conn_ufo[$id]);
660                 if($disconnect) {
661                     if(!empty($message)) {
662                         $this->write_data($handle, $message."\n\n");
663                     }
664                     socket_shutdown($handle);
665                     socket_close($handle);
666                 }
667                 return true;
668             }
669         }
670         return false;
671     }
673     function conn_accept() {
674         $read_socket = array($this->listen_socket);
675         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
677         if(!$changed) {
678             return false;
679         }
680         $handle = socket_accept($this->listen_socket);
681         if(!$handle) {
682             return false;
683         }
685         $newconn = New ChatConnection($handle);
686         $id = $this->new_ufo_id();
687         $this->conn_ufo[$id] = $newconn;
689         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
690     }
692     function conn_activity_ufo (&$handles) {
693         $monitor = array();
694         if(!empty($this->conn_ufo)) {
695             foreach($this->conn_ufo as $ufoid => $ufo) {
696                 $monitor[$ufoid] = $ufo->handle;
697             }
698         }
700         if(empty($monitor)) {
701             $handles = array();
702             return 0;
703         }
705         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
706         $handles = $monitor;
708         return $retval;
709     }
711     function message_broadcast($message, $sender) {
712         global $PAGE;
714         if(empty($this->conn_sets)) {
715             return true;
716         }
718         $now = time();
720         // First of all, mark this chatroom as having had activity now
721         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
723         foreach($this->sets_info as $sessionid => $info) {
724             // We need to get handles from users that are in the same chatroom, same group
725             if($info['chatid'] == $message->chatid &&
726               ($info['groupid'] == $message->groupid || $message->groupid == 0))
727             {
729                 // Simply give them the message
730                 $PAGE->set_course($info['course']);
731                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
732                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
734                 if($output->beep) {
735                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
736                 }
738                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
739                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
740                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
741                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
742                 }
744                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
745                     $this->disconnect_session($sessionid);
746                 }
747                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
748             }
749         }
750     }
752     function disconnect_session($sessionid) {
753         global $DB;
755         $info = $this->sets_info[$sessionid];
757         $DB->delete_records('chat_users', array('sid'=>$sessionid));
758         $msg = New stdClass;
759         $msg->chatid = $info['chatid'];
760         $msg->userid = $info['userid'];
761         $msg->groupid = $info['groupid'];
762         $msg->system = 1;
763         $msg->message = 'exit';
764         $msg->timestamp = time();
766         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
767         $DB->insert_record('chat_messages', $msg, false);
768         $DB->insert_record('chat_messages_current', $msg, false);
770         // *************************** IMPORTANT
771         //
772         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
773         //
774         // **********************************************************************
775         $latesender = $info['user'];
776         $this->dismiss_set($sessionid);
777         $this->message_broadcast($msg, $latesender);
778     }
780     function fatal($message) {
781         $message .= "\n";
782         if($this->_logfile) {
783             $this->trace($message, E_USER_ERROR);
784         }
785         echo "FATAL ERROR:: $message\n";
786         die();
787     }
789     function init_sockets() {
790         global $CFG;
792         $this->trace('Setting up sockets');
794         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
795             // Failed to create socket
796             $lasterr = socket_last_error();
797             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
798         }
800         //socket_close($DAEMON->listen_socket);
801         //die();
803         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
804             // Failed to bind socket
805             $lasterr = socket_last_error();
806             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
807         }
809         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
810             // Failed to get socket to listen
811             $lasterr = socket_last_error();
812             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
813         }
815         // Socket has been initialized and is ready
816         $this->trace('Socket opened on port '.$CFG->chat_serverport);
818         // [pj]: I really must have a good read on sockets. What exactly does this do?
819         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
820         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
821         socket_set_nonblock($this->listen_socket);
822     }
824     function cli_switch($switch, $param = NULL) {
825         switch($switch) { //LOL
826             case 'reset':
827                 // Reset sockets
828                 $this->_resetsocket = true;
829                 return false;
830             case 'start':
831                 // Start the daemon
832                 $this->_readytogo = true;
833                 return false;
834             break;
835             case 'v':
836                 // Verbose mode
837                 $this->_trace_level = E_ALL;
838                 return false;
839             break;
840             case 'l':
841                 // Use logfile
842                 if(!empty($param)) {
843                     $this->_logfile_name = $param;
844                 }
845                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
846                 if($this->_logfile == false) {
847                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
848                 }
849                 return false;
850             default:
851                 // Unrecognized
852                 $this->fatal('Unrecognized command line switch: '.$switch);
853             break;
854         }
855         return false;
856     }
860 $DAEMON = New ChatDaemon;
861 set_error_handler(array($DAEMON, 'error_handler'));
863 /// Check the parameters //////////////////////////////////////////////////////
865 unset($argv[0]);
866 $commandline = implode(' ', $argv);
867 if(strpos($commandline, '-') === false) {
868     if(!empty($commandline)) {
869         // We cannot have received any meaningful parameters
870         $DAEMON->fatal('Garbage in command line');
871     }
873 else {
874     // Parse command line
875     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
877     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
878     // We will be using that to pass additional information to those switches who need it
879     $numswitches = count($switches);
881     // Fancy way to give a "hyphen" boolean flag to each "switch"
882     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
884     for($i = 0; $i < $numswitches; ++$i) {
886         $switch = $switches[$i]['str'];
887         $params = ($i == $numswitches - 1 ? NULL :
888                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
889                   );
891         if(substr($switch, 0, 2) == '--') {
892             // Double-hyphen switch
893             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
894         }
895         else if(substr($switch, 0, 1) == '-') {
896             // Single-hyphen switch(es), may be more than one run together
897             $switch = substr($switch, 1); // Get rid of the -
898             $len = strlen($switch);
899             for($j = 0; $j < $len; ++$j) {
900                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
901             }
902         }
903     }
906 if(!$DAEMON->query_start()) {
907     // For some reason we didn't start, so print out some info
908     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
909     echo "\n\n";
910     echo "Usage: chatd.php [parameters]\n\n";
911     echo "Parameters:\n";
912     echo "  --start         Starts the daemon\n";
913     echo "  -v              Verbose mode (prints trivial information messages)\n";
914     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
915     echo "Example:\n";
916     echo "  chatd.php --start -l\n\n";
917     die();
920 if (!function_exists('socket_setopt')) {
921     echo "Error: Function socket_setopt() does not exist.\n";
922     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
923     die();
926 $DAEMON->init_sockets();
928 /*
929 declare(ticks=1);
931 $pid = pcntl_fork();
932 if ($pid == -1) {
933      die("could not fork");
934 } else if ($pid) {
935      exit(); // we are the parent
936 } else {
937      // we are the child
940 // detatch from the controlling terminal
941 if (!posix_setsid()) {
942    die("could not detach from terminal");
945 // setup signal handlers
946 pcntl_signal(SIGTERM, "sig_handler");
947 pcntl_signal(SIGHUP, "sig_handler");
949 if($DAEMON->_pcntl_exists && false) {
950     $DAEMON->trace('Unholy spirit possession: daemonizing');
951     $DAEMON->pid = pcntl_fork();
952     if($pid == -1) {
953         $DAEMON->trace('Process fork failed, terminating');
954         die();
955     }
956     else if($pid) {
957         // We are the parent
958         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
959         die();
960     }
961     else {
962         // We are the daemon! :P
963     }
965     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
967     // Detach from controlling terminal
968     if(!posix_setsid()) {
969         $DAEMON->trace('Could not detach daemon process from terminal!');
970     }
972 else {
973     // Cannot go demonic
974     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
976 */
978 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
980 /// Clear the decks of old stuff
981 $DB->delete_records('chat_users', array('version'=>'sockets'));
983 while(true) {
984     $active = array();
986     // First of all, let's see if any of our UFOs has identified itself
987     if($DAEMON->conn_activity_ufo($active)) {
988         foreach($active as $handle) {
989             $read_socket = array($handle);
990             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
992             if($changed > 0) {
993                 // Let's see what it has to say
995                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
996                 if(empty($data)) {
997                     continue;
998                 }
1000                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1001                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1002                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1003                     continue;
1004                 }
1006                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1007                     // Malformed data
1008                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1009                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1010                     continue;
1011                 }
1013                 $type      = $info[1];
1014                 $sessionid = $info[2];
1016                 $customdata = array();
1018                 switch($type) {
1019                     case 'chat':
1020                        $type = CHAT_CONNECTION_CHANNEL;
1021                         $customdata['quirks'] = 0;
1022                         if(strpos($data, 'Safari')) {
1023                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1024                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1025                         }
1026                     break;
1027                     case 'users':
1028                         $type = CHAT_SIDEKICK_USERS;
1029                     break;
1030                     case 'beep':
1031                         $type = CHAT_SIDEKICK_BEEP;
1032                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1033                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1034                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1035                             continue;
1036                         }
1037                         else {
1038                             $customdata = array('beep' => intval($info[1]));
1039                         }
1040                     break;
1041                     case 'message':
1042                         $type = CHAT_SIDEKICK_MESSAGE;
1043                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1044                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1045                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1046                             continue;
1047                         }
1048                         else {
1049                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1050                         }
1051                     break;
1052                     default:
1053                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1054                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1055                         continue;
1056                     break;
1057                 }
1059                 // OK, now we know it's something good... promote it and pass it all the data it needs
1060                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1061                 continue;
1062             }
1063         }
1064     }
1066     $now = time();
1068     // Clean up chatrooms with no activity as required
1069     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1070         $DAEMON->poll_idle_chats($now);
1071     }
1073     // Finally, accept new connections
1074     $DAEMON->conn_accept();
1076     usleep($DAEMON->_time_rest_socket);
1079 @socket_shutdown($DAEMON->listen_socket, 0);
1080 die("\n\n-- terminated --\n");