[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/mod/chat/ -> chatd.php (source)

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


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7