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