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

LibreSign / libresign / 20816247002

08 Jan 2026 12:06PM UTC coverage: 44.659%. First build
20816247002

Pull #6409

github

web-flow
Merge dad0e1564 into d7326b5f4
Pull Request #6409: fix: remove cache of signRequest

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

6731 of 15072 relevant lines covered (44.66%)

5.02 hits per line

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

51.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\DataObjects\VisibleElementAssoc;
19
use OCA\Libresign\Db\File as FileEntity;
20
use OCA\Libresign\Db\FileElement;
21
use OCA\Libresign\Db\FileElementMapper;
22
use OCA\Libresign\Db\FileMapper;
23
use OCA\Libresign\Db\IdDocs;
24
use OCA\Libresign\Db\IdDocsMapper;
25
use OCA\Libresign\Db\IdentifyMethod;
26
use OCA\Libresign\Db\IdentifyMethodMapper;
27
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
28
use OCA\Libresign\Db\SignRequestMapper;
29
use OCA\Libresign\Db\UserElementMapper;
30
use OCA\Libresign\Events\SignedEventFactory;
31
use OCA\Libresign\Exception\LibresignException;
32
use OCA\Libresign\Handler\DocMdpHandler;
33
use OCA\Libresign\Handler\FooterHandler;
34
use OCA\Libresign\Handler\PdfTk\Pdf;
35
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
36
use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
37
use OCA\Libresign\Handler\SignEngine\SignEngineHandler;
38
use OCA\Libresign\Helper\JSActions;
39
use OCA\Libresign\Helper\ValidateHelper;
40
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
41
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
42
use OCP\AppFramework\Db\DoesNotExistException;
43
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
44
use OCP\AppFramework\Utility\ITimeFactory;
45
use OCP\EventDispatcher\IEventDispatcher;
46
use OCP\Files\File;
47
use OCP\Files\IRootFolder;
48
use OCP\Files\NotPermittedException;
49
use OCP\Http\Client\IClientService;
50
use OCP\IAppConfig;
51
use OCP\IDateTimeZone;
52
use OCP\IL10N;
53
use OCP\ITempManager;
54
use OCP\IURLGenerator;
55
use OCP\IUser;
56
use OCP\IUserManager;
57
use OCP\IUserSession;
58
use OCP\Security\Events\GenerateSecurePasswordEvent;
59
use OCP\Security\ISecureRandom;
60
use Psr\Log\LoggerInterface;
61
use RuntimeException;
62
use Sabre\DAV\UUIDUtil;
63

