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

LibreSign / libresign / 21500367177

30 Jan 2026 12:54AM UTC coverage: 46.602%. First build
21500367177

Pull #6641

github

web-flow
Merge cb4c40590 into f39fc2360
Pull Request #6641: refactor: centralize file status management

75 of 104 new or added lines in 13 files covered. (72.12%)

7906 of 16965 relevant lines covered (46.6%)

5.11 hits per line

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

52.17
/lib/Service/SignFileService.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 DateTime;
12
use DateTimeInterface;
13
use Exception;
14
use InvalidArgumentException;
15
use OC\AppFramework\Http as AppFrameworkHttp;
16
use OC\User\NoUserException;
17
use OCA\Libresign\AppInfo\Application;
18
use OCA\Libresign\BackgroundJob\SignSingleFileJob;
19
use OCA\Libresign\DataObjects\VisibleElementAssoc;
20
use OCA\Libresign\Db\File as FileEntity;
21
use OCA\Libresign\Db\FileElement;
22
use OCA\Libresign\Db\FileElementMapper;
23
use OCA\Libresign\Db\FileMapper;
24
use OCA\Libresign\Db\IdDocs;
25
use OCA\Libresign\Db\IdDocsMapper;
26
use OCA\Libresign\Db\IdentifyMethod;
27
use OCA\Libresign\Db\IdentifyMethodMapper;
28
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
29
use OCA\Libresign\Db\SignRequestMapper;
30
use OCA\Libresign\Db\UserElementMapper;
31
use OCA\Libresign\Enum\FileStatus;
32
use OCA\Libresign\Events\SignedEventFactory;
33
use OCA\Libresign\Exception\LibresignException;
34
use OCA\Libresign\Handler\DocMdpHandler;
35
use OCA\Libresign\Handler\FooterHandler;
36
use OCA\Libresign\Handler\PdfTk\Pdf;
37
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
38
use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
39
use OCA\Libresign\Handler\SignEngine\SignEngineHandler;
40
use OCA\Libresign\Helper\JSActions;
41
use OCA\Libresign\Helper\ValidateHelper;
42
use OCA\Libresign\Service\Envelope\EnvelopeStatusDeterminer;
43
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
44
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
45
use OCA\Libresign\Service\SignRequest\StatusService;
46
use OCP\AppFramework\Db\DoesNotExistException;
47
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
48
use OCP\AppFramework\Utility\ITimeFactory;
49
use OCP\BackgroundJob\IJobList;
50
use OCP\EventDispatcher\IEventDispatcher;
51
use OCP\Files\File;
52
use OCP\Files\IRootFolder;
53
use OCP\Files\NotPermittedException;
54
use OCP\Http\Client\IClientService;
55
use OCP\IAppConfig;
56
use OCP\IDateTimeZone;
57
use OCP\IL10N;
58
use OCP\ITempManager;
59
use OCP\IURLGenerator;
60
use OCP\IUser;
61
use OCP\IUserSession;
62
use OCP\Security\ICredentialsManager;
63
use OCP\Security\ISecureRandom;
64
use Psr\Log\LoggerInterface;
65
use RuntimeException;
66
use Sabre\DAV\UUIDUtil;
67

