<?php

require_once 'newedge/classes/NE_Error.php';
require_once 'newedge/classes/NE_MailGateway.php';
require_once 'classes/domain.php';
require_once 'classes/ServerPlugin.php';
/**
* @package Plugins
*/
class PluginCastcontrol extends ServerPlugin
{
        
		
	var $apierror='';
		
    /*****************************************************************/
    // function getVariables - required function
    /*****************************************************************/
    function getVariables(){
        /* Specification
              itemkey     - used to identify variable in your other functions
              type        - text,textarea,yesno,password
              description - description of the variable, displayed in ClientExec
        */
    
    
    
        $variables = array (
                   /*T*/"Name"/*/T*/ => array (
                                        "type"          => "hidden",
                                        "description"   => "Used By CE to show plugin - must match how you call the action function names",
                                        "value"         => "Castcontrol"
                                       ),
                   /*T*/"Description"/*/T*/ => array (
                                        "type"          => "hidden",
                                        "description"   => /*T*/"Description viewable by admin in server settings"/*/T*/,
                                        "value"         => /*T*/"Cast-Control server integration.  Note: The custom field settings are used to hold information about the clients server.  Please create these fields in admin->custom fields->packages first.  The package name on server fields for each package hold the slot count.  Suspending a server sets the slot count to 0."/*/T*/
                                       ),
                   /*T*/"HTTP SSL"/*/T*/ => array (
                                        "type"          => "yesno",
                                        "description"   => /*T*/"Must also specify appropriate HTTP Port, usually 443"/*/T*/,
                                        "value"         => ""
                                       ),
                   /*T*/"HTTP Host"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"DOMAIN/HOST, DO NOT INCLUDE http:// PREFIX (EG: mydomain.com)"/*/T*/,
                                        "value"         => ""
                                       ),
                   /*T*/"HTTP Port"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"SHOULD GENERALLY BE 80"/*/T*/,
                                        "value"         => "80"
                                       ),
                   /*T*/"HTTP Path"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"PATH TO THE CAST-CONTROL ROOT DIRECTORY (EG: /shoutcast/)   *MUST END IN FORWARD SLASH"/*/T*/,
                                        "value"         => "/"
                                       ),
                   /*T*/"API Key"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"CAST-CONTROL SECURITY HASH "/*/T*/,
                                        "value"         => ""
                                       ),
                   /*T*/"Portbase Custom Field"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"Package Custom Field Name"/*/T*/,
                                        "value"         => ""
                                       ),
                   /*T*/"Username Custom Field"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"Package Custom Field Name"/*/T*/,
                                        "value"         => ""
                                       ),
                   /*T*/"Password Custom Field"/*/T*/ => array (
                                        "type"          => "text",
                                        "description"   => /*T*/"Package Custom Field Name"/*/T*/,
                                        "value"         => ""
                                       ),
									   
									   
                   /*T*/"Actions"/*/T*/ => array (
                                        "type"          => "hidden",
                                        "description"   => /*T*/"Current actions that are active for this plugin per server"/*/T*/,
                                        "value"         => "Create,Update,Delete,Suspend,Unsuspend"
                                       ),
		            /*T*/'package_vars_values'/*/T*/ => array(
		                'type'          => 'hidden',
		                'description'   => /*T*/'Hosting account parameters'/*/T*/,
		                'value'         => array(
		                                        'BitRate' => array(
		                                                                'type'          => 'text',
																		'size'			=> '5',
																		'description'	=> 'Bitrate',
																		'value'			=> '24',
		                                                            //    "options"		=> "8,16,20,24,32,40,48,56,64,80,96,112,128,160,192,224,256,320,384,512,768,1024"
		                                                           ),
		                                        'MaxUsers' => array(
		                                                                'type'          => 'text',
																		'size'			=> '5',
		                                                                'description'   => /*T*/'Listener Slots'/*/T*/,
		                                                                'value'         => '25',
		                                                           ),
		                                        'Bandwidth' => array(
		                                                                'type'          => 'text',
																		'size'			=> '5',
		                                                                'description'   => /*T*/'Bandwidth'/*/T*/,
		                                                                'value'         => '0',
		                                                           ),
		                                        'AutoDJ' => array(
		                                                                'type'          => 'yesno',
																		'size'			=> '5',
		                                                                'description'   => /*T*/'Allow AutoDJ'/*/T*/,
																		'options'		=> 'enabled,disabled'
		                                                           ),
		                                        'AutoDJ Quota' => array(
		                                                                'type'          => 'text',
																		'size'			=> '5',
		                                                                'description'   => /*T*/'AutoDJ Quota'/*/T*/,
		                                                                'value'         => '25',
		                                                           ),
		                                        'Trial' => array(
		                                                                'type'          => 'text',
																		'size'			=> '15',
		                                                                'description'   => /*T*/'Set Trial Period for example: +5 days'/*/T*/,
																		'options'		=> ''
		                                                           ),
		                                        'SystemID' => array(
		                                                                'type'          => 'text',
																		'size'			=> '5',
		                                                                'description'   => /*T*/'SystemID'/*/T*/,
		                                                                'value'         => '25',
		                                                           ),
											)
										)

							);
        return $variables;
    }
    

    function createUserName($params)
    {
        return $params['DomainUsername'];
    }
    
    function create($params)
    {
		if ( $params['plugin_castcontrol_Create'] == 0 )
		{	return;		}
		
    	$package = new Domain($params['PackageID'], $this->user);
    	$package->PopulateCustomFields();
		$package->getCustomFieldsValue($params['plugin_castcontrol_Username_Custom_Field'], $username); 
		$package->getCustomFieldsValue($params['plugin_castcontrol_Password_Custom_Field'], $password);

		
		if ( empty($username) || empty($password) )
		{	return new NE_Error("The username or password contains no value", 90);	}
		
		
	// Firstly we need to create the user account, if one already exists we will skip
	
		$api['auth']		= $params["plugin_castcontrol_API_Key"];
		$api['http_ssl']	= $params["plugin_castcontrol_HTTP_SSL"];
		$api['http_host']	= $params["plugin_castcontrol_HTTP_Host"];
		$api['http_path']	= $params["plugin_castcontrol_HTTP_Path"];
		$api['http_port']	= $params["plugin_castcontrol_HTTP_Port"];
		$api['cmd']			= 'newuser';
		$api['username']	= $username;
		$api['password']	= $password;
		$api['email_address']= $params['UserEmail'];

		
		if (  $response = api( $api )   )
		{
			list($status, $msg) = split(",", $response);

			
		 	if ( $status != 'Success' && strstr($response, 'incorrect_password') )
			{	return new NE_Error("This username already exists or you have entered incorrect credentials. :: ".$response, 90);		}
		
		
			if ( $status != 'Success'  && $msg != 'User already exists')
			{	return new NE_Error("There was a problem creating the user account in cast-control :: $response", 90);	}
			
		}else if ($this->apierror = 'auth_failed'){
			return new NE_Error("Cast-Control API Authentication error, please check API Key", 90);
		}else{
			return new NE_Error("Could not communicate with the Cast-Control API", 90);
		}
		unset($api);



	// Once User is created, we can now create the server
		$api['auth']		= $params["plugin_castcontrol_API_Key"];
		$api['http_ssl']	= $params["plugin_castcontrol_HTTP_SSL"];
		$api['http_host']	= $params["plugin_castcontrol_HTTP_Host"];
		$api['http_path']	= $params["plugin_castcontrol_HTTP_Path"];
		$api['http_port']	= $params["plugin_castcontrol_HTTP_Port"];
		$api['cmd']			= 'newserver';
		$api['plan']		= false;
		$api['username']	= $username;
		$api['srv_password']= $password;
		$api['slots']		= $params["package_vars"]["MaxUsers"];
		$api['bitrate']		= $params["package_vars"]["BitRate"];
		$api['bandwidth']	= $params["package_vars"]["Bandwidth"];
		$api['autodj']		= (isset($params["package_vars"]["AutoDJ"]) && $params['package_vars']['AutoDJ']==1)? 'Enabled' : 'Disabled';
		$api['autodj_upload']= $params["package_vars"]["AutoDJ_Quota"];
		
		if ( isset($params["package_vars"]["Trial"]) && $params["package_vars"]["Trial"] != '' &&  $params["package_vars"]["Trial"] != 'disabled' ){
			$api['expire']		=$params["package_vars"]["Trial"];
		}
		
		if ( !empty($params["package_vars"]["SystemID"]) )
		{	$api['system']	=  $params["package_vars"]["SystemID"];	}

		//	Configurable Options
			if ( isset($params['package_addons']['MaxUsers']) )	{		$api['slots']		= $params['package_addons']['MaxUsers'];		}
			if ( isset($params['package_addons']['BitRate']) )	{		$api['bitrate']		= $params['package_addons']['BitRate'];			}
			if ( isset($params['package_addons']['Bandwidth']) ){		$api['bandwidth']	= $params['package_addons']['Bandwidth'];		}
			if ( isset($params['package_addons']['AutoDJ']) )	{		$api['autodj']		= $params['package_addons']['AutoDJ'];			}
			if ( isset($params['package_addons']['AutoDJQuota']) ){		$api['autodj_upload']=$params['package_addons']['AutoDJQuota'];	}
			if ( isset($params['package_addons']['System']) ){			$api['SystemID']=$params['package_addons']['System'];	}
		//	Configurable Options

		if (   $response = api($api)   )
		{
			// Here we have successfully connected and authenticated to the cast-control API
			list($status, $portbase, $msg) = split(",", $response);
			if ( $status != 'Success' )
			{	return new NE_Error("There was a problem creating the server in cast-control:: '$status' :: {$response}", 90);	}
			
			$package = new Domain($params['PackageID'], $this->user);
	    	$package->PopulateCustomFields();
			$package->UpdateCustomTag($params['plugin_castcontrol_Portbase_Custom_Field'], $portbase);

		}else if ($this->apierror = 'auth_failed'){
			return new NE_Error("Cast-Control API Authentication error, please check API Key", 90);
		}else{
			//			API FAILED
			//		Ussually either no connection has been established
			//		or  the API key is incorrect.
			return new NE_Error("User created, Could not communicate with the Cast-Control API", 90);
		}
		
		// Reach here, Success
		return;
    }
    
	
    function delete($params)
    {
		if ( $params['plugin_castcontrol_Delete'] == 0 )
		{	return;		}
	
    	$package = new Domain($params['PackageID'], $this->user);
    	$package->PopulateCustomFields();
		$package->getCustomFieldsValue($params['plugin_castcontrol_Portbase_Custom_Field'], $portbase); 

		if ( empty($portbase) )
		{	// If protbase is empty, ignore the process as no server was assigned
			return;
		}
		
		$api['auth']		= $params["plugin_castcontrol_API_Key"];
		$api['http_ssl']	= $params["plugin_castcontrol_HTTP_SSL"];
		$api['http_host']	= $params["plugin_castcontrol_HTTP_Host"];
		$api['http_path']	= $params["plugin_castcontrol_HTTP_Path"];
		$api['http_port']	= $params["plugin_castcontrol_HTTP_Port"];
		$api['cmd']			= 'delserver';
		$api['port']		= $portbase;
		
		if (   $response = api( $api )   )
		{
			// Here we have successfully connected and authenticated to the cast-control API
			
			list($status, $msg) = split(",", $response);

			if ( $status != 'Success' )
			{	return new NE_Error("There was a problem terminating the server in cast-control:: {$response}", 90);	}
			
			$package = new Domain($params['PackageID'], $this->user);
	    	$package->PopulateCustomFields();
			$package->UpdateCustomTag($params['plugin_castcontrol_Portbase_Custom_Field'], '');
		}else if ($this->apierror = 'auth_failed'){
			return new NE_Error("Cast-Control API Authentication error, please check API Key", 90);
		}else{
			//			API FAILED
			//		Ussually either no connection has been established
			//		or  the API key is incorrect.
			return new NE_Error("User created, Could not communicate with the Cast-Control API", 90);

		}
		
		
		//Reach here, Success
		return;
    }
    
	
    function update($params)
    {
		// No Action required here
		return true;
    }
	
	
    function suspend($params) {

		if ( $params['plugin_castcontrol_Suspend'] == 0 )
		{	return;	}
		
    	$package = new Domain($params['PackageID'], $this->user);
    	$package->PopulateCustomFields();
		$package->getCustomFieldsValue($params['plugin_castcontrol_Portbase_Custom_Field'], $portbase); 

		if ( empty($portbase) )
		{	// If protbase is empty, ignore the process as no server was assigned
			return;
		}
		
		$api['auth']		= $params["plugin_castcontrol_API_Key"];
		$api['http_ssl']	= $params["plugin_castcontrol_HTTP_SSL"];
		$api['http_host']	= $params["plugin_castcontrol_HTTP_Host"];
		$api['http_path']	= $params["plugin_castcontrol_HTTP_Path"];
		$api['http_port']	= $params["plugin_castcontrol_HTTP_Port"];
		$api['cmd']			= 'suspend';
		$api['port']		= $portbase;
		$api['reason']		= 'Suspended by ClientExec';
		$api['days']		= 9999999999999; // indefinite 
		
		if (   $response = api( $api )   )
		{
			// Here we have successfully connected and authenticated to the cast-control API
			
			list($status, $msg) = split(",", $response);
			
			if ( $status != 'Success' )
			{	return new NE_Error("There was a problem suspending the server:: {$response}", 90);	}

		}else if ($this->apierror = 'auth_failed'){
			return new NE_Error("Cast-Control API Authentication error, please check API Key", 90);
		}else{
			//			API FAILED
			//		Ussually either no connection has been established
			//		or  the API key is incorrect.
			return new NE_Error("Could not communicate with the Cast-Control API", 90);
		}
		
		// Reach here, Success
		return;
    }
    
	
    function unsuspend($params) {
	
		if ( $params['plugin_castcontrol_Unsuspend'] == 0 )
		{	return;		}

    	$package = new Domain($params['PackageID'], $this->user);
    	$package->PopulateCustomFields();
		$package->getCustomFieldsValue($params['plugin_castcontrol_Portbase_Custom_Field'], $portbase); 

		if ( empty($portbase) )
		{	// If protbase is empty, ignore the process as no server was assigned
			return;
		}
		
		
		$api['auth']		= $params["plugin_castcontrol_API_Key"];
	    $api['http_ssl']	= $params["plugin_castcontrol_HTTP_SSL"];	
		$api['http_host']	= $params["plugin_castcontrol_HTTP_Host"];
		$api['http_path']	= $params["plugin_castcontrol_HTTP_Path"];
		$api['http_port']	= $params["plugin_castcontrol_HTTP_Port"];
		$api['cmd']			= 'unsuspend';
		$api['port']		= $portbase;
		$api['start']		= true;
		

		if (   $response = api( $api )  )
		{
			// Here we have successfully connected and authenticated to the cast-control API
			
			list($status, $msg) = split(",", $response);
			
			if ( $status != 'Success' )
			{	return new NE_Error("There was a problem unsuspending the server:: {$response}", 90);	}

		}else if ($this->apierror = 'auth_failed'){
			return new NE_Error("Cast-Control API Authentication error, please check API Key", 90);
		}else{
			//			API FAILED
			//		Ussually either no connection has been established
			//		or  the API key is incorrect.
			
			return new NE_Error("Could not communicate with the Cast-Control API", 90);
		}
		
		// Reach here, Success
		return;
    }
	
	
	
}