64
class SignFileService {
65
        private ?SignRequestEntity $signRequest = null;
66
        private string $password = '';
67
        private ?FileEntity $libreSignFile = null;
68
        /** @var VisibleElementAssoc[] */
69
        private $elements = [];
70
        private bool $signWithoutPassword = false;
71
        private ?File $fileToSign = null;
72
        private string $userUniqueIdentifier = '';
73
        private string $friendlyName = '';
74
        private ?IUser $user = null;
75
        private ?SignEngineHandler $engine = null;
76

77
        public function __construct(
78
                protected IL10N $l10n,
79
                private FileMapper $fileMapper,
80
                private SignRequestMapper $signRequestMapper,
81
                private IdDocsMapper $idDocsMapper,
82
                private FooterHandler $footerHandler,
83
                protected FolderService $folderService,
84
                private IClientService $client,
85
                private IUserManager $userManager,
86
                protected LoggerInterface $logger,
87
                private IAppConfig $appConfig,
88
                protected ValidateHelper $validateHelper,
89
                private SignerElementsService $signerElementsService,
90
                private IRootFolder $root,
91
                private IUserSession $userSession,
92
                private IDateTimeZone $dateTimeZone,
93
                private FileElementMapper $fileElementMapper,
94
                private UserElementMapper $userElementMapper,
95
                private IEventDispatcher $eventDispatcher,
96
                protected ISecureRandom $secureRandom,
97
                private IURLGenerator $urlGenerator,
98
                private IdentifyMethodMapper $identifyMethodMapper,
99
                private ITempManager $tempManager,
100
                private IdentifyMethodService $identifyMethodService,
101
                private ITimeFactory $timeFactory,
102
                protected SignEngineFactory $signEngineFactory,
103
                private SignedEventFactory $signedEventFactory,
104
                private Pdf $pdf,
105
                private DocMdpHandler $docMdpHandler,
106
                private PdfSignatureDetectionService $pdfSignatureDetectionService,
107
                private SequentialSigningService $sequentialSigningService,
108
                private FileStatusService $fileStatusService,
109
        ) {
110
        }
139✔
111

112
        /**
113
         * Can delete sing request
114
         */
115
        public function canDeleteRequestSignature(array $data): void {
116
                if (!empty($data['uuid'])) {
2✔
117
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
2✔
118
                } elseif (!empty($data['file']['fileId'])) {
×
119
                        $signatures = $this->signRequestMapper->getByNodeId($data['file']['fileId']);
×
120
                } else {
121
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
122
                }
123
                $signed = array_filter($signatures, fn ($s) => $s->getSigned());
2✔
124
                if ($signed) {
2✔
125
                        throw new \Exception($this->l10n->t('Document already signed'));
1✔
126
                }
127
                array_walk($data['users'], function ($user) use ($signatures): void {
1✔
128
                        $exists = array_filter($signatures, function (SignRequestEntity $signRequest) use ($user) {
1✔
129
                                $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($signRequest->getId());
1✔
130
                                if ($identifyMethod->getName() === 'email') {
1✔
131
                                        return $identifyMethod->getEntity()->getIdentifierValue() === $user['email'];
×
132
                                }
133
                                return false;
1✔
134
                        });
1✔
135
                        if (!$exists) {
1✔
136
                                throw new \Exception($this->l10n->t('No signature was requested to %s', $user['email']));
1✔
137
                        }
138
                });
1✔
139
        }
140

141
        public function notifyCallback(File $file): void {
142
                $uri = $this->libreSignFile->getCallback();
1✔
143
                if (!$uri) {
1✔
144
                        $uri = $this->appConfig->getValueString(Application::APP_ID, 'webhook_sign_url');
×
145
                        if (!$uri) {
×
146
                                return;
×
147
                        }
148
                }
149
                $options = [
1✔
150
                        'multipart' => [
1✔
151
                                [
1✔
152
                                        'name' => 'uuid',
1✔
153
                                        'contents' => $this->libreSignFile->getUuid(),
1✔
154
                                ],
1✔
155
                                [
1✔
156
                                        'name' => 'status',
1✔
157
                                        'contents' => $this->libreSignFile->getStatus(),
1✔
158
                                ],
1✔
159
                                [
1✔
160
                                        'name' => 'file',
1✔
161
                                        'contents' => $file->fopen('r'),
1✔
162
                                        'filename' => $file->getName()
1✔
163
                                ]
1✔
164
                        ]
1✔
165
                ];
1✔
166
                $this->client->newClient()->post($uri, $options);
1✔
167
        }
168

169
        /**
170
         * @return static
171
         */
172
        public function setLibreSignFile(FileEntity $libreSignFile): self {
173
                $this->libreSignFile = $libreSignFile;
39✔
174
                return $this;
39✔
175
        }
176

177
        public function setUserUniqueIdentifier(string $identifier): self {
178
                $this->userUniqueIdentifier = $identifier;
×
179
                return $this;
×
180
        }
181

182
        public function setFriendlyName(string $friendlyName): self {
183
                $this->friendlyName = $friendlyName;
×
184
                return $this;
×
185
        }
186

187
        /**
188
         * @return static
189
         */
190
        public function setSignRequest(SignRequestEntity $signRequest): self {
191
                $this->signRequest = $signRequest;
66✔
192
                return $this;
66✔
193
        }
194

195
        /**
196
         * @return static
197
         */
198
        public function setSignWithoutPassword(bool $signWithoutPassword = true): self {
199
                $this->signWithoutPassword = $signWithoutPassword;
2✔
200
                return $this;
2✔
201
        }
202

203
        /**
204
         * @return static
205
         */
206
        public function setPassword(?string $password = null): self {
207
                $this->password = $password;
2✔
208
                return $this;
2✔
209
        }
210

211
        public function setCurrentUser(?IUser $user): self {
212
                $this->user = $user;
24✔
213
                return $this;
24✔
214
        }
215

216
        public function setVisibleElements(array $list): self {
217
                if (!$this->signRequest instanceof SignRequestEntity) {
14✔
218
                        return $this;
×
219
                }
220
                $fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($this->signRequest->getFileId(), $this->signRequest->getId());
14✔
221
                $canCreateSignature = $this->signerElementsService->canCreateSignature();
14✔
222

223
                foreach ($fileElements as $fileElement) {
14✔
224
                        $this->elements[] = $this->buildVisibleElementAssoc($fileElement, $list, $canCreateSignature);
12✔
225
                }
226

227
                return $this;
5✔
228
        }
229

230
        private function buildVisibleElementAssoc(FileElement $fileElement, array $list, bool $canCreateSignature): VisibleElementAssoc {
231
                if (!$canCreateSignature) {
12✔
232
                        return new VisibleElementAssoc($fileElement);
1✔
233
                }
234

235
                $element = $this->array_find($list, fn (array $element): bool => ($element['documentElementId'] ?? '') === $fileElement->getId());
11✔
236
                $nodeId = $this->getNodeId($element, $fileElement);
11✔
237

238
                return $this->bindFileElementWithTempFile($fileElement, $nodeId);
7✔
239
        }
240

241
        private function getNodeId(?array $element, FileElement $fileElement): int {
242
                if ($this->isValidElement($element)) {
11✔
243
                        return (int)$element['profileNodeId'];
7✔
244
                }
245

246
                return $this->retrieveUserElement($fileElement);
×
247
        }
248

249
        private function isValidElement(?array $element): bool {
250
                if (is_array($element) && !empty($element['profileNodeId']) && is_int($element['profileNodeId'])) {
11✔
251
                        return true;
7✔
252
                }
253
                $this->logger->error('Invalid data provided for signing file.', ['element' => $element]);
4✔
254
                throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
4✔
255
        }
256

257
        private function retrieveUserElement(FileElement $fileElement): int {
258
                try {
259
                        if (!$this->user instanceof IUser) {
×
260
                                throw new Exception('User not set');
×
261
                        }
262
                        $userElement = $this->userElementMapper->findOne([
×
263
                                'user_id' => $this->user->getUID(),
×
264
                                'type' => $fileElement->getType(),
×
265
                        ]);
×
266
                } catch (MultipleObjectsReturnedException|DoesNotExistException|Exception) {
×
267
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
×
268
                }
269
                return $userElement->getNodeId();
×
270
        }
271

272
        private function bindFileElementWithTempFile(FileElement $fileElement, int $nodeId): VisibleElementAssoc {
273
                try {
274
                        $node = $this->getNode($nodeId);
7✔
275
                        if (!$node) {
4✔
276
                                throw new \Exception('Node content is empty or unavailable.');
4✔
277
                        }
278
                } catch (\Throwable) {
4✔
279
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
4✔
280
                }
281

282
                $tempFile = $this->tempManager->getTemporaryFile('_' . $nodeId . '.png');
3✔
283
                $content = $node->getContent();
3✔
284
                if (empty($content)) {
3✔
285
                        $this->logger->error('Failed to retrieve content for node.', ['nodeId' => $nodeId, 'fileElement' => $fileElement]);
1✔
286
                        throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
1✔
287
                }
288
                file_put_contents($tempFile, $content);
2✔
289
                return new VisibleElementAssoc($fileElement, $tempFile);
2✔
290
        }
291

292
        private function getNode(int $nodeId): ?File {
293
                if ($this->user instanceof IUser) {
7✔
294
                        return $this->folderService->getFileByNodeId($nodeId);
6✔
295
                }
296

297
                $filesOfElementes = $this->signerElementsService->getElementsFromSession();
1✔
298
                return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
1✔
299
        }
300

301
        /**
302
         * Fallback to PHP < 8.4
303
         *
304
         * Reference: https://www.php.net/manual/en/function.array-find.php#130257
305
         *
306
         * @todo remove this after minor PHP version is >= 8.4
307
         * @deprecated This method will be removed once the minimum PHP version is >= 8.4. Use native array_find instead.
308
         */
309
        private function array_find(array $array, callable $callback): mixed {
310
                foreach ($array as $key => $value) {
12✔
311
                        if ($callback($value, $key)) {
11✔
312
                                return $value;
10✔
313
                        }
314
                }
315

316
                return null;
3✔
317
        }
318

319
        /**
320
         * @return VisibleElementAssoc[]
321
         */
322
        public function getVisibleElements(): array {
323
                return $this->elements;
7✔
324
        }
325

326
        public function sign(): void {
327
                $signRequests = $this->getSignRequestsToSign();
18✔
328

329
                if (empty($signRequests)) {
18✔
330
                        throw new LibresignException('No sign requests found to process');
×
331
                }
332

333
                $envelopeLastSignedDate = null;
18✔
334

335
                foreach ($signRequests as $signRequestData) {
18✔
336
                        $this->libreSignFile = $signRequestData['file'];
18✔
337
                        if ($this->libreSignFile->getSignedHash()) {
18✔
338
                                continue;
×
339
                        }
340
                        $this->signRequest = $signRequestData['signRequest'];
18✔
341
                        $this->engine = null;
18✔
342
                        $this->elements = [];
18✔
343
                        $this->fileToSign = null;
18✔
344

345
                        $this->validateDocMdpAllowsSignatures();
18✔
346

347
                        try {
348
                                $signedFile = $this->getEngine()->sign();
16✔
349
                        } catch (LibresignException|Exception $e) {
×
350
                                $this->recordSignatureAttempt($e);
×
351
                                continue;
×
352
                        }
353

354
                        $hash = $this->computeHash($signedFile);
16✔
355
                        $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
16✔
356

357
                        $this->updateSignRequest($hash);
16✔
358
                        $this->updateLibreSignFile($signedFile->getId(), $hash);
16✔
359

360
                        $this->dispatchSignedEvent();
16✔
361
                }
362

363
                $envelopeContext = $this->getEnvelopeContext();
16✔
364
                if ($envelopeContext['envelope'] instanceof FileEntity) {
16✔
365
                        $this->updateEnvelopeStatus(
×
366
                                $envelopeContext['envelope'],
×
367
                                $envelopeContext['envelopeSignRequest'] ?? null,
×
368
                                $envelopeLastSignedDate
×
369
                        );
×
370
                }
371
        }
372

373
        /**
374
         * Get sign requests to process.
375
         *
376
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
377
         */
378
        private function getSignRequestsToSign(): array {
379
                if (!$this->libreSignFile->isEnvelope()
19✔
380
                        && !$this->libreSignFile->hasParent()
19✔
381
                ) {
382
                        return [[
18✔
383
                                'file' => $this->libreSignFile,
18✔
384
                                'signRequest' => $this->signRequest,
18✔
385
                        ]];
18✔
386
                }
387

388
                return $this->buildEnvelopeSignRequests();
1✔
389
        }
390

391
        /**
392
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
393
         */
394
        private function buildEnvelopeSignRequests(): array {
395
                $envelopeId = $this->libreSignFile->isEnvelope()
1✔
396
                        ? $this->libreSignFile->getId()
×
397
                        : $this->libreSignFile->getParentFileId();
1✔
398

399
                $childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
1✔
400
                if (empty($childFiles)) {
1✔
401
                        throw new LibresignException('No files found in envelope');
×
402
                }
403

404
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
1✔
405
                        $envelopeId,
1✔
406
                        $this->signRequest->getId()
1✔
407
                );
1✔
408

409
                if (empty($childSignRequests)) {
1✔
410
                        throw new LibresignException('No sign requests found for envelope files');
×
411
                }
412

413
                $signRequestsData = [];
1✔
414
                foreach ($childSignRequests as $childSignRequest) {
1✔
415
                        $childFile = $this->array_find(
1✔
416
                                $childFiles,
1✔
417
                                fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
1✔
418
                        );
1✔
419

420
                        if ($childFile) {
1✔
421
                                $signRequestsData[] = [
1✔
422
                                        'file' => $childFile,
1✔
423
                                        'signRequest' => $childSignRequest,
1✔
424
                                ];
1✔
425
                        }
426
                }
427

428
                return $signRequestsData;
1✔
429
        }
