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

LibreSign / libresign / 20816145844

08 Jan 2026 12:02PM UTC coverage: 44.642%. First build
20816145844

Pull #6406

github

web-flow
Merge f2bc43ab6 into bdcba8a99
Pull Request #6406: feat: Store signature attempt

2 of 20 new or added lines in 1 file covered. (10.0%)

6732 of 15080 relevant lines covered (44.64%)

5.02 hits per line

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

51.09
/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 array $signers = [];
75
        private ?IUser $user = null;
76
        private ?SignEngineHandler $engine = null;
77

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

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

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

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

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

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

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

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

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

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

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

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

228
                return $this;
5✔
229
        }
230

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

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

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

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

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

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

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

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

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

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

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

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

317
                return null;
3✔
318
        }
319

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

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

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

334
                $envelopeLastSignedDate = null;
18✔
335

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

429
                return $signRequestsData;
1✔
430
        }
431

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

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

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

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

467
                return $result;
×
468
        }
469

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

668
        /**
669
         * @return SignRequestEntity[]
670
         */
671
        protected function getSigners(): array {
672
                if (empty($this->signers)) {
×
673
                        $this->signers = $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
674
                        if ($this->signers) {
×
675
                                foreach ($this->signers as $key => $signer) {
×
676
                                        if ($signer->getId() === $this->signRequest->getId()) {
×
677
                                                $this->signers[$key] = $this->signRequest;
×
678
                                                break;
×
679
                                        }
680
                                }
681
                        }
682
                }
683
                return $this->signers;
×
684
        }
685

686
        protected function setNewStatusIfNecessary(): bool {
687
                $newStatus = $this->evaluateStatusFromSigners();
10✔
688

689
                if ($newStatus === null || $newStatus === $this->libreSignFile->getStatus()) {
10✔
690
                        return false;
4✔
691
                }
692

693
                $this->libreSignFile->setStatus($newStatus);
6✔
694
                return true;
6✔
695
        }
696

697
        private function evaluateStatusFromSigners(): ?int {
698
                $signers = $this->getSigners();
10✔
699

700
                $total = count($signers);
10✔
701

702
                if ($total === 0) {
10✔
703
                        return null;
1✔
704
                }
705

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

708
                if ($totalSigned === $total) {
9✔
709
                        return FileEntity::STATUS_SIGNED;
5✔
710
                }
711

712
                if ($totalSigned > 0) {
4✔
713
                        return FileEntity::STATUS_PARTIAL_SIGNED;
3✔
714
                }
715

716
                return null;
1✔
717
        }
718

719
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
720
                if ($certificate = $engine->getCertificate()) {
12✔
721
                        return $certificate;
×
722
                }
723
                if ($this->signWithoutPassword) {
12✔
724
                        $tempPassword = $this->generateTemporaryPassword();
1✔
725
                        $this->setPassword($tempPassword);
1✔
726
                        $engine->generateCertificate(
1✔
727
                                [
1✔
728
                                        'host' => $this->userUniqueIdentifier,
1✔
729
                                        'uid' => $this->userUniqueIdentifier,
1✔
730
                                        'name' => $this->friendlyName,
1✔
731
                                ],
1✔
732
                                $tempPassword,
1✔
733
                                $this->friendlyName,
1✔
734
                        );
1✔
735
                }
736
                return $engine->getPfxOfCurrentSigner();
12✔
737
        }
738

739
        private function generateTemporaryPassword(): string {
740
                $passwordEvent = new GenerateSecurePasswordEvent();
1✔
741
                $this->eventDispatcher->dispatchTyped($passwordEvent);
1✔
742
                return $passwordEvent->getPassword() ?? $this->secureRandom->generate(20);
1✔
743
        }
744

745
        protected function readCertificate(): array {
746
                return $this->getEngine()
×
747
                        ->readCertificate();
×
748
        }
749

750
        /**
751
         * Get file to sign
752
         *
753
         * @throws LibresignException
754
         */
755
        protected function getFileToSign(): File {
756
                if ($this->fileToSign instanceof File) {
×
757
                        return $this->fileToSign;
×
758
                }
759

760
                $userId = $this->libreSignFile->getUserId();
×
761
                $nodeId = $this->libreSignFile->getNodeId();
×
762

763
                $originalFile = $this->root->getUserFolder($userId)->getFirstNodeById($nodeId);
×
764
                if (!$originalFile instanceof File) {
×
765
                        throw new LibresignException($this->l10n->t('File not found'));
×
766
                }
767
                if ($this->isPdf($originalFile)) {
×
768
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
769
                } else {
770
                        $this->fileToSign = $originalFile;
×
771
                }
772
                return $this->fileToSign;
×
773
        }
