Merge branch 'm27_MDL-43482_Lot_Of_Passed_By_Reference_Messages' of https://github...
[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 core_php_time_limit::raise(0);
61 error_reporting(E_ALL);
63 function chat_empty_connection() {
64     return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL);
65 }
67 class ChatConnection {
68     // Chat-related info
69     var $sid    = NULL;
70     var $type   = NULL;
71     //var $groupid        = NULL;
73     // PHP-level info
74     var $handle = NULL;
76     // TCP/IP
77     var $ip     = NULL;
78     var $port   = NULL;
80     function ChatConnection($resource) {
81         $this->handle = $resource;
82         @socket_getpeername($this->handle, $this->ip, $this->port);
83     }
84 }
86 class ChatDaemon {
87     var $_resetsocket       = false;
88     var $_readytogo         = false;
89     var $_logfile           = false;
90     var $_trace_to_console  = true;
91     var $_trace_to_stdout   = true;
92     var $_logfile_name      = 'chatd.log';
93     var $_last_idle_poll    = 0;
95     var $conn_ufo  = array();    // Connections not identified yet
96     var $conn_side = array();    // Sessions with sidekicks waiting for the main connection to be processed
97     var $conn_half = array();    // Sessions that have valid connections but not all of them
98     var $conn_sets = array();    // Sessions with complete connection sets sets
99     var $sets_info = array();    // Keyed by sessionid exactly like conn_sets, one of these for each of those
100     var $chatrooms = array();    // Keyed by chatid, holding arrays of data
102     // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized!
103     //            Pay extra attention when you write code that affects any of them!
105     function ChatDaemon() {
106         $this->_trace_level         = E_ALL ^ E_USER_NOTICE;
107         $this->_pcntl_exists        = function_exists('pcntl_fork');
108         $this->_time_rest_socket    = 20;
109         $this->_beepsoundsrc        = $GLOBALS['CFG']->wwwroot.'/mod/chat/beep.wav';
110         $this->_freq_update_records = 20;
111         $this->_freq_poll_idle_chat = $GLOBALS['CFG']->chat_old_ping;
112         $this->_stdout = fopen('php://stdout', 'w');
113         if($this->_stdout) {
114             // Avoid double traces for everything
115             $this->_trace_to_console = false;
116         }
117     }
119     function error_handler ($errno, $errmsg, $filename, $linenum, $vars) {
120         // Checks if an error needs to be suppressed due to @
121         if(error_reporting() != 0) {
122             $this->trace($errmsg.' on line '.$linenum, $errno);
123         }
124         return true;
125     }
127     function poll_idle_chats($now) {
128         $this->trace('Polling chats to detect disconnected users');
129         if(!empty($this->chatrooms)) {
130             foreach($this->chatrooms as $chatid => $chatroom) {
131                 if(!empty($chatroom['users'])) {
132                     foreach($chatroom['users'] as $sessionid => $userid) {
133                         // We will be polling each user as required
134                         $this->trace('...shall we poll '.$sessionid.'?');
135                         if($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) {
136                             $this->trace('YES!');
137                             // This user hasn't been polled since his last message
138                             if($this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<!-- poll -->') === false) {
139                                 // User appears to have disconnected
140                                 $this->disconnect_session($sessionid);
141                             }
142                         }
143                     }
144                 }
145             }
146         }
147         $this->_last_idle_poll = $now;
148     }
150     function query_start() {
151         return $this->_readytogo;
152     }
154     function trace($message, $level = E_USER_NOTICE) {
155         $severity = '';
157         switch($level) {
158             case E_USER_WARNING: $severity = '*IMPORTANT* '; break;
159             case E_USER_ERROR:   $severity = ' *CRITICAL* '; break;
160             case E_NOTICE:
161             case E_WARNING:      $severity = ' *CRITICAL* [php] '; break;
162         }
164         $date = date('[Y-m-d H:i:s] ');
165         $message = $date.$severity.$message."\n";
167         if ($this->_trace_level & $level) {
168             // It is accepted for output
170             // Error-class traces go to STDERR too
171             if($level & E_USER_ERROR) {
172                 fwrite(STDERR, $message);
173             }
175             // Emit the message to wherever we should
176             if($this->_trace_to_stdout) {
177                 fwrite($this->_stdout, $message);
178                 fflush($this->_stdout);
179             }
180             if($this->_trace_to_console) {
181                 echo $message;
182                 flush();
183             }
184             if($this->_logfile) {
185                 fwrite($this->_logfile, $message);
186                 fflush($this->_logfile);
187             }
188         }
189     }
191     function write_data($connection, $text) {
192         $written = @socket_write($connection, $text, strlen($text));
193         if($written === false) {
194             // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)));
195             return false;
196         }
197         return true;
199         // Enclosing the above code inside this blocks makes sure that
200         // "a socket write operation will not block". I 'm not so sure
201         // if this is needed, as we have a nonblocking socket anyway.
202         // If trouble starts to creep up, we 'll restore this.
203 //        $check_socket = array($connection);
204 //        $read = null;
205 //        $except = null;
206 //        $socket_changed = socket_select($read, $check_socket, $except, 0, 0);
207 //        if($socket_changed > 0) {
208 //
209 //            // ABOVE CODE GOES HERE
210 //
211 //        }
212 //        return false;
213     }
215     function user_lazy_update($sessionid) {
216         global $DB;
218         // TODO: this can and should be written as a single UPDATE query
219         if(empty($this->sets_info[$sessionid])) {
220             $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING);
221             return false;
222         }
224         $now = time();
226         // We 'll be cheating a little, and NOT updating the record data as
227         // often as we can, so that we save on DB queries (imagine MANY users)
228         if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) {
229             // commit to permanent storage
230             $this->sets_info[$sessionid]['lastinfocommit'] = $now;
231             $DB->update_record('chat_users', $this->sets_info[$sessionid]['chatuser']);
232         }
233         return true;
234     }
236     function get_user_window($sessionid) {
237         global $CFG, $OUTPUT;
239         static $str;
241         $info = &$this->sets_info[$sessionid];
243         $timenow = time();
245         if (empty($str)) {
246             $str->idle  = get_string("idle", "chat");
247             $str->beep  = get_string("beep", "chat");
248             $str->day   = get_string("day");
249             $str->days  = get_string("days");
250             $str->hour  = get_string("hour");
251             $str->hours = get_string("hours");
252             $str->min   = get_string("min");
253             $str->mins  = get_string("mins");
254             $str->sec   = get_string("sec");
255             $str->secs  = get_string("secs");
256             $str->years = get_string('years');
257         }
259         ob_start();
260         $refresh_inval = $CFG->chat_refresh_userlist * 1000;
261         echo <<<EOD
262         <html><head>
263         <meta http-equiv="refresh" content="$refresh_inval">
264         <style type="text/css"> img{border:0} </style>
265         <script type="text/javascript">
266         //<![CDATA[
267         function openpopup(url,name,options,fullscreen) {
268             fullurl = "$CFG->wwwroot" + url;
269             windowobj = window.open(fullurl,name,options);
270             if (fullscreen) {
271                 windowobj.moveTo(0,0);
272                 windowobj.resizeTo(screen.availWidth,screen.availHeight);
273             }
274             windowobj.focus();
275             return false;
276         }
277         //]]>
278         </script></head><body><table><tbody>
279 EOD;
281         // Get the users from that chatroom
282         $users = $this->chatrooms[$info['chatid']]['users'];
284         foreach ($users as $usersessionid => $userid) {
285             // Fetch each user's sessionid and then the rest of his data from $this->sets_info
286             $userinfo = $this->sets_info[$usersessionid];
288             $lastping = $timenow - $userinfo['chatuser']->lastmessageping;
290             echo '<tr><td width="35">';
292             $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid'];
293             $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid']));
295             $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id);
296             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
298             echo $anchortag;
299             echo "</td><td valign=\"center\">";
300             echo "<p><font size=\"1\">";
301             echo fullname($userinfo['user'])."<br />";
302             echo "<font color=\"#888888\">$str->idle: ".format_time($lastping, $str)."</font> ";
303             echo '<a target="empty" href="http://'.$CFG->chat_serverhost.':'.$CFG->chat_serverport.'/?win=beep&amp;beep='.$userinfo['user']->id.
304                  '&chat_sid='.$sessionid.'">'.$str->beep."</a>\n";
305             echo "</font></p>";
306             echo "<td></tr>";
307         }
309         echo '</tbody></table>';
311         // About 2K of HTML comments to force browsers to render the HTML
312         // echo $GLOBALS['CHAT_DUMMY_DATA'];
314         echo "</body>\n</html>\n";
316         return ob_get_clean();
318     }
320     function new_ufo_id() {
321         static $id = 0;
322         if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow
323             $id = 0;
324         }
325         return $id;
326     }
328     function process_sidekicks($sessionid) {
329         if(empty($this->conn_side[$sessionid])) {
330             return true;
331         }
332         foreach($this->conn_side[$sessionid] as $sideid => $sidekick) {
333             // TODO: is this late-dispatch working correctly?
334             $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']);
335             unset($this->conn_side[$sessionid][$sideid]);
336         }
337         return true;
338     }
340     function dispatch_sidekick($handle, $type, $sessionid, $customdata) {
341         global $CFG, $DB;
343         switch($type) {
344             case CHAT_SIDEKICK_BEEP:
346                 // Incoming beep
347                 $msg = New stdClass;
348                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
349                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
350                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
351                 $msg->system    = 0;
352                 $msg->message   = 'beep '.$customdata['beep'];
353                 $msg->timestamp = time();
355                 // Commit to DB
356                 chat_send_chatmessage($this->sets_info[$sessionid]['chatuser'], $msg->message, false,
357                     $this->sets_info[$sessionid]['cm']);
359                 // OK, now push it out to all users
360                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
362                 // Update that user's lastmessageping
363                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
364                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
365                 $this->user_lazy_update($sessionid);
367                 // We did our work, but before slamming the door on the poor browser
368                 // show the courtesy of responding to the HTTP request. Otherwise, some
369                 // browsers decide to get vengeance by flooding us with repeat requests.
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 .= "\n";
381                 // That's enough headers for one lousy dummy response
382                 $this->write_data($handle, $header);
383                 // All done
384             break;
386             case CHAT_SIDEKICK_USERS:
387                 // A request to paint a user window
389                 $content = $this->get_user_window($sessionid);
391                 $header  = "HTTP/1.1 200 OK\n";
392                 $header .= "Connection: close\n";
393                 $header .= "Date: ".date('r')."\n";
394                 $header .= "Server: Moodle\n";
395                 $header .= "Content-Type: text/html; charset=utf-8\n";
396                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
397                 $header .= "Cache-Control: no-cache, must-revalidate\n";
398                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
399                 $header .= "Content-Length: ".strlen($content)."\n";
401                 // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time.
402                 // However, if the JS doesn't work for some reason, we still want to refresh once in a while.
403                 $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&".
404                            "chat_sid=".$sessionid."\n";
405                 $header .= "\n";
407                 // That's enough headers for one lousy dummy response
408                 $this->trace('writing users http response to handle '.$handle);
409                 $this->write_data($handle, $header . $content);
411                 // Update that user's lastping
412                 $this->sets_info[$sessionid]['chatuser']->lastping = time();
413                 $this->user_lazy_update($sessionid);
415             break;
417             case CHAT_SIDEKICK_MESSAGE:
418                 // Incoming message
420                 // Browser stupidity protection from duplicate messages:
421                 $messageindex = intval($customdata['index']);
423                 if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) {
424                     // We have already broadcasted that!
425                     // $this->trace('discarding message with stale index');
426                     break;
427                 }
428                 else {
429                     // Update our info
430                     $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex;
431                 }
433                 $msg = New stdClass;
434                 $msg->chatid    = $this->sets_info[$sessionid]['chatid'];
435                 $msg->userid    = $this->sets_info[$sessionid]['userid'];
436                 $msg->groupid   = $this->sets_info[$sessionid]['groupid'];
437                 $msg->system    = 0;
438                 $msg->message   = urldecode($customdata['message']); // have to undo the browser's encoding
439                 $msg->timestamp = time();
441                 if(empty($msg->message)) {
442                     // Someone just hit ENTER, send them on their way
443                     break;
444                 }
446                 // A slight hack to prevent malformed SQL inserts
447                 $origmsg = $msg->message;
448                 $msg->message = $msg->message;
450                 // Commit to DB
451                 chat_send_chatmessage($this->sets_info[$sessionid]['chatuser'], $msg->message, false,
452                     $this->sets_info[$sessionid]['cm']);
454                 // Undo the hack
455                 $msg->message = $origmsg;
457                 // OK, now push it out to all users
458                 $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
460                 // Update that user's lastmessageping
461                 $this->sets_info[$sessionid]['chatuser']->lastping        = $msg->timestamp;
462                 $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp;
463                 $this->user_lazy_update($sessionid);
465                 // We did our work, but before slamming the door on the poor browser
466                 // show the courtesy of responding to the HTTP request. Otherwise, some
467                 // browsers decide to get vengeance by flooding us with repeat requests.
469                 $header  = "HTTP/1.1 200 OK\n";
470                 $header .= "Connection: close\n";
471                 $header .= "Date: ".date('r')."\n";
472                 $header .= "Server: Moodle\n";
473                 $header .= "Content-Type: text/html; charset=utf-8\n";
474                 $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
475                 $header .= "Cache-Control: no-cache, must-revalidate\n";
476                 $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
477                 $header .= "\n";
479                 // That's enough headers for one lousy dummy response
480                 $this->write_data($handle, $header);
482                 // All done
483             break;
484         }
486         socket_shutdown($handle);
487         socket_close($handle);
488     }
490     function promote_final($sessionid, $customdata) {
491         global $DB;
493         if(isset($this->conn_sets[$sessionid])) {
494             $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active');
495             return false;
496         }
498         $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid));
499         if($chatuser === false) {
500             $this->dismiss_half($sessionid);
501             return false;
502         }
503         $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid));
504         if($chat === false) {
505             $this->dismiss_half($sessionid);
506             return false;
507         }
508         $user = $DB->get_record('user', array('id'=>$chatuser->userid));
509         if($user === false) {
510             $this->dismiss_half($sessionid);
511             return false;
512         }
513         $course = $DB->get_record('course', array('id'=>$chat->course));
514         if($course === false) {
515             $this->dismiss_half($sessionid);
516             return false;
517         }
518         if (!($cm = get_coursemodule_from_instance('chat', $chat->id, $course->id))) {
519             $this->dismiss_half($sessionid);
520             return false;
521         }
523         global $CHAT_HTMLHEAD_JS, $CFG;
525         $this->conn_sets[$sessionid] = $this->conn_half[$sessionid];
527         // This whole thing needs to be purged of redundant info, and the
528         // code base to follow suit. But AFTER development is done.
529         $this->sets_info[$sessionid] = array(
530             'lastinfocommit' => 0,
531             'lastmessageindex' => 0,
532             'course'    => $course,
533             'courseid'  => $course->id,
534             'chatuser'  => $chatuser,
535             'chatid'    => $chat->id,
536             'cm'        => $cm,
537             'user'      => $user,
538             'userid'    => $user->id,
539             'groupid'   => $chatuser->groupid,
540             'lang'      => $chatuser->lang,
541             'quirks'    => $customdata['quirks']
542         );
544         // If we know nothing about this chatroom, initialize it and add the user
545         if(!isset($this->chatrooms[$chat->id]['users'])) {
546             $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id);
547         }
548         else {
549             // Otherwise just add the user
550             $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id;
551         }
553         // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']);
555         $header  = "HTTP/1.1 200 OK\n";
556         $header .= "Connection: close\n";
557         $header .= "Date: ".date('r')."\n";
558         $header .= "Server: Moodle\n";
559         $header .= "Content-Type: text/html; charset=utf-8\n";
560         $header .= "Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT\n";
561         $header .= "Cache-Control: no-cache, must-revalidate\n";
562         $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n";
563         $header .= "\n";
565         $this->dismiss_half($sessionid, false);
566         $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $header . $CHAT_HTMLHEAD_JS);
567         $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING);
569         // Finally, broadcast the "entered the chat" message
571         $msg = new stdClass;
572         $msg->chatid = $chatuser->chatid;
573         $msg->userid = $chatuser->userid;
574         $msg->groupid = $chatuser->groupid;
575         $msg->system = 1;
576         $msg->message = 'enter';
577         $msg->timestamp = time();
579         chat_send_chatmessage($chatuser, $msg->message, true);
580         $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']);
582         return true;
583     }
585     function promote_ufo($handle, $type, $sessionid, $customdata) {
586         if(empty($this->conn_ufo)) {
587             return false;
588         }
589         foreach($this->conn_ufo as $id => $ufo) {
590             if($ufo->handle == $handle) {
591                 // OK, got the id of the UFO, but what is it?
593                 if($type & CHAT_SIDEKICK) {
594                     // Is the main connection ready?
595                     if(isset($this->conn_sets[$sessionid])) {
596                         // Yes, so dispatch this sidekick now and be done with it
597                         //$this->trace('Dispatching sidekick immediately');
598                         $this->dispatch_sidekick($handle, $type, $sessionid, $customdata);
599                         $this->dismiss_ufo($handle, false);
600                     }
601                     else {
602                         // No, so put it in the waiting list
603                         $this->trace('sidekick waiting');
604                         $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata);
605                     }
606                     return true;
607                 }
609                 // If it's not a sidekick, at this point it can only be da man
611                 if($type & CHAT_CONNECTION) {
612                     // This forces a new connection right now...
613                     $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port);
615                     // Do we have such a connection active?
616                     if(isset($this->conn_sets[$sessionid])) {
617                         // Yes, so regrettably we cannot promote you
618                         $this->trace('Connection rejected: session '.$sessionid.' is already final');
619                         $this->dismiss_ufo($handle, true, 'Your SID was rejected.');
620                         return false;
621                     }
623                     // Join this with what we may have already
624                     $this->conn_half[$sessionid][$type] = $handle;
626                     // Do the bookkeeping
627                     $this->promote_final($sessionid, $customdata);
629                     // It's not an UFO anymore
630                     $this->dismiss_ufo($handle, false);
632                     // Dispatch waiting sidekicks
633                     $this->process_sidekicks($sessionid);
635                     return true;
636                 }
637             }
638         }
639         return false;
640     }
642     function dismiss_half($sessionid, $disconnect = true) {
643         if(!isset($this->conn_half[$sessionid])) {
644             return false;
645         }
646         if($disconnect) {
647             foreach($this->conn_half[$sessionid] as $handle) {
648                 @socket_shutdown($handle);
649                 @socket_close($handle);
650             }
651         }
652         unset($this->conn_half[$sessionid]);
653         return true;
654     }
656     function dismiss_set($sessionid) {
657         if(!empty($this->conn_sets[$sessionid])) {
658             foreach($this->conn_sets[$sessionid] as $handle) {
659                 // Since we want to dismiss this, don't generate any errors if it's dead already
660                 @socket_shutdown($handle);
661                 @socket_close($handle);
662             }
663         }
664         $chatroom = $this->sets_info[$sessionid]['chatid'];
665         $userid   = $this->sets_info[$sessionid]['userid'];
666         unset($this->conn_sets[$sessionid]);
667         unset($this->sets_info[$sessionid]);
668         unset($this->chatrooms[$chatroom]['users'][$sessionid]);
669         $this->trace('Removed all traces of user with session '.$sessionid, E_USER_NOTICE);
670         return true;
671     }
674     function dismiss_ufo($handle, $disconnect = true, $message = NULL) {
675         if(empty($this->conn_ufo)) {
676             return false;
677         }
678         foreach($this->conn_ufo as $id => $ufo) {
679             if($ufo->handle == $handle) {
680                 unset($this->conn_ufo[$id]);
681                 if($disconnect) {
682                     if(!empty($message)) {
683                         $this->write_data($handle, $message."\n\n");
684                     }
685                     socket_shutdown($handle);
686                     socket_close($handle);
687                 }
688                 return true;
689             }
690         }
691         return false;
692     }
694     function conn_accept() {
695         $read_socket = array($this->listen_socket);
696         $write = null;
697         $except = null;
698         $changed = socket_select($read_socket, $write, $except, 0, 0);
700         if(!$changed) {
701             return false;
702         }
703         $handle = socket_accept($this->listen_socket);
704         if(!$handle) {
705             return false;
706         }
708         $newconn = New ChatConnection($handle);
709         $id = $this->new_ufo_id();
710         $this->conn_ufo[$id] = $newconn;
712         //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle);
713     }
715     function conn_activity_ufo (&$handles) {
716         $monitor = array();
717         if(!empty($this->conn_ufo)) {
718             foreach($this->conn_ufo as $ufoid => $ufo) {
719                 $monitor[$ufoid] = $ufo->handle;
720             }
721         }
723         if(empty($monitor)) {
724             $handles = array();
725             return 0;
726         }
728         $a = null;
729         $b = null;
730         $retval = socket_select($monitor, $a, $b, null);
731         $handles = $monitor;
733         return $retval;
734     }
736     function message_broadcast($message, $sender) {
738         if(empty($this->conn_sets)) {
739             return true;
740         }
742         $now = time();
744         // First of all, mark this chatroom as having had activity now
745         $this->chatrooms[$message->chatid]['lastactivity'] = $now;
747         foreach($this->sets_info as $sessionid => $info) {
748             // We need to get handles from users that are in the same chatroom, same group
749             if($info['chatid'] == $message->chatid &&
750               ($info['groupid'] == $message->groupid || $message->groupid == 0))
751             {
753                 // Simply give them the message
754                 $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']);
755                 $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]);
757                 if($output->beep) {
758                     $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '<embed src="'.$this->_beepsoundsrc.'" autostart="true" hidden="true" />');
759                 }
761                 if($info['quirks'] & QUIRK_CHUNK_UPDATE) {
762                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
763                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
764                     $output->html .= $GLOBALS['CHAT_DUMMY_DATA'];
765                 }
767                 if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) {
768                     $this->disconnect_session($sessionid);
769                 }
770                 //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_);
771             }
772         }
773     }
775     function disconnect_session($sessionid) {
776         global $DB;
778         $info = $this->sets_info[$sessionid];
780         $DB->delete_records('chat_users', array('sid'=>$sessionid));
781         $msg = New stdClass;
782         $msg->chatid = $info['chatid'];
783         $msg->userid = $info['userid'];
784         $msg->groupid = $info['groupid'];
785         $msg->system = 1;
786         $msg->message = 'exit';
787         $msg->timestamp = time();
789         $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING);
790         chat_send_chatmessage($info['chatuser'], $msg->message, true);
792         // *************************** IMPORTANT
793         //
794         // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion!
795         //
796         // **********************************************************************
797         $latesender = $info['user'];
798         $this->dismiss_set($sessionid);
799         $this->message_broadcast($msg, $latesender);
800     }
802     function fatal($message) {
803         $message .= "\n";
804         if($this->_logfile) {
805             $this->trace($message, E_USER_ERROR);
806         }
807         echo "FATAL ERROR:: $message\n";
808         die();
809     }
811     function init_sockets() {
812         global $CFG;
814         $this->trace('Setting up sockets');
816         if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
817             // Failed to create socket
818             $lasterr = socket_last_error();
819             $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
820         }
822         //socket_close($DAEMON->listen_socket);
823         //die();
825         if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) {
826             // Failed to bind socket
827             $lasterr = socket_last_error();
828             $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
829         }
831         if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) {
832             // Failed to get socket to listen
833             $lasterr = socket_last_error();
834             $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']');
835         }
837         // Socket has been initialized and is ready
838         $this->trace('Socket opened on port '.$CFG->chat_serverport);
840         // [pj]: I really must have a good read on sockets. What exactly does this do?
841         // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me.
842         socket_set_option($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1);
843         socket_set_nonblock($this->listen_socket);
844     }
846     function cli_switch($switch, $param = NULL) {
847         switch($switch) { //LOL
848             case 'reset':
849                 // Reset sockets
850                 $this->_resetsocket = true;
851                 return false;
852             case 'start':
853                 // Start the daemon
854                 $this->_readytogo = true;
855                 return false;
856             break;
857             case 'v':
858                 // Verbose mode
859                 $this->_trace_level = E_ALL;
860                 return false;
861             break;
862             case 'l':
863                 // Use logfile
864                 if(!empty($param)) {
865                     $this->_logfile_name = $param;
866                 }
867                 $this->_logfile = @fopen($this->_logfile_name, 'a+');
868                 if($this->_logfile == false) {
869                     $this->fatal('Failed to open '.$this->_logfile_name.' for writing');
870                 }
871                 return false;
872             default:
873                 // Unrecognized
874                 $this->fatal('Unrecognized command line switch: '.$switch);
875             break;
876         }
877         return false;
878     }
882 $DAEMON = New ChatDaemon;
883 set_error_handler(array($DAEMON, 'error_handler'));
885 /// Check the parameters //////////////////////////////////////////////////////
887 unset($argv[0]);
888 $commandline = implode(' ', $argv);
889 if(strpos($commandline, '-') === false) {
890     if(!empty($commandline)) {
891         // We cannot have received any meaningful parameters
892         $DAEMON->fatal('Garbage in command line');
893     }
895 else {
896     // Parse command line
897     $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
899     // Taking advantage of the fact that $switches is indexed with incrementing numeric keys
900     // We will be using that to pass additional information to those switches who need it
901     $numswitches = count($switches);
903     // Fancy way to give a "hyphen" boolean flag to each "switch"
904     $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches);
906     for($i = 0; $i < $numswitches; ++$i) {
908         $switch = $switches[$i]['str'];
909         $params = ($i == $numswitches - 1 ? NULL :
910                                             ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str']))
911                   );
913         if(substr($switch, 0, 2) == '--') {
914             // Double-hyphen switch
915             $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params);
916         }
917         else if(substr($switch, 0, 1) == '-') {
918             // Single-hyphen switch(es), may be more than one run together
919             $switch = substr($switch, 1); // Get rid of the -
920             $len = strlen($switch);
921             for($j = 0; $j < $len; ++$j) {
922                 $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params);
923             }
924         }
925     }
928 if(!$DAEMON->query_start()) {
929     // For some reason we didn't start, so print out some info
930     echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport;
931     echo "\n\n";
932     echo "Usage: chatd.php [parameters]\n\n";
933     echo "Parameters:\n";
934     echo "  --start         Starts the daemon\n";
935     echo "  -v              Verbose mode (prints trivial information messages)\n";
936     echo "  -l [logfile]    Log all messages to logfile (if not specified, chatd.log)\n";
937     echo "Example:\n";
938     echo "  chatd.php --start -l\n\n";
939     die();
942 if (!function_exists('socket_set_option')) {
943     echo "Error: Function socket_set_option() does not exist.\n";
944     echo "Possibly PHP has not been compiled with --enable-sockets.\n\n";
945     die();
948 $DAEMON->init_sockets();
950 /*
951 declare(ticks=1);
953 $pid = pcntl_fork();
954 if ($pid == -1) {
955      die("could not fork");
956 } else if ($pid) {
957      exit(); // we are the parent
958 } else {
959      // we are the child
962 // detatch from the controlling terminal
963 if (!posix_setsid()) {
964    die("could not detach from terminal");
967 // setup signal handlers
968 pcntl_signal(SIGTERM, "sig_handler");
969 pcntl_signal(SIGHUP, "sig_handler");
971 if($DAEMON->_pcntl_exists && false) {
972     $DAEMON->trace('Unholy spirit possession: daemonizing');
973     $DAEMON->pid = pcntl_fork();
974     if($pid == -1) {
975         $DAEMON->trace('Process fork failed, terminating');
976         die();
977     }
978     else if($pid) {
979         // We are the parent
980         $DAEMON->trace('Successfully forked the daemon with PID '.$pid);
981         die();
982     }
983     else {
984         // We are the daemon! :P
985     }
987     // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING!
989     // Detach from controlling terminal
990     if(!posix_setsid()) {
991         $DAEMON->trace('Could not detach daemon process from terminal!');
992     }
994 else {
995     // Cannot go demonic
996     $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl');
998 */
1000 $DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING);
1002 /// Clear the decks of old stuff
1003 $DB->delete_records('chat_users', array('version'=>'sockets'));
1005 while(true) {
1006     $active = array();
1008     // First of all, let's see if any of our UFOs has identified itself
1009     if($DAEMON->conn_activity_ufo($active)) {
1010         foreach($active as $handle) {
1011             $read_socket = array($handle);
1012             $write = null;
1013             $except = null;
1014             $changed = socket_select($read_socket, $write, $except, 0, 0);
1016             if($changed > 0) {
1017                 // Let's see what it has to say
1019                 $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!!
1020                 if(empty($data)) {
1021                     continue;
1022                 }
1024                 if (strlen($data) == 2048) { // socket_read has more data, ignore all data
1025                     $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING);
1026                     $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed');
1027                     continue;
1028                 }
1030                 if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) {
1031                     // Malformed data
1032                     $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING);
1033                     $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1034                     continue;
1035                 }
1037                 $type      = $info[1];
1038                 $sessionid = $info[2];
1040                 $customdata = array();
1042                 switch($type) {
1043                     case 'chat':
1044                        $type = CHAT_CONNECTION_CHANNEL;
1045                         $customdata['quirks'] = 0;
1046                         if(strpos($data, 'Safari')) {
1047                             $DAEMON->trace('Safari identified...', E_USER_WARNING);
1048                             $customdata['quirks'] += QUIRK_CHUNK_UPDATE;
1049                         }
1050                     break;
1051                     case 'users':
1052                         $type = CHAT_SIDEKICK_USERS;
1053                     break;
1054                     case 'beep':
1055                         $type = CHAT_SIDEKICK_BEEP;
1056                         if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) {
1057                             $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING);
1058                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1059                             continue;
1060                         }
1061                         else {
1062                             $customdata = array('beep' => intval($info[1]));
1063                         }
1064                     break;
1065                     case 'message':
1066                         $type = CHAT_SIDEKICK_MESSAGE;
1067                         if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) {
1068                             $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING);
1069                             $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed');
1070                             continue;
1071                         }
1072                         else {
1073                             $customdata = array('message' => $info[1], 'index' => $info[2]);
1074                         }
1075                     break;
1076                     default:
1077                         $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING);
1078                         $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed');
1079                         continue;
1080                     break;
1081                 }
1083                 // OK, now we know it's something good... promote it and pass it all the data it needs
1084                 $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata);
1085                 continue;
1086             }
1087         }
1088     }
1090     $now = time();
1092     // Clean up chatrooms with no activity as required
1093     if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) {
1094         $DAEMON->poll_idle_chats($now);
1095     }
1097     // Finally, accept new connections
1098     $DAEMON->conn_accept();
1100     usleep($DAEMON->_time_rest_socket);
1103 @socket_shutdown($DAEMON->listen_socket, 0);
1104 die("\n\n-- terminated --\n");