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

LibreSign / libresign / 21773266345

07 Feb 2026 03:16AM UTC coverage: 47.628%. First build
21773266345

Pull #6758

github

web-flow
Merge b712f1d36 into 20ff6e8ee
Pull Request #6758: fix: async signing job context

32 of 38 new or added lines in 3 files covered. (84.21%)

8242 of 17305 relevant lines covered (47.63%)

5.17 hits per line

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

53.7
/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 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
        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;
147✔
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;
8✔
194
                return $this;
8✔
195
        }
196

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

202
        /**
203
         * @return static
204
         */
205
        public function setSignRequest(SignRequestEntity $signRequest): self {
206
                $this->signRequest = $signRequest;
79✔
207
                return $this;
79✔
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;
30✔
233
                return $this;
30✔
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✔
NEW
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✔
NEW
295
                                $newElements[$fileElementId] = $existing;
×
NEW
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 {
NEW
308
                $tempFile = $elementAssoc->getTempFile();
×
NEW
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) {
11✔
382
                        if ($callback($value, $key)) {
11✔
383
                                return $value;
11✔
384
                        }
385
                }
386

387
                return null;
4✔
388
        }
389

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

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

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

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

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

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

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

417
                return $args;
1✔
418
        }
419

420
        public function validateSigningRequirements(): void {
421
                $this->tsaValidationService->validateConfiguration();
×
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;
×
NEW
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)) {
1✔
532
                        throw new LibresignException('No sign requests found to process');
×
533
                }
534

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

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

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

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

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

555
                return $enqueued;
1✔
556
        }
557

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

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

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

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

590
                return $args;
1✔
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()
19✔
650
                        && !$this->libreSignFile->hasParent()
19✔
651
                ) {
652
                        return [[
18✔
653
                                'file' => $this->libreSignFile,
18✔
654
                                'signRequest' => $this->signRequest,
18✔
655
                        ]];
18✔
656
                }
657

658
                return $this->buildEnvelopeSignRequests();
1✔
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()
1✔
666
                        ? $this->libreSignFile->getId()
×
667
                        : $this->libreSignFile->getParentFileId();
1✔
668

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

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

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

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

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

698
                return $signRequestsData;
1✔
699
        }
700

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

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

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

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

733
                return $result;
×
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 = [];
1✔
756
                foreach ($childFiles as $childFile) {
1✔
757
                        $signRequestsMap[$childFile->getId()] = $this->signRequestMapper->getByFileId($childFile->getId());
1✔
758
                }
759
                return $signRequestsMap;
1✔
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)) {
1✔
769
                        return;
×
770
                }
771

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

783
        private function updateEnvelopeMetadata(FileEntity $envelope): void {
784
                $meta = $envelope->getMetadata() ?? [];
1✔
785
                $meta['status_changed_at'] = (new DateTime())->format(DateTimeInterface::ATOM);
1✔
786
                $envelope->setMetadata($meta);
1✔
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();
17✔
794

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

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

805
                        try {
806
                                if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
16✔
807
                                        throw new LibresignException(
3✔
808
                                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
3✔
809
                                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
810
                                        );
3✔
811
                                }
812
                        } finally {
813
                                fclose($resource);
16✔
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
                $this->signRequestMapper->update($this->signRequest);
13✔
849

850
                $this->sequentialSigningService
13✔
851
                        ->setFile($this->libreSignFile)
13✔
852
                        ->releaseNextOrder(
13✔
853
                                $this->signRequest->getFileId(),
13✔
854
                                $this->signRequest->getSigningOrder()
13✔
855
                        );
13✔
856
        }
857

858
        protected function updateLibreSignFile(FileEntity $libreSignFile, int $nodeId, string $hash): void {
859
                $libreSignFile->setSignedNodeId($nodeId);
13✔
860
                $libreSignFile->setSignedHash($hash);
13✔
861
                $this->setNewStatusIfNecessary($libreSignFile);
13✔
862
                $this->fileStatusService->update($libreSignFile);
13✔
863

864
                if ($libreSignFile->hasParent()) {
13✔
865
                        $this->fileStatusService->propagateStatusToParent($libreSignFile->getParentFileId());
×
866
                }
867
        }
