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

LibreSign / libresign / 22082781483

17 Feb 2026 01:28AM UTC coverage: 52.311%. First build
22082781483

Pull #6912

github

web-flow
Merge cfefd6887 into d076967de
Pull Request #6912: feat: signers contract normalization

34 of 43 new or added lines in 4 files covered. (79.07%)

9271 of 17723 relevant lines covered (52.31%)

6.23 hits per line

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

63.28
/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\IdentifyMethodMapper;
27
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
28
use OCA\Libresign\Db\SignRequestMapper;
29
use OCA\Libresign\Db\UserElementMapper;
30
use OCA\Libresign\Enum\FileStatus;
31
use OCA\Libresign\Events\SignedEventFactory;
32
use OCA\Libresign\Exception\LibresignException;
33
use OCA\Libresign\Handler\DocMdpHandler;
34
use OCA\Libresign\Handler\FooterHandler;
35
use OCA\Libresign\Handler\PdfTk\Pdf;
36
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
37
use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
38
use OCA\Libresign\Handler\SignEngine\SignEngineHandler;
39
use OCA\Libresign\Helper\JSActions;
40
use OCA\Libresign\Helper\ValidateHelper;
41
use OCA\Libresign\Service\Envelope\EnvelopeStatusDeterminer;
42
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
43
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
44
use OCA\Libresign\Service\SignRequest\SignRequestService;
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 array<int, VisibleElementAssoc> indexed by fileElementId */
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

84
        public function __construct(
85
                protected IL10N $l10n,
86
                private FileMapper $fileMapper,
87
                private SignRequestMapper $signRequestMapper,
88
                private IdDocsMapper $idDocsMapper,
89
                private FooterHandler $footerHandler,
90
                protected FolderService $folderService,
91
                private IClientService $client,
92
                protected LoggerInterface $logger,
93
                private IAppConfig $appConfig,
94
                protected ValidateHelper $validateHelper,
95
                private SignerElementsService $signerElementsService,
96
                private IRootFolder $root,
97
                private IUserSession $userSession,
98
                private IDateTimeZone $dateTimeZone,
99
                private FileElementMapper $fileElementMapper,
100
                private UserElementMapper $userElementMapper,
101
                private IEventDispatcher $eventDispatcher,
102
                protected ISecureRandom $secureRandom,
103
                private IURLGenerator $urlGenerator,
104
                private IdentifyMethodMapper $identifyMethodMapper,
105
                private ITempManager $tempManager,
106
                private SigningCoordinatorService $signingCoordinatorService,
107
                private IdentifyMethodService $identifyMethodService,
108
                private ITimeFactory $timeFactory,
109
                protected SignEngineFactory $signEngineFactory,
110
                private SignedEventFactory $signedEventFactory,
111
                private Pdf $pdf,
112
                private DocMdpHandler $docMdpHandler,
113
                private PdfSignatureDetectionService $pdfSignatureDetectionService,
114
                private SequentialSigningService $sequentialSigningService,
115
                private FileStatusService $fileStatusService,
116
                private StatusService $statusService,
117
                private IJobList $jobList,
118
                private ICredentialsManager $credentialsManager,
119
                private EnvelopeStatusDeterminer $envelopeStatusDeterminer,
120
                private TsaValidationService $tsaValidationService,
121
                private PfxProvider $pfxProvider,
122
                private SubjectAlternativeNameService $subjectAlternativeNameService,
123
                private SignRequestService $signRequestService,
124
        ) {
125
        }
