-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathFileService.php
More file actions
622 lines (537 loc) · 18.9 KB
/
FileService.php
File metadata and controls
622 lines (537 loc) · 18.9 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
<?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 DateTimeInterface;
use InvalidArgumentException;
use OCA\Libresign\Db\File;
use OCA\Libresign\Db\FileElementMapper;
use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Db\IdDocsMapper;
use OCA\Libresign\Db\SignRequest;
use OCA\Libresign\Db\SignRequestMapper;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Handler\DocMdpHandler;
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
use OCA\Libresign\Helper\FileUploadHelper;
use OCA\Libresign\ResponseDefinitions;
use OCA\Libresign\Service\File\CertificateChainService;
use OCA\Libresign\Service\File\EnvelopeAssembler;
use OCA\Libresign\Service\File\EnvelopeProgressService;
use OCA\Libresign\Service\File\FileContentProvider;
use OCA\Libresign\Service\File\FileResponseOptions;
use OCA\Libresign\Service\File\MessagesLoader;
use OCA\Libresign\Service\File\MetadataLoader;
use OCA\Libresign\Service\File\MimeService;
use OCA\Libresign\Service\File\PdfValidator;
use OCA\Libresign\Service\File\SettingsLoader;
use OCA\Libresign\Service\File\SignersLoader;
use OCA\Libresign\Service\File\UploadProcessor;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
use stdClass;
/**
* @psalm-import-type LibresignEnvelopeChildFile from ResponseDefinitions
* @psalm-import-type LibresignValidateFile from ResponseDefinitions
* @psalm-import-type LibresignVisibleElement from ResponseDefinitions
*/
class FileService {
private string $fileContent = '';
private ?File $file = null;
private ?SignRequest $signRequest = null;
private array $certData = [];
private stdClass $fileData;
private FileResponseOptions $options;
public const IDENTIFICATION_DOCUMENTS_DISABLED = 0;
public const IDENTIFICATION_DOCUMENTS_NEED_SEND = 1;
public const IDENTIFICATION_DOCUMENTS_NEED_APPROVAL = 2;
public const IDENTIFICATION_DOCUMENTS_APPROVED = 3;
public function __construct(
protected FileMapper $fileMapper,
protected SignRequestMapper $signRequestMapper,
protected FileElementMapper $fileElementMapper,
protected FileElementService $fileElementService,
protected FolderService $folderService,
private IdDocsMapper $idDocsMapper,
private IdentifyMethodService $identifyMethodService,
private IUserManager $userManager,
private IURLGenerator $urlGenerator,
protected IMimeTypeDetector $mimeTypeDetector,
protected Pkcs12Handler $pkcs12Handler,
protected DocMdpHandler $docMdpHandler,
protected PdfValidator $pdfValidator,
private IRootFolder $root,
protected LoggerInterface $logger,
protected IL10N $l10n,
private EnvelopeService $envelopeService,
private SignersLoader $signersLoader,
protected FileUploadHelper $uploadHelper,
private EnvelopeAssembler $envelopeAssembler,
private EnvelopeProgressService $envelopeProgressService,
private CertificateChainService $certificateChainService,
private MimeService $mimeService,
private FileContentProvider $contentProvider,
private UploadProcessor $uploadProcessor,
private MetadataLoader $metadataLoader,
private SettingsLoader $settingsLoader,
private MessagesLoader $messagesLoader,
) {
$this->fileData = new stdClass();
$this->options = new FileResponseOptions();
}
public function getNodeFromData(array $data): Node {
if (!$this->folderService->getUserId()) {
$this->folderService->setUserId($data['userManager']->getUID());
}
if (isset($data['uploadedFile'])) {
return $this->getNodeFromUploadedFile($data);
}
if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
return $data['file']['fileNode'];
}
if (isset($data['file']['fileId'])) {
return $this->folderService->getFileById($data['file']['fileId']);
}
if (isset($data['file']['path'])) {
return $this->folderService->getFileByPath($data['file']['path']);
}
$content = $this->getFileRaw($data);
$extension = $this->getExtension($content);
$this->validateFileContent($content, $extension);
$folderToFile = $this->folderService->getFolderForFile($data, $data['userManager']);
$filename = $this->resolveFileName($data, $extension);
return $folderToFile->newFile($filename, $content);
}
public function getNodeFromUploadedFile(array $data): Node {
return $this->uploadProcessor->getNodeFromUploadedFile($data);
}
public function validateFileContent(string $content, string $extension): void {
if ($extension === 'pdf') {
$this->pdfValidator->validate($content);
}
}
private function getExtension(string $content): string {
return $this->mimeService->getExtension($content);
}
private function getFileRaw(array $data): string {
return $this->contentProvider->getContentFromData($data);
}
private function resolveFileName(array $data, string $extension): string {
$name = '';
if (isset($data['name'])) {
$name = trim((string)$data['name']);
}
if ($name === '') {
$basename = '';
if (!empty($data['file']['url'])) {
$path = (string)parse_url((string)$data['file']['url'], PHP_URL_PATH);
if ($path !== '') {
$basename = basename($path);
}
}
if ($basename !== '') {
$filenameNoExt = pathinfo($basename, PATHINFO_FILENAME);
$name = $filenameNoExt !== '' ? $filenameNoExt : $basename;
} else {
$name = 'document';
}
}
$name = preg_replace('/\s+/', '_', $name);
$name = $name !== '' ? $name : 'document';
return $name . '.' . $extension;
}
/**
* @return static
*/
public function showSigners(bool $show = true): self {
$this->options->showSigners($show);
return $this;
}
/**
* @return static
*/
public function showSettings(bool $show = true): self {
$this->options->showSettings($show);
if ($show) {
$this->fileData->settings = [
'canSign' => false,
'canRequestSign' => false,
'signerFileUuid' => null,
'phoneNumber' => '',
];
} else {
unset($this->fileData->settings);
}
return $this;
}
/**
* @return static
*/
public function showVisibleElements(bool $show = true): self {
$this->options->showVisibleElements($show);
return $this;
}
/**
* @return static
*/
public function showMessages(bool $show = true): self {
$this->options->showMessages($show);
return $this;
}
/**
* @return static
*/
public function setMe(?IUser $user): self {
$this->options->setMe($user);
return $this;
}
public function setSignerIdentified(bool $identified = true): self {
$this->options->setSignerIdentified($identified);
return $this;
}
public function setIdentifyMethodId(?int $id): self {
$this->options->setIdentifyMethodId($id);
return $this;
}
public function setHost(string $host): self {
$this->options->setHost($host);
return $this;
}
/**
* @return static
*/
public function setFile(File $file): self {
$this->file = $file;
$this->fileData->status = $this->file->getStatus();
return $this;
}
public function setSignRequest(SignRequest $signRequest): self {
$this->signRequest = $signRequest;
return $this;
}
public function showValidateFile(bool $validateFile = true): self {
$this->options->validateFile($validateFile);
return $this;
}
private function setFileOrFail(callable $resolver): self {
try {
$file = $resolver();
} catch (\Throwable) {
throw new LibresignException($this->l10n->t('Invalid data to validate file'), 404);
}
if (!$file instanceof File) {
throw new LibresignException($this->l10n->t('Invalid file identifier'), 404);
}
return $this->setFile($file);
}
public function setFileById(int $fileId): self {
return $this->setFileOrFail(fn () => $this->fileMapper->getById($fileId));
}
public function setFileByUuid(string $uuid): self {
return $this->setFileOrFail(fn () => $this->fileMapper->getByUuid($uuid));
}
public function setFileBySignerUuid(string $uuid): self {
return $this->setFileOrFail(fn () => $this->fileMapper->getBySignerUuid($uuid));
}
public function setFileByNodeId(int $nodeId): self {
return $this->setFileOrFail(fn () => $this->fileMapper->getByNodeId($nodeId));
}
public function validateUploadedFile(array $file): void {
$this->uploadHelper->validateUploadedFile($file);
}
public function setFileFromRequest(?array $file): self {
if ($file === null) {
throw new InvalidArgumentException($this->l10n->t('No file provided'));
}
$this->uploadHelper->validateUploadedFile($file);
$this->fileContent = file_get_contents($file['tmp_name']);
$mimeType = $this->mimeService->getMimeType($this->fileContent);
if ($mimeType !== 'application/pdf') {
$this->fileContent = '';
unlink($file['tmp_name']);
throw new InvalidArgumentException($this->l10n->t('Invalid file provided'));
}
$this->fileData->size = $file['size'];
$memoryFile = fopen($file['tmp_name'], 'rb');
try {
$this->certData = $this->pkcs12Handler->getCertificateChain($memoryFile);
$this->fileData->status = File::STATUS_SIGNED;
// Ignore when isnt a signed file
} catch (LibresignException) {
$this->fileData->status = File::STATUS_DRAFT;
}
fclose($memoryFile);
unlink($file['tmp_name']);
$this->fileData->hash = hash('sha256', $this->fileContent);
try {
$libresignFile = $this->fileMapper->getBySignedHash($this->fileData->hash);
$this->setFile($libresignFile);
} catch (DoesNotExistException) {
$this->fileData->status = File::STATUS_NOT_LIBRESIGN_FILE;
}
$this->fileData->name = $file['name'];
return $this;
}
private function getFile(): \OCP\Files\File {
$nodeId = $this->file->getSignedNodeId();
if (!$nodeId) {
$nodeId = $this->file->getNodeId();
}
$fileToValidate = $this->root->getUserFolder($this->file->getUserId())->getFirstNodeById($nodeId);
if (!$fileToValidate instanceof \OCP\Files\File) {
throw new LibresignException($this->l10n->t('File not found'), 404);
}
return $fileToValidate;
}
public function getStatus(): int {
return $this->file->getStatus();
}
public function isLibresignFile(int $nodeId): bool {
return $this->fileMapper->fileIdExists($nodeId);
}
public function getSignedNodeId(): ?int {
$status = $this->file->getStatus();
if (!in_array($status, [File::STATUS_PARTIAL_SIGNED, File::STATUS_SIGNED])) {
return null;
}
return $this->file->getSignedNodeId();
}
private function loadSigners(): void {
if (!$this->options->isShowSigners()) {
return;
}
if (!$this->file instanceof File) {
return;
}
if ($this->file->getSignedNodeId()) {
$fileNode = $this->getFile();
$certData = $this->certificateChainService->getCertificateChain($fileNode, $this->file, $this->options);
if ($certData) {
$this->signersLoader->loadSignersFromCertData($this->fileData, $certData, $this->options->getHost());
}
}
$this->signersLoader->loadLibreSignSigners($this->file, $this->fileData, $this->options, $this->certData);
}
private function loadFileMetadata(): void {
$this->metadataLoader->loadMetadata($this->file, $this->fileData);
}
private function loadSettings(): void {
$this->settingsLoader->loadSettings($this->fileData, $this->options);
}
public function getIdentificationDocumentsStatus(string $userId = ''): int {
return $this->settingsLoader->getIdentificationDocumentsStatus($userId);
}
private function loadLibreSignData(): void {
if (!$this->file) {
return;
}
$this->fileData->id = $this->file->getId();
$this->fileData->uuid = $this->file->getUuid();
$this->fileData->name = $this->file->getName();
$this->fileData->status = $this->file->getStatus();
$this->fileData->created_at = $this->file->getCreatedAt()->format(DateTimeInterface::ATOM);
$this->fileData->statusText = $this->fileMapper->getTextOfStatus($this->file->getStatus());
$this->fileData->nodeId = $this->file->getNodeId();
$this->fileData->signatureFlow = $this->file->getSignatureFlow();
$this->fileData->docmdpLevel = $this->file->getDocmdpLevel();
$this->fileData->nodeType = $this->file->getNodeType();
if ($this->fileData->nodeType !== 'envelope' && !$this->file->getParentFileId()) {
$fileId = $this->file->getId();
$childrenFiles = $this->fileMapper->getChildrenFiles($fileId);
if (!empty($childrenFiles)) {
$this->file->setNodeType('envelope');
$this->fileMapper->update($this->file);
$this->fileData->nodeType = 'envelope';
$this->fileData->filesCount = count($childrenFiles);
$this->fileData->files = [];
}
}
if ($this->fileData->nodeType === 'envelope') {
$metadata = $this->file->getMetadata();
$this->fileData->filesCount = $metadata['filesCount'] ?? 0;
$this->fileData->files = [];
$this->loadEnvelopeFiles();
if ($this->file->getStatus() === File::STATUS_SIGNED) {
$latestSignedDate = $this->getLatestSignedDateFromEnvelope();
if ($latestSignedDate) {
$this->fileData->signedDate = $latestSignedDate->format(DateTimeInterface::ATOM);
}
}
}
$this->fileData->requested_by = [
'userId' => $this->file->getUserId(),
'displayName' => $this->userManager->get($this->file->getUserId())->getDisplayName(),
];
$this->fileData->file = $this->urlGenerator->linkToRoute('libresign.page.getPdf', ['uuid' => $this->file->getUuid()]);
$this->loadEnvelopeData();
if ($this->options->isShowVisibleElements()) {
$signers = $this->signRequestMapper->getByMultipleFileId([$this->file->getId()]);
$this->fileData->visibleElements = [];
foreach ($this->signRequestMapper->getVisibleElementsFromSigners($signers) as $visibleElements) {
if (empty($visibleElements)) {
continue;
}
$file = array_filter($this->fileData->files, fn (stdClass $file) => $file->id === $visibleElements[0]->getFileId());
if (empty($file)) {
continue;
}
$file = current($file);
$fileMetadata = $this->file->getMetadata();
$this->fileData->visibleElements = array_merge(
$this->fileElementService->formatVisibleElements($visibleElements, $fileMetadata),
$this->fileData->visibleElements
);
}
}
}
private function getLatestSignedDateFromEnvelope(): ?\DateTime {
if (!$this->file || $this->file->getNodeType() !== 'envelope') {
return null;
}
$childrenFiles = $this->fileMapper->getChildrenFiles($this->file->getId());
$latestDate = null;
foreach ($childrenFiles as $childFile) {
$signRequests = $this->signRequestMapper->getByFileId($childFile->getId());
foreach ($signRequests as $signRequest) {
$signed = $signRequest->getSigned();
if ($signed && (!$latestDate || $signed > $latestDate)) {
$latestDate = $signed;
}
}
}
return $latestDate;
}
private function loadEnvelopeFiles(): void {
if (!$this->file || $this->file->getNodeType() !== 'envelope') {
return;
}
$childrenFiles = $this->fileMapper->getChildrenFiles($this->file->getId());
foreach ($childrenFiles as $childFile) {
$this->fileData->files[] = $this->buildEnvelopeChildData($childFile);
}
}
private function buildEnvelopeChildData(File $childFile): stdClass {
return $this->envelopeAssembler->buildEnvelopeChildData($childFile, $this->options);
}
private function loadEnvelopeData(): void {
if (!$this->file->hasParent()) {
return;
}
$envelope = $this->envelopeService->getEnvelopeByFileId($this->file->getId());
if (!$envelope) {
return;
}
$envelopeMetadata = $envelope->getMetadata();
$this->fileData->envelope = [
'id' => $envelope->getId(),
'uuid' => $envelope->getUuid(),
'name' => $envelope->getName(),
'status' => $envelope->getStatus(),
'statusText' => $this->fileMapper->getTextOfStatus($envelope->getStatus()),
'filesCount' => $envelopeMetadata['filesCount'] ?? 0,
'files' => [],
];
}
private function loadMessages(): void {
$this->messagesLoader->loadMessages($this->file, $this->fileData, $this->options, $this->certData);
}
/**
* @return LibresignValidateFile
* @psalm-return LibresignValidateFile
*/
public function toArray(): array {
$this->loadLibreSignData();
$this->loadFileMetadata();
$this->loadSettings();
$this->loadSigners();
$this->loadMessages();
$this->computeEnvelopeSignersProgress();
$return = json_decode(json_encode($this->fileData), true);
ksort($return);
return $return;
}
private function computeEnvelopeSignersProgress(): void {
if (!$this->file || $this->file->getParentFileId()) {
return;
}
if (empty($this->fileData->signers)) {
return;
}
$childrenFiles = $this->fileMapper->getChildrenFiles($this->file->getId());
if (empty($childrenFiles)) {
return;
}
$signRequestsByFileId = [];
$identifyMethodsBySignRequest = [];
foreach ($childrenFiles as $child) {
$signRequestsByFileId[$child->getId()] = $this->signRequestMapper->getByFileId($child->getId());
foreach ($signRequestsByFileId[$child->getId()] as $sr) {
$identifyMethodsBySignRequest[$sr->getId()] = $this->identifyMethodService->setIsRequest(false)->getIdentifyMethodsFromSignRequestId($sr->getId());
}
}
$this->envelopeProgressService->computeProgress(
$this->fileData,
$this->file,
$childrenFiles,
$signRequestsByFileId,
$identifyMethodsBySignRequest
);
}
public function delete(int $fileId): void {
$file = $this->fileMapper->getById($fileId);
$this->decrementEnvelopeFilesCountIfNeeded($file);
if ($file->getNodeType() === 'envelope') {
$childrenFiles = $this->fileMapper->getChildrenFiles($file->getId());
foreach ($childrenFiles as $childFile) {
$this->delete($childFile->getId());
}
}
$this->fileElementService->deleteVisibleElements($file->getId());
$list = $this->signRequestMapper->getByFileId($file->getId());
foreach ($list as $signRequest) {
$this->identifyMethodService->deleteBySignRequestId($signRequest->getId());
$this->signRequestMapper->delete($signRequest);
}
$this->idDocsMapper->deleteByFileId($file->getId());
$this->fileMapper->delete($file);
if ($file->getSignedNodeId()) {
$signedNextcloudFile = $this->folderService->getFileById($file->getSignedNodeId());
$signedNextcloudFile->delete();
}
try {
$nextcloudFile = $this->folderService->getFileById($fileId);
$nextcloudFile->delete();
} catch (NotFoundException) {
}
}
public function processUploadedFilesWithRollback(array $filesArray, IUser $user, array $settings): array {
return $this->uploadProcessor->processUploadedFilesWithRollback($filesArray, $user, $settings);
}
public function updateEnvelopeFilesCount(File $envelope, int $delta = 0): void {
$metadata = $envelope->getMetadata();
$currentCount = $metadata['filesCount'] ?? 0;
$metadata['filesCount'] = max(0, $currentCount + $delta);
$envelope->setMetadata($metadata);
$this->fileMapper->update($envelope);
}
private function decrementEnvelopeFilesCountIfNeeded(File $file): void {
if ($file->getParentFileId() === null) {
return;
}
$parentEnvelope = $this->fileMapper->getById($file->getParentFileId());
if ($parentEnvelope->getNodeType() === 'envelope') {
$this->updateEnvelopeFilesCount($parentEnvelope, -1);
}
}
}