868

869
        protected function dispatchSignedEvent(): void {
870
                $certificateSerialNumber = null;
13✔
871
                if ($this->signWithoutPassword) {
13✔
872
                        try {
873
                                $certificateInfo = $this->getEngine()->readCertificate();
×
874
                                if (isset($certificateInfo['serialNumber']) && is_string($certificateInfo['serialNumber'])) {
×
875
                                        $certificateSerialNumber = $certificateInfo['serialNumber'];
×
876
                                } else {
877
                                        $this->logger->warning('Unable to extract certificate serial number for event payload');
×
878
                                }
879
                        } catch (\Throwable $e) {
×
880
                                $this->logger->error('Failed to get certificate info for event', [
×
881
                                        'exception' => $e,
×
882
                                        'signRequestId' => $this->signRequest->getId()
×
883
                                ]);
×
884
                        }
885
                }
886

887
                $event = $this->signedEventFactory->make(
13✔
888
                        $this->signRequest,
13✔
889
                        $this->libreSignFile,
13✔
890
                        $this->getEngine()->getInputFile(),
13✔
891
                        $this->signWithoutPassword,
13✔
892
                        $certificateSerialNumber,
13✔
893
                );
13✔
894
                $this->eventDispatcher->dispatchTyped($event);
13✔
895
        }
896

897
        protected function identifyEngine(File $file): SignEngineHandler {
898
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
899
        }
900

901
        protected function getSignatureParams(): array {
902
                $certificateData = $this->readCertificate();
15✔
903
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
904
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
905
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
906
                return $signatureParams;
15✔
907
        }
908

909
        private function buildBaseSignatureParams(array $certificateData): array {
910
                return [
15✔
911
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
912
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
913
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
914
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
915
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
916
                                ->format(DateTimeInterface::ATOM)
15✔
917
                ];
15✔
918
        }
919

920
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
921
                if (isset($certificateData['extensions']['subjectAltName'])) {
15✔
922
                        preg_match('/(?:email:)+(?<email>[^\s,]+)/', $certificateData['extensions']['subjectAltName'], $matches);
6✔
923
                        if ($matches && filter_var($matches['email'], FILTER_VALIDATE_EMAIL)) {
6✔
924
                                $signatureParams['SignerEmail'] = $matches['email'];
4✔
925
                        } elseif (filter_var($certificateData['extensions']['subjectAltName'], FILTER_VALIDATE_EMAIL)) {
2✔
926
                                $signatureParams['SignerEmail'] = $certificateData['extensions']['subjectAltName'];
1✔
927
                        }
928
                }
929
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
930
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
1✔
931
                }
932
                if (empty($signatureParams['SignerEmail']) && $this->signRequest instanceof SignRequestEntity) {
15✔
933
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
934
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
935
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
936
                        }
937
                }
938
                return $signatureParams;
15✔
939
        }
940

941
        private function addMetadataToSignatureParams(array $signatureParams): array {
942
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
943
                if (isset($signRequestMetadata['remote-address'])) {
15✔
944
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
945
                }
946
                if (isset($signRequestMetadata['user-agent'])) {
15✔
947
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
948
                }
949
                return $signatureParams;
15✔
950
        }
951

952
        public function storeUserMetadata(array $metadata = []): self {
953
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
954
                if (!$collectMetadata || !$metadata) {
18✔
955
                        return $this;
7✔
956
                }
957
                $this->signRequest->setMetadata(array_merge(
11✔
958
                        $this->signRequest->getMetadata() ?? [],
11✔
959
                        $metadata,
11✔
960
                ));
11✔
961
                $this->signRequestMapper->update($this->signRequest);
11✔
962
                return $this;
11✔
963
        }
964

965
        /**
966
         * @return SignRequestEntity[]
967
         */
968
        protected function getSigners(): array {
969
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
970
        }
971

972
        protected function setNewStatusIfNecessary(FileEntity $libreSignFile): bool {
973
                $newStatus = $this->evaluateStatusFromSigners();
9✔
974

975
                if ($newStatus === null || $newStatus === $libreSignFile->getStatus()) {
9✔
976
                        return false;
3✔
977
                }
978

979
                $libreSignFile->setStatus($newStatus);
6✔
980

981
                return true;
6✔
982
        }