774

775
        private function isPdf(File $file): bool {
776
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
777
        }
778

779
        protected function getEngine(): SignEngineHandler {
780
                if (!$this->engine) {
12✔
781
                        $originalFile = $this->getFileToSign();
12✔
782
                        $this->engine = $this->identifyEngine($originalFile);
12✔
783

784
                        $this->configureEngine();
12✔
785
                }
786
                return $this->engine;
12✔
787
        }
788

789
        private function configureEngine(): void {
790
                $this->engine
12✔
791
                        ->setInputFile($this->getFileToSign())
12✔
792
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
793
                        ->setPassword($this->password);
12✔
794

795
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
796
                        $this->engine
2✔
797
                                ->setVisibleElements($this->getVisibleElements())
2✔
798
                                ->setSignatureParams($this->getSignatureParams());
2✔
799
                }
800
        }
801

802
        public function getLibresignFile(?int $nodeId, ?string $signRequestUuid = null): FileEntity {
803
                try {
804
                        if ($nodeId) {
3✔
805
                                return $this->fileMapper->getByNodeId($nodeId);
1✔
806
                        }
807

808
                        if ($signRequestUuid) {
2✔
809
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
810
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
811
                        }
812

813
                        throw new \Exception('Invalid arguments');
×
814

815
                } catch (DoesNotExistException) {
1✔
816
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
817
                }
818
        }
819

820
        public function renew(SignRequestEntity $signRequest, string $method): void {
821
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
822
                if (empty($identifyMethods[$method])) {
×
823
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
824
                }
825

826
                $signRequest->setUuid(UUIDUtil::getUUID());
×
827
                $this->signRequestMapper->update($signRequest);
×
828

829
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
830
                        $entity = $identifyMethod->getEntity();
×
831
                        $entity->setAttempts($entity->getAttempts() + 1);
×
832
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
833
                        $identifyMethod->save();
×
834
                }, $identifyMethods[$method]);
×
835
        }
836

837
        public function requestCode(
838
                SignRequestEntity $signRequest,
839
                string $identifyMethodName,
840
                string $signMethodName,
841
                string $identify = '',
842
        ): void {
843
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
844
                if (empty($identifyMethods[$identifyMethodName])) {
×
845
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
846
                }
847
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
848
                        try {
849
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
850
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
851
                        } catch (InvalidArgumentException) {
×
852
                                continue;
×
853
                        }
854
                        /** @var IToken $signatureMethod */
855
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
856
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
857
                        return;
×
858
                }
859
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
860
        }
861

862
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
863
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
864
                try {
865
                        if ($libresignFile->isEnvelope()) {
2✔
866
                                $childFiles = $this->fileMapper->getChildrenFiles($libresignFile->getId());
×
867
                                $allSignRequests = [];
×
868
                                foreach ($childFiles as $childFile) {
×
869
                                        $childSignRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
870
                                        $allSignRequests = array_merge($allSignRequests, $childSignRequests);
×
871
                                }
872
                                $signRequests = $allSignRequests;
×
873
                        } else {
874
                                $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
875
                        }
876

877
                        if (!empty($signRequestUuid)) {
2✔
878
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
879
                        } else {
880
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
881
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
882
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
883
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
884
                                                        && $user
885
                                                        && (
886
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
887
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
888
                                                        )
889
                                                ) {
890
                                                        return true;
×
891
                                                }
892
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
893
                                                        && $user
894
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
895
                                                ) {
896
                                                        return true;
×
897
                                                }
898
                                                return false;
×
899
                                        });
×
900
                                        if (count($found) > 0) {
×
901
                                                return $signRequest;
×
902
                                        }
903
                                        return $carry;
×
904
                                });
×
905
                        }
906

907
                        if (!$signRequest) {
2✔
908
                                throw new DoesNotExistException('Sign request not found');
×
909
                        }
910
                        if ($signRequest->getSigned()) {
2✔
911
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
912
                        }
913
                        return $signRequest;
2✔
914
                } catch (DoesNotExistException) {
×
915
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
916
                }
917
        }
