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

LibreSign / libresign / 20816984639

08 Jan 2026 12:34PM UTC coverage: 44.635%. First build
20816984639

Pull #6410

github

web-flow
Merge 24e8e1ab9 into 41b243a85
Pull Request #6410: chore: cleanup signed file

1 of 11 new or added lines in 1 file covered. (9.09%)

6731 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.01
/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();
×
NEW
352
                                $this->recordSignatureAttempt($e);
×
353
                                continue;
×
354
                        }
355

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

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

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

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

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

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

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

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

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

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

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

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

430
                return $signRequestsData;
1✔
431
        }
432

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

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

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

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

468
                return $result;
×
469
        }
470

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

690
                $total = count($signers);
10✔
691

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

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

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

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

706
                return null;
1✔
707
        }
708

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

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

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

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

750
                $userId = $this->libreSignFile->getUserId();
×
751
                $nodeId = $this->libreSignFile->getNodeId();
×
752

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

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

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

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

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

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

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

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

803
                        throw new \Exception('Invalid arguments');
×
804

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

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

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

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

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

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

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

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

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

915
                $originalContent = $originalFile->getContent();
×
916

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

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

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

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

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

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

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

976
        private function cleanupUnsignedSignedFile(): void {
977
                if (!$this->createdSignedFile instanceof File) {
×
978
                        return;
×
979
                }
980

981
                try {
982
                        $this->createdSignedFile->delete();
×
983
                } catch (\Throwable $e) {
×
984
                        $this->logger->warning('Failed to delete temporary signed file: ' . $e->getMessage());
×
985
                } finally {
986
                        $this->createdSignedFile = null;
×
987
                }
988
        }
989

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

1007
        /**
1008
         * @throws DoesNotExistException
1009
         */
1010
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
1011
                $this->validateHelper->validateUuidFormat($uuid);
4✔
1012
                return $this->signRequestMapper->getByUuid($uuid);
3✔
1013
        }
1014

1015
        /**
1016
         * @throws DoesNotExistException
1017
         */
1018
        public function getFile(int $signRequestId): FileEntity {
1019
                return $this->fileMapper->getById($signRequestId);
×
1020
        }
1021

1022
        /**
1023
         * @throws DoesNotExistException
1024
         */
1025
        public function getFileByUuid(string $uuid): FileEntity {
1026
                return $this->fileMapper->getByUuid($uuid);
×
1027
        }
1028

1029
        public function getIdDocById(int $fileId): IdDocs {
1030
                return $this->idDocsMapper->getByFileId($fileId);
×
1031
        }
1032

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

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

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

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

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

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

1121
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
1122
                $return = ['user' => ['name' => null]];
×
1123
                if ($signRequest) {
×
1124
                        $return['user']['name'] = $signRequest->getDisplayName();
×
1125
                } elseif ($user) {
×
1126
                        $return['user']['name'] = $user->getDisplayName();
×
1127
                }
1128
                return $return;
×
1129
        }
1130

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

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

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

1165
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1166
                        $fileEntity->getId(),
×
1167
                        $signRequestEntity->getId()
×
1168
                );
×
1169

1170
                $pdfUrls = [];
×
1171
                foreach ($childSignRequests as $childSignRequest) {
×
1172
                        $pdfUrls[] = $this->getFileUrl(
×
1173
                                $childSignRequest->getFileId(),
×
1174
                                $childSignRequest->getUuid()
×
1175
                        );
×
1176
                }
1177

1178
                return $pdfUrls;
×
1179
        }
1180

1181
        private function recordSignatureAttempt(Exception $exception): void {
1182
                if (!$this->libreSignFile) {
×
1183
                        return;
×
1184
                }
1185

1186
                $metadata = $this->libreSignFile->getMetadata() ?? [];
×
1187

1188
                if (!isset($metadata['signature_attempts'])) {
×
1189
                        $metadata['signature_attempts'] = [];
×
1190
                }
1191

1192
                $attempt = [
×
1193
                        'timestamp' => (new DateTime())->format(\DateTime::ATOM),
×
1194
                        'engine' => get_class($this->engine),
×
1195
                        'error_message' => $exception->getMessage(),
×
1196
                        'error_code' => $exception->getCode(),
×
1197
                ];
×
1198

1199
                $metadata['signature_attempts'][] = $attempt;
×
1200
                $this->libreSignFile->setMetadata($metadata);
×
1201
                $this->fileMapper->update($this->libreSignFile);
×
1202
        }
1203
}
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