192✔
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['signers'], function ($signer) use ($signatures): void {
1✔
143
                        $exists = array_filter($signatures, function (SignRequestEntity $signRequest) use ($signer) {
1✔
144
                                $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($signRequest->getId());
1✔
145
                                if ($identifyMethod->getName() === 'email') {
1✔
NEW
146
                                        return $identifyMethod->getEntity()->getIdentifierValue() === $signer['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', $signer['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;
57✔
189
                return $this;
57✔
190
        }
191

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

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

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

210
        /**
211
         * @return static
212
         */
213
        public function setSignWithoutPassword(bool $signWithoutPassword = true): self {
214
                $this->signWithoutPassword = $signWithoutPassword;
8✔
215
                return $this;
8✔
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;
36✔
263
                if (!$this->signRequest instanceof SignRequestEntity) {
36✔
264
                        return $this;
×
265
                }
266
                $fileId = $this->signRequest->getFileId();
36✔
267
                $signRequestId = $this->signRequest->getId();
36✔
268

269
                if (empty($list) && ($fileId === null || $signRequestId === null)) {
36✔
270
                        return $this;
20✔
271
                }
272

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

277
                $fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
13✔
278
                $canCreateSignature = $this->signerElementsService->canCreateSignature();
13✔
279
                $newElements = [];
13✔
280

281
                foreach ($fileElements as $fileElement) {
13✔
282
                        $fileElementId = $fileElement->getId();
11✔
283
                        if (!$canCreateSignature) {
11✔
284
                                $newElements[$fileElementId] = new VisibleElementAssoc($fileElement);
1✔
285
                                continue;
1✔
286
                        }
287
                        $element = $this->array_find($list, fn (array $element): bool => ($element['documentElementId'] ?? '') === $fileElementId);
10✔
288
                        if (!$element) {
10✔
289
                                continue;
×
290
                        }
291
                        $nodeId = $this->getNodeId($element, $fileElement);
10✔
292

293
                        $existing = $this->elements[$fileElementId] ?? null;
8✔
294
                        if ($existing instanceof VisibleElementAssoc && $this->isTempFileValid($existing)) {
8✔
295
                                $newElements[$fileElementId] = $existing;
×
296
                                continue;
×
297
                        }
298

299
                        $newElements[$fileElementId] = $this->bindFileElementWithTempFile($fileElement, $nodeId);
8✔
300
                }
301

302
                $this->elements = $newElements;
6✔
303

304
                return $this;
6✔
305
        }
306

307
        private function isTempFileValid(VisibleElementAssoc $elementAssoc): bool {
308
                $tempFile = $elementAssoc->getTempFile();
×
309
                return $tempFile !== '' && is_file($tempFile);
×
310
        }
311

312
        private function getNodeId(?array $element, FileElement $fileElement): int {
313
                if ($this->isValidElement($element)) {
10✔
314
                        return (int)$element['profileNodeId'];
8✔
315
                }
316

317
                return $this->retrieveUserElement($fileElement);
×
318
        }
319

320
        private function isValidElement(?array $element): bool {
321
                if (is_array($element) && !empty($element['profileNodeId']) && is_int($element['profileNodeId'])) {
10✔
322
                        return true;
8✔
323
                }
324
                $this->logger->error('Invalid data provided for signing file.', ['element' => $element]);
2✔
325
                throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
2✔
326
        }
327

328
        private function retrieveUserElement(FileElement $fileElement): int {
329
                try {
330
                        if (!$this->user instanceof IUser) {
×
331
                                throw new Exception('User not set');
×
332
                        }
333
                        $userElement = $this->userElementMapper->findOne([
×
334
                                'user_id' => $this->user->getUID(),
×
335
                                'type' => $fileElement->getType(),
×
336
                        ]);
×
337
                } catch (MultipleObjectsReturnedException|DoesNotExistException|Exception) {
×
338
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
×
339
                }
340
                return $userElement->getNodeId();
×
341
        }
342

343
        private function bindFileElementWithTempFile(FileElement $fileElement, int $nodeId): VisibleElementAssoc {
344
                try {
345
                        $node = $this->getNode($nodeId);
8✔
346
                        if (!$node) {
8✔
347
                                throw new \Exception('Node content is empty or unavailable.');
8✔
348
                        }
349
                } catch (\Throwable) {
4✔
350
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
4✔
351
                }
352

353
                $tempFile = $this->tempManager->getTemporaryFile('_' . $nodeId . '.png');
4✔
354
                $content = $node->getContent();
4✔
355
                if (empty($content)) {
4✔
356
                        $this->logger->error('Failed to retrieve content for node.', ['nodeId' => $nodeId, 'fileElement' => $fileElement]);
1✔
357
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
1✔
358
                }
359
                file_put_contents($tempFile, $content);
3✔
360
                return new VisibleElementAssoc($fileElement, $tempFile);
3✔
361
        }
362

363
        private function getNode(int $nodeId): ?File {
364
                try {
365
                        return $this->folderService->getFileByNodeId($nodeId);
8✔
366
                } catch (\Throwable) {
4✔
367
                        $filesOfElementes = $this->signerElementsService->getElementsFromSession();
4✔
368
                        return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
4✔
369
                }
370
        }
371

372
        /**
373
         * Fallback to PHP < 8.4
374
         *
375
         * Reference: https://www.php.net/manual/en/function.array-find.php#130257
376
         *
377
         * @todo remove this after minor PHP version is >= 8.4
378
         * @deprecated This method will be removed once the minimum PHP version is >= 8.4. Use native array_find instead.
379
         */
380
        private function array_find(array $array, callable $callback): mixed {
381
                foreach ($array as $key => $value) {
12✔
382
                        if ($callback($value, $key)) {
12✔
383
                                return $value;
12✔
384
                        }
385
                }
386

387
                return null;
4✔
388
        }
389

390
        public function getVisibleElements(): array {
391
                return $this->elements;
6✔
392
        }
393

394
        public function getJobArgumentsWithoutCredentials(): array {
395
                $args = [];
2✔
396

397
                if (!empty($this->userUniqueIdentifier)) {
2✔
398
                        $args['userUniqueIdentifier'] = $this->userUniqueIdentifier;
2✔
399
                }
400

401
                if (!empty($this->friendlyName)) {
2✔
402
                        $args['friendlyName'] = $this->friendlyName;
2✔
403
                }
404

405
                if (!empty($this->elements)) {
2✔
406
                        $args['visibleElements'] = $this->elements;
1✔
407
                }
408

409
                if ($this->signRequest instanceof SignRequestEntity && $this->signRequest->getMetadata()) {
2✔
410
                        $args['metadata'] = $this->signRequest->getMetadata();
2✔
411
                }
412

413
                if ($this->user instanceof IUser) {
2✔
414
                        $args['userId'] = $this->user->getUID();
2✔
415
                }
416

417
                return $args;
2✔
418
        }
419

420
        public function validateSigningRequirements(): void {
421
                $this->tsaValidationService->validateConfiguration();
1✔
422
        }
423

424
        public function sign(): void {
425
                $signRequests = $this->getSignRequestsToSign();
18✔
426

427
                if (empty($signRequests)) {
18✔
428
                        throw new LibresignException('No sign requests found to process');
×
429
                }
430

431
                $this->executeSigningStrategy($signRequests);
18✔
432
        }
433

434
        private function executeSigningStrategy(array $signRequests): ?DateTimeInterface {
435
                if ($this->signingCoordinatorService->shouldUseParallelProcessing(count($signRequests))) {
18✔
436
                        return $this->processParallelSigning($signRequests);
×
437
                }
438
                return $this->signSequentially($signRequests);
18✔
439
        }
440

441
        private function processParallelSigning(array $signRequests): ?DateTimeInterface {
442
                $this->enqueueParallelSigningJobs($signRequests, $this->getJobArgumentsWithoutCredentials());
×
443
                return $this->getLatestSignedDate($signRequests);
×
444
        }
445

446
        private function getLatestSignedDate(array $signRequests): ?DateTimeInterface {
447
                $latestSignedDate = null;
×
448

449
                foreach ($signRequests as $signRequestData) {
×
450
                        try {
451
                                $signRequest = $this->signRequestMapper->getById($signRequestData['signRequest']->getId());
×
452
                                if ($signRequest->getSigned()) {
×
453
                                        $latestSignedDate = $signRequest->getSigned();
×
454
                                }
455
                        } catch (DoesNotExistException) {
×
456
                        }
457
                }
458

459
                return $latestSignedDate;
×
460
        }
461

462
        public function signSingleFile(FileEntity $libreSignFile, SignRequestEntity $signRequest): void {
463
                $previousState = $this->saveCachedState();
×
464
                $this->resetCachedState();
×
465

466
                if ($libreSignFile->getSignedHash()) {
×
467
                        $this->restoreCachedState($previousState);
×
468
                        return;
×
469
                }
470

471
                $previousLibreSignFile = $this->libreSignFile;
×
472
                $previousSignRequest = $this->signRequest;
×
473
                $this->libreSignFile = $libreSignFile;
×
474
                $this->signRequest = $signRequest;
×
475
                $this->setVisibleElements($this->elementsInput);
×
476

477
                try {
478
                        $this->validateDocMdpAllowsSignatures();
×
479

480
                        try {
481
                                $signedFile = $this->getEngine()->sign();
×
482
                        } catch (LibresignException|Exception $e) {
×
483
                                $this->cleanupUnsignedSignedFile();
×
484
                                $this->recordSignatureAttempt($e);
×
485
                                throw $e;
×
486
                        }
487

488
                        $hash = $this->computeHash($signedFile);
×
489
                        $this->updateSignRequest($hash);
×
490
                        $this->updateLibreSignFile($libreSignFile, $signedFile->getId(), $hash);
×
491

492
                        $this->dispatchSignedEvent();
×
493

494
                        $envelopeContext = $this->getEnvelopeContext();
×
495
                        if ($envelopeContext['envelope'] instanceof FileEntity) {
×
496
                                $this->updateEnvelopeStatus(
×
497
                                        $envelopeContext['envelope'],
×
498
                                        $envelopeContext['envelopeSignRequest'] ?? null,
×
499
                                        $signRequest->getSigned()
×
500
                                );
×
501
                        }
502
                } finally {
503
                        $this->libreSignFile = $previousLibreSignFile;
×
504
                        $this->signRequest = $previousSignRequest;
×
505
                        $this->restoreCachedState($previousState);
×
506
                }
507
        }
508

509
        private function saveCachedState(): array {
510
                return [
×
511
                        'fileToSign' => $this->fileToSign,
×
512
                        'createdSignedFile' => $this->createdSignedFile,
×
513
                        'engine' => $this->engine,
×
514
                ];
×
515
        }
516

517
        private function resetCachedState(): void {
518
                $this->fileToSign = null;
×
519
                $this->createdSignedFile = null;
×
520
                $this->engine = null;
×
521
        }
522

523
        private function restoreCachedState(array $state): void {
524
                $this->fileToSign = $state['fileToSign'];
×
525
                $this->createdSignedFile = $state['createdSignedFile'];
×
526
                $this->engine = $state['engine'];
×
527
        }
528

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

531
                if (empty($signRequests)) {
3✔
532
                        throw new LibresignException('No sign requests found to process');
×
533
                }
534

535
                $enqueued = 0;
3✔
536
                foreach ($signRequests as $signRequestData) {
3✔
537
                        $file = $signRequestData['file'];
3✔
538
                        $signRequest = $signRequestData['signRequest'];
3✔
539

540
                        if ($file->getSignedHash()) {
3✔
541
                                continue;
1✔
542
                        }
543

544
                        $nodeId = $file->getNodeId();
3✔
545
                        $userId = $file->getUserId() ?? $signRequest->getUserId();
3✔
546

547
                        if ($nodeId === null || !$this->verifyFileExists($userId, $nodeId)) {
3✔
548
                                continue;
×
549
                        }
550

551
                        $this->enqueueSigningJobForFile($signRequest, $file, $jobArguments);
3✔
552
                        $enqueued++;
3✔
553
                }
554

555
                return $enqueued;
3✔
556
        }
557

558
        private function enqueueSigningJobForFile(SignRequestEntity $signRequest, FileEntity $file, array $jobArguments): void {
559
                $args = $jobArguments;
3✔
560
                $args = $this->addCredentialsToJobArgs($args, $signRequest, $file);
3✔
561
                $args = array_merge($args, [
3✔
562
                        'fileId' => $file->getId(),
3✔
563
                        'signRequestId' => $signRequest->getId(),
3✔
564
                        'signRequestUuid' => $signRequest->getUuid(),
3✔
565
                        'userId' => $file->getUserId(),
3✔
566
                        'isExternalSigner' => !str_starts_with($args['userUniqueIdentifier'] ?? '', 'account:'),
3✔
567
                ]);
3✔
568

569
                $this->jobList->add(SignSingleFileJob::class, $args);
3✔
570
        }
571

572
        private function addCredentialsToJobArgs(array $args, SignRequestEntity $signRequest, FileEntity $file): array {
573
                if (!($this->signWithoutPassword || !empty($this->password))) {
3✔
574
                        return $args;
1✔
575
                }
576

577
                $credentialsId = 'libresign_sign_' . $signRequest->getId() . '_' . $file->getId() . '_' . $this->secureRandom->generate(8, ISecureRandom::CHAR_ALPHANUMERIC);
2✔
578
                $this->credentialsManager->store(
2✔
579
                        $this->user?->getUID() ?? '',
2✔
580
                        $credentialsId,
2✔
581
                        [
2✔
582
                                'signWithoutPassword' => $this->signWithoutPassword,
2✔
583
                                'password' => $this->password,
2✔
584
                                'timestamp' => time(),
2✔
585
                                'expires' => time() + 3600,
2✔
586
                        ]
2✔
587
                );
2✔
588
                $args['credentialsId'] = $credentialsId;
2✔
589

590
                return $args;
2✔
591
        }
592

593
        /**
594
         * @return DateTimeInterface|null Last signed date
595
         */
596
        private function signSequentially(array $signRequests): ?DateTimeInterface {
597
                $envelopeLastSignedDate = null;
18✔
598
                $envelopeContext = $this->getEnvelopeContext();
18✔
599

600
                foreach ($signRequests as $index => $signRequestData) {
18✔
601
                        $this->libreSignFile = $signRequestData['file'];
18✔
602
                        if ($this->libreSignFile->getStatus() === FileStatus::SIGNED->value) {
18✔
603
                                continue;
1✔
604
                        }
605
                        $this->signRequest = $signRequestData['signRequest'];
17✔
606
                        $this->engine = null;
17✔
607
                        $this->setVisibleElements($this->elementsInput);
17✔
608
                        $this->fileToSign = null;
17✔
609

610
                        $this->validateDocMdpAllowsSignatures();
17✔
611

612
                        try {
613
                                $signedFile = $this->getEngine()->sign();
15✔
614
                        } catch (LibresignException|Exception $e) {
×
615
                                $this->cleanupUnsignedSignedFile();
×
616
                                $this->recordSignatureAttempt($e);
×
617

618
                                $isEnvelope = $this->libreSignFile->isEnvelope() || $this->libreSignFile->hasParent();
×
619
                                if (!$isEnvelope) {
×
620
                                        throw $e;
×
621
                                }
622
                                continue;
×
623
                        }
624

625
                        $hash = $this->computeHash($signedFile);
15✔
626
                        $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
15✔
627

628
                        $this->updateSignRequest($hash);
15✔
629
                        $this->updateLibreSignFile($this->libreSignFile, $signedFile->getId(), $hash);
15✔
630

631
                        $this->dispatchSignedEvent();
15✔
632
                }
633

634
                if ($envelopeContext['envelope'] instanceof FileEntity) {
16✔
635
                        $this->updateEnvelopeStatus(
×
636
                                $envelopeContext['envelope'],
×
637
                                $envelopeContext['envelopeSignRequest'] ?? null,
×
638
                                $envelopeLastSignedDate
×
639
                        );
×
640
                }
641

642
                return $envelopeLastSignedDate;
16✔
643
        }
644

645
        /**
646
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
647
         */
648
        private function getSignRequestsToSign(): array {
649
                if (!$this->libreSignFile->isEnvelope()
23✔
650
                        && !$this->libreSignFile->hasParent()
23✔
651
                ) {
652
                        return [[
19✔
653
                                'file' => $this->libreSignFile,
19✔
654
                                'signRequest' => $this->signRequest,
19✔
655
                        ]];
19✔
656
                }
657

658
                return $this->buildEnvelopeSignRequests();
4✔
659
        }
660

661
        /**
662
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
663
         */
664
        private function buildEnvelopeSignRequests(): array {
665
                $envelopeId = $this->libreSignFile->isEnvelope()
4✔
666
                        ? $this->libreSignFile->getId()
3✔
667
                        : $this->libreSignFile->getParentFileId();
1✔
668

669
                $childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
4✔
670
                if (empty($childFiles)) {
4✔
671
                        throw new LibresignException('No files found in envelope');
1✔
672
                }
673

674
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
3✔
675
                        $envelopeId,
3✔
676
                        $this->signRequest->getId()
3✔
677
                );
3✔
678

679
                if (empty($childSignRequests)) {
3✔
680
                        throw new LibresignException('No sign requests found for envelope files');
1✔
681
                }
682

683
                $signRequestsData = [];
2✔
684
                foreach ($childSignRequests as $childSignRequest) {
2✔
685
                        $childFile = $this->array_find(
2✔
686
                                $childFiles,
2✔
687
                                fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
2✔
688
                        );
2✔
689

690
                        if ($childFile) {
2✔
691
                                $signRequestsData[] = [
2✔
692
                                        'file' => $childFile,
2✔
693
                                        'signRequest' => $childSignRequest,
2✔
694
                                ];
2✔
695
                        }
696
                }
697

698
                return $signRequestsData;
2✔
699
        }
700

701
        /**
702
         * @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
703
         */
704
        private function getEnvelopeContext(): array {
705
                $result = [
22✔
706
                        'envelope' => null,
22✔
707
                        'envelopeSignRequest' => null,
22✔
708
                ];
22✔
709

710
                if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
22✔
711
                        return $result;
19✔
712
                }
713

714
                if ($this->libreSignFile->isEnvelope()) {
3✔
715
                        $result['envelope'] = $this->libreSignFile;
1✔
716
                        $result['envelopeSignRequest'] = $this->signRequest;
1✔
717
                        return $result;
1✔
718
                }
719

720
                try {
721
                        $envelopeId = $this->libreSignFile->isEnvelope()
2✔
722
                                ? $this->libreSignFile->getId()
×
723
                                : $this->libreSignFile->getParentFileId();
2✔
724
                        $result['envelope'] = $this->fileMapper->getById($envelopeId);
2✔
725
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
1✔
726
                        $result['envelopeSignRequest'] = $this->signRequestMapper->getByIdentifyMethodAndFileId(
1✔
727
                                $identifyMethod,
1✔
728
                                $result['envelope']->getId()
1✔
729
                        );
1✔
730
                } catch (DoesNotExistException $e) {
1✔
731
                }
732

733
                return $result;
2✔
734
        }
735

736
        private function updateEnvelopeStatus(
737
                FileEntity $envelope,
738
                ?SignRequestEntity $envelopeSignRequest = null,
739
                ?DateTimeInterface $signedDate = null,
740
        ): void {
741
                $childFiles = $this->fileMapper->getChildrenFiles($envelope->getId());
1✔
742
                $signRequestsMap = $this->buildSignRequestsMap($childFiles);
1✔
743

744
                $status = $this->envelopeStatusDeterminer->determineStatus($childFiles, $signRequestsMap);
1✔
745
                $envelope->setStatus($status);
1✔
746

747
                $this->handleSignedEnvelopeSignRequest($envelope, $envelopeSignRequest, $signedDate, $status);
1✔
748

749
                $this->updateEnvelopeMetadata($envelope);
1✔
750
                $this->fileMapper->update($envelope);
1✔
751
                $this->updateEntityCacheAfterDbSave($envelope);
1✔
752
        }
753

754
        private function buildSignRequestsMap(array $childFiles): array {
755
                $signRequestsMap = [];
2✔
756
                foreach ($childFiles as $childFile) {
2✔
757
                        $signRequestsMap[$childFile->getId()] = $this->signRequestMapper->getByFileId($childFile->getId());
2✔
758
                }
759
                return $signRequestsMap;
2✔
760
        }
761

762
        private function handleSignedEnvelopeSignRequest(
763
                FileEntity $envelope,
764
                ?SignRequestEntity $envelopeSignRequest,
765
                ?DateTimeInterface $signedDate,
766
                int $status,
767
        ): void {
768
                if (!($envelopeSignRequest instanceof SignRequestEntity)) {
3✔
769
                        return;
1✔
770
                }
771

772
                $envelopeSignRequest->setSigned($signedDate ?: new DateTime());
2✔
773
                $envelopeSignRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
2✔
774
                $this->signRequestMapper->update($envelopeSignRequest);
2✔
775
                $this->sequentialSigningService
2✔
776
                        ->setFile($envelope)
2✔
777
                        ->releaseNextOrder(
2✔
778
                                $envelopeSignRequest->getFileId(),
2✔
779
                                $envelopeSignRequest->getSigningOrder()
2✔
780
                        );
2✔
781
        }
782

783
        private function updateEnvelopeMetadata(FileEntity $envelope): void {
784
                $meta = $envelope->getMetadata() ?? [];
2✔
785
                $meta['status_changed_at'] = (new DateTime())->format(DateTimeInterface::ATOM);
2✔
786
                $envelope->setMetadata($meta);
2✔
787
        }
788

789
        /**
790
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
791
         */
792
        protected function validateDocMdpAllowsSignatures(): void {
793
                $docmdpLevel = $this->libreSignFile->getDocmdpLevelEnum();
19✔
794

795
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED) {
19✔
796
                        throw new LibresignException(
1✔
797
                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
1✔
798
                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
1✔
799
                        );
1✔
800
                }
801

802
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::NOT_CERTIFIED) {
18✔
803
                        $resource = $this->getLibreSignFileAsResource();
18✔
804

805
                        try {
806
                                if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
17✔
807
                                        throw new LibresignException(
4✔
808
                                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
4✔
809
                                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
4✔
810
                                        );
4✔
811
                                }
812
                        } finally {
813
                                fclose($resource);
17✔
814
                        }
815
                }
