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

LibreSign / libresign / 19881416377

03 Dec 2025 03:33AM UTC coverage: 41.566%. First build
19881416377

Pull #5951

github

web-flow
Merge 5a6b1bb3e into a3b5116b0
Pull Request #5951: fix: remove duplicate extension

7 of 17 new or added lines in 2 files covered. (41.18%)

5128 of 12337 relevant lines covered (41.57%)

4.17 hits per line

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

81.03
/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\Db\File as FileEntity;
12
use OCA\Libresign\Db\FileElementMapper;
13
use OCA\Libresign\Db\FileMapper;
14
use OCA\Libresign\Db\IdentifyMethodMapper;
15
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
16
use OCA\Libresign\Db\SignRequestMapper;
17
use OCA\Libresign\Helper\ValidateHelper;
18
use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod;
19
use OCP\AppFramework\Db\DoesNotExistException;
20
use OCP\Files\IMimeTypeDetector;
21
use OCP\Files\Node;
22
use OCP\Http\Client\IClientService;
23
use OCP\IL10N;
24
use OCP\IUser;
25
use OCP\IUserManager;
26
use Psr\Log\LoggerInterface;
27
use Sabre\DAV\UUIDUtil;
28

29
class RequestSignatureService {
30
        use TFile;
31

32
        public function __construct(
33
                protected IL10N $l10n,
34
                protected IdentifyMethodService $identifyMethod,
35
                protected SignRequestMapper $signRequestMapper,
36
                protected IUserManager $userManager,
37
                protected FileMapper $fileMapper,
38
                protected IdentifyMethodMapper $identifyMethodMapper,
39
                protected PdfParserService $pdfParserService,
40
                protected FileElementService $fileElementService,
41
                protected FileElementMapper $fileElementMapper,
42
                protected FolderService $folderService,
43
                protected IMimeTypeDetector $mimeTypeDetector,
44
                protected ValidateHelper $validateHelper,
45
                protected IClientService $client,
46
                protected LoggerInterface $logger,
47
        ) {
48
        }
54✔
49

50
        public function save(array $data): FileEntity {
51
                $file = $this->saveFile($data);
14✔
52
                $this->saveVisibleElements($data, $file);
14✔
53
                if (empty($data['status'])) {
14✔
54
                        $data['status'] = $file->getStatus();
13✔
55
                }
56
                $this->associateToSigners($data, $file->getId());
14✔
57
                return $file;
14✔
58
        }
59

60
        /**
61
         * Save file data
62
         *
63
         * @param array{?userManager: IUser, ?signRequest: SignRequest, name: string, callback: string, uuid?: ?string, status: int, file?: array{fileId?: int, fileNode?: Node}} $data
64
         */
65
        public function saveFile(array $data): FileEntity {
66
                if (!empty($data['uuid'])) {
15✔
67
                        $file = $this->fileMapper->getByUuid($data['uuid']);
1✔
68
                        return $this->updateStatus($file, $data['status'] ?? 0);
1✔
69
                }
70
                $fileId = null;
15✔
71
                if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
15✔
72
                        $fileId = $data['file']['fileNode']->getId();
1✔
73
                } elseif (!empty($data['file']['fileId'])) {
14✔
74
                        $fileId = $data['file']['fileId'];
×
75
                }
76
                if (!is_null($fileId)) {
15✔
77
                        try {
78
                                $file = $this->fileMapper->getByFileId($fileId);
1✔
79
                                return $this->updateStatus($file, $data['status'] ?? 0);
×
80
                        } catch (\Throwable) {
1✔
81
                        }
82
                }
83

84
                $node = $this->getNodeFromData($data);
15✔
85

86
                $file = new FileEntity();
15✔
87
                $file->setNodeId($node->getId());
15✔
88
                if ($data['userManager'] instanceof IUser) {
15✔
89
                        $file->setUserId($data['userManager']->getUID());
15✔
90
                } elseif ($data['signRequest'] instanceof SignRequestEntity) {
×
91
                        $file->setSignRequestId($data['signRequest']->getId());
×
92
                }
93
                $file->setUuid(UUIDUtil::getUUID());
15✔
94
                $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
15✔
95
                $metadata = $this->getFileMetadata($node);
15✔
96
                $file->setName($this->removeExtensionFromName($data['name'], $metadata));
15✔
97
                $file->setMetadata($metadata);
15✔
98
                if (!empty($data['callback'])) {
15✔
99
                        $file->setCallback($data['callback']);
×
100
                }
101
                if (isset($data['status'])) {
15✔
102
                        $file->setStatus($data['status']);
2✔
103
                } else {
104
                        $file->setStatus(FileEntity::STATUS_ABLE_TO_SIGN);
13✔
105
                }
106
                $this->fileMapper->insert($file);
15✔
107
                return $file;
15✔
108
        }
