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

LibreSign / libresign / 22001013727

13 Feb 2026 08:03PM UTC coverage: 51.563%. First build
22001013727

Pull #6856

github

web-flow
Merge 8d73038b1 into 61b58bf2d
Pull Request #6856: feat: signers count order by

0 of 6 new or added lines in 2 files covered. (0.0%)

9058 of 17567 relevant lines covered (51.56%)

6.13 hits per line

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

25.27
/lib/Service/AccountService.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 InvalidArgumentException;
12
use OCA\Libresign\AppInfo\Application;
13
use OCA\Libresign\Db\FileMapper;
14
use OCA\Libresign\Db\FileTypeMapper;
15
use OCA\Libresign\Db\IdentifyMethodMapper;
16
use OCA\Libresign\Db\SignRequest;
17
use OCA\Libresign\Db\SignRequestMapper;
18
use OCA\Libresign\Db\UserElement;
19
use OCA\Libresign\Db\UserElementMapper;
20
use OCA\Libresign\Enum\FileStatus;
21
use OCA\Libresign\Exception\InvalidPasswordException;
22
use OCA\Libresign\Exception\LibresignException;
23
use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory;
24
use OCA\Libresign\Handler\SignEngine\Pkcs12Handler;
25
use OCA\Libresign\Helper\FileUploadHelper;
26
use OCA\Libresign\Helper\ValidateHelper;
27
use OCA\Settings\Mailer\NewUserMailHelper;
28
use OCP\Accounts\IAccountManager;
29
use OCP\AppFramework\Db\DoesNotExistException;
30
use OCP\AppFramework\Utility\ITimeFactory;
31
use OCP\Files\Config\IMountProviderCollection;
32
use OCP\Files\File;
33
use OCP\Files\IMimeTypeDetector;
34
use OCP\Files\IRootFolder;
35
use OCP\Files\NotFoundException;
36
use OCP\Http\Client\IClientService;
37
use OCP\IAppConfig;
38
use OCP\IConfig;
39
use OCP\IGroupManager;
40
use OCP\IL10N;
41
use OCP\IURLGenerator;
42
use OCP\IUser;
43
use OCP\IUserManager;
44
use Sabre\DAV\UUIDUtil;
45
use Throwable;
46

47
class AccountService {
48
        private ?SignRequest $signRequest = null;
49
        private ?\OCA\Libresign\Db\File $fileData = null;
50
        private \OCP\Files\File $fileToSign;
51

52
        public function __construct(
53
                private IL10N $l10n,
54
                private SignRequestMapper $signRequestMapper,
55
                private IUserManager $userManager,
56
                private IAccountManager $accountManager,
57
                private IRootFolder $root,
58
                private IMimeTypeDetector $mimeTypeDetector,
59
                private FileMapper $fileMapper,
60
                private FileTypeMapper $fileTypeMapper,
61
                private SignFileService $signFileService,
62
                private RequestSignatureService $requestSignatureService,
63
                private CertificateEngineFactory $certificateEngineFactory,
64
                private IConfig $config,
65
                private IAppConfig $appConfig,
66
                private IMountProviderCollection $mountProviderCollection,
67
                private NewUserMailHelper $newUserMail,
68
                private IdentifyMethodService $identifyMethodService,
69
                private IdentifyMethodMapper $identifyMethodMapper,
70
                private ValidateHelper $validateHelper,
71
                private IURLGenerator $urlGenerator,
72
                private Pkcs12Handler $pkcs12Handler,
73
                private IGroupManager $groupManager,
74
                private IdDocsService $idDocsService,
75
                private SignerElementsService $signerElementsService,
76
                private UserElementMapper $userElementMapper,
77
                private FolderService $folderService,
78
                private IClientService $clientService,
79
                private ITimeFactory $timeFactory,
80
                private FileUploadHelper $uploadHelper,
81
        ) {
82
        }
49✔
83

84
        public function validateCreateToSign(array $data): void {
85
                if (!UUIDUtil::validateUUID($data['uuid'])) {
1✔
86
                        throw new LibresignException($this->l10n->t('Invalid UUID'), 1);
1✔
87
                }
88
                try {
89
                        $signRequest = $this->getSignRequestByUuid($data['uuid']);
×
90
                } catch (\Throwable) {
×
91
                        throw new LibresignException($this->l10n->t('UUID not found'), 1);
×
92
                }
93
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId());
×
94
                if (!array_key_exists('identify', $data['user'])) {
×
95
                        throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
×
96
                }
97
                foreach ($data['user']['identify'] as $method => $value) {
×
98
                        if (!array_key_exists($method, $identifyMethods)) {
×
99
                                throw new LibresignException($this->l10n->t('Invalid identification method'), 1);
×
100
                        }
101
                        foreach ($identifyMethods[$method] as $identifyMethod) {
×
102
                                $identifyMethod->validateToCreateAccount($value);
×
103
                        }
104
                }
105
                if (empty($data['password'])) {
×
106
                        throw new LibresignException($this->l10n->t('Password is mandatory'), 1);
×
107
                }
108
                $file = $this->getFileByUuid($data['uuid']);
×
109
                if (empty($file['fileToSign'])) {
×
110
                        throw new LibresignException($this->l10n->t('File not found'));
×
111
                }
112
        }
