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