983

984
        private function updateEntityCacheAfterDbSave(FileEntity $file): void {
985
                $this->statusService->cacheFileStatus($file);
1✔
986
        }
987

988
        private function evaluateStatusFromSigners(): ?int {
989
                $signers = $this->getSigners();
9✔
990

991
                $total = count($signers);
9✔
992

993
                if ($total === 0) {
9✔
994
                        return null;
1✔
995
                }
996

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

999
                if ($totalSigned === $total) {
8✔
1000
                        return FileStatus::SIGNED->value;
4✔
1001
                }
1002

1003
                if ($totalSigned > 0) {
4✔
1004
                        return FileStatus::PARTIAL_SIGNED->value;
3✔
1005
                }
1006

1007
                return null;
1✔
1008
        }
1009

1010
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
1011
                $result = $this->pfxProvider->getOrGeneratePfx(
13✔
1012
                        $engine,
13✔
1013
                        $this->signWithoutPassword,
13✔
1014
                        $this->signatureMethodName,
13✔
1015
                        $this->userUniqueIdentifier,
13✔
1016
                        $this->friendlyName,
13✔
1017
                        $this->password,
13✔
1018
                );
13✔
1019
                if ($result['password'] !== null) {
13✔
1020
                        $this->setPassword($result['password']);
2✔
1021
                }
1022
                return $result['pfx'];
13✔
1023
        }
1024

1025
        protected function readCertificate(): array {
1026
                return $this->getEngine()
×
1027
                        ->readCertificate();
×
1028
        }
1029

1030
        /**
1031
         * Get file to sign
1032
         *
1033
         * @throws LibresignException
1034
         */
1035
        protected function getFileToSign(): File {
1036
                if ($this->fileToSign instanceof File) {
×
1037
                        return $this->fileToSign;
×
1038
                }
1039

1040
                $userId = $this->libreSignFile->getUserId()
×
1041
                        ?? $this->user?->getUID()
×
1042
                        ?? ($this->signRequest?->getUserId() ?? null);
×
1043
                $nodeId = $this->libreSignFile->getNodeId();
×
1044

1045
                if ($userId === null) {
×
1046
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1047
                }
1048

1049
                try {
1050
                        $originalFile = $this->getNodeByIdUsingUid($userId, $nodeId);
×
1051
                } catch (\Throwable $e) {
×
1052
                        $this->logger->error('[file-access] FAILED to find file - userId={userId} nodeId={nodeId} error={error}', [
×
1053
                                'userId' => $userId,
×
1054
                                'nodeId' => $nodeId,
×
1055
                                'error' => $e->getMessage(),
×
1056
                        ]);
×
1057
                        throw $e;
×
1058
                }
1059

1060
                if ($originalFile->getOwner()->getUID() !== $userId) {
×
1061
                        $originalFile = $this->getNodeByIdUsingUid($originalFile->getOwner()->getUID(), $nodeId);
×
1062
                }
1063
                if ($this->isPdf($originalFile)) {
×
1064
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
1065
                } else {
1066
                        $this->fileToSign = $originalFile;
×
1067
                }
1068
                return $this->fileToSign;
×
1069
        }
1070

1071
        private function isPdf(File $file): bool {
1072
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
1073
        }
1074

1075
        protected function getEngine(): SignEngineHandler {
1076
                if (!$this->engine) {
12✔
1077
                        $originalFile = $this->getFileToSign();
12✔
1078
                        $this->engine = $this->identifyEngine($originalFile);
12✔
1079

1080
                        $this->configureEngine();
12✔
1081
                }
1082
                return $this->engine;
12✔
1083
        }
1084

1085
        private function configureEngine(): void {
1086
                $this->engine
12✔
1087
                        ->setInputFile($this->getFileToSign())
12✔
1088
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
1089
                        ->setPassword($this->password);
12✔
1090

1091
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
1092
                        $this->engine
2✔
1093
                                ->setVisibleElements($this->getVisibleElements())
2✔
1094
                                ->setSignatureParams($this->getSignatureParams());
2✔
1095
                }
