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

LibreSign / libresign / 19928466437

04 Dec 2025 12:09PM UTC coverage: 41.374%. First build
19928466437

Pull #5988

github

web-flow
Merge 63ce2c8de into aa586ed2c
Pull Request #5988: refactor: footer handler reduce coupling

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

5132 of 12404 relevant lines covered (41.37%)

4.15 hits per line

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

59.38
/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\FooterHandler;
33
use OCA\Libresign\Handler\PdfTk\Pdf;
34
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
35
use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
36
use OCA\Libresign\Handler\SignEngine\SignEngineHandler;
37
use OCA\Libresign\Helper\JSActions;
38
use OCA\Libresign\Helper\ValidateHelper;
39
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
40
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
41
use OCP\AppFramework\Db\DoesNotExistException;
42
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
43
use OCP\AppFramework\Utility\ITimeFactory;
44
use OCP\EventDispatcher\IEventDispatcher;
45
use OCP\Files\File;
46
use OCP\Files\IRootFolder;
47
use OCP\Files\NotPermittedException;
48
use OCP\Http\Client\IClientService;
49
use OCP\IAppConfig;
50
use OCP\IDateTimeZone;
51
use OCP\IL10N;
52
use OCP\ITempManager;
53
use OCP\IURLGenerator;
54
use OCP\IUser;
55
use OCP\IUserManager;
56
use OCP\IUserSession;
57
use OCP\Security\Events\GenerateSecurePasswordEvent;
58
use OCP\Security\ISecureRandom;
59
use Psr\Log\LoggerInterface;
60
use RuntimeException;
61
use Sabre\DAV\UUIDUtil;
62

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

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

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

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

165
        /**
166
         * @return static
167
         */
168
        public function setLibreSignFile(FileEntity $libreSignFile): self {
169
                $this->libreSignFile = $libreSignFile;
29✔
170
                return $this;
29✔
171
        }
172

173
        public function setUserUniqueIdentifier(string $identifier): self {
174
                $this->userUniqueIdentifier = $identifier;
×
175
                return $this;
×
176
        }
177

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

183
        /**
184
         * @return static
185
         */
186
        public function setSignRequest(SignRequestEntity $signRequest): self {
187
                $this->signRequest = $signRequest;
62✔
188
                return $this;
62✔
189
        }
190

191
        /**
192
         * @return static
193
         */
194
        public function setSignWithoutPassword(bool $signWithoutPassword = true): self {
195
                $this->signWithoutPassword = $signWithoutPassword;
2✔
196
                return $this;
2✔
197
        }
198

199
        /**
200
         * @return static
201
         */
202
        public function setPassword(?string $password = null): self {
203
                $this->password = $password;
2✔
204
                return $this;
2✔
205
        }
206

207
        public function setCurrentUser(?IUser $user): self {
208
                $this->user = $user;
24✔
209
                return $this;
24✔
210
        }
211

212
        public function setVisibleElements(array $list): self {
213
                $fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($this->signRequest->getFileId(), $this->signRequest->getId());
14✔
214
                $canCreateSignature = $this->signerElementsService->canCreateSignature();
14✔
215

216
                foreach ($fileElements as $fileElement) {
14✔
217
                        $this->elements[] = $this->buildVisibleElementAssoc($fileElement, $list, $canCreateSignature);
12✔
218
                }
219

220
                return $this;
5✔
221
        }
222

223
        private function buildVisibleElementAssoc(FileElement $fileElement, array $list, bool $canCreateSignature): VisibleElementAssoc {
224
                if (!$canCreateSignature) {
12✔
225
                        return new VisibleElementAssoc($fileElement);
1✔
226
                }
227

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

231
                return $this->bindFileElementWithTempFile($fileElement, $nodeId);
7✔
232
        }
233

234
        private function getNodeId(?array $element, FileElement $fileElement): int {
235
                if ($this->isValidElement($element)) {
11✔
236
                        return (int)$element['profileNodeId'];
7✔
237
                }
238

239
                return $this->retrieveUserElement($fileElement);
×
240
        }
241

242
        private function isValidElement(?array $element): bool {
243
                if (is_array($element) && !empty($element['profileNodeId']) && is_int($element['profileNodeId'])) {
11✔
244
                        return true;
7✔
245
                }
246
                $this->logger->error('Invalid data provided for signing file.', ['element' => $element]);
4✔
247
                throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
4✔
248
        }
