• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LibreSign / libresign / 20796469636

07 Jan 2026 09:04PM UTC coverage: 44.715%. First build
20796469636

Pull #6379

github

web-flow
Merge 92837e940 into bfecdab01
Pull Request #6379: fix: prevent false error when edit without users

1 of 2 new or added lines in 1 file covered. (50.0%)

6731 of 15053 relevant lines covered (44.72%)

5.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.44
/lib/Service/RequestSignatureService.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Service;
10

11
use OCA\Libresign\AppInfo\Application;
12
use OCA\Libresign\Db\File as FileEntity;
13
use OCA\Libresign\Db\FileElementMapper;
14
use OCA\Libresign\Db\FileMapper;
15
use OCA\Libresign\Db\IdentifyMethodMapper;
16
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
17
use OCA\Libresign\Db\SignRequestMapper;
18
use OCA\Libresign\Enum\SignatureFlow;
19
use OCA\Libresign\Events\SignRequestCanceledEvent;
20
use OCA\Libresign\Exception\LibresignException;
21
use OCA\Libresign\Handler\DocMdpHandler;
22
use OCA\Libresign\Helper\FileUploadHelper;
23
use OCA\Libresign\Helper\ValidateHelper;
24
use OCA\Libresign\Service\Envelope\EnvelopeFileRelocator;
25
use OCA\Libresign\Service\Envelope\EnvelopeService;
26
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
27
use OCP\EventDispatcher\IEventDispatcher;
28
use OCP\Files\IMimeTypeDetector;
29
use OCP\Files\Node;
30
use OCP\Http\Client\IClientService;
31
use OCP\IAppConfig;
32
use OCP\IL10N;
33
use OCP\IUser;
34
use OCP\IUserManager;
35
use Psr\Log\LoggerInterface;
36
use Sabre\DAV\UUIDUtil;
37