68
class SignFileService {
69
        private ?SignRequestEntity $signRequest = null;
70
        private string $password = '';
71
        private ?FileEntity $libreSignFile = null;
72
        /** @var VisibleElementAssoc[] */
73
        private $elements = [];
74
        private array $elementsInput = [];
75
        private bool $signWithoutPassword = false;
76
        private ?string $signatureMethodName = null;
77
        private ?File $fileToSign = null;
78
        private ?File $createdSignedFile = null;
79
        private string $userUniqueIdentifier = '';
80
        private string $friendlyName = '';
81
        private ?IUser $user = null;
82
        private ?SignEngineHandler $engine = null;
83
        private PfxProvider $pfxProvider;
84

85
        public function __construct(
86
                protected IL10N $l10n,
87
                private FileMapper $fileMapper,
88
                private SignRequestMapper $signRequestMapper,
89
                private IdDocsMapper $idDocsMapper,
90
                private FooterHandler $footerHandler,
91
                protected FolderService $folderService,
92
                private IClientService $client,
93
                protected LoggerInterface $logger,
94
                private IAppConfig $appConfig,
95
                protected ValidateHelper $validateHelper,
96
                private SignerElementsService $signerElementsService,
97
                private IRootFolder $root,
98
                private IUserSession $userSession,
99
                private IDateTimeZone $dateTimeZone,
100
                private FileElementMapper $fileElementMapper,
101
                private UserElementMapper $userElementMapper,
102
                private IEventDispatcher $eventDispatcher,
103
                protected ISecureRandom $secureRandom,
104
                private IURLGenerator $urlGenerator,
105
                private IdentifyMethodMapper $identifyMethodMapper,
106
                private ITempManager $tempManager,
107
                private SigningCoordinatorService $signingCoordinatorService,
108
                private IdentifyMethodService $identifyMethodService,
109
                private ITimeFactory $timeFactory,
110
                protected SignEngineFactory $signEngineFactory,
111
                private SignedEventFactory $signedEventFactory,
112
                private Pdf $pdf,
113
                private DocMdpHandler $docMdpHandler,
114
                private PdfSignatureDetectionService $pdfSignatureDetectionService,
115
                private SequentialSigningService $sequentialSigningService,
116
                private FileStatusService $fileStatusService,
117
                private StatusService $statusService,
118
                private IJobList $jobList,
119
                private ICredentialsManager $credentialsManager,
120
                private EnvelopeStatusDeterminer $envelopeStatusDeterminer,
121
                private TsaValidationService $tsaValidationService,
122
                PfxProvider $pfxProvider,
123
        ) {
124
                $this->pfxProvider = $pfxProvider;
149✔
125
        }
126

127
        /**
128
         * Can delete sing request
129
         */
130
        public function canDeleteRequestSignature(array $data): void {
131
                if (!empty($data['uuid'])) {
2✔
132
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
2✔
133
                } elseif (!empty($data['file']['fileId'])) {
×
134
                        $signatures = $this->signRequestMapper->getByNodeId($data['file']['fileId']);
×
135
                } else {
136
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
137
                }
138
                $signed = array_filter($signatures, fn ($s) => $s->getSigned());
2✔
139
                if ($signed) {
2✔
140
                        throw new \Exception($this->l10n->t('Document already signed'));
1✔
141
                }
142
                array_walk($data['users'], function ($user) use ($signatures): void {
1✔
143
                        $exists = array_filter($signatures, function (SignRequestEntity $signRequest) use ($user) {
1✔
144
                                $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($signRequest->getId());
1✔
145
                                if ($identifyMethod->getName() === 'email') {
1✔
146
                                        return $identifyMethod->getEntity()->getIdentifierValue() === $user['email'];
×
147
                                }
148
                                return false;
1✔
149
                        });
1✔
150
                        if (!$exists) {
1✔
151
                                throw new \Exception($this->l10n->t('No signature was requested to %s', $user['email']));
1✔
152
                        }
153
                });
1✔
154
        }
155

156
        public function notifyCallback(File $file): void {
157
                $uri = $this->libreSignFile->getCallback();
1✔
158
                if (!$uri) {
1✔
159
                        $uri = $this->appConfig->getValueString(Application::APP_ID, 'webhook_sign_url');
×
160
                        if (!$uri) {
×
161
                                return;
×
162
                        }
163
                }
164
                $options = [
1✔
165
                        'multipart' => [
1✔
166
                                [
1✔
167
                                        'name' => 'uuid',
1✔
168
                                        'contents' => $this->libreSignFile->getUuid(),
1✔
169
                                ],
1✔
170
                                [
1✔
171
                                        'name' => 'status',
1✔
172
                                        'contents' => $this->libreSignFile->getStatus(),
1✔
173
                                ],
1✔
174
                                [
1✔
175
                                        'name' => 'file',
1✔
176
                                        'contents' => $file->fopen('r'),
1✔
177
                                        'filename' => $file->getName()
1✔
178
                                ]
1✔
179
                        ]
1✔
180
                ];
1✔
181
                $this->client->newClient()->post($uri, $options);
1✔
182
        }
183

184
        /**
185
         * @return static
186
         */
187
        public function setLibreSignFile(FileEntity $libreSignFile): self {
188
                $this->libreSignFile = $libreSignFile;
47✔
189
                return $this;
47✔
190
        }
191

192
        public function setUserUniqueIdentifier(string $identifier): self {
193
                $this->userUniqueIdentifier = $identifier;
7✔
194
                return $this;
7✔
195
        }
196

197
        public function setFriendlyName(string $friendlyName): self {
198
                $this->friendlyName = $friendlyName;
7✔
199
                return $this;
7✔
200
        }
201

202
        /**
203
         * @return static
204
         */
205
        public function setSignRequest(SignRequestEntity $signRequest): self {
206
                $this->signRequest = $signRequest;
81✔
207
                return $this;
81✔
208
        }
209

210
        /**
211
         * @return static
212
         */
213
        public function setSignWithoutPassword(bool $signWithoutPassword = true): self {
214
                $this->signWithoutPassword = $signWithoutPassword;
7✔
215
                return $this;
7✔
216
        }
217

218
        public function setSignatureMethod(?string $signatureMethodName): self {
219
                $this->signatureMethodName = $signatureMethodName;
7✔
220
                return $this;
7✔
221
        }
222

223
        /**
224
         * @return static
225
         */
226
        public function setPassword(?string $password = null): self {
227
                $this->password = $password;
6✔
228
                return $this;
6✔
229
        }
230

231
        public function setCurrentUser(?IUser $user): self {
232
                $this->user = $user;
32✔
233
                return $this;
32✔
234
        }
235

236
        public function prepareForSigning(
237
                FileEntity $libreSignFile,
238
                SignRequestEntity $signRequest,
239
                ?IUser $user,
240
                string $userIdentifier,
241
                string $displayName,
242
                bool $signWithoutPassword,
243
                ?string $password = null,
244
                ?string $signatureMethodName = null,
245
        ): self {
246
                if ($signWithoutPassword) {
6✔
247
                        $this->setSignWithoutPassword();
4✔
248
                } else {
249
                        $this->setPassword($password);
2✔
250
                }
251

252
                return $this
6✔
253
                        ->setLibreSignFile($libreSignFile)
6✔
254
                        ->setSignRequest($signRequest)
6✔
255
                        ->setCurrentUser($user)
6✔
256
                        ->setUserUniqueIdentifier($userIdentifier)
6✔
257
                        ->setFriendlyName($displayName)
6✔
258
                        ->setSignatureMethod($signatureMethodName);
6✔
259
        }
260

261
        public function setVisibleElements(array $list): self {
262
                $this->elementsInput = $list;
39✔
263
                $this->elements = [];
39✔
264
                if (!$this->signRequest instanceof SignRequestEntity) {
39✔
265
                        return $this;
×
266
                }
267
                $fileId = $this->signRequest->getFileId();
39✔
268
                $signRequestId = $this->signRequest->getId();
39✔
269

270
                if (empty($list) && ($fileId === null || $signRequestId === null)) {
39✔
271
                        return $this;
21✔
272
                }
273

274
                if ($fileId === null || $signRequestId === null) {
18✔
275
                        throw new LibresignException($this->l10n->t('File not found'));
3✔
276
                }
277

278
                $fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
15✔
279
                $canCreateSignature = $this->signerElementsService->canCreateSignature();
15✔
280

281
                foreach ($fileElements as $fileElement) {
15✔
282
                        $this->elements[] = $this->buildVisibleElementAssoc($fileElement, $list, $canCreateSignature);
13✔
283
                }
284

285
                return $this;
6✔
286
        }
287

288
        private function buildVisibleElementAssoc(FileElement $fileElement, array $list, bool $canCreateSignature): VisibleElementAssoc {
289
                if (!$canCreateSignature) {
13✔
290
                        return new VisibleElementAssoc($fileElement);
1✔
291
                }
292

293
                $element = $this->array_find($list, fn (array $element): bool => ($element['documentElementId'] ?? '') === $fileElement->getId());
12✔
294
                $nodeId = $this->getNodeId($element, $fileElement);
12✔
295

296
                return $this->bindFileElementWithTempFile($fileElement, $nodeId);
8✔
297
        }
298

299
        private function getNodeId(?array $element, FileElement $fileElement): int {
300
                if ($this->isValidElement($element)) {
12✔
301
                        return (int)$element['profileNodeId'];
8✔
302
                }
303

304
                return $this->retrieveUserElement($fileElement);
×
305
        }
306

307
        private function isValidElement(?array $element): bool {
308
                if (is_array($element) && !empty($element['profileNodeId']) && is_int($element['profileNodeId'])) {
12✔
309
                        return true;
8✔
310
                }
311
                $this->logger->error('Invalid data provided for signing file.', ['element' => $element]);
4✔
312
                throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
4✔
313
        }
314

315
        private function retrieveUserElement(FileElement $fileElement): int {
316
                try {
317
                        if (!$this->user instanceof IUser) {
×
318
                                throw new Exception('User not set');
×
319
                        }
320
                        $userElement = $this->userElementMapper->findOne([
×
321
                                'user_id' => $this->user->getUID(),
×
322
                                'type' => $fileElement->getType(),
×
323
                        ]);
×
324
                } catch (MultipleObjectsReturnedException|DoesNotExistException|Exception) {
×
325
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
×
326
                }
327
                return $userElement->getNodeId();
×
328
        }
329

330
        private function bindFileElementWithTempFile(FileElement $fileElement, int $nodeId): VisibleElementAssoc {
331
                try {
332
                        $node = $this->getNode($nodeId);
8✔
333
                        if (!$node) {
8✔
334
                                throw new \Exception('Node content is empty or unavailable.');
8✔
335
                        }
336
                } catch (\Throwable) {
4✔
337
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
4✔
338
                }
339

340
                $tempFile = $this->tempManager->getTemporaryFile('_' . $nodeId . '.png');
4✔
341
                $content = $node->getContent();
4✔
342
                if (empty($content)) {
4✔
343
                        $this->logger->error('Failed to retrieve content for node.', ['nodeId' => $nodeId, 'fileElement' => $fileElement]);
1✔
344
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
1✔
345
                }
346
                file_put_contents($tempFile, $content);
3✔
347
                return new VisibleElementAssoc($fileElement, $tempFile);
3✔
348
        }
349

350
        private function getNode(int $nodeId): ?File {
351
                try {
352
                        return $this->folderService->getFileByNodeId($nodeId);
8✔
353
                } catch (\Throwable) {
4✔
354
                        $filesOfElementes = $this->signerElementsService->getElementsFromSession();
4✔
355
                        return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
4✔
356
                }
357
        }
358

359
        /**
360
         * Fallback to PHP < 8.4
361
         *
362
         * Reference: https://www.php.net/manual/en/function.array-find.php#130257
363
         *
364
         * @todo remove this after minor PHP version is >= 8.4
365
         * @deprecated This method will be removed once the minimum PHP version is >= 8.4. Use native array_find instead.
366
         */
367
        private function array_find(array $array, callable $callback): mixed {
368
                foreach ($array as $key => $value) {
13✔
369
                        if ($callback($value, $key)) {
12✔
370
                                return $value;
11✔
371
                        }
372
                }
373

374
                return null;
6✔
375
        }
376

377
        public function getVisibleElements(): array {
378
                return $this->elements;
8✔
379
        }
380

381
        public function getJobArgumentsWithoutCredentials(): array {
382
                $args = [];
×
383

384
                if (!empty($this->userUniqueIdentifier)) {
×
385
                        $args['userUniqueIdentifier'] = $this->userUniqueIdentifier;
×
386
                }
387

388
                if (!empty($this->friendlyName)) {
×
389
                        $args['friendlyName'] = $this->friendlyName;
×
390
                }
391

392
                if (!empty($this->elements)) {
×
393
                        $args['visibleElements'] = $this->elements;
×
394
                }
395

396
                if ($this->signRequest instanceof SignRequestEntity && $this->signRequest->getMetadata()) {
×
397
                        $args['metadata'] = $this->signRequest->getMetadata();
×
398
                }
399

400
                if ($this->user instanceof IUser) {
×
401
                        $args['userId'] = $this->user->getUID();
×
402
                }
403

404
                return $args;
×
405
        }
406

407
        public function validateSigningRequirements(): void {
408
                $this->tsaValidationService->validateConfiguration();
×
409
        }
410

411
        public function sign(): void {
412
                $signRequests = $this->getSignRequestsToSign();
18✔
413

414
                if (empty($signRequests)) {
18✔
415
                        throw new LibresignException('No sign requests found to process');
×
416
                }
417

418
                $this->executeSigningStrategy($signRequests);
18✔
419
        }
420

421
        private function executeSigningStrategy(array $signRequests): ?DateTimeInterface {
422
                if ($this->signingCoordinatorService->shouldUseParallelProcessing(count($signRequests))) {
18✔
423
                        return $this->processParallelSigning($signRequests);
×
424
                }
425
                return $this->signSequentially($signRequests);
18✔
426
        }
427

428
        private function processParallelSigning(array $signRequests): ?DateTimeInterface {
429
                $this->enqueueParallelSigningJobs($signRequests, $this->getJobArgumentsWithoutCredentials());
×
430
                return $this->getLatestSignedDate($signRequests);
×
431
        }
432

433
        private function getLatestSignedDate(array $signRequests): ?DateTimeInterface {
434
                $latestSignedDate = null;
×
435

436
                foreach ($signRequests as $signRequestData) {
×
437
                        try {
438
                                $signRequest = $this->signRequestMapper->getById($signRequestData['signRequest']->getId());
×
439
                                if ($signRequest->getSigned()) {
×
440
                                        $latestSignedDate = $signRequest->getSigned();
×
441
                                }
442
                        } catch (DoesNotExistException) {
×
443
                        }
444
                }
445

446
                return $latestSignedDate;
×
447
        }
448

449
        public function signSingleFile(FileEntity $libreSignFile, SignRequestEntity $signRequest): void {
450
                $previousState = $this->saveCachedState();
×
451
                $this->resetCachedState();
×
452

453
                if ($libreSignFile->getSignedHash()) {
×
454
                        $this->restoreCachedState($previousState);
×
455
                        return;
×
456
                }
457

458
                $previousLibreSignFile = $this->libreSignFile;
×
459
                $previousSignRequest = $this->signRequest;
×
460
                $this->libreSignFile = $libreSignFile;
×
461
                $this->signRequest = $signRequest;
×
462

463
                try {
464
                        $this->validateDocMdpAllowsSignatures();
×
465

466
                        try {
467
                                $signedFile = $this->getEngine()->sign();
×
468
                        } catch (LibresignException|Exception $e) {
×
469
                                $this->cleanupUnsignedSignedFile();
×
470
                                $this->recordSignatureAttempt($e);
×
471
                                throw $e;
×
472
                        }
473

474
                        $hash = $this->computeHash($signedFile);
×
475
                        $this->updateSignRequest($hash);
×
476
                        $this->updateLibreSignFile($libreSignFile, $signedFile->getId(), $hash);
×
477

478
                        $this->dispatchSignedEvent();
×
479

480
                        $envelopeContext = $this->getEnvelopeContext();
×
481
                        if ($envelopeContext['envelope'] instanceof FileEntity) {
×
482
                                $this->updateEnvelopeStatus(
×
483
                                        $envelopeContext['envelope'],
×
484
                                        $envelopeContext['envelopeSignRequest'] ?? null,
×
485
                                        $signRequest->getSigned()
×
486
                                );
×
487
                        }
488
                } finally {
489
                        $this->libreSignFile = $previousLibreSignFile;
×
490
                        $this->signRequest = $previousSignRequest;
×
491
                        $this->restoreCachedState($previousState);
×
492
                }
493
        }
494

495
        private function saveCachedState(): array {
496
                return [
×
497
                        'fileToSign' => $this->fileToSign,
×
498
                        'createdSignedFile' => $this->createdSignedFile,
×
499
                        'engine' => $this->engine,
×
500
                ];
×
501
        }
502

503
        private function resetCachedState(): void {
504
                $this->fileToSign = null;
×
505
                $this->createdSignedFile = null;
×
506
                $this->engine = null;
×
507
        }
508

509
        private function restoreCachedState(array $state): void {
510
                $this->fileToSign = $state['fileToSign'];
×
511
                $this->createdSignedFile = $state['createdSignedFile'];
×
512
                $this->engine = $state['engine'];
×
513
        }
514

515
        public function enqueueParallelSigningJobs(array $signRequests, array $jobArguments = []): int {
516

517
                if (empty($signRequests)) {
1✔
518
                        throw new LibresignException('No sign requests found to process');
×
519
                }
520

521
                $enqueued = 0;
1✔
522
                foreach ($signRequests as $signRequestData) {
1✔
523
                        $file = $signRequestData['file'];
1✔
524
                        $signRequest = $signRequestData['signRequest'];
1✔
525

526
                        if ($file->getSignedHash()) {
1✔
527
                                continue;
×
528
                        }
529

530
                        $nodeId = $file->getNodeId();
1✔
531
                        $userId = $file->getUserId() ?? $signRequest->getUserId();
1✔
532

533
                        if ($nodeId === null || !$this->verifyFileExists($userId, $nodeId)) {
1✔
534
                                continue;
×
535
                        }
536

537
                        $this->enqueueSigningJobForFile($signRequest, $file, $jobArguments);
1✔
538
                        $enqueued++;
1✔
539
                }
540

541
                return $enqueued;
1✔
542
        }
543

544
        private function enqueueSigningJobForFile(SignRequestEntity $signRequest, FileEntity $file, array $jobArguments): void {
545
                $args = $jobArguments;
1✔
546
                $args = $this->addCredentialsToJobArgs($args, $signRequest, $file);
1✔
547
                $args = array_merge($args, [
1✔
548
                        'fileId' => $file->getId(),
1✔
549
                        'signRequestId' => $signRequest->getId(),
1✔
550
                        'signRequestUuid' => $signRequest->getUuid(),
1✔
551
                ]);
1✔
552

553
                $this->jobList->add(SignSingleFileJob::class, $args);
1✔
554
        }
555

556
        private function addCredentialsToJobArgs(array $args, SignRequestEntity $signRequest, FileEntity $file): array {
557
                if (!($this->signWithoutPassword || !empty($this->password))) {
1✔
558
                        return $args;
×
559
                }
560

561
                $credentialsId = 'libresign_sign_' . $signRequest->getId() . '_' . $file->getId() . '_' . $this->secureRandom->generate(8, ISecureRandom::CHAR_ALPHANUMERIC);
1✔
562
                $this->credentialsManager->store(
1✔
563
                        $this->user?->getUID() ?? '',
1✔
564
                        $credentialsId,
1✔
565
                        [
1✔
566
                                'signWithoutPassword' => $this->signWithoutPassword,
1✔
567
                                'password' => $this->password,
1✔
568
                                'timestamp' => time(),
1✔
569
                                'expires' => time() + 3600,
1✔
570
                        ]
1✔
571
                );
1✔
572
                $args['credentialsId'] = $credentialsId;
1✔
573

574
                return $args;
1✔
575
        }
576

577
        /**
578
         * @return DateTimeInterface|null Last signed date
579
         */
580
        private function signSequentially(array $signRequests): ?DateTimeInterface {
581
                $envelopeLastSignedDate = null;
18✔
582
                $envelopeContext = $this->getEnvelopeContext();
18✔
583

584
                foreach ($signRequests as $index => $signRequestData) {
18✔
585
                        $this->libreSignFile = $signRequestData['file'];
18✔
586
                        if ($this->libreSignFile->getSignedHash()) {
18✔
587
                                continue;
×
588
                        }
589
                        $this->signRequest = $signRequestData['signRequest'];
18✔
590
                        $this->engine = null;
18✔
591
                        $this->setVisibleElements($this->elementsInput);
18✔
592
                        $this->fileToSign = null;
18✔
593

594
                        $this->validateDocMdpAllowsSignatures();
18✔
595

596
                        try {
597
                                $signedFile = $this->getEngine()->sign();
16✔
598
                        } catch (LibresignException|Exception $e) {
×
599
                                $this->cleanupUnsignedSignedFile();
×
600
                                $this->recordSignatureAttempt($e);
×
601

602
                                $isEnvelope = $this->libreSignFile->isEnvelope() || $this->libreSignFile->hasParent();
×
603
                                if (!$isEnvelope) {
×
604
                                        throw $e;
×
605
                                }
606
                                continue;
×
607
                        }
608

609
                        $hash = $this->computeHash($signedFile);
16✔
610
                        $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
16✔
611

612
                        $this->updateSignRequest($hash);
16✔
613
                        $this->updateLibreSignFile($this->libreSignFile, $signedFile->getId(), $hash);
16✔
614

615
                        $this->dispatchSignedEvent();
16✔
616
                }
617

618
                if ($envelopeContext['envelope'] instanceof FileEntity) {
16✔
619
                        $this->updateEnvelopeStatus(
×
620
                                $envelopeContext['envelope'],
×
621
                                $envelopeContext['envelopeSignRequest'] ?? null,
×
622
                                $envelopeLastSignedDate
×
623
                        );
×
624
                }
625

626
                return $envelopeLastSignedDate;
16✔
627
        }
628

629
        /**
630
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
631
         */
632
        private function getSignRequestsToSign(): array {
633
                if (!$this->libreSignFile->isEnvelope()
19✔
634
                        && !$this->libreSignFile->hasParent()
19✔
635
                ) {
636
                        return [[
18✔
637
                                'file' => $this->libreSignFile,
18✔
638
                                'signRequest' => $this->signRequest,
18✔
639
                        ]];
18✔
640
                }
641

642
                return $this->buildEnvelopeSignRequests();
1✔
643
        }
644

645
        /**
646
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
647
         */
648
        private function buildEnvelopeSignRequests(): array {
649
                $envelopeId = $this->libreSignFile->isEnvelope()
1✔
650
                        ? $this->libreSignFile->getId()
×
651
                        : $this->libreSignFile->getParentFileId();
1✔
652

653
                $childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
1✔
654
                if (empty($childFiles)) {
1✔
655
                        throw new LibresignException('No files found in envelope');
×
656
                }
657

658
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
1✔
659
                        $envelopeId,
1✔
660
                        $this->signRequest->getId()
1✔
661
                );
1✔
662

663
                if (empty($childSignRequests)) {
1✔
664
                        throw new LibresignException('No sign requests found for envelope files');
×
665
                }
666

667
                $signRequestsData = [];
1✔
668
                foreach ($childSignRequests as $childSignRequest) {
1✔
669
                        $childFile = $this->array_find(
1✔
670
                                $childFiles,
1✔
671
                                fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
1✔
672
                        );
1✔
673

674
                        if ($childFile) {
1✔
675
                                $signRequestsData[] = [
1✔
676
                                        'file' => $childFile,
1✔
677
                                        'signRequest' => $childSignRequest,
1✔
678
                                ];
1✔
679
                        }
680
                }
681

682
                return $signRequestsData;
1✔
683
        }
