Passed
Push — devel-3.0 ( 543c48...5b8639 )
by Rubén
03:28
created

AccountService::updateBulk()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 1
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Services\Account;
26
27
use Defuse\Crypto\Exception\CryptoException;
28
use SP\Core\Crypt\Crypt;
29
use SP\Core\Exceptions\QueryException;
30
use SP\Core\Exceptions\SPException;
31
use SP\DataModel\AccountData;
32
use SP\DataModel\AccountHistoryData;
33
use SP\DataModel\AccountPassData;
34
use SP\DataModel\Dto\AccountDetailsResponse;
35
use SP\DataModel\Dto\AccountHistoryCreateDto;
36
use SP\DataModel\ItemPreset\AccountPermission;
37
use SP\DataModel\ItemPreset\AccountPrivate;
38
use SP\DataModel\ItemSearchData;
39
use SP\Repositories\Account\AccountRepository;
40
use SP\Repositories\Account\AccountToTagRepository;
41
use SP\Repositories\Account\AccountToUserGroupRepository;
42
use SP\Repositories\Account\AccountToUserRepository;
43
use SP\Repositories\NoSuchItemException;
44
use SP\Services\Config\ConfigService;
45
use SP\Services\ItemPreset\ItemPresetInterface;
46
use SP\Services\ItemPreset\ItemPresetService;
47
use SP\Services\Service;
48
use SP\Services\ServiceException;
49
use SP\Services\ServiceItemTrait;
50
use SP\Storage\Database\QueryResult;
51
52
/**
53
 * Class AccountService
54
 *
55
 * @package SP\Services\Account
56
 */
