MDL-27398 mod_chat Adding file basic doc
[moodle.git] / mod / chat / chatd.php
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.
14 //
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
20  *
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
24  */
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");
63 }
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);
70 }
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);
88     }
89 }
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;
121         }
122     }
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);
128         }
129         return true;
130     }
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);
146                             }
147                         }
148                     }
149                 }
150             }
151         }
152         $this->_last_idle_poll = $now;
153     }
155     function query_start() {
156         return $this->_readytogo;
157     }
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;
167         }
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);
178             }
180             // Emit the message to wherever we should
181             if($this->_trace_to_stdout) {
182                 fwrite($this->_stdout, $message);
183                 fflush($this->_stdout);
184             }
185             if($this->_trace_to_console) {
186                 echo $message;
187                 flush();
188             }
189             if($this->_logfile) {
190                 fwrite($this->_logfile, $message);
191                 fflush($this->_logfile);
192             }
193         }
194     }
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;
201         }
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) {
211 //
212 //            // ABOVE CODE GOES HERE
213 //
214 //        }
215 //        return false;
216     }
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;
225         }
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']);
235         }
236         return true;
237     }
239     function get_user_window($sessionid) {
240         global $CFG, $PAGE, $OUTPUT;
242         static $str;
244         $info = &$this->sets_info[$sessionid];
245         $PAGE->set_course($info['course']);
247         $timenow = time();
249         if (empty($str)) {
250             $str->idle  = get_string("idle", "chat");
251             $str->beep  = get_string("beep", "chat");
252             $str->day   = get_string("day");
253             $str->days  = get_string("days");
254             $str->hour  = get_string("hour");
255             $str->hours = get_string("hours");
256             $str->min   = get_string("min");
257             $str->mins  = get_string("mins");
258             $str->sec   = get_string("sec");
259             $str->secs  = get_string("secs");
260             $str->years = get_string('years');
261         }
263         ob_start();
264         $refresh_inval = $CFG->chat_refresh_userlist * 1000;
265         echo <<<EOD
266         <html><head>
267         <meta http-equiv="refresh" content="$refresh_inval">
268         <style type="text/css"> img{border:0} </style>
269         <script type="text/javascript">
270         //<![CDATA[
271         function openpopup(url,name,options,fullscreen) {
272             fullurl = "$CFG->wwwroot" + url;
273             windowobj = window.open(fullurl,name,options);
274             if (fullscreen) {
275                 windowobj.moveTo(0,0);
276                 windowobj.resizeTo(screen.availWidth,screen.availHeight);
277             }
278             windowobj.focus();
279             return false;
280         }
281         //]]>
282         </script></head><body><table><tbody>
283 EOD;
285         // Get the users from that chatroom
286         $users = $this->chatrooms[$info['chatid']]['users'];
288         foreach ($users as $usersessionid => $userid) {
289             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
290             $userinfo = $this->sets_info[$usersessionid];
292             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
294             echo '<tr><td width="35">';
296             $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid'];
297             $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
299             $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id);
300             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
302             echo $anchortag;
303             echo "</td><td valign=\"center\">";
304             echo "<p><font size=\"1\">";
305             echo fullname($userinfo['user'])."<br />";
306             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
307             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
308                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
309             echo "</font></p>";
310             echo "<td></tr>";
311         }
313         echo '</tbody></table>';
315         // About 2K of HTML comments to force browsers to render the HTML
316         // echo $GLOBALS['CHAT_DUMMY_DATA'];
318         echo "</body>\n</html>\n";
320         return ob_get_clean();
322     }
324     function new_ufo_id() {
325         static $id = 0;
326         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
327             $id = 0;
328         }
329         return $id;
330     }
332     function process_sidekicks($sessionid) {
333         if(empty($this->conn_side[$sessionid])) {
334             return true;
335         }
336         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
337             // TODO: is this late-dispatch working correctly?
338             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
339             unset($this->conn_side[$sessionid][$sideid]);
340         }
341         return true;
342     }
344     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
345         global $CFG, $DB;
347         switch($type) {
348             case CHAT_SIDEKICK_BEEP:
349                 // Incoming beep
350                 $msg = New stdClass;
351                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
352                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
353                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
354                 $msg->system    = 0;
355                 $msg->message   = 'beep '.$customdata['beep'];
356                 $msg->timestamp = time();
358                 // Commit to DB
359                 $DB->insert_record('chat_messages', $msg, false);
360                 $DB->insert_record('chat_messages_current', $msg, false);
362                 // OK, now push it out to all users
363                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
365                 // Update that user's lastmessageping
366                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
367                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
368                 $this->user_lazy_update($sessionid);
370                 // We did our work, but before slamming the door on the poor browser
371                 // show the courtesy of responding to the HTTP request. Otherwise, some
372                 // browsers decide to get vengeance by flooding us with repeat requests.
374                 $header  = "HTTP/1.1 200 OK\n";
375                 $header .= "Connection: close\n";
376                 $header .= "Date: ".date('r')."\n";
377                 $header .= "Server: Moodle\n";
378                 $header .= "Content-Type: text/html; charset=utf-8\n";
379                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
380                 $header .= "Cache-Control: no-cache, must-revalidate\n";
381                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
382                 $header .= "\n";
384                 // That's enough headers for one lousy dummy response
385                 $this->write_data($handle, $header);
386                 // All done
387             break;
389             case CHAT_SIDEKICK_USERS:
390                 // A request to paint a user window
392                 $content = $this->get_user_window($sessionid);
394                 $header  = "HTTP/1.1 200 OK\n";
395                 $header .= "Connection: close\n";
396                 $header .= "Date: ".date('r')."\n";
397                 $header .= "Server: Moodle\n";
398                 $header .= "Content-Type: text/html; charset=utf-8\n";
399                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
400                 $header .= "Cache-Control: no-cache, must-revalidate\n";
401                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
402                 $header .= "Content-Length: ".strlen($content)."\n";
404                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
405                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
406                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
407                            "chat_sid=".$sessionid."\n";
408                 $header .= "\n";
410                 // That's enough headers for one lousy dummy response
411                 $this->trace('writing users http response to handle '.$handle);
412                 $this->write_data($handle, $header . $content);
414                 // Update that user's lastping
415                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
416                 $this->user_lazy_update($sessionid);
418             break;
420             case CHAT_SIDEKICK_MESSAGE:
421                 // Incoming message
423                 // Browser stupidity protection from duplicate messages:
424                 $messageindex = intval($customdata['index']);
426                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
427                     // We have already broadcasted that!
428                     // $this->trace('discarding message with stale index');
429                     break;
430                 }
431                 else {
432                     // Update our info
433                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
434                 }
436                 $msg = New stdClass;
437                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
438                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
439                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
440                 $msg->system    = 0;
441                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
442                 $msg->timestamp = time();
444                 if(empty($msg->message)) {
445                     // Someone just hit ENTER, send them on their way
446                     break;
447                 }
449                 // A slight hack to prevent malformed SQL inserts
450                 $origmsg = $msg->message;
451                 $msg->message = $msg->message;
453                 // Commit to DB
454                 $DB->insert_record('chat_messages', $msg, false);
455                 $DB->insert_record('chat_messages_current', $msg, false);
457                 // Undo the hack
458                 $msg->message = $origmsg;
460                 // OK, now push it out to all users
461                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
463                 // Update that user's lastmessageping
464                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
465                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
466                 $this->user_lazy_update($sessionid);
468                 // We did our work, but before slamming the door on the poor browser
469                 // show the courtesy of responding to the HTTP request. Otherwise, some
470                 // browsers decide to get vengeance by flooding us with repeat requests.
472                 $header  = "HTTP/1.1 200 OK\n";
473                 $header .= "Connection: close\n";
474                 $header .= "Date: ".date('r')."\n";
475                 $header .= "Server: Moodle\n";
476                 $header .= "Content-Type: text/html; charset=utf-8\n";
477                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
478                 $header .= "Cache-Control: no-cache, must-revalidate\n";
479                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
480                 $header .= "\n";
482                 // That's enough headers for one lousy dummy response
483                 $this->write_data($handle, $header);
485                 // All done
486             break;
487         }
489         socket_shutdown($handle);
490         socket_close($handle);
491     }
493     function promote_final($sessionid, $customdata) {
494         global $DB;
496         if(isset($this->conn_sets[$sessionid])) {
497             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
498             return false;
499         }
501         $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
502         if($chatuser === false) {
503             $this->dismiss_half($sessionid);
504             return false;
505         }
506         $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
507         if($chat === false) {
508             $this->dismiss_half($sessionid);
509             return false;
510         }
511         $user = $DB->get_record('user', array('id'=>$chatuser->userid));
512         if($user === false) {
513             $this->dismiss_half($sessionid);
514             return false;
515         }
516         $course = $DB->get_record('course', array('id'=>$chat->course));
517         if($course === false) {
518             $this->dismiss_half($sessionid);
519             return false;
520         }
522         global $CHAT_HTMLHEAD_JS, $CFG;
524         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
526         // This whole thing needs to be purged of redundant info, and the
527         // code base to follow suit. But AFTER development is done.
528         $this->sets_info[$sessionid] = array(
529             'lastinfocommit' => 0,
530             'lastmessageindex' => 0,
531             'course'    => $course,
532             'courseid'  => $course->id,
533             'chatuser'  => $chatuser,
534             'chatid'    => $chat->id,
535             'user'      => $user,
536             'userid'    => $user->id,
537             'groupid'   => $chatuser->groupid,
538             'lang'      => $chatuser->lang,
539             'quirks'    => $customdata['quirks']
540         );
542         // If we know nothing about this chatroom, initialize it and add the user
543         if(!isset($this->chatrooms[$chat->id]['users'])) {
544             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
545         }
546         else {
547             // Otherwise just add the user
548             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
549         }
551         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
553         $this->dismiss_half($sessionid, false);
554         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
555         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
557         // Finally, broadcast the "entered the chat" message
559         $msg = new stdClass;
560         $msg->chatid = $chatuser->chatid;
561         $msg->userid = $chatuser->userid;
562         $msg->groupid = $chatuser->groupid;
563         $msg->system = 1;
564         $msg->message = 'enter';
565         $msg->timestamp = time();
567         $DB->insert_record('chat_messages', $msg, false);
568         $DB->insert_record('chat_messages_current', $msg, false);
569         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
571         return true;
572     }
574     function promote_ufo($handle, $type, $sessionid, $customdata) {
575         if(empty($this->conn_ufo)) {
576             return false;
577         }
578         foreach($this->conn_ufo as $id => $ufo) {
579             if($ufo->handle == $handle) {
580                 // OK, got the id of the UFO, but what is it?
582                 if($type & CHAT_SIDEKICK) {
583                     // Is the main connection ready?
584                     if(isset($this->conn_sets[$sessionid])) {
585                         // Yes, so dispatch this sidekick now and be done with it
586                         //$this->trace('Dispatching sidekick immediately');
587                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
588                         $this->dismiss_ufo($handle, false);
589                     }
590                     else {
591                         // No, so put it in the waiting list
592                         $this->trace('sidekick waiting');
593                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
594                     }
595                     return true;
596                 }
598                 // If it's not a sidekick, at this point it can only be da man
600                 if($type & CHAT_CONNECTION) {
601                     // This forces a new connection right now...
602                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
604                     // Do we have such a connection active?
605                     if(isset($this->conn_sets[$sessionid])) {
606                         // Yes, so regrettably we cannot promote you
607                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
608                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
609                         return false;
610                     }
612                     // Join this with what we may have already
613                     $this->conn_half[$sessionid][$type] = $handle;
615                     // Do the bookkeeping
616                     $this->promote_final($sessionid, $customdata);
618                     // It's not an UFO anymore
619                     $this->dismiss_ufo($handle, false);
621                     // Dispatch waiting sidekicks
622                     $this->process_sidekicks($sessionid);
624                     return true;
625                 }
626             }
627         }
628         return false;
629     }
631     function dismiss_half($sessionid, $disconnect = true) {
632         if(!isset($this->conn_half[$sessionid])) {
633             return false;
634         }
635         if($disconnect) {
636             foreach($this->conn_half[$sessionid] as $handle) {
637                 @socket_shutdown($handle);
638                 @socket_close($handle);
639             }
640         }
641         unset($this->conn_half[$sessionid]);
642         return true;
643     }
645     function dismiss_set($sessionid) {
646         if(!empty($this->conn_sets[$sessionid])) {
647             foreach($this->conn_sets[$sessionid] as $handle) {
648                 // Since we want to dismiss this, don't generate any errors if it's dead already
649                 @socket_shutdown($handle);
650                 @socket_close($handle);
651             }
652         }
653         $chatroom = $this->sets_info[$sessionid]['chatid'];
654         $userid   = $this->sets_info[$sessionid]['userid'];
655         unset($this->conn_sets[$sessionid]);
656         unset($this->sets_info[$sessionid]);
657         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
658         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
659         return true;
660     }
663     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
664         if(empty($this->conn_ufo)) {
665             return false;
666         }
667         foreach($this->conn_ufo as $id => $ufo) {
668             if($ufo->handle == $handle) {
669                 unset($this->conn_ufo[$id]);
670                 if($disconnect) {
671                     if(!empty($message)) {
672                         $this->write_data($handle, $message."\n\n");
673                     }
674                     socket_shutdown($handle);
675                     socket_close($handle);
676                 }
677                 return true;
678             }
679         }
680         return false;
681     }
683     function conn_accept() {
684         $read_socket = array($this->listen_socket);
685         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
687         if(!$changed) {
688             return false;
689         }
690         $handle = socket_accept($this->listen_socket);
691         if(!$handle) {
692             return false;
693         }
695         $newconn = New ChatConnection($handle);
696         $id = $this->new_ufo_id();
697         $this->conn_ufo[$id] = $newconn;
699         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
700     }
702     function conn_activity_ufo (&$handles) {
703         $monitor = array();
704         if(!empty($this->conn_ufo)) {
705             foreach($this->conn_ufo as $ufoid => $ufo) {
706                 $monitor[$ufoid] = $ufo->handle;
707             }
708         }
710         if(empty($monitor)) {
711             $handles = array();
712             return 0;
713         }
715         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
716         $handles = $monitor;
718         return $retval;
719     }
721     function message_broadcast($message, $sender) {
722         global $PAGE;
724         if(empty($this->conn_sets)) {
725             return true;
726         }
728         $now = time();
730         // First of all, mark this chatroom as having had activity now
731         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
733         foreach($this->sets_info as $sessionid => $info) {
734             // We need to get handles from users that are in the same chatroom, same group
735             if($info['chatid'] == $message->chatid &&
736               ($info['groupid'] == $message->groupid || $message->groupid == 0))
737             {
739                 // Simply give them the message
740                 $PAGE->set_course($info['course']);
741                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
742                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
744                 if($output->beep) {
745                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
746                 }
748                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
749                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
750                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
751                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
752                 }
754                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
755                     $this->disconnect_session($sessionid);
756                 }
757                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
758             }
759         }
760     }
762     function disconnect_session($sessionid) {
763         global $DB;
765         $info = $this->sets_info[$sessionid];
767         $DB->delete_records('chat_users', array('sid'=>$sessionid));
768         $msg = New stdClass;
769         $msg->chatid = $info['chatid'];
770         $msg->userid = $info['userid'];
771         $msg->groupid = $info['groupid'];
772         $msg->system = 1;
773         $msg->message = 'exit';
774         $msg->timestamp = time();
776         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
777         $DB->insert_record('chat_messages', $msg, false);
778         $DB->insert_record('chat_messages_current', $msg, false);
780         // *************************** IMPORTANT
781         //
782         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
783         //
784         // **********************************************************************
785         $latesender = $info['user'];
786         $this->dismiss_set($sessionid);
787         $this->message_broadcast($msg, $latesender);
788     }
790     function fatal($message) {
791         $message .= "\n";
792         if($this->_logfile) {
793             $this->trace($message, E_USER_ERROR);
794         }
795         echo "FATAL ERROR:: $message\n";
796         die();
797     }
799     function init_sockets() {
800         global $CFG;
802         $this->trace('Setting up sockets');
804         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
805             // Failed to create socket
806             $lasterr = socket_last_error();
807             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
808         }
810         //socket_close($DAEMON->listen_socket);
811         //die();
813         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
814             // Failed to bind socket
815             $lasterr = socket_last_error();
816             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
817         }
819         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
820             // Failed to get socket to listen
821             $lasterr = socket_last_error();
822             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
823         }
825         // Socket has been initialized and is ready
826         $this->trace('Socket opened on port '.$CFG->chat_serverport);
828         // [pj]: I really must have a good read on sockets. What exactly does this do?
829         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
830         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
831         socket_set_nonblock($this->listen_socket);
832     }
834     function cli_switch($switch, $param = NULL) {
835         switch($switch) { //LOL
836             case 'reset':
837                 // Reset sockets
838                 $this->_resetsocket = true;
839                 return false;
840             case 'start':
841                 // Start the daemon
842                 $this->_readytogo = true;
843                 return false;
844             break;
845             case 'v':
846                 // Verbose mode
847                 $this->_trace_level = E_ALL;
848                 return false;
849             break;
850             case 'l':
851                 // Use logfile
852                 if(!empty($param)) {
853                     $this->_logfile_name = $param;
854                 }
855                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
856                 if($this->_logfile == false) {
857                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
858                 }
859                 return false;
860             default:
861                 // Unrecognized
862                 $this->fatal('Unrecognized command line switch: '.$switch);
863             break;
864         }
865         return false;
866     }
870 $DAEMON = New ChatDaemon;
871 set_error_handler(array($DAEMON, 'error_handler'));
873 /// Check the parameters //////////////////////////////////////////////////////
875 unset($argv[0]);
876 $commandline = implode(' ', $argv);
877 if(strpos($commandline, '-') === false) {
878     if(!empty($commandline)) {
879         // We cannot have received any meaningful parameters
880         $DAEMON->fatal('Garbage in command line');
881     }
883 else {
884     // Parse command line
885     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
887     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
888     // We will be using that to pass additional information to those switches who need it
889     $numswitches = count($switches);
891     // Fancy way to give a "hyphen" boolean flag to each "switch"
892     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
894     for($i = 0; $i < $numswitches; ++$i) {
896         $switch = $switches[$i]['str'];
897         $params = ($i == $numswitches - 1 ? NULL :
898                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
899                   );
901         if(substr($switch, 0, 2) == '--') {
902             // Double-hyphen switch
903             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
904         }
905         else if(substr($switch, 0, 1) == '-') {
906             // Single-hyphen switch(es), may be more than one run together
907             $switch = substr($switch, 1); // Get rid of the -
908             $len = strlen($switch);
909             for($j = 0; $j < $len; ++$j) {
910                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
911             }
912         }
913     }
916 if(!$DAEMON->query_start()) {
917     // For some reason we didn't start, so print out some info
918     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
919     echo "\n\n";
920     echo "Usage: chatd.php [parameters]\n\n";
921     echo "Parameters:\n";
922     echo "  --start         Starts the daemon\n";
923     echo "  -v              Verbose mode (prints trivial information messages)\n";
924     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
925     echo "Example:\n";
926     echo "  chatd.php --start -l\n\n";
927     die();
930 if (!function_exists('socket_setopt')) {
931     echo "Error: Function socket_setopt() does not exist.\n";
932     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
933     die();
936 $DAEMON->init_sockets();
938 /*
939 declare(ticks=1);
941 $pid = pcntl_fork();
942 if ($pid == -1) {
943      die("could not fork");
944 } else if ($pid) {
945      exit(); // we are the parent
946 } else {
947      // we are the child
950 // detatch from the controlling terminal
951 if (!posix_setsid()) {
952    die("could not detach from terminal");
955 // setup signal handlers
956 pcntl_signal(SIGTERM, "sig_handler");
957 pcntl_signal(SIGHUP, "sig_handler");
959 if($DAEMON->_pcntl_exists && false) {
960     $DAEMON->trace('Unholy spirit possession: daemonizing');
961     $DAEMON->pid = pcntl_fork();
962     if($pid == -1) {
963         $DAEMON->trace('Process fork failed, terminating');
964         die();
965     }
966     else if($pid) {
967         // We are the parent
968         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
969         die();
970     }
971     else {
972         // We are the daemon! :P
973     }
975     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
977     // Detach from controlling terminal
978     if(!posix_setsid()) {
979         $DAEMON->trace('Could not detach daemon process from terminal!');
980     }
982 else {
983     // Cannot go demonic
984     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
986 */
988 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
990 /// Clear the decks of old stuff
991 $DB->delete_records('chat_users', array('version'=>'sockets'));
993 while(true) {
994     $active = array();
996     // First of all, let's see if any of our UFOs has identified itself
997     if($DAEMON->conn_activity_ufo($active)) {
998         foreach($active as $handle) {
999             $read_socket = array($handle);
1000             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
1002             if($changed > 0) {
1003                 // Let's see what it has to say
1005                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
1006                 if(empty($data)) {
1007                     continue;
1008                 }
1010                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1011                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1012                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1013                     continue;
1014                 }
1016                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1017                     // Malformed data
1018                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1019                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1020                     continue;
1021                 }
1023                 $type      = $info[1];
1024                 $sessionid = $info[2];
1026                 $customdata = array();
1028                 switch($type) {
1029                     case 'chat':
1030                        $type = CHAT_CONNECTION_CHANNEL;
1031                         $customdata['quirks'] = 0;
1032                         if(strpos($data, 'Safari')) {
1033                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1034                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1035                         }
1036                     break;
1037                     case 'users':
1038                         $type = CHAT_SIDEKICK_USERS;
1039                     break;
1040                     case 'beep':
1041                         $type = CHAT_SIDEKICK_BEEP;
1042                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1043                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1044                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1045                             continue;
1046                         }
1047                         else {
1048                             $customdata = array('beep' => intval($info[1]));
1049                         }
1050                     break;
1051                     case 'message':
1052                         $type = CHAT_SIDEKICK_MESSAGE;
1053                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1054                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1055                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1056                             continue;
1057                         }
1058                         else {
1059                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1060                         }
1061                     break;
1062                     default:
1063                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1064                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1065                         continue;
1066                     break;
1067                 }
1069                 // OK, now we know it's something good... promote it and pass it all the data it needs
1070                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1071                 continue;
1072             }
1073         }
1074     }
1076     $now = time();
1078     // Clean up chatrooms with no activity as required
1079     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1080         $DAEMON->poll_idle_chats($now);
1081     }
1083     // Finally, accept new connections
1084     $DAEMON->conn_accept();
1086     usleep($DAEMON->_time_rest_socket);
1089 @socket_shutdown($DAEMON->listen_socket, 0);
1090 die("\n\n-- terminated --\n");