684

685
        /**
686
         * @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
687
         */
688
        private function getEnvelopeContext(): array {
689
                $result = [
18✔
690
                        'envelope' => null,
18✔
691
                        'envelopeSignRequest' => null,
18✔
692
                ];
18✔
693

694
                if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
18✔
695
                        return $result;
18✔
696
                }
697

698
                if ($this->libreSignFile->isEnvelope()) {
×
699
                        $result['envelope'] = $this->libreSignFile;
×
700
                        $result['envelopeSignRequest'] = $this->signRequest;
×
701
                        return $result;
×
702
                }
703

704
                try {
705
                        $envelopeId = $this->libreSignFile->isEnvelope()
×
706
                                ? $this->libreSignFile->getId()
×
707
                                : $this->libreSignFile->getParentFileId();
×
708
                        $result['envelope'] = $this->fileMapper->getById($envelopeId);
×
709
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
×
710
                        $result['envelopeSignRequest'] = $this->signRequestMapper->getByIdentifyMethodAndFileId(
×
711
                                $identifyMethod,
×
712
                                $result['envelope']->getId()
×
713
                        );
×
714
                } catch (DoesNotExistException $e) {
×
715
                }
716

717
                return $result;
×
718
        }
719

720
        private function updateEnvelopeStatus(
721
                FileEntity $envelope,
722
                ?SignRequestEntity $envelopeSignRequest = null,
723
                ?DateTimeInterface $signedDate = null,
724
        ): void {
725
                $childFiles = $this->fileMapper->getChildrenFiles($envelope->getId());
1✔
726
                $signRequestsMap = $this->buildSignRequestsMap($childFiles);
1✔
727

728
                $status = $this->envelopeStatusDeterminer->determineStatus($childFiles, $signRequestsMap);
1✔
729
                $envelope->setStatus($status);
1✔
730

731
                $this->handleSignedEnvelopeSignRequest($envelope, $envelopeSignRequest, $signedDate, $status);
1✔
732

733
                $this->updateEnvelopeMetadata($envelope);
1✔
734
                $this->fileMapper->update($envelope);
1✔
735
                $this->updateEntityCacheAfterDbSave($envelope);
1✔
736
        }
