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

LibreSign / libresign / 20213135400

14 Dec 2025 07:38PM UTC coverage: 44.224%. First build
20213135400

Pull #6187

github

web-flow
Merge 50b66c4f7 into 7a542b3a8
Pull Request #6187: feat: docmdp per file

17 of 26 new or added lines in 5 files covered. (65.38%)

5961 of 13479 relevant lines covered (44.22%)

5.12 hits per line

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

80.25
/lib/Service/RequestSignatureService.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 OCA\Libresign\AppInfo\Application;
12
use OCA\Libresign\Db\File as FileEntity;
13
use OCA\Libresign\Db\FileElementMapper;
14
use OCA\Libresign\Db\FileMapper;
15
use OCA\Libresign\Db\IdentifyMethodMapper;
16
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
17
use OCA\Libresign\Db\SignRequestMapper;
18
use OCA\Libresign\Enum\SignatureFlow;
19
use OCA\Libresign\Events\SignRequestCanceledEvent;
20
use OCA\Libresign\Handler\DocMdpHandler;
21
use OCA\Libresign\Helper\ValidateHelper;
22
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
23
use OCP\AppFramework\Db\DoesNotExistException;
24
use OCP\EventDispatcher\IEventDispatcher;
25
use OCP\Files\IMimeTypeDetector;
26
use OCP\Files\Node;
27
use OCP\Http\Client\IClientService;
28
use OCP\IAppConfig;
29
use OCP\IL10N;
30
use OCP\IUser;
31
use OCP\IUserManager;
32
use Psr\Log\LoggerInterface;
33
use Sabre\DAV\UUIDUtil;
34

35
class RequestSignatureService {
36
        use TFile;
37

38
        public function __construct(
39
                protected IL10N $l10n,
40
                protected IdentifyMethodService $identifyMethod,
41
                protected SignRequestMapper $signRequestMapper,
42
                protected IUserManager $userManager,
43
                protected FileMapper $fileMapper,
44
                protected IdentifyMethodMapper $identifyMethodMapper,
45
                protected PdfParserService $pdfParserService,
46
                protected FileElementService $fileElementService,
47
                protected FileElementMapper $fileElementMapper,
48
                protected FolderService $folderService,
49
                protected IMimeTypeDetector $mimeTypeDetector,
50
                protected ValidateHelper $validateHelper,
51
                protected IClientService $client,
52
                protected DocMdpHandler $docMdpHandler,
53
                protected LoggerInterface $logger,
54
                protected SequentialSigningService $sequentialSigningService,
55
                protected IAppConfig $appConfig,
56
                protected IEventDispatcher $eventDispatcher,
57
                protected FileStatusService $fileStatusService,
58
                protected SignRequestStatusService $signRequestStatusService,
59
                protected DocMdpConfigService $docMdpConfigService,
60
        ) {
61
        }
54✔
62

63
        public function save(array $data): FileEntity {
64
                $file = $this->saveFile($data);
14✔
65
                $this->saveVisibleElements($data, $file);
14✔
66
                if (!isset($data['status'])) {
14✔
67
                        $data['status'] = $file->getStatus();
12✔
68
                }
69
                $this->sequentialSigningService->setFile($file);
14✔
70
                $this->associateToSigners($data, $file->getId());
14✔
71
                return $file;
14✔
72
        }
73

74
        /**
75
         * Save file data
76
         *
77
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
78
         */
79
        public function saveFile(array $data): FileEntity {
80
                if (!empty($data['uuid'])) {
15✔
81
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
82
                        return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
1✔
83
                }
84
                $fileId = null;
15✔
85
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
86
                        $fileId = $data['file']['fileNode']->getId();
1✔
87
                } elseif (!empty($data['file']['fileId'])) {
14✔
88
                        $fileId = $data['file']['fileId'];
×
89
                }
90
                if (!is_null($fileId)) {
15✔
91
                        try {
92
                                $file = $this->fileMapper->getByFileId($fileId);
1✔
93
                                return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0);
×
94
                        } catch (\Throwable) {
1✔
95
                        }
96
                }
