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

LibreSign / libresign / 20047893885

09 Dec 2025 12:46AM UTC coverage: 44.16%. First build
20047893885

Pull #6035

github

web-flow
Merge b1a68dcdc into 2abe0feb0
Pull Request #6035: fix: prevent footer on signed pdfs

12 of 19 new or added lines in 2 files covered. (63.16%)

5690 of 12885 relevant lines covered (44.16%)

5.11 hits per line

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

60.15
/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;
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
        ) {
109
        }
138✔
110

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

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

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

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

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

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

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

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

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

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

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

223
                return $this;
5✔
224
        }
225

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

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

234
                return $this->bindFileElementWithTempFile($fileElement, $nodeId);
7✔
235
        }
236

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

242
                return $this->retrieveUserElement($fileElement);
×
243
        }
244

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

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

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

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

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

293
                $filesOfElementes = $this->signerElementsService->getElementsFromSession();
1✔
294
                return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
1✔
295
        }
296

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

312
                return null;
3✔
313
        }
314

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

322
        public function sign(): File {
323
                $this->validateDocMdpAllowsSignatures();
18✔
324
                $signedFile = $this->getEngine()->sign();
16✔
325

326
                $hash = $this->computeHash($signedFile);
16✔
327

328
                $this->updateSignRequest($hash);
16✔
329
                $this->updateLibreSignFile($hash);
16✔
330

331
                $this->dispatchSignedEvent();
16✔
332

333
                return $signedFile;
16✔
334
        }
335

336
        /**
337
         * @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
338
         */
339
        protected function validateDocMdpAllowsSignatures(): void {
340
                $resource = $this->getLibreSignFileAsResource();
22✔
341

342
                try {
343
                        if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
21✔
344
                                throw new LibresignException(
3✔
345
                                        $this->l10n->t('This document has been certified with no changes allowed, so no additional signatures can be added.'),
3✔
346
                                        AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
347
                                );
3✔
348
                        }
349
                } finally {
350
                        fclose($resource);
21✔
351
                }
352
        }
353

354
        /**
355
         * @return resource
356
         * @throws LibresignException
357
         */
358
        protected function getLibreSignFileAsResource() {
359
                $fileToSign = $this->getNextcloudFile($this->libreSignFile);
16✔
360
                $content = $fileToSign->getContent();
15✔
361
                $resource = fopen('php://memory', 'r+');
15✔
362
                if ($resource === false) {
15✔
363
                        throw new LibresignException('Failed to create temporary resource for PDF validation');
×
364
                }
365
                fwrite($resource, $content);
15✔
366
                rewind($resource);
15✔
367
                return $resource;
15✔
368
        }
369

370
        protected function computeHash(File $file): string {
371
                return hash('sha256', $file->getContent());
2✔
372
        }
373

374
        protected function updateSignRequest(string $hash): void {
375
                $lastSignedDate = $this->getEngine()->getLastSignedDate();
14✔
376
                $this->signRequest->setSigned($lastSignedDate);
14✔
377
                $this->signRequest->setSignedHash($hash);
14✔
378
                $this->signRequestMapper->update($this->signRequest);
14✔
379
        }
380

381
        protected function updateLibreSignFile(string $hash): void {
382
                $nodeId = $this->getEngine()->getInputFile()->getId();
14✔
383
                $this->libreSignFile->setSignedNodeId($nodeId);
14✔
384
                $this->libreSignFile->setSignedHash($hash);
14✔
385
                $this->setNewStatusIfNecessary();
14✔
386
                $this->fileMapper->update($this->libreSignFile);
14✔
387
        }
388

389
        protected function dispatchSignedEvent(): void {
390
                $event = $this->signedEventFactory->make(
14✔
391
                        $this->signRequest,
14✔
392
                        $this->libreSignFile,
14✔
393
                        $this->getEngine()->getInputFile(),
14✔
394
                );
14✔
395
                $this->eventDispatcher->dispatchTyped($event);
14✔
396
        }