1096
        }
1097

1098
        public function getLibresignFile(?int $fileId, ?string $signRequestUuid = null): FileEntity {
1099
                try {
1100
                        if ($fileId) {
3✔
1101
                                return $this->fileMapper->getById($fileId);
1✔
1102
                        }
1103

1104
                        if ($signRequestUuid) {
2✔
1105
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
1106
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
1107
                        }
1108

1109
                        throw new \Exception('Invalid arguments');
×
1110

1111
                } catch (DoesNotExistException) {
1✔
1112
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
1113
                }
1114
        }
1115

1116
        public function renew(SignRequestEntity $signRequest, string $method): void {
1117
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1118
                if (empty($identifyMethods[$method])) {
×
1119
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1120
                }
1121

1122
                $signRequest->setUuid(UUIDUtil::getUUID());
×
1123
                $this->signRequestMapper->update($signRequest);
×
1124

1125
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
1126
                        $entity = $identifyMethod->getEntity();
×
1127
                        $entity->setAttempts($entity->getAttempts() + 1);
×
1128
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
1129
                        $identifyMethod->save();
×
1130
                }, $identifyMethods[$method]);
×
1131
        }
1132

1133
        public function requestCode(
1134
                SignRequestEntity $signRequest,
1135
                string $identifyMethodName,
1136
                string $signMethodName,
1137
                string $identify = '',
1138
        ): void {
1139
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1140
                if (empty($identifyMethods[$identifyMethodName])) {
×
1141
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
1142
                }
1143
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
1144
                        try {
1145
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
1146
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
1147
                        } catch (InvalidArgumentException) {
×
1148
                                continue;
×
1149
                        }
1150
                        /** @var IToken $signatureMethod */
1151
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
1152
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
1153
                        return;
×
1154
                }
1155
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
1156
        }
1157

1158
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
1159
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
1160
                try {
1161
                        if ($libresignFile->isEnvelope()) {
2✔
1162
                                $childFiles = $this->fileMapper->getChildrenFiles($libresignFile->getId());
×
1163
                                $allSignRequests = [];
×
1164
                                foreach ($childFiles as $childFile) {
×
1165
                                        $childSignRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
1166
                                        $allSignRequests = array_merge($allSignRequests, $childSignRequests);
×
1167
                                }
1168
                                $signRequests = $allSignRequests;
×
1169
                        } else {
1170
                                $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
1171
                        }
1172

1173
                        if (!empty($signRequestUuid)) {
2✔
1174
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
1175
                        } else {
1176
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
1177
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
1178
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
1179
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
1180
                                                        && $user
1181
                                                        && (
1182
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
1183
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
1184
                                                        )
1185
                                                ) {
1186
                                                        return true;
×
1187
                                                }
1188
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
1189
                                                        && $user
1190
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
1191
                                                ) {
1192
                                                        return true;
×
1193
                                                }
1194
                                                return false;
×
1195
                                        });
×
1196
                                        if (count($found) > 0) {
×
1197
                                                return $signRequest;
×
1198
                                        }
1199
                                        return $carry;
×
1200
                                });
×
1201
                        }
1202

1203
                        if (!$signRequest) {
2✔
1204
                                throw new DoesNotExistException('Sign request not found');
×
1205
                        }
1206
                        $signRequestFile = $libresignFile;
2✔
1207
                        if ($signRequestFile->getId() !== $signRequest->getFileId()) {
2✔
1208
                                $signRequestFile = $this->fileMapper->getById($signRequest->getFileId());
×
1209
                        }
1210
                        $this->sequentialSigningService->setFile($signRequestFile);
2✔
1211
                        if (
1212
                                $this->sequentialSigningService->isOrderedNumericFlow()
2✔
1213
                                && $this->sequentialSigningService->hasPendingLowerOrderSigners(
2✔
1214
                                        $signRequest->getFileId(),
2✔
1215
                                        $signRequest->getSigningOrder()
2✔
1216
                                )
2✔
1217
                        ) {
1218
                                throw new LibresignException(json_encode([
×
1219
                                        'action' => JSActions::ACTION_DO_NOTHING,
×
1220
                                        'errors' => [['message' => $this->l10n->t('You are not allowed to sign this document yet')]],
×
1221
                                ]));
×
1222
                        }