97

98
                $node = $this->getNodeFromData($data);
15✔
99

100
                $file = new FileEntity();
15✔
101
                $file->setNodeId($node->getId());
15✔
102
                if ($data['userManager'] instanceof IUser) {
15✔
103
                        $file->setUserId($data['userManager']->getUID());
15✔
104
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
105
                        $file->setSignRequestId($data['signRequest']->getId());
×
106
                }
107
                $file->setUuid(UUIDUtil::getUUID());
15✔
108
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
109
                $metadata = $this->getFileMetadata($node);
15✔
110
                $file->setName($this->removeExtensionFromName($data['name'], $metadata));
15✔
111
                $file->setMetadata($metadata);
15✔
112
                if (!empty($data['callback'])) {
15✔
113
                        $file->setCallback($data['callback']);
×
114
                }
115
                if (isset($data['status'])) {
15✔
116
                        $file->setStatus($data['status']);
2✔
117
                } else {
118
                        $file->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
13✔
119
                }
120

121
                if (isset($data['signatureFlow']) && is_string($data['signatureFlow'])) {
15✔
122
                        try {
123
                                $signatureFlow = \OCA\Libresign\Enum\SignatureFlow::from($data['signatureFlow']);
×
124
                                $file->setSignatureFlowEnum($signatureFlow);
×
125
                        } catch (\ValueError) {
×
126
                                $this->setSignatureFlowFromGlobalConfig($file);
×
127
                        }
128
                } else {
129
                        $this->setSignatureFlowFromGlobalConfig($file);
15✔
130
                }
131

132
                $this->setDocMdpLevelFromGlobalConfig($file);
15✔
133

134
                $this->fileMapper->insert($file);
15✔
135
                return $file;
15✔
136
        }
137

138
        private function setSignatureFlowFromGlobalConfig(FileEntity $file): void {
139
                $globalFlowValue = $this->appConfig->getValueString(Application::APP_ID, 'signature_flow', SignatureFlow::PARALLEL->value);
15✔
140
                $globalFlow = SignatureFlow::from($globalFlowValue);
15✔
141
                $file->setSignatureFlowEnum($globalFlow);
15✔
142
        }
143

144
        private function setDocMdpLevelFromGlobalConfig(FileEntity $file): void {
145
                if ($this->docMdpConfigService->isEnabled()) {
15✔
NEW
146
                        $docmdpLevel = $this->docMdpConfigService->getLevel();
×
NEW
147
                        $file->setDocmdpLevelEnum($docmdpLevel);
×
148
                }
149
        }
150

151
        private function getFileMetadata(\OCP\Files\Node $node): array {
152
                $metadata = [];
18✔
153
                if ($extension = strtolower($node->getExtension())) {
18✔
154
                        $metadata = [
17✔
155
                                'extension' => $extension,
17✔
156
                        ];
17✔
157
                        if ($metadata['extension'] === 'pdf') {
17✔
158
                                $metadata = array_merge(
16✔
159
                                        $metadata,
16✔
160
                                        $this->pdfParserService
16✔
161
                                                ->setFile($node)
16✔
162
                                                ->getPageDimensions()
16✔
163
                                );
16✔
164
                        }
165
                }
166
                return $metadata;
18✔
167
        }
168

169
        private function removeExtensionFromName(string $name, array $metadata): string {
170
                if (!isset($metadata['extension'])) {
15✔
171
                        return $name;
×
172
                }
173
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
174
                $result = preg_replace($extensionPattern, '', $name);
15✔
175
                return $result ?? $name;
15✔
176
        }
177

178
        private function deleteIdentifyMethodIfNotExits(array $users, int $fileId): void {
179
                $file = $this->fileMapper->getById($fileId);
13✔
180
                $signRequests = $this->signRequestMapper->getByFileId($fileId);
13✔
181
                foreach ($signRequests as $key => $signRequest) {
13✔
182
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
183
                        if (empty($identifyMethods)) {
1✔
184
                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
×
185
                                continue;
×
186
                        }
187
                        foreach ($identifyMethods as $methodName => $list) {
1✔
188
                                foreach ($list as $method) {
1✔
189
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
190
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
191
                                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
1✔
192
                                                continue 3;
1✔
193
                                        }
194
                                }
195
                        }
196
                }
