<?php
/**
 * @class action
 * @brief Manage VirtualHosts
 * @author Vincent Giersch
 * @date 28/08/2009
 * @modified Xavier Perrissoud
 * @date 13/10/2009
 * @version 0.1
 * @todo Uncomment the action creation in createVhost()
 * @todo Review the history entry adding in createVhost() (static-like call to a non-static method of class history)
*/
class vhost
{
	private $vhost_records = null;
	/**
	 * @brief Add a VirtualHost for the current user
	 * @param host : Host which is related to the virtualhost
	 * @param doc_root : The root of the virtualhost
	 * @param active : boolean for activation at creation time
	 * @param server_admin : e-mail address of the server's admin (optional)
	 * @param php_values : array of additionnal options related to the vhost (optional)
	 * @return -2 : The vhost already exists
	 * @return -1 : Quota of vhosts is reached
	 * @return true : VirtualHost successfully added
	*/
	public function userAddVhost( $host, $doc_root, $active, $server_admin = null, $php_values = null )
	{
		$hosting_id = $_SESSION['hosting']->information_hosting->id;
		$http_service = $_SESSION['hosting']->information_hosting->http_ip;
		$server_admin = ( is_null($server_admin) ? APACHE_SERVER_ADMIN : $server_admin );
		$php_values = ( is_null($php_values) ) ? array() : $php_values;
		
		 // Quota
		if ( $_SESSION['hosting']->information_hosting->offer_virtualhosts_number >= 0 ) {
			$current_number_vhosts = $this->countVhosts( $_SESSION['hosting']->information_hosting->id );
			if ( $current_number_vhosts >= $_SESSION['hosting']->information_hosting->offer_virtualhosts_number ) return -1;
		}
			
		// Check existence of the VirtualHosts
		if ( $this->checkVhostExistence($host) ) return -2;
		
		$this->createVhost(
			$hosting_id,
			$http_service, 
			$host, 
			$doc_root,
			$active,
			$server_admin,
			$php_values
		);
		
		return true;
	}

	/**
	 * @brief Create VirtualHosts
	 * @param hosting_id : Id of the hosting
	 * @param service_id : Id of the HTTP service
	 * @param host : Host related to the virtualhost
	 * @param doc_root : The root of the virtualhost
	 * @param active : boolean for activation at creation time
	 * @param server_admin : the e-mail address of the member
	 * @param php_values : array of additionnal options related to the vhost (optionnal)
	 * @return true if successfull, false otherwise
	*/
	private function createVhost( $hosting_id, $service_id, $host, $doc_root, $active, $server_admin, $php_values)
	{
		// First, try to add the VHost in database
		$hosting_id = $_SESSION['database']->clearString($hosting_id);
		$host = $_SESSION['database']->clearString($host);
		$doc_root = $_SESSION['database']->clearString($doc_root);
		$active = $_SESSION['database']->clearString( strtolower($active));
		$server_admin = $_SESSION['database']->clearString($server_admin);
		$clean_php_values=array();
		foreach ( $php_values as $key=>$value)
		{
			$key = $_SESSION['database']->clearString($key);
			$value = $_SESSION['database']->clearString($value);
			$clean_php_values[$key] = $value;
		}
		$values = serialize( $clean_php_values);
		$req = "INSERT INTO service_vhost
				SET
					created_at = CURRENT_TIMESTAMP,
					hosting_id = '$hosting_id',
					host = '$host',
					doc_root = '$doc_root',
					is_active = '$active',
					server_admin = '$server_admin',
					php_values = '$values'";
		
		$_SESSION['database']->execRequest($req);
		$vhost = $_SESSION['database']->getInsertId();

		if ( $active == 'true' )
		{
			// Add action
			$data = array();
			$data['action'] = 'create_vhost';
			$data['host'] = $host;
			$data['vhost_id'] = $vhost;
			$data['doc_root'] = $doc_root;
			$data['server_admin'] = $server_admin;
			$data['php_values'] = $values;
			// $action = action::userAddAction($service_id, $data);
		}
		
		// save action to history
		history::add("history_action_new_domain",$_SESSION['user']->information_user->userid);
		
		return true;
	}	 
	
	/**
	 * @brief Delete a VirtualHost
	 * @param host : Host which is related to the virtualhost
	*/
	public function userDeleteVhost( $host )
	{
		$hosting_id = $_SESSION['hosting']->information_hosting->id;
		$http_service = $_SESSION['hosting']->information_hosting->http_ip;

		return $this->deleteVhost(
			$hosting_id,
			$http_service, 
			$host
		);
	}
	
	
	/* @brief Delete VirtualHosts
	 * @param hosting_id : Id of the hosting
	 * @param service_id : Id of the HTTP service
	 * @param host : Host which is related to the virtualhost
	 * @return -1 : Host not found
	*/
	private function deleteVhost( $hosting_id, $service_id, $host)
	{
		// Check if the hosts exists
		$hosting_id = $_SESSION['database']->clearString($hosting_id);
		if ( !$this->checkVhostExistence($host, false, "AND hosting_id = '$hosting_id'") ) return -1;

		// Add action
		$data = array();
		$data['action'] = 'delete_vhost';
		$data['host'] = $host;
		$action = action::userAddAction($service_id, $data);
		
		// Add Vhost to the table service_vhost
		$host = $_SESSION['database']->clearString($host);
		$req = "DELETE FROM service_vhost
				WHERE
					host = '$host'";
		$_SESSION['database']->execRequest($req);
	}
	