109

110
        private function updateStatus(FileEntity $file, int $status): FileEntity {
111
                if ($status > $file->getStatus()) {
1✔
112
                        $file->setStatus($status);
×
113
                        /** @var FileEntity */
114
                        return $this->fileMapper->update($file);
×
115
                }
116
                return $file;
1✔
117
        }
118

119
        private function getFileMetadata(\OCP\Files\Node $node): array {
120
                $metadata = [];
18✔
121
                if ($extension = strtolower($node->getExtension())) {
18✔
122
                        $metadata = [
17✔
123
                                'extension' => $extension,
17✔
124
                        ];
17✔
125
                        if ($metadata['extension'] === 'pdf') {
17✔
126
                                $metadata = array_merge(
16✔
127
                                        $metadata,
16✔
128
                                        $this->pdfParserService
16✔
129
                                                ->setFile($node)
16✔
130
                                                ->getPageDimensions()
16✔
131
                                );
16✔
132
                        }
133
                }
134
                return $metadata;
18✔
135
        }
136

137
        private function removeExtensionFromName(string $name, array $metadata): string {
138
                if (!isset($metadata['extension'])) {
15✔
NEW
139
                        return $name;
×
140
                }
141
                $extensionPattern = '/\.' . preg_quote($metadata['extension'], '/') . '$/i';
15✔
142
                $result = preg_replace($extensionPattern, '', $name);
15✔
143
                return $result ?? $name;
15✔
144
        }
145

146
        private function deleteIdentifyMethodIfNotExits(array $users, int $fileId): void {
147
                $file = $this->fileMapper->getById($fileId);
13✔
148
                $signRequests = $this->signRequestMapper->getByFileId($fileId);
13✔
149
                foreach ($signRequests as $key => $signRequest) {
13✔
150
                        $identifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequest->getId());
1✔
151
                        if (empty($identifyMethods)) {
1✔
152
                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
×
153
                                continue;
×
154
                        }
155
                        foreach ($identifyMethods as $methodName => $list) {
1✔
156
                                foreach ($list as $method) {
1✔
157
                                        $exists[$key]['identify'][$methodName] = $method->getEntity()->getIdentifierValue();
1✔
158
                                        if (!$this->identifyMethodExists($users, $method)) {
1✔
159
                                                $this->unassociateToUser($file->getNodeId(), $signRequest->getId());
1✔
160
                                                continue 3;
1✔
161
                                        }
162
                                }
163
                        }
164
                }
165
        }
166

167
        private function identifyMethodExists(array $users, IIdentifyMethod $identifyMethod): bool {
168
                foreach ($users as $user) {
1✔
169
                        if (!empty($user['identifyMethods'])) {
1✔
170
                                foreach ($user['identifyMethods'] as $data) {
×
171
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $data['method']) {
×
172
                                                continue;
×
173
                                        }
174
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $data['value']) {
×
175
                                                return true;
×
176
                                        }
177
                                }
178
                        } else {
179
                                foreach ($user['identify'] as $method => $value) {
1✔
180
                                        if ($identifyMethod->getEntity()->getIdentifierKey() !== $method) {
1✔
181
                                                continue;
×
182
                                        }
183
                                        if ($identifyMethod->getEntity()->getIdentifierValue() === $value) {
1✔
184
                                                return true;
×
185
                                        }
186
                                }
187
                        }
188
                }
189
                return false;
1✔
190
        }
191

192
        /**
193
         * @return SignRequestEntity[]
194
         *
195
         * @psalm-return list<SignRequestEntity>
196
         */