430

431
        /**
432
         * Get envelope context if the current file is or belongs to an envelope.
433
         *
434
         * @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
435
         */
436
        private function getEnvelopeContext(): array {
437
                $result = [
16✔
438
                        'envelope' => null,
16✔
439
                        'envelopeSignRequest' => null,
16✔
440
                ];
16✔
441

442
                if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
16✔
443
                        return $result;
16✔
444
                }
445

446
                if ($this->libreSignFile->isEnvelope()) {
×
447
                        $result['envelope'] = $this->libreSignFile;
×
448
                        $result['envelopeSignRequest'] = $this->signRequest;
×
449
                        return $result;
×
450
                }
451

452
                try {
453
                        $envelopeId = $this->libreSignFile->isEnvelope()
×
454
                                ? $this->libreSignFile->getId()
×
455
                                : $this->libreSignFile->getParentFileId();
×
456
                        $result['envelope'] = $this->fileMapper->getById($envelopeId);
×
457
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
×
458
                        $result['envelopeSignRequest'] = $this->signRequestMapper->getByIdentifyMethodAndFileId(
×
459
                                $identifyMethod,
×
460
                                $result['envelope']->getId()
×
461
                        );
×
462
                } catch (DoesNotExistException $e) {
×
463
                        // Envelope not found or sign request not found, leave as null
464
                }
