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

LibreSign / libresign / 20771036005

07 Jan 2026 04:53AM UTC coverage: 44.772%. First build
20771036005

Pull #6366

github

web-flow
Merge 571045e9c into 4ad2113a7
Pull Request #6366: fix: ci

6 of 28 new or added lines in 1 file covered. (21.43%)

6727 of 15025 relevant lines covered (44.77%)

5.03 hits per line

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

52.6
/lib/Service/SignFileService.php
1
<?php
2

3
declare(strict_types=1);
4
/**
5
 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6
 * SPDX-License-Identifier: AGPL-3.0-or-later
7
 */
8

9
namespace OCA\Libresign\Service;
10

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

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

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

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

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

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

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

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

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

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

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

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

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

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

228
                return $this;
5✔
229
        }
230

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

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

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

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

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

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

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

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

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

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

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

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

317
                return null;
3✔
318
        }
319

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

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

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

334
                $envelopeLastSignedDate = null;
18✔
335

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

343
                        $this->validateDocMdpAllowsSignatures();
18✔
344
                        $signedFile = $this->getEngine()->sign();
16✔
345

346
                        $hash = $this->computeHash($signedFile);
16✔
347
                        $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
16✔
348

349
                        $this->updateSignRequest($hash);
16✔
350
                        $this->updateLibreSignFile($signedFile->getId(), $hash);
16✔
351

352
                        $this->dispatchSignedEvent();
16✔
353
                }
354

355
                $envelopeContext = $this->getEnvelopeContext();
16✔
356
                if ($envelopeContext['envelope'] instanceof FileEntity) {
16✔
357
                        $this->updateEnvelopeStatus(
×
358
                                $envelopeContext['envelope'],
×
359
                                $envelopeContext['envelopeSignRequest'] ?? null,
×
360
                                $envelopeLastSignedDate
×
361
                        );
×
362
                }
363
        }
364

365
        /**
366
         * Get sign requests to process.
367
         *
368
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
369
         */
370
        private function getSignRequestsToSign(): array {
371
                if (!$this->libreSignFile->isEnvelope()
19✔
372
                        && !$this->libreSignFile->hasParent()
19✔
373
                ) {
374
                        return [[
18✔
375
                                'file' => $this->libreSignFile,
18✔
376
                                'signRequest' => $this->signRequest,
18✔
377
                        ]];
18✔
378
                }
379

380
                return $this->buildEnvelopeSignRequests();
1✔
381
        }
382

383
        /**
384
         * @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
385
         */
386
        private function buildEnvelopeSignRequests(): array {
387
                $envelopeId = $this->libreSignFile->isEnvelope()
1✔
388
                        ? $this->libreSignFile->getId()
×
389
                        : $this->libreSignFile->getParentFileId();
1✔
390

391
                $childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
1✔
392
                if (empty($childFiles)) {
1✔
393
                        throw new LibresignException('No files found in envelope');
×
394
                }
395

396
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
1✔
397
                        $envelopeId,
1✔
398
                        $this->signRequest->getId()
1✔
399
                );
1✔
400

401
                if (empty($childSignRequests)) {
1✔
402
                        throw new LibresignException('No sign requests found for envelope files');
×
403
                }
404

405
                $signRequestsData = [];
1✔
406
                foreach ($childSignRequests as $childSignRequest) {
1✔
407
                        $childFile = $this->array_find(
1✔
408
                                $childFiles,
1✔
409
                                fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
1✔
410
                        );
1✔
411

412
                        if ($childFile) {
1✔
413
                                $signRequestsData[] = [
1✔
414
                                        'file' => $childFile,
1✔
415
                                        'signRequest' => $childSignRequest,
1✔
416
                                ];
1✔
417
                        }
418
                }
419

420
                return $signRequestsData;
1✔
421
        }
422

423
        /**
424
         * Get envelope context if the current file is or belongs to an envelope.
425
         *
426
         * @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
427
         */