38
class RequestSignatureService {
39

40
        public function __construct(
41
                protected FileService $fileService,
42
                protected IL10N $l10n,
43
                protected IdentifyMethodService $identifyMethod,
44
                protected SignRequestMapper $signRequestMapper,
45
                protected IUserManager $userManager,
46
                protected FileMapper $fileMapper,
47
                protected IdentifyMethodMapper $identifyMethodMapper,
48
                protected PdfParserService $pdfParserService,
49
                protected FileElementService $fileElementService,
50
                protected FileElementMapper $fileElementMapper,
51
                protected FolderService $folderService,
52
                protected IMimeTypeDetector $mimeTypeDetector,
53
                protected ValidateHelper $validateHelper,
54
                protected IClientService $client,
55
                protected DocMdpHandler $docMdpHandler,
56
                protected LoggerInterface $logger,
57
                protected SequentialSigningService $sequentialSigningService,
58
                protected IAppConfig $appConfig,
59
                protected IEventDispatcher $eventDispatcher,
60
                protected FileStatusService $fileStatusService,
61
                protected DocMdpConfigService $docMdpConfigService,
62
                protected EnvelopeService $envelopeService,
63
                protected EnvelopeFileRelocator $envelopeFileRelocator,
64
                protected FileUploadHelper $uploadHelper,
65
                protected SignRequestService $signRequestService,
66
        ) {
67
        }
41✔
68

69
        /**
70
         * Save files - creates single file or envelope based on files count
71
         *
72
         * @return array{file: FileEntity, children: list<FileEntity>}
73
         */
74
        public function saveFiles(array $data): array {
75
                if (empty($data['files'])) {
1✔
76
                        throw new LibresignException('Files parameter is required');
×
77
                }
78

79
                if (count($data['files']) === 1) {
1✔
80
                        $fileData = $data['files'][0];
1✔
81

82
                        $saveData = [
1✔
83
                                'name' => $data['name'] ?? $fileData['name'] ?? '',
1✔
84
                                'userManager' => $data['userManager'],
1✔
85
                                'status' => FileEntity::STATUS_DRAFT,
1✔
86
                                'settings' => $data['settings'],
1✔
87
                        ];
1✔
88

89
                        if (isset($fileData['uploadedFile'])) {
1✔
90
                                $saveData['uploadedFile'] = $fileData['uploadedFile'];
×
91
                        } elseif (isset($fileData['fileNode'])) {
1✔
92
                                $saveData['file'] = ['fileNode' => $fileData['fileNode']];
×
93
                        } else {
94
                                $saveData['file'] = $fileData;
1✔
95
                        }
96

97
                        $savedFile = $this->save($saveData);
1✔
98

99
                        return [
1✔
100
                                'file' => $savedFile,
1✔
101
                                'children' => [$savedFile],
1✔
102
                        ];
1✔
103
                }
104

105
                $result = $this->saveEnvelope([
×
106
                        'files' => $data['files'],
×
107
                        'name' => $data['name'],
×
108
                        'userManager' => $data['userManager'],
×
109
                        'settings' => $data['settings'],
×
110
                        'users' => $data['users'] ?? [],
×
111
                        'status' => $data['status'] ?? FileEntity::STATUS_DRAFT,
×
112
                        'visibleElements' => $data['visibleElements'] ?? [],
×
113
                        'signatureFlow' => $data['signatureFlow'] ?? null,
×
114
                ]);
×
115

116
                return [
×
117
                        'file' => $result['envelope'],
×
118
                        'children' => $result['files'],
×
119
                ];
×
120
        }
121

122
        public function save(array $data): FileEntity {
123
                $file = $this->saveFile($data);
14✔
124
                if (!isset($data['status'])) {
14✔
125
                        $data['status'] = $file->getStatus();
12✔
126
                }
127
                $this->sequentialSigningService->setFile($file);
14✔
128
                $this->associateToSigners($data, $file);
14✔
129
                $this->propagateSignersToChildren($file, $data);
14✔
130
                $this->saveVisibleElements($data, $file);
14✔
131

132
                return $file;
14✔
133
        }
134

135
        private function propagateSignersToChildren(FileEntity $envelope, array $data): void {
136
                if ($envelope->getNodeType() !== 'envelope' || empty($data['users'])) {
14✔
137
                        return;
14✔
138
                }
139

140
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
141

142
                $dataWithoutNotification = $data;
×
143
                foreach ($dataWithoutNotification['users'] as &$user) {
×
144
                        $user['notify'] = 0;
×
145
                }
146

147
                foreach ($children as $child) {
×
148
                        $this->identifyMethod->clearCache();
×
149
                        $this->sequentialSigningService->setFile($child);
×
150
                        $this->associateToSigners($dataWithoutNotification, $child);
×
151
                }
152

153
                if ($envelope->getStatus() > FileEntity::STATUS_DRAFT) {
×
154
                        $this->fileStatusService->propagateStatusToChildren($envelope->getId(), $envelope->getStatus());
×
155
                }
156
        }
157

158
        public function saveEnvelope(array $data): array {
159
                $this->envelopeService->validateEnvelopeConstraints(count($data['files']));
×
160

161
                $envelopeName = $data['name'] ?: $this->l10n->t('Envelope %s', [date('Y-m-d H:i:s')]);
×
162
                $userManager = $data['userManager'] ?? null;
×
163
                $userId = $userManager instanceof IUser ? $userManager->getUID() : null;
×
164
                $filesCount = count($data['files']);
×
165

166
                $envelope = null;
×
167
                $files = [];
×
168
                $createdNodes = [];
×
169

170
                try {
171
                        $envelopePath = $data['settings']['path'] ?? null;
×
172
                        $envelope = $this->envelopeService->createEnvelope($envelopeName, $userId, $filesCount, $envelopePath);
×
173

174
                        $envelopeFolder = $this->envelopeService->getEnvelopeFolder($envelope);
×
175
                        $envelopeSettings = array_merge($data['settings'] ?? [], [
×
176
                                'envelopeFolderId' => $envelopeFolder->getId(),
×
177
                        ]);
×
178

179
                        foreach ($data['files'] as $fileData) {
×
180
                                $node = $this->processFileData($fileData, $userManager, $envelopeSettings);
×
181
                                $createdNodes[] = $node;
×
182

183
                                $fileData['node'] = $node;
×
184
                                $fileEntity = $this->createFileForEnvelope($fileData, $userManager, $envelopeSettings);
×
185
                                $this->envelopeService->addFileToEnvelope($envelope->getId(), $fileEntity);
×
186
                                $files[] = $fileEntity;
×
187
                        }
188

189
                        if (!empty($data['users'])) {
×
190
                                $this->sequentialSigningService->setFile($envelope);
×
191
                                $this->associateToSigners($data, $envelope);
×
192
                                $this->propagateSignersToChildren($envelope, $data);
×
193
                        }
194

195
                        return [
×
196
                                'envelope' => $envelope,
×
197
                                'files' => $files,
×
198
                        ];
×
199
                } catch (\Throwable $e) {
×
200
                        $this->rollbackEnvelopeCreation($envelope, $files, $createdNodes);
×
201
                        throw $e;
×
202
                }
203
        }
204

205
        private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node {
206
                if (isset($fileData['uploadedFile'])) {
×
207
                        $sourceNode = $this->fileService->getNodeFromData([
×
208
                                'userManager' => $userManager,
×
209
                                'name' => $fileData['name'] ?? '',
×
210
                                'uploadedFile' => $fileData['uploadedFile'],
×
211
                                'settings' => $settings,
×
212
                        ]);
×
213
                } else {
214
                        $sourceNode = $this->fileService->getNodeFromData([
×
215
                                'userManager' => $userManager,
×
216
                                'name' => $fileData['name'] ?? '',
×
217
                                'file' => $fileData,
×
218
                                'settings' => $settings,
×
219
                        ]);
×
220
                }
221

222
                if (isset($settings['envelopeFolderId'])) {
×
223
                        return $this->envelopeFileRelocator->ensureFileInEnvelopeFolder(
×
224
                                $sourceNode,
×
225
                                $settings['envelopeFolderId'],
×
226
                                $userManager,
×
227
                        );
×
228
                }
229

230
                return $sourceNode;
×
231
        }
232

233
        private function rollbackEnvelopeCreation(?FileEntity $envelope, array $files, array $createdNodes): void {
234
                $this->rollbackCreatedNodes($createdNodes);
×
235
                $this->rollbackCreatedFiles($files);
×
236
                $this->rollbackEnvelope($envelope);
×
237
        }
238

239
        private function rollbackCreatedNodes(array $nodes): void {
240
                foreach ($nodes as $node) {
×
241
                        try {
242
                                $node->delete();
×
243
                        } catch (\Throwable $deleteError) {
×
244
                                $this->logger->error('Failed to rollback created node in envelope', [
×
245
                                        'nodeId' => $node->getId(),
×
246
                                        'error' => $deleteError->getMessage(),
×
247
                                ]);
×
248
                        }
249
                }
250
        }
251

252
        private function rollbackCreatedFiles(array $files): void {
253
                foreach ($files as $file) {
×
254
                        try {
255
                                $this->fileMapper->delete($file);
×
256
                        } catch (\Throwable $deleteError) {
×
257
                                $this->logger->error('Failed to rollback created file entity in envelope', [
×
258
                                        'fileId' => $file->getId(),
×
259
                                        'error' => $deleteError->getMessage(),
×
260
                                ]);
×
261
                        }
262
                }
263
        }
264

265
        private function rollbackEnvelope(?FileEntity $envelope): void {
266
                if ($envelope === null) {
×
267
                        return;
×
268
                }
269

270
                try {
271
                        $this->fileMapper->delete($envelope);
×
272
                } catch (\Throwable $deleteError) {
×
273
                        $this->logger->error('Failed to rollback created envelope', [
×
274
                                'envelopeId' => $envelope->getId(),
×
275
                                'error' => $deleteError->getMessage(),
×
276
                        ]);
×
277
                }
278
        }
279

280
        private function createFileForEnvelope(array $fileData, ?IUser $userManager, array $settings): FileEntity {
281
                if (!isset($fileData['node'])) {
×
282
                        throw new \InvalidArgumentException('Node not provided in file data');
×
283
                }
284

285
                $node = $fileData['node'];
×
286
                $fileName = $fileData['name'] ?? $node->getName();
×
287

288
                return $this->saveFile([
×
289
                        'file' => ['fileNode' => $node],
×
290
                        'name' => $fileName,
×
291
                        'userManager' => $userManager,
×
292
                        'status' => FileEntity::STATUS_DRAFT,
×
293
                        'settings' => $settings,
×
294
                ]);
×
295
        }
296

297
        /**
298
         * Save file data
299
         *
300
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
301
         */
302
        public function saveFile(array $data): FileEntity {
303
                if (!empty($data['uuid'])) {
15✔
304
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
305
                        $this->updateSignatureFlowIfAllowed($file, $data);
1✔
306
                        if (!empty($data['name'])) {
1✔
307
                                $file->setName($data['name']);
×
308
                                $this->fileMapper->update($file);
×
309
                        }
310
                        return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
1✔
311
                }
312
                $fileId = null;
15✔
313
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
314
                        $fileId = $data['file']['fileNode']->getId();
×
315
                } elseif (!empty($data['file']['fileId'])) {
15✔
316
                        $fileId = $data['file']['fileId'];
×
317
                }
318
                if (!is_null($fileId)) {
15✔
319
                        try {
320
                                $file = $this->fileMapper->getByNodeId($fileId);
×
321
                                $this->updateSignatureFlowIfAllowed($file, $data);
×
322
                                return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
×
323
                        } catch (\Throwable) {
×
324
                        }
325
                }
326

327
                $node = $this->fileService->getNodeFromData($data);
15✔
328

329
                $file = new FileEntity();
15✔
330
                $file->setNodeId($node->getId());
15✔
331
                if ($data['userManager'] instanceof IUser) {
15✔
332
                        $file->setUserId($data['userManager']->getUID());
15✔
333
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
334
                        $file->setSignRequestId($data['signRequest']->getId());
×
335
                }
336
                $file->setUuid(UUIDUtil::getUUID());
15✔
337
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
338
                $metadata = $this->getFileMetadata($node);
15✔
339
                $name = trim((string)($data['name'] ?? ''));
15✔
340
                if ($name === '') {
15✔
341
                        $name = $node->getName();
×
342
                }
343
                $file->setName($this->removeExtensionFromName($name, $metadata));
15✔
344
                $file->setMetadata($metadata);
15✔
345
                if (!empty($data['callback'])) {
15✔
346
                        $file->setCallback($data['callback']);
×
347
                }
348
                if (isset($data['status'])) {
15✔
349
                        $file->setStatus($data['status']);
2✔
350
                } else {
351
                        $file->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
13✔
352
                }
353

354
                if (isset($data['parentFileId'])) {
15✔
355
                        $file->setParentFileId($data['parentFileId']);
×
356
                }
357

358
                $this->setSignatureFlow($file, $data);
15✔
359
                $this->setDocMdpLevelFromGlobalConfig($file);
15✔
360

361
                $this->fileMapper->insert($file);
15✔
362
                return $file;
15✔
363
        }