1223
                        if ($signRequest->getSigned()) {
2✔
1224
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
1225
                        }
1226
                        return $signRequest;
2✔
1227
                } catch (DoesNotExistException) {
×
1228
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1229
                }
1230
        }
1231

1232
        protected function getPdfToSign(File $originalFile): File {
1233
                $file = $this->getSignedFile();
×
1234
                if ($file instanceof File) {
×
1235
                        return $file;
×
1236
                }
1237

1238
                $originalContent = $originalFile->getContent();
×
1239

1240
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
1241
                        return $this->createSignedFile($originalFile, $originalContent);
×
1242
                }
1243
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
1244
                $footer = $this->footerHandler
×
1245
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
1246
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
1247
                                'displayName' => $signer->getDisplayName(),
×
1248
                                'signed' => $signer->getSigned()
×
1249
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
1250
                                        : null,
1251
                        ], $this->getSigners()))
×
1252
                        ->getFooter($metadata['d']);
×
1253
                if ($footer) {
×
1254
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
1255
                        file_put_contents($stamp, $footer);
×
1256

1257
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
1258
                        file_put_contents($input, $originalContent);
×
1259

1260
                        try {
1261
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
1262
                        } catch (RuntimeException $e) {
×
1263
                                throw new LibresignException($e->getMessage());
×
1264
                        }
1265
                } else {
1266
                        $pdfContent = $originalContent;
×
1267
                }
1268
                return $this->createSignedFile($originalFile, $pdfContent);
×
1269
        }
1270

1271
        protected function getSignedFile(): ?File {
1272
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
1273
                if (!$nodeId) {
3✔
1274
                        return null;
1✔
1275
                }
1276

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

1279
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
1280
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
1281
                }
1282
                return $fileToSign;
2✔
1283
        }
1284

1285
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
1286
                try {
1287
                        $userFolder = $this->root->getUserFolder($uid);
4✔
1288
                } catch (NoUserException $e) {
2✔
1289
                        $this->logger->error('[file-access] NoUserException for uid={uid}', ['uid' => $uid]);
1✔
1290
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
1291
                } catch (NotPermittedException $e) {
1✔
1292
                        $this->logger->error('[file-access] NotPermittedException for uid={uid}', ['uid' => $uid]);
1✔
1293
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
1294
                }
1295

1296
                try {
1297
                        $fileToSign = $userFolder->getFirstNodeById($nodeId);
2✔
1298
                } catch (\Throwable $e) {
×
1299
                        $this->logger->error('[file-access] Failed getFirstNodeById - nodeId={nodeId} error={error}', [
×
1300
                                'nodeId' => $nodeId,
×
1301
                                'error' => $e->getMessage(),
×
1302
                        ]);
×
1303
                        throw $e;
×
1304
                }
1305

1306
                if (!$fileToSign instanceof File) {
2✔
1307
                        $this->logger->error('[file-access] Node is not a File - nodeId={nodeId} type={type}', [
1✔
1308
                                'nodeId' => $nodeId,
1✔
1309
                                'type' => $fileToSign ? get_class($fileToSign) : 'NULL',
1✔
1310
                        ]);
1✔
1311
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
1312
                }
1313
                return $fileToSign;
1✔
1314
        }
1315

1316
        /**
1317
         * Verify if file exists in filesystem before enqueuing background job
1318
         *
1319
         * @param string|null $uid User ID
1320
         * @param int $nodeId File node ID
1321
         * @return bool True if file exists and is accessible
1322
         */
