-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathSignFileService.php
More file actions
1624 lines (1406 loc) · 50.5 KB
/
SignFileService.php
File metadata and controls
1624 lines (1406 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Libresign\Service;
use DateTime;
use DateTimeInterface;
use Exception;
use InvalidArgumentException;
use OC\AppFramework\Http as AppFrameworkHttp;
use OC\User\NoUserException;
use OCA\Libresign\AppInfo\Application;
use OCA\Libresign\BackgroundJob\SignSingleFileJob;
use OCA\Libresign\DataObjects\VisibleElementAssoc;
use OCA\Libresign\Db\File as FileEntity;
use OCA\Libresign\Db\FileElement;
use OCA\Libresign\Db\FileElementMapper;
use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Db\IdDocs;
use OCA\Libresign\Db\IdDocsMapper;
use OCA\Libresign\Db\IdentifyMethodMapper;
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
use OCA\Libresign\Db\SignRequestMapper;
use OCA\Libresign\Db\UserElementMapper;
use OCA\Libresign\Enum\FileStatus;
use OCA\Libresign\Events\SignedEventFactory;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\DocMdpHandler;
use OCA\Libresign\Handler\FooterHandler;
use OCA\Libresign\Handler\PdfTk\Pdf;
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
use OCA\Libresign\Handler\SignEngine\SignEngineHandler;
use OCA\Libresign\Helper\JSActions;
use OCA\Libresign\Helper\ValidateHelper;
use OCA\Libresign\Service\Envelope\EnvelopeStatusDeterminer;
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
use OCA\Libresign\Service\SignRequest\SignRequestService;
use OCA\Libresign\Service\SignRequest\StatusService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\Files\NotPermittedException;
use OCP\Http\Client\IClientService;
use OCP\IAppConfig;
use OCP\IDateTimeZone;
use OCP\IL10N;
use OCP\ITempManager;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Security\ICredentialsManager;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Sabre\DAV\UUIDUtil;
class SignFileService {
private ?SignRequestEntity $signRequest = null;
private string $password = '';
private ?FileEntity $libreSignFile = null;
/** @var array<int, VisibleElementAssoc> indexed by fileElementId */
private $elements = [];
private array $elementsInput = [];
private bool $signWithoutPassword = false;
private ?string $signatureMethodName = null;
private ?File $fileToSign = null;
private ?File $createdSignedFile = null;
private string $userUniqueIdentifier = '';
private string $friendlyName = '';
private ?IUser $user = null;
private ?SignEngineHandler $engine = null;
public function __construct(
protected IL10N $l10n,
private FileMapper $fileMapper,
private SignRequestMapper $signRequestMapper,
private IdDocsMapper $idDocsMapper,
private FooterHandler $footerHandler,
protected FolderService $folderService,
private IClientService $client,
protected LoggerInterface $logger,
private IAppConfig $appConfig,
protected ValidateHelper $validateHelper,
private SignerElementsService $signerElementsService,
private IRootFolder $root,
private IUserSession $userSession,
private IDateTimeZone $dateTimeZone,
private FileElementMapper $fileElementMapper,
private UserElementMapper $userElementMapper,
private IEventDispatcher $eventDispatcher,
protected ISecureRandom $secureRandom,
private IURLGenerator $urlGenerator,
private IdentifyMethodMapper $identifyMethodMapper,
private ITempManager $tempManager,
private SigningCoordinatorService $signingCoordinatorService,
private IdentifyMethodService $identifyMethodService,
private ITimeFactory $timeFactory,
protected SignEngineFactory $signEngineFactory,
private SignedEventFactory $signedEventFactory,
private Pdf $pdf,
private DocMdpHandler $docMdpHandler,
private PdfSignatureDetectionService $pdfSignatureDetectionService,
private SequentialSigningService $sequentialSigningService,
private FileStatusService $fileStatusService,
private StatusService $statusService,
private IJobList $jobList,
private ICredentialsManager $credentialsManager,
private EnvelopeStatusDeterminer $envelopeStatusDeterminer,
private TsaValidationService $tsaValidationService,
private PfxProvider $pfxProvider,
private SubjectAlternativeNameService $subjectAlternativeNameService,
private SignRequestService $signRequestService,
) {
}
/**
* Can delete sing request
*/
public function canDeleteRequestSignature(array $data): void {
if (!empty($data['uuid'])) {
$signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
} elseif (!empty($data['file']['nodeId'])) {
$signatures = $this->signRequestMapper->getByNodeId($data['file']['nodeId']);
} else {
throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
}
$signed = array_filter($signatures, fn ($s) => $s->getSigned());
if ($signed) {
throw new \Exception($this->l10n->t('Document already signed'));
}
array_walk($data['signers'], function ($signer) use ($signatures): void {
$exists = array_filter($signatures, function (SignRequestEntity $signRequest) use ($signer) {
$identifyMethod = $this->identifyMethodService->getIdentifiedMethod($signRequest->getId());
if ($identifyMethod->getName() === 'email') {
return $identifyMethod->getEntity()->getIdentifierValue() === $signer['email'];
}
return false;
});
if (!$exists) {
throw new \Exception($this->l10n->t('No signature was requested to %s', $signer['email']));
}
});
}
public function notifyCallback(File $file): void {
$uri = $this->libreSignFile->getCallback();
if (!$uri) {
$uri = $this->appConfig->getValueString(Application::APP_ID, 'webhook_sign_url');
if (!$uri) {
return;
}
}
$options = [
'multipart' => [
[
'name' => 'uuid',
'contents' => $this->libreSignFile->getUuid(),
],
[
'name' => 'status',
'contents' => $this->libreSignFile->getStatus(),
],
[
'name' => 'file',
'contents' => $file->fopen('r'),
'filename' => $file->getName()
]
]
];
$this->client->newClient()->post($uri, $options);
}
/**
* @return static
*/
public function setLibreSignFile(FileEntity $libreSignFile): self {
$this->libreSignFile = $libreSignFile;
return $this;
}
public function setUserUniqueIdentifier(string $identifier): self {
$this->userUniqueIdentifier = $identifier;
return $this;
}
public function setFriendlyName(string $friendlyName): self {
$this->friendlyName = $friendlyName;
return $this;
}
/**
* @return static
*/
public function setSignRequest(SignRequestEntity $signRequest): self {
$this->signRequest = $signRequest;
return $this;
}
/**
* @return static
*/
public function setSignWithoutPassword(bool $signWithoutPassword = true): self {
$this->signWithoutPassword = $signWithoutPassword;
return $this;
}
public function setSignatureMethod(?string $signatureMethodName): self {
$this->signatureMethodName = $signatureMethodName;
return $this;
}
/**
* @return static
*/
public function setPassword(?string $password = null): self {
$this->password = $password;
return $this;
}
public function setCurrentUser(?IUser $user): self {
$this->user = $user;
return $this;
}
public function prepareForSigning(
FileEntity $libreSignFile,
SignRequestEntity $signRequest,
?IUser $user,
string $userIdentifier,
string $displayName,
bool $signWithoutPassword,
?string $password = null,
?string $signatureMethodName = null,
): self {
if ($signWithoutPassword) {
$this->setSignWithoutPassword();
} else {
$this->setPassword($password);
}
return $this
->setLibreSignFile($libreSignFile)
->setSignRequest($signRequest)
->setCurrentUser($user)
->setUserUniqueIdentifier($userIdentifier)
->setFriendlyName($displayName)
->setSignatureMethod($signatureMethodName);
}
public function setVisibleElements(array $list): self {
$this->elementsInput = $list;
if (!$this->signRequest instanceof SignRequestEntity) {
return $this;
}
$fileId = $this->signRequest->getFileId();
$signRequestId = $this->signRequest->getId();
if (empty($list) && ($fileId === null || $signRequestId === null)) {
return $this;
}
if ($fileId === null || $signRequestId === null) {
throw new LibresignException($this->l10n->t('File not found'));
}
$fileElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
$canCreateSignature = $this->signerElementsService->canCreateSignature();
$newElements = [];
foreach ($fileElements as $fileElement) {
$fileElementId = $fileElement->getId();
if (!$canCreateSignature) {
$newElements[$fileElementId] = new VisibleElementAssoc($fileElement);
continue;
}
$element = $this->array_find($list, fn (array $element): bool => ($element['documentElementId'] ?? '') === $fileElementId);
if (!$element) {
// No user-submitted image for this element (e.g. clickToSign).
// Still include the file element so the admin background image (n0 layer)
// is rendered in the signature stamp on the document.
$newElements[$fileElementId] = new VisibleElementAssoc($fileElement);
continue;
}
$nodeId = $this->getNodeId($element, $fileElement);
$existing = $this->elements[$fileElementId] ?? null;
if ($existing instanceof VisibleElementAssoc && $this->isTempFileValid($existing)) {
$newElements[$fileElementId] = $existing;
continue;
}
$newElements[$fileElementId] = $this->bindFileElementWithTempFile($fileElement, $nodeId);
}
$this->elements = $newElements;
return $this;
}
private function isTempFileValid(VisibleElementAssoc $elementAssoc): bool {
$tempFile = $elementAssoc->getTempFile();
return $tempFile !== '' && is_file($tempFile);
}
private function getNodeId(?array $element, FileElement $fileElement): int {
if ($this->isValidElement($element)) {
return (int)$element['profileNodeId'];
}
return $this->retrieveUserElement($fileElement);
}
private function isValidElement(?array $element): bool {
if (is_array($element) && !empty($element['profileNodeId']) && is_int($element['profileNodeId'])) {
return true;
}
$this->logger->error('Invalid data provided for signing file.', ['element' => $element]);
throw new LibresignException($this->l10n->t('Invalid data to sign file'), 1);
}
private function retrieveUserElement(FileElement $fileElement): int {
try {
if (!$this->user instanceof IUser) {
throw new Exception('User not set');
}
$userElement = $this->userElementMapper->findOne([
'user_id' => $this->user->getUID(),
'type' => $fileElement->getType(),
]);
} catch (MultipleObjectsReturnedException|DoesNotExistException|Exception) {
throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
}
return $userElement->getNodeId();
}
private function bindFileElementWithTempFile(FileElement $fileElement, int $nodeId): VisibleElementAssoc {
try {
$node = $this->getNode($nodeId);
if (!$node) {
throw new \Exception('Node content is empty or unavailable.');
}
} catch (\Throwable) {
throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
}
$tempFile = $this->tempManager->getTemporaryFile('_' . $nodeId . '.png');
$content = $node->getContent();
if (empty($content)) {
$this->logger->error('Failed to retrieve content for node.', ['nodeId' => $nodeId, 'fileElement' => $fileElement]);
throw new LibresignException($this->l10n->t('You need to define a visible signature or initials to sign this document.'));
}
file_put_contents($tempFile, $content);
return new VisibleElementAssoc($fileElement, $tempFile);
}
private function getNode(int $nodeId): ?File {
try {
return $this->folderService->getFileByNodeId($nodeId);
} catch (\Throwable) {
$filesOfElementes = $this->signerElementsService->getElementsFromSession();
return $this->array_find($filesOfElementes, fn ($file) => $file->getId() === $nodeId);
}
}
/**
* Fallback to PHP < 8.4
*
* Reference: https://www.php.net/manual/en/function.array-find.php#130257
*
* @todo remove this after minor PHP version is >= 8.4
* @deprecated This method will be removed once the minimum PHP version is >= 8.4. Use native array_find instead.
*/
private function array_find(array $array, callable $callback): mixed {
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return null;
}
public function getVisibleElements(): array {
return $this->elements;
}
public function getJobArgumentsWithoutCredentials(): array {
$args = [];
if (!empty($this->userUniqueIdentifier)) {
$args['userUniqueIdentifier'] = $this->userUniqueIdentifier;
}
if (!empty($this->friendlyName)) {
$args['friendlyName'] = $this->friendlyName;
}
if (!empty($this->elements)) {
$args['visibleElements'] = $this->elements;
}
if ($this->signRequest instanceof SignRequestEntity && $this->signRequest->getMetadata()) {
$args['metadata'] = $this->signRequest->getMetadata();
}
if ($this->user instanceof IUser) {
$args['userId'] = $this->user->getUID();
}
return $args;
}
public function validateSigningRequirements(): void {
$this->tsaValidationService->validateConfiguration();
}
public function sign(): void {
$signRequests = $this->getSignRequestsToSign();
if (empty($signRequests)) {
throw new LibresignException('No sign requests found to process');
}
$this->executeSigningStrategy($signRequests);
}
private function executeSigningStrategy(array $signRequests): ?DateTimeInterface {
if ($this->signingCoordinatorService->shouldUseParallelProcessing(count($signRequests))) {
return $this->processParallelSigning($signRequests);
}
return $this->signSequentially($signRequests);
}
private function processParallelSigning(array $signRequests): ?DateTimeInterface {
$this->enqueueParallelSigningJobs($signRequests, $this->getJobArgumentsWithoutCredentials());
return $this->getLatestSignedDate($signRequests);
}
private function getLatestSignedDate(array $signRequests): ?DateTimeInterface {
$latestSignedDate = null;
foreach ($signRequests as $signRequestData) {
try {
$signRequest = $this->signRequestMapper->getById($signRequestData['signRequest']->getId());
if ($signRequest->getSigned()) {
$latestSignedDate = $signRequest->getSigned();
}
} catch (DoesNotExistException) {
}
}
return $latestSignedDate;
}
public function signSingleFile(FileEntity $libreSignFile, SignRequestEntity $signRequest): void {
$previousState = $this->saveCachedState();
$this->resetCachedState();
if ($libreSignFile->getSignedHash()) {
$this->restoreCachedState($previousState);
return;
}
$previousLibreSignFile = $this->libreSignFile;
$previousSignRequest = $this->signRequest;
$this->libreSignFile = $libreSignFile;
$this->signRequest = $signRequest;
$this->setVisibleElements($this->elementsInput);
try {
$this->validateDocMdpAllowsSignatures();
try {
$signedFile = $this->getEngine()->sign();
} catch (LibresignException|Exception $e) {
$this->cleanupUnsignedSignedFile();
$this->recordSignatureAttempt($e);
throw $e;
}
$hash = $this->computeHash($signedFile);
$this->updateSignRequest($hash);
$this->updateLibreSignFile($libreSignFile, $signedFile->getId(), $hash);
$this->dispatchSignedEvent();
$envelopeContext = $this->getEnvelopeContext();
if ($envelopeContext['envelope'] instanceof FileEntity) {
$this->updateEnvelopeStatus(
$envelopeContext['envelope'],
$envelopeContext['envelopeSignRequest'] ?? null,
$signRequest->getSigned()
);
}
} finally {
$this->libreSignFile = $previousLibreSignFile;
$this->signRequest = $previousSignRequest;
$this->restoreCachedState($previousState);
}
}
private function saveCachedState(): array {
return [
'fileToSign' => $this->fileToSign,
'createdSignedFile' => $this->createdSignedFile,
'engine' => $this->engine,
];
}
private function resetCachedState(): void {
$this->fileToSign = null;
$this->createdSignedFile = null;
$this->engine = null;
}
private function restoreCachedState(array $state): void {
$this->fileToSign = $state['fileToSign'];
$this->createdSignedFile = $state['createdSignedFile'];
$this->engine = $state['engine'];
}
public function enqueueParallelSigningJobs(array $signRequests, array $jobArguments = []): int {
if (empty($signRequests)) {
throw new LibresignException('No sign requests found to process');
}
$enqueued = 0;
foreach ($signRequests as $signRequestData) {
$file = $signRequestData['file'];
$signRequest = $signRequestData['signRequest'];
if ($file->getSignedHash()) {
continue;
}
$nodeId = $file->getNodeId();
$userId = $file->getUserId() ?? $signRequest->getUserId();
if ($nodeId === null || !$this->verifyFileExists($userId, $nodeId)) {
continue;
}
$this->enqueueSigningJobForFile($signRequest, $file, $jobArguments);
$enqueued++;
}
return $enqueued;
}
private function enqueueSigningJobForFile(SignRequestEntity $signRequest, FileEntity $file, array $jobArguments): void {
$args = $jobArguments;
$args = $this->addCredentialsToJobArgs($args, $signRequest, $file);
$args = array_merge($args, [
'fileId' => $file->getId(),
'signRequestId' => $signRequest->getId(),
'signRequestUuid' => $signRequest->getUuid(),
'userId' => $file->getUserId(),
'isExternalSigner' => !str_starts_with($args['userUniqueIdentifier'] ?? '', 'account:'),
]);
$this->jobList->add(SignSingleFileJob::class, $args);
}
private function addCredentialsToJobArgs(array $args, SignRequestEntity $signRequest, FileEntity $file): array {
if (!($this->signWithoutPassword || !empty($this->password))) {
return $args;
}
$credentialsId = 'libresign_sign_' . $signRequest->getId() . '_' . $file->getId() . '_' . $this->secureRandom->generate(8, ISecureRandom::CHAR_ALPHANUMERIC);
$this->credentialsManager->store(
$this->user?->getUID() ?? '',
$credentialsId,
[
'signWithoutPassword' => $this->signWithoutPassword,
'password' => $this->password,
'timestamp' => time(),
'expires' => time() + 3600,
]
);
$args['credentialsId'] = $credentialsId;
return $args;
}
/**
* @return DateTimeInterface|null Last signed date
*/
private function signSequentially(array $signRequests): ?DateTimeInterface {
$envelopeLastSignedDate = null;
$envelopeContext = $this->getEnvelopeContext();
foreach ($signRequests as $index => $signRequestData) {
$this->libreSignFile = $signRequestData['file'];
if ($this->libreSignFile->getStatus() === FileStatus::SIGNED->value) {
continue;
}
$this->signRequest = $signRequestData['signRequest'];
$this->engine = null;
$this->setVisibleElements($this->elementsInput);
$this->fileToSign = null;
$this->validateDocMdpAllowsSignatures();
try {
$signedFile = $this->getEngine()->sign();
} catch (LibresignException|Exception $e) {
$this->cleanupUnsignedSignedFile();
$this->recordSignatureAttempt($e);
$isEnvelope = $this->libreSignFile->isEnvelope() || $this->libreSignFile->hasParent();
if (!$isEnvelope) {
throw $e;
}
continue;
}
$hash = $this->computeHash($signedFile);
$envelopeLastSignedDate = $this->getEngine()->getLastSignedDate();
$this->updateSignRequest($hash);
$this->updateLibreSignFile($this->libreSignFile, $signedFile->getId(), $hash);
$this->dispatchSignedEvent();
}
if ($envelopeContext['envelope'] instanceof FileEntity) {
$this->updateEnvelopeStatus(
$envelopeContext['envelope'],
$envelopeContext['envelopeSignRequest'] ?? null,
$envelopeLastSignedDate
);
}
return $envelopeLastSignedDate;
}
/**
* @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
*/
private function getSignRequestsToSign(): array {
if (!$this->libreSignFile->isEnvelope()
&& !$this->libreSignFile->hasParent()
) {
return [[
'file' => $this->libreSignFile,
'signRequest' => $this->signRequest,
]];
}
return $this->buildEnvelopeSignRequests();
}
/**
* @return array Array of sign request data with 'file' => FileEntity, 'signRequest' => SignRequestEntity
*/
private function buildEnvelopeSignRequests(): array {
$envelopeId = $this->libreSignFile->isEnvelope()
? $this->libreSignFile->getId()
: $this->libreSignFile->getParentFileId();
$childFiles = $this->fileMapper->getChildrenFiles($envelopeId);
if (empty($childFiles)) {
throw new LibresignException('No files found in envelope');
}
$childSignRequests = $this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod(
$envelopeId,
$this->signRequest->getId()
);
if (empty($childSignRequests)) {
throw new LibresignException('No sign requests found for envelope files');
}
$signRequestsData = [];
foreach ($childSignRequests as $childSignRequest) {
$childFile = $this->array_find(
$childFiles,
fn (FileEntity $file) => $file->getId() === $childSignRequest->getFileId()
);
if ($childFile) {
$signRequestsData[] = [
'file' => $childFile,
'signRequest' => $childSignRequest,
];
}
}
return $signRequestsData;
}
/**
* @return array Array with 'envelope' => FileEntity or null, 'envelopeSignRequest' => SignRequestEntity or null
*/
private function getEnvelopeContext(): array {
$result = [
'envelope' => null,
'envelopeSignRequest' => null,
];
if (!$this->libreSignFile->isEnvelope() && !$this->libreSignFile->hasParent()) {
return $result;
}
if ($this->libreSignFile->isEnvelope()) {
$result['envelope'] = $this->libreSignFile;
$result['envelopeSignRequest'] = $this->signRequest;
return $result;
}
try {
$envelopeId = $this->libreSignFile->isEnvelope()
? $this->libreSignFile->getId()
: $this->libreSignFile->getParentFileId();
$result['envelope'] = $this->fileMapper->getById($envelopeId);
$identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
$result['envelopeSignRequest'] = $this->signRequestMapper->getByIdentifyMethodAndFileId(
$identifyMethod,
$result['envelope']->getId()
);
} catch (DoesNotExistException) {
}
return $result;
}
private function updateEnvelopeStatus(
FileEntity $envelope,
?SignRequestEntity $envelopeSignRequest = null,
?DateTimeInterface $signedDate = null,
): void {
$childFiles = $this->fileMapper->getChildrenFiles($envelope->getId());
$signRequestsMap = $this->buildSignRequestsMap($childFiles);
$status = $this->envelopeStatusDeterminer->determineStatus($childFiles, $signRequestsMap);
$envelope->setStatus($status);
$this->handleSignedEnvelopeSignRequest($envelope, $envelopeSignRequest, $signedDate, $status);
$this->updateEnvelopeMetadata($envelope);
$this->fileMapper->update($envelope);
$this->updateEntityCacheAfterDbSave($envelope);
}
private function buildSignRequestsMap(array $childFiles): array {
$signRequestsMap = [];
foreach ($childFiles as $childFile) {
$signRequestsMap[$childFile->getId()] = $this->signRequestMapper->getByFileId($childFile->getId());
}
return $signRequestsMap;
}
private function handleSignedEnvelopeSignRequest(
FileEntity $envelope,
?SignRequestEntity $envelopeSignRequest,
?DateTimeInterface $signedDate,
int $status,
): void {
if (!($envelopeSignRequest instanceof SignRequestEntity)) {
return;
}
$envelopeSignRequest->setSigned($signedDate ?: new DateTime());
$envelopeSignRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
$this->signRequestMapper->update($envelopeSignRequest);
$this->sequentialSigningService
->setFile($envelope)
->releaseNextOrder(
$envelopeSignRequest->getFileId(),
$envelopeSignRequest->getSigningOrder()
);
}
private function updateEnvelopeMetadata(FileEntity $envelope): void {
$meta = $envelope->getMetadata() ?? [];
$meta['status_changed_at'] = (new DateTime())->format(DateTimeInterface::ATOM);
$envelope->setMetadata($meta);
}
/**
* @throws LibresignException If the document has DocMDP level 1 (no changes allowed)
*/
protected function validateDocMdpAllowsSignatures(): void {
$resource = $this->getLibreSignFileAsResource();
try {
if (!$this->docMdpHandler->allowsAdditionalSignatures($resource)) {
throw new LibresignException(
$this->l10n->t('This document has been certified with no changes allowed. You cannot add more signers to this document.'),
AppFrameworkHttp::STATUS_UNPROCESSABLE_ENTITY
);
}
} finally {
fclose($resource);
}
}
/**
* @return resource
* @throws LibresignException
*/
protected function getLibreSignFileAsResource() {
$files = $this->getNextcloudFiles($this->libreSignFile);
if (empty($files)) {
throw new LibresignException('File not found');
}
$fileToSign = current($files);
$content = $fileToSign->getContent();
$resource = fopen('php://memory', 'r+');
if ($resource === false) {
throw new LibresignException('Failed to create temporary resource for PDF validation');
}
fwrite($resource, $content);
rewind($resource);
return $resource;
}
protected function computeHash(File $file): string {
return hash('sha256', $file->getContent());
}
protected function updateSignRequest(string $hash): void {
$lastSignedDate = $this->getEngine()->getLastSignedDate();
$this->signRequest->setSigned($lastSignedDate);
$this->signRequest->setSignedHash($hash);
$this->signRequest->setStatusEnum(\OCA\Libresign\Enum\SignRequestStatus::SIGNED);
$certificateInfo = $this->getEngine()->readCertificate();
$this->storeCertificateInfoInMetadata($certificateInfo);
$this->signRequestMapper->update($this->signRequest);
$this->sequentialSigningService
->setFile($this->libreSignFile)
->releaseNextOrder(
$this->signRequest->getFileId(),
$this->signRequest->getSigningOrder()
);
}
private function storeCertificateInfoInMetadata(array $certificateInfo): void {
$metadata = $this->signRequest->getMetadata() ?? [];
$certificateData = [];
if (isset($certificateInfo['serialNumber'])) {
$certificateData['serialNumber'] = $certificateInfo['serialNumber'];
}
if (isset($certificateInfo['serialNumberHex'])) {
$certificateData['serialNumberHex'] = $certificateInfo['serialNumberHex'];
}
if (isset($certificateInfo['hash'])) {
$certificateData['hash'] = $certificateInfo['hash'];
}
if (isset($certificateInfo['subject'])) {
$certificateData['subject'] = $certificateInfo['subject'];
}
if (!empty($certificateData)) {
$metadata['certificate_info'] = $certificateData;
$this->signRequest->setMetadata($metadata);
}
}
protected function updateLibreSignFile(FileEntity $libreSignFile, int $nodeId, string $hash): void {
$libreSignFile->setSignedNodeId($nodeId);
$libreSignFile->setSignedHash($hash);
$this->setNewStatusIfNecessary($libreSignFile);
$this->fileStatusService->update($libreSignFile);
if ($libreSignFile->hasParent()) {
$this->fileStatusService->propagateStatusToParent($libreSignFile->getParentFileId());
}
}
protected function dispatchSignedEvent(): void {
$certificateSerialNumber = null;
if ($this->signWithoutPassword) {
try {
$certificateInfo = $this->getEngine()->readCertificate();
if (isset($certificateInfo['serialNumber']) && is_string($certificateInfo['serialNumber'])) {
$certificateSerialNumber = $certificateInfo['serialNumber'];
} else {
$this->logger->warning('Unable to extract certificate serial number for event payload');
}
} catch (\Throwable $e) {
$this->logger->error('Failed to get certificate info for event', [
'exception' => $e,
'signRequestId' => $this->signRequest->getId()
]);
}
}
$event = $this->signedEventFactory->make(
$this->signRequest,
$this->libreSignFile,
$this->getEngine()->getInputFile(),
$this->signWithoutPassword,
$certificateSerialNumber,
);
$this->eventDispatcher->dispatchTyped($event);
}
protected function identifyEngine(File $file): SignEngineHandler {
return $this->signEngineFactory->resolve($file->getExtension());
}
protected function getSignatureParams(): array {
$certificateData = $this->readCertificate();
$signatureParams = $this->buildBaseSignatureParams($certificateData);
$signatureParams = $this->addEmailToSignatureParams($signatureParams, $certificateData);
$signatureParams = $this->addMetadataToSignatureParams($signatureParams);
return $signatureParams;
}
private function buildBaseSignatureParams(array $certificateData): array {
$issuerCommonName = $this->normalizeCertificateFieldToString($certificateData['issuer']['CN'] ?? '');
$signerCommonName = $this->normalizeCertificateFieldToString($certificateData['subject']['CN'] ?? '');
return [
'DocumentUUID' => $this->libreSignFile?->getUuid(),
'IssuerCommonName' => $issuerCommonName,
'SignerCommonName' => $signerCommonName,
'LocalSignerTimezone' => $this->dateTimeZone->getTimeZone()->getName(),
'LocalSignerSignatureDateTime' => (new DateTime('now', new \DateTimeZone('UTC')))
->format(DateTimeInterface::ATOM)
];
}
private function normalizeCertificateFieldToString(mixed $value): string {
if (is_array($value)) {
$flattened = [];
array_walk_recursive($value, static function (mixed $item) use (&$flattened): void {
if ($item !== null) {
$flattened[] = (string)$item;
}
});
$displayValues = array_values(array_filter(
$flattened,
static fn (string $item) => !preg_match('/^account:\s*/i', $item),
));
return implode(', ', $displayValues);
}
return $value === null ? '' : (string)$value;
}
private function addEmailToSignatureParams(array $signatureParams, array $certificateData): array {
$email = $this->subjectAlternativeNameService->extractEmailFromCertificate($certificateData);
if ($email) {
$signatureParams['SignerEmail'] = $email;
}
if (empty($signatureParams['SignerEmail']) && $this->user instanceof IUser) {
$signatureParams['SignerEmail'] = $this->user->getEMailAddress();
}
if (empty($signatureParams['SignerEmail']) && $this->signRequest instanceof SignRequestEntity) {
$identifyMethod = $this->identifyMethodService->getIdentifiedMethod($this->signRequest->getId());
if ($identifyMethod->getName() === IdentifyMethodService::IDENTIFY_EMAIL) {
$signatureParams['SignerEmail'] = $identifyMethod->getEntity()->getIdentifierValue();
}
}
return $signatureParams;
}
private function addMetadataToSignatureParams(array $signatureParams): array {
$signRequestMetadata = $this->signRequest->getMetadata();
if (isset($signRequestMetadata['remote-address'])) {
$signatureParams['SignerIP'] = $signRequestMetadata['remote-address'];
}
if (isset($signRequestMetadata['user-agent'])) {
$signatureParams['SignerUserAgent'] = $signRequestMetadata['user-agent'];
}
if ($this->libreSignFile?->getMetadata()) {
$metadata = $this->libreSignFile->getMetadata();
if (isset($metadata['d']) && !empty($metadata['d'])) {
$signatureParams['PageDimensions'] = $metadata['d'];
}
}
return $signatureParams;
}
public function storeUserMetadata(array $metadata = []): self {
$collectMetadata = $this->appConfig->getValueBool(Application::APP_ID, 'collect_metadata', false);
if (!$collectMetadata || !$metadata) {
return $this;