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