364

365
        private function updateSignatureFlowIfAllowed(FileEntity $file, array $data): void {
366
                $adminFlow = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::NONE->value);
1✔
367
                $adminForcedConfig = $adminFlow !== SignatureFlow::NONE->value;
1✔
368

369
                if ($adminForcedConfig) {
1✔
370
                        $adminFlowEnum = SignatureFlow::from($adminFlow);
×
371
                        if ($file->getSignatureFlowEnum() !== $adminFlowEnum) {
×
372
                                $file->setSignatureFlowEnum($adminFlowEnum);
×
373
                                $this->fileMapper->update($file);
×
374
                        }
375
                        return;
×
376
                }
377

378
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
1✔
379
                        $newFlow = SignatureFlow::from($data['signatureFlow']);
×
380
                        if ($file->getSignatureFlowEnum() !== $newFlow) {
×
381
                                $file->setSignatureFlowEnum($newFlow);
×
382
                                $this->fileMapper->update($file);
×
383
                        }
384
                }
385
        }
386

387
        private function setSignatureFlow(FileEntity $file, array $data): void {
388
                $adminFlow = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::NONE->value);
15✔
389

390
                if (isset($data['signatureFlow']) && !empty($data['signatureFlow'])) {
15✔
391
                        $file->setSignatureFlowEnum(SignatureFlow::from($data['signatureFlow']));
×
392
                } elseif ($adminFlow !== SignatureFlow::NONE->value) {
15✔
393
                        $file->setSignatureFlowEnum(SignatureFlow::from($adminFlow));
×
394
                } else {
395
                        $file->setSignatureFlowEnum(SignatureFlow::NONE);
15✔
396
                }