816
        }
817

818
        /**
819
         * @return resource
820
         * @throws LibresignException
821
         */
822
        protected function getLibreSignFileAsResource() {
823
                $files = $this->getNextcloudFiles($this->libreSignFile);
11✔
824
                if (empty($files)) {
10✔
825
                        throw new LibresignException('File not found');
×
826
                }
827
                $fileToSign = current($files);
10✔
828
                $content = $fileToSign->getContent();
10✔
829
                $resource = fopen('php://memory', 'r+');
10✔
830
                if ($resource === false) {
10✔
831
                        throw new LibresignException('Failed to create temporary resource for PDF validation');
×
832
                }
833
                fwrite($resource, $content);
10✔
834
                rewind($resource);
10✔
835
                return $resource;
10✔
836
        }
837

838
        protected function computeHash(File $file): string {
839
                return hash('sha256', $file->getContent());
2✔
840
        }
841

842
        protected function updateSignRequest(string $hash): void {
843
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
13✔
844
                $this->signRequest->setSigned($lastSignedDate);
13✔
845
                $this->signRequest->setSignedHash($hash);
13✔
846
                $this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
13✔
847

848
                $certificateInfo = $this->getEngine()->readCertificate();
13✔
849
                $this->storeCertificateInfoInMetadata($certificateInfo);
13✔
850

851
                $this->signRequestMapper->update($this->signRequest);
13✔
852

853
                $this->sequentialSigningService
13✔
854
                        ->setFile($this->libreSignFile)
13✔
855
                        ->releaseNextOrder(
13✔
856
                                $this->signRequest->getFileId(),
13✔
857
                                $this->signRequest->getSigningOrder()
13✔
858
                        );
13✔
859
        }
