Files
espocrm/custom/Espo/Custom/Hooks/CDokumente/CDokumente.php

71 lines
2.1 KiB
PHP

<?php
namespace Espo\Custom\Hooks\CDokumente;
use Espo\ORM\Entity;
use Espo\ORM\Repository\Option\SaveOptions;
use Espo\Core\Hook\Hook\BeforeSave;
/**
* Hook: Berechnet Dokumenten-Hashes und setzt fileStatus
*
* Verwendet Blake3 als Hash-Algorithmus für optimale Performance
*/
class CDokumente implements BeforeSave
{
public function __construct(
private \Espo\ORM\EntityManager $entityManager
) {}
public function beforeSave(Entity $entity, SaveOptions $options): void
{
// Problem: isAttributeChanged('dokument') erkennt Datei-Änderungen nicht,
// da EspoCRM Datei-Uploads nicht als Feld-Änderung markiert.
// Daher läuft der Hook bei jeder beforeSave mit dokument-Feld,
// um sicherzustellen, dass Hashes bei Datei-Änderungen berechnet werden.
// Optimierung wäre wünschenswert, aber nicht möglich mit aktueller API.
$dokumentId = $entity->get('dokumentId');
if (!$dokumentId) {
return;
}
// Verwende EntityManager zur korrekten Relation-Verwaltung
$attachment = $this->entityManager->getEntityById('Attachment', $dokumentId);
if (!$attachment) {
return;
}
$filePath = 'data/upload/' . $attachment->getId();
if (!file_exists($filePath)) {
return;
}
// Berechne Blake3 Hash
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
return;
}
// Blake3 Hashing - schneller als SHA3 und kryptographisch sicher
$newBlake3 = blake3($fileContent);
// Setze Hash
$entity->set('blake3hash', $newBlake3);
// Bestimme Status
if ($entity->isNew()) {
$entity->set('fileStatus', 'new');
} else {
$oldBlake3 = $entity->getFetched('blake3hash');
if ($oldBlake3 !== $newBlake3) {
$entity->set('fileStatus', 'changed');
} else {
$entity->set('fileStatus', 'synced');
}
}
}
}