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

LibreSign / libresign / 21337895635

25 Jan 2026 07:02PM UTC coverage: 45.433%. First build
21337895635

Pull #6572

github

web-flow
Merge 920e90605 into 14d0dcc48
Pull Request #6572: fix: load visible elements at parallel jobs

9 of 10 new or added lines in 1 file covered. (90.0%)

7476 of 16455 relevant lines covered (45.43%)

4.97 hits per line

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

52.44
/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 OCP\AppFramework\Db\DoesNotExistException;
46
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
47
use OCP\AppFramework\Utility\ITimeFactory;
48
use OCP\BackgroundJob\IJobList;
49
use OCP\EventDispatcher\IEventDispatcher;
50
use OCP\Files\File;
51
use OCP\Files\IRootFolder;
52
use OCP\Files\NotPermittedException;
53
use OCP\Http\Client\IClientService;
54
use OCP\IAppConfig;
55
use OCP\ICache;
56
use OCP\ICacheFactory;
57
use OCP\IDateTimeZone;
58
use OCP\IL10N;
59
use OCP\ITempManager;
60
use OCP\IURLGenerator;
61
use OCP\IUser;
62
use OCP\IUserSession;
63
use OCP\Security\ICredentialsManager;
64
use OCP\Security\ISecureRandom;
65
use Psr\Log\LoggerInterface;
66
use RuntimeException;
67
use Sabre\DAV\UUIDUtil;
68

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

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

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

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

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

195
        public function setUserUniqueIdentifier(string $identifier): self {
196
                $this->userUniqueIdentifier = $identifier;
7✔
197
                return $this;
7✔
198
        }
199

200
        public function setFriendlyName(string $friendlyName): self {
201
                $this->friendlyName = $friendlyName;
7✔
202
                return $this;
7✔
203
        }
204

205
        /**
206
         * @return static
207
         */
208
        public function setSignRequest(SignRequestEntity $signRequest): self {
209
                $this->signRequest = $signRequest;
75✔
210
                return $this;
75✔
211
        }
212

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

221
        public function setSignatureMethod(?string $signatureMethodName): self {
222
                $this->signatureMethodName = $signatureMethodName;
7✔
223
                return $this;
7✔
224
        }
225

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

234
        public function setCurrentUser(?IUser $user): self {
235
                $this->user = $user;
32✔
236
                return $this;
32✔
237
        }
238

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

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

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

273
                if (empty($list) && ($fileId === null || $signRequestId === null)) {
33✔
274
                        return $this;
18✔
275
                }
276

277
                if ($fileId === null || $signRequestId === null) {
15✔
NEW
278
                        throw new LibresignException($this->l10n->t('File not found'));
×
279
                }
280

281
                $fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
15✔
282
                $canCreateSignature = $this->signerElementsService->canCreateSignature();
15✔
283

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

288
                return $this;
6✔
289
        }
290

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

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

299
                return $this->bindFileElementWithTempFile($fileElement, $nodeId);
8✔
300
        }
301

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

307
                return $this->retrieveUserElement($fileElement);
×
308
        }
309

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

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

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

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

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

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

377
                return null;
6✔
378
        }
379

380
        public function getVisibleElements(): array {
381
                return $this->elements;
8✔
382
        }
383

384
        public function getJobArgumentsWithoutCredentials(): array {
385
                $args = [];
×
386

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

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

395
                if (!empty($this->elements)) {
×
396
                        $args['visibleElements'] = $this->elements;
×
397
                }
398

399
                if ($this->signRequest instanceof SignRequestEntity && $this->signRequest->getMetadata()) {
×
400
                        $args['metadata'] = $this->signRequest->getMetadata();
×
401
                }
402

403
                if ($this->user instanceof IUser) {
×
404
                        $args['userId'] = $this->user->getUID();
×
405
                }
406

407
                return $args;
×
408
        }
409

410
        public function validateSigningRequirements(): void {
411
                $this->tsaValidationService->validateConfiguration();
×
412
        }
413

414
        public function sign(): void {
415
                $signRequests = $this->getSignRequestsToSign();
18✔
416

417
                if (empty($signRequests)) {
18✔
418
                        throw new LibresignException('No sign requests found to process');
×
419
                }
420

421
                $this->executeSigningStrategy($signRequests);
18✔
422
        }