737

738
        private function buildSignRequestsMap(array $childFiles): array {
739
                $signRequestsMap = [];
1✔
740
                foreach ($childFiles as $childFile) {
1✔
741
                        $signRequestsMap[$childFile->getId()] = $this->signRequestMapper->getByFileId($childFile->getId());
1✔
742
                }
743
                return $signRequestsMap;
1✔
744
        }
745

746
        private function handleSignedEnvelopeSignRequest(
747
                FileEntity $envelope,
748
                ?SignRequestEntity $envelopeSignRequest,
749
                ?DateTimeInterface $signedDate,
750
                int $status,
751
        ): void {
752
                if (!($envelopeSignRequest instanceof SignRequestEntity)) {
1✔
753
                        return;
×
754
                }
755

756
                $envelopeSignRequest->setSigned($signedDate ?: new DateTime());
1✔
757
                $envelopeSignRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
1✔
758
                $this->signRequestMapper->update($envelopeSignRequest);
1✔
759
                $this->sequentialSigningService
1✔
760
                        ->setFile($envelope)
1✔
761
                        ->releaseNextOrder(
1✔
762
                                $envelopeSignRequest->getFileId(),
1✔
763
                                $envelopeSignRequest->getSigningOrder()
1✔
764
                        );
1✔
765
        }