860

861
        private function storeCertificateInfoInMetadata(array $certificateInfo): void {
862
                $metadata = $this->signRequest->getMetadata() ?? [];
15✔
863

864
                $certificateData = [];
15✔
865

866
                if (isset($certificateInfo['serialNumber'])) {
15✔
867
                        $certificateData['serialNumber'] = $certificateInfo['serialNumber'];
2✔
868
                }
869
                if (isset($certificateInfo['serialNumberHex'])) {
15✔
870
                        $certificateData['serialNumberHex'] = $certificateInfo['serialNumberHex'];
1✔
871
                }
872
                if (isset($certificateInfo['hash'])) {
15✔
873
                        $certificateData['hash'] = $certificateInfo['hash'];
1✔
874
                }
875
                if (isset($certificateInfo['subject'])) {
15✔
876
                        $certificateData['subject'] = $certificateInfo['subject'];
1✔
877
                }
878

879
                if (!empty($certificateData)) {
15✔
880
                        $metadata['certificate_info'] = $certificateData;
2✔
881
                        $this->signRequest->setMetadata($metadata);
2✔
882
                }
883
        }
884

885
        protected function updateLibreSignFile(FileEntity $libreSignFile, int $nodeId, string $hash): void {
886
                $libreSignFile->setSignedNodeId($nodeId);
13✔
887
                $libreSignFile->setSignedHash($hash);
13✔
888
                $this->setNewStatusIfNecessary($libreSignFile);
13✔
889
                $this->fileStatusService->update($libreSignFile);
13✔
890

891
                if ($libreSignFile->hasParent()) {
13✔
892
                        $this->fileStatusService->propagateStatusToParent($libreSignFile->getParentFileId());
×
893
                }
894
        }
