Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 29 additions & 18 deletions lib/Db/FileMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,31 +220,42 @@ public function getFilesOfAccount(string $userId): array {
return $return;
}

public function getFileType(int $id): string {
public function getDeletionContext(int $nodeId): array {
$fullOuterJoin = $this->db->getQueryBuilder();
$fullOuterJoin->select($fullOuterJoin->expr()->literal(1));

$qb = $this->db->getQueryBuilder();
$qb
->selectAlias('f.id', 'file')
->selectAlias('sf.signed_node_id', 'signed_file')
->selectAlias('ue.id', 'user_element')
->selectAlias('fe.id', 'file_element')
->selectAlias('f.id', 'file_id')
->selectAlias('sf.id', 'signed_file_id')
->selectAlias('ue.id', 'user_element_id')
->selectAlias('fe.file_id', 'file_element_file_id')
->from($qb->createFunction('(' . $fullOuterJoin->getSQL() . ')'), 'foj')
->leftJoin('foj', 'libresign_file', 'f', $qb->expr()->eq('f.node_id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_file', 'sf', $qb->expr()->eq('sf.signed_node_id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_user_element', 'ue', $qb->expr()->eq('ue.file_id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_file_element', 'fe', $qb->expr()->eq('fe.file_id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
$cursor = $qb->executeQuery();
$row = $cursor->fetch();
if ($row) {
foreach ($row as $key => $value) {
if ($value) {
return $key;
}
}
->leftJoin('foj', 'libresign_file', 'f', $qb->expr()->eq('f.node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_file', 'sf', $qb->expr()->eq('sf.signed_node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_user_element', 'ue', $qb->expr()->eq('ue.node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)))
->leftJoin('foj', 'libresign_file_element', 'fe', $qb->expr()->eq('fe.file_id', 'f.id'))
->setMaxResults(1);

$row = $qb->executeQuery()->fetch();
if (!$row) {
return ['type' => 'not_libresign_file', 'fileId' => null];
}
return 'not_libresign_file';

if (!empty($row['signed_file_id'])) {
return ['type' => 'signed_file', 'fileId' => (int)$row['signed_file_id']];
}
if (!empty($row['file_id'])) {
return ['type' => 'file', 'fileId' => (int)$row['file_id']];
}
if (!empty($row['user_element_id'])) {
return ['type' => 'user_element', 'fileId' => null];
}
if (!empty($row['file_element_file_id'])) {
return ['type' => 'file_element', 'fileId' => (int)$row['file_element_file_id']];
}

return ['type' => 'not_libresign_file', 'fileId' => null];
}

public function getTextOfStatus(int|FileStatus $status): string {
Expand Down
8 changes: 4 additions & 4 deletions lib/Db/UserElement.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
* @method int getId()
* @method void setType(string $type)
* @method string getType()
* @method void setFileId(int $fileId)
* @method int getFileId()
* @method void setNodeId(int $nodeId)
* @method int getNodeId()
* @method void setUserId(string $userId)
* @method void setStarred(int $starred)
* @method int getStarred()
Expand All @@ -27,7 +27,7 @@
*/
class UserElement extends Entity {
public string $type = '';
protected int $fileId = 0;
protected int $nodeId = 0;
protected string $userId = '';
public bool $starred = false;
public ?\DateTime $createdAt = null;
Expand All @@ -37,7 +37,7 @@ class UserElement extends Entity {
public function __construct() {
$this->addType('id', Types::INTEGER);
$this->addType('type', Types::STRING);
$this->addType('fileId', Types::INTEGER);
$this->addType('nodeId', Types::INTEGER);
$this->addType('userId', Types::STRING);
$this->addType('starred', Types::INTEGER);
$this->addType('createdAt', Types::DATETIME);
Expand Down
4 changes: 2 additions & 2 deletions lib/Db/UserElementMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ private function getQueryBuilder(array $data): IQueryBuilder {
$qb->expr()->eq('ue.id', $qb->createNamedParameter($data['id'], IQueryBuilder::PARAM_INT))
);
}
if (isset($data['file_id'])) {
if (isset($data['node_id'])) {
$qb->andWhere(
$qb->expr()->eq('ue.file_id', $qb->createNamedParameter($data['file_id'], IQueryBuilder::PARAM_INT))
$qb->expr()->eq('ue.node_id', $qb->createNamedParameter($data['node_id'], IQueryBuilder::PARAM_INT))
);
}
if (isset($data['type'])) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Helper/ValidateHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ public function validateVisibleElementsRelation(array $list, SignRequest $signRe
$this->validateSignerIsOwnerOfPdfVisibleElement($elements['documentElementId'], $signRequest);
if ($canCreateSignature && $user instanceof IUser) {
try {
$this->userElementMapper->findOne(['file_id' => $elements['profileNodeId'], 'user_id' => $user->getUID()]);
$this->userElementMapper->findOne(['node_id' => $elements['profileNodeId'], 'user_id' => $user->getUID()]);
} catch (\Throwable) {
throw new LibresignException($this->l10n->t('Field %s does not belong to user', $elements['profileNodeId']));
}
Expand Down
25 changes: 17 additions & 8 deletions lib/Listener/BeforeNodeDeletedListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,26 +50,35 @@ public function handle(Event $event): void {
}

private function delete(int $nodeId): void {
$type = $this->fileMapper->getFileType($nodeId);
if ($type === 'not_libresign_file') {
$context = $this->fileMapper->getDeletionContext($nodeId);
if ($context['type'] === 'not_libresign_file') {
return;
}
switch ($type) {
switch ($context['type']) {
case 'signed_file':
$file = $this->fileMapper->getByNodeId($nodeId);
$this->requestSignatureService->deleteRequestSignature(['file' => ['fileId' => $file->getId()]]);
if (!isset($context['fileId'])) {
return;
}
$this->requestSignatureService->deleteRequestSignature(['file' => ['fileId' => $context['fileId']]]);
break;
case 'file':
$libresignFile = $this->fileMapper->getByNodeId($nodeId);
$this->requestSignatureService->deleteRequestSignature(['file' => ['fileId' => $libresignFile->getId()]]);
$this->fileMapper->delete($libresignFile);
break;
case 'user_element':
$qb = $this->db->getQueryBuilder();
$qb->delete('libresign_user_element')
->where($qb->expr()->eq('node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)))
->executeStatement();
break;
case 'file_element':
$field = $type === 'file' ? 'node_id' : 'file_id';
if (!isset($context['fileId'])) {
return;
}
$qb = $this->db->getQueryBuilder();
$qb->delete('libresign_' . $type)
->where($qb->expr()->eq($field, $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)))
$qb->delete('libresign_file_element')
->where($qb->expr()->eq('file_id', $qb->createNamedParameter($context['fileId'], IQueryBuilder::PARAM_INT)))
->executeStatement();
}
}
Expand Down
140 changes: 140 additions & 0 deletions lib/Migration/Version16002Date20251230120000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2025 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\DB\Types;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Files\IAppData;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version16002Date20251230120000 extends SimpleMigrationStep {
protected IAppData $appData;

public function __construct(
private IDBConnection $connection,
private IAppDataFactory $appDataFactory,
) {
$this->appData = $appDataFactory->get('libresign');
}

#[\Override]
public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
$this->backupUserElementTable();
}

#[\Override]
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$changed = false;

if ($schema->hasTable('libresign_user_element')) {
$table = $schema->getTable('libresign_user_element');
if (!$table->hasColumn('node_id')) {
$table->addColumn('node_id', Types::BIGINT, [
'notnull' => false,
'unsigned' => true,
]);
$changed = true;
}

if ($table->hasColumn('file_id')) {
$table->dropColumn('file_id');
$changed = true;
}
}

return $changed ? $schema : null;
}

private function backupUserElementTable(): void {
$qb = $this->connection->getQueryBuilder();
$qb->select('*')
->from('libresign_user_element')
->orderBy('id');

$cursor = $qb->executeQuery();
$row = $cursor->fetch();
if (!$row) {
$cursor->closeCursor();
return;
}

$folder = $this->appData->getFolder('/');
$file = $folder->newFile('backup-table-libresign_user_element_Version16002Date20251230120000.csv');
$fp = $file->write();

fputcsv($fp, array_keys($row));
fputcsv($fp, $row);
while ($row = $cursor->fetch()) {
fputcsv($fp, $row);
}

fclose($fp);
$cursor->closeCursor();
}

private function restoreNodeIdsFromBackup(): void {
$folder = $this->appData->getFolder('/');
$filename = 'backup-table-libresign_user_element_Version16002Date20251230120000.csv';
if (!$folder->fileExists($filename)) {
return;
}

$file = $folder->getFile($filename);
$handle = $file->read();
if ($handle === false) {
return;
}

$header = fgetcsv($handle);
if ($header === false) {
fclose($handle);
return;
}

$columnIndex = array_flip($header);
if (!isset($columnIndex['id']) || !isset($columnIndex['file_id'])) {
fclose($handle);
return;
}

while (($row = fgetcsv($handle)) !== false) {
if (!isset($row[$columnIndex['id']])) {
continue;
}

$userElementId = (int)$row[$columnIndex['id']];
$nodeId = $row[$columnIndex['file_id']] ?? null;
if ($nodeId === null || $nodeId === '') {
continue;
}

$qb = $this->connection->getQueryBuilder();
$qb->update('libresign_user_element')
->set('node_id', $qb->createNamedParameter((int)$nodeId, IQueryBuilder::PARAM_INT))
->where($qb->expr()->eq('id', $qb->createNamedParameter($userElementId, IQueryBuilder::PARAM_INT)));

$qb->executeStatement();
}

fclose($handle);
}

#[\Override]
public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
$this->restoreNodeIdsFromBackup();
}

}
10 changes: 5 additions & 5 deletions lib/Service/AccountService.php
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ public function getPdfByUuid(string $uuid): File {

public function getFileByNodeId(int $nodeId): File {
try {
return $this->folderService->getFileById($nodeId);
return $this->folderService->getFileByNodeId($nodeId);
} catch (NotFoundException) {
throw new DoesNotExistException('Not found');
}
Expand Down Expand Up @@ -394,7 +394,7 @@ private function updateFileOfVisibleElement(array $data): void {
return;
}
$userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
$file = $this->folderService->getFileById($userElement->getFileId());
$file = $this->folderService->getFileByNodeId($userElement->getNodeId());
$file->putContent($this->getFileRaw($data));
}

Expand Down Expand Up @@ -449,7 +449,7 @@ private function createFileOfVisibleElementUsingSession(array $data, string $ses
private function insertVisibleElement(array $data, IUser $user, File $file): void {
$userElement = new UserElement();
$userElement->setType($data['type']);
$userElement->setFileId($file->getId());
$userElement->setNodeId($file->getId());
$userElement->setUserId($user->getUID());
$userElement->setStarred(isset($data['starred']) && $data['starred'] ? 1 : 0);
$userElement->setCreatedAt($this->timeFactory->getDateTime());
Expand Down Expand Up @@ -489,12 +489,12 @@ private function getFileRaw(array $data): string {
public function deleteSignatureElement(?IUser $user, string $sessionId, int $nodeId): void {
if ($user instanceof IUser) {
$element = $this->userElementMapper->findOne([
'file_id' => $nodeId,
'node_id' => $nodeId,
'user_id' => $user->getUID(),
]);
$this->userElementMapper->delete($element);
try {
$file = $this->folderService->getFileById($element->getFileId());
$file = $this->folderService->getFileByNodeId($element->getNodeId());
$file->delete();
} catch (NotFoundException) {
}
Expand Down
6 changes: 3 additions & 3 deletions lib/Service/FileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public function getNodeFromData(array $data): Node {
return $data['file']['fileNode'];
}
if (isset($data['file']['fileId'])) {
return $this->folderService->getFileById($data['file']['fileId']);
return $this->folderService->getFileByNodeId($data['file']['fileId']);
}
if (isset($data['file']['path'])) {
return $this->folderService->getFileByPath($data['file']['path']);
Expand Down Expand Up @@ -589,11 +589,11 @@ public function delete(int $fileId): void {
$this->idDocsMapper->deleteByFileId($file->getId());
$this->fileMapper->delete($file);
if ($file->getSignedNodeId()) {
$signedNextcloudFile = $this->folderService->getFileById($file->getSignedNodeId());
$signedNextcloudFile = $this->folderService->getFileByNodeId($file->getSignedNodeId());
$signedNextcloudFile->delete();
}
try {
$nextcloudFile = $this->folderService->getFileById($fileId);
$nextcloudFile = $this->folderService->getFileByNodeId($file->getNodeId());
$nextcloudFile->delete();
} catch (NotFoundException) {
}
Expand Down
2 changes: 1 addition & 1 deletion lib/Service/FolderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public function getFolder(): Folder {
/**
* @throws NotFoundException
*/
public function getFileById(?int $nodeId = null): File {
public function getFileByNodeId(?int $nodeId = null): File {
if ($this->getUserId()) {

$file = $this->root->getUserFolder($this->getUserId())->getFirstNodeById($nodeId);
Expand Down
4 changes: 2 additions & 2 deletions lib/Service/SignFileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ private function retrieveUserElement(FileElement $fileElement): int {
} catch (MultipleObjectsReturnedException|DoesNotExistException|Exception) {
throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
}
return $userElement->getFileId();
return $userElement->getNodeId();
}

private function bindFileElementWithTempFile(FileElement $fileElement, int $nodeId): VisibleElementAssoc {
Expand All @@ -292,7 +292,7 @@ private function bindFileElementWithTempFile(FileElement $fileElement, int $node

private function getNode(int $nodeId): ?File {
if ($this->user instanceof IUser) {
return $this->folderService->getFileById($nodeId);
return $this->folderService->getFileByNodeId($nodeId);
}

$filesOfElementes = $this->signerElementsService->getElementsFromSession();
Expand Down
Loading
Loading