1323
        private function verifyFileExists(?string $uid, int $nodeId): bool {
1324
                if ($uid === null || $nodeId === 0) {
1✔
1325
                        return false;
×
1326
                }
1327

1328
                try {
1329
                        $userFolder = $this->root->getUserFolder($uid);
1✔
1330
                        $node = $userFolder->getFirstNodeById($nodeId);
1✔
1331
                        return $node instanceof File;
1✔
1332
                } catch (\Throwable $e) {
×
1333
                        $this->logger->warning('[verify-file] File not accessible - nodeId={nodeId} uid={uid} error={error}', [
×
1334
                                'nodeId' => $nodeId,
×
1335
                                'uid' => $uid,
×
1336
                                'error' => $e->getMessage(),
×
1337
                        ]);
×
1338
                        return false;
×
1339
                }
1340
        }
1341

1342
        private function cleanupUnsignedSignedFile(): void {
1343
                if (!$this->createdSignedFile instanceof File) {
×
1344
                        return;
×
1345
                }
1346

1347
                try {
1348
                        $this->createdSignedFile->delete();
×
1349
                } catch (\Throwable $e) {
×
1350
                        $this->logger->warning('Failed to delete temporary signed file: ' . $e->getMessage());
×
1351
                } finally {
1352
                        $this->createdSignedFile = null;
×
1353
                }
1354
        }
1355

1356
        private function createSignedFile(File $originalFile, string $content): File {
1357
                $filename = preg_replace(
×
1358
                        '/' . $originalFile->getExtension() . '$/',
×
1359
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
1360
                        basename($originalFile->getPath())
×
1361
                );
×
1362
                $owner = $originalFile->getOwner()->getUID();
×
1363

1364
                $fileId = $this->libreSignFile->getId();
×
1365
                $extension = $originalFile->getExtension();
×
1366
                $uniqueFilename = substr($filename, 0, -strlen($extension) - 1) . '_' . $fileId . '.' . $extension;
×
1367

1368
                try {
1369
                        /** @var \OCP\Files\Folder */
1370
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
1371

1372
                        $this->createdSignedFile = $parentFolder->newFile($uniqueFilename, $content);
×
1373

1374
                        return $this->createdSignedFile;
×
1375
                } catch (NotPermittedException) {
×
1376
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
1377
                } catch (\Exception $e) {
×
1378
                        throw $e;
×
1379
                }
1380
        }
1381

1382
        /**
1383
         * @throws DoesNotExistException
1384
         */
1385
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1386
                $this->validateHelper->validateUuidFormat($uuid);
4✔
1387
                return $this->signRequestMapper->getByUuid($uuid);
3✔
1388
        }
1389

1390
        /**
1391
         * @throws DoesNotExistException
1392
         */
1393
        public function getFile(int $signRequestId): FileEntity {
1394
                return $this->fileMapper->getById($signRequestId);
×
1395
        }
1396

1397
        /**
1398
         * @throws DoesNotExistException
1399
         */
1400
        public function getFileByUuid(string $uuid): FileEntity {
1401
                return $this->fileMapper->getByUuid($uuid);
×
1402
        }
1403

1404
        public function getIdDocById(int $fileId): IdDocs {
1405
                return $this->idDocsMapper->getByFileId($fileId);
×
1406
        }
1407

1408
        /**
1409
         * @return File[] Array of files
1410
         */