/*	_---------------------------------------	*/
	function api( $api )
	{
		
	    // Establish connection

	    $scheme = (isset($api['http_ssl']) && $api['http_ssl']==1)?'ssl://':'';
	    $connection = fsockopen($scheme.$api['http_host'], $api['http_port'], $errno, $errstr, 8);
	    if (!$connection)
	    {   // If no connection then fail
			$this->apierror = 'no_connection';
	        return false;
	    }else{
	        
			$send='';
			foreach( $api as $option => $setting )
			{
				if ( strstr($option, 'http_') )
				{	continue;	}
			
				if ( is_array($setting) )
				{	$setting = serialize( $setting );	}
				
				$send .= $option .'='. urlencode($setting) .'&';
			}
			
			
			
			
	        $request = $send;

	        $headers  = "POST ".  $api['http_path']  ."/castcontrol/api.php HTTP/1.0\r\n";
	        $headers .= "Host: ". $api['http_host'] ."\r\n";
	        $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
	        $headers .= "User-Agent: Cast-control (http://cast-control.net)\r\n";
	        $headers .= "Content-Length: " . strlen($request) . "\r\n";
	        $headers .= "Connection: close\r\n\r\n";
	        $headers .= $request."\r\n";

	        fputs( $connection, $headers);  // Send headers to the open connection
	        while ( !feof($connection) )
	        {   // Return feedback
	            $res = fgets ($connection, 1024);
	        }
	        fclose($connection);



	        if ( strstr($res, "Error,Your API Key is not valid") )
	        {   // If gets to here, we are successfully verified
				$this->apierror = 'auth_failed';
	            return false;
	        }
			return urldecode($res);
	    }

	}



?>
