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

LibreSign / libresign / 20819638014

08 Jan 2026 02:09PM UTC coverage: 44.612%. First build
20819638014

Pull #6415

github

web-flow
Merge 7fb00a208 into 7ea6fe959
Pull Request #6415: fix: handle error when sign pdf

0 of 25 new or added lines in 2 files covered. (0.0%)

6731 of 15088 relevant lines covered (44.61%)

5.01 hits per line

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

50.75
/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 ?File $createdSignedFile = null;
73
        private string $userUniqueIdentifier = '';
74
        private string $friendlyName = '';
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✔
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✔
350
                        } catch (LibresignException|Exception $e) {
×
351
                                $this->cleanupUnsignedSignedFile();
×
352
                                $this->recordSignatureAttempt($e);
×
353

NEW
354
                                $isEnvelope = $this->libreSignFile->isEnvelope() || $this->libreSignFile->hasParent();
×
NEW
355
                                if (!$isEnvelope) {
×
NEW
356
                                        throw $e;
×
357
                                }
358
                                continue;
×
359
                        }
360

361
                        $hash = $this->computeHash($signedFile);
16✔
362
                        $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
16✔
363

364
                        $this->updateSignRequest($hash);
16✔
365
                        $this->updateLibreSignFile($signedFile->getId(), $hash);
16✔
366

367
                        $this->dispatchSignedEvent();
16✔
368
                }
369

370
                $envelopeContext = $this->getEnvelopeContext();
16✔
371
                if ($envelopeContext['envelope'] instanceof FileEntity) {
16✔
372
                        $this->updateEnvelopeStatus(
×
373
                                $envelopeContext['envelope'],
×
374
                                $envelopeContext['envelopeSignRequest'] ?? null,
×
375
                                $envelopeLastSignedDate
×
376
                        );
×
377
                }
378
        }
379

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

395
                return $this->buildEnvelopeSignRequests();
1✔
396
        }
397

398
        /**
399
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
400
         */
401
        private function buildEnvelopeSignRequests(): array {
402
                $envelopeId = $this->libreSignFile->isEnvelope()
1✔
403
                        ? $this->libreSignFile->getId()
×
404
                        : $this->libreSignFile->getParentFileId();
1✔
405

406
                $childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
1✔
407
                if (empty($childFiles)) {
1✔
408
                        throw new LibresignException('No files found in envelope');
×
409
                }
410

411
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
1✔
412
                        $envelopeId,
1✔
413
                        $this->signRequest->getId()
1✔
414
                );
1✔
415

416
                if (empty($childSignRequests)) {
1✔
417
                        throw new LibresignException('No sign requests found for envelope files');
×
418
                }
419

420
                $signRequestsData = [];
1✔
421
                foreach ($childSignRequests as $childSignRequest) {
1✔
422
                        $childFile = $this->array_find(
1✔
423
                                $childFiles,
1✔
424
                                fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
1✔
425
                        );
1✔
426

427
                        if ($childFile) {
1✔
428
                                $signRequestsData[] = [
1✔
429
                                        'file' => $childFile,
1✔
430
                                        'signRequest' => $childSignRequest,
1✔
431
                                ];
1✔
432
                        }
433
                }
434

435
                return $signRequestsData;
1✔
436
        }
437

438
        /**
439
         * Get envelope context if the current file is or belongs to an envelope.
440
         *
441
         * @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
442
         */
443
        private function getEnvelopeContext(): array {
444
                $result = [
16✔
445
                        'envelope' => null,
16✔
446
                        'envelopeSignRequest' => null,
16✔
447
                ];
16✔
448

449
                if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
16✔
450
                        return $result;
16✔
451
                }
452

453
                if ($this->libreSignFile->isEnvelope()) {
×
454
                        $result['envelope'] = $this->libreSignFile;
×
455
                        $result['envelopeSignRequest'] = $this->signRequest;
×
456
                        return $result;
×
457
                }
458

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

473
                return $result;