397
        }
398

399
        private function setDocMdpLevelFromGlobalConfig(FileEntity $file): void {
400
                if ($this->docMdpConfigService->isEnabled()) {
15✔
401
                        $docmdpLevel = $this->docMdpConfigService->getLevel();
×
402
                        $file->setDocmdpLevelEnum($docmdpLevel);
×
403
                }
404
        }
405

406
        private function getFileMetadata(\OCP\Files\Node $node): array {
407
                $metadata = [];
18✔
408
                if ($extension = strtolower($node->getExtension())) {
18✔
409
                        $metadata = [
17✔
410
                                'extension' => $extension,
17✔
411
                        ];
17✔
412
                        if ($metadata['extension'] === 'pdf') {
17✔
413
                                $pdfParser = $this->pdfParserService->setFile($node);
16✔
414
                                $metadata = array_merge(
16✔
415
                                        $metadata,
16✔
416
                                        $pdfParser->getPageDimensions()
16✔
417
                                );
16✔
418
                                $metadata['pdfVersion'] = $pdfParser->getPdfVersion();
16✔
419
                        }
420
                }
421
                return $metadata;
18✔
422
        }
423

424
        private function removeExtensionFromName(string $name, array $metadata): string {
425
                if (!isset($metadata['extension'])) {
15✔
426
                        return $name;
×
427
                }
428
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
429
                $result = preg_replace($extensionPattern, '', $name);
15✔
430
                return $result ?? $name;
15✔
431
        }