113

114
        public function getFileByUuid(string $uuid): array {
115
                $signRequest = $this->getSignRequestByUuid($uuid);
×
116
                if (!$this->fileData instanceof \OCA\Libresign\Db\File) {
×
117
                        $this->fileData = $this->fileMapper->getById($signRequest->getFileId());
×
118

119
                        $nodeId = $this->fileData->getNodeId();
×
120

121
                        $fileToSign = $this->root->getUserFolder($this->fileData->getUserId())->getFirstNodeById($nodeId);
×
122
                        if ($fileToSign) {
×
123
                                $this->fileToSign = $fileToSign;
×
124
                        }
125
                }
126
                return [
×
127
                        'fileData' => $this->fileData,
×
128
                        'fileToSign' => $this->fileToSign
×
129
                ];
×
130
        }
131

132
        public function validateCertificateData(array $data): void {
133
                if (array_key_exists('email', $data['user']) && empty($data['user']['email'])) {
7✔
134
                        throw new LibresignException($this->l10n->t('You must have an email. You can define the email in your profile.'), 1);
2✔
135
                }
136
                if (!empty($data['user']['email']) && !filter_var($data['user']['email'], FILTER_VALIDATE_EMAIL)) {
5✔
137
                        throw new LibresignException($this->l10n->t('Invalid email'), 1);
2✔
138
                }
139
                if (empty($data['signPassword'])) {
3✔
140
                        throw new LibresignException($this->l10n->t('Password to sign is mandatory'), 1);
1✔
141
                }
142
        }
143

144
        /**
145
         * Get signRequest by Uuid
146
         */
147
        public function getSignRequestByUuid(string $uuid): SignRequest {
148
                if (!$this->signRequest instanceof SignRequest) {
2✔
149
                        $this->signRequest = $this->signRequestMapper->getByUuid($uuid);
2✔
150
                }
151
                return $this->signRequest;
2✔
152
        }
153

154
        public function createToSign(string $uuid, string $email, string $password, ?string $signPassword): void {
155
                $signRequest = $this->getSignRequestByUuid($uuid);
2✔
156

157
                $newUser = $this->userManager->createUser($email, $password);
2✔
158
                $newUser->setDisplayName($signRequest->getDisplayName());
2✔
159
                $newUser->setSystemEMailAddress($email);
2✔
160

161
                $this->updateIdentifyMethodToAccount($signRequest->getId(), $email, $newUser->getUID());
2✔
162

163
                if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
2✔
164
                        try {
165
                                $emailTemplate = $this->newUserMail->generateTemplate($newUser, false);
2✔
166
                                $this->newUserMail->sendMail($newUser, $emailTemplate);
2✔
167
                        } catch (\Exception) {
2✔
168
                                throw new LibresignException('Unable to send the invitation', 1);
2✔
169
                        }
170
                }
171

172
                if ($signPassword) {
×
173
                        $certificate = $this->pkcs12Handler->generateCertificate(
×
174
                                [
×
175
                                        'host' => $newUser->getPrimaryEMailAddress(),
×
176
                                        'uid' => 'account:' . $newUser->getUID(),
×
177
                                        'name' => $newUser->getDisplayName()
×
178
                                ],
×
179
                                $signPassword,
×
180
                                $newUser->getDisplayName()
×
181
                        );
×
182
                        $this->pkcs12Handler->savePfx($newUser->getPrimaryEMailAddress(), $certificate);
×
183
                }
184
        }
185

186
        public function getCertificateEngineName(): string {
187
                return $this->certificateEngineFactory->getEngine()->getName();
×
188
        }
189

190
        /**
191
         * @return array<string, mixed>
192
         */