895

896
        protected function dispatchSignedEvent(): void {
897
                $certificateSerialNumber = null;
13✔
898
                if ($this->signWithoutPassword) {
13✔
899
                        try {
900
                                $certificateInfo = $this->getEngine()->readCertificate();
×
901
                                if (isset($certificateInfo['serialNumber']) && is_string($certificateInfo['serialNumber'])) {
×
902
                                        $certificateSerialNumber = $certificateInfo['serialNumber'];
×
903
                                } else {
904
                                        $this->logger->warning('Unable to extract certificate serial number for event payload');
×
905
                                }
906
                        } catch (\Throwable $e) {
×
907
                                $this->logger->error('Failed to get certificate info for event', [
×
908
                                        'exception' => $e,
×
909
                                        'signRequestId' => $this->signRequest->getId()
×
910
                                ]);
×
911
                        }
912
                }
913

914
                $event = $this->signedEventFactory->make(
13✔
915
                        $this->signRequest,
13✔
916
                        $this->libreSignFile,
13✔
917
                        $this->getEngine()->getInputFile(),
13✔
918
                        $this->signWithoutPassword,
13✔
919
                        $certificateSerialNumber,
13✔
920
                );
13✔
921
                $this->eventDispatcher->dispatchTyped($event);
13✔
922
        }
923

924
        protected function identifyEngine(File $file): SignEngineHandler {
925
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
926
        }
927

928
        protected function getSignatureParams(): array {
929
                $certificateData = $this->readCertificate();
15✔
930
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
931
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
932
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
933
                return $signatureParams;
15✔
934
        }
935

936
        private function buildBaseSignatureParams(array $certificateData): array {
937
                return [
15✔
938
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
939
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
940
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
941
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
942
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
943
                                ->format(DateTimeInterface::ATOM)
15✔
944
                ];
15✔
945
        }
946

947
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
948
                $email = $this->subjectAlternativeNameService->extractEmailFromCertificate($certificateData);
15✔
949
                if ($email) {
15✔
950
                        $signatureParams['SignerEmail'] = $email;
6✔
951
                }
952

953
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
954
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
×
955
                }
956

957
                if (empty($signatureParams['SignerEmail']) && $this->signRequest instanceof SignRequestEntity) {
15✔
958
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
959
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
960
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
961
                        }
962
                }
963
                return $signatureParams;
15✔
964
        }
965

966
        private function addMetadataToSignatureParams(array $signatureParams): array {
967
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
968
                if (isset($signRequestMetadata['remote-address'])) {
15✔
969
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
970
                }
971
                if (isset($signRequestMetadata['user-agent'])) {
15✔
972
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
973
                }
974
                return $signatureParams;
15✔
975
        }
976

977
        public function storeUserMetadata(array $metadata = []): self {
978
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
979
                if (!$collectMetadata || !$metadata) {
18✔
980
                        return $this;
7✔
981
                }
982
                $this->signRequest->setMetadata(array_merge(
11✔
983
                        $this->signRequest->getMetadata() ?? [],
11✔
984
                        $metadata,
11✔
985
                ));
11✔
986
                $this->signRequestMapper->update($this->signRequest);
11✔
987
                return $this;
11✔
988
        }
989

990
        /**
991
         * @return SignRequestEntity[]
992
         */
993
        protected function getSigners(): array {
994
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
995
        }
996

997
        protected function setNewStatusIfNecessary(FileEntity $libreSignFile): bool {
998
                $newStatus = $this->evaluateStatusFromSigners();
9✔
999

1000
                if ($newStatus === null || $newStatus === $libreSignFile->getStatus()) {
9✔
1001
                        return false;
3✔
1002
                }
1003

1004
                $libreSignFile->setStatus($newStatus);
6✔
1005

1006
                return true;
6✔
1007
        }
1008

1009
        private function updateEntityCacheAfterDbSave(FileEntity $file): void {
1010
                $this->statusService->cacheFileStatus($file);
1✔
1011
        }
1012

1013
        private function evaluateStatusFromSigners(): ?int {
1014
                $signers = $this->getSigners();
9✔
1015

1016
                $total = count($signers);
9✔
1017

1018
                if ($total === 0) {
9✔
1019
                        return null;
1✔
1020
                }
1021

1022
                $totalSigned = count(array_filter($signers, fn ($s) => $s->getSigned() !== null));
8✔
1023

1024
                if ($totalSigned === $total) {
8✔
1025
                        return FileStatus::SIGNED->value;
4✔
1026
                }
1027

1028
                if ($totalSigned > 0) {
4✔
1029
                        return FileStatus::PARTIAL_SIGNED->value;
3✔
1030
                }
1031

1032
                return null;
1✔
1033
        }
1034

1035
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
1036
                $result = $this->pfxProvider->getOrGeneratePfx(
13✔
1037
                        $engine,
13✔
1038
                        $this->signWithoutPassword,
13✔
1039
                        $this->signatureMethodName,
13✔
1040
                        $this->userUniqueIdentifier,
13✔
1041
                        $this->friendlyName,
13✔
1042
                        $this->password,
13✔
1043
                );