766

767
        private function updateEnvelopeMetadata(FileEntity $envelope): void {
768
                $meta = $envelope->getMetadata() ?? [];
1✔
769
                $meta['status_changed_at'] = (new DateTime())->format(DateTimeInterface::ATOM);
1✔
770
                $envelope->setMetadata($meta);
1✔
771
        }
772

773
        /**
774
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
775
         */
776
        protected function validateDocMdpAllowsSignatures(): void {
777
                $docmdpLevel = $this->libreSignFile->getDocmdpLevelEnum();
18✔
778

779
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED) {
18✔
780
                        throw new LibresignException(
×
781
                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
×
782
                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
×
783
                        );
×
784
                }
785

786
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::NOT_CERTIFIED) {
18✔
787
                        $resource = $this->getLibreSignFileAsResource();
18✔
788

789
                        try {
790
                                if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
17✔
791
                                        throw new LibresignException(
3✔
792
                                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
3✔
793
                                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
794
                                        );
3✔
795
                                }
796
                        } finally {
797
                                fclose($resource);
17✔
798
                        }
799
                }
800
        }
801

802
        /**
803
         * @return resource
804
         * @throws LibresignException
805
         */
806
        protected function getLibreSignFileAsResource() {
807
                $files = $this->getNextcloudFiles($this->libreSignFile);
12✔
808
                if (empty($files)) {
11✔
809
                        throw new LibresignException('File not found');
×
810
                }
811
                $fileToSign = current($files);
11✔
812
                $content = $fileToSign->getContent();
11✔
813
                $resource = fopen('php://memory', 'r+');
11✔
814
                if ($resource === false) {
11✔
815
                        throw new LibresignException('Failed to create temporary resource for PDF validation');
×
816
                }
817
                fwrite($resource, $content);
11✔
818
                rewind($resource);
11✔
819
                return $resource;
11✔
820
        }
821

822
        protected function computeHash(File $file): string {
823
                return hash('sha256', $file->getContent());
2✔
824
        }
825

826
        protected function updateSignRequest(string $hash): void {
827
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
828
                $this->signRequest->setSigned($lastSignedDate);
14✔
829
                $this->signRequest->setSignedHash($hash);
14✔
830
                $this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
14✔
831

832
                $this->signRequestMapper->update($this->signRequest);
14✔
833

834
                $this->sequentialSigningService
14✔
835
                        ->setFile($this->libreSignFile)
14✔
836
                        ->releaseNextOrder(
14✔
837
                                $this->signRequest->getFileId(),
14✔
838
                                $this->signRequest->getSigningOrder()
14✔
839
                        );
14✔
840
        }
841

842
        protected function updateLibreSignFile(FileEntity $libreSignFile, int $nodeId, string $hash): void {
843
                $libreSignFile->setSignedNodeId($nodeId);
14✔
844
                $libreSignFile->setSignedHash($hash);
14✔
845
                $this->setNewStatusIfNecessary($libreSignFile);
14✔
846
                $this->fileStatusService->update($libreSignFile);
14✔
847

848
                if ($libreSignFile->hasParent()) {
14✔
849
                        $this->fileStatusService->propagateStatusToParent($libreSignFile->getParentFileId());
×
850
                }
851
        }
852

853
        protected function dispatchSignedEvent(): void {
854
                $certificateSerialNumber = null;
14✔
855
                if ($this->signWithoutPassword) {
14✔
856
                        try {
857
                                $certificateInfo = $this->getEngine()->readCertificate();
×
858
                                if (isset($certificateInfo['serialNumber']) && is_string($certificateInfo['serialNumber'])) {
×
859
                                        $certificateSerialNumber = $certificateInfo['serialNumber'];
×
860
                                } else {
861
                                        $this->logger->warning('Unable to extract certificate serial number for event payload');
×
862
                                }
863
                        } catch (\Throwable $e) {
×
864
                                $this->logger->error('Failed to get certificate info for event', [
×
865
                                        'exception' => $e,
×
866
                                        'signRequestId' => $this->signRequest->getId()
×
867
                                ]);
×
868
                        }
869
                }
870

871
                $event = $this->signedEventFactory->make(
14✔
872
                        $this->signRequest,
14✔
873
                        $this->libreSignFile,
14✔
874
                        $this->getEngine()->getInputFile(),
14✔
875
                        $this->signWithoutPassword,
14✔
876
                        $certificateSerialNumber,
14✔
877
                );
14✔
878
                $this->eventDispatcher->dispatchTyped($event);
14✔
879
        }
880

881
        protected function identifyEngine(File $file): SignEngineHandler {
882
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
883
        }
884

885
        protected function getSignatureParams(): array {
886
                $certificateData = $this->readCertificate();
15✔
887
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
888
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
889
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
890
                return $signatureParams;
15✔
891
        }
892

893
        private function buildBaseSignatureParams(array $certificateData): array {
894
                return [
15✔
895
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
896
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
897
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
898
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
899
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
900
                                ->format(DateTimeInterface::ATOM)
15✔
901
                ];
15✔
902
        }
903

904
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
905
                if (isset($certificateData['extensions']['subjectAltName'])) {
15✔
906
                        preg_match('/(?:email:)+(?<email>[^\s,]+)/', $certificateData['extensions']['subjectAltName'], $matches);
6✔
907
                        if ($matches && filter_var($matches['email'], FILTER_VALIDATE_EMAIL)) {
6✔
908
                                $signatureParams['SignerEmail'] = $matches['email'];
4✔
909
                        } elseif (filter_var($certificateData['extensions']['subjectAltName'], FILTER_VALIDATE_EMAIL)) {
2✔
910
                                $signatureParams['SignerEmail'] = $certificateData['extensions']['subjectAltName'];
1✔
911
                        }
912
                }
