Skip to content

Commit

Permalink
Merge pull request #183 from robmachado/master
Browse files Browse the repository at this point in the history
[UPD] ISSUE #182 Melhoria na manipulação de chaves temporárias
  • Loading branch information
robmachado committed Jun 7, 2018
2 parents 767d4f8 + 430d780 commit 8988051
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 39 deletions.
4 changes: 2 additions & 2 deletions src/DOMImproved.php
Expand Up @@ -155,7 +155,7 @@ public function getChave($nodeName = 'infNFe')
* Serão inclusos erros na array $erros[] sempre que a tag for obrigatória e
* nenhum parâmetro for passado na variável $content e $force for false
* @param \DOMElement $parent
* @param string $name
* @param string|null $name
* @param string|float|null $content
* @param boolean $obrigatorio
* @param string $descricao
Expand All @@ -170,7 +170,7 @@ public function addChild(
$descricao = '',
$force = false
) {
if ($content === null) {
if ($content === null || empty($name)) {
return;
}
$content = (string) $content;
Expand Down
43 changes: 6 additions & 37 deletions src/Soap/SoapBase.php
Expand Up @@ -221,12 +221,6 @@ public function loadCA($capath)
public function setEncriptPrivateKey($encript = true)
{
$this->encriptPrivateKey = $encript;
if (null !== $this->filesystem) {
$this->removeTemporarilyFiles();
}
if (null !== $this->certificate) {
$this->saveTemporarilyKeyFiles();
}
return $this->encriptPrivateKey;
}

Expand Down Expand Up @@ -451,6 +445,7 @@ private function getStringAttributes($namespaces = [])
*/
public function saveTemporarilyKeyFiles()
{
//certs already exists
if (!empty($this->certsdir)) {
return;
}
Expand All @@ -462,16 +457,17 @@ public function saveTemporarilyKeyFiles()
if (empty($this->filesystem)) {
$this->setTemporaryFolder();
}
//clear dir cert
$this->removeTemporarilyFiles();
$this->certsdir = $this->certificate->getCnpj() . '/certs/';
$this->prifile = $this->certsdir . Strings::randomString(10) . '.pem';
$this->pubfile = $this->certsdir . Strings::randomString(10) . '.pem';
$this->certfile = $this->certsdir . Strings::randomString(10) . '.pem';
$ret = true;
//load private key pem
$private = $this->certificate->privateKey;
if ($this->encriptPrivateKey) {
//cria uma senha temporária ALEATÓRIA para salvar a chave primaria
//portanto mesmo que localizada e identificada não estará acessível
//pois sua senha não existe além do tempo de execução desta classe
//replace private key pem with password
$this->temppass = Strings::randomString(16);
//encripta a chave privada entes da gravação do filesystem
openssl_pkey_export(
Expand Down Expand Up @@ -509,35 +505,8 @@ public function removeTemporarilyFiles()
return;
}
$contents = $this->filesystem->listContents($this->certsdir, true);
//define um limite de $waitingTime min, ou seja qualquer arquivo criado a mais
//de $waitingTime min será removido
//NOTA: quando ocorre algum erro interno na execução do script, alguns
//arquivos temporários podem permanecer
//NOTA: O tempo default é de 45 minutos e pode ser alterado diretamente nas
//propriedades da classe, esse tempo entre 5 a 45 min é recomendável pois
//podem haver processos concorrentes para um mesmo usuário. Esses processos
//como o DFe podem ser mais longos, dependendo a forma que o aplicativo
//utilize a API. Outra solução para remover arquivos "perdidos" pode ser
//encontrada oportunamente.
$dt = new \DateTime();
$tint = new \DateInterval("PT" . $this->waitingTime . "M");
$tint->invert = 1;
$tsLimit = $dt->add($tint)->getTimestamp();
foreach ($contents as $item) {
if ($item['type'] == 'file') {
if ($item['path'] == $this->prifile

This comment has been minimized.

Copy link
@gersonfs

gersonfs Jun 7, 2018

Contributor

Sem este if, se tenho 2 caixas no mesmo cnpj, realizando uma operação ao mesmo tempo, não será mais frequente uma requisição apagar os arquivos temporários de outra? Referente a issue #182

|| $item['path'] == $this->pubfile
|| $item['path'] == $this->certfile
) {
$this->filesystem->delete($item['path']);
continue;
}
$timestamp = $this->filesystem->getTimestamp($item['path']);
if ($timestamp < $tsLimit) {
//remove arquivos criados a mais de 45 min
$this->filesystem->delete($item['path']);
}
}
$this->filesystem->delete($item['path']);
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/Soap/SoapCurl.php
Expand Up @@ -56,6 +56,8 @@ public function send(
$request = '',
$soapheader = null
) {
//check or create key files
//before send request
$this->saveTemporarilyKeyFiles();
$response = '';
$envelope = $this->makeEnvelopeSoap(
Expand Down

1 comment on commit 8988051

@robmachado
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ainda não subi todas as alterações. Essa que está ai irá QUEBRAR sua aplicação se não estabelecer um pasta temporária para cada caixa

Please sign in to comment.