432

433
        private function deleteIdentifyMethodIfNotExits(array $users, FileEntity $file): void {
434
                $signRequests = $this->signRequestMapper->getByFileId($file->getId());
13✔
435
                foreach ($signRequests as $key => $signRequest) {
13✔
436
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
437
                        if (empty($identifyMethods)) {
1✔
438
                                $this->unassociateToUser($file->getId(), $signRequest->getId());
×
439
                                continue;
×
440
                        }
441
                        foreach ($identifyMethods as $methodName => $list) {
1✔
442
                                foreach ($list as $method) {
1✔
443
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
444
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
445
                                                $this->unassociateToUser($file->getId(), $signRequest->getId());
1✔
446
                                                continue 3;
1✔
447
                                        }
448
                                }
449
                        }
450
                }
451
        }
452

453
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
454
                foreach ($users as $user) {
1✔
455
                        if (!empty($user['identifyMethods'])) {
1✔
456
                                foreach ($user['identifyMethods'] as $data) {
×
457
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
458
                                                continue;
×
459
                                        }
460
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
461
                                                return true;
×
462
                                        }
463
                                }
464
                        } else {
465
                                foreach ($user['identify'] as $method => $value) {
1✔
466
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
467
                                                continue;
×
468
                                        }
469
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
470
                                                return true;
×
471
                                        }
472
                                }
473
                        }
474
                }
475
                return false;
1✔
476
        }
477

478
        /**
479
         * @return SignRequestEntity[]
480
         *
481
         * @psalm-return list<SignRequestEntity>
482
         */