465

466
                return $result;
×
467
        }
468

469
        private function updateEnvelopeStatus(FileEntity $envelope, ?SignRequestEntity $envelopeSignRequest = null, ?DateTimeInterface $signedDate = null): void {
470
                $childFiles = $this->fileMapper->getChildrenFiles($envelope->getId());
×
471

472
                $totalSignRequests = 0;
×
473
                $signedSignRequests = 0;
×
474

475
                foreach ($childFiles as $childFile) {
×
476
                        $signRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
477
                        $totalSignRequests += count($signRequests);
×
478

479
                        foreach ($signRequests as $signRequest) {
×
480
                                if ($signRequest->getSigned()) {
×
481
                                        $signedSignRequests++;
×
482
                                }
483
                        }
484
                }
485

486
                if ($totalSignRequests === 0) {
×
487
                        $envelope->setStatus(FileEntity::STATUS_DRAFT);
×
488
                } elseif ($signedSignRequests === 0) {
×
489
                        $envelope->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
×
490
                } elseif ($signedSignRequests === $totalSignRequests) {
×
491
                        $envelope->setStatus(FileEntity::STATUS_SIGNED);
×
492
                        if ($envelopeSignRequest instanceof SignRequestEntity) {
×
493
                                $envelopeSignRequest->setSigned($signedDate ?: new DateTime());
×
494
                                $envelopeSignRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
×
495
                                $this->signRequestMapper->update($envelopeSignRequest);
×
496
                                $this->sequentialSigningService
×
497
                                        ->setFile($envelope)
×
498
                                        ->releaseNextOrder(
×
499
                                                $envelopeSignRequest->getFileId(),
×
500
                                                $envelopeSignRequest->getSigningOrder()
×
501
                                        );
×
502
                        }
503
                } else {
504
                        $envelope->setStatus(FileEntity::STATUS_PARTIAL_SIGNED);
×
505
                }
506

507
                $this->fileMapper->update($envelope);
×
508
        }
509

510
        /**
511
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
512
         */
513
        protected function validateDocMdpAllowsSignatures(): void {
514
                $docmdpLevel = $this->libreSignFile->getDocmdpLevelEnum();
18✔
515

516
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED) {
18✔
517
                        throw new LibresignException(
×
518
                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
×
519
                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
×
520
                        );
×
521
                }
522

523
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::NOT_CERTIFIED) {
18✔
524
                        $resource = $this->getLibreSignFileAsResource();
18✔
525

526
                        try {
527
                                if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
17✔
528
                                        throw new LibresignException(
3✔
529
                                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
3✔
530
                                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
531
                                        );
3✔
532
                                }
533
                        } finally {
534
                                fclose($resource);
17✔
535
                        }