913
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
914
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
1✔
915
                }
916
                if (empty($signatureParams['SignerEmail']) && $this->signRequest instanceof SignRequestEntity) {
15✔
917
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
918
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
919
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
920
                        }
921
                }
922
                return $signatureParams;
15✔
923
        }
924

925
        private function addMetadataToSignatureParams(array $signatureParams): array {
926
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
927
                if (isset($signRequestMetadata['remote-address'])) {
15✔
928
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
929
                }
930
                if (isset($signRequestMetadata['user-agent'])) {
15✔
931
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
932
                }
933
                return $signatureParams;
15✔
934
        }
935

936
        public function storeUserMetadata(array $metadata = []): self {
937
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
938
                if (!$collectMetadata || !$metadata) {
18✔
939
                        return $this;
7✔
940
                }
941
                $this->signRequest->setMetadata(array_merge(
11✔
942
                        $this->signRequest->getMetadata() ?? [],
11✔
943
                        $metadata,
11✔
944
                ));
11✔
945
                $this->signRequestMapper->update($this->signRequest);
11✔
946
                return $this;
11✔
947
        }
948

949
        /**
950
         * @return SignRequestEntity[]
951
         */
952
        protected function getSigners(): array {
953
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
954
        }
955

956
        protected function setNewStatusIfNecessary(FileEntity $libreSignFile): bool {
957
                $newStatus = $this->evaluateStatusFromSigners();
10✔
958

959
                if ($newStatus === null || $newStatus === $libreSignFile->getStatus()) {
10✔
960
                        return false;
4✔
961
                }
962

963
                $libreSignFile->setStatus($newStatus);
6✔
964

965
                return true;
6✔
966
        }
967

968
        private function updateEntityCacheAfterDbSave(FileEntity $file): void {
969
                $this->statusService->cacheFileStatus($file);
1✔
970
        }
971

972
        private function evaluateStatusFromSigners(): ?int {
973
                $signers = $this->getSigners();
10✔
974

975
                $total = count($signers);
10✔
976

977
                if ($total === 0) {
10✔
978
                        return null;
1✔
979
                }
980

981
                $totalSigned = count(array_filter($signers, fn ($s) => $s->getSigned() !== null));
9✔
982

983
                if ($totalSigned === $total) {
9✔
984
                        return FileStatus::SIGNED->value;
5✔
985
                }
986

987
                if ($totalSigned > 0) {
4✔
988
                        return FileStatus::PARTIAL_SIGNED->value;
3✔
989
                }
990

991
                return null;
1✔
992
        }
993

994
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
995
                $result = $this->pfxProvider->getOrGeneratePfx(
13✔
996
                        $engine,
13✔
997
                        $this->signWithoutPassword,
13✔
998
                        $this->signatureMethodName,
13✔
999
                        $this->userUniqueIdentifier,
13✔
1000
                        $this->friendlyName,
13✔
1001
                        $this->password,
13✔
1002
                );
13✔
1003
                if ($result['password'] !== null) {
13✔
1004
                        $this->setPassword($result['password']);
2✔
1005
                }
1006
                return $result['pfx'];
13✔
1007
        }
1008

1009
        protected function readCertificate(): array {
1010
                return $this->getEngine()
×
1011
                        ->readCertificate();
×
1012
        }
1013

1014
        /**
1015
         * Get file to sign
1016
         *
1017
         * @throws LibresignException
1018
         */
1019
        protected function getFileToSign(): File {
1020
                if ($this->fileToSign instanceof File) {
×
1021
                        return $this->fileToSign;
×
1022
                }
1023

1024
                $userId = $this->libreSignFile->getUserId()
×
1025
                        ?? $this->user?->getUID()
×
1026
                        ?? ($this->signRequest?->getUserId() ?? null);
×
1027
                $nodeId = $this->libreSignFile->getNodeId();
×
1028

1029
                if ($userId === null) {
×
1030
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1031
                }
1032

1033
                try {
1034
                        $originalFile = $this->getNodeByIdUsingUid($userId, $nodeId);
×
1035
                } catch (\Throwable $e) {
×
1036
                        $this->logger->error('[file-access] FAILED to find file - userId={userId} nodeId={nodeId} error={error}', [
×
1037
                                'userId' => $userId,
×
1038
                                'nodeId' => $nodeId,
×
1039
                                'error' => $e->getMessage(),
×
1040
                        ]);
×
1041
                        throw $e;
×
1042
                }
1043

1044
                if ($originalFile->getOwner()->getUID() !== $userId) {
×
1045
                        $originalFile = $this->getNodeByIdUsingUid($originalFile->getOwner()->getUID(), $nodeId);
×
1046
                }
1047
                if ($this->isPdf($originalFile)) {
×
1048
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
1049
                } else {
1050
                        $this->fileToSign = $originalFile;
×
1051
                }
1052
                return $this->fileToSign;
×
1053
        }
1054

1055
        private function isPdf(File $file): bool {
1056
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
1057
        }
1058

1059
        protected function getEngine(): SignEngineHandler {
1060
                if (!$this->engine) {
12✔
1061
                        $originalFile = $this->getFileToSign();
12✔
1062
                        $this->engine = $this->identifyEngine($originalFile);
12✔
1063

1064
                        $this->configureEngine();
12✔
1065
                }
1066
                return $this->engine;
12✔
1067
        }
1068

1069
        private function configureEngine(): void {
1070
                $this->engine
12✔
1071
                        ->setInputFile($this->getFileToSign())
12✔
1072
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
1073
                        ->setPassword($this->password);
12✔
1074

1075
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
1076
                        $this->engine
2✔
1077
                                ->setVisibleElements($this->getVisibleElements())
2✔
1078
                                ->setSignatureParams($this->getSignatureParams());
2✔
1079
                }
1080
        }
1081

1082
        public function getLibresignFile(?int $fileId, ?string $signRequestUuid = null): FileEntity {
1083
                try {
1084
                        if ($fileId) {
3✔
1085
                                return $this->fileMapper->getById($fileId);
1✔
1086
                        }
1087

1088
                        if ($signRequestUuid) {
2✔
1089
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
1090
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
1091
                        }
1092

1093
                        throw new \Exception('Invalid arguments');
×
1094

1095
                } catch (DoesNotExistException) {
1✔
1096
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
1097
                }
1098
        }
1099

1100
        public function renew(SignRequestEntity $signRequest, string $method): void {
1101
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1102
                if (empty($identifyMethods[$method])) {
×
1103
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1104
                }
1105

1106
                $signRequest->setUuid(UUIDUtil::getUUID());
×
1107
                $this->signRequestMapper->update($signRequest);
×
1108

1109
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
1110
                        $entity = $identifyMethod->getEntity();
×
1111
                        $entity->setAttempts($entity->getAttempts() + 1);
×
1112
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
1113
                        $identifyMethod->save();
×
1114
                }, $identifyMethods[$method]);
×
1115
        }
1116

1117
        public function requestCode(
1118
                SignRequestEntity $signRequest,
1119
                string $identifyMethodName,
1120
                string $signMethodName,
1121
                string $identify = '',
1122
        ): void {
1123
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1124
                if (empty($identifyMethods[$identifyMethodName])) {
×
1125
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1126
                }
1127
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
1128
                        try {
1129
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
1130
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
1131
                        } catch (InvalidArgumentException) {
×
1132
                                continue;
×
1133
                        }
1134
                        /** @var IToken $signatureMethod */
1135
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
1136
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
1137
                        return;
×
1138
                }