57
final class AccountService extends Service implements AccountServiceInterface
58
{
59
    use ServiceItemTrait;
60
61
    /**
62
     * @var AccountRepository
63
     */
64
    protected $accountRepository;
65
    /**
66
     * @var AccountToUserGroupRepository
67
     */
68
    protected $accountToUserGroupRepository;
69
    /**
70
     * @var AccountToUserRepository
71
     */
72
    protected $accountToUserRepository;
73
    /**
74
     * @var AccountToTagRepository
75
     */
76
    protected $accountToTagRepository;
77
    /**
78
     * @var ItemPresetService
79
     */
80
    protected $itemPresetService;
81
82
    /**
83
     * @param AccountDetailsResponse $accountDetailsResponse
84
     *
85
     * @return AccountService
86
     * @throws QueryException
87
     * @throws \SP\Core\Exceptions\ConstraintException
88
     */
89
    public function withUsersById(AccountDetailsResponse $accountDetailsResponse)
90
    {
91
        $accountDetailsResponse->setUsers($this->accountToUserRepository->getUsersByAccountId($accountDetailsResponse->getId())->getDataAsArray());
92
93
        return $this;
94
    }
95
96
    /**
97
     * @param AccountDetailsResponse $accountDetailsResponse
98
     *
99
     * @return AccountService
100
     * @throws QueryException
101
     * @throws \SP\Core\Exceptions\ConstraintException
102
     */
103
    public function withUserGroupsById(AccountDetailsResponse $accountDetailsResponse)
104
    {
105
        $accountDetailsResponse->setUserGroups($this->accountToUserGroupRepository->getUserGroupsByAccountId($accountDetailsResponse->getId())->getDataAsArray());
106
107
        return $this;
108
    }
109
110
    /**
111
     * @param AccountDetailsResponse $accountDetailsResponse
112
     *
113
     * @return AccountService
114
     * @throws QueryException
115
     * @throws \SP\Core\Exceptions\ConstraintException
116
     */
117
    public function withTagsById(AccountDetailsResponse $accountDetailsResponse)
118
    {
119
        $accountDetailsResponse->setTags($this->accountToTagRepository->getTagsByAccountId($accountDetailsResponse->getId())->getDataAsArray());
120
121
        return $this;
122
    }
123
124
    /**
125
     * @param $id
126
     *
127
     * @return bool
128
     * @throws QueryException
129
     * @throws \SP\Core\Exceptions\ConstraintException
130
     */
131
    public function incrementViewCounter($id)
132
    {
133
        return $this->accountRepository->incrementViewCounter($id);
134
    }
135
136
    /**
137
     * @param $id
138
     *
139
     * @return bool
140
     * @throws QueryException
141
     * @throws \SP\Core\Exceptions\ConstraintException
142
     */
143
    public function incrementDecryptCounter($id)
144
    {
145
        return $this->accountRepository->incrementDecryptCounter($id);
146
    }
147
148
    /**
149
     * @param $id
150
     *
151
     * @return \SP\DataModel\AccountPassData
152
     * @throws QueryException
153
     * @throws \SP\Core\Exceptions\ConstraintException
154
     * @throws NoSuchItemException
155
     */
156
    public function getPasswordForId($id)
157
    {
158
        $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter();
159
160
        $result = $this->accountRepository->getPasswordForId($id, $queryFilter);
161
162
        if ($result->getNumRows() === 0) {
163
            throw new NoSuchItemException(__u('Cuenta no encontrada'));
164
        }
165
166
        return $result->getData();
167
    }
168
169
    /**
170
     * @param AccountRequest $accountRequest
171
     *
172
     * @return int
173
     * @throws QueryException
174
     * @throws SPException
175
     * @throws \SP\Core\Exceptions\ConstraintException
176
     * @throws \SP\Core\Exceptions\NoSuchPropertyException
177
     */
178
    public function create(AccountRequest $accountRequest)
179
    {
180
        $accountRequest->changePermissions = AccountAclService::getShowPermission(
181
            $this->context->getUserData(),
182
            $this->context->getUserProfile());
183
        $accountRequest->userGroupId = $accountRequest->userGroupId ?: $this->context->getUserData()->getUserGroupId();
184
185
        if (empty($accountRequest->key)) {
186
            $pass = $this->getPasswordEncrypted($accountRequest->pass);
187
188
            $accountRequest->pass = $pass['pass'];
189
            $accountRequest->key = $pass['key'];
190
        }
191
192
        $this->setPresetPrivate($accountRequest);
193
194
        $accountRequest->id = $this->accountRepository->create($accountRequest);
195
196
        $this->addItems($accountRequest);
197
198
        $this->addPresetPermissions($accountRequest->id);
199
200
        return $accountRequest->id;
201
    }
202
203
    /**
204
     * Devolver los datos de la clave encriptados
205
     *
206
     * @param string $pass
207
     * @param string $masterPass Clave maestra a utilizar
208
     *
209
     * @return array
210
     * @throws ServiceException
211
     */
212
    public function getPasswordEncrypted($pass, $masterPass = null)
213
    {
214
        try {
215
            if ($masterPass === null) {
216
                $masterPass = $this->getMasterKeyFromContext();
217
            }
218
219
            if (empty($masterPass)) {
220
                throw new ServiceException(__u('Clave maestra no establecida'));
221
            }
222
223
            $out['key'] = Crypt::makeSecuredKey($masterPass);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$out was never initialized. Although not strictly required by PHP, it is generally a good practice to add $out = array(); before regardless.
Loading history...
224
            $out['pass'] = Crypt::encrypt($pass, $out['key'], $masterPass);
225
226
            if (strlen($out['pass']) > 1000 || strlen($out['key']) > 1000) {
227
                throw new ServiceException(__u('Error interno'));
228
            }
229
230
            return $out;
231
        } catch (CryptoException $e) {
232
            throw new ServiceException(__u('Error interno'));
233
        }
234
    }
235
236
    /**
237
     * @param AccountRequest $accountRequest
238
     *
239
     * @throws QueryException
240
     * @throws \SP\Core\Exceptions\ConstraintException
241
     * @throws \SP\Core\Exceptions\NoSuchPropertyException
242
     * @throws NoSuchItemException
243
     */
244
    private function setPresetPrivate(AccountRequest $accountRequest)
245
    {
246
        $userData = $this->context->getUserData();
247
        $itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE);
248
249
        if ($itemPreset !== null
250
            && $itemPreset->getFixed()
251
        ) {
252
            $accountPrivate = $itemPreset->hydrate(AccountPrivate::class);
253
254
            $userId = $accountRequest->userId;
255
256
            if ($userId === null && $accountRequest->id > 0) {
0 ignored issues
show
introduced by
The condition $userId is always false. If $userId can have other possible types, add them to lib/SP/Services/Account/AccountRequest.php:63
Loading history...
257
                $userId = $this->getById($accountRequest->id)->getAccountVData()->getUserId();
258
            }
259
260
            if ($userData->getId() === $userId) {
261
                $accountRequest->isPrivate = (int)$accountPrivate->isPrivateUser();
262
            }
263
264
            if ($userData->getUserGroupId() === $accountRequest->userGroupId) {
265
                $accountRequest->isPrivateGroup = (int)$accountPrivate->isPrivateGroup();
266
            }
267
        }
268
    }