193
        public function getConfig(?IUser $user = null): array {
194
                $info['identificationDocumentsFlow'] = $this->appConfig->getValueBool(Application::APP_ID, 'identification_documents', false);
×
195
                $info['hasSignatureFile'] = $this->hasSignatureFile($user);
×
196
                $info['phoneNumber'] = $this->getPhoneNumber($user);
×
197
                $info['isApprover'] = $this->validateHelper->userCanApproveValidationDocuments($user, false);
×
198
                $info['id_docs_filters'] = $this->getUserConfigIdDocsFilters($user);
×
199
                $info['id_docs_sort'] = $this->getUserConfigIdDocsSort($user);
×
200
                $info['crl_filters'] = $this->getUserConfigCrlFilters($user);
×
201
                $info['crl_sort'] = $this->getUserConfigCrlSort($user);
×
202
                $info['grid_view'] = $this->getUserConfigByKey('grid_view', $user) === '1';
×
203
                $info['signer_identify_tab'] = $this->getUserConfigByKey('signer_identify_tab', $user);
×
NEW
204
                $info['sorting_mode'] = $this->getUserConfigByKey('sorting_mode', $user) ?: 'name';
×
NEW
205
                $info['sorting_direction'] = $this->getUserConfigByKey('sorting_direction', $user) ?: 'asc';
×
206

207
                return array_filter($info);
×
208
        }
209

210
        public function getConfigFilters(?IUser $user = null): array {
211
                $info['filter_modified'] = $this->getUserConfigByKey('filter_modified', $user);
×
212
                $info['filter_status'] = $this->getUserConfigByKey('filter_status', $user);
×
213

214
                return $info;
×
215
        }
216

217
        public function getConfigSorting(?IUser $user = null): array {
218
                $info['sorting_mode'] = $this->getUserConfigByKey('sorting_mode', $user) ?: 'name';
×
219
                $info['sorting_direction'] = $this->getUserConfigByKey('sorting_direction', $user) ?: 'asc';
×
220

221
                return $info;
×
222
        }
223

224
        private function updateIdentifyMethodToAccount(int $signRequestId, string $email, string $uid): void {
225
                $identifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequestId);
2✔
226
                foreach ($identifyMethods as $name => $methods) {
2✔
227
                        if ($name === IdentifyMethodService::IDENTIFY_EMAIL) {
×
228
                                foreach ($methods as $identifyMethod) {
×
229
                                        $entity = $identifyMethod->getEntity();
×
230
                                        if ($entity->getIdentifierValue() === $email) {
×
231
                                                $entity->setIdentifierKey(IdentifyMethodService::IDENTIFY_ACCOUNT);
×
232
                                                $entity->setIdentifierValue($uid);
×
233
                                                $this->identifyMethodMapper->update($entity);
×
234
                                        }
235
                                }
236
                        }
237
                }
238
        }
239

240
        private function getPhoneNumber(?IUser $user): string {
241
                if (!$user) {
×
242
                        return '';
×
243
                }
244
                $userAccount = $this->accountManager->getAccount($user);
×
245
                return $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
×
246
        }
247

248
        public function hasSignatureFile(?IUser $user = null): bool {
249
                if (!$user) {
1✔
250
                        return false;
×
251
                }
252
                try {
253
                        $this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID());
1✔
254
                        return true;
×
255
                } catch (LibresignException) {
1✔
256
                        return false;
1✔
257
                }
258
        }
259

260
        private function getUserConfigByKey(string $key, ?IUser $user = null): string {
261
                if (!$user) {
×
262
                        return '';
×
263
                }
264

265
                return $this->config->getUserValue($user->getUID(), Application::APP_ID, $key);
×
266
        }
267

268
        private function getUserConfigIdDocsFilters(?IUser $user = null): array {
269
                if (!$user) {
×
270
                        return [];
×
271
                }
272

273
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'id_docs_filters', '');
×
274
                if (empty($value)) {
×
275
                        return [];
×
276
                }
277

278
                $decoded = json_decode($value, true);
×
279
                return is_array($decoded) ? $decoded : [];
×
280
        }
281

282
        private function getUserConfigCrlFilters(?IUser $user = null): array {
283
                if (!$user || !$this->groupManager->isAdmin($user->getUID())) {
×
284
                        return [];
×
285
                }
286

287
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_filters', '');
×
288
                if (empty($value)) {
×
289
                        return [];
×
290
                }
291

292
                $decoded = json_decode($value, true);
×
293
                return is_array($decoded) ? $decoded : [];
×
294
        }
295