1139
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
1140
        }
1141

1142
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
1143
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
1144
                try {
1145
                        if ($libresignFile->isEnvelope()) {
2✔
1146
                                $childFiles = $this->fileMapper->getChildrenFiles($libresignFile->getId());
×
1147
                                $allSignRequests = [];
×
1148
                                foreach ($childFiles as $childFile) {
×
1149
                                        $childSignRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
1150
                                        $allSignRequests = array_merge($allSignRequests, $childSignRequests);
×
1151
                                }
1152
                                $signRequests = $allSignRequests;
×
1153
                        } else {
1154
                                $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
1155
                        }
1156

1157
                        if (!empty($signRequestUuid)) {
2✔
1158
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
1159
                        } else {
1160
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
1161
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1162
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
1163
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
1164
                                                        && $user
1165
                                                        && (
1166
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
1167
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
1168
                                                        )
1169
                                                ) {
1170
                                                        return true;
×
1171
                                                }
1172
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
1173
                                                        && $user
1174
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
1175
                                                ) {
1176
                                                        return true;
×
1177
                                                }
1178
                                                return false;
×
1179
                                        });
×
1180
                                        if (count($found) > 0) {
×
1181
                                                return $signRequest;
×
1182
                                        }
1183
                                        return $carry;
×
1184
                                });
×
1185
                        }
1186

1187
                        if (!$signRequest) {
2✔
1188
                                throw new DoesNotExistException('Sign request not found');
×
1189
                        }
1190
                        $signRequestFile = $libresignFile;
2✔
1191
                        if ($signRequestFile->getId() !== $signRequest->getFileId()) {
2✔
NEW
1192
                                $signRequestFile = $this->fileMapper->getById($signRequest->getFileId());
×
1193
                        }
1194
                        $this->sequentialSigningService->setFile($signRequestFile);
2✔
1195
                        if (
1196
                                $this->sequentialSigningService->isOrderedNumericFlow()
2✔
1197
                                && $this->sequentialSigningService->hasPendingLowerOrderSigners(
2✔
1198
                                        $signRequest->getFileId(),
2✔
1199
                                        $signRequest->getSigningOrder()
2✔
1200
                                )
2✔
1201
                        ) {
NEW
1202
                                throw new LibresignException(json_encode([
×
NEW
1203
                                        'action' => JSActions::ACTION_DO_NOTHING,
×
NEW
1204
                                        'errors' => [['message' => $this->l10n->t('You are not allowed to sign this document yet')]],
×
NEW
1205
                                ]));
×
1206
                        }
1207
                        if ($signRequest->getSigned()) {
2✔
1208
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
1209
                        }
1210
                        return $signRequest;
2✔
1211
                } catch (DoesNotExistException) {
×
1212
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1213
                }
1214
        }
1215

1216
        protected function getPdfToSign(File $originalFile): File {
1217
                $file = $this->getSignedFile();
×
1218
                if ($file instanceof File) {
×
1219
                        return $file;
×
1220
                }
1221

1222
                $originalContent = $originalFile->getContent();
×
1223

1224
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
1225
                        return $this->createSignedFile($originalFile, $originalContent);
×
1226
                }
1227
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
1228
                $footer = $this->footerHandler
×
1229
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
1230
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
1231
                                'displayName' => $signer->getDisplayName(),
×
1232
                                'signed' => $signer->getSigned()
×
1233
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
1234
                                        : null,
1235
                        ], $this->getSigners()))
×
1236
                        ->getFooter($metadata['d']);
×
1237
                if ($footer) {
×
1238
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
1239
                        file_put_contents($stamp, $footer);
×
1240

1241
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
1242
                        file_put_contents($input, $originalContent);
×
1243

1244
                        try {
1245
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
1246
                        } catch (RuntimeException $e) {
×
1247
                                throw new LibresignException($e->getMessage());
×
1248
                        }
1249
                } else {
1250
                        $pdfContent = $originalContent;
×
1251
                }
1252
                return $this->createSignedFile($originalFile, $pdfContent);
×
1253
        }
1254

1255
        protected function getSignedFile(): ?File {
1256
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
1257
                if (!$nodeId) {
3✔
1258
                        return null;
1✔
1259
                }
1260

1261
                $fileToSign = $this->getNodeByIdUsingUid($this->libreSignFile->getUserId(), $nodeId);
2✔
1262

1263
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
1264
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
1265
                }
1266
                return $fileToSign;
2✔
1267
        }
1268

1269
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
1270
                try {
1271
                        $userFolder = $this->root->getUserFolder($uid);
4✔
1272
                } catch (NoUserException $e) {
2✔
1273
                        $this->logger->error('[file-access] NoUserException for uid={uid}', ['uid' => $uid]);
1✔
1274
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
1275
                } catch (NotPermittedException $e) {
1✔
1276
                        $this->logger->error('[file-access] NotPermittedException for uid={uid}', ['uid' => $uid]);
1✔
1277
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
1278
                }
1279

1280
                try {
1281
                        $fileToSign = $userFolder->getFirstNodeById($nodeId);
2✔
1282
                } catch (\Throwable $e) {
×
1283
                        $this->logger->error('[file-access] Failed getFirstNodeById - nodeId={nodeId} error={error}', [
×
1284
                                'nodeId' => $nodeId,
×
1285
                                'error' => $e->getMessage(),
×
1286
                        ]);
×
1287
                        throw $e;
×
1288
                }
1289

1290
                if (!$fileToSign instanceof File) {
2✔
1291
                        $this->logger->error('[file-access] Node is not a File - nodeId={nodeId} type={type}', [
1✔
1292
                                'nodeId' => $nodeId,
1✔
1293
                                'type' => $fileToSign ? get_class($fileToSign) : 'NULL',
1✔
1294
                        ]);
1✔
1295
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
1296
                }
1297
                return $fileToSign;
1✔
1298
        }
1299

1300
        /**
1301
         * Verify if file exists in filesystem before enqueuing background job
1302
         *
1303
         * @param string|null $uid User ID
1304
         * @param int $nodeId File node ID
1305
         * @return bool True if file exists and is accessible
1306
         */
1307
        private function verifyFileExists(?string $uid, int $nodeId): bool {
1308
                if ($uid === null || $nodeId === 0) {
1✔
1309
                        return false;
×
1310
                }
1311

1312
                try {
1313
                        $userFolder = $this->root->getUserFolder($uid);
1✔
1314
                        $node = $userFolder->getFirstNodeById($nodeId);
1✔
1315
                        return $node instanceof File;
1✔
1316
                } catch (\Throwable $e) {
×
1317
                        $this->logger->warning('[verify-file] File not accessible - nodeId={nodeId} uid={uid} error={error}', [
×
1318
                                'nodeId' => $nodeId,
×
1319
                                'uid' => $uid,
×
1320
                                'error' => $e->getMessage(),
×
1321
                        ]);
×
1322
                        return false;
×
1323
                }
1324
        }
1325

1326
        private function cleanupUnsignedSignedFile(): void {
1327
                if (!$this->createdSignedFile instanceof File) {
×
1328
                        return;
×
1329
                }
1330

1331
                try {
1332
                        $this->createdSignedFile->delete();
×
1333
                } catch (\Throwable $e) {
×
1334
                        $this->logger->warning('Failed to delete temporary signed file: ' . $e->getMessage());
×
1335
                } finally {
1336
                        $this->createdSignedFile = null;
×
1337
                }
1338
        }