249

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

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

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

285
        private function getNode(int $nodeId): ?File {
286
                if ($this->user instanceof IUser) {
7✔
287
                        return $this->folderService->getFileById($nodeId);
6✔
288
                }
289

290
                $filesOfElementes = $this->signerElementsService->getElementsFromSession();
1✔
291
                return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
1✔
292
        }
293

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

309
                return null;
3✔
310
        }
311

312
        /**
313
         * @return VisibleElementAssoc[]
314
         */
315
        public function getVisibleElements(): array {
316
                return $this->elements;
7✔
317
        }
318

319
        public function sign(): File {
320
                $signedFile = $this->getEngine()->sign();
17✔
321

322
                $hash = $this->computeHash($signedFile);
16✔
323

324
                $this->updateSignRequest($hash);
16✔
325
                $this->updateLibreSignFile($hash);
16✔
326

327
                $this->dispatchSignedEvent();
16✔
328

329
                return $signedFile;
16✔
330
        }
331

332
        protected function computeHash(File $file): string {
333
                return hash('sha256', $file->getContent());
2✔
334
        }
335

336
        protected function updateSignRequest(string $hash): void {
337
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
338
                $this->signRequest->setSigned($lastSignedDate);
14✔
339
                $this->signRequest->setSignedHash($hash);
14✔
340
                $this->signRequestMapper->update($this->signRequest);
14✔
341
        }
342

343
        protected function updateLibreSignFile(string $hash): void {
344
                $nodeId = $this->getEngine()->getInputFile()->getId();
14✔
345
                $this->libreSignFile->setSignedNodeId($nodeId);
14✔
346
                $this->libreSignFile->setSignedHash($hash);
14✔
347
                $this->setNewStatusIfNecessary();
14✔
348
                $this->fileMapper->update($this->libreSignFile);
14✔
349
        }
350

351
        protected function dispatchSignedEvent(): void {
352
                $event = $this->signedEventFactory->make(
14✔
353
                        $this->signRequest,
14✔
354
                        $this->libreSignFile,
14✔
355
                        $this->getEngine()->getInputFile(),
14✔
356
                );
14✔
357
                $this->eventDispatcher->dispatchTyped($event);
14✔
358
        }
359

360
        protected function identifyEngine(File $file): SignEngineHandler {
361
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
362
        }
363

364
        protected function getSignatureParams(): array {
365
                $certificateData = $this->readCertificate();
15✔
366
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
367
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
368
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
369
                return $signatureParams;
15✔
370
        }
371

372
        private function buildBaseSignatureParams(array $certificateData): array {
373
                return [
15✔
374
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
375
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
376
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
377
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
378
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
379
                                ->format(DateTimeInterface::ATOM)
15✔
380
                ];
15✔
381
        }
382

383
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
384
                if (isset($certificateData['extensions']['subjectAltName'])) {
15✔
385
                        preg_match('/(?:email:)+(?<email>[^\s,]+)/', $certificateData['extensions']['subjectAltName'], $matches);
6✔
386
                        if ($matches && filter_var($matches['email'], FILTER_VALIDATE_EMAIL)) {
6✔
387
                                $signatureParams['SignerEmail'] = $matches['email'];
4✔
388
                        } elseif (filter_var($certificateData['extensions']['subjectAltName'], FILTER_VALIDATE_EMAIL)) {
2✔
389
                                $signatureParams['SignerEmail'] = $certificateData['extensions']['subjectAltName'];
1✔
390
                        }
391
                }
392
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
393
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
1✔
394
                }
395
                if (empty($signatureParams['SignerEmail'])) {
15✔
396
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
397
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
398
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
399
                        }
400
                }
401
                return $signatureParams;
15✔
402
        }
403

404
        private function addMetadataToSignatureParams(array $signatureParams): array {
405
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
406
                if (isset($signRequestMetadata['remote-address'])) {
15✔
407
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
408
                }
409
                if (isset($signRequestMetadata['user-agent'])) {
15✔
410
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
411
                }
412
                return $signatureParams;
15✔
413
        }
414

415
        public function storeUserMetadata(array $metadata = []): self {
416
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
417
                if (!$collectMetadata || !$metadata) {
18✔
418
                        return $this;
7✔
419
                }
420
                $this->signRequest->setMetadata(array_merge(
11✔
421
                        $this->signRequest->getMetadata() ?? [],
11✔
422
                        $metadata,
11✔
423
                ));
11✔
424
                $this->signRequestMapper->update($this->signRequest);
11✔
425
                return $this;
11✔
426
        }