1411
        public function getNextcloudFiles(FileEntity $fileData): array {
1412
                if ($fileData->getNodeType() === 'envelope') {
1✔
1413
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1414
                        $files = [];
×
1415
                        foreach ($children as $child) {
×
1416
                                $nodeId = $child->getNodeId();
×
1417
                                if ($nodeId === null) {
×
1418
                                        throw new LibresignException(json_encode([
×
1419
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1420
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1421
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1422
                                }
1423
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1424
                                if ($file instanceof File) {
×
1425
                                        $files[] = $file;
×
1426
                                }
1427
                        }
1428
                        return $files;
×
1429
                }
1430

1431
                $nodeId = $fileData->getNodeId();
1✔
1432
                if ($nodeId === null) {
1✔
1433
                        throw new LibresignException(json_encode([
1✔
1434
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1435
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1436
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1437
                }
1438
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1439
                if (!$fileToSign instanceof File) {
×
1440
                        throw new LibresignException(json_encode([
×
1441
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1442
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1443
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1444
                }
1445
                return [$fileToSign];
×
1446
        }
1447

1448
        /**
1449
         * @return array<FileEntity>
1450
         */
1451
        public function getNextcloudFilesWithEntities(FileEntity $fileData): array {
1452
                if ($fileData->getNodeType() === 'envelope') {
×
1453
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1454
                        $result = [];
×
1455
                        foreach ($children as $child) {
×
1456
                                $nodeId = $child->getNodeId();
×
1457
                                if ($nodeId === null) {
×
1458
                                        throw new LibresignException(json_encode([
×
1459
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1460
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1461
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1462
                                }
1463
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1464
                                if ($file instanceof File) {
×
1465
                                        $result[] = $child;
×
1466
                                }
1467
                        }
1468
                        return $result;
×
1469
                }
1470

1471
                $nodeId = $fileData->getNodeId();
×
1472
                if ($nodeId === null) {
×
1473
                        throw new LibresignException(json_encode([
×
1474
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1475
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1476
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1477
                }
1478
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1479
                if (!$fileToSign instanceof File) {
×
1480
                        throw new LibresignException(json_encode([
×
1481
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1482
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1483
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1484
                }
1485
                return [$fileData];
×
1486
        }
1487

1488
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1489
                $this->validateHelper->validateSigner($uuid, $user);
×
1490
        }
1491

1492
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1493
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1494
        }
1495

1496
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1497
                $return = ['user' => ['name' => null]];
×
1498
                if ($signRequest) {
×
1499
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1500
                } elseif ($user) {
×
1501
                        $return['user']['name'] = $user->getDisplayName();
×
1502
                }
1503
                return $return;
×
1504
        }
1505

1506
        public function getAvailableIdentifyMethodsFromSettings(): array {
1507
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1508
                $return = array_map(fn (array $identifyMethod): array => [
×
1509
                        'mandatory' => $identifyMethod['mandatory'],
×
1510
                        'identifiedAtDate' => null,
×
1511
                        'validateCode' => false,
×
1512
                        'method' => $identifyMethod['name'],
×
1513
                ], $identifyMethods);
×
1514
                return $return;
×
1515
        }
1516

1517
        public function getFileUrl(int $fileId, string $uuid): string {
1518
                try {
1519
                        $this->idDocsMapper->getByFileId($fileId);
×
1520
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1521
                } catch (DoesNotExistException) {
×
1522
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1523
                }
1524
        }
1525

1526
        /**
1527
         * Get PDF URLs for signing
1528
         * For envelopes: returns URLs for all child files
1529
         * For regular files: returns URL for the file itself
1530
         *
1531
         * @return string[]
1532
         */
1533
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1534
                if (!$fileEntity->isEnvelope()) {
×
1535
                        return [
×
1536
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1537
                        ];
×
1538
                }
1539

1540
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1541
                        $fileEntity->getId(),
×
1542
                        $signRequestEntity->getId()
×
1543
                );
×
1544

1545
                $pdfUrls = [];
×
1546
                foreach ($childSignRequests as $childSignRequest) {
×
1547
                        $pdfUrls[] = $this->getFileUrl(
×
1548
                                $childSignRequest->getFileId(),
×
1549
                                $childSignRequest->getUuid()
×
1550
                        );
×
1551
                }
1552

1553
                return $pdfUrls;
×
1554
        }
1555

1556
        private function recordSignatureAttempt(Exception $exception): void {
1557
                if (!$this->libreSignFile) {
×
1558
                        return;
×
1559
                }
1560

1561
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1562

1563
                if (!isset($metadata['signature_attempts'])) {
×
1564
                        $metadata['signature_attempts'] = [];
×
1565
                }
1566

1567
                $attempt = [
×
1568
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1569
                        'engine' => $this->engine ? get_class($this->engine) : 'unknown',
×
1570
                        'error_message' => $exception->getMessage(),
×
1571
                        'error_code' => $exception->getCode(),
×
1572
                ];
×
1573

1574
                $metadata['signature_attempts'][] = $attempt;
×
1575
                $this->libreSignFile->setMetadata($metadata);
×
1576
                $this->fileMapper->update($this->libreSignFile);
×
1577
        }
1578
}
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