1339

1340
        private function createSignedFile(File $originalFile, string $content): File {
1341
                $filename = preg_replace(
×
1342
                        '/' . $originalFile->getExtension() . '$/',
×
1343
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
1344
                        basename($originalFile->getPath())
×
1345
                );
×
1346
                $owner = $originalFile->getOwner()->getUID();
×
1347

1348
                $fileId = $this->libreSignFile->getId();
×
1349
                $extension = $originalFile->getExtension();
×
1350
                $uniqueFilename = substr($filename, 0, -strlen($extension) - 1) . '_' . $fileId . '.' . $extension;
×
1351

1352
                try {
1353
                        /** @var \OCP\Files\Folder */
1354
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
1355

1356
                        $this->createdSignedFile = $parentFolder->newFile($uniqueFilename, $content);
×
1357

1358
                        return $this->createdSignedFile;
×
1359
                } catch (NotPermittedException) {
×
1360
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
1361
                } catch (\Exception $e) {
×
1362
                        throw $e;
×
1363
                }
1364
        }
1365

1366
        /**
1367
         * @throws DoesNotExistException
1368
         */
1369
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1370
                $this->validateHelper->validateUuidFormat($uuid);
4✔
1371
                return $this->signRequestMapper->getByUuid($uuid);
3✔
1372
        }
1373

1374
        /**
1375
         * @throws DoesNotExistException
1376
         */
1377
        public function getFile(int $signRequestId): FileEntity {
1378
                return $this->fileMapper->getById($signRequestId);
×
1379
        }
1380

1381
        /**
1382
         * @throws DoesNotExistException
1383
         */
1384
        public function getFileByUuid(string $uuid): FileEntity {
1385
                return $this->fileMapper->getByUuid($uuid);
×
1386
        }
1387

1388
        public function getIdDocById(int $fileId): IdDocs {
1389
                return $this->idDocsMapper->getByFileId($fileId);
×
1390
        }
1391

1392
        /**
1393
         * @return File[] Array of files
1394
         */
1395
        public function getNextcloudFiles(FileEntity $fileData): array {
1396
                if ($fileData->getNodeType() === 'envelope') {
1✔
1397
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1398
                        $files = [];
×
1399
                        foreach ($children as $child) {
×
1400
                                $nodeId = $child->getNodeId();
×
1401
                                if ($nodeId === null) {
×
1402
                                        throw new LibresignException(json_encode([
×
1403
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1404
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1405
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1406
                                }
1407
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1408
                                if ($file instanceof File) {
×
1409
                                        $files[] = $file;
×
1410
                                }
1411
                        }
1412
                        return $files;
×
1413
                }
1414

1415
                $nodeId = $fileData->getNodeId();
1✔
1416
                if ($nodeId === null) {
1✔
1417
                        throw new LibresignException(json_encode([
1✔
1418
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1419
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1420
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1421
                }
1422
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1423
                if (!$fileToSign instanceof File) {
×
1424
                        throw new LibresignException(json_encode([
×
1425
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1426
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1427
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1428
                }
1429
                return [$fileToSign];
×
1430
        }
1431

1432
        /**
1433
         * @return array<FileEntity>
1434
         */
1435
        public function getNextcloudFilesWithEntities(FileEntity $fileData): array {
1436
                if ($fileData->getNodeType() === 'envelope') {
×
1437
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1438
                        $result = [];
×
1439
                        foreach ($children as $child) {
×
1440
                                $nodeId = $child->getNodeId();
×
1441
                                if ($nodeId === null) {
×
1442
                                        throw new LibresignException(json_encode([
×
1443
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1444
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1445
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1446
                                }
1447
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1448
                                if ($file instanceof File) {
×
1449
                                        $result[] = $child;
×
1450
                                }
1451
                        }
1452
                        return $result;
×
1453
                }
1454

1455
                $nodeId = $fileData->getNodeId();
×
1456
                if ($nodeId === null) {
×
1457
                        throw new LibresignException(json_encode([
×
1458
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1459
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1460
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1461
                }
1462
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1463
                if (!$fileToSign instanceof File) {
×
1464
                        throw new LibresignException(json_encode([
×
1465
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1466
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1467
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1468
                }
1469
                return [$fileData];
×
1470
        }
1471

1472
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1473
                $this->validateHelper->validateSigner($uuid, $user);
×
1474
        }
1475

1476
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1477
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1478
        }
1479

1480
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1481
                $return = ['user' => ['name' => null]];
×
1482
                if ($signRequest) {
×
1483
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1484
                } elseif ($user) {
×
1485
                        $return['user']['name'] = $user->getDisplayName();
×
1486
                }
1487
                return $return;
×
1488
        }
1489

1490
        public function getAvailableIdentifyMethodsFromSettings(): array {
1491
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1492
                $return = array_map(fn (array $identifyMethod): array => [
×
1493
                        'mandatory' => $identifyMethod['mandatory'],
×
1494
                        'identifiedAtDate' => null,
×
1495
                        'validateCode' => false,
×
1496
                        'method' => $identifyMethod['name'],
×
1497
                ], $identifyMethods);
×
1498
                return $return;
×
1499
        }
1500

1501
        public function getFileUrl(int $fileId, string $uuid): string {
1502
                try {
1503
                        $this->idDocsMapper->getByFileId($fileId);
×
1504
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1505
                } catch (DoesNotExistException) {
×
1506
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1507
                }
1508
        }
1509

1510
        /**
1511
         * Get PDF URLs for signing
1512
         * For envelopes: returns URLs for all child files
1513
         * For regular files: returns URL for the file itself
1514
         *
1515
         * @return string[]
1516
         */
1517
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1518
                if (!$fileEntity->isEnvelope()) {
×
1519
                        return [
×
1520
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1521
                        ];
×
1522
                }
1523

1524
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1525
                        $fileEntity->getId(),
×
1526
                        $signRequestEntity->getId()
×
1527
                );
×
1528

1529
                $pdfUrls = [];
×
1530
                foreach ($childSignRequests as $childSignRequest) {
×
1531
                        $pdfUrls[] = $this->getFileUrl(
×
1532
                                $childSignRequest->getFileId(),
×
1533
                                $childSignRequest->getUuid()
×
1534
                        );
×
1535
                }
1536

1537
                return $pdfUrls;
×
1538
        }
1539

1540
        private function recordSignatureAttempt(Exception $exception): void {
1541
                if (!$this->libreSignFile) {
×
1542
                        return;
×
1543
                }
1544

1545
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1546

1547
                if (!isset($metadata['signature_attempts'])) {
×
1548
                        $metadata['signature_attempts'] = [];
×
1549
                }
1550

1551
                $attempt = [
×
1552
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1553
                        'engine' => $this->engine ? get_class($this->engine) : 'unknown',
×
1554
                        'error_message' => $exception->getMessage(),
×
1555
                        'error_code' => $exception->getCode(),
×
1556
                ];
×
1557

1558
                $metadata['signature_attempts'][] = $attempt;
×
1559
                $this->libreSignFile->setMetadata($metadata);
×
1560
                $this->fileMapper->update($this->libreSignFile);
×
1561
        }
1562
}
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