197
        }
198

199
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
200
                foreach ($users as $user) {
1✔
201
                        if (!empty($user['identifyMethods'])) {
1✔
202
                                foreach ($user['identifyMethods'] as $data) {
×
203
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
204
                                                continue;
×
205
                                        }
206
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
207
                                                return true;
×
208
                                        }
209
                                }
210
                        } else {
211
                                foreach ($user['identify'] as $method => $value) {
1✔
212
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
213
                                                continue;
×
214
                                        }
215
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
216
                                                return true;
×
217
                                        }
218
                                }
219
                        }
220
                }
221
                return false;
1✔
222
        }
223

224
        /**
225
         * @return SignRequestEntity[]
226
         *
227
         * @psalm-return list<SignRequestEntity>
228
         */
229
        private function associateToSigners(array $data, int $fileId): array {
230
                $return = [];
14✔
231
                if (!empty($data['users'])) {
14✔
232
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $fileId);
13✔
233

234
                        $this->sequentialSigningService->resetOrderCounter();
13✔
235
                        $fileStatus = $data['status'] ?? null;
13✔
236

237
                        foreach ($data['users'] as $user) {
13✔
238
                                $userProvidedOrder = isset($user['signingOrder']) ? (int)$user['signingOrder'] : null;
13✔
239
                                $signingOrder = $this->sequentialSigningService->determineSigningOrder($userProvidedOrder);
13✔
240
                                $signerStatus = $user['status'] ?? null;
13✔
241

242
                                if (isset($user['identifyMethods'])) {
13✔
243
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
244
                                                $return[] = $this->associateToSigner(
×
245
                                                        identifyMethods: [
×
246
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
247
                                                        ],
×
248
                                                        displayName: $user['displayName'] ?? '',
×
249
                                                        description: $user['description'] ?? '',
×
250
                                                        notify: empty($user['notify']),
×
251
                                                        fileId: $fileId,
×
252
                                                        signingOrder: $signingOrder,
×
253
                                                        fileStatus: $fileStatus,
×
254
                                                        signerStatus: $signerStatus,
×
255
                                                );
×
256
                                        }
257
                                } else {
258
                                        $return[] = $this->associateToSigner(
13✔
259
                                                identifyMethods: $user['identify'],
13✔
260
                                                displayName: $user['displayName'] ?? '',
13✔
261
                                                description: $user['description'] ?? '',
13✔
262
                                                notify: empty($user['notify']),
13✔
263
                                                fileId: $fileId,
13✔
264
                                                signingOrder: $signingOrder,
13✔
265
                                                fileStatus: $fileStatus,
13✔
266
                                                signerStatus: $signerStatus,
13✔
267
                                        );
13✔
268
                                }
269
                        }
270
                }
271
                return $return;
14✔
272
        }
273

