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