269
270
    /**
271
     * @param int $id
272
     *
273
     * @return AccountDetailsResponse
274
     * @throws QueryException
275
     * @throws \SP\Repositories\NoSuchItemException
276
     * @throws \SP\Core\Exceptions\ConstraintException
277
     */
278
    public function getById($id)
279
    {
280
        $result = $this->accountRepository->getById($id);
281
282
        if ($result->getNumRows() === 0) {
283
            throw new NoSuchItemException(__u('La cuenta no existe'));
284
        }
285
286
        return new AccountDetailsResponse($id, $result->getData());
287
    }
288
289
    /**
290
     * Adds external items to the account
291
     *
292
     * @param AccountRequest $accountRequest
293
     */
294
    private function addItems(AccountRequest $accountRequest)
295
    {
296
        try {
297
298
            if ($accountRequest->changePermissions) {
299
                if (is_array($accountRequest->userGroupsView)
300
                    && !empty($accountRequest->userGroupsView)
301
                ) {
302
                    $this->accountToUserGroupRepository->addByType($accountRequest, false);
303
                }
304
305
                if (is_array($accountRequest->userGroupsEdit)
306
                    && !empty($accountRequest->userGroupsEdit)
307
                ) {
308
                    $this->accountToUserGroupRepository->addByType($accountRequest, true);
309
                }
310
311
                if (is_array($accountRequest->usersView)
312
                    && !empty($accountRequest->usersView)
313
                ) {
314
                    $this->accountToUserRepository->addByType($accountRequest, false);
315
                }
316
317
                if (is_array($accountRequest->usersEdit)
318
                    && !empty($accountRequest->usersEdit)
319
                ) {
320
                    $this->accountToUserRepository->addByType($accountRequest, true);
321
                }
322
            }
323
324
            if (is_array($accountRequest->tags)
325
                && !empty($accountRequest->tags)
326
            ) {
327
                $this->accountToTagRepository->add($accountRequest);
328
            }
329
        } catch (SPException $e) {
330
            logger($e->getMessage());
331
        }
332
    }
333
334
    /**
335
     * @param int $accountId
336
     *
337
     * @throws QueryException
338
     * @throws \SP\Core\Exceptions\ConstraintException
339
     * @throws \SP\Core\Exceptions\NoSuchPropertyException
340
     */
341
    private function addPresetPermissions(int $accountId)
342
    {
343
        $itemPresetData = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION);
344
345
        if ($itemPresetData !== null
346
            && $itemPresetData->getFixed()
347
        ) {
348
            $userData = $this->context->getUserData();
349
            $accountPermission = $itemPresetData->hydrate(AccountPermission::class);
350
351
            $accountRequest = new AccountRequest();
352
            $accountRequest->id = $accountId;
353
            $accountRequest->usersView = array_diff($accountPermission->getUsersView(), [$userData->getId()]);
354
            $accountRequest->usersEdit = array_diff($accountPermission->getUsersEdit(), [$userData->getId()]);
355
            $accountRequest->userGroupsView = array_diff($accountPermission->getUserGroupsView(), [$userData->getUserGroupId()]);
356
            $accountRequest->userGroupsEdit = array_diff($accountPermission->getUserGroupsEdit(), [$userData->getUserGroupId()]);
357
358
            if (!empty($accountRequest->usersView)) {
359
                $this->accountToUserRepository->addByType($accountRequest, false);
360
            }
361
362
            if (!empty($accountRequest->usersEdit)) {
363
                $this->accountToUserRepository->addByType($accountRequest, true);
364
            }
365
366
            if (!empty($accountRequest->userGroupsView)) {
367
                $this->accountToUserGroupRepository->addByType($accountRequest, false);
368
            }
369
370
            if (!empty($accountRequest->userGroupsEdit)) {
371
                $this->accountToUserGroupRepository->addByType($accountRequest, true);
372
            }
373
        }
374
    }
375
376
    /**
377
     * @param AccountHistoryData $data
378
     *
379
     * @return int
380
     * @throws QueryException
381
     * @throws \SP\Core\Exceptions\ConstraintException
382
     */
383
    public function createFromHistory(AccountHistoryData $data)