427

428
        /**
429
         * @return SignRequestEntity[]
430
         */
431
        protected function getSigners(): array {
432
                if (empty($this->signers)) {
×
433
                        $this->signers = $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
434
                        if ($this->signers) {
×
435
                                foreach ($this->signers as $key => $signer) {
×
436
                                        if ($signer->getId() === $this->signRequest->getId()) {
×
437
                                                $this->signers[$key] = $this->signRequest;
×
438
                                                break;
×
439
                                        }
440
                                }
441
                        }
442
                }
443
                return $this->signers;
×
444
        }
445

446
        protected function setNewStatusIfNecessary(): bool {
447
                $newStatus = $this->evaluateStatusFromSigners();
10✔
448

449
                if ($newStatus === null || $newStatus === $this->libreSignFile->getStatus()) {
10✔
450
                        return false;
4✔
451
                }
452

453
                $this->libreSignFile->setStatus($newStatus);
6✔
454
                return true;
6✔
455
        }
456

457
        private function evaluateStatusFromSigners(): ?int {
458
                $signers = $this->getSigners();
10✔
459

460
                $total = count($signers);
10✔
461

462
                if ($total === 0) {
10✔
463
                        return null;
1✔
464
                }
465

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

468
                if ($totalSigned === $total) {
9✔
469
                        return FileEntity::STATUS_SIGNED;
5✔
470
                }
471

472
                if ($totalSigned > 0) {
4✔
473
                        return FileEntity::STATUS_PARTIAL_SIGNED;
3✔
474
                }
475

476
                return null;
1✔
477
        }
478

479
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
480
                if ($certificate = $engine->getCertificate()) {
12✔
481
                        return $certificate;
×
482
                }
483
                if ($this->signWithoutPassword) {
12✔
484
                        $tempPassword = $this->generateTemporaryPassword();
1✔
485
                        $this->setPassword($tempPassword);
1✔
486
                        $engine->generateCertificate(
1✔
487
                                [
1✔
488
                                        'host' => $this->userUniqueIdentifier,
1✔
489
                                        'uid' => $this->userUniqueIdentifier,
1✔
490
                                        'name' => $this->friendlyName,
1✔
491
                                ],
1✔
492
                                $tempPassword,
1✔
493
                                $this->friendlyName,
1✔
494
                        );
1✔
495
                }
496
                return $engine->getPfxOfCurrentSigner();
12✔
497
        }
498

499
        private function generateTemporaryPassword(): string {
500
                $passwordEvent = new GenerateSecurePasswordEvent();
1✔
501
                $this->eventDispatcher->dispatchTyped($passwordEvent);
1✔
502
                return $passwordEvent->getPassword() ?? $this->secureRandom->generate(20);
1✔
503
        }
504

505
        protected function readCertificate(): array {
506
                return $this->getEngine()
×
507
                        ->readCertificate();
×
508
        }
509

510
        /**
511
         * Get file to sign
512
         *
513
         * @throws LibresignException
514
         */
515
        protected function getFileToSign(): File {
516
                if ($this->fileToSign instanceof File) {
1✔
517
                        return $this->fileToSign;
×
518
                }
519

520
                $userId = $this->libreSignFile->getUserId();
1✔
521
                $nodeId = $this->libreSignFile->getNodeId();
1✔
522

523
                $originalFile = $this->root->getUserFolder($userId)->getFirstNodeById($nodeId);
1✔
524
                if (!$originalFile instanceof File) {
1✔
525
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
526
                }
527
                if ($this->isPdf($originalFile)) {
×
528
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
529
                } else {
530
                        $this->fileToSign = $originalFile;
×
531
                }
532
                return $this->fileToSign;
×
533
        }
534

535
        private function isPdf(File $file): bool {
536
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
537
        }
538

539
        protected function getEngine(): SignEngineHandler {
540
                if (!$this->engine) {
13✔
541
                        $originalFile = $this->getFileToSign();
13✔
542
                        $this->engine = $this->identifyEngine($originalFile);
12✔
543

544
                        $this->configureEngine();
12✔
545
                }
546
                return $this->engine;
12✔
547
        }
548

