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