423

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

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

436
        private function getLatestSignedDate(array $signRequests): ?DateTimeInterface {
437
                $latestSignedDate = null;
×
438

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

449
                return $latestSignedDate;
×
450
        }
451

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

456
                if ($libreSignFile->getSignedHash()) {
×
457
                        $this->restoreCachedState($previousState);
×
458
                        return;
×
459
                }
460

461
                $previousLibreSignFile = $this->libreSignFile;
×
462
                $previousSignRequest = $this->signRequest;
×
463
                $this->libreSignFile = $libreSignFile;
×
464
                $this->signRequest = $signRequest;
×
465

466
                try {
467
                        $this->validateDocMdpAllowsSignatures();
×
468

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

477
                        $hash = $this->computeHash($signedFile);
×
478
                        $this->updateSignRequest($hash);
×
479
                        $this->updateLibreSignFile($libreSignFile, $signedFile->getId(), $hash);
×
480

481
                        $this->dispatchSignedEvent();
×
482

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

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

506
        private function resetCachedState(): void {
507
                $this->fileToSign = null;
×
508
                $this->createdSignedFile = null;
×
509
                $this->engine = null;
×
510
        }
511

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

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

520
                if (empty($signRequests)) {
1✔
521
                        throw new LibresignException('No sign requests found to process');
×
522
                }
523

524
                $enqueued = 0;
1✔
525
                foreach ($signRequests as $signRequestData) {
1✔
526
                        $file = $signRequestData['file'];
1✔
527
                        $signRequest = $signRequestData['signRequest'];
1✔
528

529
                        if ($file->getSignedHash()) {
1✔
530
                                continue;
×
531
                        }
532

533
                        $nodeId = $file->getNodeId();
1✔
534
                        $userId = $file->getUserId() ?? $signRequest->getUserId();
1✔
535

536
                        if ($nodeId === null || !$this->verifyFileExists($userId, $nodeId)) {
1✔
537
                                continue;
×
538
                        }
539

540
                        $this->enqueueSigningJobForFile($signRequest, $file, $jobArguments);
1✔
541
                        $enqueued++;
1✔
542
                }
543

544
                return $enqueued;
1✔
545
        }
546

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

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

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

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

576
                return $args;
1✔
577
        }
578

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

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

596
                        $this->validateDocMdpAllowsSignatures();
18✔
597

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

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

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

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

617
                        $this->dispatchSignedEvent();
16✔
618
                }
619

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

628
                return $envelopeLastSignedDate;
16✔
629
        }
630

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

644
                return $this->buildEnvelopeSignRequests();
1✔
645
        }
646

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

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

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

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

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

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

684
                return $signRequestsData;
1✔
685
        }
686

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

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

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

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

719
                return $result;
×
720
        }
721

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

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

733
                $this->handleSignedEnvelopeSignRequest($envelope, $envelopeSignRequest, $signedDate, $status);
1✔
734

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

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

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

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

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

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

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

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

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

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

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

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

834
                $this->signRequestMapper->update($this->signRequest);
14✔
835

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

844
        protected function updateLibreSignFile(FileEntity $libreSignFile, int $nodeId, string $hash): void {
845
                $libreSignFile->setSignedNodeId($nodeId);
14✔
846
                $libreSignFile->setSignedHash($hash);
14✔
847
                $this->setNewStatusIfNecessary($libreSignFile);
14✔
848
                $meta = $libreSignFile->getMetadata() ?? [];
14✔
849
                $meta['status_changed_at'] = (new \DateTime())->format(\DateTimeInterface::ATOM);
14✔
850
                $libreSignFile->setMetadata($meta);
14✔
851
                $this->fileMapper->update($libreSignFile);
14✔
852
                $this->updateCacheAfterDbSave($libreSignFile); // Update cache AFTER DB save
14✔
853

854
                if ($libreSignFile->hasParent()) {
14✔
855
                        $this->fileStatusService->propagateStatusToParent($libreSignFile->getParentFileId());
×
856
                }
857
        }
858

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

877
                $event = $this->signedEventFactory->make(
14✔
878
                        $this->signRequest,
14✔
879
                        $this->libreSignFile,
14✔
880
                        $this->getEngine()->getInputFile(),
14✔
881
                        $this->signWithoutPassword,
14✔
882
                        $certificateSerialNumber,
14✔
883
                );
