use PHPMailer\PHPMailer\PHPMailer;
class P7Manager {
public $filePath;
public $fileContent;
private $cafolder;
private $bash_folder;
private $tmp_folder;
function __construct($path) {
$this->filePath = $path;
if (file_exists($this->filePath)) {
adaptMemoryLimitToFile($this->filePath,-1);
ini_set("max_execution_time","600");
$this->fileContent = file_get_contents($this->filePath);
global $config;
$this->cafolder = $config["cafolder"];
$this->bash_folder = $config["bash_folder"];
$this->tmp_folder = $config["chunk_folder"];
} else {
throw new Exception('File not found');
}
}
public static function bustaEstensioneSoloP7M($fileName) {
$component = explode(".",$fileName);
if (count($component) == 2) {
$ext = end($component);
if ($ext === "p7m") {
return true;
}
}
return false;
}
static public function generateKeys($id,$oggetto,$destinatario = "") {
if (isset($_SESSION["ente"]) && isset($_SESSION["utente"])) {
global $root;
global $config;
$res = openssl_pkey_new();
$path = sys_get_temp_dir() . "/" . rand() . ".pem";
if (openssl_pkey_export_to_file($res,$path)) {
$destinatario_chiave = [];
$indirizziChiave = $_SESSION["ente"]->getInfo()["email_chiavi"];
if (!empty($indirizziChiave)) {
if (strpos($indirizziChiave,",")===false) {
$destinatario_chiave[] = $indirizziChiave;
} else {
$tmp = explode(",",$indirizziChiave);
$destinatario_chiave = array_merge($destinatario_chiave,$tmp);
}
} else if (!empty($destinatario)) {
$destinatario_chiave[] = $destinatario;
}
if (!empty($config["casella_bk_pkey"])) { $destinatario_chiave[] = $config["casella_bk_pkey"]; }
$indirizziBackup = $_SESSION["ente"]->getInfo()["email_chavi_bkInterno"];
if (!empty($indirizziBackup)) {
if (strpos($indirizziBackup,",")===false) {
$destinatario_chiave[] = $indirizziBackup;
} else {
$tmp = explode(",",$indirizziBackup);
$destinatario_chiave = array_merge($destinatario_chiave,$tmp);
}
}
$oggettoMail = __('Invio chiave privata') . " ID " . $id;
$corpo = __('Si invia in allegato la chiave privata utile alla gestione della seguente procedura') . "
ID " . $id . " - " . $oggetto . "
";
if (file_exists($root."/template/default.html")) {
$html = file_get_contents($root."/template/default.html");
$html = str_replace("#---NOME-SITO---#", $config["nome_sito"], $html);
$html = str_replace("#---MSG-OBJECT---#", $oggettoMail, $html);
$html = str_replace("#---MSG-BODY---#", $corpo, $html);
} else {
$html = $corpo;
}
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = $config["smtp_server"];
$mail->Port = $config["smtp_port"];
if (!empty($config["smtp_ssl"])) { $mail->SMTPSecure = 'ssl'; }
$mail->SMTPAuth = true;
$mail->Username = $config["smtp_username"] ?? $config["mittente_mail"];
$mail->Password = $config["smtp_password"];
$mail->SetFrom($config["mittente_mail"],$config["nome_sito"]);
foreach($destinatario_chiave AS $indirizzo) {
$mail->AddAddress($indirizzo);
}
$mail->Subject = $oggettoMail . " - " . substr($oggetto,0,350);
$mail->MsgHTML($html);
$mail->AddAttachment($path);
if($mail->Send()){
$public = openssl_pkey_get_details($res);
$return = $public["key"];
} else {
$return = false;
}
unlink($path);
unset($mail);
return $return;
}
}
return false;
}
static public function der2smime($file,$buffer = false)
{
$to = "MIME-Version: 1.0" . PHP_EOL;
$to .="Content-Disposition: attachment; filename=\"smime.p7m\"" . PHP_EOL;
$to .="Content-Type: application/x-pkcs7-mime; smime-type=signed-data; name=\"smime.p7m\"" . PHP_EOL;
$to .="Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL;
$tmp = (!$buffer) ? file_get_contents($file) : $file;
$from = base64_decode($tmp,true);
if (empty($from)) { $from = $tmp; }
$to.=chunk_split(base64_encode($from));
return (!$buffer) ? file_put_contents($file.".smime",$to) : $to;
}
public function opensslExtract($objectPath,$extractType = false,$forceOpen = false) {
$return = false;
if (empty($objectPath)) { $objectPath = $this->filePath; }
if (file_exists($objectPath)) {
if (self::der2smime($objectPath)) {
$tmp_file = $this->tmp_folder . "/" . session_id() . rand() .time();
$certPath = $tmp_file.".pem";
$contentPath = $tmp_file.".tmp";
$caPath = $this->cafolder . "/european_ca.pem";
if (openssl_pkcs7_verify($objectPath.".smime",PKCS7_BINARY,$certPath,[$caPath],$caPath,$contentPath) === true) {
$return = true;
} else {
$comando = $this->bash_folder.'/verifica.bash \'' . $objectPath . '\' \'' . $this->cafolder . '/european_ca.pem\'';
$esito = shell_exec("sh " . $comando . " 2>&1");
$esito = trim($esito);
if ($esito != "Verification successful") {
$data = base64_decode(file_get_contents($objectPath), true);
if ($data !== false) {
$tmp_file_verify = $this->tmp_folder . "/" . session_id() . ".tmp";
file_put_contents($tmp_file_verify, $data);
$comando = $this->bash_folder.'/verifica.bash \'' . $tmp_file_verify . '\' \'' . $this->cafolder . '/european_ca.pem\'';
$esito = shell_exec("sh " . $comando . " 2>&1");
$esito = trim($esito);
if ($esito === "Verification successful") {
$return = true;
}
}
} else {
$return = true;
}
if (($return || $forceOpen) && $extractType !== false) {
$comando = $this->bash_folder.'/estrai_Certificato.bash \'' . $objectPath . '\'';
$esito = shell_exec("sh " . $comando . " 2>&1");
$esito = trim($esito);
if (!empty($esito)) {
file_put_contents($certPath,$esito);
}
$comando = $this->bash_folder.'/estrai.bash \'' . $objectPath . '\' \'' . $contentPath .'\'';
shell_exec("sh " . $comando . " 2>&1");
}
if (isset($tmp_file_verify) && file_exists($tmp_file_verify)) {
unlink($tmp_file_verify);
}
}
if (($return || $forceOpen) && $extractType !== false) {
$certs = [];
if (file_exists($certPath)) {
$fileCerts = file_get_contents($certPath);
$fileCerts = explode("-----END CERTIFICATE-----",$fileCerts);
foreach($fileCerts AS $singleCert) {
if (!empty(trim($singleCert))) {
$singleCert .= "-----END CERTIFICATE-----";
$tmp = openssl_x509_parse($singleCert,false);
$certs[] = $tmp;
}
}
}
if (isset($certs["hash"])) { $certs = [$certs]; }
if (file_exists($contentPath)) {
$content = file_get_contents($contentPath);
$tmp = base64_decode($content,true);
if (!empty($tmp)) { $content = $tmp; }
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($content);
if ($mime_type == "application/octet-stream" || ($mime_type == "application/pdf" && $extractType == "cert")) {
file_put_contents($contentPath,$content);
$inner = $this->opensslExtract($contentPath,$extractType,$forceOpen);
if ($extractType == "cert") {
$certs = array_merge($certs,$inner);
} else if ($extractType == "content") {
$content = $inner;
}
}
}
if ($extractType == "cert") {
$return = $certs ?? false;
} else if ($extractType == "content") {
$return = $content ?? false;
}
if (file_exists($certPath)) {
unlink($certPath);
}
if (file_exists($contentPath)) {
unlink($contentPath);
}
}
if (file_exists($objectPath.".smime")) {
unlink($objectPath.".smime");
}
}
}
return $return;
}
public static function updatePEM() {
global $config;
libxml_use_internal_errors(true);
$EU_xml = "https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml";
if (file_exists($config["cafolder"] . '/european_ca.pem')) { $ultima_modifica = filemtime($config["cafolder"] . '/european_ca.pem'); }
if (!isset($ultima_modifica) || $ultima_modifica < strtotime("-1 day")) {
$pem = "";
try {
$xml_list = new SimpleXMLElement($EU_xml,0,1);
} catch (Exception $error_pem) {
$error_list = true;
}
if (!empty($xml_list->SchemeInformation->PointersToOtherTSL->OtherTSLPointer) && !isset($error_list)) {
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new Exception($errstr, $errno);
});
foreach($xml_list->SchemeInformation->PointersToOtherTSL->OtherTSLPointer AS $tsl_pointer) {
$error_pem = false;
$url = explode(".",$tsl_pointer->TSLLocation);
if (end($url) == "xml") {
try {
$xml = new \SimpleXMLElement($tsl_pointer->TSLLocation,0,1);
} catch (\Exception $error_pem) {
$error_pem = true;
}
if (!empty($xml->TrustServiceProviderList->TrustServiceProvider) && !$error_pem) {
foreach ($xml->TrustServiceProviderList->TrustServiceProvider as $provider) {
foreach ($provider->TSPServices->TSPService as $service) {
if (!empty($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate)) {
if(strstr($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate, PHP_EOL)) {
$pem .= "-----BEGIN CERTIFICATE-----";
$pem .= $service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate;
$pem .= "-----END CERTIFICATE-----";
} else {
$pem .= "-----BEGIN CERTIFICATE-----" . PHP_EOL;
$pem .= chunk_split($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate,64);
$pem .= "-----END CERTIFICATE-----" . PHP_EOL;
}
}
}
}
}
}
}
restore_error_handler();
$others = [];
$others = ["https://www.ssi.gouv.fr/uploads/2016/07/tl-fr.xml"];
$others = ["https://portail-qualite.public.lu/content/dam/qualite/fr/publications/confiance-numerique/liste-confiance-nationale/tsl-xml/tsl.xml"];
$others = ["http://tsl.gov.cz/publ/TSL_CZ.xtsl"];
$others = ["http://crc.bg/files/_bg/TSL-CRC-BG-signed.xml"];
$others = ["https://sr.riik.ee/tsl/estonian-tsl.xml"];
$others = ["https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml"];
$others = ["http://www.nmhh.hu/tl/pub/HU_TL.xml"];
$others = ["http://www.neytendastofa.is/library/Files/TSl/tsl.xml"];
$others = ["https://tl-norway.no/TSL/NO_TSL.XML"];
$others = ["http://www.gns.gov.pt/media/1894/TSLPT.xml"];
$others = ["https://www.tscheme.org/sites/default/files/tsl-uk0019signed.xml"];
foreach($others AS $tslLocation) {
$error_pem = false;
try {
$xml = @new SimpleXMLElement($tslLocation,0,1);
} catch (Exception $error_pem) {
$error_pem = true;
}
if (!empty($xml->TrustServiceProviderList->TrustServiceProvider) && !$error_pem) {
foreach ($xml->TrustServiceProviderList->TrustServiceProvider as $provider) {
foreach ($provider->TSPServices->TSPService as $service) {
if (!empty($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate)) {
if(strstr($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate, PHP_EOL)) {
$pem .= "-----BEGIN CERTIFICATE-----";
$pem .= $service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate;
$pem .= "-----END CERTIFICATE-----";
} else {
$pem .= "-----BEGIN CERTIFICATE-----" . PHP_EOL;
$pem .= chunk_split($service->ServiceInformation->ServiceDigitalIdentity->DigitalId->X509Certificate,64);
$pem .= "-----END CERTIFICATE-----" . PHP_EOL;
}
}
}
}
}
}
if ($pem != "") {
$fp = fopen($config["cafolder"] . '/european_ca.pem', 'w');
fwrite($fp, $pem);
fclose($fp);
}
}
}
}
private function pdfUtility($type,$objectPath="") {
$return_value = false;
if ($type =="Certificati") { $return_value = array(); }
if (empty($objectPath)) { $objectPath = $this->filePath; }
if (file_exists($objectPath)) {
$content = file_get_contents($objectPath);
if (preg_match_all('/\/Contents\s?<([a-zA-Z0-9]+)[>]{1}/s',$content,$signatures)) {
$signatures = $signatures[1];
$esito = array();
$caPath = $this->cafolder . "/european_ca.pem";
$certs = [];
foreach($signatures AS $pkcs7) {
$pkcs7 = hex2bin($pkcs7);
$data = chunk_split(base64_encode(trim($pkcs7)),64,"\n");
$data = "-----BEGIN CERTIFICATE-----\n" . $data . "-----END CERTIFICATE-----";
if (openssl_pkcs7_read($data,$result)) {
$certs = array_merge($certs,$result);
} else {
file_put_contents($objectPath.".p7b",$pkcs7);
$comando = $this->bash_folder.'/estrai_Certificato.bash \'' . $objectPath. '.p7b\'';
$certs[] = shell_exec("sh " . $comando . " 2>&1");
unlink($objectPath.'.p7b');
}
}
if (!empty($certs)) {
switch ($type) {
case 'Certificati':
$return_value = [];
foreach ($certs AS $cert) {
$return_value[] = openssl_x509_parse($cert,false);
}
break;
default:
$esito = 0;
foreach ($certs AS $cert) {
if (openssl_x509_checkpurpose($cert,X509_PURPOSE_ANY)) {
$esito++;
} else {
file_put_contents($objectPath.".p7b",substr($cert, strpos($cert, '-----BEGIN CERTIFICATE----- ')));
$comando = $this->bash_folder.'/verifica_SignedPDF.bash \'' . $objectPath . '.p7b\' \'' . $caPath . '\'';
$msg = shell_exec("sh " . $comando . " 2>&1");
if (strpos($msg, ": OK")!== false) { $esito++; }
unlink($objectPath.'.p7b');
}
}
if (count($certs) === $esito) { $return_value = true; }
break;
}
}
}
}
return $return_value;
}
static public function verifyXmlSignature($xml_string) {
$return = false;
if (!empty($xml_string)) {
$xmlDoc = new DOMDocument();
if ($xmlDoc->loadXML($xml_string)) {
$xpath = new DOMXPath($xmlDoc);
$xpath->registerNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#');
$query = ".//ds:Signature";
$nodeset = $xpath->query($query, $xmlDoc);
if (!empty($nodeset)) {
$signatureNode = $nodeset->item(0);
$query = "./ds:SignedInfo";
$nodeset = $xpath->query($query, $signatureNode);
if (!empty($nodeset)) {
$signedInfoNode = $nodeset->item(0);
$signedInfoNodeCanonicalized = $signedInfoNode->C14N(true, false);
if (!empty($signedInfoNodeCanonicalized)) {
$query = 'string(./ds:SignatureValue)';
$signature_value = $xpath->evaluate($query, $signatureNode);
if (!empty($signature_value)) {
$signature_value = base64_decode($signature_value);
$query = 'string(./ds:KeyInfo/ds:X509Data/ds:X509Certificate)';
$x509cert = $xpath->evaluate($query, $signatureNode);
if (!empty($x509cert) ) {
$x509cert = str_replace(PHP_EOL, "", $x509cert);
$x509cert = str_replace("-----BEGIN CERTIFICATE-----","",$x509cert);
$x509cert = str_replace("-----END CERTIFICATE-----","",$x509cert);
$cert = "-----BEGIN CERTIFICATE-----" . PHP_EOL;
$cert .= chunk_split($x509cert,64);
$cert .= "-----END CERTIFICATE-----" . PHP_EOL;
$publicKey = openssl_get_publickey($cert);
$return = openssl_verify($signedInfoNodeCanonicalized, $signature_value, $publicKey,OPENSSL_ALGO_SHA256);
}
}
}
}
}
}
}
return $return;
}
public function checkSignatures($objectPath="") {
if (empty($objectPath)) { $objectPath = $this->filePath; }
self::updatePEM();
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->file($objectPath);
$esito = false;
if (strpos($mime_type,"pdf") !== false) {
$esito = $this->pdfUtility("Valida",$objectPath);
} else {
$esito = $this->opensslExtract($objectPath);
}
return $esito;
}
public function extractSignatures($objectPath="") {
if (empty($objectPath)) { $objectPath = $this->filePath; }
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->file($objectPath);
$certificati = array();
if (strpos($mime_type,"pdf") !== false) {
$certificati = $this->pdfUtility("Certificati",$objectPath);
} else {
$certificati = $this->opensslExtract($objectPath,"cert",true);
}
return $certificati;
}
public function extract($force = false) {
return $this->opensslExtract($this->filePath,"content",$force);
}
public function find($hash,$algorithm,$signed=true,$checkContent=false) {
$found = false;
$result = array();
$tmp_file = $this->tmp_folder . "/" . session_id() . time() . ".find.tmp";
if ($signed) {
$content = $this->opensslExtract($this->filePath,"content");
} else {
$content = $this->fileContent;
}
if ($content !== false) {
file_put_contents($tmp_file,$content);
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($content);
if (strpos($mime_type,"pdf") !== false || strpos($mime_type,"xml") !== false) {
if (!$checkContent) {
$dataContent = $content;
} else {
try {
$parser = new \Smalot\PdfParser\Parser();
$dataContent = @$parser->parseFile($tmp_file)->getText();
$dataContent = preg_replace("/[^a-zA-Z0-9]/", '', $dataContent);
} catch (Exception $e) {
$dataContent = "";
}
}
$result[] = hash($algorithm,$dataContent);
} else if ((strpos($mime_type,"zip") !== false)||(strpos($mime_type,"rar") !== false)||(strpos($mime_type,"7z") !== false)) {
$result[] = hash($algorithm,$content);
$zip_folder = $this->tmp_folder .'/'. session_id() . '/zip/';
$unzipped = false;
if (strpos($mime_type,"zip")) {
$zip = new ZipArchive;
$res_zip = $zip->open($tmp_file);
if ($res_zip === true) {
$unzipped = true;
$zip->extractTo($zip_folder);
$zip->close();
}
} else if (strpos($mime_type,"rar")) {
$res_zip = RarArchive::open($tmp_file);
$entries = $res_zip->getEntries();
if ($entries !== false) {
$unzipped = true;
foreach ($entries as $e) {
$e->extract($zip_folder);
}
$res_zip->close();
}
} else if (strpos($mime_type,"7z")) {
$comando = $this->bash_folder.'/estrai_7z.bash \''.$tmp_file.'\' \''.$zip_folder.'\'';
$esito_extract = shell_exec("sh " . $comando . " 2>&1");
if (strpos($esito_extract,"Everything is Ok") !== false) { $unzipped = true; }
}
if ($unzipped) {
$it = new RecursiveDirectoryIterator($zip_folder, RecursiveDirectoryIterator::SKIP_DOTS);
$filesZip = new RecursiveIteratorIterator($it,RecursiveIteratorIterator::CHILD_FIRST);
foreach($filesZip as $fileZip) {
if (!$fileZip->isDir()) {
$evaluating_tmp = $zip_folder . ".evaluating.tmp";
rename($fileZip->getRealPath(),$evaluating_tmp);
$evaluating_content = file_get_contents($evaluating_tmp);
$mime_type_evaluating = $file_info->buffer($evaluating_content);
if ($signed && strpos($mime_type_evaluating, "pdf") === false ) {
$evaluating_content = $this->opensslExtract($evaluating_tmp,"content");
}
file_put_contents($evaluating_tmp,$evaluating_content);
if ($evaluating_content !== false) {
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($evaluating_content);
if (strpos($mime_type,"pdf") !== false) {
if (!$checkContent) {
$dataContent = $evaluating_content;
} else {
try {
$parser = new \Smalot\PdfParser\Parser();
$dataContent = $parser->parseFile($evaluating_tmp)->getText();
$dataContent = preg_replace("/[^a-zA-Z0-9]/", '', $dataContent);
} catch (Exception $e) {
$dataContent = "";
}
}
$result[] = hash($algorithm,$dataContent);
} else {
$result[] = hash($algorithm,file_get_contents($evaluating_tmp));
}
} else {
if ($checkContent) {
$esito = $this->pdfUtility("Valida", $evaluating_tmp);
if ($esito === true || !$signed) {
try {
$parser = new \Smalot\PdfParser\Parser();
$dataContent = $parser->parseFile($evaluating_tmp)->getText();
$dataContent = preg_replace("/[^a-zA-Z0-9]/", '', $dataContent);
} catch (Exception $e) {
$dataContent = "";
}
$result[] = hash($algorithm,$dataContent);
}
}
}
}
}
$it = new RecursiveDirectoryIterator($zip_folder, RecursiveDirectoryIterator::SKIP_DOTS);
$filesZip = new RecursiveIteratorIterator($it,RecursiveIteratorIterator::CHILD_FIRST);
foreach($filesZip as $fileZip) {
if ($fileZip->isDir()){
rmdir($fileZip->getRealPath());
} else {
unlink($fileZip->getRealPath());
}
}
rmdir($zip_folder);
}
}
unlink($tmp_file);
} else {
if ($checkContent) {
$esito = $this->pdfUtility("Valida", $this->filePath);
if ($esito === true || !$signed) {
try {
$parser = new \Smalot\PdfParser\Parser();
$dataContent = $parser->parseFile($this->filePath)->getText();
$dataContent = preg_replace("/[^a-zA-Z0-9]/", '', $dataContent);
} catch (Exception $e) {
$dataContent = "";
}
$result[] = hash($algorithm,$dataContent);
}
}
}
if (!isset($result)) { $result = array(''); }
else if (isset($result) && !is_array($result)) { $result = array($result); }
if (in_array($hash,$result)!==false) { $found = true; }
if (!$found && !$signed) {
$found = $this->find($hash,$algorithm,true,$checkContent);
}
return $found;
}
public function hasSignedContent($filePath) {
$return = false;
$tmp_file = $this->tmp_folder . "/" . session_id() . time() . ".find.tmp";
$content = file_get_contents($filePath);
if (!empty($content)) {
file_put_contents($tmp_file,$content);
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($content);
if ($this->checkSignatures($tmp_file)) {
$return = true;
} else {
if ((strpos($mime_type,"zip") !== false)||(strpos($mime_type,"rar") !== false)||(strpos($mime_type,"7z") !== false)) {
$zip_folder = $this->tmp_folder .'/'. session_id() . '/zip/';
$unzipped = false;
if (strpos($mime_type,"zip")) {
$zip = new ZipArchive;
$res_zip = $zip->open($tmp_file);
if ($res_zip === true) {
$unzipped = true;
$zip->extractTo($zip_folder);
$zip->close();
}
} else if (strpos($mime_type,"rar")) {
$res_zip = RarArchive::open($tmp_file);
$entries = $res_zip->getEntries();
if ($entries !== false) {
$unzipped = true;
foreach ($entries as $e) {
$e->extract($zip_folder);
}
$res_zip->close();
}
} else if (strpos($mime_type,"7z")) {
$comando = $this->bash_folder.'/estrai_7z.bash \''.$tmp_file.'\' \''.$zip_folder.'\'';
$esito_extract = shell_exec("sh " . $comando . " 2>&1");
if (strpos($esito_extract,"Everything is Ok") !== false) { $unzipped = true; }
}
if ($unzipped) {
$it = new RecursiveDirectoryIterator($zip_folder, RecursiveDirectoryIterator::SKIP_DOTS);
$filesZip = new RecursiveIteratorIterator($it,RecursiveIteratorIterator::CHILD_FIRST);
foreach($filesZip as $fileZip) {
if (!$fileZip->isDir() && ($this->hasSignedContent($fileZip->getRealPath()))) {
$return = true;
break;
}
}
}
$it = new RecursiveDirectoryIterator($zip_folder, RecursiveDirectoryIterator::SKIP_DOTS);
$filesZip = new RecursiveIteratorIterator($it,RecursiveIteratorIterator::CHILD_FIRST);
foreach($filesZip as $fileZip) {
if ($fileZip->isDir()){
rmdir($fileZip->getRealPath());
} else {
unlink($fileZip->getRealPath());
}
}
rmdir($zip_folder);
}
}
unlink($tmp_file);
}
return $return;
}
public static function compHash($file,$algorithm) {
return hash($algorithm,$file);
}
public function getHash($algorithm) {
return $this->compHash($this->fileContent,$algorithm);
}
public function encrypt($salt,$easy_salt = false) {
if (strlen($salt) >= 12 || $easy_salt) {
$enc_busta = openssl_encrypt($this->fileContent,"AES128",$salt,OPENSSL_RAW_DATA,$config["simple_encrypt"]["offer"]);
if ($enc_busta !== FALSE) {
return $enc_busta;
} else {
return false;
}
} else {
return false;
}
}
public static function getTimestampInfo($path) {
return \vakata\asn1\structures\TimestampResponse::fromFile($path)->toArray();
}
public static function putTimestamp($path) {
global $config;
if (!$_SESSION["demoEnv"]) {
$ts_request = \vakata\asn1\structures\TimestampRequest::generateFromFile($path,true,true,"sha256");
$ch = curl_init();
$ts_body = fopen($path.".tsr","w+");
curl_setopt($ch, CURLOPT_URL, $config["ts-url"]);
curl_setopt($ch, CURLOPT_USERPWD, "{$config["ts-username"]}:{$config["ts-password"]}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ts_request);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/timestamp-query","Accept: application/timestamp-reply,application/timestamp-response"]);
curl_setopt($ch, CURLOPT_USERAGENT, "OpenTSA tsgetStudioAmica/1.0");
curl_setopt($ch, CURLOPT_FILE, $ts_body);
curl_exec($ch);
if(!curl_errno($ch)) {
fclose($ts_body);
$response = self::getTimestampInfo($path.".tsr");
if (!empty($response["timeStampToken"]["signedData"]["tokenInfo"]["data"]["genTime"])) {
$timestamp = date("Y-m-d H:i:s",$response["timeStampToken"]["signedData"]["tokenInfo"]["data"]["genTime"]);
}
}
curl_close($ch);
} else {
$timestamp = date("Y-m-d H:i:s");
}
if (!empty($timestamp)) {
return $timestamp;
} else {
return false;
}
}
static function publicEncrypt($data,$public) {
$public = openssl_pkey_get_public(trim($public));
if (openssl_public_encrypt($data,$encrypted,$public)) {
return $encrypted;
} else {
return false;
}
}
public static function extFromMime($mime) {
$extension = explode("/",$mime);
$extension = $extension[1];
if (strpos($extension,"rar")!==FALSE) {
$extension = "rar";
} else if (strpos($extension,"7z")!==FALSE) {
$extension = "7z";
} else if (strpos($extension,"plain")!==FALSE) {
$extension = "xml";
} else {
switch($mime) {
case "application/msword": $extension = "doc"; break;
case "application/msword": $extension = "dot"; break;
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": $extension = "docx"; break;
case "application/vnd.openxmlformats-officedocument.wordprocessingml.template": $extension = "dotx"; break;
case "application/vnd.ms-word.document.macroEnabled.12": $extension = "docm"; break;
case "application/vnd.ms-word.template.macroEnabled.12": $extension = "dotm"; break;
case "application/vnd.ms-excel": $extension = "xls"; break;
case "application/vnd.ms-excel": $extension = "xlt"; break;
case "application/vnd.ms-excel": $extension = "xla"; break;
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": $extension = "xlsx"; break;
case "application/vnd.openxmlformats-officedocument.spreadsheetml.template": $extension = "xltx"; break;
case "application/vnd.ms-excel.sheet.macroEnabled.12": $extension = "xlsm"; break;
case "application/vnd.ms-excel.template.macroEnabled.12": $extension = "xltm"; break;
case "application/vnd.ms-excel.addin.macroEnabled.12": $extension = "xlam"; break;
case "application/vnd.ms-excel.sheet.binary.macroEnabled.12": $extension = "xlsb"; break;
case "application/vnd.ms-powerpoint": $extension = "ppt"; break;
case "application/vnd.ms-powerpoint": $extension = "pot"; break;
case "application/vnd.ms-powerpoint": $extension = "pps"; break;
case "application/vnd.ms-powerpoint": $extension = "ppa"; break;
case "application/vnd.openxmlformats-officedocument.presentationml.presentation": $extension = "pptx"; break;
case "application/vnd.openxmlformats-officedocument.presentationml.template": $extension = "potx"; break;
case "application/vnd.openxmlformats-officedocument.presentationml.slideshow": $extension = "ppsx"; break;
case "application/vnd.ms-powerpoint.addin.macroEnabled.12": $extension = "ppam"; break;
case "application/vnd.ms-powerpoint.presentation.macroEnabled.12": $extension = "pptm"; break;
case "application/vnd.ms-powerpoint.template.macroEnabled.12": $extension = "potm"; break;
case "application/vnd.ms-powerpoint.slideshow.macroEnabled.12": $extension = "ppsm"; break;
case "application/vnd.ms-access": $extension = "mdb"; break;
}
}
return $extension;
}
}
?>