296
        private function getUserConfigCrlSort(?IUser $user): array {
297
                if (!$user || !$this->groupManager->isAdmin($user->getUID())) {
×
298
                        return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
299
                }
300

301
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'crl_sort', '');
×
302
                if (empty($value)) {
×
303
                        return ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
304
                }
305

306
                $decoded = json_decode($value, true);
×
307
                return is_array($decoded) ? $decoded : ['sortBy' => 'revoked_at', 'sortOrder' => 'DESC'];
×
308
        }
309

310
        private function getUserConfigIdDocsSort(?IUser $user): array {
311
                if (!$user || !$this->validateHelper->userCanApproveValidationDocuments($user, false)) {
×
312
                        return ['sortBy' => null, 'sortOrder' => null];
×
313
                }
314

315
                $value = $this->config->getUserValue($user->getUID(), Application::APP_ID, 'id_docs_sort', '');
×
316
                if (empty($value)) {
×
317
                        return ['sortBy' => null, 'sortOrder' => null];
×
318
                }
319

320
                $decoded = json_decode($value, true);
×
321
                return is_array($decoded) ? $decoded : ['sortBy' => null, 'sortOrder' => null];
×
322
        }
323

324
        /**
325
         * Get PDF node by UUID
326
         *
327
         * @psalm-suppress MixedReturnStatement
328
         * @throws Throwable
329
         * @return \OCP\Files\File
330
         */
331
        public function getPdfByUuid(string $uuid): File {
332
                $fileData = $this->fileMapper->getByUuid($uuid);
4✔
333

334
                if (in_array($fileData->getStatus(), [FileStatus::PARTIAL_SIGNED->value, FileStatus::SIGNED->value])) {
4✔
335
                        $nodeId = $fileData->getSignedNodeId();
3✔
336
                } else {
337
                        $nodeId = $fileData->getNodeId();
1✔
338
                }
339
                if ($nodeId === null) {
4✔
340
                        throw new DoesNotExistException('Not found');
×
341
                }
342
                $file = $this->root->getUserFolder($fileData->getUserId())->getFirstNodeById($nodeId);
4✔
343
                if (!$file instanceof File) {
4✔
344
                        throw new DoesNotExistException('Not found');
×
345
                }
346
                return $file;
4✔
347
        }
348

349
        public function getFileByNodeId(int $nodeId): File {
350
                try {
351
                        return $this->folderService->getFileByNodeId($nodeId);
×
352
                } catch (NotFoundException) {
×
353
                        throw new DoesNotExistException('Not found');
×
354
                }
355
        }
356

357
        public function canRequestSign(?IUser $user = null): bool {
358
                if (!$user) {
9✔
359
                        return false;
2✔
360
                }
361
                $authorized = $this->appConfig->getValueArray(Application::APP_ID, 'groups_request_sign', ['admin']);
7✔
362
                if (empty($authorized)) {
7✔
363
                        return false;
2✔
364
                }
365
                $userGroups = $this->groupManager->getUserGroupIds($user);
5✔
366
                if (!array_intersect($userGroups, $authorized)) {
5✔
367
                        return false;
3✔
368
                }
369
                return true;
2✔
370
        }
371

372
        public function getSettings(?IUser $user = null): array {
373
                $return['canRequestSign'] = $this->canRequestSign($user);
1✔
374
                $return['hasSignatureFile'] = $this->hasSignatureFile($user);
1✔
375
                return $return;
1✔
376
        }
377

378
        public function addFilesToAccount(array $files, IUser $user): void {
379
                $this->idDocsService->addIdDocs($files, $user);
×
380
        }
381

382
        public function deleteFileFromAccount(int $nodeId, IUser $user): void {
383
                $this->idDocsService->deleteIdDoc($nodeId, $user);
×
384
        }
385

386
        public function saveVisibleElements(array $elements, string $sessionId, ?IUser $user): void {
387
                foreach ($elements as $element) {
×
388
                        $this->saveVisibleElement($element, $sessionId, $user);
×
389
                }
390
        }
391

392
        public function saveVisibleElement(array $data, string $sessionId, ?IUser $user): void {
393
                if (isset($data['elementId'])) {
×
394
                        $this->updateFileOfVisibleElement($data);
×
395
                        $this->updateDataOfVisibleElement($data);
×
396
                } elseif ($user instanceof IUser) {
×
397
                        $file = $this->saveFileOfVisibleElementUsingUser($data, $user);
×
398
                        $this->insertVisibleElement($data, $user, $file);
×
399
                } else {
400
                        $file = $this->saveFileOfVisibleElementUsingSession($data, $sessionId);
×
401
                }
402
        }
