<?php

/*
* Class written by Thomas Smit 6/12/06 - 7/12/06, composed from slightly messy procedural code found from unknown source
* Some of the code isn't nice but was found to be necessary through testing
*/

class ts_interface
{

    private 
$users = array();    // @var array $users - user list
    
private $conn;               // @var resource $conn - connection to server

    /*
    * ts_interface::__construct() - try opening connection to server
    * @param str $ip - IP of TS server
    * @param int $port - port of server
    * @param int $tcp - TCP port of server
    * @return void
    */

    
public function __construct($ip$port$tcp 51234)
    {
        
$conn = @fsockopen($ip$tcp$errno$errstr10);
        if(
$conn)
        {
            
$this->conn $conn;
            
$this->command('SEL ' $port);
            
$this->command('pl');

            if(
fgets($this->conn) != '[TS]' "\r\n")
                throw new 
Exception('No TeamSpeak server found on this port.');
            else
                
$this->connect();
        }
        else
            throw new 
Exception($errstr);
    }

    
/*
    * ts_interface::connect() - try connecting to TS server (all fgets() needed to get info)
    * @return void
    */

    
private function connect()
    {
        
fgets($this->conn);
        if(
fgets($this->conn) != 'OK' "\r\n")
        {
            while(
$users['p_id'] != 'OK' "\r\n")
            {
                list(
$users['p_id'], $users['c_id'], $users['ps'], $users['bs'], $users['pr'], $users['br'], $users['pl'], $users['ping'], $users['logintime'], $users['idletime'], $users['cprivs'], $users['pprivs'], $users['pflags'], $users['ip'], $users['nick'], $users['loginname']) = explode("    "fgets($this->conn));
                
$this->users[] = $users;
            }
            unset(
$this->users[count($this->users) - 1]);
        }
    }

    
/*
    * ts_interface::command() - execute a TS command
    * @param str $command - command to execute
    * @return boolean
    */

    
protected function command($command)
    {
        return (
fwrite($this->conn$command "\r\n")) ? true false;
    }

    
/*
    * ts_interface::getusers() - return associative array containing user list
    * @return array
    */

    
public function getusers()
    {
        return 
$this->users;
    }

    
/*
    * ts_interface::__destruct() - close connection to server
    * @return void
    */

    
public function __destruct()
    {
        
fclose($this->conn);
    }

}

?>