MDL-27398 mod_chat Removing PAGE references
[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, $OUTPUT;
242         static $str;
244         $info = &$this->sets_info[$sessionid];
246         $timenow = time();
248         if (empty($str)) {
249             $str->idle  = get_string("idle", "chat");
250             $str->beep  = get_string("beep", "chat");
251             $str->day   = get_string("day");
252             $str->days  = get_string("days");
253             $str->hour  = get_string("hour");
254             $str->hours = get_string("hours");
255             $str->min   = get_string("min");
256             $str->mins  = get_string("mins");
257             $str->sec   = get_string("sec");
258             $str->secs  = get_string("secs");
259             $str->years = get_string('years');
260         }
262         ob_start();
263         $refresh_inval = $CFG->chat_refresh_userlist * 1000;
264         echo <<<EOD
265         <html><head>
266         <meta http-equiv="refresh" content="$refresh_inval">
267         <style type="text/css"> img{border:0} </style>
268         <script type="text/javascript">
269         //<![CDATA[
270         function openpopup(url,name,options,fullscreen) {
271             fullurl = "$CFG->wwwroot" + url;
272             windowobj = window.open(fullurl,name,options);
273             if (fullscreen) {
274                 windowobj.moveTo(0,0);
275                 windowobj.resizeTo(screen.availWidth,screen.availHeight);
276             }
277             windowobj.focus();
278             return false;
279         }
280         //]]>
281         </script></head><body><table><tbody>
282 EOD;
284         // Get the users from that chatroom
285         $users = $this->chatrooms[$info['chatid']]['users'];
287         foreach ($users as $usersessionid => $userid) {
288             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
289             $userinfo = $this->sets_info[$usersessionid];
291             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
293             echo '<tr><td width="35">';
295             $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid'];
296             $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
298             $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id);
299             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
301             echo $anchortag;
302             echo "</td><td valign=\"center\">";
303             echo "<p><font size=\"1\">";
304             echo fullname($userinfo['user'])."<br />";
305             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
306             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
307                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
308             echo "</font></p>";
309             echo "<td></tr>";
310         }
312         echo '</tbody></table>';
314         // About 2K of HTML comments to force browsers to render the HTML
315         // echo $GLOBALS['CHAT_DUMMY_DATA'];
317         echo "</body>\n</html>\n";
319         return ob_get_clean();
321     }
323     function new_ufo_id() {
324         static $id = 0;
325         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
326             $id = 0;
327         }
328         return $id;
329     }
331     function process_sidekicks($sessionid) {
332         if(empty($this->conn_side[$sessionid])) {
333             return true;
334         }
335         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
336             // TODO: is this late-dispatch working correctly?
337             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
338             unset($this->conn_side[$sessionid][$sideid]);
339         }
340         return true;
341     }
343     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
344         global $CFG, $DB;
346         switch($type) {
347             case CHAT_SIDEKICK_BEEP:
348                 // Incoming beep
349                 $msg = New stdClass;
350                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
351                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
352                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
353                 $msg->system    = 0;
354                 $msg->message   = 'beep '.$customdata['beep'];
355                 $msg->timestamp = time();
357                 // Commit to DB
358                 $DB->insert_record('chat_messages', $msg, false);
359                 $DB->insert_record('chat_messages_current', $msg, false);
361                 // OK, now push it out to all users
362                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
364                 // Update that user's lastmessageping
365                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
366                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
367                 $this->user_lazy_update($sessionid);
369                 // We did our work, but before slamming the door on the poor browser
370                 // show the courtesy of responding to the HTTP request. Otherwise, some
371                 // browsers decide to get vengeance by flooding us with repeat requests.
373                 $header  = "HTTP/1.1 200 OK\n";
374                 $header .= "Connection: close\n";
375                 $header .= "Date: ".date('r')."\n";
376                 $header .= "Server: Moodle\n";
377                 $header .= "Content-Type: text/html; charset=utf-8\n";
378                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
379                 $header .= "Cache-Control: no-cache, must-revalidate\n";
380                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
381                 $header .= "\n";
383                 // That's enough headers for one lousy dummy response
384                 $this->write_data($handle, $header);
385                 // All done
386             break;
388             case CHAT_SIDEKICK_USERS:
389                 // A request to paint a user window
391                 $content = $this->get_user_window($sessionid);
393                 $header  = "HTTP/1.1 200 OK\n";
394                 $header .= "Connection: close\n";
395                 $header .= "Date: ".date('r')."\n";
396                 $header .= "Server: Moodle\n";
397                 $header .= "Content-Type: text/html; charset=utf-8\n";
398                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
399                 $header .= "Cache-Control: no-cache, must-revalidate\n";
400                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
401                 $header .= "Content-Length: ".strlen($content)."\n";
403                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
404                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
405                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
406                            "chat_sid=".$sessionid."\n";
407                 $header .= "\n";
409                 // That's enough headers for one lousy dummy response
410                 $this->trace('writing users http response to handle '.$handle);
411                 $this->write_data($handle, $header . $content);
413                 // Update that user's lastping
414                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
415                 $this->user_lazy_update($sessionid);
417             break;
419             case CHAT_SIDEKICK_MESSAGE:
420                 // Incoming message
422                 // Browser stupidity protection from duplicate messages:
423                 $messageindex = intval($customdata['index']);
425                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
426                     // We have already broadcasted that!
427                     // $this->trace('discarding message with stale index');
428                     break;
429                 }
430                 else {
431                     // Update our info
432                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
433                 }
435                 $msg = New stdClass;
436                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
437                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
438                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
439                 $msg->system    = 0;
440                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
441                 $msg->timestamp = time();
443                 if(empty($msg->message)) {
444                     // Someone just hit ENTER, send them on their way
445                     break;
446                 }
448                 // A slight hack to prevent malformed SQL inserts
449                 $origmsg = $msg->message;
450                 $msg->message = $msg->message;
452                 // Commit to DB
453                 $DB->insert_record('chat_messages', $msg, false);
454                 $DB->insert_record('chat_messages_current', $msg, false);
456                 // Undo the hack
457                 $msg->message = $origmsg;
459                 // OK, now push it out to all users
460                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
462                 // Update that user's lastmessageping
463                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
464                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
465                 $this->user_lazy_update($sessionid);
467                 // We did our work, but before slamming the door on the poor browser
468                 // show the courtesy of responding to the HTTP request. Otherwise, some
469                 // browsers decide to get vengeance by flooding us with repeat requests.
471                 $header  = "HTTP/1.1 200 OK\n";
472                 $header .= "Connection: close\n";
473                 $header .= "Date: ".date('r')."\n";
474                 $header .= "Server: Moodle\n";
475                 $header .= "Content-Type: text/html; charset=utf-8\n";
476                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
477                 $header .= "Cache-Control: no-cache, must-revalidate\n";
478                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
479                 $header .= "\n";
481                 // That's enough headers for one lousy dummy response
482                 $this->write_data($handle, $header);
484                 // All done
485             break;
486         }
488         socket_shutdown($handle);
489         socket_close($handle);
490     }
492     function promote_final($sessionid, $customdata) {
493         global $DB;
495         if(isset($this->conn_sets[$sessionid])) {
496             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
497             return false;
498         }
500         $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
501         if($chatuser === false) {
502             $this->dismiss_half($sessionid);
503             return false;
504         }
505         $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
506         if($chat === false) {
507             $this->dismiss_half($sessionid);
508             return false;
509         }
510         $user = $DB->get_record('user', array('id'=>$chatuser->userid));
511         if($user === false) {
512             $this->dismiss_half($sessionid);
513             return false;
514         }
515         $course = $DB->get_record('course', array('id'=>$chat->course));
516         if($course === false) {
517             $this->dismiss_half($sessionid);
518             return false;
519         }
521         global $CHAT_HTMLHEAD_JS, $CFG;
523         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
525         // This whole thing needs to be purged of redundant info, and the
526         // code base to follow suit. But AFTER development is done.
527         $this->sets_info[$sessionid] = array(
528             'lastinfocommit' => 0,
529             'lastmessageindex' => 0,
530             'course'    => $course,
531             'courseid'  => $course->id,
532             'chatuser'  => $chatuser,
533             'chatid'    => $chat->id,
534             'user'      => $user,
535             'userid'    => $user->id,
536             'groupid'   => $chatuser->groupid,
537             'lang'      => $chatuser->lang,
538             'quirks'    => $customdata['quirks']
539         );
541         // If we know nothing about this chatroom, initialize it and add the user
542         if(!isset($this->chatrooms[$chat->id]['users'])) {
543             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
544         }
545         else {
546             // Otherwise just add the user
547             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
548         }
550         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
552         $this->dismiss_half($sessionid, false);
553         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $CHAT_HTMLHEAD_JS);
554         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
556         // Finally, broadcast the "entered the chat" message
558         $msg = new stdClass;
559         $msg->chatid = $chatuser->chatid;
560         $msg->userid = $chatuser->userid;
561         $msg->groupid = $chatuser->groupid;
562         $msg->system = 1;
563         $msg->message = 'enter';
564         $msg->timestamp = time();
566         $DB->insert_record('chat_messages', $msg, false);
567         $DB->insert_record('chat_messages_current', $msg, false);
568         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
570         return true;
571     }
573     function promote_ufo($handle, $type, $sessionid, $customdata) {
574         if(empty($this->conn_ufo)) {
575             return false;
576         }
577         foreach($this->conn_ufo as $id => $ufo) {
578             if($ufo->handle == $handle) {
579                 // OK, got the id of the UFO, but what is it?
581                 if($type & CHAT_SIDEKICK) {
582                     // Is the main connection ready?
583                     if(isset($this->conn_sets[$sessionid])) {
584                         // Yes, so dispatch this sidekick now and be done with it
585                         //$this->trace('Dispatching sidekick immediately');
586                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
587                         $this->dismiss_ufo($handle, false);
588                     }
589                     else {
590                         // No, so put it in the waiting list
591                         $this->trace('sidekick waiting');
592                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
593                     }
594                     return true;
595                 }
597                 // If it's not a sidekick, at this point it can only be da man
599                 if($type & CHAT_CONNECTION) {
600                     // This forces a new connection right now...
601                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
603                     // Do we have such a connection active?
604                     if(isset($this->conn_sets[$sessionid])) {
605                         // Yes, so regrettably we cannot promote you
606                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
607                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
608                         return false;
609                     }
611                     // Join this with what we may have already
612                     $this->conn_half[$sessionid][$type] = $handle;
614                     // Do the bookkeeping
615                     $this->promote_final($sessionid, $customdata);
617                     // It's not an UFO anymore
618                     $this->dismiss_ufo($handle, false);
620                     // Dispatch waiting sidekicks
621                     $this->process_sidekicks($sessionid);
623                     return true;
624                 }
625             }
626         }
627         return false;
628     }
630     function dismiss_half($sessionid, $disconnect = true) {
631         if(!isset($this->conn_half[$sessionid])) {
632             return false;
633         }
634         if($disconnect) {
635             foreach($this->conn_half[$sessionid] as $handle) {
636                 @socket_shutdown($handle);
637                 @socket_close($handle);
638             }
639         }
640         unset($this->conn_half[$sessionid]);
641         return true;
642     }
644     function dismiss_set($sessionid) {
645         if(!empty($this->conn_sets[$sessionid])) {
646             foreach($this->conn_sets[$sessionid] as $handle) {
647                 // Since we want to dismiss this, don't generate any errors if it's dead already
648                 @socket_shutdown($handle);
649                 @socket_close($handle);
650             }
651         }
652         $chatroom = $this->sets_info[$sessionid]['chatid'];
653         $userid   = $this->sets_info[$sessionid]['userid'];
654         unset($this->conn_sets[$sessionid]);
655         unset($this->sets_info[$sessionid]);
656         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
657         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
658         return true;
659     }
662     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
663         if(empty($this->conn_ufo)) {
664             return false;
665         }
666         foreach($this->conn_ufo as $id => $ufo) {
667             if($ufo->handle == $handle) {
668                 unset($this->conn_ufo[$id]);
669                 if($disconnect) {
670                     if(!empty($message)) {
671                         $this->write_data($handle, $message."\n\n");
672                     }
673                     socket_shutdown($handle);
674                     socket_close($handle);
675                 }
676                 return true;
677             }
678         }
679         return false;
680     }
682     function conn_accept() {
683         $read_socket = array($this->listen_socket);
684         $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
686         if(!$changed) {
687             return false;
688         }
689         $handle = socket_accept($this->listen_socket);
690         if(!$handle) {
691             return false;
692         }
694         $newconn = New ChatConnection($handle);
695         $id = $this->new_ufo_id();
696         $this->conn_ufo[$id] = $newconn;
698         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
699     }
701     function conn_activity_ufo (&$handles) {
702         $monitor = array();
703         if(!empty($this->conn_ufo)) {
704             foreach($this->conn_ufo as $ufoid => $ufo) {
705                 $monitor[$ufoid] = $ufo->handle;
706             }
707         }
709         if(empty($monitor)) {
710             $handles = array();
711             return 0;
712         }
714         $retval = socket_select($monitor, $a = NULL, $b = NULL, NULL);
715         $handles = $monitor;
717         return $retval;
718     }
720     function message_broadcast($message, $sender) {
722         if(empty($this->conn_sets)) {
723             return true;
724         }
726         $now = time();
728         // First of all, mark this chatroom as having had activity now
729         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
731         foreach($this->sets_info as $sessionid => $info) {
732             // We need to get handles from users that are in the same chatroom, same group
733             if($info['chatid'] == $message->chatid &&
734               ($info['groupid'] == $message->groupid || $message->groupid == 0))
735             {
737                 // Simply give them the message
738                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
739                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
741                 if($output->beep) {
742                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
743                 }
745                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
746                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
747                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
748                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
749                 }
751                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
752                     $this->disconnect_session($sessionid);
753                 }
754                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
755             }
756         }
757     }
759     function disconnect_session($sessionid) {
760         global $DB;
762         $info = $this->sets_info[$sessionid];
764         $DB->delete_records('chat_users', array('sid'=>$sessionid));
765         $msg = New stdClass;
766         $msg->chatid = $info['chatid'];
767         $msg->userid = $info['userid'];
768         $msg->groupid = $info['groupid'];
769         $msg->system = 1;
770         $msg->message = 'exit';
771         $msg->timestamp = time();
773         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
774         $DB->insert_record('chat_messages', $msg, false);
775         $DB->insert_record('chat_messages_current', $msg, false);
777         // *************************** IMPORTANT
778         //
779         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
780         //
781         // **********************************************************************
782         $latesender = $info['user'];
783         $this->dismiss_set($sessionid);
784         $this->message_broadcast($msg, $latesender);
785     }
787     function fatal($message) {
788         $message .= "\n";
789         if($this->_logfile) {
790             $this->trace($message, E_USER_ERROR);
791         }
792         echo "FATAL ERROR:: $message\n";
793         die();
794     }
796     function init_sockets() {
797         global $CFG;
799         $this->trace('Setting up sockets');
801         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
802             // Failed to create socket
803             $lasterr = socket_last_error();
804             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
805         }
807         //socket_close($DAEMON->listen_socket);
808         //die();
810         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
811             // Failed to bind socket
812             $lasterr = socket_last_error();
813             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
814         }
816         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
817             // Failed to get socket to listen
818             $lasterr = socket_last_error();
819             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
820         }
822         // Socket has been initialized and is ready
823         $this->trace('Socket opened on port '.$CFG->chat_serverport);
825         // [pj]: I really must have a good read on sockets. What exactly does this do?
826         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
827         socket_setopt($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
828         socket_set_nonblock($this->listen_socket);
829     }
831     function cli_switch($switch, $param = NULL) {
832         switch($switch) { //LOL
833             case 'reset':
834                 // Reset sockets
835                 $this->_resetsocket = true;
836                 return false;
837             case 'start':
838                 // Start the daemon
839                 $this->_readytogo = true;
840                 return false;
841             break;
842             case 'v':
843                 // Verbose mode
844                 $this->_trace_level = E_ALL;
845                 return false;
846             break;
847             case 'l':
848                 // Use logfile
849                 if(!empty($param)) {
850                     $this->_logfile_name = $param;
851                 }
852                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
853                 if($this->_logfile == false) {
854                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
855                 }
856                 return false;
857             default:
858                 // Unrecognized
859                 $this->fatal('Unrecognized command line switch: '.$switch);
860             break;
861         }
862         return false;
863     }
867 $DAEMON = New ChatDaemon;
868 set_error_handler(array($DAEMON, 'error_handler'));
870 /// Check the parameters //////////////////////////////////////////////////////
872 unset($argv[0]);
873 $commandline = implode(' ', $argv);
874 if(strpos($commandline, '-') === false) {
875     if(!empty($commandline)) {
876         // We cannot have received any meaningful parameters
877         $DAEMON->fatal('Garbage in command line');
878     }
880 else {
881     // Parse command line
882     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
884     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
885     // We will be using that to pass additional information to those switches who need it
886     $numswitches = count($switches);
888     // Fancy way to give a "hyphen" boolean flag to each "switch"
889     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
891     for($i = 0; $i < $numswitches; ++$i) {
893         $switch = $switches[$i]['str'];
894         $params = ($i == $numswitches - 1 ? NULL :
895                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
896                   );
898         if(substr($switch, 0, 2) == '--') {
899             // Double-hyphen switch
900             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
901         }
902         else if(substr($switch, 0, 1) == '-') {
903             // Single-hyphen switch(es), may be more than one run together
904             $switch = substr($switch, 1); // Get rid of the -
905             $len = strlen($switch);
906             for($j = 0; $j < $len; ++$j) {
907                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
908             }
909         }
910     }
913 if(!$DAEMON->query_start()) {
914     // For some reason we didn't start, so print out some info
915     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
916     echo "\n\n";
917     echo "Usage: chatd.php [parameters]\n\n";
918     echo "Parameters:\n";
919     echo "  --start         Starts the daemon\n";
920     echo "  -v              Verbose mode (prints trivial information messages)\n";
921     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
922     echo "Example:\n";
923     echo "  chatd.php --start -l\n\n";
924     die();
927 if (!function_exists('socket_setopt')) {
928     echo "Error: Function socket_setopt() does not exist.\n";
929     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
930     die();
933 $DAEMON->init_sockets();
935 /*
936 declare(ticks=1);
938 $pid = pcntl_fork();
939 if ($pid == -1) {
940      die("could not fork");
941 } else if ($pid) {
942      exit(); // we are the parent
943 } else {
944      // we are the child
947 // detatch from the controlling terminal
948 if (!posix_setsid()) {
949    die("could not detach from terminal");
952 // setup signal handlers
953 pcntl_signal(SIGTERM, "sig_handler");
954 pcntl_signal(SIGHUP, "sig_handler");
956 if($DAEMON->_pcntl_exists && false) {
957     $DAEMON->trace('Unholy spirit possession: daemonizing');
958     $DAEMON->pid = pcntl_fork();
959     if($pid == -1) {
960         $DAEMON->trace('Process fork failed, terminating');
961         die();
962     }
963     else if($pid) {
964         // We are the parent
965         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
966         die();
967     }
968     else {
969         // We are the daemon! :P
970     }
972     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
974     // Detach from controlling terminal
975     if(!posix_setsid()) {
976         $DAEMON->trace('Could not detach daemon process from terminal!');
977     }
979 else {
980     // Cannot go demonic
981     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
983 */
985 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
987 /// Clear the decks of old stuff
988 $DB->delete_records('chat_users', array('version'=>'sockets'));
990 while(true) {
991     $active = array();
993     // First of all, let's see if any of our UFOs has identified itself
994     if($DAEMON->conn_activity_ufo($active)) {
995         foreach($active as $handle) {
996             $read_socket = array($handle);
997             $changed = socket_select($read_socket, $write = NULL, $except = NULL, 0, 0);
999             if($changed > 0) {
1000                 // Let's see what it has to say
1002                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
1003                 if(empty($data)) {
1004                     continue;
1005                 }
1007                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1008                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1009                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1010                     continue;
1011                 }
1013                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1014                     // Malformed data
1015                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1016                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1017                     continue;
1018                 }
1020                 $type      = $info[1];
1021                 $sessionid = $info[2];
1023                 $customdata = array();
1025                 switch($type) {
1026                     case 'chat':
1027                        $type = CHAT_CONNECTION_CHANNEL;
1028                         $customdata['quirks'] = 0;
1029                         if(strpos($data, 'Safari')) {
1030                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1031                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1032                         }
1033                     break;
1034                     case 'users':
1035                         $type = CHAT_SIDEKICK_USERS;
1036                     break;
1037                     case 'beep':
1038                         $type = CHAT_SIDEKICK_BEEP;
1039                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1040                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1041                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1042                             continue;
1043                         }
1044                         else {
1045                             $customdata = array('beep' => intval($info[1]));
1046                         }
1047                     break;
1048                     case 'message':
1049                         $type = CHAT_SIDEKICK_MESSAGE;
1050                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1051                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1052                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1053                             continue;
1054                         }
1055                         else {
1056                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1057                         }
1058                     break;
1059                     default:
1060                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1061                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1062                         continue;
1063                     break;
1064                 }
1066                 // OK, now we know it's something good... promote it and pass it all the data it needs
1067                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1068                 continue;
1069             }
1070         }
1071     }
1073     $now = time();
1075     // Clean up chatrooms with no activity as required
1076     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1077         $DAEMON->poll_idle_chats($now);
1078     }
1080     // Finally, accept new connections
1081     $DAEMON->conn_accept();
1083     usleep($DAEMON->_time_rest_socket);
1086 @socket_shutdown($DAEMON->listen_socket, 0);
1087 die("\n\n-- terminated --\n");