×
474
        }
475

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

479
                $totalSignRequests = 0;
×
480
                $signedSignRequests = 0;
×
481

482
                foreach ($childFiles as $childFile) {
×
483
                        $signRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
484
                        $totalSignRequests += count($signRequests);
×
485

486
                        foreach ($signRequests as $signRequest) {
×
487
                                if ($signRequest->getSigned()) {
×
488
                                        $signedSignRequests++;
×
489
                                }
490
                        }
491
                }
492

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

514
                $this->fileMapper->update($envelope);
×
515
        }
516

517
        /**
518
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
519
         */
520
        protected function validateDocMdpAllowsSignatures(): void {
521
                $docmdpLevel = $this->libreSignFile->getDocmdpLevelEnum();
18✔
522

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

530
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::NOT_CERTIFIED) {
18✔
531
                        $resource = $this->getLibreSignFileAsResource();
18✔
532

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

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

566
        protected function computeHash(File $file): string {
567
                return hash('sha256', $file->getContent());
2✔
568
        }
569

570
        protected function updateSignRequest(string $hash): void {
571
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
572
                $this->signRequest->setSigned($lastSignedDate);
14✔
573
                $this->signRequest->setSignedHash($hash);
14✔
574
                $this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
14✔
575

576
                $this->signRequestMapper->update($this->signRequest);
14✔
577

578
                $this->sequentialSigningService
14✔
579
                        ->setFile($this->libreSignFile)
14✔
580
                        ->releaseNextOrder(
14✔
581
                                $this->signRequest->getFileId(),
14✔
582
                                $this->signRequest->getSigningOrder()
14✔
583
                        );
14✔
584
        }
585

586
        protected function updateLibreSignFile(int $nodeId, string $hash): void {
587
                $this->libreSignFile->setSignedNodeId($nodeId);
14✔
588
                $this->libreSignFile->setSignedHash($hash);
14✔
589
                $this->setNewStatusIfNecessary();
14✔
590
                $this->fileMapper->update($this->libreSignFile);
14✔
591

592
                if ($this->libreSignFile->hasParent()) {
14✔
593
                        $this->fileStatusService->propagateStatusToParent($this->libreSignFile->getParentFileId());
×
594
                }
595
        }
596

597
        protected function dispatchSignedEvent(): void {
598
                $event = $this->signedEventFactory->make(
14✔
599
                        $this->signRequest,
14✔
600
                        $this->libreSignFile,
14✔
601
                        $this->getEngine()->getInputFile(),
14✔
602
                );
14✔
603
                $this->eventDispatcher->dispatchTyped($event);
14✔
604
        }
605

606
        protected function identifyEngine(File $file): SignEngineHandler {
607
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
608
        }
609

610
        protected function getSignatureParams(): array {
611
                $certificateData = $this->readCertificate();
15✔
612
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
613
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
614
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
615
                return $signatureParams;
15✔
616
        }
617

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

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

650
        private function addMetadataToSignatureParams(array $signatureParams): array {
651
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
652
                if (isset($signRequestMetadata['remote-address'])) {
15✔
653
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
654
                }
655
                if (isset($signRequestMetadata['user-agent'])) {
15✔
656
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
657
                }
658
                return $signatureParams;
15✔
659
        }
660

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

674
        /**
675
         * @return SignRequestEntity[]
676
         */
677
        protected function getSigners(): array {
678
                return $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
679
        }
680

681
        protected function setNewStatusIfNecessary(): bool {
682
                $newStatus = $this->evaluateStatusFromSigners();
10✔
683

684
                if ($newStatus === null || $newStatus === $this->libreSignFile->getStatus()) {
10✔
685
                        return false;
4✔
686
                }
687

688
                $this->libreSignFile->setStatus($newStatus);
6✔
689
                return true;
6✔
690
        }
691

692
        private function evaluateStatusFromSigners(): ?int {
693
                $signers = $this->getSigners();
10✔
694

695
                $total = count($signers);
10✔
696

697
                if ($total === 0) {
10✔
698
                        return null;
1✔
699
                }
700

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

703
                if ($totalSigned === $total) {
9✔
704
                        return FileEntity::STATUS_SIGNED;
5✔
705
                }
706

707
                if ($totalSigned > 0) {
4✔
708
                        return FileEntity::STATUS_PARTIAL_SIGNED;
3✔
709
                }
710

711
                return null;
1✔
712
        }
713

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

734
        private function generateTemporaryPassword(): string {
735
                $passwordEvent = new GenerateSecurePasswordEvent();
1✔
736
                $this->eventDispatcher->dispatchTyped($passwordEvent);
1✔
737
                return $passwordEvent->getPassword() ?? $this->secureRandom->generate(20);
1✔
738
        }
739

740
        protected function readCertificate(): array {
741
                return $this->getEngine()
×
742
                        ->readCertificate();
×
743
        }
744

745
        /**
746
         * Get file to sign
747
         *
748
         * @throws LibresignException
749
         */
750
        protected function getFileToSign(): File {
751
                if ($this->fileToSign instanceof File) {
×
752
                        return $this->fileToSign;
×
753
                }
754

755
                $userId = $this->libreSignFile->getUserId();
×
756
                $nodeId = $this->libreSignFile->getNodeId();
×
757

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

770
        private function isPdf(File $file): bool {
771
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
772
        }
773

774
        protected function getEngine(): SignEngineHandler {
775
                if (!$this->engine) {
12✔
776
                        $originalFile = $this->getFileToSign();
12✔
777
                        $this->engine = $this->identifyEngine($originalFile);
12✔
778

779
                        $this->configureEngine();
12✔
780
                }
781
                return $this->engine;
12✔
782
        }
783

784
        private function configureEngine(): void {
785
                $this->engine
12✔
786
                        ->setInputFile($this->getFileToSign())
12✔
787
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
788
                        ->setPassword($this->password);
12✔
789

790
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
791
                        $this->engine
2✔
792
                                ->setVisibleElements($this->getVisibleElements())
2✔
793
                                ->setSignatureParams($this->getSignatureParams());
2✔
794
                }
795
        }
796

797
        public function getLibresignFile(?int $nodeId, ?string $signRequestUuid = null): FileEntity {
798
                try {
799
                        if ($nodeId) {
3✔
800
                                return $this->fileMapper->getByNodeId($nodeId);
1✔
801
                        }
802

803
                        if ($signRequestUuid) {
2✔
804
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
805
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
806
                        }
807

808
                        throw new \Exception('Invalid arguments');
×
809

810
                } catch (DoesNotExistException) {
1✔
811
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
812
                }
813
        }
814

815
        public function renew(SignRequestEntity $signRequest, string $method): void {
816
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
817
                if (empty($identifyMethods[$method])) {
×
818
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
819
                }
820

821
                $signRequest->setUuid(UUIDUtil::getUUID());
×
822
                $this->signRequestMapper->update($signRequest);
×
823

824
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
825
                        $entity = $identifyMethod->getEntity();
×
826
                        $entity->setAttempts($entity->getAttempts() + 1);
×
827
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
828
                        $identifyMethod->save();
×
829
                }, $identifyMethods[$method]);