274
        private function associateToSigner(
275
                array $identifyMethods,
276
                string $displayName,
277
                string $description,
278
                bool $notify,
279
                int $fileId,
280
                int $signingOrder = 0,
281
                ?int $fileStatus = null,
282
                ?int $signerStatus = null,
283
        ): SignRequestEntity {
284
                $identifyMethodsIncances = $this->identifyMethod->getByUserData($identifyMethods);
13✔
285
                if (empty($identifyMethodsIncances)) {
13✔
286
                        throw new \Exception($this->l10n->t('Invalid identification method'));
×
287
                }
288
                $signRequest = $this->getSignRequestByIdentifyMethod(
13✔
289
                        current($identifyMethodsIncances),
13✔
290
                        $fileId
13✔
291
                );
13✔
292
                $displayName = $this->getDisplayNameFromIdentifyMethodIfEmpty($identifyMethodsIncances, $displayName);
13✔
293
                $this->setDataToUser($signRequest, $displayName, $description, $fileId);
13✔
294

295
                $signRequest->setSigningOrder($signingOrder);
13✔
296

297
                $isNewSignRequest = !$signRequest->getId();
13✔
298
                $currentStatus = $signRequest->getStatusEnum();
13✔
299

300
                if ($isNewSignRequest || $currentStatus === \OCA\Libresign\Enum\SignRequestStatus::DRAFT) {
13✔
301
                        $desiredStatus = $this->signRequestStatusService->determineInitialStatus($signingOrder, $fileId, $fileStatus, $signerStatus, $currentStatus);
13✔
302
                        $this->signRequestStatusService->updateStatusIfAllowed($signRequest, $currentStatus, $desiredStatus, $isNewSignRequest);
13✔
303
                }
304

305
                $this->saveSignRequest($signRequest);
13✔
306

307
                $shouldNotify = $notify && $this->signRequestStatusService->shouldNotifySignRequest(
13✔
308
                        $signRequest->getStatusEnum(),
13✔
309
                        $fileStatus
13✔
310
                );
13✔
311

312
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
313
                        $identifyMethod->getEntity()->setSignRequestId($signRequest->getId());
13✔
314
                        $identifyMethod->willNotifyUser($shouldNotify);
13✔
315
                        $identifyMethod->save();
13✔
316
                }
317
                return $signRequest;
13✔
318
        }
319

320
        /**
321
         * @param IIdentifyMethod[] $identifyMethodsIncances
322
         * @param string $displayName
323
         * @return string
324
         */
325
        private function getDisplayNameFromIdentifyMethodIfEmpty(array $identifyMethodsIncances, string $displayName): string {
326
                if (!empty($displayName)) {
13✔
327
                        return $displayName;
×
328
                }
329
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
330
                        if ($identifyMethod->getName() === 'account') {
13✔
331
                                return $this->userManager->get($identifyMethod->getEntity()->getIdentifierValue())->getDisplayName();
2✔
332
                        }
333
                }
334
                foreach ($identifyMethodsIncances as $identifyMethod) {
11✔
335
                        if ($identifyMethod->getName() !== 'account') {
11✔
336
                                return $identifyMethod->getEntity()->getIdentifierValue();
11✔
337
                        }
338
                }
339
                return '';
×
340
        }
341

342
        private function saveVisibleElements(array $data, FileEntity $file): array {
343
                if (empty($data['visibleElements'])) {
17✔
344
                        return [];
15✔
345
                }
346
                $elements = $data['visibleElements'];
2✔
347
                foreach ($elements as $key => $element) {
2✔
348
                        $element['fileId'] = $file->getId();
2✔
349
                        $elements[$key] = $this->fileElementService->saveVisibleElement($element);
2✔
350
                }
351
                return $elements;
2✔
352
        }
353

354
        public function validateNewRequestToFile(array $data): void {
355
                $this->validateNewFile($data);
7✔
356
                $this->validateUsers($data);
6✔
357
                $this->validateHelper->validateFileStatus($data);
2✔
358
        }
359

360
        public function validateNewFile(array $data): void {
361
                if (empty($data['name'])) {
7✔
362
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
363
                }
364
                $this->validateHelper->validateNewFile($data);
6✔
365
        }
366

367
        public function validateUsers(array $data): void {
368
                if (empty($data['users'])) {
6✔
369
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
370
                }
371
                if (!is_array($data['users'])) {
3✔
372
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
373
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
374
                }
375
                foreach ($data['users'] as $user) {
2✔
376
                        if (!array_key_exists('identify', $user)) {
2✔
377
                                throw new \Exception('Identify key not found');
×
378
                        }
379
                        $this->identifyMethod->setAllEntityData($user);
2✔
380
                }
381
        }
382

383
        public function saveSignRequest(SignRequestEntity $signRequest): void {
384
                if ($signRequest->getId()) {
15✔
385
                        $this->signRequestMapper->update($signRequest);
1✔
386
                } else {
387
                        $this->signRequestMapper->insert($signRequest);
14✔
388
                }
389
        }
390