536
                }
537
        }
538

539
        /**
540
         * @return resource
541
         * @throws LibresignException
542
         */
543
        protected function getLibreSignFileAsResource() {
544
                $files = $this->getNextcloudFiles($this->libreSignFile);
12✔
545
                if (empty($files)) {
11✔
546
                        throw new LibresignException('File not found');
×
547
                }
548
                $fileToSign = current($files);
11✔
549
                $content = $fileToSign->getContent();
11✔
550
                $resource = fopen('php://memory', 'r+');
11✔
551
                if ($resource === false) {
11✔
552
                        throw new LibresignException('Failed to create temporary resource for PDF validation');
×
553
                }
554
                fwrite($resource, $content);
11✔
555
                rewind($resource);
11✔
556
                return $resource;
11✔
557
        }
558

559
        protected function computeHash(File $file): string {
560
                return hash('sha256', $file->getContent());
2✔
561
        }
562

563
        protected function updateSignRequest(string $hash): void {
564
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
565
                $this->signRequest->setSigned($lastSignedDate);
14✔
566
                $this->signRequest->setSignedHash($hash);
14✔
567
                $this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
14✔
568

569
                $this->signRequestMapper->update($this->signRequest);
14✔
570

571
                $this->sequentialSigningService
14✔
572
                        ->setFile($this->libreSignFile)
14✔
573
                        ->releaseNextOrder(
14✔
574
                                $this->signRequest->getFileId(),
14✔
575
                                $this->signRequest->getSigningOrder()
14✔
576
                        );
14✔
577
        }
578

579
        protected function updateLibreSignFile(int $nodeId, string $hash): void {
580
                $this->libreSignFile->setSignedNodeId($nodeId);
14✔
581
                $this->libreSignFile->setSignedHash($hash);
14✔
582
                $this->setNewStatusIfNecessary();
14✔
583
                $this->fileMapper->update($this->libreSignFile);
14✔
584

585
                if ($this->libreSignFile->hasParent()) {
14✔
586
                        $this->fileStatusService->propagateStatusToParent($this->libreSignFile->getParentFileId());
×
587
                }
588
        }
589

590
        protected function dispatchSignedEvent(): void {
591
                $event = $this->signedEventFactory->make(
14✔
592
                        $this->signRequest,
14✔
593
                        $this->libreSignFile,
14✔
594
                        $this->getEngine()->getInputFile(),
14✔
595
                );
14✔
596
                $this->eventDispatcher->dispatchTyped($event);
14✔
597
        }
598

599
        protected function identifyEngine(File $file): SignEngineHandler {
600
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
601
        }
602

603
        protected function getSignatureParams(): array {
604
                $certificateData = $this->readCertificate();
15✔
605
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
606
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
607
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
608
                return $signatureParams;
15✔
609
        }
610

611
        private function buildBaseSignatureParams(array $certificateData): array {
612
                return [
15✔
613
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
614
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
615
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
616
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
617
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
618
                                ->format(DateTimeInterface::ATOM)
15✔
619
                ];
15✔
620
        }
621

622
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
623
                if (isset($certificateData['extensions']['subjectAltName'])) {
15✔
624
                        preg_match('/(?:email:)+(?<email>[^\s,]+)/', $certificateData['extensions']['subjectAltName'], $matches);
6✔
625
                        if ($matches && filter_var($matches['email'], FILTER_VALIDATE_EMAIL)) {
6✔
626
                                $signatureParams['SignerEmail'] = $matches['email'];
4✔
627
                        } elseif (filter_var($certificateData['extensions']['subjectAltName'], FILTER_VALIDATE_EMAIL)) {
2✔
628
                                $signatureParams['SignerEmail'] = $certificateData['extensions']['subjectAltName'];
1✔
629
                        }
630
                }
631
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
632
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
1✔
633
                }
634
                if (empty($signatureParams['SignerEmail']) && $this->signRequest instanceof SignRequestEntity) {
15✔
635
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
636
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
637
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
638
                        }
639
                }
640
                return $signatureParams;
15✔
641
        }
642

643
        private function addMetadataToSignatureParams(array $signatureParams): array {
644
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
645
                if (isset($signRequestMetadata['remote-address'])) {
15✔
646
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
647
                }
648
                if (isset($signRequestMetadata['user-agent'])) {
15✔
649
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
650
                }
651
                return $signatureParams;
15✔
652
        }
653

654
        public function storeUserMetadata(array $metadata = []): self {
655
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
656
                if (!$collectMetadata || !$metadata) {
18✔
657
                        return $this;
7✔
658
                }
659
                $this->signRequest->setMetadata(array_merge(
11✔
660
                        $this->signRequest->getMetadata() ?? [],
11✔
661
                        $metadata,
11✔
662
                ));
11✔
663
                $this->signRequestMapper->update($this->signRequest);
11✔
664
                return $this;
11✔
665
        }
666

667
        /**
668
         * @return SignRequestEntity[]
669
         */
670
        protected function getSigners(): array {
NEW
671
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
672
        }
673