428
        private function getEnvelopeContext(): array {
429
                $result = [
16✔
430
                        'envelope' => null,
16✔
431
                        'envelopeSignRequest' => null,
16✔
432
                ];
16✔
433

434
                if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
16✔
435
                        return $result;
16✔
436
                }
437

438
                if ($this->libreSignFile->isEnvelope()) {
×
439
                        $result['envelope'] = $this->libreSignFile;
×
440
                        $result['envelopeSignRequest'] = $this->signRequest;
×
441
                        return $result;
×
442
                }
443

444
                try {
445
                        $envelopeId = $this->libreSignFile->isEnvelope()
×
446
                                ? $this->libreSignFile->getId()
×
447
                                : $this->libreSignFile->getParentFileId();
×
448
                        $result['envelope'] = $this->fileMapper->getById($envelopeId);
×
449
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
×
450
                        $result['envelopeSignRequest'] = $this->signRequestMapper->getByIdentifyMethodAndFileId(
×
451
                                $identifyMethod,
×
452
                                $result['envelope']->getId()
×
453
                        );
×
454
                } catch (DoesNotExistException $e) {
×
455
                        // Envelope not found or sign request not found, leave as null
456
                }
457

458
                return $result;
×
459
        }
460

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

464
                $totalSignRequests = 0;
×
465
                $signedSignRequests = 0;
×
466

467
                foreach ($childFiles as $childFile) {
×
468
                        $signRequests = $this->signRequestMapper->getByFileId($childFile->getId());
×
469
                        $totalSignRequests += count($signRequests);
×
470

471
                        foreach ($signRequests as $signRequest) {
×
472
                                if ($signRequest->getSigned()) {
×
473
                                        $signedSignRequests++;
×
474
                                }
475
                        }
476
                }
477

478
                if ($totalSignRequests === 0) {
×
479
                        $envelope->setStatus(FileEntity::STATUS_DRAFT);
×
480
                } elseif ($signedSignRequests === 0) {
×
481
                        $envelope->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
×
482
                } elseif ($signedSignRequests === $totalSignRequests) {
×
483
                        $envelope->setStatus(FileEntity::STATUS_SIGNED);
×
484
                        if ($envelopeSignRequest instanceof SignRequestEntity) {
×
485
                                $envelopeSignRequest->setSigned($signedDate ?: new DateTime());
×
486
                                $envelopeSignRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
×
487
                                $this->signRequestMapper->update($envelopeSignRequest);
×
488
                                $this->sequentialSigningService
×
489
                                        ->setFile($envelope)
×
490
                                        ->releaseNextOrder(
×
491
                                                $envelopeSignRequest->getFileId(),
×
492
                                                $envelopeSignRequest->getSigningOrder()
×
493
                                        );
×
494
                        }
495
                } else {
496
                        $envelope->setStatus(FileEntity::STATUS_PARTIAL_SIGNED);
×
497
                }
498

499
                $this->fileMapper->update($envelope);
×
500
        }
501

502
        /**
503
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
504
         */
505
        protected function validateDocMdpAllowsSignatures(): void {
506
                $docmdpLevel = $this->libreSignFile->getDocmdpLevelEnum();
18✔
507

508
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED) {
18✔
509
                        throw new LibresignException(
×
510
                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
×
511
                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
×
512
                        );
×
513
                }
514

515
                if ($docmdpLevel === \OCA\Libresign\Enum\DocMdpLevel::NOT_CERTIFIED) {
18✔
516
                        $resource = $this->getLibreSignFileAsResource();
18✔
517

518
                        try {
519
                                if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
17✔
520
                                        throw new LibresignException(
3✔
521
                                                $this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
3✔
522
                                                AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
523
                                        );
3✔
524
                                }
525
                        } finally {
526
                                fclose($resource);
17✔
527
                        }
528
                }
529
        }
530

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

551
        protected function computeHash(File $file): string {
552
                return hash('sha256', $file->getContent());
2✔
553
        }
554