197
        private function associateToSigners(array $data, int $fileId): array {
198
                $return = [];
14✔
199
                if (!empty($data['users'])) {
14✔
200
                        $this->deleteIdentifyMethodIfNotExits($data['users'], $fileId);
13✔
201
                        foreach ($data['users'] as $user) {
13✔
202
                                if (isset($user['identifyMethods'])) {
13✔
203
                                        foreach ($user['identifyMethods'] as $identifyMethod) {
×
204
                                                $return[] = $this->associateToSigner(
×
205
                                                        identifyMethods: [
×
206
                                                                $identifyMethod['method'] => $identifyMethod['value'],
×
207
                                                        ],
×
208
                                                        displayName: $user['displayName'] ?? '',
×
209
                                                        description: $user['description'] ?? '',
×
210
                                                        notify: empty($user['notify']) && $this->isStatusAbleToNotify($data['status'] ?? null),
×
211
                                                        fileId: $fileId,
×
212
                                                );
×
213
                                        }
214
                                } else {
215
                                        $return[] = $this->associateToSigner(
13✔
216
                                                identifyMethods: $user['identify'],
13✔
217
                                                displayName: $user['displayName'] ?? '',
13✔
218
                                                description: $user['description'] ?? '',
13✔
219
                                                notify: empty($user['notify']) && $this->isStatusAbleToNotify($data['status'] ?? null),
13✔
220
                                                fileId: $fileId,
13✔
221
                                        );
13✔
222
                                }
223
                        }
224
                }
225
                return $return;
14✔
226
        }
227

228
        private function isStatusAbleToNotify(?int $status): bool {
229
                return in_array($status, [
13✔
230
                        FileEntity::STATUS_ABLE_TO_SIGN,
13✔
231
                        FileEntity::STATUS_PARTIAL_SIGNED,
13✔
232
                ]);
13✔
233
        }
234

235
        private function associateToSigner(array $identifyMethods, string $displayName, string $description, bool $notify, int $fileId): SignRequestEntity {
236
                $identifyMethodsIncances = $this->identifyMethod->getByUserData($identifyMethods);
13✔
237
                if (empty($identifyMethodsIncances)) {
13✔
238
                        throw new \Exception($this->l10n->t('Invalid identification method'));
×
239
                }
240
                $signRequest = $this->getSignRequestByIdentifyMethod(
13✔
241
                        current($identifyMethodsIncances),
13✔
242
                        $fileId
13✔
243
                );
13✔
244
                $displayName = $this->getDisplayNameFromIdentifyMethodIfEmpty($identifyMethodsIncances, $displayName);
13✔
245
                $this->setDataToUser($signRequest, $displayName, $description, $fileId);
13✔
246
                $this->saveSignRequest($signRequest);
13✔
247
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
248
                        $identifyMethod->getEntity()->setSignRequestId($signRequest->getId());
13✔
249
                        $identifyMethod->willNotifyUser($notify);
13✔
250
                        $identifyMethod->save();
13✔
251
                }
252
                return $signRequest;
13✔
253
        }
254

255
        /**
256
         * @param IIdentifyMethod[] $identifyMethodsIncances
257
         * @param string $displayName
258
         * @return string
259
         */
260
        private function getDisplayNameFromIdentifyMethodIfEmpty(array $identifyMethodsIncances, string $displayName): string {
261
                if (!empty($displayName)) {
13✔
262
                        return $displayName;
×
263
                }
264
                foreach ($identifyMethodsIncances as $identifyMethod) {
13✔
265
                        if ($identifyMethod->getName() === 'account') {
13✔
266
                                return $this->userManager->get($identifyMethod->getEntity()->getIdentifierValue())->getDisplayName();
2✔
267
                        }
268
                }
269
                foreach ($identifyMethodsIncances as $identifyMethod) {
11✔
270
                        if ($identifyMethod->getName() !== 'account') {
11✔
271
                                return $identifyMethod->getEntity()->getIdentifierValue();
11✔
272
                        }
273
                }
274
                return '';
×
275
        }
276

277
        private function saveVisibleElements(array $data, FileEntity $file): array {
278
                if (empty($data['visibleElements'])) {
17✔
279
                        return [];
15✔
280
                }
281
                $elements = $data['visibleElements'];
2✔
282
                foreach ($elements as $key => $element) {
2✔
283
                        $element['fileId'] = $file->getId();
2✔
284
                        $elements[$key] = $this->fileElementService->saveVisibleElement($element);
2✔
285
                }
286
                return $elements;
2✔
287
        }
288

289
        public function validateNewRequestToFile(array $data): void {
290
                $this->validateNewFile($data);
7✔
291
                $this->validateUsers($data);
6✔
292
                $this->validateHelper->validateFileStatus($data);
2✔
293
        }
294