397

398
        protected function identifyEngine(File $file): SignEngineHandler {
399
                return $this->signEngineFactory->resolve($file->getExtension());
10✔
400
        }
401

402
        protected function getSignatureParams(): array {
403
                $certificateData = $this->readCertificate();
15✔
404
                $signatureParams = $this->buildBaseSignatureParams($certificateData);
15✔
405
                $signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
15✔
406
                $signatureParams = $this->addMetadataToSignatureParams($signatureParams);
15✔
407
                return $signatureParams;
15✔
408
        }
409

410
        private function buildBaseSignatureParams(array $certificateData): array {
411
                return [
15✔
412
                        'DocumentUUID' => $this->libreSignFile?->getUuid(),
15✔
413
                        'IssuerCommonName' => $certificateData['issuer']['CN'] ?? '',
15✔
414
                        'SignerCommonName' => $certificateData['subject']['CN'] ?? '',
15✔
415
                        'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
15✔
416
                        'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
15✔
417
                                ->format(DateTimeInterface::ATOM)
15✔
418
                ];
15✔
419
        }
420

421
        private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
422
                if (isset($certificateData['extensions']['subjectAltName'])) {
15✔
423
                        preg_match('/(?:email:)+(?<email>[^\s,]+)/', $certificateData['extensions']['subjectAltName'], $matches);
6✔
424
                        if ($matches && filter_var($matches['email'], FILTER_VALIDATE_EMAIL)) {
6✔
425
                                $signatureParams['SignerEmail'] = $matches['email'];
4✔
426
                        } elseif (filter_var($certificateData['extensions']['subjectAltName'], FILTER_VALIDATE_EMAIL)) {
2✔
427
                                $signatureParams['SignerEmail'] = $certificateData['extensions']['subjectAltName'];
1✔
428
                        }
429
                }
430
                if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
15✔
431
                        $signatureParams['SignerEmail'] = $this->user->getEMailAddress();
1✔
432
                }
433
                if (empty($signatureParams['SignerEmail'])) {
15✔
434
                        $identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
9✔
435
                        if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
9✔
436
                                $signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
1✔
437
                        }
438
                }
439
                return $signatureParams;
15✔
440
        }
441

442
        private function addMetadataToSignatureParams(array $signatureParams): array {
443
                $signRequestMetadata = $this->signRequest->getMetadata();
15✔
444
                if (isset($signRequestMetadata['remote-address'])) {
15✔
445
                        $signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
2✔
446
                }
447
                if (isset($signRequestMetadata['user-agent'])) {
15✔
448
                        $signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
2✔
449
                }
450
                return $signatureParams;
15✔
451
        }
452

453
        public function storeUserMetadata(array $metadata = []): self {
454
                $collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
18✔
455
                if (!$collectMetadata || !$metadata) {
18✔
456
                        return $this;
7✔
457
                }
458
                $this->signRequest->setMetadata(array_merge(
11✔
459
                        $this->signRequest->getMetadata() ?? [],
11✔
460
                        $metadata,
11✔
461
                ));
11✔
462
                $this->signRequestMapper->update($this->signRequest);
11✔
463
                return $this;
11✔
464
        }
465

466
        /**
467
         * @return SignRequestEntity[]
468
         */
469
        protected function getSigners(): array {
470
                if (empty($this->signers)) {
×
471
                        $this->signers = $this->signRequestMapper->getByFileId($this->signRequest->getFileId());
×
472
                        if ($this->signers) {
×
473
                                foreach ($this->signers as $key => $signer) {
×
474
                                        if ($signer->getId() === $this->signRequest->getId()) {
×
475
                                                $this->signers[$key] = $this->signRequest;
×
476
                                                break;
×
477
                                        }
478
                                }
479
                        }
480
                }
481
                return $this->signers;
×
482
        }
483

484
        protected function setNewStatusIfNecessary(): bool {
485
                $newStatus = $this->evaluateStatusFromSigners();
10✔
486

487
                if ($newStatus === null || $newStatus === $this->libreSignFile->getStatus()) {
10✔
488
                        return false;
4✔
489
                }
490

491
                $this->libreSignFile->setStatus($newStatus);
6✔
492
                return true;
6✔
493
        }
494

495
        private function evaluateStatusFromSigners(): ?int {
496
                $signers = $this->getSigners();
10✔
497

498
                $total = count($signers);
10✔
499

500
                if ($total === 0) {
10✔
501
                        return null;
1✔
502
                }
503

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

506
                if ($totalSigned === $total) {
9✔
507
                        return FileEntity::STATUS_SIGNED;
5✔
508
                }
509

510
                if ($totalSigned > 0) {
4✔
511
                        return FileEntity::STATUS_PARTIAL_SIGNED;
3✔
512
                }
513

514
                return null;
1✔
515
        }
516

517
        private function getOrGeneratePfxContent(SignEngineHandler $engine): string {
518
                if ($certificate = $engine->getCertificate()) {
12✔
519
                        return $certificate;
×
520
                }
521
                if ($this->signWithoutPassword) {
12✔
522
                        $tempPassword = $this->generateTemporaryPassword();
1✔
523
                        $this->setPassword($tempPassword);
1✔
524
                        $engine->generateCertificate(
1✔
525
                                [
1✔
526
                                        'host' => $this->userUniqueIdentifier,
1✔
527
                                        'uid' => $this->userUniqueIdentifier,
1✔
528
                                        'name' => $this->friendlyName,
1✔
529
                                ],
1✔
530
                                $tempPassword,
1✔
531
                                $this->friendlyName,
1✔
532
                        );
1✔
533
                }
534
                return $engine->getPfxOfCurrentSigner();
12✔
535
        }
536

537
        private function generateTemporaryPassword(): string {
538
                $passwordEvent = new GenerateSecurePasswordEvent();
1✔
539
                $this->eventDispatcher->dispatchTyped($passwordEvent);
1✔
540
                return $passwordEvent->getPassword() ?? $this->secureRandom->generate(20);
1✔
541
        }
542

543
        protected function readCertificate(): array {
544
                return $this->getEngine()
×
545
                        ->readCertificate();
×
546
        }
547

548
        /**
549
         * Get file to sign
550
         *
551
         * @throws LibresignException
552
         */
553
        protected function getFileToSign(): File {
554
                if ($this->fileToSign instanceof File) {
×
555
                        return $this->fileToSign;
×
556
                }
557

558
                $userId = $this->libreSignFile->getUserId();
×
559
                $nodeId = $this->libreSignFile->getNodeId();
×
560

561
                $originalFile = $this->root->getUserFolder($userId)->getFirstNodeById($nodeId);
×
562
                if (!$originalFile instanceof File) {
×
563
                        throw new LibresignException($this->l10n->t('File not found'));
×
564
                }
565
                if ($this->isPdf($originalFile)) {
×
566
                        $this->fileToSign = $this->getPdfToSign($originalFile);
×
567
                } else {
568
                        $this->fileToSign = $originalFile;
×
569
                }
570
                return $this->fileToSign;
×
571
        }
572

573
        private function isPdf(File $file): bool {
574
                return strcasecmp($file->getExtension(), 'pdf') === 0;
×
575
        }
576

577
        protected function getEngine(): SignEngineHandler {
578
                if (!$this->engine) {
12✔
579
                        $originalFile = $this->getFileToSign();
12✔
580
                        $this->engine = $this->identifyEngine($originalFile);
12✔
581

582
                        $this->configureEngine();
12✔
583
                }
584
                return $this->engine;
12✔
585
        }
586

587
        private function configureEngine(): void {
588
                $this->engine
12✔
589
                        ->setInputFile($this->getFileToSign())
12✔
590
                        ->setCertificate($this->getOrGeneratePfxContent($this->engine))
12✔
591
                        ->setPassword($this->password);
12✔
592

593
                if ($this->engine::class === Pkcs12Handler::class) {
12✔
594
                        $this->engine
2✔
595
                                ->setVisibleElements($this->getVisibleElements())
2✔
596
                                ->setSignatureParams($this->getSignatureParams());
2✔
597
                }
598
        }
599

600
        public function getLibresignFile(?int $nodeId, ?string $signRequestUuid = null): FileEntity {
601
                try {
602
                        if ($nodeId) {
3✔
603
                                return $this->fileMapper->getByFileId($nodeId);
1✔
604
                        }
605

606
                        if ($signRequestUuid) {
2✔
607
                                $signRequest = $this->signRequestMapper->getByUuid($signRequestUuid);
2✔
608
                                return $this->fileMapper->getById($signRequest->getFileId());
2✔
609
                        }
610

611
                        throw new \Exception('Invalid arguments');
×
612

613
                } catch (DoesNotExistException) {
1✔
614
                        throw new LibresignException($this->l10n->t('File not found'), 1);
1✔
615
                }
616
        }
617

618
        public function renew(SignRequestEntity $signRequest, string $method): void {
619
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
620
                if (empty($identifyMethods[$method])) {
×
621
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
622
                }
623

624
                $signRequest->setUuid(UUIDUtil::getUUID());
×
625
                $this->signRequestMapper->update($signRequest);
×
626

627
                array_map(function (IIdentifyMethod $identifyMethod): void {
×
628
                        $entity = $identifyMethod->getEntity();
×
629
                        $entity->setAttempts($entity->getAttempts() + 1);
×
630
                        $entity->setLastAttemptDate($this->timeFactory->getDateTime());
×
631
                        $identifyMethod->save();
×
632
                }, $identifyMethods[$method]);
×
633
        }
634

635
        public function requestCode(
636
                SignRequestEntity $signRequest,
637
                string $identifyMethodName,
638
                string $signMethodName,
639
                string $identify = '',
640
        ): void {
641
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
642
                if (empty($identifyMethods[$identifyMethodName])) {
×
643
                        throw new LibresignException($this->l10n->t('Invalid identification method'));
×
644
                }
645
                foreach ($identifyMethods[$identifyMethodName] as $identifyMethod) {
×
646
                        try {
647
                                $signatureMethod = $identifyMethod->getEmptyInstanceOfSignatureMethodByName($signMethodName);
×
648
                                $signatureMethod->setEntity($identifyMethod->getEntity());
×
649
                        } catch (InvalidArgumentException) {
×
650
                                continue;
×
651
                        }
652
                        /** @var IToken $signatureMethod */
653
                        $identifier = $identify ?: $identifyMethod->getEntity()->getIdentifierValue();
×
654
                        $signatureMethod->requestCode($identifier, $identifyMethod->getEntity()->getIdentifierKey());
×
655
                        return;
×
656
                }
657
                throw new LibresignException($this->l10n->t('Sending authorization code not enabled.'));
×
658
        }
659

660
        public function getSignRequestToSign(FileEntity $libresignFile, ?string $signRequestUuid, ?IUser $user): SignRequestEntity {
661
                $this->validateHelper->fileCanBeSigned($libresignFile);
2✔
662
                try {
663
                        $signRequests = $this->signRequestMapper->getByFileId($libresignFile->getId());
2✔
664

665
                        if (!empty($signRequestUuid)) {
2✔
666
                                $signRequest = $this->getSignRequestByUuid($signRequestUuid);
2✔
667
                        } else {
668
                                $signRequest = array_reduce($signRequests, function (?SignRequestEntity $carry, SignRequestEntity $signRequest) use ($user): ?SignRequestEntity {
×
669
                                        $identifyMethods = $this->identifyMethodMapper->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
670
                                        $found = array_filter($identifyMethods, function (IdentifyMethod $identifyMethod) use ($user) {
×
671
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_EMAIL
×
672
                                                        && $user
673
                                                        && (
674
                                                                $identifyMethod->getIdentifierValue() === $user->getUID()
×
675
                                                                || $identifyMethod->getIdentifierValue() === $user->getEMailAddress()
×
676
                                                        )
677
                                                ) {
678
                                                        return true;
×
679
                                                }
680
                                                if ($identifyMethod->getIdentifierKey() === IdentifyMethodService::IDENTIFY_ACCOUNT
×
681
                                                        && $user
682
                                                        && $identifyMethod->getIdentifierValue() === $user->getUID()
×
683
                                                ) {
684
                                                        return true;
×
685
                                                }
686
                                                return false;
×
687
                                        });
×
688
                                        if (count($found) > 0) {
×
689
                                                return $signRequest;
×
690
                                        }
691
                                        return $carry;
×
692
                                });
×
693
                        }
694

695
                        if (!$signRequest) {
2✔
696
                                throw new DoesNotExistException('Sign request not found');
×
697
                        }
698
                        if ($signRequest->getSigned()) {
2✔
699
                                throw new LibresignException($this->l10n->t('File already signed by you'), 1);
×
700
                        }
701
                        return $signRequest;
2✔
702
                } catch (DoesNotExistException) {
×
703
                        throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
×
704
                }
705
        }
706

707
        protected function getPdfToSign(File $originalFile): File {
708
                $file = $this->getSignedFile();
×
709
                if ($file instanceof File) {
×
710
                        return $file;
×
711
                }
712

NEW
713
                $originalContent = $originalFile->getContent();
×
714

NEW
715
                if ($this->pdfSignatureDetectionService->hasSignatures($originalContent)) {
×
NEW
716
                        return $this->createSignedFile($originalFile, $originalContent);
×
717
                }
718
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
719
                $footer = $this->footerHandler
×
720
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
721
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
722
                                'displayName' => $signer->getDisplayName(),
×
723
                                'signed' => $signer->getSigned()
×
724
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
725
                                        : null,
726
                        ], $this->getSigners()))
×
727
                        ->getFooter($metadata['d']);
×
728
                if ($footer) {
×
729
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
730
                        file_put_contents($stamp, $footer);
×
731

732
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
NEW
733
                        file_put_contents($input, $originalContent);
×
734

735
                        try {
736
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
737
                        } catch (RuntimeException $e) {
×
738
                                throw new LibresignException($e->getMessage());
×
739
                        }
740
                } else {
NEW
741
                        $pdfContent = $originalContent;
×
742
                }
743
                return $this->createSignedFile($originalFile, $pdfContent);
×
744
        }
745

746
        protected function getSignedFile(): ?File {
747
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
748
                if (!$nodeId) {
3✔
749
                        return null;
1✔
750
                }
751

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

754
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
755
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
756
                }
757
                return $fileToSign;
2✔
758
        }
759

760
        protected function getNodeByIdUsingUid(string $uid, int $nodeId): File {
761
                try {
762
                        $fileToSign = $this->root->getUserFolder($uid)->getFirstNodeById($nodeId);
4✔
763
                } catch (NoUserException) {
2✔
764
                        throw new LibresignException($this->l10n->t('User not found.'));
1✔
765
                } catch (NotPermittedException) {
1✔
766
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
1✔
767
                }
768
                if (!$fileToSign instanceof File) {
2✔
769
                        throw new LibresignException($this->l10n->t('File not found'));
1✔
770
                }
771
                return $fileToSign;
1✔
772
        }
773