674
        protected function setNewStatusIfNecessary(): bool {
675
                $newStatus = $this->evaluateStatusFromSigners();
10✔
676

677
                if ($newStatus === null || $newStatus === $this->libreSignFile->getStatus()) {
10✔
678
                        return false;
4✔
679
                }
680

681
                $this->libreSignFile->setStatus($newStatus);
6✔
682
                return true;
6✔
683
        }
684

685
        private function evaluateStatusFromSigners(): ?int {
686
                $signers = $this->getSigners();
10✔
687

688
                $total = count($signers);
10✔
689

690
                if ($total === 0) {
10✔
691
                        return null;
1✔
692
                }
693

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

696
                if ($totalSigned === $total) {
9✔
697
                        return FileEntity::STATUS_SIGNED;
5✔
698
                }
699

700
                if ($totalSigned > 0) {
4✔
701
                        return FileEntity::STATUS_PARTIAL_SIGNED;
3✔
702
                }
703

704
                return null;
1✔
705
        }
706

707
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
708
                if ($certificate = $engine->getCertificate()) {
12✔
709
                        return $certificate;
×
710
                }
711
                if ($this->signWithoutPassword) {
12✔
712
                        $tempPassword = $this->generateTemporaryPassword();
1✔
713
                        $this->setPassword($tempPassword);
1✔
714
                        $engine->generateCertificate(
1✔
715
                                [
1✔
716
                                        'host' => $this->userUniqueIdentifier,
1✔
717
                                        'uid' => $this->userUniqueIdentifier,
1✔
718
                                        'name' => $this->friendlyName,
1✔
719
                                ],
1✔
720
                                $tempPassword,
1✔
721
                                $this->friendlyName,
1✔
722
                        );
1✔
723
                }
724
                return $engine->getPfxOfCurrentSigner();
12✔
725
        }
726

727
        private function generateTemporaryPassword(): string {
728
                $passwordEvent = new GenerateSecurePasswordEvent();
1✔
729
                $this->eventDispatcher->dispatchTyped($passwordEvent);
1✔
730
                return $passwordEvent->getPassword() ?? $this->secureRandom->generate(20);
1✔
731
        }
732

733
        protected function readCertificate(): array {
734
                return $this->getEngine()
×
735
                        ->readCertificate();
×
736
        }
737

738
        /**
739
         * Get file to sign
740
         *
741
         * @throws LibresignException
742
         */
743
        protected function getFileToSign(): File {
744
                if ($this->fileToSign instanceof File) {
×
745
                        return $this->fileToSign;
×
746
                }
747

748
                $userId = $this->libreSignFile->getUserId();
×
749
                $nodeId = $this->libreSignFile->getNodeId();
×
750

751
                $originalFile = $this->root->getUserFolder($userId)->getFirstNodeById($nodeId);
×
752
                if (!$originalFile instanceof File) {
×
753
                        throw new LibresignException($this->l10n->t('File not found'));
×
754
                }
755
                if ($this->isPdf($originalFile)) {
×
756
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
757
                } else {
758
                        $this->fileToSign = $originalFile;
×
759
                }
760
                return $this->fileToSign;
×
761
        }
762

763
        private function isPdf(File $file): bool {
764
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
765
        }
766

767
        protected function getEngine(): SignEngineHandler {
768
                if (!$this->engine) {
12✔
769
                        $originalFile = $this->getFileToSign();
12✔
770
                        $this->engine = $this->identifyEngine($originalFile);
12✔
771

772
                        $this->configureEngine();
12✔
773
                }
774
                return $this->engine;
12✔
775
        }
776

777
        private function configureEngine(): void {
778
                $this->engine
12✔
779
                        ->setInputFile($this->getFileToSign())
12✔
780
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
781
                        ->setPassword($this->password);
12✔
782

783
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
784
                        $this->engine
2✔
785
                                ->setVisibleElements($this->getVisibleElements())
2✔
786
                                ->setSignatureParams($this->getSignatureParams());
2✔
787
                }
788
        }
789

790
        public function getLibresignFile(?int $nodeId, ?string $signRequestUuid = null): FileEntity {
791
                try {
792
                        if ($nodeId) {
3✔
793
                                return $this->fileMapper->getByNodeId($nodeId);
1✔
794
                        }
795

796
                        if ($signRequestUuid) {
2✔
797
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
798
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
799
                        }
800

801
                        throw new \Exception('Invalid arguments');
×
802

803
                } catch (DoesNotExistException) {
1✔
804
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
805
                }
806
        }
807

808
        public function renew(SignRequestEntity $signRequest, string $method): void {
809
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
810
                if (empty($identifyMethods[$method])) {
×
811
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
812
                }
813

814
                $signRequest->setUuid(UUIDUtil::getUUID());
×
815
                $this->signRequestMapper->update($signRequest);
×
816

817
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
818
                        $entity = $identifyMethod->getEntity();
×
819
                        $entity->setAttempts($entity->getAttempts() + 1);
×
820
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
821
                        $identifyMethod->save();
×
822
                }, $identifyMethods[$method]);
×
823
        }
824