295
        public function validateNewFile(array $data): void {
296
                if (empty($data['name'])) {
7✔
297
                        throw new \Exception($this->l10n->t('Name is mandatory'));
1✔
298
                }
299
                $this->validateHelper->validateNewFile($data);
6✔
300
        }
301

302
        public function validateUsers(array $data): void {
303
                if (empty($data['users'])) {
6✔
304
                        throw new \Exception($this->l10n->t('Empty users list'));
3✔
305
                }
306
                if (!is_array($data['users'])) {
3✔
307
                        // TRANSLATION This message will be displayed when the request to API with the key users has a value that is not an array
308
                        throw new \Exception($this->l10n->t('User list needs to be an array'));
1✔
309
                }
310
                foreach ($data['users'] as $user) {
2✔
311
                        if (!array_key_exists('identify', $user)) {
2✔
312
                                throw new \Exception('Identify key not found');
×
313
                        }
314
                        $this->identifyMethod->setAllEntityData($user);
2✔
315
                }
316
        }
317

318
        public function saveSignRequest(SignRequestEntity $signRequest): void {
319
                if ($signRequest->getId()) {
15✔
320
                        $this->signRequestMapper->update($signRequest);
1✔
321
                } else {
322
                        $this->signRequestMapper->insert($signRequest);
14✔
323
                }
324
        }
325

326
        /**
327
         * @psalm-suppress MixedMethodCall
328
         */
329
        private function setDataToUser(SignRequestEntity $signRequest, string $displayName, string $description, int $fileId): void {
330
                $signRequest->setFileId($fileId);
13✔
331
                if (!$signRequest->getUuid()) {
13✔
332
                        $signRequest->setUuid(UUIDUtil::getUUID());
13✔
333
                }
334
                if (!empty($displayName)) {
13✔
335
                        $signRequest->setDisplayName($displayName);
13✔
336
                }
337
                if (!empty($description)) {
13✔
338
                        $signRequest->setDescription($description);
×
339
                }
340
                if (!$signRequest->getId()) {
13✔
341
                        $signRequest->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
13✔
342
                }
343
        }
344

345
        private function getSignRequestByIdentifyMethod(IIdentifyMethod $identifyMethod, int $fileId): SignRequestEntity {
346
                try {
347
                        $signRequest = $this->signRequestMapper->getByIdentifyMethodAndFileId($identifyMethod, $fileId);
13✔
348
                } catch (DoesNotExistException) {
13✔
349
                        $signRequest = new SignRequestEntity();
13✔
350
                }
351
                return $signRequest;
13✔
352
        }
353

354
        public function unassociateToUser(int $fileId, int $signRequestId): void {
355
                $signRequest = $this->signRequestMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
356
                try {
357
                        $this->signRequestMapper->delete($signRequest);
2✔
358
                        $groupedIdentifyMethods = $this->identifyMethod->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
359
                        foreach ($groupedIdentifyMethods as $identifyMethods) {
2✔
360
                                foreach ($identifyMethods as $identifyMethod) {
2✔
361
                                        $identifyMethod->delete();
2✔
362
                                }
363
                        }
364
                        $visibleElements = $this->fileElementMapper->getByFileIdAndSignRequestId($fileId, $signRequestId);
2✔
365
                        foreach ($visibleElements as $visibleElement) {
2✔
366
                                $this->fileElementMapper->delete($visibleElement);
×
367
                        }
368
                } catch (\Throwable) {
×
369
                }
370
        }
371

372
        public function deleteRequestSignature(array $data): void {
373
                if (!empty($data['uuid'])) {
2✔
374
                        $signatures = $this->signRequestMapper->getByFileUuid($data['uuid']);
×
375
                        $fileData = $this->fileMapper->getByUuid($data['uuid']);
×
376
                } elseif (!empty($data['file']['fileId'])) {
2✔
377
                        $signatures = $this->signRequestMapper->getByNodeId($data['file']['fileId']);
2✔
378
                        $fileData = $this->fileMapper->getByFileId($data['file']['fileId']);
2✔
379
                } else {
380
                        throw new \Exception($this->l10n->t('Please provide either UUID or File object'));
×
381
                }
382
                foreach ($signatures as $signRequest) {
2✔
383
                        $this->signRequestMapper->delete($signRequest);
2✔
384
                }
385
                $this->fileMapper->delete($fileData);
2✔
386
                $this->fileElementService->deleteVisibleElements($fileData->getId());
2✔
387
        }
388
}
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