549
        private function configureEngine(): void {
550
                $this->engine
12✔
551
                        ->setInputFile($this->getFileToSign())
12✔
552
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
553
                        ->setPassword($this->password);
12✔
554

555
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
556
                        $this->engine
2✔
557
                                ->setVisibleElements($this->getVisibleElements())
2✔
558
                                ->setSignatureParams($this->getSignatureParams());
2✔
559
                }
560
        }
561

562
        public function getLibresignFile(?int $nodeId, ?string $signRequestUuid = null): FileEntity {
563
                try {
564
                        if ($nodeId) {
3✔
565
                                return $this->fileMapper->getByFileId($nodeId);
1✔
566
                        }
567

568
                        if ($signRequestUuid) {
2✔
569
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
570
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
571
                        }
572

573
                        throw new \Exception('Invalid arguments');
×
574

575
                } catch (DoesNotExistException) {
1✔
576
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
577
                }
578
        }
579

580
        public function renew(SignRequestEntity $signRequest, string $method): void {
581
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
582
                if (empty($identifyMethods[$method])) {
×
583
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
584
                }
585

586
                $signRequest->setUuid(UUIDUtil::getUUID());
×
587
                $this->signRequestMapper->update($signRequest);
×
588

589
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
590
                        $entity = $identifyMethod->getEntity();
×
591
                        $entity->setAttempts($entity->getAttempts() + 1);
×
592
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
593
                        $identifyMethod->save();
×
594
                }, $identifyMethods[$method]);
×
595
        }
596

597
        public function requestCode(
598
                SignRequestEntity $signRequest,
599
                string $identifyMethodName,
600
                string $signMethodName,
601
                string $identify = '',
602
        ): void {
603
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
604
                if (empty($identifyMethods[$identifyMethodName])) {
×
605
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
606
                }
607
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
608
                        try {
609
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
610
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
611
                        } catch (InvalidArgumentException) {
×
612
                                continue;
×
613
                        }
614
                        /** @var IToken $signatureMethod */
615
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
616
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
617
                        return;
×
618
                }
619
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
620
        }
621

622
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
623
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
624
                try {
625
                        $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
626

627
                        if (!empty($signRequestUuid)) {
2✔
628
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
629
                        } else {
630
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
631
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
632
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
633
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
634
                                                        && $user
635
                                                        && (
636
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
637
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
638
                                                        )
639
                                                ) {
640
                                                        return true;
×
641
                                                }
642
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
643
                                                        && $user
644
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
645
                                                ) {
646
                                                        return true;
×
647
                                                }
648
                                                return false;
×
649
                                        });
×
650
                                        if (count($found) > 0) {
×
651
                                                return $signRequest;
×
652
                                        }
653
                                        return $carry;
×
654
                                });
×
655
                        }
656

657
                        if (!$signRequest) {
2✔
658
                                throw new DoesNotExistException('Sign request not found');
×
659
                        }
660
                        if ($signRequest->getSigned()) {
2✔
661
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
662
                        }
663
                        return $signRequest;
2✔
664
                } catch (DoesNotExistException) {
×
665
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
666
                }
667
        }
668

669
        protected function getPdfToSign(File $originalFile): File {
670
                $file = $this->getSignedFile();
×
671
                if ($file instanceof File) {
×
672
                        return $file;
×
673
                }
NEW
674
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
675
                $footer = $this->footerHandler
×
676
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
677
                                'displayName' => $signer->getDisplayName(),
×
678
                                'signed' => $signer->getSigned()
×
679
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
680
                                        : null,
681
                        ], $this->getSigners()))
×
NEW
682
                        ->getFooter($metadata['d'], $this->libreSignFile);
×
683
                if ($footer) {
×
684
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
685
                        file_put_contents($stamp, $footer);
×
686

687
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
688
                        file_put_contents($input, $originalFile->getContent());
×
689

690
                        try {
691
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
692
                        } catch (RuntimeException $e) {
×
693
                                throw new LibresignException($e->getMessage());
×
694
                        }
695
                } else {
696
                        $pdfContent = $originalFile->getContent();
×
697
                }
698
                return $this->createSignedFile($originalFile, $pdfContent);
×
699
        }
700

701
        protected function getSignedFile(): ?File {
702
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
703
                if (!$nodeId) {
3✔
704
                        return null;
1✔
705
                }
706

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

709
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
710
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
711
                }