13✔
1044
                if ($result['password'] !== null) {
13✔
1045
                        $this->setPassword($result['password']);
2✔
1046
                }
1047
                return $result['pfx'];
13✔
1048
        }
1049

1050
        protected function readCertificate(): array {
1051
                return $this->getEngine()
×
1052
                        ->readCertificate();
×
1053
        }
1054

1055
        /**
1056
         * Get file to sign
1057
         *
1058
         * @throws LibresignException
1059
         */
1060
        protected function getFileToSign(): File {
1061
                if ($this->fileToSign instanceof File) {
×
1062
                        return $this->fileToSign;
×
1063
                }
1064

1065
                $userId = $this->libreSignFile->getUserId()
×
1066
                        ?? $this->user?->getUID()
×
1067
                        ?? ($this->signRequest?->getUserId() ?? null);
×
1068
                $nodeId = $this->libreSignFile->getNodeId();
×
1069

1070
                if ($userId === null) {
×
1071
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1072
                }
1073

1074
                try {
1075
                        $originalFile = $this->getNodeByIdUsingUid($userId, $nodeId);
×
1076
                } catch (\Throwable $e) {
×
1077
                        $this->logger->error('[file-access] FAILED to find file - userId={userId} nodeId={nodeId} error={error}', [
×
1078
                                'userId' => $userId,
×
1079
                                'nodeId' => $nodeId,
×
1080
                                'error' => $e->getMessage(),
×
1081
                        ]);
×
1082
                        throw $e;
×
1083
                }
1084

1085
                if ($originalFile->getOwner()->getUID() !== $userId) {
×
1086
                        $originalFile = $this->getNodeByIdUsingUid($originalFile->getOwner()->getUID(), $nodeId);
×
1087
                }
1088
                if ($this->isPdf($originalFile)) {
×
1089
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
1090
                } else {
1091
                        $this->fileToSign = $originalFile;
×
1092
                }
1093
                return $this->fileToSign;
×
1094
        }
1095

1096
        private function isPdf(File $file): bool {
1097
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
1098
        }
1099

1100
        protected function getEngine(): SignEngineHandler {
1101
                if (!$this->engine) {
12✔
1102
                        $originalFile = $this->getFileToSign();
12✔
1103
                        $this->engine = $this->identifyEngine($originalFile);
12✔
1104

1105
                        $this->configureEngine();
12✔
1106
                }
1107
                return $this->engine;
12✔
1108
        }
1109

1110
        private function configureEngine(): void {
1111
                $this->engine
12✔
1112
                        ->setInputFile($this->getFileToSign())
12✔
1113
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
1114
                        ->setPassword($this->password);
12✔
1115

1116
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
1117
                        $this->engine
×
1118
                                ->setVisibleElements($this->getVisibleElements())
×
1119
                                ->setSignatureParams($this->getSignatureParams());
×
1120
                }
1121
        }
1122

1123
        public function getLibresignFile(?int $fileId, ?string $signRequestUuid = null): FileEntity {
1124
                try {
1125
                        if ($fileId) {
3✔
1126
                                return $this->fileMapper->getById($fileId);
1✔
1127
                        }
1128

1129
                        if ($signRequestUuid) {
2✔
1130
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
1131
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
1132
                        }
1133

1134
                        throw new \Exception('Invalid arguments');
×
1135

1136
                } catch (DoesNotExistException) {
1✔
1137
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
1138
                }
1139
        }
1140

1141
        public function renew(SignRequestEntity $signRequest, string $method): void {
1142
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1143
                if (empty($identifyMethods[$method])) {
×
1144
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1145
                }
1146

1147
                $signRequest->setUuid(UUIDUtil::getUUID());
×
1148
                $this->signRequestMapper->update($signRequest);
×
1149

1150
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
1151
                        $entity = $identifyMethod->getEntity();
×
1152
                        $entity->setAttempts($entity->getAttempts() + 1);
×
1153
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
1154
                        $identifyMethod->save();
×
1155
                }, $identifyMethods[$method]);
×
1156
        }
1157

1158
        public function requestCode(
1159
                SignRequestEntity $signRequest,
1160
                string $identifyMethodName,
1161
                string $signMethodName,
1162
                string $identify = '',
1163
        ): void {
1164
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1165
                if (empty($identifyMethods[$identifyMethodName])) {
×
1166
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1167
                }
1168
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
1169
                        try {
1170
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
1171
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
1172
                        } catch (InvalidArgumentException) {
×
1173
                                continue;
×
1174
                        }
1175
                        /** @var IToken $signatureMethod */
1176
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
1177
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
1178
                        return;
×
1179
                }
1180
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
1181
        }
1182

1183
        private function getOrCreateApproverSignRequest(FileEntity $file, IUser $user): ?SignRequestEntity {
1184
                if (!$this->validateHelper->userCanApproveValidationDocuments($user, false)) {
6✔
1185
                        return null;
4✔
1186
                }
1187

1188
                try {
1189
                        $this->idDocsMapper->getByFileId($file->getId());
2✔
1190
                } catch (\Throwable) {
1✔
1191
                        return null;
1✔
1192
                }
1193

1194
                try {
1195
                        $this->sequentialSigningService->setFile($file);
1✔
1196
                        $signRequest = $this->signRequestService->createOrUpdateSignRequest(
1✔
1197
                                identifyMethods: [IdentifyMethodService::IDENTIFY_ACCOUNT => $user->getUID()],
1✔
1198
                                displayName: $user->getDisplayName(),
1✔
1199
                                description: '',
1✔
1200
                                notify: false,
1✔
1201
                                fileId: $file->getId(),
1✔
1202
                                signingOrder: 0,
1✔
1203
                                fileStatus: FileStatus::ABLE_TO_SIGN->value,
1✔
1204
                        );
1✔
1205

1206
                        return $signRequest;
1✔
1207
                } catch (\Throwable $e) {
×
1208
                        $this->logger->error('Failed to create/get SignRequest for approver', [
×
1209
                                'exception' => $e,
×
1210
                                'fileId' => $file->getId(),
×
1211
                                'userId' => $user->getUID(),
×
1212
                        ]);
×
1213
                        return null;
×
1214
                }
1215
        }
1216

1217
        /**
1218
         * @param SignRequestEntity[] $signRequests
1219
         * @param IUser $user
1220
         * @return SignRequestEntity|null
1221
         */
1222
        private function findSignRequestByIdentifyMethod(array $signRequests, IUser $user): ?SignRequestEntity {
1223
                foreach ($signRequests as $signRequest) {
5✔
1224
                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
5✔
1225
                        foreach ($identifyMethods as $method) {
5✔
1226
                                if ($method->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
5✔
1227
                                        && ($method->getIdentifierValue() === $user->getUID()
5✔
1228
                                                || $method->getIdentifierValue() === $user->getEMailAddress())
5✔
1229
                                ) {
1230
                                        return $signRequest;
2✔
1231
                                }
1232
                                if ($method->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
3✔
1233
                                        && $method->getIdentifierValue() === $user->getUID()
3✔
1234
                                ) {
1235
                                        return $signRequest;
2✔
1236
                                }
1237
                        }
1238
                }
1239
                return null;
1✔
1240
        }