384
    {
385
        $accountRequest = new AccountRequest();
386
        $accountRequest->name = $data->getName();
387
        $accountRequest->categoryId = $data->getCategoryId();
388
        $accountRequest->clientId = $data->getClientId();
389
        $accountRequest->url = $data->getUrl();
390
        $accountRequest->login = $data->getLogin();
391
        $accountRequest->pass = $data->getPass();
392
        $accountRequest->key = $data->getKey();
393
        $accountRequest->notes = $data->getNotes();
394
        $accountRequest->userId = $data->getUserId();
395
        $accountRequest->userGroupId = $data->getUserGroupId();
396
        $accountRequest->passDateChange = $data->getPassDateChange();
397
        $accountRequest->parentId = $data->getParentId();
398
        $accountRequest->isPrivate = $data->getIsPrivate();
399
        $accountRequest->isPrivateGroup = $data->getIsPrivateGroup();
400
401
        return $this->accountRepository->create($accountRequest);
402
    }
403
404
    /**
405
     * Updates external items for the account
406
     *
407
     * @param AccountRequest $accountRequest
408
     *
409
     * @throws \Exception
410
     */
411
    public function update(AccountRequest $accountRequest)
412
    {
413
        $this->transactionAware(function () use ($accountRequest) {
414
            $userData = $this->context->getUserData();
415
416
            $accountRequest->changePermissions = AccountAclService::getShowPermission(
417
                $userData,
418
                $this->context->getUserProfile());
419
420
            $accountRequest->changeOwner = $accountRequest->userId > 0
421
                && ($userData->getIsAdminApp() || $userData->getIsAdminAcc());
422
423
            $accountRequest->changeUserGroup = $accountRequest->userGroupId > 0
424
                && $accountRequest->changePermissions;
425
426
            $this->addHistory($accountRequest->id);
427
428
            $this->setPresetPrivate($accountRequest);
429
430
            $this->accountRepository->update($accountRequest);
431
432
            $this->updateItems($accountRequest);
433
434
            $this->addPresetPermissions($accountRequest->id);
435
        });
436
    }
437
438
    /**
439
     * @param int  $accountId
440
     * @param bool $isDelete
441
     *
442
     * @return bool
443
     * @throws NoSuchItemException
444
     * @throws QueryException
445
     * @throws ServiceException
446
     * @throws \SP\Core\Exceptions\ConstraintException
447
     */
448
    private function addHistory($accountId, $isDelete = false)
449
    {
450
        $accountHistoryRepository = $this->dic->get(AccountHistoryService::class);
451
        $configService = $this->dic->get(ConfigService::class);
452
453
        return $accountHistoryRepository->create(
454
            new AccountHistoryCreateDto(
455
                $accountId,
456
                !$isDelete,
457
                $isDelete,
458
                $configService->getByParam('masterPwd'))
459
        );
460
    }
461
462
    /**
463
     * Updates external items for the account
464
     *
465
     * @param AccountRequest $accountRequest
466
     *
467
     * @throws QueryException
468
     * @throws \SP\Core\Exceptions\ConstraintException
469
     */
470
    private function updateItems(AccountRequest $accountRequest)
471
    {
472
        if ($accountRequest->changePermissions) {
473
            if ($accountRequest->userGroupsView !== null) {
474
                if (count($accountRequest->userGroupsView) > 0) {
475
                    $this->accountToUserGroupRepository->updateByType($accountRequest, false);
476
                } else {
477
                    $this->accountToUserGroupRepository->deleteTypeByAccountId($accountRequest->id, false);
478
                }
479
            }
480
481
            if ($accountRequest->userGroupsEdit !== null) {
482
                if (count($accountRequest->userGroupsEdit) > 0) {
483
                    $this->accountToUserGroupRepository->updateByType($accountRequest, true);
484
                } else {
485
                    $this->accountToUserGroupRepository->deleteTypeByAccountId($accountRequest->id, true);
486
                }
487
            }
488
489
            if ($accountRequest->usersView !== null) {
490
                if (count($accountRequest->usersView) > 0) {
491
                    $this->accountToUserRepository->updateByType($accountRequest, false);
492
                } else {
493
                    $this->accountToUserRepository->deleteTypeByAccountId($accountRequest->id, false);
494
                }
495
            }
496
497
            if ($accountRequest->usersEdit !== null) {
498
                if (count($accountRequest->usersEdit) > 0) {
499
                    $this->accountToUserRepository->updateByType($accountRequest, true);
500
                } else {
501
                    $this->accountToUserRepository->deleteTypeByAccountId($accountRequest->id, true);
502
                }
503
            }
504
        }
505
506
        if ($accountRequest->tags !== null) {
507
            if (count($accountRequest->tags) > 0) {
508
                $this->accountToTagRepository->update($accountRequest);
509
            } else {
510
                $this->accountToTagRepository->deleteByAccountId($accountRequest->id);
511
            }
512
        }
513
    }