483
        private function associateToSigners(array $data, FileEntity $file): array {
484
                $return = [];
14✔
485
                if (!empty($data['users'])) {
14✔
486
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $file);
13✔
487

488
                        $this->sequentialSigningService->resetOrderCounter();
13✔
489
                        $fileStatus = $data['status'] ?? null;
13✔
490

491
                        foreach ($data['users'] as $user) {
13✔
492
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
493
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
494
                                $signerStatus = $user['status'] ?? null;
13✔
495
                                $shouldNotify = !isset($user['notify']) || $user['notify'] !== 0;
13✔
496

497
                                if (isset($user['identifyMethods'])) {
13✔
498
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
499
                                                $return[] = $this->signRequestService->createOrUpdateSignRequest(
×
500
                                                        identifyMethods: [
×
501
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
502
                                                        ],
×
503
                                                        displayName: $user['displayName'] ?? '',
×
504
                                                        description: $user['description'] ?? '',
×
505
                                                        notify: $shouldNotify,
×
506
                                                        fileId: $file->getId(),
×
507
                                                        signingOrder: $signingOrder,
×
508
                                                        fileStatus: $fileStatus,
×
509
                                                        signerStatus: $signerStatus,
×
510
                                                );
×
511
                                        }
512
                                } else {
513
                                        $return[] = $this->signRequestService->createOrUpdateSignRequest(
13✔
514
                                                identifyMethods: $user['identify'],
13✔
515
                                                displayName: $user['displayName'] ?? '',
13✔
516
                                                description: $user['description'] ?? '',
13✔
517
                                                notify: $shouldNotify,
13✔
518
                                                fileId: $file->getId(),
13✔
519
                                                signingOrder: $signingOrder,
13✔
520
                                                fileStatus: $fileStatus,
13✔
521
                                                signerStatus: $signerStatus,
13✔
522
                                        );
13✔
523
                                }
524
                        }
525
                }
526
                return $return;
14✔
527
        }
528

529

530

531
        private function saveVisibleElements(array $data, FileEntity $file): array {
532
                if (empty($data['visibleElements'])) {
17✔
533
                        return [];
15✔
534
                }
535
                $persisted = [];
2✔
536
                foreach ($data['visibleElements'] as $element) {
2✔
537
                        if ($file->isEnvelope() && !empty($element['signRequestId'])) {
2✔
538
                                $envelopeSignRequest = $this->signRequestMapper->getById((int)$element['signRequestId']);
×
539
                                // Only translate if the provided SR belongs to the envelope itself
540
                                if ($envelopeSignRequest && $envelopeSignRequest->getFileId() === $file->getId()) {
×
541
                                        $childrenSrs = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($file->getId(), (int)$element['signRequestId']);
×
542
                                        foreach ($childrenSrs as $childSr) {
×
543
                                                if ($childSr->getFileId() === (int)$element['fileId']) {
×
544
                                                        $element['signRequestId'] = $childSr->getId();
×
545
                                                        break;
×
546
                                                }
547
                                        }
548
                                }
549
                        }
550

551
                        $persisted[] = $this->fileElementService->saveVisibleElement($element);
2✔
552
                }
553
                return $persisted;
2✔
554
        }
555

556

557
        public function validateNewRequestToFile(array $data): void {
558
                $this->validateNewFile($data);
7✔
559
                $this->validateUsers($data);
6✔
560
                $this->validateHelper->validateFileStatus($data);
2✔
561
        }
562

563
        public function validateNewFile(array $data): void {
564
                if (empty($data['name'])) {
7✔
565
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
566
                }
567
                $this->validateHelper->validateNewFile($data);
6✔
568
        }
569

570
        public function validateUsers(array $data): void {
571
                if (empty($data['users'])) {
6✔
572
                        if (($data['status'] ?? FileEntity::STATUS_ABLE_TO_SIGN) === FileEntity::STATUS_DRAFT) {
3✔
NEW
573
                                return;
×
574
                        }
575
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
576
                }
577
                if (!is_array($data['users'])) {
3✔
578
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
579
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
580
                }
581
                foreach ($data['users'] as $user) {
2✔
582
                        if (!array_key_exists('identify', $user)) {
2✔
583
                                throw new \Exception('Identify key not found');
×
584
                        }
585
                        $this->identifyMethod->setAllEntityData($user);
2✔
586
                }
587
        }