918

919
        protected function getPdfToSign(File $originalFile): File {
920
                $file = $this->getSignedFile();
×
921
                if ($file instanceof File) {
×
922
                        return $file;
×
923
                }
924

925
                $originalContent = $originalFile->getContent();
×
926

927
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
928
                        return $this->createSignedFile($originalFile, $originalContent);
×
929
                }
930
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
931
                $footer = $this->footerHandler
×
932
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
933
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
934
                                'displayName' => $signer->getDisplayName(),
×
935
                                'signed' => $signer->getSigned()
×
936
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
937
                                        : null,
938
                        ], $this->getSigners()))
×
939
                        ->getFooter($metadata['d']);
×
940
                if ($footer) {
×
941
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
942
                        file_put_contents($stamp, $footer);
×
943

944
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
945
                        file_put_contents($input, $originalContent);
×
946

947
                        try {
948
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
949
                        } catch (RuntimeException $e) {
×
950
                                throw new LibresignException($e->getMessage());
×
951
                        }
952
                } else {
953
                        $pdfContent = $originalContent;
×
954
                }
955
                return $this->createSignedFile($originalFile, $pdfContent);
×
956
        }
957

958
        protected function getSignedFile(): ?File {
959
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
960
                if (!$nodeId) {
3✔
961
                        return null;
1✔
962
                }
963

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

966
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
967
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
968
                }
969
                return $fileToSign;
2✔
970
        }
971

972
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
973
                try {
974
                        $fileToSign = $this->root->getUserFolder($uid)->getFirstNodeById($nodeId);
4✔
975
                } catch (NoUserException) {
2✔
976
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
977
                } catch (NotPermittedException) {
1✔
978
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
979
                }
980
                if (!$fileToSign instanceof File) {
2✔
981
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
982
                }
983
                return $fileToSign;
1✔
984
        }
985

986
        private function createSignedFile(File $originalFile, string $content): File {
987
                $filename = preg_replace(
×
988
                        '/' . $originalFile->getExtension() . '$/',
×
989
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
990
                        basename($originalFile->getPath())
×
991
                );
×
992
                $owner = $originalFile->getOwner()->getUID();
×
993
                try {
994
                        /** @var \OCP\Files\Folder */
995
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
996
                        return $parentFolder->newFile($filename, $content);
×
997
                } catch (NotPermittedException) {
×
998
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
999
                }
1000
        }
1001

1002
        /**
1003
         * @throws DoesNotExistException
1004
         */
1005
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1006
                $this->validateHelper->validateUuidFormat($uuid);
4✔
1007
                return $this->signRequestMapper->getByUuid($uuid);
3✔
1008
        }
1009

1010
        /**
1011
         * @throws DoesNotExistException
1012
         */
1013
        public function getFile(int $signRequestId): FileEntity {
1014
                return $this->fileMapper->getById($signRequestId);
×
1015
        }
1016

1017
        /**
1018
         * @throws DoesNotExistException
1019
         */
1020
        public function getFileByUuid(string $uuid): FileEntity {
1021
                return $this->fileMapper->getByUuid($uuid);
×
1022
        }
1023

1024
        public function getIdDocById(int $fileId): IdDocs {
1025
                return $this->idDocsMapper->getByFileId($fileId);
×
1026
        }
1027

1028
        /**
1029
         * @return File[] Array of files
1030
         */