555
        protected function updateSignRequest(string $hash): void {
556
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
557
                $this->signRequest->setSigned($lastSignedDate);
14✔
558
                $this->signRequest->setSignedHash($hash);
14✔
559
                $this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
14✔
560

561
                $this->signRequestMapper->update($this->signRequest);
14✔
562

563
                $this->sequentialSigningService
14✔
564
                        ->setFile($this->libreSignFile)
14✔
565
                        ->releaseNextOrder(
14✔
566
                                $this->signRequest->getFileId(),
14✔
567
                                $this->signRequest->getSigningOrder()
14✔
568
                        );
14✔
569
        }
570

571
        protected function updateLibreSignFile(int $nodeId, string $hash): void {
572
                $this->libreSignFile->setSignedNodeId($nodeId);
14✔
573
                $this->libreSignFile->setSignedHash($hash);
14✔
574
                $this->setNewStatusIfNecessary();
14✔
575
                $this->fileMapper->update($this->libreSignFile);
14✔
576

577
                if ($this->libreSignFile->hasParent()) {
14✔
578
                        $this->fileStatusService->propagateStatusToParent($this->libreSignFile->getParentFileId());
×
579
                }
580
        }
581

582
        protected function dispatchSignedEvent(): void {
583
                $event = $this->signedEventFactory->make(
14✔
584
                        $this->signRequest,
14✔
585
                        $this->libreSignFile,
14✔
586
                        $this->getEngine()->getInputFile(),
14✔
587
                );
14✔
588
                $this->eventDispatcher->dispatchTyped($event);
14✔
589
        }
590

591
        protected function identifyEngine(File $file): SignEngineHandler {
592
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
593
        }
594

595
        protected function getSignatureParams(): array {
596
                $certificateData = $this->readCertificate();
15✔
597
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
598
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
599
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
600
                return $signatureParams;
15✔
601
        }
602

603
        private function buildBaseSignatureParams(array $certificateData): array {
604
                return [
15✔
605
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
606
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
607
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
608
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
609
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
610
                                ->format(DateTimeInterface::ATOM)
15✔
611
                ];
15✔
612
        }
613

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

635
        private function addMetadataToSignatureParams(array $signatureParams): array {
636
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
637
                if (isset($signRequestMetadata['remote-address'])) {
15✔
638
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
639
                }
640
                if (isset($signRequestMetadata['user-agent'])) {
15✔
641
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
642
                }
643
                return $signatureParams;
15✔
644
        }
645

646
        public function storeUserMetadata(array $metadata = []): self {
647
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
648
                if (!$collectMetadata || !$metadata) {
18✔
649
                        return $this;
7✔
650
                }
651
                $this->signRequest->setMetadata(array_merge(
11✔
652
                        $this->signRequest->getMetadata() ?? [],
11✔
653
                        $metadata,
11✔
654
                ));
11✔
655
                $this->signRequestMapper->update($this->signRequest);
11✔
656
                return $this;
11✔
657
        }
658

659
        /**
660
         * @return SignRequestEntity[]
661
         */
662
        protected function getSigners(): array {
663
                if (empty($this->signers)) {
×
664
                        $this->signers = $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
665
                        if ($this->signers) {
×
666
                                foreach ($this->signers as $key => $signer) {
×
667
                                        if ($signer->getId() === $this->signRequest->getId()) {
×
668
                                                $this->signers[$key] = $this->signRequest;
×
669
                                                break;
×
670
                                        }
671
                                }
672
                        }
673
                }
674
                return $this->signers;
×
675
        }
676

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

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

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

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

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

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

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

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

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

707
                return null;
1✔
708
        }
709

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1015
        public function getIdDocById(int $fileId): IdDocs {
1016
                return $this->idDocsMapper->getByFileId($fileId);
×
1017
        }
1018

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

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

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

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

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

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

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

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

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

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

1151
                $childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
×
1152
                        $fileEntity->getId(),
×
1153
                        $signRequestEntity->getId()
×
1154
                );
×
1155

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

1164
                return $pdfUrls;
×
1165
        }
1166
}
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