403

404
        private function updateFileOfVisibleElement(array $data): void {
405
                if (!isset($data['file'])) {
×
406
                        return;
×
407
                }
408
                $userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
×
409
                $file = $this->folderService->getFileByNodeId($userElement->getNodeId());
×
410
                $file->putContent($this->getFileRaw($data));
×
411
        }
412

413
        private function updateDataOfVisibleElement(array $data): void {
414
                if (!isset($data['starred'])) {
×
415
                        return;
×
416
                }
417
                $userElement = $this->userElementMapper->findOne(['id' => $data['elementId']]);
×
418
                $userElement->setStarred($data['starred'] ? 1 : 0);
×
419
                $this->userElementMapper->update($userElement);
×
420
        }
421

422
        private function saveFileOfVisibleElementUsingUser(array $data, IUser $user): File {
423
                $rootSignatureFolder = $this->folderService->getFolder();
×
424
                $folderName = $this->folderService->getFolderName($data, $user);
×
425
                $folderToFile = $rootSignatureFolder->newFolder($folderName);
×
426
                return $folderToFile->newFile(UUIDUtil::getUUID() . '.png', $this->getFileRaw($data));
×
427
        }
428

429
        private function saveFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
430
                if (!empty($data['nodeId'])) {
×
431
                        return $this->updateFileOfVisibleElementUsingSession($data, $sessionId);
×
432
                }
433
                return $this->createFileOfVisibleElementUsingSession($data, $sessionId);
×
434
        }
435

436
        private function updateFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
437
                $fileList = $this->signerElementsService->getElementsFromSession();
×
438
                $element = array_filter($fileList, fn (File $element) => $element->getId() === $data['nodeId']);
×
439
                $element = current($element);
×
440
                if (!$element instanceof File) {
×
441
                        throw new \Exception($this->l10n->t('File not found'));
×
442
                }
443
                $element->putContent($this->getFileRaw($data));
×
444
                return $element;
×
445
        }
446

447
        private function createFileOfVisibleElementUsingSession(array $data, string $sessionId): File {
448
                $rootSignatureFolder = $this->folderService->getFolder();
×
449
                $folderName = $sessionId;
×
450
                $folderToFile = $rootSignatureFolder->newFolder($folderName);
×
451
                $filename = implode(
×
452
                        '_',
×
453
                        [
×
454
                                $data['type'],
×
455
                                $this->timeFactory->getDateTime()->getTimestamp(),
×
456
                        ]
×
457
                ) . '.png';
×
458
                return $folderToFile->newFile($filename, $this->getFileRaw($data));
×
459
        }
460

461
        private function insertVisibleElement(array $data, IUser $user, File $file): void {
462
                $userElement = new UserElement();
×
463
                $userElement->setType($data['type']);
×
464
                $userElement->setNodeId($file->getId());
×
465
                $userElement->setUserId($user->getUID());
×
466
                $userElement->setStarred(isset($data['starred']) && $data['starred'] ? 1 : 0);
×
467
                $userElement->setCreatedAt($this->timeFactory->getDateTime());
×
468
                $this->userElementMapper->insert($userElement);
×
469
        }
470