1241

1242
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
1243
                $this->validateHelper->fileCanBeSigned($libresignFile);
9✔
1244
                try {
1245
                        if (!empty($signRequestUuid)) {
9✔
1246
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
3✔
1247
                        } elseif ($user) {
6✔
1248
                                $signRequest = $this->getOrCreateApproverSignRequest($libresignFile, $user);
6✔
1249
                        }
1250

1251
                        if (!isset($signRequest)) {
9✔
1252
                                if ($libresignFile->isEnvelope()) {
5✔
1253
                                        $childFiles = $this->fileMapper->getChildrenFiles($libresignFile->getId());
×
1254
                                        $allSignRequests = [];
×
1255
                                        foreach ($childFiles as $childFile) {
×
1256
                                                $childSignRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
1257
                                                $allSignRequests = array_merge($allSignRequests, $childSignRequests);
×
1258
                                        }
1259
                                        $signRequests = $allSignRequests;
×
1260
                                } else {
1261
                                        $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
5✔
1262
                                }
1263

1264
                                $signRequest = $this->findSignRequestByIdentifyMethod($signRequests, $user);
5✔
1265
                        }
1266

1267
                        if (!$signRequest) {
9✔
1268
                                throw new DoesNotExistException('Sign request not found');
1✔
1269
                        }
1270
                        $signRequestFile = $libresignFile;
8✔
1271
                        if ($signRequestFile->getId() !== $signRequest->getFileId()) {
8✔
1272
                                $signRequestFile = $this->fileMapper->getById($signRequest->getFileId());
×
1273
                        }
1274
                        $this->sequentialSigningService->setFile($signRequestFile);
8✔
1275
                        if (
1276
                                $this->sequentialSigningService->isOrderedNumericFlow()
8✔
1277
                                && $this->sequentialSigningService->hasPendingLowerOrderSigners(
8✔
1278
                                        $signRequest->getFileId(),
8✔
1279
                                        $signRequest->getSigningOrder()
8✔
1280
                                )
8✔
1281
                        ) {
1282
                                throw new LibresignException(json_encode([
×
1283
                                        'action' => JSActions::ACTION_DO_NOTHING,
×
1284
                                        'errors' => [['message' => $this->l10n->t('You are not allowed to sign this document yet')]],
×
1285
                                ]));
×
1286
                        }
1287
                        if ($signRequest->getSigned()) {
8✔
1288
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
1289
                        }
1290
                        return $signRequest;
8✔
1291
                } catch (DoesNotExistException) {
1✔
1292
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
1✔
1293
                }
1294
        }
1295

1296
        protected function getPdfToSign(File $originalFile): File {
1297
                $file = $this->getSignedFile();
×
1298
                if ($file instanceof File) {
×
1299
                        return $file;
×
1300
                }
1301

1302
                $originalContent = $originalFile->getContent();
×
1303

1304
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
1305
                        return $this->createSignedFile($originalFile, $originalContent);
×
1306
                }
1307
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
1308
                $footer = $this->footerHandler
×
1309
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
1310
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
1311
                                'displayName' => $signer->getDisplayName(),
×
1312
                                'signed' => $signer->getSigned()
×
1313
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
1314
                                        : null,
1315
                        ], $this->getSigners()))
×
1316
                        ->getFooter($metadata['d']);
×
1317
                if ($footer) {
×
1318
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
1319
                        file_put_contents($stamp, $footer);
×
1320

1321
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
1322
                        file_put_contents($input, $originalContent);
×
1323

1324
                        try {
1325
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
1326
                        } catch (RuntimeException $e) {
×
1327
                                throw new LibresignException($e->getMessage());
×
1328
                        }
1329
                } else {
1330
                        $pdfContent = $originalContent;
×
1331
                }
1332
                return $this->createSignedFile($originalFile, $pdfContent);
×
1333
        }
1334

1335
        protected function getSignedFile(): ?File {
1336
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
1337
                if (!$nodeId) {
3✔
1338
                        return null;
1✔
1339
                }
1340

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

1343
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
1344
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
1345
                }
1346
                return $fileToSign;
2✔
1347
        }
1348

1349
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
1350
                try {
1351
                        $userFolder = $this->root->getUserFolder($uid);
4✔
1352
                } catch (NoUserException $e) {
2✔
1353
                        $this->logger->error('[file-access] NoUserException for uid={uid}', ['uid' => $uid]);
1✔
1354
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
1355
                } catch (NotPermittedException $e) {
1✔
1356
                        $this->logger->error('[file-access] NotPermittedException for uid={uid}', ['uid' => $uid]);
1✔
1357
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
1358
                }
1359

1360
                try {
1361
                        $fileToSign = $userFolder->getFirstNodeById($nodeId);
2✔
1362
                } catch (\Throwable $e) {
×
1363
                        $this->logger->error('[file-access] Failed getFirstNodeById - nodeId={nodeId} error={error}', [
×
1364
                                'nodeId' => $nodeId,
×
1365
                                'error' => $e->getMessage(),
×
1366
                        ]);
×
1367
                        throw $e;
×
1368
                }
1369

1370
                if (!$fileToSign instanceof File) {
2✔
1371
                        $this->logger->error('[file-access] Node is not a File - nodeId={nodeId} type={type}', [
1✔
1372
                                'nodeId' => $nodeId,
1✔
1373
                                'type' => $fileToSign ? get_class($fileToSign) : 'NULL',
1✔
1374
                        ]);
1✔
1375
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
1376
                }
1377
                return $fileToSign;
1✔
1378
        }
1379

1380
        /**
1381
         * Verify if file exists in filesystem before enqueuing background job
1382
         *
1383
         * @param string|null $uid User ID
1384
         * @param int $nodeId File node ID
1385
         * @return bool True if file exists and is accessible
1386
         */
1387
        private function verifyFileExists(?string $uid, int $nodeId): bool {
1388
                if ($uid === null || $nodeId === 0) {
8✔
1389
                        return false;
2✔
1390
                }
1391

1392
                try {
1393
                        $userFolder = $this->root->getUserFolder($uid);
6✔
1394
                        $node = $userFolder->getFirstNodeById($nodeId);
5✔
1395
                        return $node instanceof File;
5✔
1396
                } catch (\Throwable $e) {
1✔
1397
                        $this->logger->warning('[verify-file] File not accessible - nodeId={nodeId} uid={uid} error={error}', [
1✔
1398
                                'nodeId' => $nodeId,
1✔
1399
                                'uid' => $uid,
1✔
1400
                                'error' => $e->getMessage(),
1✔
1401
                        ]);
1✔
1402
                        return false;
1✔
1403
                }
1404
        }