1031
        public function getNextcloudFiles(FileEntity $fileData): array {
1032
                if ($fileData->getNodeType() === 'envelope') {
1✔
1033
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1034
                        $files = [];
×
1035
                        foreach ($children as $child) {
×
1036
                                $nodeId = $child->getNodeId();
×
1037
                                if ($nodeId === null) {
×
1038
                                        throw new LibresignException(json_encode([
×
1039
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1040
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1041
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1042
                                }
1043
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1044
                                if ($file instanceof File) {
×
1045
                                        $files[] = $file;
×
1046
                                }
1047
                        }
1048
                        return $files;
×
1049
                }
1050

1051
                $nodeId = $fileData->getNodeId();
1✔
1052
                if ($nodeId === null) {
1✔
1053
                        throw new LibresignException(json_encode([
1✔
1054
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1055
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1056
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1057
                }
1058
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1059
                if (!$fileToSign instanceof File) {
×
1060
                        throw new LibresignException(json_encode([
×
1061
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1062
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1063
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1064
                }
1065
                return [$fileToSign];
×
1066
        }
1067

1068
        /**
1069
         * @return array<FileEntity>
1070
         */
1071
        public function getNextcloudFilesWithEntities(FileEntity $fileData): array {
1072
                if ($fileData->getNodeType() === 'envelope') {
×
1073
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1074
                        $result = [];
×
1075
                        foreach ($children as $child) {
×
1076
                                $nodeId = $child->getNodeId();
×
1077
                                if ($nodeId === null) {
×
1078
                                        throw new LibresignException(json_encode([
×
1079
                                                'action' => JSActions::ACTION_DO_NOTHING,
×
1080
                                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1081
                                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1082
                                }
1083
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1084
                                if ($file instanceof File) {
×
1085
                                        $result[] = $child;
×
1086
                                }
1087
                        }
1088
                        return $result;
×
1089
                }
1090

1091
                $nodeId = $fileData->getNodeId();
×
1092
                if ($nodeId === null) {
×
1093
                        throw new LibresignException(json_encode([
×
1094
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1095
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1096
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1097
                }
1098
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1099
                if (!$fileToSign instanceof File) {
×
1100
                        throw new LibresignException(json_encode([
×
1101
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1102
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1103
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1104
                }
1105
                return [$fileData];
×
1106
        }
1107

1108
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1109
                $this->validateHelper->validateSigner($uuid, $user);
×
1110
        }
1111

1112
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1113
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1114
        }
1115

1116
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1117
                $return = ['user' => ['name' => null]];
×
1118
                if ($signRequest) {
×
1119
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1120
                } elseif ($user) {
×
1121
                        $return['user']['name'] = $user->getDisplayName();
×
1122
                }
1123
                return $return;
×
1124
        }
1125

1126
        public function getAvailableIdentifyMethodsFromSettings(): array {
1127
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1128
                $return = array_map(fn (array $identifyMethod): array => [
×
1129
                        'mandatory' => $identifyMethod['mandatory'],
×
1130
                        'identifiedAtDate' => null,
×
1131
                        'validateCode' => false,
×
1132
                        'method' => $identifyMethod['name'],
×
1133
                ], $identifyMethods);
×
1134
                return $return;
×
1135
        }
1136

1137
        public function getFileUrl(int $fileId, string $uuid): string {
1138
                try {
1139
                        $this->idDocsMapper->getByFileId($fileId);
×
1140
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1141
                } catch (DoesNotExistException) {
×
1142
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1143
                }
1144
        }
1145

1146
        /**
1147
         * Get PDF URLs for signing
1148
         * For envelopes: returns URLs for all child files
1149
         * For regular files: returns URL for the file itself
1150
         *
1151
         * @return string[]
1152
         */
1153
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1154
                if (!$fileEntity->isEnvelope()) {
×
1155
                        return [
×
1156
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1157
                        ];
×
1158
                }
1159

1160
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1161
                        $fileEntity->getId(),
×
1162
                        $signRequestEntity->getId()
×
1163
                );
×
1164

1165
                $pdfUrls = [];
×
1166
                foreach ($childSignRequests as $childSignRequest) {
×
1167
                        $pdfUrls[] = $this->getFileUrl(
×
1168
                                $childSignRequest->getFileId(),
×
1169
                                $childSignRequest->getUuid()
×
1170
                        );
×
1171
                }
1172

1173
                return $pdfUrls;
×
1174
        }
1175

1176
        private function recordSignatureAttempt(Exception $exception): void {
NEW
1177
                if (!$this->libreSignFile) {
×
NEW
1178
                        return;
×
1179
                }
1180

NEW
1181
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1182

NEW
1183
                if (!isset($metadata['signature_attempts'])) {
×
NEW
1184
                        $metadata['signature_attempts'] = [];
×
1185
                }
1186

NEW
1187
                $attempt = [
×
NEW
1188
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
NEW
1189
                        'engine' => get_class($this->engine),
×
NEW
1190
                        'error_message' => $exception->getMessage(),
×
NEW
1191
                        'error_code' => $exception->getCode(),
×
NEW
1192
                ];
×
1193

NEW
1194
                $metadata['signature_attempts'][] = $attempt;
×
NEW
1195
                $this->libreSignFile->setMetadata($metadata);
×
NEW
1196
                $this->fileMapper->update($this->libreSignFile);
×
1197
        }
1198
}
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