514
515
    /**
516
     * Update accounts in bulk mode
517
     *
518
     * @param AccountBulkRequest $request
519
     *
520
     * @throws ServiceException
521
     */
522
    public function updateBulk(AccountBulkRequest $request)
523
    {
524
        $this->transactionAware(function () use ($request) {
525
            foreach ($request->getItemsId() as $itemId) {
526
                $accountRequest = $request->getAccountRequestForId($itemId);
527
528
                $this->addHistory($accountRequest->id);
529
530
                $this->accountRepository->updateBulk($accountRequest);
531
532
                $this->updateItems($accountRequest);
533
            }
534
        });
535
    }
536
537
    /**
538
     * @param AccountRequest $accountRequest
539
     *
540
     * @throws \Exception
541
     */
542
    public function editPassword(AccountRequest $accountRequest)
543
    {
544
        $this->transactionAware(function () use ($accountRequest) {
545
            $this->addHistory($accountRequest->id);
546
547
            $pass = $this->getPasswordEncrypted($accountRequest->pass);
548
549
            $accountRequest->pass = $pass['pass'];
550
            $accountRequest->key = $pass['key'];
551
552
            $this->accountRepository->editPassword($accountRequest);
553
        });
554
    }
555
556
    /**
557
     * Updates an already encrypted password data from a master password changing action
558
     *
559
     * @param AccountPasswordRequest $accountRequest
560
     *
561
     * @return bool
562
     * @throws \SP\Core\Exceptions\ConstraintException
563
     * @throws QueryException
564
     */
565
    public function updatePasswordMasterPass(AccountPasswordRequest $accountRequest)
566
    {
567
        return $this->accountRepository->updatePassword($accountRequest);
568
    }
569
570
    /**
571
     * @param $historyId
572
     * @param $accountId
573
     *
574
     * @throws \Exception
575
     */
576
    public function editRestore($historyId, $accountId)
577
    {
578
        $this->transactionAware(function () use ($historyId, $accountId) {
579
            $this->addHistory($accountId);
580
581
            if (!$this->accountRepository->editRestore($historyId, $this->context->getUserData()->getId())) {
582
                throw new ServiceException(__u('Error al restaurar cuenta'));
583
            }
584
        });
585
    }
586
587
    /**
588
     * @param $id
589
     *
590
     * @return AccountService
591
     * @throws ServiceException
592
     */
593
    public function delete($id)
594
    {
595
        $this->transactionAware(function () use ($id) {
596
            $this->addHistory($id, 1);
597
598
            if ($this->accountRepository->delete($id) === 0) {
599
                throw new NoSuchItemException(__u('Cuenta no encontrada'));
600
            }
601
        });
602
603
        return $this;
604
    }
605
606
    /**
607
     * @param array $ids
608
     *
609
     * @return AccountService
610
     * @throws SPException
611
     * @throws ServiceException
612
     */
613
    public function deleteByIdBatch(array $ids)
614
    {
615
        if ($this->accountRepository->deleteByIdBatch($ids) === 0) {
616
            throw new ServiceException(__u('Error al eliminar las cuentas'));
617
        }
618
619
        return $this;
620
    }
621
622
    /**
623
     * @param $accountId
624
     *
625
     * @return array
626
     * @throws QueryException
627
     * @throws \SP\Core\Exceptions\ConstraintException
628
     */
629
    public function getForUser($accountId = null)
630
    {
631
        $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter();
632
633
        if (null !== $accountId) {
634
            $queryFilter->addFilter('Account.id <> ? AND (Account.parentId = 0 OR Account.parentId IS NULL)', [$accountId]);
635
        }
636
637
        return $this->accountRepository->getForUser($queryFilter)->getDataAsArray();
638
    }
639
640
    /**
641
     * @param $accountId
642
     *
643
     * @return array
644
     * @throws QueryException
645
     * @throws \SP\Core\Exceptions\ConstraintException
646
     */