1405

1406
        private function cleanupUnsignedSignedFile(): void {
1407
                if (!$this->createdSignedFile instanceof File) {
3✔
1408
                        return;
1✔
1409
                }
1410

1411
                try {
1412
                        $this->createdSignedFile->delete();
2✔
1413
                } catch (\Throwable $e) {
1✔
1414
                        $this->logger->warning('Failed to delete temporary signed file: ' . $e->getMessage());
1✔
1415
                } finally {
1416
                        $this->createdSignedFile = null;
2✔
1417
                }
1418
        }
1419

1420
        private function createSignedFile(File $originalFile, string $content): File {
1421
                $filename = preg_replace(
×
1422
                        '/' . $originalFile->getExtension() . '$/',
×
1423
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
1424
                        basename($originalFile->getPath())
×
1425
                );
×
1426
                $owner = $originalFile->getOwner()->getUID();
×
1427

1428
                $fileId = $this->libreSignFile->getId();
×
1429
                $extension = $originalFile->getExtension();
×
1430
                $uniqueFilename = substr($filename, 0, -strlen($extension) - 1) . '_' . $fileId . '.' . $extension;
×
1431

1432
                try {
1433
                        /** @var \OCP\Files\Folder */
1434
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
1435

1436
                        $this->createdSignedFile = $parentFolder->newFile($uniqueFilename, $content);
×
1437

1438
                        return $this->createdSignedFile;
×
1439
                } catch (NotPermittedException) {
×
1440
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
1441
                } catch (\Exception $e) {
×
1442
                        throw $e;
×
1443
                }
1444
        }
1445

1446
        /**
1447
         * @throws DoesNotExistException
1448
         */
1449
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1450
                $this->validateHelper->validateUuidFormat($uuid);
5✔
1451
                return $this->signRequestMapper->getByUuid($uuid);
4✔
1452
        }
1453

1454
        /**
1455
         * @throws DoesNotExistException
1456
         */
1457
        public function getFile(int $signRequestId): FileEntity {
1458
                return $this->fileMapper->getById($signRequestId);
×
1459
        }
1460

1461
        /**
1462
         * @throws DoesNotExistException
1463
         */
1464
        public function getFileByUuid(string $uuid): FileEntity {
1465
                return $this->fileMapper->getByUuid($uuid);
×
1466
        }
1467

1468
        public function getIdDocById(int $fileId): IdDocs {
1469
                return $this->idDocsMapper->getByFileId($fileId);
×
1470
        }
1471

1472
        /**
1473
         * @return File[] Array of files
1474
         */
1475
        public function getNextcloudFiles(FileEntity $fileData): array {
1476
                if ($fileData->getNodeType() === 'envelope') {
1✔
1477
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1478
                        $files = [];
×
1479
                        foreach ($children as $child) {
×
1480
                                $nodeId = $child->getNodeId();
×
1481
                                if ($nodeId === null) {
×
1482
                                        throw new LibresignException(json_encode([
×
1483
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1484
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1485
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1486
                                }
1487
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1488
                                if ($file instanceof File) {
×
1489
                                        $files[] = $file;
×
1490
                                }
1491
                        }
1492
                        return $files;
×
1493
                }
1494

1495
                $nodeId = $fileData->getNodeId();
1✔
1496
                if ($nodeId === null) {
1✔
1497
                        throw new LibresignException(json_encode([
1✔
1498
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1499
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1500
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1501
                }
1502
                $storageUserId = $this->fileMapper->getStorageUserIdByUuid($fileData->getUuid());
×
1503
                $this->folderService->setUserId($storageUserId);
×
1504
                $fileToSign = $this->folderService->getFileByNodeId($nodeId);
×
1505
                if (!$fileToSign instanceof File) {
×
1506
                        throw new LibresignException(json_encode([
×
1507
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1508
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1509
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1510
                }
1511
                return [$fileToSign];
×
1512
        }
1513

1514
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1515
                $this->validateHelper->validateSigner($uuid, $user);
×
1516
        }
1517

1518
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1519
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1520
        }
1521

1522
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1523
                $return = ['user' => ['name' => null]];
×
1524
                if ($signRequest) {
×
1525
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1526
                } elseif ($user) {
×
1527
                        $return['user']['name'] = $user->getDisplayName();
×
1528
                }
1529
                return $return;
×
1530
        }
1531

1532
        public function getAvailableIdentifyMethodsFromSettings(): array {
1533
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1534
                $return = array_map(fn (array $identifyMethod): array => [
×
1535
                        'mandatory' => $identifyMethod['mandatory'],
×
1536
                        'identifiedAtDate' => null,
×
1537
                        'validateCode' => false,
×
1538
                        'method' => $identifyMethod['name'],
×
1539
                ], $identifyMethods);
×
1540
                return $return;
×
1541
        }
1542

1543
        public function getFileUrl(int $fileId, string $uuid): string {
1544
                try {
1545
                        $this->idDocsMapper->getByFileId($fileId);
×
1546
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1547
                } catch (DoesNotExistException) {
×
1548
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1549
                }
1550
        }
1551

1552
        /**
1553
         * Get PDF URLs for signing
1554
         * For envelopes: returns URLs for all child files
1555
         * For regular files: returns URL for the file itself
1556
         *
1557
         * @return string[]
1558
         */
1559
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1560
                if (!$fileEntity->isEnvelope()) {
×
1561
                        return [
×
1562
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1563
                        ];
×
1564
                }
1565

1566
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1567
                        $fileEntity->getId(),
×
1568
                        $signRequestEntity->getId()
×
1569
                );
×
1570

1571
                $pdfUrls = [];
×
1572
                foreach ($childSignRequests as $childSignRequest) {
×
1573
                        $pdfUrls[] = $this->getFileUrl(
×
1574
                                $childSignRequest->getFileId(),
×
1575
                                $childSignRequest->getUuid()
×
1576
                        );
×
1577
                }
1578

1579
                return $pdfUrls;
×
1580
        }
1581

1582
        private function recordSignatureAttempt(Exception $exception): void {
1583
                if (!$this->libreSignFile) {
×
1584
                        return;
×
1585
                }
1586

1587
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1588

1589
                if (!isset($metadata['signature_attempts'])) {
×
1590
                        $metadata['signature_attempts'] = [];
×
1591
                }
1592

1593
                $attempt = [
×
1594
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1595
                        'engine' => $this->engine ? get_class($this->engine) : 'unknown',
×
1596
                        'error_message' => $exception->getMessage(),
×
1597
                        'error_code' => $exception->getCode(),
×
1598
                ];
×
1599

1600
                $metadata['signature_attempts'][] = $attempt;
×
1601
                $this->libreSignFile->setMetadata($metadata);
×
1602
                $this->fileMapper->update($this->libreSignFile);
×
1603
        }
1604
}
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