×
830
        }
831

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

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

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

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

914
        protected function getPdfToSign(File $originalFile): File {
915
                $file = $this->getSignedFile();
×
916
                if ($file instanceof File) {
×
917
                        return $file;
×
918
                }
919

920
                $originalContent = $originalFile->getContent();
×
921

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

939
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
940
                        file_put_contents($input, $originalContent);
×
941

942
                        try {
943
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
944
                        } catch (RuntimeException $e) {
×
945
                                throw new LibresignException($e->getMessage());
×
946
                        }
947
                } else {
948
                        $pdfContent = $originalContent;
×
949
                }
950
                return $this->createSignedFile($originalFile, $pdfContent);
×
951
        }
952

953
        protected function getSignedFile(): ?File {
954
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
955
                if (!$nodeId) {
3✔
956
                        return null;
1✔
957
                }
958

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

961
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
962
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
963
                }
964
                return $fileToSign;
2✔
965
        }
966

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

981
        private function cleanupUnsignedSignedFile(): void {
982
                if (!$this->createdSignedFile instanceof File) {
×
983
                        return;
×
984
                }
985

986
                try {
987
                        $this->createdSignedFile->delete();
×
988
                } catch (\Throwable $e) {
×
989
                        $this->logger->warning('Failed to delete temporary signed file: ' . $e->getMessage());
×
990
                } finally {
991
                        $this->createdSignedFile = null;
×
992
                }
993
        }