588

589

590

591
        public function unassociateToUser(int $fileId, int $signRequestId): void {
592
                $file = $this->fileMapper->getById($fileId);
2✔
593
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
594
                $deletedOrder = $signRequest->getSigningOrder();
2✔
595
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
596

597
                $this->dispatchCancellationEventIfNeeded($signRequest, $file, $groupedIdentifyMethods);
2✔
598

599
                try {
600
                        $this->signRequestMapper->delete($signRequest);
2✔
601
                        $this->identifyMethod->deleteBySignRequestId($signRequestId);
2✔
602
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
603
                        foreach ($visibleElements as $visibleElement) {
2✔
604
                                $this->fileElementMapper->delete($visibleElement);
×
605
                        }
606

607
                        $this->sequentialSigningService
2✔
608
                                ->setFile($file)
2✔
609
                                ->reorderAfterDeletion($file->getId(), $deletedOrder);
2✔
610

611
                        $this->propagateSignerDeletionToChildren($file, $signRequest);
2✔
612
                } catch (\Throwable) {
×
613
                }
614
        }
615

616
        private function propagateSignerDeletionToChildren(FileEntity $envelope, SignRequestEntity $deletedSignRequest): void {
617
                if ($envelope->getNodeType() !== 'envelope') {
2✔
618
                        return;
2✔
619
                }
620

621
                $children = $this->fileMapper->getChildrenFiles($envelope->getId());
×
622

623
                $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($deletedSignRequest->getId());
×
624
                if (empty($identifyMethods)) {
×
625
                        return;
×
626
                }
627

628
                foreach ($children as $child) {
×
629
                        try {
630
                                $this->identifyMethod->clearCache();
×
631
                                $childSignRequest = $this->signRequestService->getSignRequestByIdentifyMethod(
×
632
                                        current(reset($identifyMethods)),
×
633
                                        $child->getId()
×
634
                                );
×
635

636
                                if ($childSignRequest->getId()) {
×
637
                                        $this->unassociateToUser($child->getId(), $childSignRequest->getId());
×
638
                                }
639
                        } catch (\Throwable $e) {
×
640
                                continue;
×
641
                        }
642
                }
643
        }
644

645
        private function dispatchCancellationEventIfNeeded(
646
                SignRequestEntity $signRequest,
647
                FileEntity $file,
648
                array $groupedIdentifyMethods,
649
        ): void {
650
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
651
                        return;
×
652
                }
653

654
                try {
655
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
656
                                foreach ($identifyMethods as $identifyMethod) {
2✔
657
                                        $event = new SignRequestCanceledEvent(
2✔
658
                                                $signRequest,
2✔
659
                                                $file,
2✔
660
                                                $identifyMethod,
2✔
661
                                        );
2✔
662
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
663
                                }
664
                        }
665
                } catch (\Throwable $e) {
×
666
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
667
                }
668
        }
669

670
        public function deleteRequestSignature(array $data): void {
671
                if (!empty($data['uuid'])) {
1✔
672
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
673
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
674
                } elseif (!empty($data['file']['fileId'])) {
1✔
675
                        $fileData = $this->fileMapper->getById($data['file']['fileId']);
1✔
676
                        $signatures = $this->signRequestMapper->getByFileId($fileData->getId());
1✔
677
                } else {
678
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
679
                }
680
                foreach ($signatures as $signRequest) {
1✔
681
                        $this->identifyMethod->deleteBySignRequestId($signRequest->getId());
1✔
682
                        $this->signRequestMapper->delete($signRequest);
1✔
683
                }
684
                $this->fileMapper->delete($fileData);
1✔
685
                $this->fileElementService->deleteVisibleElements($fileData->getId());
1✔
686
        }
687
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc