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

LibreSign / libresign / 20040103294

08 Dec 2025 07:23PM UTC coverage: 44.146%. First build
20040103294

Pull #6021

github

web-flow
Merge 6275726ed into eb7183cb5
Pull Request #6021: feat: docmdp implementation

66 of 113 new or added lines in 10 files covered. (58.41%)

5678 of 12862 relevant lines covered (44.15%)

5.1 hits per line

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

60.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;
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
        ) {
108
        }
138✔
109

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

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

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

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

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

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

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

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

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

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

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

222
                return $this;
5✔
223
        }
224

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

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

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

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

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

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

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

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

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

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

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

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

311
                return null;
3✔
312
        }
313

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

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

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

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

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

332
                return $signedFile;
16✔
333
        }
334

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

341
                try {
342
                        if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
21✔
343
                                throw new LibresignException(
3✔
344
                                        $this->l10n->t('This document is certified with DocMDP level 1 (no changes allowed) and cannot receive additional signatures'),
3✔
345
                                        AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
3✔
346
                                );
3✔
347
                        }
348
                } finally {
349
                        fclose($resource);
21✔
350
                }
351
        }
352

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

513
                return null;
1✔
514
        }
515

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

706
        protected function getPdfToSign(File $originalFile): File {
707
                $file = $this->getSignedFile();
×
708
                if ($file instanceof File) {
×
709
                        return $file;
×
710
                }
711
                $metadata = $this->footerHandler->getMetadata($originalFile, $this->libreSignFile);
×
712
                $footer = $this->footerHandler
×
713
                        ->setTemplateVar('uuid', $this->libreSignFile->getUuid())
×
714
                        ->setTemplateVar('signers', array_map(fn (SignRequestEntity $signer) => [
×
715
                                'displayName' => $signer->getDisplayName(),
×
716
                                'signed' => $signer->getSigned()
×
717
                                        ? $signer->getSigned()->format(DateTimeInterface::ATOM)
×
718
                                        : null,
719
                        ], $this->getSigners()))
×
720
                        ->getFooter($metadata['d']);
×
721
                if ($footer) {
×
722
                        $stamp = $this->tempManager->getTemporaryFile('stamp.pdf');
×
723
                        file_put_contents($stamp, $footer);
×
724

725
                        $input = $this->tempManager->getTemporaryFile('input.pdf');
×
726
                        file_put_contents($input, $originalFile->getContent());
×
727

728
                        try {
729
                                $pdfContent = $this->pdf->applyStamp($input, $stamp);
×
730
                        } catch (RuntimeException $e) {
×
731
                                throw new LibresignException($e->getMessage());
×
732
                        }
733
                } else {
734
                        $pdfContent = $originalFile->getContent();
×
735
                }
736
                return $this->createSignedFile($originalFile, $pdfContent);
×
737
        }
738

739
        protected function getSignedFile(): ?File {
740
                $nodeId = $this->libreSignFile->getSignedNodeId();
3✔
741
                if (!$nodeId) {
3✔
742
                        return null;
1✔
743
                }
744

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

747
                if ($fileToSign->getOwner()->getUID() !== $this->libreSignFile->getUserId()) {
2✔
748
                        $fileToSign = $this->getNodeByIdUsingUid($fileToSign->getOwner()->getUID(), $nodeId);
1✔
749
                }
750
                return $fileToSign;
2✔
751
        }
752

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

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

783
        /**
784
         * @throws DoesNotExistException
785
         */
786
        public function getSignRequestByUuid(string $uuid): SignRequestEntity {
787
                $this->validateHelper->validateUuidFormat($uuid);
4✔
788
                return $this->signRequestMapper->getByUuid($uuid);
3✔
789
        }
790

791
        /**
792
         * @throws DoesNotExistException
793
         */
794
        public function getFile(int $signRequestId): FileEntity {
795
                return $this->fileMapper->getById($signRequestId);
×
796
        }
797

798
        /**
799
         * @throws DoesNotExistException
800
         */
801
        public function getFileByUuid(string $uuid): FileEntity {
802
                return $this->fileMapper->getByUuid($uuid);
×
803
        }
804

805
        public function getIdDocById(int $fileId): IdDocs {
806
                return $this->idDocsMapper->getByFileId($fileId);
×
807
        }
808

809
        public function getNextcloudFile(FileEntity $fileData): File {
810
                $fileToSign = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($fileData->getNodeId());
1✔
811
                if (!$fileToSign instanceof File) {
1✔
812
                        throw new LibresignException(json_encode([
1✔
813
                                'action' => JSActions::ACTION_DO_NOTHING,
1✔
814
                                'errors' => [['message' => $this->l10n->t('File not found')]],
1✔
815
                        ]), AppFrameworkHttp::STATUS_NOT_FOUND);
1✔
816
                }
817
                return $fileToSign;
×
818
        }
819

820
        public function validateSigner(string $uuid, ?IUser $user = null): void {
821
                $this->validateHelper->validateSigner($uuid, $user);
×
822
        }
823

824
        public function validateRenewSigner(string $uuid, ?IUser $user = null): void {
825
                $this->validateHelper->validateRenewSigner($uuid, $user);
×
826
        }
827

828
        public function getSignerData(?IUser $user, ?SignRequestEntity $signRequest = null): array {
829
                $return = ['user' => ['name' => null]];
×
830
                if ($signRequest) {
×
831
                        $return['user']['name'] = $signRequest->getDisplayName();
×
832
                } elseif ($user) {
×
833
                        $return['user']['name'] = $user->getDisplayName();
×
834
                }
835
                return $return;
×
836
        }
837

838
        public function getAvailableIdentifyMethodsFromSettings(): array {
839
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsSettings();
×
840
                $return = array_map(fn (array $identifyMethod): array => [
×
841
                        'mandatory' => $identifyMethod['mandatory'],
×
842
                        'identifiedAtDate' => null,
×
843
                        'validateCode' => false,
×
844
                        'method' => $identifyMethod['name'],
×
845
                ], $identifyMethods);
×
846
                return $return;
×
847
        }
848

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