825
        public function requestCode(
826
                SignRequestEntity $signRequest,
827
                string $identifyMethodName,
828
                string $signMethodName,
829
                string $identify = '',
830
        ): void {
831
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
832
                if (empty($identifyMethods[$identifyMethodName])) {
×
833
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
834
                }
835
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
836
                        try {
837
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
838
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
839
                        } catch (InvalidArgumentException) {
×
840
                                continue;
×
841
                        }
842
                        /** @var IToken $signatureMethod */
843
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
844
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
845
                        return;
×
846
                }
847
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
848
        }
849

850
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
851
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
852
                try {
853
                        if ($libresignFile->isEnvelope()) {
2✔
854
                                $childFiles = $this->fileMapper->getChildrenFiles($libresignFile->getId());
×
855
                                $allSignRequests = [];
×
856
                                foreach ($childFiles as $childFile) {
×
857
                                        $childSignRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
858
                                        $allSignRequests = array_merge($allSignRequests, $childSignRequests);
×
859
                                }
860
                                $signRequests = $allSignRequests;
×
861
                        } else {
862
                                $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
863
                        }
864

865
                        if (!empty($signRequestUuid)) {
2✔
866
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
867
                        } else {
868
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
869
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
870
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
871
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
872
                                                        && $user
873
                                                        && (
874
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
875
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
876
                                                        )
877
                                                ) {
878
                                                        return true;
×
879
                                                }
880
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
881
                                                        && $user
882
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
883
                                                ) {
884
                                                        return true;
×
885
                                                }
886
                                                return false;
×
887
                                        });
×
888
                                        if (count($found) > 0) {
×
889
                                                return $signRequest;
×
890
                                        }
891
                                        return $carry;
×
892
                                });
×
893
                        }
894

895
                        if (!$signRequest) {
2✔
896
                                throw new DoesNotExistException('Sign request not found');
×
897
                        }
898
                        if ($signRequest->getSigned()) {
2✔
899
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
900
                        }
901
                        return $signRequest;
2✔
902
                } catch (DoesNotExistException) {
×
903
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
904
                }
905
        }
906

907
        protected function getPdfToSign(File $originalFile): File {
908
                $file = $this->getSignedFile();
×
909
                if ($file instanceof File) {
×
910
                        return $file;
×
911
                }
912

913
                $originalContent = $originalFile->getContent();
×
914

915
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
916
                        return $this->createSignedFile($originalFile, $originalContent);
×
917
                }
918
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
919
                $footer = $this->footerHandler
×
920
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
921
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
922
                                'displayName' => $signer->getDisplayName(),
×
923
                                'signed' => $signer->getSigned()
×
924
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
925
                                        : null,
926
                        ], $this->getSigners()))
×
927
                        ->getFooter($metadata['d']);
×
928
                if ($footer) {
×
929
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
930
                        file_put_contents($stamp, $footer);
×
931

932
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
933
                        file_put_contents($input, $originalContent);
×
934

935
                        try {
936
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
937
                        } catch (RuntimeException $e) {
×
938
                                throw new LibresignException($e->getMessage());
×
939
                        }
940
                } else {
941
                        $pdfContent = $originalContent;
×
942
                }
943
                return $this->createSignedFile($originalFile, $pdfContent);
×
944
        }
945

946
        protected function getSignedFile(): ?File {
947
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
948
                if (!$nodeId) {
3✔
949
                        return null;
1✔
950
                }
951

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

954
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
955
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
956
                }
957
                return $fileToSign;
2✔
958
        }
959

960
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
961
                try {
962
                        $fileToSign = $this->root->getUserFolder($uid)->getFirstNodeById($nodeId);
4✔
963
                } catch (NoUserException) {
2✔
964
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
965
                } catch (NotPermittedException) {
1✔
966
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
967
                }
968
                if (!$fileToSign instanceof File) {
2✔
969
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
970
                }
971
                return $fileToSign;
1✔
972
        }
973

974
        private function createSignedFile(File $originalFile, string $content): File {
975
                $filename = preg_replace(
×
976
                        '/' . $originalFile->getExtension() . '$/',
×
977
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
978
                        basename($originalFile->getPath())
×
979
                );
×
980
                $owner = $originalFile->getOwner()->getUID();
×
981
                try {
982
                        /** @var \OCP\Files\Folder */
983
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
984
                        return $parentFolder->newFile($filename, $content);
×
985
                } catch (NotPermittedException) {
×
986
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
987
                }
988
        }
989

990
        /**
991
         * @throws DoesNotExistException
992
         */
993
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
994
                $this->validateHelper->validateUuidFormat($uuid);
4✔
995
                return $this->signRequestMapper->getByUuid($uuid);
3✔
996
        }
997

998
        /**
999
         * @throws DoesNotExistException
1000
         */
1001
        public function getFile(int $signRequestId): FileEntity {
1002
                return $this->fileMapper->getById($signRequestId);
×
1003
        }
1004

1005
        /**
1006
         * @throws DoesNotExistException
1007
         */
1008
        public function getFileByUuid(string $uuid): FileEntity {
1009
                return $this->fileMapper->getByUuid($uuid);
×
1010
        }
1011

1012
        public function getIdDocById(int $fileId): IdDocs {
1013
                return $this->idDocsMapper->getByFileId($fileId);
×
1014
        }
1015

1016
        /**
1017
         * @return File[] Array of files
1018
         */
