*/ class Attachment extends Database implements Di\FileManagerAware, Di\FileStorageManagerAware, Di\ConfigAware { use Di\FileManagerSetter; use Di\FileStorageManagerSetter; use Di\ConfigSetter; /** * @var string[] */ protected $imageTypeList = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp', ]; /** * @var string[] */ protected $imageThumbList = [ 'xxx-small', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', ]; protected function beforeSave(Entity $entity, array $options = []) { parent::beforeSave($entity, $options); if ($entity->isNew()) { $this->processBeforeSaveNew($entity); } } protected function processBeforeSaveNew(AttachmentEntity $entity): void { if ($entity->isBeingUploaded()) { $entity->set('storage', EspoUploadDir::NAME); } if (!$entity->get('storage')) { $defaultStorage = $this->config->get('defaultFileStorage'); $entity->set('storage', $defaultStorage); } $contents = $entity->get('contents'); if (is_null($contents)) { return; } if (!$entity->isBeingUploaded()) { $entity->set('size', strlen($contents)); } $this->fileStorageManager->putContents($entity, $contents); } /** * @param AttachmentEntity $entity */ protected function afterRemove(Entity $entity, array $options = []) { parent::afterRemove($entity, $options); $duplicateCount = $this ->where([ 'OR' => [ [ 'sourceId' => $entity->getSourceId() ], [ 'id' => $entity->getSourceId() ] ], ]) ->count(); if ($duplicateCount === 0) { $this->fileStorageManager->unlink($entity); if (in_array($entity->get('type'), $this->imageTypeList)) { $this->removeImageThumbs($entity); } } } public function removeImageThumbs(AttachmentEntity $entity): void { foreach ($this->imageThumbList as $suffix) { $filePath = "data/upload/thumbs/" . $entity->getSourceId() . "_{$suffix}"; if ($this->fileManager->isFile($filePath)) { $this->fileManager->removeFile($filePath); } } } public function getCopiedAttachment(AttachmentEntity $entity, ?string $role = null): AttachmentEntity { $attachment = $this->getNew(); $attachment->set([ 'sourceId' => $entity->getSourceId(), 'name' => $entity->get('name'), 'type' => $entity->get('type'), 'size' => $entity->get('size'), 'role' => $entity->get('role'), ]); if ($role) { $attachment->set('role', $role); } $this->save($attachment); return $attachment; } public function getContents(AttachmentEntity $entity): string { return $this->fileStorageManager->getContents($entity); } public function getStream(AttachmentEntity $entity): StreamInterface { return $this->fileStorageManager->getStream($entity); } public function getSize(AttachmentEntity $entity): int { return $this->fileStorageManager->getSize($entity); } public function getFilePath(AttachmentEntity $entity): string { return $this->fileStorageManager->getLocalFilePath($entity); } }