994

995
        private function createSignedFile(File $originalFile, string $content): File {
996
                $filename = preg_replace(
×
997
                        '/' . $originalFile->getExtension() . '$/',
×
998
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
999
                        basename($originalFile->getPath())
×
1000
                );
×
1001
                $owner = $originalFile->getOwner()->getUID();
×
1002
                try {
1003
                        /** @var \OCP\Files\Folder */
1004
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
1005
                        $this->createdSignedFile = $parentFolder->newFile($filename, $content);
×
1006
                        return $this->createdSignedFile;
×
1007
                } catch (NotPermittedException) {
×
1008
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
1009
                }
1010
        }
1011

1012
        /**
1013
         * @throws DoesNotExistException
1014
         */
1015
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1016
                $this->validateHelper->validateUuidFormat($uuid);
4✔
1017
                return $this->signRequestMapper->getByUuid($uuid);
3✔
1018
        }
1019

1020
        /**
1021
         * @throws DoesNotExistException
1022
         */
1023
        public function getFile(int $signRequestId): FileEntity {
1024
                return $this->fileMapper->getById($signRequestId);
×
1025
        }
1026

1027
        /**
1028
         * @throws DoesNotExistException
1029
         */
1030
        public function getFileByUuid(string $uuid): FileEntity {
1031
                return $this->fileMapper->getByUuid($uuid);
×
1032
        }
1033

1034
        public function getIdDocById(int $fileId): IdDocs {
1035
                return $this->idDocsMapper->getByFileId($fileId);
×
1036
        }
1037

1038
        /**
1039
         * @return File[] Array of files
1040
         */