774
        private function createSignedFile(File $originalFile, string $content): File {
775
                $filename = preg_replace(
×
776
                        '/' . $originalFile->getExtension() . '$/',
×
777
                        $this->l10n->t('signed') . '.' . $originalFile->getExtension(),
×
778
                        basename($originalFile->getPath())
×
779
                );
×
780
                $owner = $originalFile->getOwner()->getUID();
×
781
                try {
782
                        /** @var \OCP\Files\Folder */
783
                        $parentFolder = $this->root->getUserFolder($owner)->getFirstNodeById($originalFile->getParentId());
×
784
                        return $parentFolder->newFile($filename, $content);
×
785
                } catch (NotPermittedException) {
×
786
                        throw new LibresignException($this->l10n->t('You do not have permission for this action.'));
×
787
                }
788
        }
789

790
        /**
791
         * @throws DoesNotExistException
792
         */
793
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
794
                $this->validateHelper->validateUuidFormat($uuid);
4✔
795
                return $this->signRequestMapper->getByUuid($uuid);
3✔
796
        }
797

798
        /**
799
         * @throws DoesNotExistException
800
         */
801
        public function getFile(int $signRequestId): FileEntity {
802
                return $this->fileMapper->getById($signRequestId);
×
803
        }
804

805
        /**
806
         * @throws DoesNotExistException
807
         */
808
        public function getFileByUuid(string $uuid): FileEntity {
809
                return $this->fileMapper->getByUuid($uuid);
×
810
        }
811

812
        public function getIdDocById(int $fileId): IdDocs {
813
                return $this->idDocsMapper->getByFileId($fileId);
×
814
        }
815

816
        public function getNextcloudFile(FileEntity $fileData): File {
817
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($fileData->getNodeId());
1✔
818
                if (!$fileToSign instanceof File) {
1✔
819
                        throw new LibresignException(json_encode([
1✔
820
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
821
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
822
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
823
                }
824
                return $fileToSign;
×
825
        }
826

827
        public function validateSigner(string $uuid, ?IUser $user = null): void {
828
                $this->validateHelper->validateSigner($uuid, $user);
×
829
        }
830

831
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
832
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
833
        }
834

835
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
836
                $return = ['user' => ['name' => null]];
×
837
                if ($signRequest) {
×
838
                        $return['user']['name'] = $signRequest->getDisplayName();
×
839
                } elseif ($user) {
×
840
                        $return['user']['name'] = $user->getDisplayName();
×
841
                }
842
                return $return;
×
843
        }
844

845
        public function getAvailableIdentifyMethodsFromSettings(): array {
846
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
847
                $return = array_map(fn (array $identifyMethod): array => [
×
848
                        'mandatory' => $identifyMethod['mandatory'],
×
849
                        'identifiedAtDate' => null,
×
850
                        'validateCode' => false,
×
851
                        'method' => $identifyMethod['name'],
×
852
                ], $identifyMethods);
×
853
                return $return;
×
854
        }
855

856
        /**
857
         * @psalm-return array{file?: File, nodeId?: int, url?: string, base64?: string}
858
         */
859
        public function getFileUrl(string $format, FileEntity $fileEntity, File $fileToSign, string $uuid): array {
860
                $url = [];
×
861
                switch ($format) {
862
                        case 'base64':
×
863
                                $url = ['base64' => base64_encode($fileToSign->getContent())];
×
864
                                break;
×
865
                        case 'url':
×
866
                                try {
867
                                        $this->idDocsMapper->getByFileId($fileEntity->getId());
×
868
                                        $url = ['url' => $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $uuid])];
×
869
                                } catch (DoesNotExistException) {
×
870
                                        $url = ['url' => $this->urlGenerator->linkToRoute('libresign.page.getPdfFile', ['uuid' => $uuid])];
×
871
                                }
872
                                break;
×
873
                        case 'nodeId':
×
874
                                $url = ['nodeId' => $fileToSign->getId()];
×
875
                                break;
×
876
                        case 'file':
×
877
                                $url = ['file' => $fileToSign];
×
878
                                break;
×
879
                }
880
                return $url;
×
881
        }
882
}
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