	/**
	 * @brief Active a deactivated VirtualHost
	 * @param host : Host which is related to the virtualhost
	 * @param is_vhost_id :  optional, if the 'host' is the id of the vhost (default false)
	 * @return -1 : Host not found
	 * @return true : Ok
	*/
	public function userActiveVhost( $host, $is_vhost_id = false )
	{
		// Check if the VirtualHost exists
		$hosting_id = $_SESSION['hosting']->information_hosting->id;
		$http_service = $_SESSION['hosting']->information_hosting->http_ip;
		if ( !$this->checkVhostExistence($host, $is_vhost_id, "AND hosting_id = '$hosting_id'") ) return -1;
		
		// Active the Virtualhost
		$this->activeOrNotVhost($host, true, $is_vhost_id);
	}	

	/**
	 * @brief Desactive an actived VirtualHost
	 * @param host : Host which is related to the virtualhost
	 * @param is_vhost_id :  optional, if the 'host' is the id of the vhost (default false)
	 * @return -1 : Host not found
	 * @return true : Ok
	*/
	public function userDesactiveVhost( $host, $is_vhost_id = false )
	{
		// Check if the VirtualHost exists
		$hosting_id = $_SESSION['hosting']->information_hosting->id;
		$http_service = $_SESSION['hosting']->information_hosting->http_ip;
		if ( !$this->checkVhostExistence($host, $is_vhost_id, "AND hosting_id = '$hosting_id'") ) return -1;
		
		// Active the Virtualhost
		$this->activeOrNotVhost($host, false, $is_vhost_id);
	}
	
	
	/**
	 * @brief Active a VirtualHost
	 * @param host : VirtualHost to active
	 * @param active : bool(true) : Active the VirtualHost / bool(false) : Desactive the VirtualHost
	 * @param is_vhost_id :  optional, if the 'host' is the id of the vhost (default true)
	 * @return always true
	*/
	private function activeOrNotVhost( $host , $active, $is_vhost_id = true )
	{
		$active = $_SESSION['database']->clearString($active);
		$host = $_SESSION['database']->clearString($host);
		if ( $is_vhost_id == true )
			$req = "UPDATE service_vhost
					SET 
						is_active = '$active'
					WHERE id = '$host'";
		else
			$req = "UPDATE service_vhost
					SET 
						is_active = '$active'
					WHERE host = '$host'";
		return true;
	}	
	
	
	/**
	* @brief Count VirtualHosts for one hosting
	* @param hosting_id : Id of the hosting
	* @return Number of vhsost
	*/
	private function countVhosts( $hosting_id )
	{
		if( !is_null($this->vhost_records) ) {
			return $this->vhost_records;
		}
		$hosting_id = $_SESSION['database']->clearString($hosting_id);
		$req = "SELECT COUNT(id) AS total FROM service_vhost WHERE hosting_id = '$hosting_id'";
		$query = $_SESSION['database']->fetchObject($req);
		$this->vhost_records = $query[0]->total;
		return $query[0]->total;
	}	

	
	/**
	 * @brief Check if the Vhost exists
	 * @param host : Host is checking
	 * @param is_vhost_id :  optional, if the 'host' is the id of the vhost (default false)
	 * @param additionnal_param : optional, add a WHERE clause
	 * @return true if the vhosts exists
	 * @return false if the vhost doesn't exists
	*/
	private function checkVhostExistence( $host, $is_vhost_id = false, $additionnal_param = null )
	{
		$host = $_SESSION['database']->clearString($host);
		if( $is_vhost_id == true )
			$req = "SELECT COUNT(id) AS exist FROM service_vhost WHERE id = '$host' " . $additionnal_param;
		else
			$req = "SELECT COUNT(id) AS exist FROM service_vhost WHERE host = '$host' " . $additionnal_param;
		$query = $_SESSION['database']->fetchObject($req);
		if( $query[0]->exist > 0 ) return true;
		else return false;
	}
	
	/**
	 * @brief Get number of vhosts for the current hosting (and the current user), regarding the total count of records and the count of items to be shown per page
	 * @return number of pages availables
	*/
	public function userCountTotalPages() 
	{
		$hosting_id = $_SESSION['hosting']->information_hosting->id;
		$items_count = $this->countVhosts( $hosting_id );
		$pages_count = intval($items_count / RECORD_BY_PAGE);
		if ( ($items_count % RECORD_BY_PAGE) != 0 ) {
			$pages_count++;
		}
		return $pages_count;
	}
	
	/**
	 * @brief List all vhosts related to the current hosting (and the current user)
	 * @param hosting_id ID of the current hosting
	 * @param start First record to extract (optional)
	 * @param extract_number Number of record to extract (optional)
	 * @return array or null if empty
	*/
	public function userListVHosts( $hosting_id, $start = null, $extract_number = null )
	{
		$hosting_id = $_SESSION['database']->clearString($hosting_id);
		
		if ( !is_null($start) and !is_null($extract_number)) {
			$start = $_SESSION['database']->clearString($start);
			$extract_number = $_SESSION['database']->clearString($extract_number);
			$limit = " LIMIT $start, $extract_number";
		} else $limit = null;
    
		$req = "SELECT id, UNIX_TIMESTAMP(created_at) AS created_at, host, doc_root, is_active, server_admin
            FROM service_vhost WHERE hosting_id = '$hosting_id' ORDER BY created_at$limit";
		$query = $_SESSION['database']->fetchObject($req);
		return $query;
	}
}
?>