14✔
884
                $this->eventDispatcher->dispatchTyped($event);
14✔
885
        }
886

887
        protected function identifyEngine(File $file): SignEngineHandler {
888
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
889
        }
890

891
        protected function getSignatureParams(): array {
892
                $certificateData = $this->readCertificate();
15✔
893
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
894
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
895
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
896
                return $signatureParams;
15✔
897
        }
898

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

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

931
        private function addMetadataToSignatureParams(array $signatureParams): array {
932
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
933
                if (isset($signRequestMetadata['remote-address'])) {
15✔
934
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
935
                }
936
                if (isset($signRequestMetadata['user-agent'])) {
15✔
937
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
938
                }
939
                return $signatureParams;
15✔
940
        }
941

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

955
        /**
956
         * @return SignRequestEntity[]
957
         */
958
        protected function getSigners(): array {
959
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
960
        }
961

962
        protected function setNewStatusIfNecessary(FileEntity $libreSignFile): bool {
963
                $newStatus = $this->evaluateStatusFromSigners();
10✔
964

965
                if ($newStatus === null || $newStatus === $libreSignFile->getStatus()) {
10✔
966
                        return false;
4✔
967
                }
968

969
                $libreSignFile->setStatus($newStatus);
6✔
970

971
                return true;
6✔
972
        }
973

974
        private function updateCacheAfterDbSave(FileEntity $libreSignFile): void {
975
                $cacheKey = 'status_' . $libreSignFile->getUuid();
14✔
976
                $status = $libreSignFile->getStatus();
14✔
977
                $this->cache->set($cacheKey, $status, 60); // Cache for 60 seconds
14✔
978
        }
979

980
        private function updateEntityCacheAfterDbSave(FileEntity $file): void {
981
                $cacheKey = 'status_' . $file->getUuid();
1✔
982
                $status = $file->getStatus();
1✔
983
                $this->cache->set($cacheKey, $status, 60);
1✔
984
        }
985

986
        private function evaluateStatusFromSigners(): ?int {
987
                $signers = $this->getSigners();
10✔
988

989
                $total = count($signers);
10✔
990

991
                if ($total === 0) {
10✔
992
                        return null;
1✔
993
                }
994

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

997
                if ($totalSigned === $total) {
9✔
998
                        return FileStatus::SIGNED->value;
5✔
999
                }
1000

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

1005
                return null;
1✔
1006
        }
1007

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1107
                        throw new \Exception('Invalid arguments');
×
1108

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

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

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

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

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

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

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

1201
                        if (!$signRequest) {
2✔
1202
                                throw new DoesNotExistException('Sign request not found');
×
1203
                        }
1204
                        if ($signRequest->getSigned()) {
2✔
1205
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
1206
                        }
1207
                        return $signRequest;
2✔
1208
                } catch (DoesNotExistException) {
×
1209
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
1210
                }
1211
        }
1212

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

1219
                $originalContent = $originalFile->getContent();
×
1220

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

1238
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
1239
                        file_put_contents($input, $originalContent);
×
1240

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

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

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

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

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

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

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

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

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

1323
        private function cleanupUnsignedSignedFile(): void {
1324
                if (!$this->createdSignedFile instanceof File) {
×
1325
                        return;
×
1326
                }
1327

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

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

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

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

1353
                        $this->createdSignedFile = $parentFolder->newFile($uniqueFilename, $content);
×
1354

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

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

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

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

1385
        public function getIdDocById(int $fileId): IdDocs {
1386
                return $this->idDocsMapper->getByFileId($fileId);
×
1387
        }
1388

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

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

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

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

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

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

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

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

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

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

1521
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1522
                        $fileEntity->getId(),
×
1523
                        $signRequestEntity->getId()
×
1524
                );
×
1525

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

1534
                return $pdfUrls;
×
1535
        }
1536

1537
        private function recordSignatureAttempt(Exception $exception): void {
1538
                if (!$this->libreSignFile) {
×
1539
                        return;
×
1540
                }
1541

1542
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1543

1544
                if (!isset($metadata['signature_attempts'])) {
×
1545
                        $metadata['signature_attempts'] = [];
×
1546
                }
1547

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

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