1041
        public function getNextcloudFiles(FileEntity $fileData): array {
1042
                if ($fileData->getNodeType() === 'envelope') {
1✔
1043
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1044
                        $files = [];
×
1045
                        foreach ($children as $child) {
×
1046
                                $nodeId = $child->getNodeId();
×
1047
                                if ($nodeId === null) {
×
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
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1054
                                if ($file instanceof File) {
×
1055
                                        $files[] = $file;
×
1056
                                }
1057
                        }
1058
                        return $files;
×
1059
                }
1060

1061
                $nodeId = $fileData->getNodeId();
1✔
1062
                if ($nodeId === null) {
1✔
1063
                        throw new LibresignException(json_encode([
1✔
1064
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
1065
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
1066
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
1067
                }
1068
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1069
                if (!$fileToSign instanceof File) {
×
1070
                        throw new LibresignException(json_encode([
×
1071
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1072
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1073
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1074
                }
1075
                return [$fileToSign];
×
1076
        }
1077

1078
        /**
1079
         * @return array<FileEntity>
1080
         */
1081
        public function getNextcloudFilesWithEntities(FileEntity $fileData): array {
1082
                if ($fileData->getNodeType() === 'envelope') {
×
1083
                        $children = $this->fileMapper->getChildrenFiles($fileData->getId());
×
1084
                        $result = [];
×
1085
                        foreach ($children as $child) {
×
1086
                                $nodeId = $child->getNodeId();
×
1087
                                if ($nodeId === null) {
×
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
                                $file = $this->root->getUserFolder($child->getUserId())->getFirstNodeById($nodeId);
×
1094
                                if ($file instanceof File) {
×
1095
                                        $result[] = $child;
×
1096
                                }
1097
                        }
1098
                        return $result;
×
1099
                }
1100

1101
                $nodeId = $fileData->getNodeId();
×
1102
                if ($nodeId === null) {
×
1103
                        throw new LibresignException(json_encode([
×
1104
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1105
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1106
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1107
                }
1108
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
×
1109
                if (!$fileToSign instanceof File) {
×
1110
                        throw new LibresignException(json_encode([
×
1111
                                'action' => JSActions::ACTION_DO_NOTHING,
×
1112
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
1113
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
1114
                }
1115
                return [$fileData];
×
1116
        }
1117

1118
        public function validateSigner(string $uuid, ?IUser $user = null): void {
1119
                $this->validateHelper->validateSigner($uuid, $user);
×
1120
        }
1121

1122
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
1123
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
1124
        }
1125

1126
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1127
                $return = ['user' => ['name' => null]];
×
1128
                if ($signRequest) {
×
1129
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1130
                } elseif ($user) {
×
1131
                        $return['user']['name'] = $user->getDisplayName();
×
1132
                }
1133
                return $return;
×
1134
        }
1135

1136
        public function getAvailableIdentifyMethodsFromSettings(): array {
1137
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
1138
                $return = array_map(fn (array $identifyMethod): array => [
×
1139
                        'mandatory' => $identifyMethod['mandatory'],
×
1140
                        'identifiedAtDate' => null,
×
1141
                        'validateCode' => false,
×
1142
                        'method' => $identifyMethod['name'],
×
1143
                ], $identifyMethods);
×
1144
                return $return;
×
1145
        }
1146

1147
        public function getFileUrl(int $fileId, string $uuid): string {
1148
                try {
1149
                        $this->idDocsMapper->getByFileId($fileId);
×
1150
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid]);
×
1151
                } catch (DoesNotExistException) {
×
1152
                        return $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid]);
×
1153
                }
1154
        }
1155

1156
        /**
1157
         * Get PDF URLs for signing
1158
         * For envelopes: returns URLs for all child files
1159
         * For regular files: returns URL for the file itself
1160
         *
1161
         * @return string[]
1162
         */
1163
        public function getPdfUrlsForSigning(FileEntity $fileEntity, SignRequestEntity $signRequestEntity): array {
1164
                if (!$fileEntity->isEnvelope()) {
×
1165
                        return [
×
1166
                                $this->getFileUrl($fileEntity->getId(), $signRequestEntity->getUuid())
×
1167
                        ];
×
1168
                }
1169

1170
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1171
                        $fileEntity->getId(),
×
1172
                        $signRequestEntity->getId()
×
1173
                );
×
1174

1175
                $pdfUrls = [];
×
1176
                foreach ($childSignRequests as $childSignRequest) {
×
1177
                        $pdfUrls[] = $this->getFileUrl(
×
1178
                                $childSignRequest->getFileId(),
×
1179
                                $childSignRequest->getUuid()
×
1180
                        );
×
1181
                }
1182

1183
                return $pdfUrls;
×
1184
        }
1185

1186
        private function recordSignatureAttempt(Exception $exception): void {
1187
                if (!$this->libreSignFile) {
×
1188
                        return;
×
1189
                }
1190

1191
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1192

1193
                if (!isset($metadata['signature_attempts'])) {
×
1194
                        $metadata['signature_attempts'] = [];
×
1195
                }
1196

1197
                $attempt = [
×
1198
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1199
                        'engine' => get_class($this->engine),
×
1200
                        'error_message' => $exception->getMessage(),
×
1201
                        'error_code' => $exception->getCode(),
×
1202
                ];
×
1203

1204
                $metadata['signature_attempts'][] = $attempt;
×
1205
                $this->libreSignFile->setMetadata($metadata);
×
1206
                $this->fileMapper->update($this->libreSignFile);
×
1207
        }
1208
}
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