391
        /**
392
         * @psalm-suppress MixedMethodCall
393
         */
394
        private function setDataToUser(SignRequestEntity $signRequest, string $displayName, string $description, int $fileId): void {
395
                $signRequest->setFileId($fileId);
13✔
396
                if (!$signRequest->getUuid()) {
13✔
397
                        $signRequest->setUuid(UUIDUtil::getUUID());
13✔
398
                }
399
                if (!empty($displayName)) {
13✔
400
                        $signRequest->setDisplayName($displayName);
13✔
401
                }
402
                if (!empty($description)) {
13✔
403
                        $signRequest->setDescription($description);
×
404
                }
405
                if (!$signRequest->getId()) {
13✔
406
                        $signRequest->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
13✔
407
                }
408
        }
409

410
        private function getSignRequestByIdentifyMethod(IIdentifyMethod $identifyMethod, int $fileId): SignRequestEntity {
411
                try {
412
                        $signRequest = $this->signRequestMapper->getByIdentifyMethodAndFileId($identifyMethod, $fileId);
13✔
413
                } catch (DoesNotExistException) {
13✔
414
                        $signRequest = new SignRequestEntity();
13✔
415
                }
416
                return $signRequest;
13✔
417
        }
418

419
        public function unassociateToUser(int $fileId, int $signRequestId): void {
420
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
421
                $deletedOrder = $signRequest->getSigningOrder();
2✔
422
                $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
423

424
                $this->dispatchCancellationEventIfNeeded($signRequest, $fileId, $groupedIdentifyMethods);
2✔
425

426
                try {
427
                        $this->signRequestMapper->delete($signRequest);
2✔
428
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
429
                                foreach ($identifyMethods as $identifyMethod) {
2✔
430
                                        $identifyMethod->delete();
2✔
431
                                }
432
                        }
433
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
434
                        foreach ($visibleElements as $visibleElement) {
2✔
435
                                $this->fileElementMapper->delete($visibleElement);
×
436
                        }
437

438
                        $this->sequentialSigningService->reorderAfterDeletion($fileId, $deletedOrder);
2✔
439
                } catch (\Throwable) {
×
440
                }
441
        }
442

443
        private function dispatchCancellationEventIfNeeded(
444
                SignRequestEntity $signRequest,
445
                int $fileId,
446
                array $groupedIdentifyMethods,
447
        ): void {
448
                if ($signRequest->getStatus() !== \OCA\Libresign\Enum\SignRequestStatus::ABLE_TO_SIGN->value) {
2✔
449
                        return;
×
450
                }
451

452
                try {
453
                        $libreSignFile = $this->fileMapper->getByFileId($fileId);
2✔
454
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
455
                                foreach ($identifyMethods as $identifyMethod) {
2✔
456
                                        $event = new SignRequestCanceledEvent(
2✔
457
                                                $signRequest,
2✔
458
                                                $libreSignFile,
2✔
459
                                                $identifyMethod,
2✔
460
                                        );
2✔
461
                                        $this->eventDispatcher->dispatchTyped($event);
2✔
462
                                }
463
                        }
464
                } catch (\Throwable $e) {
×
465
                        $this->logger->error('Error dispatching SignRequestCanceledEvent: ' . $e->getMessage(), ['exception' => $e]);
×
466
                }
467
        }
468

469
        public function deleteRequestSignature(array $data): void {
470
                if (!empty($data['uuid'])) {
2✔
471
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
472
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
473
                } elseif (!empty($data['file']['fileId'])) {
2✔
474
                        $signatures = $this->signRequestMapper->getByNodeId($data['file']['fileId']);
2✔
475
                        $fileData = $this->fileMapper->getByFileId($data['file']['fileId']);
2✔
476
                } else {
477
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
478
                }
479
                foreach ($signatures as $signRequest) {
2✔
480
                        $this->signRequestMapper->delete($signRequest);
2✔
481
                }
482
                $this->fileMapper->delete($fileData);
2✔
483
                $this->fileElementService->deleteVisibleElements($fileData->getId());
2✔
484
        }
485
}
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