<?php
class IvSignClient {

	private $url;
	//It is needed to ask for a module and a modulekey to Ivnosys Soluciones
	//Integration module name
	private $module = "integra";
	//Integration module key
	private $modkey = "K#t@g-n2a_d[3-G1";
	public $userid;
	public $orgaid;
	private $token = '';
	public $error = "";

	function __construct($url) {
		
		$this->url = $url;
	}

	function connect() {

	try {
		
		$response = $this->Call("https://". $this->url . "/keyman/prodinfo",array("accept" => "json"),"","get");
		
		if($response["apimax"] >= 4 || $response["apimin"] <= 4) {
			
			return true;
		} 
		else {
			
			$this->error = "Server API version no compatible";
			return false;
		}
	}
	catch(Exception $e) {
		
		$this->error = $e->getMessage();
		return false;
	}
}

function login($userid, $orgaid, $pass) {
	
	$data = array(
	"login"=>$userid,
	"pass"=>$pass,
	"orgaid"=>$orgaid,
	"module"=>$this->module,
	"modkey"=>$this->modkey,
	"authmethod"=>"pass");

	try{
		
		$response = $this->Call("https://" . $this->url . "/keyman/rest/v4/auth/login", $data);
		$this->token=$response->token;
		$this->userid=$response->user->userid;
		$this->orgaid=$response->user->orgaid;
		
		return true;
	}
	catch(Exception $e) {
		
		$this->error=$e->getMessage();
		return false;
	}
}

function certlistavailable() {

	$request = array("cert"=>array(
	"userid"=>$this->userid,
	"orgaid"=>$this->orgaid
	));
	
	try{
		
		$result =$this->Call("https://" . $this->url . "/keyman/rest/v4/cert/listavailable", $request, $this->token);
		if($result == null) $this->error="Sin certificados disponibles";
		
		return $result;
	}
	catch(Exception $e) {
		
		$this->error=$e->getMessage();
		return null;
	}
}

public function signhash($certid, $pin, $digest, $algorithm) {
	
	$request = array();
	$cert = array();
	$cert["certid"] = $certid;
	$cert["pin"] = $pin;
	$request["cert"] = $cert;
	$hash = array();
	$hash["algorithm"] = $algorithm;
	$hash["digest"] = base64_encode($digest);
	$request["hash"] = $hash;
	$retorno = null;
	
	try{
		
		return $this->Call("https://" . $this->url . "/keyman/rest/v4/sign/hash", $request, $this->token);
	}
	catch(Exception $e) {
		
		$this->error=$e->getMessage();
		return null;
	}
}

function Call($url, $data, $token = '', $method = 'post') {

	$ch = curl_init($url);
	//echo "url=$url".PHP_EOL;
	
	if(strtolower($method) == "post") {
		
		curl_setopt ($ch, CURLOPT_POST, 1);
		$headers = array('Content-Type: application/json','Accept: application/json');
		
		if(strlen($token) > 1) {
			
			$headers[] = 'Authentication: '.$token;
		}
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	}

	curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($data));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  //use for development only; unsecure
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  //use for development only; unsecure
	curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);

	$response = curl_exec($ch);
	$error = curl_error($ch);
	$error_no = curl_errno($ch);
	$statuscode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close ($ch);
	
	if($statuscode != 200) {
		
		throw new Exception('ERROR HTTP '.$statuscode." - ".$response);
	}

	$response = json_decode($response);

	if(is_object($response)) {
		
		if($response->error->code != "K0000") {
			
			throw new Exception($response->error->code." - ".$response->error->message);
		}
	}
	
	return $response;
}

$ivs= new IvSignClient("test.ivsign.net");

function prueba() {
	
	global $ivs;

	if(!$ivs->connect()) {
		
		echo "Error connecting to IvSign:  " . $ivs->error.PHP_EOL;
		return;
	}

	echo "Connexion correct to IvSign environment".PHP_EOL;

	if(!$ivs->login("userid", "organization", "userpassword")) {
		
		echo "Login error:  " .$ivs->error. PHP_EOL;
		return;
	}
	
	echo "Login OK user " . $ivs->userid.PHP_EOL;
	$response = $ivs->certlistavailable();
	
	if($response == null) {
		
		$console->log("ERROR:" . $ivs->error);
		return;
	}

	echo "Certificate obtained properly, it will be used " . $response->certlist[0]->certid . " for performing a signature" . PHP_EOL;
	$signed_string_data = $ivs->signhash($response->certlist[0]->certid, "PinDelCertificado", "85608bd7a1419306aed84c2ddd02bf8d8ce75fe63a2d8a94f2d6ade672683cee", "SHA256");

	if($signed_string_data == null) {
		
		echo "ERROR:" . $ivs->error.PHP_EOL;
		return;
	}
	
	echo "Signed string data=" . $signed_string_data->data.PHP_EOL;
}

prueba();