1019
        public function getNextcloudFiles(FileEntity $fileData): array {
1020
                if ($fileData->getNodeType() === 'envelope') {
1✔
1021
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1022
                        $files = [];
×
1023
                        foreach ($children as $child) {
×
1024
                                $nodeId = $child->getNodeId();
×
1025
                                if ($nodeId === null) {
×
1026
                                        throw new LibresignException(json_encode([
×
1027
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1028
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1029
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1030
                                }
1031
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1032
                                if ($file instanceof File) {
×
1033
                                        $files[] = $file;
×
1034
                                }
1035
                        }
1036
                        return $files;
×
1037
                }
1038

1039
                $nodeId = $fileData->getNodeId();
1✔
1040
                if ($nodeId === null) {
1✔
1041
                        throw new LibresignException(json_encode([
1✔
1042
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1043
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1044
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1045
                }
1046
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1047
                if (!$fileToSign instanceof File) {
×
1048
                        throw new LibresignException(json_encode([
×
1049
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1050
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1051
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1052
                }
1053
                return [$fileToSign];
×
1054
        }
1055

1056
        /**
1057
         * @return array<FileEntity>
1058
         */
1059
        public function getNextcloudFilesWithEntities(FileEntity $fileData): array {
1060
                if ($fileData->getNodeType() === 'envelope') {
×
1061
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1062
                        $result = [];
×
1063
                        foreach ($children as $child) {
×
1064
                                $nodeId = $child->getNodeId();
×
1065
                                if ($nodeId === null) {
×
1066
                                        throw new LibresignException(json_encode([
×
1067
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1068
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1069
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1070
                                }
1071
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1072
                                if ($file instanceof File) {
×
1073
                                        $result[] = $child;
×
1074
                                }
1075
                        }
1076
                        return $result;
×
1077
                }
1078

1079
                $nodeId = $fileData->getNodeId();
×
1080
                if ($nodeId === null) {
×
1081
                        throw new LibresignException(json_encode([
×
1082
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1083
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1084
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1085
                }
1086
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1087
                if (!$fileToSign instanceof File) {
×
1088
                        throw new LibresignException(json_encode([
×
1089
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1090
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1091
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1092
                }
1093
                return [$fileData];
×
1094
        }
1095

1096
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1097
                $this->validateHelper->validateSigner($uuid, $user);
×
1098
        }
1099

1100
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1101
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1102
        }
1103

1104
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1105
                $return = ['user' => ['name' => null]];
×
1106
                if ($signRequest) {
×
1107
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1108
                } elseif ($user) {
×
1109
                        $return['user']['name'] = $user->getDisplayName();
×
1110
                }
1111
                return $return;
×
1112
        }
1113

1114
        public function getAvailableIdentifyMethodsFromSettings(): array {
1115
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1116
                $return = array_map(fn (array $identifyMethod): array => [
×
1117
                        'mandatory' => $identifyMethod['mandatory'],
×
1118
                        'identifiedAtDate' => null,
×
1119
                        'validateCode' => false,
×
1120
                        'method' => $identifyMethod['name'],
×
1121
                ], $identifyMethods);
×
1122
                return $return;
×
1123
        }
1124

1125
        public function getFileUrl(int $fileId, string $uuid): string {
1126
                try {
1127
                        $this->idDocsMapper->getByFileId($fileId);
×
1128
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1129
                } catch (DoesNotExistException) {
×
1130
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1131
                }
1132
        }
1133

1134
        /**
1135
         * Get PDF URLs for signing
1136
         * For envelopes: returns URLs for all child files
1137
         * For regular files: returns URL for the file itself
1138
         *
1139
         * @return string[]
1140
         */
1141
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1142
                if (!$fileEntity->isEnvelope()) {
×
1143
                        return [
×
1144
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1145
                        ];
×
1146
                }
1147

1148
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1149
                        $fileEntity->getId(),
×
1150
                        $signRequestEntity->getId()
×
1151
                );
×
1152

1153
                $pdfUrls = [];
×
1154
                foreach ($childSignRequests as $childSignRequest) {
×
1155
                        $pdfUrls[] = $this->getFileUrl(
×
1156
                                $childSignRequest->getFileId(),
×
1157
                                $childSignRequest->getUuid()
×
1158
                        );
×
1159
                }
1160

1161
                return $pdfUrls;
×
1162
        }
1163

1164
        private function recordSignatureAttempt(Exception $exception): void {
1165
                if (!$this->libreSignFile) {
×
1166
                        return;
×
1167
                }
1168

1169
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1170

1171
                if (!isset($metadata['signature_attempts'])) {
×
1172
                        $metadata['signature_attempts'] = [];
×
1173
                }
1174

1175
                $attempt = [
×
1176
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1177
                        'engine' => get_class($this->engine),
×
1178
                        'error_message' => $exception->getMessage(),
×
1179
                        'error_code' => $exception->getCode(),
×
1180
                ];
×
1181

1182
                $metadata['signature_attempts'][] = $attempt;
×
1183
                $this->libreSignFile->setMetadata($metadata);
×
1184
                $this->fileMapper->update($this->libreSignFile);
×
1185
        }
1186
}
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