712
                return $fileToSign;
2✔
713
        }
714

715
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
716
                try {
717
                        $fileToSign = $this->root->getUserFolder($uid)->getFirstNodeById($nodeId);
4✔
718
                } catch (NoUserException) {
2✔
719
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
720
                } catch (NotPermittedException) {
1✔
721
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
722
                }
723
                if (!$fileToSign instanceof File) {
2✔
724
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
725
                }
726
                return $fileToSign;
1✔
727
        }
728

729
        private function createSignedFile(File $originalFile, string $content): File {
730
                $filename = preg_replace(
×
731
                        '/' . $originalFile->getExtension() . '$/',
×
732
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
733
                        basename($originalFile->getPath())
×
734
                );
×
735
                $owner = $originalFile->getOwner()->getUID();
×
736
                try {
737
                        /** @var \OCP\Files\Folder */
738
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
739
                        return $parentFolder->newFile($filename, $content);
×
740
                } catch (NotPermittedException) {
×
741
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
742
                }
743
        }
744

745
        /**
746
         * @throws DoesNotExistException
747
         */
748
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
749
                $this->validateHelper->validateUuidFormat($uuid);
4✔
750
                return $this->signRequestMapper->getByUuid($uuid);
3✔
751
        }
752

753
        /**
754
         * @throws DoesNotExistException
755
         */
756
        public function getFile(int $signRequestId): FileEntity {
757
                return $this->fileMapper->getById($signRequestId);
×
758
        }
759

760
        /**
761
         * @throws DoesNotExistException
762
         */
763
        public function getFileByUuid(string $uuid): FileEntity {
764
                return $this->fileMapper->getByUuid($uuid);
×
765
        }
766

767
        public function getIdDocById(int $fileId): IdDocs {
768
                return $this->idDocsMapper->getByFileId($fileId);
×
769
        }
770

771
        public function getNextcloudFile(FileEntity $fileData): File {
772
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($fileData->getNodeId());
×
773
                if (!$fileToSign instanceof File) {
×
774
                        throw new LibresignException(json_encode([
×
775
                                'action' => JSActions::ACTION_DO_NOTHING,
×
776
                                'errors' => [['message' => $this->l10n->t('File not found')]],
×
777
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
×
778
                }
779
                return $fileToSign;
×
780
        }
781

782
        public function validateSigner(string $uuid, ?IUser $user = null): void {
783
                $this->validateHelper->validateSigner($uuid, $user);
×
784
        }
785

786
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
787
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
788
        }
789

790
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
791
                $return = ['user' => ['name' => null]];
×
792
                if ($signRequest) {
×
793
                        $return['user']['name'] = $signRequest->getDisplayName();
×
794
                } elseif ($user) {
×
795
                        $return['user']['name'] = $user->getDisplayName();
×
796
                }
797
                return $return;
×
798
        }
799

800
        public function getAvailableIdentifyMethodsFromSettings(): array {
801
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
802
                $return = array_map(fn (array $identifyMethod): array => [
×
803
                        'mandatory' => $identifyMethod['mandatory'],
×
804
                        'identifiedAtDate' => null,
×
805
                        'validateCode' => false,
×
806
                        'method' => $identifyMethod['name'],
×
807
                ], $identifyMethods);
×
808
                return $return;
×
809
        }
810

811
        /**
812
         * @psalm-return array{file?: File, nodeId?: int, url?: string, base64?: string}
813
         */
814
        public function getFileUrl(string $format, FileEntity $fileEntity, File $fileToSign, string $uuid): array {
815
                $url = [];
×
816
                switch ($format) {
817
                        case 'base64':
×
818
                                $url = ['base64' => base64_encode($fileToSign->getContent())];
×
819
                                break;
×
820
                        case 'url':
×
821
                                try {
822
                                        $this->idDocsMapper->getByFileId($fileEntity->getId());
×
823
                                        $url = ['url' => $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid])];
×
824
                                } catch (DoesNotExistException) {
×
825
                                        $url = ['url' => $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid])];
×
826
                                }
827
                                break;
×
828
                        case 'nodeId':
×
829
                                $url = ['nodeId' => $fileToSign->getId()];
×
830
                                break;
×
831
                        case 'file':
×
832
                                $url = ['file' => $fileToSign];
×
833
                                break;
×
834
                }
835
                return $url;
×
836
        }
837
}
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