<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides PLESK support
 *
 * @package    OSB
 * @subpackage Plugins/Plesk
 * @category   Plugins
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Plesk implements Serializable {
	private $protocol = '1.6.0.1';
	private $path = 'enterprise/control/agent.php';
	// Service Object
	protected $hso;
	protected $packet;
	protected $xml;
	protected $_object;

	public function serialize() {
		return serialize($this->_object);
	}
	public function unserialize($s) {
		$this->_object = unserialize($s);
	}

	protected $curlopts = array(
		CURLOPT_CONNECTTIMEOUT => 60,
		CURLOPT_FAILONERROR => TRUE,
		CURLOPT_FOLLOWLOCATION => FALSE,
		CURLOPT_HEADER => FALSE,
		CURLOPT_HTTPPROXYTUNNEL => FALSE,
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_SSL_VERIFYHOST => FALSE,
		CURLOPT_SSL_VERIFYPEER => FALSE,
		CURLOPT_VERBOSE => FALSE,
	);

	public function __construct(Model_Host_Server $hso) {
		$this->hso = $hso;
		$this->xml = XML::factory(null,'plesk');
		$this->packet = $this->xml->add_node('packet','',array('version'=>$this->protocol));
	}

	protected function server_command(XML $xml) {
		if (count($a=array_keys($xml->packet->as_array())) != 1)
			throw kohana_exception('XML command malformed?');

		// We need to find out the command key, so we can get the status result.
		$key = array_shift($a);

		$hs = $this->hso->prov_plugin_data();

		$request = Request::factory(sprintf('%s/%s',$this->hso->manage_url,$this->path))
			->method('POST');

		$request->get_client()->options(Arr::merge($this->curlopts,array(
			CURLOPT_HTTPHEADER => array(
				'HTTP_AUTH_LOGIN: '.$hs['user'],
				'HTTP_AUTH_PASSWD: '.$hs['pass'],
				'Content-Type: text/xml',
			),
			CURLOPT_POSTFIELDS => $this->render($xml),
			)));

		$response = $request->execute();

		$result = XML::factory(null,'plesk',$response->body());
		return $result;

		return ($result->$key->get->result->status->value() == 'ok') ? $result->data : $result;
	}

	protected function collapse(XML $xml) {
		$result = array();

		foreach ($xml->as_array() as $j=>$k) {
			$v = $xml->$j->value();

			if (count($k) > 1) {
				foreach ($xml->get($j,1) as $k)
					if (isset($k['name'][0]))
						$result[$j][$k['name'][0]] = (isset($k['value'][0]) ? $k['value'][0] : '');
					else
						$result[$j][] = $k;
				
			} elseif (! is_null($v))
				$result[$j] = $v;
			else
				$result[$j] = $this->collapse($xml->$j);
		}

		if (array_key_exists('name',$result) AND array_key_exists('value',$result))
			$result = array($result['name']=>$result['value']);

		return $result;
	}

	/**
	 * Get a Client Configuration
	 */
	public function cmd_getclient(Model_Service $so) {
		$pco = new Plesk_Client($this->hso);
		return $pco->cmd_getclient($so);
	}

	/**
	 * Get a Server Configuration
	 */
	public function cmd_getdomain(Model_Service $so) {
		$pdo = new Plesk_Domain($this->hso);
		return $pdo->cmd_getdomain($so);
	}

	/**
	 * Get Domain Traffic
	 */
	public function cmd_gettraffic(Model_Service $so) {
		$client = $this->packet->add_node('domain');
		$get = $client->add_node('get_traffic');
		$filter = $get->add_node('filter');
		$filter->add_node('domain-name',strtolower($so->plugin()->name()));
#		$filter->add_node('id',1);
#		$get->add_node('since_date','2012-04-01');
#		$get->add_node('end_date','2012-04-02');

		return $this->server_command($this->xml);
	}

	/**
	 * Add a new client to the host server
	 */
	public function add_client(Model_Service $so) {
		$client_template = 'DefaultClient';
		$reseller_id = $so->affiliate->host_server_affiliate->host_username;

		$client = $this->packet->add_node('client');
		$add = $client->add_node('add');
		$gen_info = $add->add_node('gen_info');
		$gen_info->add_node('cname',$so->account->company);
		$gen_info->add_node('pname',sprintf('%s %s',$so->account->first_name,$so->account->last_name));

		$gen_info->add_node('login',$so->plugin()->host_username);
		$gen_info->add_node('passwd',$so->plugin()->host_password);

		$gen_info->add_node('status',0);
		$gen_info->add_node('email',$so->account->email);

		if ($reseller_id)
			$gen_info->add_node('owner-login',$reseller_id);

		return $this->server_command($this->xml);
	}

	public function add_service(Model_Service $so) {
		// @todo This should come from the DB.
		$host_ip = '111.67.13.20';
		$domain_template = 'Default Domain';

		$domain = $this->packet->add_node('domain');
		$add = $domain->add_node('add');
		$gen_setup = $add->add_node('gen_setup');
		$gen_setup->add_node('name',strtolower($so->name()));
		$gen_setup->add_node('owner-login',$so->plugin()->host_username);
		$gen_setup->add_node('htype','vrt_hst');
		$gen_setup->add_node('ip_address',$host_ip);
		$gen_setup->add_node('status','0');
		$hosting = $add->add_node('hosting');
		$vrt_host = $hosting->add_node('vrt_hst');
		$property = $vrt_host->add_node('property');
		$property->add_node('name','ftp_login');
		$property->add_node('value',$so->plugin()->ftp_username);
		$property = $vrt_host->add_node('property');
		$property->add_node('name','ftp_password');
		$property->add_node('value',$so->plugin()->ftp_password);
		$vrt_host->add_node('ip_address',$host_ip);

		$add->add_node('template-name',$domain_template);

		return $this->server_command($this->xml);
	}

	// @todo not sure if this is actually working as desired
	public function setlimits(Model_Service $so) {
		$client = $this->packet->add_node('client');

		// Permissions
		$set = $client->add_node('set');
		$filter = $set->add_node('filter');
		$filter->add_node('login',$so->plugin()->host_username);
		$values = $set->add_node('values');

		$x = $values->add_node('permissions');
		foreach ($this->permissions as $k=>$v) {
			$l = $x->add_node('permission');
			$l->add_node('name',$k);
			$l->add_node('value',$v==TRUE?'true':'false');
		}

		// Limits
		$set = $client->add_node('set');
		$filter = $set->add_node('filter');
		$filter->add_node('login',$so->plugin()->host_username);
		$values = $set->add_node('values');

		$x = $values->add_node('limits');
		foreach ($this->limits as $k=>$v) {
			$l = $x->add_node('limit');
			$l->add_node('name',$k);
			$l->add_node('value',$v);
		}

		return $this->server_command($this->xml);
	}

	public function setip($id) {
		$client = $this->packet->add_node('client');
		$ip = $client->add_node('ippool_add_ip');
		$ip->add_node('client_id',$id);
		foreach ($this->ippool as $k=>$v)
			$ip->add_node('ip_address',$k);

		return $this->server_command($this->xml);
	}

	public function disablemail($id) {
		$client = $this->packet->add_node('mail');
		$disable = $client->add_node('disable');
		$disable->add_node('domain_id',$id);

		return $this->server_command($this->xml);
	}

	private function render(XML $xml) {
		return preg_replace('/<\/?plesk>/','',(string)$xml->render(FALSE));
	}
}
?>