647
    public function getLinked($accountId)
648
    {
649
        $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter();
650
651
        $queryFilter->addFilter('Account.parentId = ?', [$accountId]);
652
653
        return $this->accountRepository->getLinked($queryFilter)->getDataAsArray();
654
    }
655
656
    /**
657
     * @param $id
658
     *
659
     * @return AccountPassData
660
     * @throws QueryException
661
     * @throws \SP\Core\Exceptions\ConstraintException
662
     * @throws NoSuchItemException
663
     */
664
    public function getPasswordHistoryForId($id)
665
    {
666
        $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilterHistory();
667
        $queryFilter->addFilter('AccountHistory.id = ?', [$id]);
668
669
        $result = $this->accountRepository->getPasswordHistoryForId($queryFilter);
670
671
        if ($result->getNumRows() === 0) {
672
            throw new NoSuchItemException(__u('La cuenta no existe'));
673
        }
674
675
        return $result->getData();
676
    }
677
678
    /**
679
     * @return AccountData[]
680
     * @throws QueryException
681
     * @throws \SP\Core\Exceptions\ConstraintException
682
     */
683
    public function getAllBasic()
684
    {
685
        return $this->accountRepository->getAll()->getDataAsArray();
686
    }
687
688
    /**
689
     * @param ItemSearchData $itemSearchData
690
     *
691
     * @return QueryResult
692
     * @throws QueryException
693
     * @throws \SP\Core\Exceptions\ConstraintException
694
     */
695
    public function search(ItemSearchData $itemSearchData)
696
    {
697
        return $this->accountRepository->search($itemSearchData);
698
    }
699
700
    /**
701
     * Devolver el número total de cuentas
702
     *
703
     * @return \stdClass
704
     * @throws QueryException
705
     * @throws \SP\Core\Exceptions\ConstraintException
706
     */
707
    public function getTotalNumAccounts()
708
    {
709
        return $this->accountRepository->getTotalNumAccounts()->num;
710
    }
711
712
    /**
713
     * Obtener los datos de una cuenta.
714
     *
715
     * @param $id
716
     *
717
     * @return \SP\DataModel\AccountExtData
718
     * @throws QueryException
719
     * @throws \SP\Repositories\NoSuchItemException
720
     * @throws \SP\Core\Exceptions\ConstraintException
721
     */
722
    public function getDataForLink($id)
723
    {
724
        $result = $this->accountRepository->getDataForLink($id);
725
726
        if ($result->getNumRows() === 0) {
727
            throw new NoSuchItemException(__u('La cuenta no existe'));
728
        }
729
730
        return $result->getData();
731
    }
732
733
    /**
734
     * Obtener los datos relativos a la clave de todas las cuentas.
735
     *
736
     * @return array Con los datos de la clave
737
     * @throws QueryException
738
     * @throws \SP\Core\Exceptions\ConstraintException
739
     */
740
    public function getAccountsPassData()
741
    {
742
        return $this->accountRepository->getAccountsPassData();
743
    }
744
745
    /**
746
     * Obtener las cuentas de una búsqueda.
747
     *
748
     * @param AccountSearchFilter $accountSearchFilter
749
     *
750
     * @return QueryResult
751
     * @throws QueryException
752
     * @throws SPException
753
     * @throws \SP\Core\Exceptions\ConstraintException
754
     */
755
    public function getByFilter(AccountSearchFilter $accountSearchFilter)
756
    {
757
        $accountFilterUser = $this->dic->get(AccountFilterUser::class);
758
759
        return $this->accountRepository->getByFilter(
760
            $accountSearchFilter,
761
            $accountFilterUser->getFilter($accountSearchFilter->getGlobalSearch())
762
        );
763
    }
764
765
    /**
766
     * @throws \Psr\Container\ContainerExceptionInterface
767
     * @throws \Psr\Container\NotFoundExceptionInterface
768
     */
769
    protected function initialize()
770
    {
771
        $this->accountRepository = $this->dic->get(AccountRepository::class);
772
        $this->accountToUserRepository = $this->dic->get(AccountToUserRepository::class);
773
        $this->accountToUserGroupRepository = $this->dic->get(AccountToUserGroupRepository::class);
774
        $this->accountToTagRepository = $this->dic->get(AccountToTagRepository::class);
775
        $this->itemPresetService = $this->dic->get(ItemPresetService::class);
776
    }
777
}