471
        private function getFileRaw(array $data): string {
472
                if (!empty($data['file']['url'])) {
×
473
                        if (!filter_var($data['file']['url'], FILTER_VALIDATE_URL)) {
×
474
                                throw new \Exception($this->l10n->t('Invalid URL file'));
×
475
                        }
476
                        $response = $this->clientService->newClient()->get($data['file']['url']);
×
477
                        $contentType = $response->getHeader('Content-Type');
×
478
                        if ($contentType !== 'image/png') {
×
479
                                throw new \Exception($this->l10n->t('Visible element file must be png.'));
×
480
                        }
481
                        $content = (string)$response->getBody();
×
482
                        if (empty($content)) {
×
483
                                throw new \Exception($this->l10n->t('Empty file'));
×
484
                        }
485
                        $this->validateHelper->validateBase64($content, ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
×
486
                        return $content;
×
487
                }
488
                $this->validateHelper->validateBase64($data['file']['base64'], ValidateHelper::TYPE_VISIBLE_ELEMENT_USER);
×
489
                $withMime = explode(',', (string)$data['file']['base64']);
×
490
                if (count($withMime) === 2) {
×
491
                        $content = base64_decode($withMime[1]);
×
492
                } else {
493
                        $content = base64_decode((string)$data['file']['base64']);
×
494
                }
495
                if (!$content) {
×
496
                        return '';
×
497
                }
498
                return $content;
×
499
        }
500

501
        public function deleteSignatureElement(?IUser $user, string $sessionId, int $nodeId): void {
502
                if ($user instanceof IUser) {
8✔
503
                        $element = $this->userElementMapper->findOne([
2✔
504
                                'node_id' => $nodeId,
2✔
505
                                'user_id' => $user->getUID(),
2✔
506
                        ]);
2✔
507
                        $this->userElementMapper->delete($element);
2✔
508
                        try {
509
                                $file = $this->folderService->getFileByNodeId($element->getNodeId());
2✔
510
                                $file->delete();
1✔
511
                        } catch (NotFoundException) {
1✔
512
                        }
513
                        return;
2✔
514
                }
515

516
                $this->deleteSignatureElementFromSession($sessionId, $nodeId);
6✔
517
        }
518

519
        private function deleteSignatureElementFromSession(string $sessionId, int $nodeId): void {
520
                $rootSignatureFolder = $this->folderService->getFolder();
6✔
521
                try {
522
                        /** @var \OCP\Files\Folder $sessionFolder */
523
                        $sessionFolder = $rootSignatureFolder->get($sessionId);
6✔
524
                } catch (NotFoundException) {
1✔
525
                        throw new DoesNotExistException($this->l10n->t('Element not found'));
1✔
526
                }
527

528
                $element = $sessionFolder->getFirstNodeById($nodeId);
5✔
529
                if (!$element instanceof File) {
5✔
530
                        throw new DoesNotExistException($this->l10n->t('Element not found'));
2✔
531
                }
532
                $element->delete();
3✔
533

534
                // Clean up empty session folder
535
                if (count($sessionFolder->getDirectoryListing()) === 0) {
3✔
536
                        $sessionFolder->delete();
2✔
537
                }
538
        }
539

540
        /**
541
         * @throws LibresignException at savePfx
542
         * @throws InvalidArgumentException
543
         */
544
        public function uploadPfx(array $file, IUser $user): void {
545
                try {
546
                        $this->uploadHelper->validateUploadedFile($file);
×
547
                } catch (InvalidArgumentException) {
×
548
                        // TRANSLATORS Error when the uploaded certificate file is not valid
549
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
550
                }
551

552
                if ($file['size'] > 10 * 1024) {
×
553
                        // TRANSLATORS Error when the certificate file is bigger than normal
554
                        throw new InvalidArgumentException($this->l10n->t('File is too big'));
×
555
                }
556
                $content = file_get_contents($file['tmp_name']);
×
557
                $mimetype = $this->mimeTypeDetector->detectString($content);
×
558
                if ($mimetype !== 'application/octet-stream') {
×
559
                        // TRANSLATORS Error when the mimetype of uploaded file is not valid
560
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
561
                }
562
                $extension = strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION));
×
563
                if ($extension !== 'pfx') {
×
564
                        // TRANSLATORS Error when the certificate file is not a pfx file
565
                        throw new InvalidArgumentException($this->l10n->t('Invalid file provided. Need to be a .pfx file.'));
×
566
                }
567
                unlink($file['tmp_name']);
×
568
                $this->pkcs12Handler->savePfx($user->getUID(), $content);
×
569
        }
570

571
        public function deletePfx(IUser $user): void {
572
                $this->pkcs12Handler->deletePfx($user->getUID());
×
573
        }
574

575
        /**
576
         * @throws LibresignException when have not a certificate file
577
         */
578
        public function updatePfxPassword(IUser $user, string $current, string $new): void {
579
                try {
580
                        $pfx = $this->pkcs12Handler->updatePassword($user->getUID(), $current, $new);
×
581
                } catch (InvalidPasswordException) {
×
582
                        throw new LibresignException($this->l10n->t('Invalid user or password'));
×
583
                }
584
        }
585

586
        /**
587
         * @throws LibresignException when have not a certificate file
588
         */
589
        public function readPfxData(IUser $user, string $password): array {
590
                try {
591
                        return $this->pkcs12Handler
×
592
                                ->setCertificate($this->pkcs12Handler->getPfxOfCurrentSigner($user->getUID()))
×
593
                                ->setPassword($password)
×
594
                                ->readCertificate();
×
595
                } catch (InvalidPasswordException) {
×
596
                        throw new LibresignException($this->l10n->t('Invalid user or password'));
×
597
                }
598
        }
599
}
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