From 94f9929be083045e42a44955d325c7853b40d8e1 Mon Sep 17 00:00:00 2001 From: nuxsmin Date: Mon, 26 Feb 2018 02:29:54 +0100 Subject: [PATCH] * [ADD] Notifications module * [ADD] Delete multiple items at once * [FIX] Some bugfixes * [MOD] Removed deprecated code --- app/config/actions.xml | 48 +- .../web/Controllers/AccountController.php | 23 +- .../web/Controllers/AccountFileController.php | 27 +- .../web/Controllers/ApiTokenController.php | 34 +- .../web/Controllers/CategoryController.php | 34 +- .../web/Controllers/ClientController.php | 34 +- .../Controllers/ConfigManagerController.php | 2 +- .../web/Controllers/ControllerBase.php | 2 +- .../web/Controllers/CustomFieldController.php | 19 +- .../Helpers/Account/AccountHelper.php | 7 +- .../Helpers/Account/AccountPasswordHelper.php | 6 +- .../Controllers/Helpers/ItemsGridHelper.php | 127 ++++- .../web/Controllers/Helpers/LayoutHelper.php | 3 +- .../web/Controllers/ItemsController.php | 33 +- .../web/Controllers/LoginController.php | 23 +- .../Controllers/NotificationController.php | 366 +++++++++++++ .../web/Controllers/PublicLinkController.php | 29 +- app/modules/web/Controllers/TagController.php | 21 +- .../web/Controllers/Traits/ItemTrait.php | 16 +- .../web/Controllers/UserController.php | 28 +- .../web/Controllers/UserGroupController.php | 48 +- .../web/Controllers/UserProfileController.php | 33 +- .../views/_partials/fixed-header.inc | 69 ++- .../material-blue/views/eventlog/eventlog.inc | 151 ------ .../views/grid/datagrid-grid.inc | 11 +- .../views/grid/datagrid-table-simple.inc | 6 +- .../views/grid/datagrid-table.inc | 6 +- .../views/itemshow/userprofile.inc | 67 +-- .../views/noticeshow/notices.inc | 144 ----- .../views/notification/index.inc | 3 + .../views/notification/notification.inc | 126 +++++ lib/SP/Bootstrap.php | 230 ++------ lib/SP/Controller/ItemActionController.php | 28 +- lib/SP/Controller/NoticeShowController.php | 12 +- lib/SP/Controller/NoticesController.php | 2 +- lib/SP/Controller/NoticesSearchController.php | 10 +- lib/SP/Core/Acl/Acl.php | 6 +- lib/SP/Core/Acl/Actions.php | 2 +- lib/SP/Core/Acl/ActionsInterface.php | 15 +- lib/SP/Core/Crypt/Session.php | 18 +- lib/SP/Core/Crypt/Vault.php | 15 +- lib/SP/Core/Messages/MessageBase.php | 22 +- lib/SP/Core/Session/Session.php | 61 ++- lib/SP/Core/SessionUtil.php | 36 +- .../{NoticeData.php => NotificationData.php} | 6 +- lib/SP/DataModel/UserProfileData.php | 2 +- .../{NoticeForm.php => NotificationForm.php} | 52 +- lib/SP/Forms/UserProfileForm.php | 78 +-- lib/SP/Mgmt/Notices/Notice.php | 36 +- lib/SP/Mgmt/Notices/NoticeBase.php | 4 +- lib/SP/Mvc/Controller/ControllerTrait.php | 3 +- .../Controller/CrudControllerInterface.php | 2 +- lib/SP/Mvc/View/Template.php | 23 +- .../Account/AccountFavoriteRepository.php | 94 ++++ .../Account/AccountFileRepository.php | 34 +- .../Account/AccountRepository.php | 106 ++-- .../Account/AccountToTagRepository.php | 34 +- .../Account/AccountToUserGroupRepository.php | 54 +- .../Account/AccountToUserRepository.php | 37 +- .../AuthToken/AuthTokenRepository.php | 186 +++---- .../Category/CategoryRepository.php | 22 +- .../Repositories/Client/ClientRepository.php | 153 +++--- .../CustomField/CustomFieldDefRepository.php | 154 +++--- .../CustomField/CustomFieldRepository.php | 49 +- .../Notification/NotificationRepository.php | 510 ++++++++++++++++++ .../Repositories/Plugin/PluginRepository.php | 2 +- .../PublicLink/PublicLinkRepository.php | 196 ++++--- lib/SP/Repositories/Tag/TagRepository.php | 172 +++--- lib/SP/Repositories/User/UserRepository.php | 316 +++++------ .../UserGroup/UserGroupRepository.php | 213 +++----- .../UserProfile/UserProfileRepository.php | 202 +++---- .../Account/AccountFavoriteService.php | 88 +++ .../Services/Account/AccountFileService.php | 23 +- .../Services/Account/AccountSearchService.php | 4 +- lib/SP/Services/Account/AccountService.php | 26 +- lib/SP/Services/Auth/LoginService.php | 5 +- .../Services/AuthToken/AuthTokenService.php | 19 + lib/SP/Services/Category/CategoryService.php | 22 +- lib/SP/Services/Client/ClientService.php | 19 +- .../CustomField/CustomFieldDefService.php | 29 +- .../CustomField/CustomFieldService.php | 14 + .../Notification/NotificationService.php | 255 +++++++++ .../Services/PublicLink/PublicLinkService.php | 21 +- lib/SP/Services/Tag/TagService.php | 35 +- lib/SP/Services/User/UserService.php | 25 +- .../Services/UserGroup/UserGroupService.php | 61 ++- .../UserProfile/UserProfileService.php | 27 +- lib/SP/Storage/Database.php | 1 + lib/SP/Storage/DbWrapper.php | 41 +- public/js/app-actions.js | 293 +++++----- public/js/app-actions.min.js | 93 ++-- public/js/app-main.js | 2 +- public/js/app-main.min.js | 6 +- public/js/app-triggers.js | 5 + public/js/app-triggers.min.js | 18 +- schemas/30018010101.sql | 8 +- schemas/dbstructure.sql | 8 +- 97 files changed, 3647 insertions(+), 2244 deletions(-) create mode 100644 app/modules/web/Controllers/NotificationController.php delete mode 100644 app/modules/web/themes/material-blue/views/eventlog/eventlog.inc delete mode 100644 app/modules/web/themes/material-blue/views/noticeshow/notices.inc create mode 100644 app/modules/web/themes/material-blue/views/notification/index.inc create mode 100644 app/modules/web/themes/material-blue/views/notification/notification.inc rename lib/SP/DataModel/{NoticeData.php => NotificationData.php} (97%) rename lib/SP/Forms/{NoticeForm.php => NotificationForm.php} (56%) create mode 100644 lib/SP/Repositories/Account/AccountFavoriteRepository.php create mode 100644 lib/SP/Repositories/Notification/NotificationRepository.php create mode 100644 lib/SP/Services/Account/AccountFavoriteService.php create mode 100644 lib/SP/Services/Notification/NotificationService.php diff --git a/app/config/actions.xml b/app/config/actions.xml index cdac373d..09911b03 100644 --- a/app/config/actions.xml +++ b/app/config/actions.xml @@ -656,16 +656,10 @@ userPreference/security - 760 - NOTICE + 76 + NOTIFICATION Notificaciones - notice/index - - - 761 - NOTICE_USER - Notificaciones Usuario - noticeUser/index + notification/index 1000 @@ -776,39 +770,39 @@ accountManager/restore - 7610 - NOTICE_USER_VIEW + 760 + NOTIFICATION_VIEW Ver Notificación - userNotice/view + notification/view - 7611 - NOTICE_USER_CREATE + 761 + NOTIFICATION_CREATE Crear Notificación - userNotice/create + notification/create - 7612 - NOTICE_USER_EDIT + 762 + NOTIFICATION_EDIT Editar Notificación - userNotice/edit + notification/edit - 7613 - NOTICE_USER_DELETE + 763 + NOTIFICATION_DELETE Eliminar Notificación - userNotice/delete + notification/delete - 7614 - NOTICE_USER_CHECK + 764 + NOTIFICATION_CHECK Marcar Notificación - userNotice/check + notification/check - 7615 - NOTICE_USER_SEARCH + 765 + NOTIFICATION_SEARCH Buscar Notificación - userNotice/search + notification/search \ No newline at end of file diff --git a/app/modules/web/Controllers/AccountController.php b/app/modules/web/Controllers/AccountController.php index cfe623b2..f7b58805 100644 --- a/app/modules/web/Controllers/AccountController.php +++ b/app/modules/web/Controllers/AccountController.php @@ -33,7 +33,6 @@ use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; -use SP\Core\SessionUtil; use SP\DataModel\AccountExtData; use SP\Forms\AccountForm; use SP\Http\JsonResponse; @@ -103,7 +102,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $this->eventDispatcher->notifyEvent('show.account.search', new Event($this)); $data = [ - 'sk' => SessionUtil::getSessionKey(), + 'sk' => $this->session->generateSecurityKey(), 'html' => $this->render() ]; @@ -359,7 +358,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { try { $accountDetailsResponse = $this->accountService->getById($id); @@ -739,7 +738,23 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function saveDeleteAction($id) { try { - if ($this->accountService->delete($id)) { + if ($id === null) { + $this->accountService->deleteByIdBatch($this->getItemsIdFromRequest()); + + $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); + + $this->eventDispatcher->notifyEvent('delete.account.selection', + new Event($this, EventMessage::factory()->addDescription(__u('Cuentas eliminadas'))) + ); + + $this->returnJsonResponseData( + ['nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_SEARCH)], + JsonResponse::JSON_SUCCESS, + __u('Cuentas eliminadas') + ); + } else { + $this->accountService->delete($id); + $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); $this->eventDispatcher->notifyEvent('delete.account', diff --git a/app/modules/web/Controllers/AccountFileController.php b/app/modules/web/Controllers/AccountFileController.php index 9b08f41f..6f4f6b3e 100644 --- a/app/modules/web/Controllers/AccountFileController.php +++ b/app/modules/web/Controllers/AccountFileController.php @@ -261,18 +261,29 @@ class AccountFileController extends ControllerBase implements CrudControllerInte * * @param $id */ - public function deleteAction($id) + public function deleteAction($id = null) { try { - $this->accountFileService->delete($id); + if ($id === null) { + $this->accountFileService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->eventDispatcher->notifyEvent('delete.accountFile', - new Event($this, EventMessage::factory() - ->addDescription(__u('Archivo eliminado')) - ->addDetail(__u('Archivo'), $id)) - ); + $this->eventDispatcher->notifyEvent('delete.accountFile.selection', + new Event($this, EventMessage::factory() + ->addDescription(__u('Archivos eliminados'))) + ); - $this->returnJsonResponse(0, __u('Archivo Eliminado')); + $this->returnJsonResponse(0, __u('Archivos Eliminados')); + } else { + $this->eventDispatcher->notifyEvent('delete.accountFile', + new Event($this, EventMessage::factory() + ->addDescription(__u('Archivo eliminado')) + ->addDetail(__u('Archivo'), $id)) + ); + + $this->accountFileService->delete($id); + + $this->returnJsonResponse(0, __u('Archivo Eliminado')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/ApiTokenController.php b/app/modules/web/Controllers/ApiTokenController.php index cc411d7e..0edc127f 100644 --- a/app/modules/web/Controllers/ApiTokenController.php +++ b/app/modules/web/Controllers/ApiTokenController.php @@ -176,25 +176,39 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::APITOKEN_DELETE)) { return; } try { - $this->authTokenService->delete($id); + if ($id === null) { + $this->authTokenService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::APITOKEN, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::APITOKEN, $id); - $this->eventDispatcher->notifyEvent('delete.authToken', - new Event($this, - EventMessage::factory() - ->addDescription(__u('Autorización eliminada')) - ->addDetail(__u('Autorización'), $id)) - ); + $this->eventDispatcher->notifyEvent('delete.authToken.selection', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Autorizaciones eliminadas'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorización eliminada')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorizaciones eliminadas')); + } else { + $this->authTokenService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::APITOKEN, $id); + + $this->eventDispatcher->notifyEvent('delete.authToken', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Autorización eliminada')) + ->addDetail(__u('Autorización'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorización eliminada')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/CategoryController.php b/app/modules/web/Controllers/CategoryController.php index 08493209..f04d73f9 100644 --- a/app/modules/web/Controllers/CategoryController.php +++ b/app/modules/web/Controllers/CategoryController.php @@ -170,25 +170,39 @@ class CategoryController extends ControllerBase implements CrudControllerInterfa * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::CATEGORY_DELETE)) { return; } try { - $this->categoryService->delete($id); + if ($id === null) { + $this->categoryService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::CATEGORY, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::CATEGORY, $id); - $this->eventDispatcher->notifyEvent('delete.category', - new Event($this, - EventMessage::factory() - ->addDescription(__u('Categoría eliminada')) - ->addDetail(__u('Categoría'), $id)) - ); + $this->eventDispatcher->notifyEvent('delete.category', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Categorías eliminadas'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Categoría eliminada')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Categorías eliminadas')); + } else { + $this->categoryService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::CATEGORY, $id); + + $this->eventDispatcher->notifyEvent('delete.category', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Categoría eliminada')) + ->addDetail(__u('Categoría'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Categoría eliminada')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/ClientController.php b/app/modules/web/Controllers/ClientController.php index ac7e6947..9af38bee 100644 --- a/app/modules/web/Controllers/ClientController.php +++ b/app/modules/web/Controllers/ClientController.php @@ -171,25 +171,39 @@ class ClientController extends ControllerBase implements CrudControllerInterface * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::CLIENT_DELETE)) { return; } try { - $this->clientService->delete($id); + if ($id === null) { + $this->clientService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::CLIENT, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::CLIENT, $id); - $this->eventDispatcher->notifyEvent('delete.client', - new Event($this, - EventMessage::factory() - ->addDescription(__u('Cliente eliminado')) - ->addDetail(__u('Cliente'), $id)) - ); + $this->eventDispatcher->notifyEvent('delete.client.selection', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Clientes eliminados'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Cliente eliminado')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Clientes eliminados')); + } else { + $this->clientService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::CLIENT, $id); + + $this->eventDispatcher->notifyEvent('delete.client', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Cliente eliminado')) + ->addDetail(__u('Cliente'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Cliente eliminado')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/ConfigManagerController.php b/app/modules/web/Controllers/ConfigManagerController.php index 6b14d03d..be491594 100644 --- a/app/modules/web/Controllers/ConfigManagerController.php +++ b/app/modules/web/Controllers/ConfigManagerController.php @@ -233,7 +233,7 @@ class ConfigManagerController extends ControllerBase $template->assign('mailSecurity', ['SSL', 'TLS']); $template->assign('configData', $this->configData); - $template->assign('numAccounts', $this->dic->get(AccountService::class)->getTotalNumAccounts()); + $template->assign('numAccounts', $this->dic->get(AccountService::class)->getTotalNumAccounts()->num); $template->assign('taskId', Task::genTaskId('masterpass')); $configService = $this->dic->get(ConfigService::class); diff --git a/app/modules/web/Controllers/ControllerBase.php b/app/modules/web/Controllers/ControllerBase.php index e9405e26..bb963b9a 100644 --- a/app/modules/web/Controllers/ControllerBase.php +++ b/app/modules/web/Controllers/ControllerBase.php @@ -191,7 +191,7 @@ abstract class ControllerBase } catch (FileNotFoundException $e) { processException($e); - echo $e->getMessage(); + echo __($e->getMessage()); } die(); diff --git a/app/modules/web/Controllers/CustomFieldController.php b/app/modules/web/Controllers/CustomFieldController.php index bf0e7075..7c71be23 100644 --- a/app/modules/web/Controllers/CustomFieldController.php +++ b/app/modules/web/Controllers/CustomFieldController.php @@ -28,6 +28,7 @@ namespace SP\Modules\Web\Controllers; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ValidationException; use SP\DataModel\CustomFieldDefinitionData; use SP\Forms\CustomFieldDefForm; @@ -175,20 +176,28 @@ class CustomFieldController extends ControllerBase implements CrudControllerInte * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::CUSTOMFIELD_DELETE)) { return; } try { - $this->customFieldService->delete($id); + if ($id === null) { + $this->customFieldService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::CUSTOMFIELD, $id); + $this->eventDispatcher->notifyEvent('delete.customField.selection', + new Event($this, EventMessage::factory()->addDescription(__u('Campos eliminados'))) + ); - $this->eventDispatcher->notifyEvent('delete.customField', new Event($this)); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Campos eliminados')); + } else { + $this->customFieldService->delete($id); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Campo eliminado')); + $this->eventDispatcher->notifyEvent('delete.customField', new Event($this)); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Campo eliminado')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php index 0dccc68d..0c7e4e44 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php @@ -33,7 +33,6 @@ use SP\Core\Acl\UnauthorizedPageException; use SP\Core\Exceptions\SPException; use SP\DataModel\Dto\AccountAclDto; use SP\DataModel\Dto\AccountDetailsResponse; -use SP\Mgmt\Users\UserPass; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Modules\Web\Controllers\Traits\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; @@ -41,6 +40,7 @@ use SP\Services\Account\AccountHistoryService; use SP\Services\Account\AccountService; use SP\Services\Category\CategoryService; use SP\Services\Client\ClientService; +use SP\Services\Crypt\MasterPassService; use SP\Services\PublicLink\PublicLinkService; use SP\Services\Tag\TagService; use SP\Services\User\UpdatedMasterPassException; @@ -160,6 +160,7 @@ class AccountHelper extends HelperBase /** * @throws UnauthorizedPageException * @throws UpdatedMasterPassException + * @throws \SP\Services\Config\ParameterNotFoundException */ public function checkActionAccess() { @@ -167,7 +168,7 @@ class AccountHelper extends HelperBase throw new UnauthorizedPageException(SPException::INFO); } - if (!UserPass::checkUserUpdateMPass($this->session->getUserData()->getId())) { + if (!$this->dic->get(MasterPassService::class)->checkUserUpdateMPass($this->session->getUserData()->getLastUpdateMPass())) { throw new UpdatedMasterPassException(SPException::INFO); } } @@ -253,6 +254,7 @@ class AccountHelper extends HelperBase * @throws \Psr\Container\NotFoundExceptionInterface * @throws \ReflectionException * @throws \SP\Core\Dic\ContainerException + * @throws \SP\Services\Config\ParameterNotFoundException */ public function setViewForBlank($actionId) { @@ -291,6 +293,7 @@ class AccountHelper extends HelperBase * @throws \Psr\Container\NotFoundExceptionInterface * @throws \ReflectionException * @throws \SP\Core\Dic\ContainerException + * @throws \SP\Services\Config\ParameterNotFoundException */ public function setViewForRequest(AccountDetailsResponse $accountDetailsResponse, $actionId) { diff --git a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php index e7028d2d..20c2ae7e 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php @@ -29,9 +29,9 @@ use SP\Core\Acl\ActionsInterface; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Session as CryptSession; use SP\DataModel\AccountPassData; -use SP\Mgmt\Users\UserPass; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Modules\Web\Controllers\Helpers\HelperException; +use SP\Services\Crypt\MasterPassService; use SP\Util\ImageUtil; /** @@ -77,6 +77,7 @@ class AccountPasswordHelper extends HelperBase * @return string * @throws HelperException * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \SP\Services\Config\ParameterNotFoundException */ protected function getPasswordClear(AccountPassData $accountData) { @@ -86,8 +87,7 @@ class AccountPasswordHelper extends HelperBase throw new HelperException(__u('No tiene permisos para acceder a esta cuenta')); } - // FIXME - if (!UserPass::checkUserUpdateMPass($this->session->getUserData()->getId())) { + if (!$this->dic->get(MasterPassService::class)->checkUserUpdateMPass($this->session->getUserData()->getLastUpdateMPass())) { throw new HelperException(__('Clave maestra actualizada') . '
' . __('Reinicie la sesión para cambiarla')); } diff --git a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php index d677a881..a91af35f 100644 --- a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php +++ b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php @@ -42,6 +42,7 @@ use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridPager; use SP\Html\DataGrid\DataGridTab; use SP\Repositories\CustomField\CustomFieldDefRepository; +use SP\Util\DateUtil; /** * Class Grids con las plantillas de tablas de datos @@ -1301,7 +1302,7 @@ class ItemsGridHelper extends HelperBase $GridActionClear->setIcon($this->icons->getIconClear()); $GridActionClear->setOnClickFunction('eventlog/clear'); $GridActionClear->addData('action-route', Acl::getActionRoute(ActionsInterface::EVENTLOG_CLEAR)); - $GridActionClear->addData('action-next', Acl::getActionRoute(ActionsInterface::EVENTLOG)); + $GridActionClear->addData('nextaction', Acl::getActionRoute(ActionsInterface::EVENTLOG)); $Grid->setDataActions($GridActionClear); @@ -1312,6 +1313,130 @@ class ItemsGridHelper extends HelperBase return $Grid; } + /** + * @param array $data + * @return DataGrid + * @throws \SP\Core\Dic\ContainerException + */ + public function getNoticesGrid(array $data) + { + $isAdminApp = $this->session->getUserData()->getIsAdminApp(); + + // Grid Header + $GridHeaders = new DataGridHeader(); + $GridHeaders->addHeader(__('Fecha')); + $GridHeaders->addHeader(__('Tipo')); + $GridHeaders->addHeader(__('Componente')); + $GridHeaders->addHeader(__('Descripción')); + $GridHeaders->addHeader(__('Estado')); + + // Grid Data + $GridData = new DataGridData(); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('date', false, + function ($value) { + return DateUtil::getDateFromUnix($value); + }); + $GridData->addDataRowSource('type'); + $GridData->addDataRowSource('component'); + $GridData->addDataRowSource('description'); + $GridData->addDataRowSourceWithIcon('checked', $this->icons->getIconEnabled()->setTitle(__('Leída'))); + $GridData->addDataRowSourceWithIcon('onlyAdmin', $this->icons->getIconAppAdmin()->setTitle(__('Sólo Admins'))); + $GridData->addDataRowSourceWithIcon('sticky', $this->icons->getIconGroup()->setTitle(__('Global'))); + $GridData->setData($data); + + // Grid + $Grid = new DataGrid(); + $Grid->setId('tblNotifications'); + $Grid->setDataRowTemplate('datagrid-rows', 'grid'); + $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid'); + $Grid->setHeader($GridHeaders); + $Grid->setData($GridData); + $Grid->setTitle(__('Notificaciones')); + $Grid->setTime(round(microtime() - $this->queryTimeStart, 5)); + + // Grid Actions + $GridActionSearch = new DataGridActionSearch(); + $GridActionSearch->setId(ActionsInterface::NOTIFICATION_SEARCH); + $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM); + $GridActionSearch->setName('frmSearchNotification'); + $GridActionSearch->setTitle(__('Buscar Notificación')); + $GridActionSearch->setOnSubmitFunction('notification/search'); + $GridActionSearch->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_SEARCH)); + + $Grid->setDataActions($GridActionSearch); + $Grid->setPager($this->getPager($GridActionSearch)); + + if ($isAdminApp) { + // Grid item's actions + $GridActionNew = new DataGridAction(); + $GridActionNew->setId(ActionsInterface::NOTIFICATION_CREATE); + $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM); + $GridActionNew->setName(__('Nueva Notificación')); + $GridActionNew->setTitle(__('Nueva Notificación')); + $GridActionNew->setIcon($this->icons->getIconAdd()); + $GridActionNew->setSkip(true); + $GridActionNew->setOnClickFunction('notification/show'); + $GridActionNew->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_CREATE)); + + $Grid->setDataActions($GridActionNew); + } + + $GridActionView = new DataGridAction(); + $GridActionView->setId(ActionsInterface::NOTIFICATION_VIEW); + $GridActionView->setType(DataGridActionType::VIEW_ITEM); + $GridActionView->setName(__('Ver Notificación')); + $GridActionView->setTitle(__('Ver Notificación')); + $GridActionView->setIcon($this->icons->getIconView()); + $GridActionView->setOnClickFunction('notification/show'); + $GridActionView->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_VIEW)); + + $Grid->setDataActions($GridActionView); + + $GridActionCheck = new DataGridAction(); + $GridActionCheck->setId(ActionsInterface::NOTIFICATION_CHECK); + $GridActionCheck->setName(__('Marcar Notificación')); + $GridActionCheck->setTitle(__('Marcar Notificación')); + $GridActionCheck->setIcon($this->icons->getIconEnabled()); + $GridActionCheck->setOnClickFunction('notification/check'); + $GridActionCheck->setFilterRowSource('checked'); + $GridActionCheck->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_CHECK)); + $GridActionCheck->addData('nextaction', Acl::getActionRoute(ActionsInterface::NOTIFICATION)); + + $Grid->setDataActions($GridActionCheck); + + $GridActionEdit = new DataGridAction(); + $GridActionEdit->setId(ActionsInterface::NOTIFICATION_EDIT); + $GridActionEdit->setName(__('Editar Notificación')); + $GridActionEdit->setTitle(__('Editar Notificación')); + $GridActionEdit->setIcon($this->icons->getIconEdit()); + $GridActionEdit->setOnClickFunction('notification/show'); + $GridActionEdit->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_EDIT)); + + $Grid->setDataActions($GridActionEdit); + + $GridActionDel = new DataGridAction(); + $GridActionDel->setId(ActionsInterface::NOTIFICATION_DELETE); + $GridActionDel->setType(DataGridActionType::DELETE_ITEM); + $GridActionDel->setName(__('Eliminar Notificación')); + $GridActionDel->setTitle(__('Eliminar Notificación')); + $GridActionDel->setIcon($this->icons->getIconDelete()); + $GridActionDel->setOnClickFunction('notification/delete'); + $GridActionDel->addData('action-route', Acl::getActionRoute(ActionsInterface::NOTIFICATION_DELETE)); + $GridActionDel->addData('nextaction', Acl::getActionRoute(ActionsInterface::NOTIFICATION)); + + if (!$isAdminApp) { + $GridActionCheck->setFilterRowSource('sticky'); + $GridActionEdit->setFilterRowSource('sticky'); + $GridActionDel->setFilterRowSource('sticky'); + } + + $Grid->setDataActions($GridActionDel); + $Grid->setDataActions($GridActionDel, true); + + return $Grid; + } + /** * Actualizar los datos del paginador * diff --git a/app/modules/web/Controllers/Helpers/LayoutHelper.php b/app/modules/web/Controllers/Helpers/LayoutHelper.php index c6049ed7..aac03e22 100644 --- a/app/modules/web/Controllers/Helpers/LayoutHelper.php +++ b/app/modules/web/Controllers/Helpers/LayoutHelper.php @@ -35,7 +35,6 @@ use SP\Core\SessionUtil; use SP\Core\UI\Theme; use SP\Core\UI\ThemeInterface; use SP\Html\DataGrid\DataGridAction; -use SP\Mgmt\Notices\Notice; use SP\Util\Checks; use SP\Util\Util; @@ -228,7 +227,7 @@ class LayoutHelper extends HelperBase $this->view->assign('userName', $userData->getName() ?: mb_strtoupper($this->view->userLogin)); $this->view->assign('userGroup', $userData->getUserGroupId()); $this->view->assign('showPassIcon', !($this->configData->isLdapEnabled() && $userData->getIsLdap())); - $this->view->assign('userNotices', count(Notice::getItem()->getAllActiveForUser())); + $this->view->assign('notifications', 0); } /** diff --git a/app/modules/web/Controllers/ItemsController.php b/app/modules/web/Controllers/ItemsController.php index bfa0d73e..7cd740e1 100644 --- a/app/modules/web/Controllers/ItemsController.php +++ b/app/modules/web/Controllers/ItemsController.php @@ -24,13 +24,13 @@ namespace SP\Modules\Web\Controllers; -use SP\Core\SessionUtil; use SP\DataModel\DataModelInterface; use SP\Http\JsonResponse; use SP\Mvc\View\Components\SelectItemAdapter; use SP\Services\Account\AccountService; use SP\Services\Category\CategoryService; use SP\Services\Client\ClientService; +use SP\Services\Notification\NotificationService; use SP\Util\Json; /** @@ -40,19 +40,10 @@ use SP\Util\Json; */ class ItemsController extends SimpleControllerBase { - /** - * ItemsController constructor. - */ - protected function initialize() - { - $this->checks(); - } - /** * Devolver las cuentas visibles por el usuario * * @param int $accountId - * @throws \Psr\Container\ContainerExceptionInterface */ public function accountsUserAction($accountId = null) { @@ -69,14 +60,12 @@ class ItemsController extends SimpleControllerBase $jsonResponse = new JsonResponse(); $jsonResponse->setStatus(0); $jsonResponse->setData($outItems); - $jsonResponse->setCsrf(SessionUtil::getSessionKey()); + $jsonResponse->setCsrf($this->session->getSecurityKey()); Json::returnJson($jsonResponse); } /** - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface * @throws \SP\Core\Exceptions\SPException */ public function clientsAction() @@ -85,8 +74,6 @@ class ItemsController extends SimpleControllerBase } /** - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface * @throws \SP\Core\Exceptions\SPException */ public function categoriesAction() @@ -94,6 +81,22 @@ class ItemsController extends SimpleControllerBase Json::returnRawJson(SelectItemAdapter::factory($this->dic->get(CategoryService::class)->getAllBasic())->getJsonItemsFromModel()); } + /** + * @throws \SP\Core\Exceptions\SPException + */ + public function notificationsAction() + { + Json::returnRawJson(Json::getJson($this->dic->get(NotificationService::class)->getAllActiveForUserId($this->session->getUserData()->getId()))); + } + + /** + * ItemsController constructor. + */ + protected function initialize() + { + $this->checks(); + } + /** * Preparar los elementos para devolverlos * diff --git a/app/modules/web/Controllers/LoginController.php b/app/modules/web/Controllers/LoginController.php index 03abaf20..fe9cd034 100644 --- a/app/modules/web/Controllers/LoginController.php +++ b/app/modules/web/Controllers/LoginController.php @@ -24,6 +24,8 @@ namespace SP\Modules\Web\Controllers; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\SessionFactory; use SP\Core\SessionUtil; use SP\Html\Html; @@ -62,19 +64,20 @@ class LoginController extends ControllerBase public function logoutAction() { if ($this->session->isLoggedIn()) { -// $inactiveTime = abs(round((time() - SessionFactory::getLastActivity()) / 60, 2)); -// $totalTime = abs(round((time() - SessionFactory::getStartActivity()) / 60, 2)); + $inactiveTime = abs(round((time() - $this->session->getLastActivity()) / 60, 2)); + $totalTime = abs(round((time() - $this->session->getStartActivity()) / 60, 2)); -// $Log = new Log(); -// $LogMessage = $Log->getLogMessage(); -// $LogMessage->setAction(__u('Finalizar sesión')); -// $LogMessage->addDetails(__u('Usuario'), SessionFactory::getUserData()->getLogin()); -// $LogMessage->addDetails(__u('Tiempo inactivo'), $inactiveTime . ' min.'); -// $LogMessage->addDetails(__u('Tiempo total'), $totalTime . ' min.'); -// $Log->writeLog(); + $this->eventDispatcher->notifyEvent('logout', + new Event($this, EventMessage::factory() + ->addDescription(__u('Finalizar sesión')) + ->addDetail(__u('Usuario'), $this->session->getUserData()->getLogin()) + ->addDetail(__u('Tiempo inactivo'), $inactiveTime . ' min.') + ->addDetail(__u('Tiempo total'), $totalTime . ' min.')) + ); SessionUtil::cleanSession(); - SessionFactory::setLoggedOut(true); + + $this->session->setLoggedOut(true); $layoutHelper = $this->dic->get(LayoutHelper::class); $layoutHelper->getCustomLayout('logout', 'logout'); diff --git a/app/modules/web/Controllers/NotificationController.php b/app/modules/web/Controllers/NotificationController.php new file mode 100644 index 00000000..9fbebedf --- /dev/null +++ b/app/modules/web/Controllers/NotificationController.php @@ -0,0 +1,366 @@ +. + */ + +namespace SP\Modules\Web\Controllers; + +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\DataModel\NotificationData; +use SP\Forms\NotificationForm; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Helpers\ItemsGridHelper; +use SP\Modules\Web\Controllers\Traits\ItemTrait; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\CrudControllerInterface; +use SP\Mvc\View\Components\SelectItemAdapter; +use SP\Services\Notification\NotificationService; +use SP\Services\User\UserService; + +/** + * Class NotificationController + * + * @package SP\Modules\Web\Controllers + */ +class NotificationController extends ControllerBase implements CrudControllerInterface +{ + use JsonTrait, ItemTrait; + + /** + * @var NotificationService + */ + protected $notificationService; + + /** + * @throws \SP\Core\Dic\ContainerException + */ + public function indexAction() + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION)) { + return; + } + + $this->view->addTemplate('index'); + + $this->view->assign('data', $this->getSearchGrid()); + + $this->view(); + } + + /** + * @return $this + * @throws \SP\Core\Dic\ContainerException + */ + protected function getSearchGrid() + { + $itemsGridHelper = $this->dic->get(ItemsGridHelper::class); + $itemSearchData = $this->getSearchData($this->configData); + + return $itemsGridHelper->updatePager($itemsGridHelper->getNoticesGrid($this->notificationService->search($itemSearchData)), $itemSearchData); + } + + /** + * View action + * + * @param $id + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function viewAction($id) + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_CREATE)) { + return; + } + + $this->view->assign('header', __('Ver Notificación')); + $this->view->assign('isView', true); + + try { + $this->setViewData($id); + + $this->eventDispatcher->notifyEvent('show.notification', new Event($this)); + + $this->returnJsonResponseData(['html' => $this->render()]); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Sets view data for displaying user's data + * + * @param $notificationId + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function setViewData($notificationId = null) + { + $this->view->addTemplate('notification'); + + $notification = $notificationId ? $this->notificationService->getById($notificationId) : new NotificationData(); + + $this->view->assign('notification', $notification); + + if ($this->userData->getIsAdminApp()) { + $this->view->assign('users', SelectItemAdapter::factory(UserService::getItemsBasic())->getItemsFromModelSelected([$notification->userId])); + } + + $this->view->assign('sk', $this->session->generateSecurityKey()); + $this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::NOTIFICATION)); + + if ($this->view->isView === true) { + $this->view->assign('disabled', 'disabled'); + $this->view->assign('readonly', 'readonly'); + } else { + $this->view->assign('disabled'); + $this->view->assign('readonly'); + } + } + + /** + * Search action + * + * @throws \SP\Core\Dic\ContainerException + */ + public function searchAction() + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_SEARCH)) { + return; + } + + $this->view->addTemplate('datagrid-table', 'grid'); + $this->view->assign('data', $this->getSearchGrid()); + + $this->returnJsonResponseData(['html' => $this->render()]); + } + + /** + * Create action + * + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function createAction() + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_CREATE)) { + return; + } + + $this->view->assign(__FUNCTION__, 1); + $this->view->assign('header', __('Nueva Notificación')); + $this->view->assign('isView', false); + $this->view->assign('route', 'notification/saveCreate'); + + try { + $this->setViewData(); + + $this->eventDispatcher->notifyEvent('show.notification.create', new Event($this)); + + $this->returnJsonResponseData(['html' => $this->render()]); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Edit action + * + * @param $id + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function editAction($id) + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_EDIT)) { + return; + } + + $this->view->assign(__FUNCTION__, 1); + $this->view->assign('header', __('Editar Notificación')); + $this->view->assign('isView', false); + $this->view->assign('route', 'notification/saveEdit/' . $id); + + try { + $this->setViewData($id); + + $this->eventDispatcher->notifyEvent('show.notification.edit', new Event($this)); + + $this->returnJsonResponseData(['html' => $this->render()]); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Delete action + * + * @param $id + */ + public function deleteAction($id = null) + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_DELETE)) { + return; + } + + try { + if ($id === null) { + if ($this->userData->getIsAdminApp()) { + $this->notificationService->deleteAdminBatch($this->getItemsIdFromRequest()); + } else { + $this->notificationService->deleteByIdBatch($this->getItemsIdFromRequest()); + } + + $this->eventDispatcher->notifyEvent('delete.notification.selection', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Notificaciones eliminadas'))) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Notificaciones eliminadas')); + } else { + if ($this->userData->getIsAdminApp()) { + $this->notificationService->deleteAdmin($id); + } else { + $this->notificationService->delete($id); + } + + $this->eventDispatcher->notifyEvent('delete.notification', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Notificación eliminada')) + ->addDetail(__u('Notificación'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Notificación eliminada')); + } + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Check action + * + * @param $id + */ + public function checkAction($id) + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_CHECK)) { + return; + } + + try { + $this->notificationService->setCheckedById($id); + + $this->eventDispatcher->notifyEvent('check.notification', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Notificación leída')) + ->addDetail(__u('Notificación'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Notificación leída')); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Saves create action + */ + public function saveCreateAction() + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_CREATE)) { + return; + } + + try { + $form = new NotificationForm(); + $form->validate(ActionsInterface::NOTIFICATION_CREATE); + + $this->notificationService->create($form->getItemData()); + + $this->eventDispatcher->notifyEvent('create.notification', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Notificación creada'))) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Notificación creada')); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + /** + * Saves edit action + * + * @param $id + */ + public function saveEditAction($id) + { + if (!$this->acl->checkUserAccess(ActionsInterface::NOTIFICATION_EDIT)) { + return; + } + + try { + $form = new NotificationForm($id); + $form->validate(ActionsInterface::NOTIFICATION_EDIT); + + $this->notificationService->update($form->getItemData()); + + $this->eventDispatcher->notifyEvent('edit.notification', + new Event($this, + EventMessage::factory() + ->addDescription(__u('Notificación actualizada'))) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Notificación actualizada')); + } catch (\Exception $e) { + processException($e); + + $this->returnJsonResponseException($e); + } + } + + protected function initialize() + { + $this->notificationService = $this->dic->get(NotificationService::class); + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/PublicLinkController.php b/app/modules/web/Controllers/PublicLinkController.php index 417b09c7..48220fc8 100644 --- a/app/modules/web/Controllers/PublicLinkController.php +++ b/app/modules/web/Controllers/PublicLinkController.php @@ -27,6 +27,7 @@ namespace SP\Modules\Web\Controllers; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\PublicLinkListData; @@ -200,21 +201,37 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::PUBLICLINK_DELETE)) { return; } try { -// $this->publicLinkService->logAction($id, ActionsInterface::PROFILE_DELETE); - $this->publicLinkService->delete($id); + if ($id === null) { + $this->publicLinkService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::PUBLICLINK, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::PUBLICLINK, $id); - $this->eventDispatcher->notifyEvent('delete.publicLink', new Event($this)); + $this->eventDispatcher->notifyEvent('delete.publicLink.selection', + new Event($this, EventMessage::factory() + ->addDescription(__u('Enlaces eliminados'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Enlace eliminado')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Enlaces eliminados')); + } else { + $this->publicLinkService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::PUBLICLINK, $id); + + $this->eventDispatcher->notifyEvent('delete.publicLink', + new Event($this, EventMessage::factory() + ->addDescription(__u('Enlace eliminado')) + ->addDetail(__u('Enlace'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Enlace eliminado')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/TagController.php b/app/modules/web/Controllers/TagController.php index c9ba6f9a..afa0adb3 100644 --- a/app/modules/web/Controllers/TagController.php +++ b/app/modules/web/Controllers/TagController.php @@ -168,20 +168,30 @@ class TagController extends ControllerBase implements CrudControllerInterface * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::TAG_DELETE)) { return; } try { - $this->tagService->delete($id); + if ($id === null) { + $this->tagService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::TAG, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::TAG, $id); - $this->eventDispatcher->notifyEvent('delete.tag', new Event($this)); + $this->eventDispatcher->notifyEvent('delete.tag.selection', new Event($this)); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Etiqueta eliminada')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Etiquetas eliminadas')); + } else { + $this->tagService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::TAG, $id); + + $this->eventDispatcher->notifyEvent('delete.tag', new Event($this)); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Etiqueta eliminada')); + } } catch (\Exception $e) { processException($e); @@ -286,5 +296,4 @@ class TagController extends ControllerBase implements CrudControllerInterface $this->tagService = $this->dic->get(TagService::class); } - } \ No newline at end of file diff --git a/app/modules/web/Controllers/Traits/ItemTrait.php b/app/modules/web/Controllers/Traits/ItemTrait.php index 221a2ce3..a4ec9606 100644 --- a/app/modules/web/Controllers/Traits/ItemTrait.php +++ b/app/modules/web/Controllers/Traits/ItemTrait.php @@ -135,7 +135,13 @@ trait ItemTrait */ protected function deleteCustomFieldsForItem($moduleId, $itemId) { - Bootstrap::getContainer()->get(CustomFieldService::class)->deleteCustomFieldData($itemId, $moduleId); + $customFieldService = Bootstrap::getContainer()->get(CustomFieldService::class); + + if (is_array($itemId)) { + $customFieldService->deleteCustomFieldDataBatch($itemId, $moduleId); + } else { + $customFieldService->deleteCustomFieldData($itemId, $moduleId); + } } /** @@ -189,4 +195,12 @@ trait ItemTrait return $itemSearchData; } + + /** + * @return mixed + */ + protected function getItemsIdFromRequest() + { + return Request::analyze('items', 0); + } } \ No newline at end of file diff --git a/app/modules/web/Controllers/UserController.php b/app/modules/web/Controllers/UserController.php index f79cda34..88164741 100644 --- a/app/modules/web/Controllers/UserController.php +++ b/app/modules/web/Controllers/UserController.php @@ -27,6 +27,7 @@ namespace SP\Modules\Web\Controllers; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ValidationException; use SP\Core\SessionUtil; use SP\DataModel\UserData; @@ -214,7 +215,7 @@ class UserController extends ControllerBase implements CrudControllerInterface * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::USER_DELETE)) { return; @@ -223,14 +224,29 @@ class UserController extends ControllerBase implements CrudControllerInterface $this->view->assign(__FUNCTION__, 1); try { -// $this->userService->logAction($id, ActionsInterface::USER_DELETE); - $this->userService->delete($id); + if ($id === null) { + $this->userService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::USER, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::USER, $id); - $this->eventDispatcher->notifyEvent('delete.user', new Event($this)); + $this->eventDispatcher->notifyEvent('delete.user.selection', + new Event($this, EventMessage::factory()->addDescription(__u('Usuarios eliminados'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Usuario eliminado')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Usuarios eliminados')); + } else { + $this->userService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::USER, $id); + + $this->eventDispatcher->notifyEvent('delete.user', + new Event($this, EventMessage::factory() + ->addDescription(__u('Usuario eliminado')) + ->addDetail(__u('Usuario'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Usuario eliminado')); + } } catch (\Exception $e) { processException($e); diff --git a/app/modules/web/Controllers/UserGroupController.php b/app/modules/web/Controllers/UserGroupController.php index ab0a4276..9b200b19 100644 --- a/app/modules/web/Controllers/UserGroupController.php +++ b/app/modules/web/Controllers/UserGroupController.php @@ -27,6 +27,7 @@ namespace SP\Modules\Web\Controllers; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ValidationException; use SP\DataModel\UserGroupData; use SP\Forms\UserGroupForm; @@ -178,21 +179,36 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::GROUP_DELETE)) { return; } try { -// $this->userGroupService->logAction($id, ActionsInterface::GROUP_DELETE); - $this->userGroupService->delete($id); + if ($id === null) { + $this->userGroupService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::GROUP, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::GROUP, $id); - $this->eventDispatcher->notifyEvent('delete.userGroup', new Event($this)); + $this->eventDispatcher->notifyEvent('delete.userGroup.selection', + new Event($this, EventMessage::factory()->addDescription(__u('Grupos eliminados'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Grupo eliminado')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Grupos eliminados')); + } else { + $this->userGroupService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::GROUP, $id); + + $this->eventDispatcher->notifyEvent('delete.userGroup', + new Event($this, EventMessage::factory() + ->addDescription(__u('Grupo eliminado')) + ->addDetail(__u('Grupo'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Grupo eliminado')); + } } catch (\Exception $e) { processException($e); @@ -215,13 +231,15 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $groupData = $form->getItemData(); - $id = $this->userGroupService->create($groupData); -// $this->userGroupService->logAction($id, ActionsInterface::GROUP_CREATE); - $this->userToUserGroupService->add($id, $groupData->getUsers()); + $id = $this->userGroupService->create($groupData, $groupData->getUsers()); $this->addCustomFieldsForItem(ActionsInterface::GROUP, $id); - $this->eventDispatcher->notifyEvent('create.userGroup', new Event($this)); + $this->eventDispatcher->notifyEvent('create.userGroup', + new Event($this, EventMessage::factory() + ->addDescription(__u('Grupo creado')) + ->addDetail(__u('Nombre'), $groupData->getName())) + ); $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Grupo creado')); } catch (ValidationException $e) { @@ -253,12 +271,14 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $groupData = $form->getItemData(); $this->userGroupService->update($groupData); -// $this->userGroupService->logAction($id, ActionsInterface::GROUP_EDIT); - $this->userToUserGroupService->update($groupData->getId(), $groupData->getUsers()); $this->updateCustomFieldsForItem(ActionsInterface::GROUP, $id); - $this->eventDispatcher->notifyEvent('edit.useGroup', new Event($this)); + $this->eventDispatcher->notifyEvent('edit.userGroup', + new Event($this, EventMessage::factory() + ->addDescription(__u('Grupo actualizado')) + ->addDetail(__u('Nombre'), $groupData->getName())) + ); $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Grupo actualizado')); } catch (ValidationException $e) { @@ -310,6 +330,6 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $this->checkLoggedIn(); $this->userGroupService = $this->dic->get(UserGroupService::class); - $this->userToUserGroupService = $this->dic->get(UserToUserGroupService::class); + $this->userToUserGroupService = $this->dic->get(UserToUserGroupService::class); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/UserProfileController.php b/app/modules/web/Controllers/UserProfileController.php index 884cdd8a..34e067c3 100644 --- a/app/modules/web/Controllers/UserProfileController.php +++ b/app/modules/web/Controllers/UserProfileController.php @@ -27,8 +27,10 @@ namespace SP\Modules\Web\Controllers; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ProfileData; +use SP\DataModel\UserProfileData; use SP\Forms\UserProfileForm; use SP\Http\JsonResponse; use SP\Http\Request; @@ -115,9 +117,10 @@ class UserProfileController extends ControllerBase implements CrudControllerInte { $this->view->addTemplate('userprofile', 'itemshow'); - $profile = $profileId ? $this->userProfileService->getById($profileId) : new ProfileData(); + $profile = $profileId ? $this->userProfileService->getById($profileId) : new UserProfileData(); $this->view->assign('profile', $profile); + $this->view->assign('profileData', $profile->getProfile() ?: new ProfileData()); $this->view->assign('sk', $this->session->generateSecurityKey()); $this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ACCESS_MANAGE)); @@ -171,21 +174,36 @@ class UserProfileController extends ControllerBase implements CrudControllerInte * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ - public function deleteAction($id) + public function deleteAction($id = null) { if (!$this->acl->checkUserAccess(ActionsInterface::PROFILE_DELETE)) { return; } try { -// $this->userProfileService->logAction($id, ActionsInterface::PROFILE_DELETE); - $this->userProfileService->delete($id); + if ($id === null) { + $this->userProfileService->deleteByIdBatch($this->getItemsIdFromRequest()); - $this->deleteCustomFieldsForItem(ActionsInterface::PROFILE, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::PROFILE, $id); - $this->eventDispatcher->notifyEvent('delete.userProfile', new Event($this)); + $this->eventDispatcher->notifyEvent('delete.userProfile.selection', + new Event($this, EventMessage::factory()->addDescription(__u('Perfiles eliminados'))) + ); - $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Perfil eliminado')); + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Perfiles eliminados')); + } else { + $this->userProfileService->delete($id); + + $this->deleteCustomFieldsForItem(ActionsInterface::PROFILE, $id); + + $this->eventDispatcher->notifyEvent('delete.userProfile', + new Event($this, EventMessage::factory() + ->addDescription(__u('Perfil eliminado')) + ->addDetail(__u('Perfil'), $id)) + ); + + $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Perfil eliminado')); + } } catch (\Exception $e) { processException($e); @@ -209,7 +227,6 @@ class UserProfileController extends ControllerBase implements CrudControllerInte $profileData = $form->getItemData(); $id = $this->userProfileService->create($profileData); -// $this->userProfileService->logAction($id, ActionsInterface::PROFILE_CREATE); $this->addCustomFieldsForItem(ActionsInterface::PROFILE, $id); diff --git a/app/modules/web/themes/material-blue/views/_partials/fixed-header.inc b/app/modules/web/themes/material-blue/views/_partials/fixed-header.inc index 9cfd2b6c..33e3ce79 100644 --- a/app/modules/web/themes/material-blue/views/_partials/fixed-header.inc +++ b/app/modules/web/themes/material-blue/views/_partials/fixed-header.inc @@ -27,28 +27,21 @@ class="mdl-tooltip mdl-tooltip--bottom">getTitle(); ?> - 0): ?> - - notifications - + + notifications + - - - - notifications - - - + + 0): ?> + + + + + @@ -101,24 +94,22 @@ - 0): ?> - - notifications - - - - - notifications - - - + + notifications + + + + 0): ?> + + + + + + - -
- -
- - - ' . __('No se encontraron registros') . ''); ?> - - -
- - - - - - - - - - - - - - - log_description) : preg_replace("/\d+\.\d+\.\d+\.\d+/", "*.*.*.*", utf8_decode($log->log_description)); ?> - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- log_id; ?> - - log_date; ?> - - log_level; ?> - - log_action); ?> - - log_login); ?> - - log_ipAddress) : $log->log_ipAddress; ?> - - ', $text); - $text = preg_replace('/(UPDATE|DELETE|TRUNCATE|INSERT|SELECT|WHERE|LEFT|ORDER|LIMIT|FROM)/', '
\\1', $text); - } - - if (strlen($text) >= 150) { - echo wordwrap($text, 150, '
', true); - } else { - echo $text . '
'; - } - } - ?> -
-
-
-
- getTotalRows(); ?> @ s -
-
- getLimitStart() > 1): ?> - getIconFirst()->getIcon(); ?> - getIconPrev()->getIcon(); ?> - -   - getFirstPage(), '/', $Pager->getLastPage(); ?> -   - getLimitStart() < $Pager->getTotalRows() && $Pager->getFirstPage() != $Pager->getLastPage()): ?> - getIconNext()->getIcon(); ?> - getIconLast()->getIcon(); ?> - -
-
- -
-
    -
  • - -
  • -
  • - -
  • -
-
\ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc b/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc index 36608d98..841fa983 100644 --- a/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc +++ b/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc @@ -19,7 +19,7 @@ if (!isset($index)): $index = 0; endif; id="btn-add-getId(); ?>" type="button" class="btn-action mdl-button mdl-js-button mdl-button--fab mdl-button--mini-fab mdl-button--colored mdl-color--indigo-A200 mdl-js-ripple-effect" - data-nextaction-id="getOnCloseAction(); ?>" + data-nextaction="getOnCloseAction(); ?>" data-onclick="getOnClick(); ?>" getData() as $dataName => $dataValue): echo 'data-', $dataName, '=', '"', $dataValue, '"'; endforeach; ?>> getIcon()->getIcon(); ?> @@ -78,20 +78,21 @@ if (!isset($index)): $index = 0; endif; getIconBack()->getTitle(); ?> + getDataActionsMenu()) > 0): ?>
  • -
      + for="menu-getId(); ?>-menu-lower-right"> getDataActionsMenu() as $action): ?>
    • + getData() as $dataName => $dataValue): echo 'data-', $dataName, '=', '"', $dataValue, '"'; endforeach; ?>> getIcon()->getIcon(); ?>
    • diff --git a/app/modules/web/themes/material-blue/views/grid/datagrid-table-simple.inc b/app/modules/web/themes/material-blue/views/grid/datagrid-table-simple.inc index fa86caf5..95b8adf5 100644 --- a/app/modules/web/themes/material-blue/views/grid/datagrid-table-simple.inc +++ b/app/modules/web/themes/material-blue/views/grid/datagrid-table-simple.inc @@ -21,8 +21,4 @@ -getDataPagerTemplate(); ?> - - \ No newline at end of file +getDataPagerTemplate(); ?> \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/grid/datagrid-table.inc b/app/modules/web/themes/material-blue/views/grid/datagrid-table.inc index bc8d71e9..593b5c94 100644 --- a/app/modules/web/themes/material-blue/views/grid/datagrid-table.inc +++ b/app/modules/web/themes/material-blue/views/grid/datagrid-table.inc @@ -25,8 +25,4 @@ -getDataPagerTemplate(); ?> - - \ No newline at end of file +getDataPagerTemplate(); ?> \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/itemshow/userprofile.inc b/app/modules/web/themes/material-blue/views/itemshow/userprofile.inc index 66cf5f78..bd317816 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/userprofile.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/userprofile.inc @@ -1,6 +1,9 @@
      @@ -36,91 +39,91 @@ @@ -136,77 +139,77 @@ @@ -222,28 +225,28 @@ @@ -259,7 +262,7 @@ @@ -278,7 +281,7 @@
    • person - user_login; ?> + login; ?>
    • diff --git a/app/modules/web/themes/material-blue/views/noticeshow/notices.inc b/app/modules/web/themes/material-blue/views/noticeshow/notices.inc deleted file mode 100644 index 9c28e794..00000000 --- a/app/modules/web/themes/material-blue/views/noticeshow/notices.inc +++ /dev/null @@ -1,144 +0,0 @@ -. - */ - -/** @var \SP\DataModel\NoticeData $notice */ -/** @var \SP\Core\UI\ThemeIconsBase $icons */ -?> -
      -

      close

      - -
      - - - - - - - - - - - - - - - - - - - - - - isUserIsAdminApp() || $isDemo)): ?> - - - - - - - - - - - - - - - - - -
      - -
      - -
      - -
      - \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/notification/index.inc b/app/modules/web/themes/material-blue/views/notification/index.inc new file mode 100644 index 00000000..2edd0615 --- /dev/null +++ b/app/modules/web/themes/material-blue/views/notification/index.inc @@ -0,0 +1,3 @@ +includeTemplate('datagrid-grid', 'grid'); \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/notification/notification.inc b/app/modules/web/themes/material-blue/views/notification/notification.inc new file mode 100644 index 00000000..c32e4f65 --- /dev/null +++ b/app/modules/web/themes/material-blue/views/notification/notification.inc @@ -0,0 +1,126 @@ + +
      +

      close

      + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + +
      + +
      + +
      \ No newline at end of file diff --git a/lib/SP/Bootstrap.php b/lib/SP/Bootstrap.php index e54f6baf..acbaf5ef 100644 --- a/lib/SP/Bootstrap.php +++ b/lib/SP/Bootstrap.php @@ -42,21 +42,15 @@ use SP\Core\Exceptions\SPException; use SP\Core\Language; use SP\Core\Plugin\PluginUtil; use SP\Core\Session\Session; -use SP\Core\SessionFactory; use SP\Core\SessionUtil; use SP\Core\UI\Theme; use SP\Core\Upgrade\Upgrade; -use SP\Http\JsonResponse; use SP\Http\Request; -use SP\Log\Email; use SP\Log\Log; -use SP\Modules\Web\Controllers\MainController; -use SP\Mvc\View\Template; use SP\Storage\Database; use SP\Storage\DBUtil; use SP\Util\Checks; use SP\Util\HttpUtil; -use SP\Util\Json; use SP\Util\Util; defined('APP_ROOT') || die(); @@ -100,10 +94,6 @@ class Bootstrap * @var bool Indica si la versión de PHP es correcta */ private static $checkPhpVersion; - /** - * @var string - */ - private static $sourceScript; /** * @var Upgrade */ @@ -175,12 +165,10 @@ class Bootstrap $router->response()->body($err_msg); }); - $self = $this; - // Manejar URLs con módulo indicado $this->router->respond(['GET', 'POST'], '@/(index\.php)?', - function ($request, $response, $service) use ($self, $oops) { + function ($request, $response, $service) use ($oops) { try { /** @var \Klein\Request $request */ $route = filter_var($request->param('r', 'index/index'), FILTER_SANITIZE_STRING); @@ -209,10 +197,10 @@ class Bootstrap throw new RuntimeException($oops); } - $self->initializeCommon(); + $this->initializeCommon(); if (!in_array($controller, APP_PARTIAL_INIT, true)) { - $self->initializeApp(); + $this->initializeApp(); } else { // Do not keep the PHP's session opened Session::close(); @@ -520,17 +508,7 @@ class Bootstrap throw new InitializationException('Not installed'); -// if (self::$SUBURI !== '/index.php') { -// // FIXME -// $this->router->response()->redirect('index.php?r=install'); -// -// $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://'; -// -// $url = $protocol . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . self::$WEBROOT . '/index.php'; -// header("Location: $url"); -// exit(); -// } -// +// FIXME: // if ($this->session->getAuthCompleted()) { // session_destroy(); // @@ -538,11 +516,6 @@ class Bootstrap // return; // } // -// // Comprobar si sysPass está instalada o en modo mantenimiento -// $Controller = new MainController(); -// $Controller->getInstaller(); -// $Controller->view(); -// exit(); } } @@ -585,45 +558,43 @@ class Bootstrap // Timeout de sesión if ($lastActivity > 0 && !$inMaintenance - && (time() - $lastActivity) > $this->getSessionLifeTime() + && time() > ($lastActivity + $this->getSessionLifeTime()) ) { if ($this->router->request()->cookies()->get(session_name()) !== null) { $this->router->response()->cookie(session_name(), '', time() - 42000); } -// $this->wrLogoutInfo(); - SessionUtil::restart(); - return; - } + } else { - $sidStartTime = $this->session->getSidStartTime(); + $sidStartTime = $this->session->getSidStartTime(); - // Regenerar el Id de sesión periódicamente para evitar fijación - if ($sidStartTime === 0) { - // Intentar establecer el tiempo de vida de la sesión en PHP - @ini_set('session.gc_maxlifetime', $this->getSessionLifeTime()); + // Regenerar el Id de sesión periódicamente para evitar fijación + if ($sidStartTime === 0) { + // Intentar establecer el tiempo de vida de la sesión en PHP + @ini_set('session.gc_maxlifetime', $this->getSessionLifeTime()); - $this->session->setSidStartTime(time()); - $this->session->setStartActivity(time()); - } else if (!$inMaintenance - && time() - $sidStartTime > 120 - && $this->session->getUserData()->getId() > 0 - ) { - try { - CryptSession::reKey(); + $this->session->setSidStartTime(time()); + $this->session->setStartActivity(time()); + } else if (!$inMaintenance + && time() > ($sidStartTime + 120) + && $this->session->isLoggedIn() + ) { + try { + CryptSession::reKey($this->session); - // Recargar los permisos del perfil de usuario + // Recargar los permisos del perfil de usuario // $this->session->setUserProfile(Profile::getItem()->getById($this->session->getUserData()->getUserProfileId())); - } catch (CryptoException $e) { - debugLog($e->getMessage()); + } catch (CryptoException $e) { + debugLog($e->getMessage()); - SessionUtil::restart(); - return; + SessionUtil::restart(); + return; + } } - } - $this->session->setLastActivity(time()); + $this->session->setLastActivity(time()); + } } /** @@ -633,13 +604,8 @@ class Bootstrap */ private function getSessionLifeTime() { - $timeout = $this->session->getSessionTimeout(); - - if (null === $timeout) { - $configTimeout = $this->configData->getSessionTimeout(); - $this->session->setSessionTimeout($configTimeout); - - return $configTimeout; + if (($timeout = $this->session->getSessionTimeout()) === null) { + return $this->session->setSessionTimeout($this->configData->getSessionTimeout()); } return $timeout; @@ -653,44 +619,12 @@ class Bootstrap return self::$container; } - /** - * Devuelve un error utilizando la plantilla de error o en formato JSON - * - * @param string $message con la descripción del error - * @param string $hint opcional, con una ayuda sobre el error - * @param bool $headers - */ - public static function initError($message, $hint = '', $headers = false) - { - debugLog(__FUNCTION__); - debugLog(__($message)); - debugLog(__($hint)); - - if (Checks::isJson()) { - $JsonResponse = new JsonResponse(); - $JsonResponse->setDescription($message); - $JsonResponse->addMessage($hint); - Json::returnJson($JsonResponse); - } elseif ($headers === true) { - header('HTTP/1.1 503 Service Temporarily Unavailable'); - header('Status: 503 Service Temporarily Unavailable'); - header('Retry-After: 120'); - } - - SessionUtil::cleanSession(); - - $Tpl = new Template(); - $Tpl->append('errors', ['type' => SPException::CRITICAL, 'description' => __($message), 'hint' => __($hint)]); - - $Controller = new MainController($Tpl, 'error', !Checks::isAjax()); - $Controller->getError(); - } - /** * @param Container $container - * @param string $module - * @throws Core\Dic\ContainerException + * @param string $module * @throws InitializationException + * @throws \DI\DependencyException + * @throws \DI\NotFoundException */ public static function run(Container $container, $module = APP_MODULE) { @@ -705,58 +639,6 @@ class Bootstrap } } - /** - * Comprobar si hay que ejecutar acciones de URL después de realizar login. - * - * @return bool - */ - public function checkPostLoginActions() - { - $action = Request::analyze('a'); - - if ($action === '') { - return false; - } - - $Controller = new MainController(); - $Controller->doAction('postlogin.' . $action); - - return false; - } - - /** - * Comprobar si hay que ejecutar acciones de URL antes de presentar la pantalla de login. - * - * @return bool - */ - public function checkPreLoginActions() - { - $action = Request::analyze('a'); - - if ($action === '') { - return false; - } - - $Controller = new MainController(); - $Controller->doAction('prelogin.' . $action); - - return true; - } - - /** - * Comprobar el archivo que realiza el include necesita inicialización. - * - * @deprecated - * @returns bool - */ - private function checkInitSourceInclude() - { - self::$sourceScript = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_BASENAME); - $skipInit = ['js.php', 'css.php', 'api.php', 'ajax_getEnvironment.php', 'ajax_task.php']; - - return in_array(self::$sourceScript, $skipInit, true); - } - /** * Comprobar si es necesario actualizar componentes * @@ -785,53 +667,5 @@ class Bootstrap $LogMessage->addDetails(__('Versión', false), $version); $LogMessage->addDetails(__('Tipo', false), 'config'); $Log->writeLog(); - - Email::sendEmail($LogMessage); - } - - /** - * Comprobar si es necesario cerrar la sesión - */ - private function checkLogout() - { - if (Request::analyze('logout', false, true)) { - $this->goLogout(); - } - } - - /** - * Deslogar el usuario actual y eliminar la información de sesión. - * - * @deprecated - */ - private function goLogout() - { - $this->wrLogoutInfo(); - - SessionUtil::cleanSession(); - - SessionFactory::setLoggedOut(true); - - $Controller = new MainController(); - $Controller->getLogout(); - } - - /** - * Escribir la información de logout en el registro de eventos. - * - * @deprecated - */ - private function wrLogoutInfo() - { - $inactiveTime = abs(round((time() - $this->session->getLastActivity()) / 60, 2)); - $totalTime = abs(round((time() - $this->session->getStartActivity()) / 60, 2)); - - $Log = new Log(); - $LogMessage = $Log->getLogMessage(); - $LogMessage->setAction(__('Finalizar sesión', false)); - $LogMessage->addDetails(__('Usuario', false), $this->session->getUserData()->getLogin()); - $LogMessage->addDetails(__('Tiempo inactivo', false), $inactiveTime . ' min.'); - $LogMessage->addDetails(__('Tiempo total', false), $totalTime . ' min.'); - $Log->writeLog(); } } \ No newline at end of file diff --git a/lib/SP/Controller/ItemActionController.php b/lib/SP/Controller/ItemActionController.php index 4a74b002..0d66db42 100644 --- a/lib/SP/Controller/ItemActionController.php +++ b/lib/SP/Controller/ItemActionController.php @@ -35,7 +35,7 @@ use SP\Core\Messages\LogMessage; use SP\Core\SessionFactory; use SP\Core\Traits\InjectableTrait; use SP\DataModel\CustomFieldData; -use SP\DataModel\NoticeData; +use SP\DataModel\NotificationData; use SP\DataModel\PluginData; use SP\DataModel\PublicLinkData; use SP\Forms\AccountForm; @@ -43,7 +43,7 @@ use SP\Forms\AuthTokenForm; use SP\Forms\CategoryForm; use SP\Forms\ClientForm; use SP\Forms\CustomFieldDefForm; -use SP\Forms\NoticeForm; +use SP\Forms\NotificationForm; use SP\Forms\TagForm; use SP\Forms\UserForm; use SP\Forms\UserGroupForm; @@ -181,11 +181,11 @@ class ItemActionController implements ItemControllerInterface case ActionsInterface::LDAP_SYNC: $this->ldapImportAction(); break; - case ActionsInterface::NOTICE_USER_CHECK: - case ActionsInterface::NOTICE_USER_VIEW: - case ActionsInterface::NOTICE_USER_CREATE: - case ActionsInterface::NOTICE_USER_EDIT: - case ActionsInterface::NOTICE_USER_DELETE: + case ActionsInterface::NOTIFICATION_CHECK: + case ActionsInterface::NOTIFICATION_VIEW: + case ActionsInterface::NOTIFICATION_CREATE: + case ActionsInterface::NOTIFICATION_EDIT: + case ActionsInterface::NOTIFICATION_DELETE: $this->noticeAction(); break; case ActionsInterface::ACCOUNT_REQUEST: @@ -1110,28 +1110,28 @@ class ItemActionController implements ItemControllerInterface protected function noticeAction() { switch ($this->actionId) { - case ActionsInterface::NOTICE_USER_CHECK: + case ActionsInterface::NOTIFICATION_CHECK: Notice::getItem()->setChecked($this->itemId); $this->JsonResponse->setDescription(__('Notificación leída')); break; - case ActionsInterface::NOTICE_USER_CREATE: - $Form = new NoticeForm($this->itemId); + case ActionsInterface::NOTIFICATION_CREATE: + $Form = new NotificationForm($this->itemId); $Form->validate($this->actionId); Notice::getItem($Form->getItemData())->add(); $this->JsonResponse->setDescription(__('Notificación creada')); break; - case ActionsInterface::NOTICE_USER_EDIT: - $Form = new NoticeForm($this->itemId); + case ActionsInterface::NOTIFICATION_EDIT: + $Form = new NotificationForm($this->itemId); $Form->validate($this->actionId); Notice::getItem($Form->getItemData())->update(); $this->JsonResponse->setDescription(__('Notificación actualizada')); break; - case ActionsInterface::NOTICE_USER_DELETE: + case ActionsInterface::NOTIFICATION_DELETE: if (is_array($this->itemId)) { Notice::getItem()->deleteBatch($this->itemId); @@ -1199,7 +1199,7 @@ class ItemActionController implements ItemControllerInterface // Crear notificaciones foreach ($users as $user) { - $NoticeData = new NoticeData(); + $NoticeData = new NotificationData(); $NoticeData->setUserId($user); $NoticeData->setComponent('Accounts'); $NoticeData->setType(__('Solicitud')); diff --git a/lib/SP/Controller/NoticeShowController.php b/lib/SP/Controller/NoticeShowController.php index b668e163..ff864f40 100644 --- a/lib/SP/Controller/NoticeShowController.php +++ b/lib/SP/Controller/NoticeShowController.php @@ -28,7 +28,7 @@ defined('APP_ROOT') || die(); use SP\Core\Acl\ActionsInterface; use SP\Core\SessionUtil; -use SP\DataModel\NoticeData; +use SP\DataModel\NotificationData; use SP\Mgmt\Notices\Notice; use SP\Mgmt\Users\User; use SP\Modules\Web\Controllers\ControllerBase; @@ -83,16 +83,16 @@ class NoticeShowController extends ControllerBase implements ActionsInterface, I { try { switch ($this->actionId) { - case self::NOTICE_USER_VIEW: + case self::NOTIFICATION_VIEW: $this->view->assign('header', __('Ver Notificación')); $this->view->assign('isView', true); $this->getNotice(); break; - case self::NOTICE_USER_CREATE: + case self::NOTIFICATION_CREATE: $this->view->assign('header', __('Nueva Notificación')); $this->getNotice(); break; - case self::NOTICE_USER_EDIT: + case self::NOTIFICATION_EDIT: $this->view->assign('header', __('Editar Notificación')); $this->getNotice(); break; @@ -122,8 +122,8 @@ class NoticeShowController extends ControllerBase implements ActionsInterface, I $this->module = self::USER; $this->view->addTemplate('notices'); - $this->view->assign('notice', $this->itemId ? Notice::getItem()->getById($this->itemId) : new NoticeData()); - $this->view->assign('isDisabled', ($this->view->isDemo || $this->view->actionId === self::NOTICE_USER_VIEW) ? 'disabled' : ''); + $this->view->assign('notice', $this->itemId ? Notice::getItem()->getById($this->itemId) : new NotificationData()); + $this->view->assign('isDisabled', ($this->view->isDemo || $this->view->actionId === self::NOTIFICATION_VIEW) ? 'disabled' : ''); $this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : ''); if ($this->userData->isIsAdminApp()){ diff --git a/lib/SP/Controller/NoticesController.php b/lib/SP/Controller/NoticesController.php index 36eb587e..ec02daa1 100644 --- a/lib/SP/Controller/NoticesController.php +++ b/lib/SP/Controller/NoticesController.php @@ -73,7 +73,7 @@ class NoticesController extends GridTabControllerBase implements ActionsInterfac */ public function getUserNotices() { - $this->setAction(self::NOTICE_USER); + $this->setAction(self::NOTIFICATION); if (!$this->checkAccess()) { return; diff --git a/lib/SP/Controller/NoticesSearchController.php b/lib/SP/Controller/NoticesSearchController.php index 26c8370a..a4b01467 100644 --- a/lib/SP/Controller/NoticesSearchController.php +++ b/lib/SP/Controller/NoticesSearchController.php @@ -26,15 +26,13 @@ namespace SP\Controller; defined('APP_ROOT') || die(); -use SP\Config\Config; use SP\Controller\Grids\Notices; use SP\Core\Acl\ActionsInterface; use SP\Core\SessionUtil; -use SP\Mvc\View\Template; use SP\DataModel\ItemSearchData; use SP\Http\Request; use SP\Mgmt\Notices\NoticeSearch; -use SP\Util\Checks; +use SP\Mvc\View\Template; use SP\Util\Json; /** @@ -92,7 +90,7 @@ class NoticesSearchController extends GridItemsSearchController implements Actio try { switch ($this->actionId) { - case ActionsInterface::NOTICE_USER_SEARCH: + case ActionsInterface::NOTIFICATION_SEARCH: $this->getNoticesUser(); break; default: @@ -117,7 +115,7 @@ class NoticesSearchController extends GridItemsSearchController implements Actio */ protected function getNoticesUser() { - $this->setAction(self::NOTICE_USER_SEARCH); + $this->setAction(self::NOTIFICATION_SEARCH); if (!$this->checkAccess()) { return; @@ -132,7 +130,7 @@ class NoticesSearchController extends GridItemsSearchController implements Actio $this->updatePager($Grid->getPager(), $this->ItemSearchData); $this->view->assign('data', $Grid); - $this->view->assign('actionId', self::NOTICE_USER); + $this->view->assign('actionId', self::NOTIFICATION); $this->JsonResponse->setStatus(0); } diff --git a/lib/SP/Core/Acl/Acl.php b/lib/SP/Core/Acl/Acl.php index 665c887f..d1fc2f0a 100644 --- a/lib/SP/Core/Acl/Acl.php +++ b/lib/SP/Core/Acl/Acl.php @@ -199,9 +199,9 @@ class Acl implements ActionsInterface case self::EVENTLOG: case self::EVENTLOG_SEARCH: return $userProfile->isEvl(); - case self::NOTICE: - case self::NOTICE_USER: - case self::NOTICE_USER_SEARCH: + case self::NOTIFICATION: + case self::NOTIFICATION_SEARCH: + case self::NOTIFICATION_CHECK: return true; } diff --git a/lib/SP/Core/Acl/Actions.php b/lib/SP/Core/Acl/Actions.php index a399177d..abce7f23 100644 --- a/lib/SP/Core/Acl/Actions.php +++ b/lib/SP/Core/Acl/Actions.php @@ -152,7 +152,7 @@ class Actions public function getActionById($id) { if (!isset($this->actions[$id])) { - throw new ActionNotFoundException(__u('Acción no encontrada'), ActionNotFoundException::ERROR); + throw new ActionNotFoundException(__u('Acción no encontrada')); } return $this->actions[$id]; diff --git a/lib/SP/Core/Acl/ActionsInterface.php b/lib/SP/Core/Acl/ActionsInterface.php index d6a0c165..f64d67f5 100644 --- a/lib/SP/Core/Acl/ActionsInterface.php +++ b/lib/SP/Core/Acl/ActionsInterface.php @@ -142,14 +142,13 @@ interface ActionsInterface const PREFERENCE = 740; const PREFERENCE_GENERAL = 741; const PREFERENCE_SECURITY = 742; - const NOTICE = 760; - const NOTICE_USER = 761; - const NOTICE_USER_VIEW = 7610; - const NOTICE_USER_CREATE = 7611; - const NOTICE_USER_EDIT = 7612; - const NOTICE_USER_DELETE = 7613; - const NOTICE_USER_CHECK = 7614; - const NOTICE_USER_SEARCH = 7615; + const NOTIFICATION = 76; + const NOTIFICATION_VIEW = 760; + const NOTIFICATION_CREATE = 761; + const NOTIFICATION_EDIT = 762; + const NOTIFICATION_DELETE = 763; + const NOTIFICATION_CHECK = 764; + const NOTIFICATION_SEARCH = 765; const CONFIG = 1000; const CONFIG_GENERAL = 1001; const ACCOUNT_CONFIG = 1010; diff --git a/lib/SP/Core/Crypt/Session.php b/lib/SP/Core/Crypt/Session.php index 5858eaaa..5bd1a01e 100644 --- a/lib/SP/Core/Crypt/Session.php +++ b/lib/SP/Core/Crypt/Session.php @@ -38,6 +38,7 @@ class Session * * @return string * @throws \Defuse\Crypto\Exception\CryptoException + * @todo Use session from DI */ public static function getSessionKey() { @@ -49,20 +50,29 @@ class Session * * @param $data * @throws \Defuse\Crypto\Exception\CryptoException + * @todo Use session from DI */ public static function saveSessionKey($data) { - $Vault = new Vault(); - CoreSession::setVault($Vault->saveData($data)); + CoreSession::setVault((new Vault())->saveData($data)); } /** * Regenerar la clave de sesión * + * @param \SP\Core\Session\Session $session * @throws \Defuse\Crypto\Exception\CryptoException */ - public static function reKey() + public static function reKey(\SP\Core\Session\Session $session) { - CoreSession::setVault(CoreSession::getVault()->reKey()); + debugLog(__METHOD__); + + $oldSeed = session_id() . $session->getSidStartTime(); + + session_regenerate_id(true); + + $newSeed = session_id() . $session->setSidStartTime(time()); + + CoreSession::setVault(CoreSession::getVault()->reKey($newSeed, $oldSeed)); } } \ No newline at end of file diff --git a/lib/SP/Core/Crypt/Vault.php b/lib/SP/Core/Crypt/Vault.php index e4c7cfd9..c0e35be0 100644 --- a/lib/SP/Core/Crypt/Vault.php +++ b/lib/SP/Core/Crypt/Vault.php @@ -25,7 +25,6 @@ namespace SP\Core\Crypt; use SP\Core\SessionFactory as CoreSession; -use SP\Core\SessionUtil; /** * Class Vault @@ -54,18 +53,17 @@ class Vault /** * Regenerar la clave de sesión * - * @param string $key + * @param string $newSeed + * @param string $oldSeed * @return Vault * @throws \Defuse\Crypto\Exception\CryptoException */ - public function reKey($key = null) + public function reKey($newSeed, $oldSeed) { $this->timeUpdated = time(); - $sessionMPass = $this->getData($key); + $sessionMPass = $this->getData($oldSeed); - SessionUtil::regenerate(); - - $this->saveData($sessionMPass, $key); + $this->saveData($sessionMPass, $newSeed); return $this; } @@ -80,9 +78,8 @@ class Vault public function getData($key = null) { $key = $key ?: $this->getKey(); - $securedKey = Crypt::unlockSecuredKey($this->key, $key); - return Crypt::decrypt($this->data, $securedKey, $key); + return Crypt::decrypt($this->data, Crypt::unlockSecuredKey($this->key, $key), $key); } /** diff --git a/lib/SP/Core/Messages/MessageBase.php b/lib/SP/Core/Messages/MessageBase.php index 1ad43ed4..57a398b7 100644 --- a/lib/SP/Core/Messages/MessageBase.php +++ b/lib/SP/Core/Messages/MessageBase.php @@ -44,6 +44,14 @@ abstract class MessageBase implements MessageInterface */ protected $description = []; + /** + * @return static + */ + public static function factory() + { + return new static(); + } + /** * @return string */ @@ -54,10 +62,13 @@ abstract class MessageBase implements MessageInterface /** * @param string $title + * @return MessageBase */ public function setTitle($title) { $this->title = $title; + + return $this; } /** @@ -70,22 +81,28 @@ abstract class MessageBase implements MessageInterface /** * @param array $description + * @return MessageBase */ public function setDescription(array $description) { $this->description = $description; + + return $this; } /** * @param string $description + * @return MessageBase */ public function addDescription($description) { $this->description[] = $description; + + return $this; } /** - * @return string + * @return array */ public function getFooter() { @@ -94,9 +111,12 @@ abstract class MessageBase implements MessageInterface /** * @param array $footer + * @return MessageBase */ public function setFooter(array $footer) { $this->footer = $footer; + + return $this; } } \ No newline at end of file diff --git a/lib/SP/Core/Session/Session.php b/lib/SP/Core/Session/Session.php index 25ffa99e..d39886bc 100644 --- a/lib/SP/Core/Session/Session.php +++ b/lib/SP/Core/Session/Session.php @@ -47,6 +47,18 @@ class Session return self::$isLocked; } + /** + * Closes session + */ + public static function close() + { + debugLog('Session closed'); + + session_write_close(); + + self::$isLocked = true; + } + /** * Devuelve el tema visual utilizado en sysPass * @@ -61,7 +73,7 @@ class Session * Devolver una variable de sesión * * @param string $key - * @param mixed $default + * @param mixed $default * @return mixed */ protected function getSessionKey($key, $default = null) @@ -86,13 +98,13 @@ class Session /** * Establecer una variable de sesión * - * @param string $key El nombre de la variable - * @param mixed $value El valor de la variable + * @param string $key El nombre de la variable + * @param mixed $value El valor de la variable * @return mixed */ protected function setSessionKey($key, $value) { - if (self::$isLocked ) { + if (self::$isLocked) { debugLog('Session locked; key=' . $key); } else { $_SESSION[$key] = $value; @@ -101,18 +113,6 @@ class Session return $value; } - /** - * Closes session - */ - public static function close() - { - debugLog('Session closed'); - - session_write_close(); - - self::$isLocked = true; - } - /** * Establecer la configuración * @@ -350,10 +350,13 @@ class Session * Establecer el timeout de la sesión * * @param int $timeout El valor en segundos + * @return int */ public function setSessionTimeout($timeout) { $this->setSessionKey('sessionTimeout', $timeout); + + return $timeout; } /** @@ -390,10 +393,13 @@ class Session * Establece la hora de creación del SID * * @param $time int La marca de hora + * @return int */ public function setSidStartTime($time) { $this->setSessionKey('sidStartTime', $time); + + return $time; } /** @@ -410,10 +416,13 @@ class Session * Establece la hora de inicio de actividad * * @param $time int La marca de hora + * @return int */ public function setStartActivity($time) { $this->setSessionKey('startActivity', $time); + + return $time; } /** @@ -455,4 +464,24 @@ class Session { $this->setSessionKey('accountcolor', $color); } + + /** + * Devuelve si se ha realizado un cierre de sesión + * + * @return bool + */ + public function getLoggedOut() + { + return $this->getSessionKey('loggedout', false); + } + + /** + * Establecer si se ha realizado un cierre de sesión + * + * @param bool $loggedout + */ + public function setLoggedOut($loggedout = false) + { + $this->setSessionKey('loggedout', $loggedout); + } } diff --git a/lib/SP/Core/SessionUtil.php b/lib/SP/Core/SessionUtil.php index 61f2447b..66764831 100644 --- a/lib/SP/Core/SessionUtil.php +++ b/lib/SP/Core/SessionUtil.php @@ -131,42 +131,20 @@ class SessionUtil foreach ($_SESSION as $key => $value) { unset($_SESSION[$key]); } - -// Session::unsetSessionKey('userData'); -// Session::unsetSessionKey('usrprofile'); -// Session::unsetSessionKey('searchFilters'); -// Session::unsetSessionKey('updated'); -// Session::unsetSessionKey('sessionTimeout'); -// Session::unsetSessionKey('reload'); -// Session::unsetSessionKey('sk'); -// Session::unsetSessionKey('mPass'); -// Session::unsetSessionKey('mPassPwd'); -// Session::unsetSessionKey('mPassIV'); -// Session::unsetSessionKey('sidStartTime'); -// Session::unsetSessionKey('startActivity'); -// Session::unsetSessionKey('lastActivity'); -// Session::unsetSessionKey('lastAccountId'); -// Session::unsetSessionKey('theme'); -// Session::unsetSessionKey('2fapass'); -// Session::unsetSessionKey('pubkey'); -// Session::unsetSessionKey('locale'); -// Session::unsetSessionKey('userpreferences'); -// Session::unsetSessionKey('tempmasterpass'); -// Session::unsetSessionKey('accountcolor'); -// Session::unsetSessionKey('curlcookiesession'); -// Session::unsetSessionKey('dokuwikisession'); -// Session::unsetSessionKey('sessiontype'); -// Session::unsetSessionKey('config'); -// Session::unsetSessionKey('configTime'); } /** * Regenerad el ID de sesión + * + * @param Session $session */ - public static function regenerate() + public static function regenerate(Session $session) { + debugLog(__METHOD__); + session_regenerate_id(true); - SessionFactory::setSidStartTime(time()); + + $session->setSidStartTime(time()); } /** diff --git a/lib/SP/DataModel/NoticeData.php b/lib/SP/DataModel/NotificationData.php similarity index 97% rename from lib/SP/DataModel/NoticeData.php rename to lib/SP/DataModel/NotificationData.php index 7f647339..43aeca5a 100644 --- a/lib/SP/DataModel/NoticeData.php +++ b/lib/SP/DataModel/NotificationData.php @@ -31,7 +31,7 @@ use SP\Core\Messages\MessageInterface; * * @package SP\DataModel */ -class NoticeData implements DataModelInterface +class NotificationData implements DataModelInterface { /** * @var int @@ -60,7 +60,7 @@ class NoticeData implements DataModelInterface /** * @var int */ - public $userId = 0; + public $userId; /** * @var bool */ @@ -139,7 +139,7 @@ class NoticeData implements DataModelInterface */ public function getDate() { - return $this->date; + return (int)$this->date; } /** diff --git a/lib/SP/DataModel/UserProfileData.php b/lib/SP/DataModel/UserProfileData.php index 2184d88d..801d96e1 100644 --- a/lib/SP/DataModel/UserProfileData.php +++ b/lib/SP/DataModel/UserProfileData.php @@ -91,6 +91,6 @@ class UserProfileData extends DataModelBase implements DataModelInterface */ public function setProfile(ProfileData $profile) { - $this->profile = serialize($profile); + $this->profile = $profile; } } \ No newline at end of file diff --git a/lib/SP/Forms/NoticeForm.php b/lib/SP/Forms/NotificationForm.php similarity index 56% rename from lib/SP/Forms/NoticeForm.php rename to lib/SP/Forms/NotificationForm.php index bbd3a24e..f3972ef5 100644 --- a/lib/SP/Forms/NoticeForm.php +++ b/lib/SP/Forms/NotificationForm.php @@ -27,20 +27,20 @@ namespace SP\Forms; use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\ValidationException; use SP\Core\Messages\NoticeMessage; -use SP\DataModel\NoticeData; +use SP\DataModel\NotificationData; use SP\Http\Request; /** - * Class NoticeForm + * Class NotificationForm * * @package SP\Forms */ -class NoticeForm extends FormBase implements FormInterface +class NotificationForm extends FormBase implements FormInterface { /** - * @var NoticeData + * @var NotificationData */ - protected $noticeData; + protected $notificationData; /** * Validar el formulario @@ -52,8 +52,8 @@ class NoticeForm extends FormBase implements FormInterface public function validate($action) { switch ($action) { - case ActionsInterface::NOTICE_USER_CREATE: - case ActionsInterface::NOTICE_USER_EDIT: + case ActionsInterface::NOTIFICATION_CREATE: + case ActionsInterface::NOTIFICATION_EDIT: $this->analyzeRequestData(); $this->checkCommon(); break; @@ -69,19 +69,17 @@ class NoticeForm extends FormBase implements FormInterface */ protected function analyzeRequestData() { - $Description = new NoticeMessage(); - $Description->addDescription(Request::analyze('notice_description')); + $this->notificationData = new NotificationData(); + $this->notificationData->setId($this->itemId); + $this->notificationData->setType(Request::analyze('notification_type')); + $this->notificationData->setComponent(Request::analyze('notification_component')); + $this->notificationData->setDescription(NoticeMessage::factory()->addDescription(Request::analyze('notification_description'))); + $this->notificationData->setUserId(Request::analyze('notification_user', 0)); + $this->notificationData->setChecked(Request::analyze('notification_checkout', 0, false, 1)); - $this->noticeData = new NoticeData(); - $this->noticeData->setId($this->itemId); - $this->noticeData->setType(Request::analyze('notice_type')); - $this->noticeData->setComponent(Request::analyze('notice_component')); - $this->noticeData->setDescription($Description); - $this->noticeData->setUserId(Request::analyze('notice_user', 0)); - - if ($this->noticeData->getUserId() === 0) { - $this->noticeData->setOnlyAdmin(Request::analyze('notice_onlyadmin', 0, false, 1)); - $this->noticeData->setSticky(Request::analyze('notice_sticky', 0, false, 1)); + if ($this->session->getUserData()->getIsAdminApp() && $this->notificationData->getUserId() === 0) { + $this->notificationData->setOnlyAdmin(Request::analyze('notification_onlyadmin', 0, false, 1)); + $this->notificationData->setSticky(Request::analyze('notification_sticky', 0, false, 1)); } } @@ -90,30 +88,30 @@ class NoticeForm extends FormBase implements FormInterface */ private function checkCommon() { - if (!$this->noticeData->getComponent()) { + if (!$this->notificationData->getComponent()) { throw new ValidationException(__u('Es necesario un componente')); } - if (!$this->noticeData->getType()) { + if (!$this->notificationData->getType()) { throw new ValidationException(__u('Es necesario un tipo')); } - if (!$this->noticeData->getDescription()) { + if (!$this->notificationData->getDescription()) { throw new ValidationException(__u('Es necesaria una descripción')); } - if (!$this->noticeData->getUserId() - && !$this->noticeData->isOnlyAdmin() - && !$this->noticeData->isSticky()) { + if (!$this->notificationData->getUserId() + && !$this->notificationData->isOnlyAdmin() + && !$this->notificationData->isSticky()) { throw new ValidationException(__u('Es necesario un destinatario')); } } /** - * @return NoticeData + * @return NotificationData */ public function getItemData() { - return $this->noticeData; + return $this->notificationData; } } \ No newline at end of file diff --git a/lib/SP/Forms/UserProfileForm.php b/lib/SP/Forms/UserProfileForm.php index bee2ce1f..f2818d67 100644 --- a/lib/SP/Forms/UserProfileForm.php +++ b/lib/SP/Forms/UserProfileForm.php @@ -27,6 +27,7 @@ namespace SP\Forms; use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ProfileData; +use SP\DataModel\UserProfileData; use SP\Http\Request; /** @@ -37,9 +38,9 @@ use SP\Http\Request; class UserProfileForm extends FormBase implements FormInterface { /** - * @var ProfileData + * @var UserProfileData */ - protected $profileData; + protected $userProfileData; /** * Validar el formulario @@ -68,38 +69,41 @@ class UserProfileForm extends FormBase implements FormInterface */ protected function analyzeRequestData() { - $this->profileData = new ProfileData(); - $this->profileData->setName(Request::analyze('profile_name')); - $this->profileData->setId($this->itemId); - $this->profileData->setAccAdd(Request::analyze('profile_accadd', 0, false, 1)); - $this->profileData->setAccView(Request::analyze('profile_accview', 0, false, 1)); - $this->profileData->setAccViewPass(Request::analyze('profile_accviewpass', 0, false, 1)); - $this->profileData->setAccViewHistory(Request::analyze('profile_accviewhistory', 0, false, 1)); - $this->profileData->setAccEdit(Request::analyze('profile_accedit', 0, false, 1)); - $this->profileData->setAccEditPass(Request::analyze('profile_acceditpass', 0, false, 1)); - $this->profileData->setAccDelete(Request::analyze('profile_accdel', 0, false, 1)); - $this->profileData->setAccFiles(Request::analyze('profile_accfiles', 0, false, 1)); - $this->profileData->setAccPublicLinks(Request::analyze('profile_accpublinks', 0, false, 1)); - $this->profileData->setAccPrivate(Request::analyze('profile_accprivate', 0, false, 1)); - $this->profileData->setAccPrivateGroup(Request::analyze('profile_accprivategroup', 0, false, 1)); - $this->profileData->setAccPermission(Request::analyze('profile_accpermissions', 0, false, 1)); - $this->profileData->setAccGlobalSearch(Request::analyze('profile_accglobalsearch', 0, false, 1)); - $this->profileData->setConfigGeneral(Request::analyze('profile_config', 0, false, 1)); - $this->profileData->setConfigEncryption(Request::analyze('profile_configmpw', 0, false, 1)); - $this->profileData->setConfigBackup(Request::analyze('profile_configback', 0, false, 1)); - $this->profileData->setConfigImport(Request::analyze('profile_configimport', 0, false, 1)); - $this->profileData->setMgmCategories(Request::analyze('profile_categories', 0, false, 1)); - $this->profileData->setMgmCustomers(Request::analyze('profile_customers', 0, false, 1)); - $this->profileData->setMgmCustomFields(Request::analyze('profile_customfields', 0, false, 1)); - $this->profileData->setMgmUsers(Request::analyze('profile_users', 0, false, 1)); - $this->profileData->setMgmGroups(Request::analyze('profile_groups', 0, false, 1)); - $this->profileData->setMgmProfiles(Request::analyze('profile_profiles', 0, false, 1)); - $this->profileData->setMgmApiTokens(Request::analyze('profile_apitokens', 0, false, 1)); - $this->profileData->setMgmPublicLinks(Request::analyze('profile_publinks', 0, false, 1)); - $this->profileData->setMgmAccounts(Request::analyze('profile_accounts', 0, false, 1)); - $this->profileData->setMgmFiles(Request::analyze('profile_files', 0, false, 1)); - $this->profileData->setMgmTags(Request::analyze('profile_tags', 0, false, 1)); - $this->profileData->setEvl(Request::analyze('profile_eventlog', 0, false, 1)); + $profileData = new ProfileData(); + $profileData->setAccAdd(Request::analyze('profile_accadd', 0, false, 1)); + $profileData->setAccView(Request::analyze('profile_accview', 0, false, 1)); + $profileData->setAccViewPass(Request::analyze('profile_accviewpass', 0, false, 1)); + $profileData->setAccViewHistory(Request::analyze('profile_accviewhistory', 0, false, 1)); + $profileData->setAccEdit(Request::analyze('profile_accedit', 0, false, 1)); + $profileData->setAccEditPass(Request::analyze('profile_acceditpass', 0, false, 1)); + $profileData->setAccDelete(Request::analyze('profile_accdel', 0, false, 1)); + $profileData->setAccFiles(Request::analyze('profile_accfiles', 0, false, 1)); + $profileData->setAccPublicLinks(Request::analyze('profile_accpublinks', 0, false, 1)); + $profileData->setAccPrivate(Request::analyze('profile_accprivate', 0, false, 1)); + $profileData->setAccPrivateGroup(Request::analyze('profile_accprivategroup', 0, false, 1)); + $profileData->setAccPermission(Request::analyze('profile_accpermissions', 0, false, 1)); + $profileData->setAccGlobalSearch(Request::analyze('profile_accglobalsearch', 0, false, 1)); + $profileData->setConfigGeneral(Request::analyze('profile_config', 0, false, 1)); + $profileData->setConfigEncryption(Request::analyze('profile_configmpw', 0, false, 1)); + $profileData->setConfigBackup(Request::analyze('profile_configback', 0, false, 1)); + $profileData->setConfigImport(Request::analyze('profile_configimport', 0, false, 1)); + $profileData->setMgmCategories(Request::analyze('profile_categories', 0, false, 1)); + $profileData->setMgmCustomers(Request::analyze('profile_customers', 0, false, 1)); + $profileData->setMgmCustomFields(Request::analyze('profile_customfields', 0, false, 1)); + $profileData->setMgmUsers(Request::analyze('profile_users', 0, false, 1)); + $profileData->setMgmGroups(Request::analyze('profile_groups', 0, false, 1)); + $profileData->setMgmProfiles(Request::analyze('profile_profiles', 0, false, 1)); + $profileData->setMgmApiTokens(Request::analyze('profile_apitokens', 0, false, 1)); + $profileData->setMgmPublicLinks(Request::analyze('profile_publinks', 0, false, 1)); + $profileData->setMgmAccounts(Request::analyze('profile_accounts', 0, false, 1)); + $profileData->setMgmFiles(Request::analyze('profile_files', 0, false, 1)); + $profileData->setMgmTags(Request::analyze('profile_tags', 0, false, 1)); + $profileData->setEvl(Request::analyze('profile_eventlog', 0, false, 1)); + + $this->userProfileData = new UserProfileData(); + $this->userProfileData->setName(Request::analyze('profile_name')); + $this->userProfileData->setId($this->itemId); + $this->userProfileData->setProfile($profileData); } /** @@ -107,16 +111,16 @@ class UserProfileForm extends FormBase implements FormInterface */ protected function checkCommon() { - if (!$this->profileData->getName()) { + if (!$this->userProfileData->getName()) { throw new ValidationException(__u('Es necesario un nombre de perfil')); } } /** - * @return ProfileData + * @return UserProfileData */ public function getItemData() { - return $this->profileData; + return $this->userProfileData; } } \ No newline at end of file diff --git a/lib/SP/Mgmt/Notices/Notice.php b/lib/SP/Mgmt/Notices/Notice.php index b96a3d2e..8dea30d3 100644 --- a/lib/SP/Mgmt/Notices/Notice.php +++ b/lib/SP/Mgmt/Notices/Notice.php @@ -26,7 +26,7 @@ namespace SP\Mgmt\Notices; use SP\Core\Exceptions\SPException; use SP\Core\SessionFactory; -use SP\DataModel\NoticeData; +use SP\DataModel\NotificationData; use SP\Mgmt\ItemInterface; use SP\Mgmt\ItemTrait; use SP\Storage\DbWrapper; @@ -36,8 +36,8 @@ use SP\Storage\QueryData; * Class Notice * * @package SP\Mgmt\Notices - * @property NoticeData $itemData - * @method NoticeData getItemData() + * @property NotificationData $itemData + * @method NotificationData getItemData() */ class Notice extends NoticeBase implements ItemInterface { @@ -50,7 +50,7 @@ class Notice extends NoticeBase implements ItemInterface public function add() { $query = /** @lang SQL */ - 'INSERT INTO Notice + 'INSERT INTO Notification SET type = ?, component = ?, description = ?, @@ -84,10 +84,10 @@ class Notice extends NoticeBase implements ItemInterface */ public function delete($id) { - $query = 'DELETE FROM Notice WHERE id = ? AND BIN(sticky) = 0 LIMIT 1'; + $query = 'DELETE FROM Notification WHERE id = ? AND BIN(sticky) = 0 LIMIT 1'; if (SessionFactory::getUserData()->isIsAdminApp()) { - $query = 'DELETE FROM Notice WHERE id = ? LIMIT 1'; + $query = 'DELETE FROM Notification WHERE id = ? LIMIT 1'; } $Data = new QueryData(); @@ -111,7 +111,7 @@ class Notice extends NoticeBase implements ItemInterface public function update() { $query = /** @lang SQL */ - 'UPDATE Notice + 'UPDATE Notification SET type = ?, component = ?, description = ?, @@ -140,7 +140,7 @@ class Notice extends NoticeBase implements ItemInterface /** * @param $id int - * @return NoticeData + * @return NotificationData * @throws SPException */ public function getById($id) @@ -155,7 +155,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice + FROM Notification WHERE id = ? LIMIT 1'; $Data = new QueryData(); @@ -173,7 +173,7 @@ class Notice extends NoticeBase implements ItemInterface } /** - * @return NoticeData[] + * @return NotificationData[] * @throws \SP\Core\Exceptions\SPException */ public function getAll() @@ -188,7 +188,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice'; + FROM Notification'; $Data = new QueryData(); $Data->setQuery($query); @@ -238,7 +238,7 @@ class Notice extends NoticeBase implements ItemInterface public function setChecked($id) { $query = /** @lang SQL */ - 'UPDATE Notice SET checked = 1 WHERE id = ? LIMIT 1'; + 'UPDATE Notification SET checked = 1 WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); @@ -269,7 +269,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice + FROM Notification WHERE component = ? AND (UNIX_TIMESTAMP() - date) <= 86400 AND userId = ?'; @@ -290,7 +290,7 @@ class Notice extends NoticeBase implements ItemInterface } /** - * @return NoticeData[] + * @return NotificationData[] * @throws \SP\Core\Exceptions\SPException */ public function getAllForUser() @@ -305,7 +305,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice + FROM Notification WHERE userId = ? OR (userId = NULL AND BIN(onlyAdmin) = 0) OR BIN(sticky) = 1 ORDER BY date DESC '; @@ -324,7 +324,7 @@ class Notice extends NoticeBase implements ItemInterface } /** - * @return NoticeData[] + * @return NotificationData[] * @throws SPException */ public function getAllActiveForUser() @@ -339,7 +339,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice + FROM Notification WHERE (userId = ? OR BIN(sticky) = 1) AND BIN(onlyAdmin) = 0 AND BIN(checked) = 0 @@ -377,7 +377,7 @@ class Notice extends NoticeBase implements ItemInterface BIN(checked) AS notice_checked, BIN(sticky) as notice_sticky, BIN(onlyAdmin) AS notice_onlyAdmin - FROM Notice + FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; $Data = new QueryData(); diff --git a/lib/SP/Mgmt/Notices/NoticeBase.php b/lib/SP/Mgmt/Notices/NoticeBase.php index a699876b..8543b477 100644 --- a/lib/SP/Mgmt/Notices/NoticeBase.php +++ b/lib/SP/Mgmt/Notices/NoticeBase.php @@ -27,7 +27,7 @@ namespace SP\Mgmt\Notices; defined('APP_ROOT') || die(); use SP\Core\Exceptions\InvalidClassException; -use SP\DataModel\NoticeData; +use SP\DataModel\NotificationData; use SP\Mgmt\ItemBaseInterface; use SP\Mgmt\ItemBaseTrait; @@ -48,6 +48,6 @@ abstract class NoticeBase implements ItemBaseInterface */ protected function init() { - $this->setDataModel(NoticeData::class); + $this->setDataModel(NotificationData::class); } } \ No newline at end of file diff --git a/lib/SP/Mvc/Controller/ControllerTrait.php b/lib/SP/Mvc/Controller/ControllerTrait.php index ece50917..52f4522f 100644 --- a/lib/SP/Mvc/Controller/ControllerTrait.php +++ b/lib/SP/Mvc/Controller/ControllerTrait.php @@ -74,8 +74,9 @@ trait ControllerTrait protected function checkSecurityToken(Session $session) { $sk = Request::analyze('sk'); + $sessionKey = $session->getSecurityKey(); - if (!$sk || (null !== $session->getSecurityKey() && $session->getSecurityKey() === $sk)) { + if (!$sk || (null !== $sessionKey && $sessionKey !== $sk)) { $this->invalidAction(); } } diff --git a/lib/SP/Mvc/Controller/CrudControllerInterface.php b/lib/SP/Mvc/Controller/CrudControllerInterface.php index 7014ef56..77856cb3 100644 --- a/lib/SP/Mvc/Controller/CrudControllerInterface.php +++ b/lib/SP/Mvc/Controller/CrudControllerInterface.php @@ -38,7 +38,7 @@ interface CrudControllerInterface * * @param $id */ - public function deleteAction($id); + public function deleteAction($id = null); /** * Saves create action diff --git a/lib/SP/Mvc/View/Template.php b/lib/SP/Mvc/View/Template.php index e291b605..385fbd50 100644 --- a/lib/SP/Mvc/View/Template.php +++ b/lib/SP/Mvc/View/Template.php @@ -28,7 +28,6 @@ defined('APP_ROOT') || die(); use SP\Core\Exceptions\FileNotFoundException; use SP\Core\Exceptions\InvalidArgumentException; -use SP\Core\Exceptions\SPException; use SP\Core\Traits\InjectableTrait; use SP\Core\UI\Theme; use SP\Core\UI\ThemeInterface; @@ -124,26 +123,12 @@ class Template $templateFile = $this->theme->getViewsPath() . DIRECTORY_SEPARATOR . (null === $base ? $this->base : $base) . DIRECTORY_SEPARATOR . $template . self::TEMPLATE_EXTENSION; } -// $base = null !== $base ? $base : $this->base; -// -// if (null !== $base) { -// $template = $base . DIRECTORY_SEPARATOR . $template . '.inc'; -// -// $useBase = is_readable($template); -// } elseif (null !== $this->base) { -// $template = $this->base . DIRECTORY_SEPARATOR . $template . '.inc'; -// -// $useBase = is_readable($template); -// } else { -// $template .= '.inc'; -// } - if (!is_readable($templateFile)) { $msg = sprintf(__('No es posible obtener la plantilla "%s" : %s'), $templateFile, $template); debugLog($msg); - throw new FileNotFoundException(SPException::ERROR, $msg); + throw new FileNotFoundException($msg); } return $templateFile; @@ -306,7 +291,7 @@ class Template if (!array_key_exists($name, $this->vars)) { debugLog(sprintf(__('No es posible obtener la variable "%s"'), $name)); - throw new InvalidArgumentException(SPException::ERROR, sprintf(__('No es posible obtener la variable "%s"'), $name)); + throw new InvalidArgumentException(sprintf(__('No es posible obtener la variable "%s"'), $name)); } return $this->vars[$name]; @@ -351,7 +336,7 @@ class Template if (!array_key_exists($name, $this->vars)) { debugLog(sprintf(__('No es posible destruir la variable "%s"'), $name)); - throw new InvalidArgumentException(SPException::ERROR, sprintf(__('No es posible destruir la variable "%s"'), $name)); + throw new InvalidArgumentException(sprintf(__('No es posible destruir la variable "%s"'), $name)); } unset($this->vars[$name]); @@ -368,7 +353,7 @@ class Template public function render() { if (count($this->files) === 0) { - throw new FileNotFoundException(SPException::ERROR, __('La plantilla no contiene archivos')); + throw new FileNotFoundException(__u('La plantilla no contiene archivos')); } extract($this->vars, EXTR_SKIP); diff --git a/lib/SP/Repositories/Account/AccountFavoriteRepository.php b/lib/SP/Repositories/Account/AccountFavoriteRepository.php new file mode 100644 index 00000000..b9d4b146 --- /dev/null +++ b/lib/SP/Repositories/Account/AccountFavoriteRepository.php @@ -0,0 +1,94 @@ +. + */ + +namespace SP\Repositories\Account; + +use SP\Repositories\Repository; +use SP\Storage\DbWrapper; +use SP\Storage\QueryData; + +/** + * Class AccountFavoriteRepository + * + * @package SP\Repositories\Account + */ +class AccountFavoriteRepository extends Repository +{ + /** + * Obtener un array con los Ids de cuentas favoritas + * + * @param $id int El Id de usuario + * @return array + */ + public function getForUserId($id) + { + $queryData = new QueryData(); + $queryData->setQuery('SELECT accountId FROM AccountToFavorite WHERE userId = ?'); + $queryData->addParam($id); + $queryData->setUseKeyPair(true); + + return DbWrapper::getResultsArray($queryData, $this->db); + } + + /** + * Añadir una cuenta a la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * @return bool + * @throws \SP\Core\Exceptions\SPException + */ + public function add($accountId, $userId) + { + $queryData = new QueryData(); + $queryData->setQuery('INSERT INTO AccountToFavorite SET accountId = ?, userId = ?'); + $queryData->addParam($accountId); + $queryData->addParam($userId); + $queryData->setOnErrorMessage(__u('Error al añadir favorito')); + + return DbWrapper::getQuery($queryData, $this->db); + } + + /** + * Eliminar una cuenta de la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete($accountId, $userId) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountToFavorite WHERE accountId = ? AND userId = ?'); + $queryData->addParam($accountId); + $queryData->addParam($userId); + $queryData->setOnErrorMessage(__u('Error al eliminar favorito')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } +} \ No newline at end of file diff --git a/lib/SP/Repositories/Account/AccountFileRepository.php b/lib/SP/Repositories/Account/AccountFileRepository.php index f9f80699..643de0b0 100644 --- a/lib/SP/Repositories/Account/AccountFileRepository.php +++ b/lib/SP/Repositories/Account/AccountFileRepository.php @@ -255,20 +255,6 @@ class AccountFileRepository extends Repository implements RepositoryItemInterfac return DbWrapper::getResultsArray($Data, $this->db); } - /** - * Deletes all the items for given ids - * - * @param array $ids - * @return void - * @throws SPException - */ - public function deleteByIdBatch(array $ids) - { - foreach ($ids as $id) { - $this->delete($id); - } - } - /** * Deletes an item * @@ -295,6 +281,26 @@ class AccountFileRepository extends Repository implements RepositoryItemInterfac return $this; } + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountFile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar el archivos')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + /** * Checks whether the item is in use or not * diff --git a/lib/SP/Repositories/Account/AccountRepository.php b/lib/SP/Repositories/Account/AccountRepository.php index 0f7aa41a..9415fabf 100644 --- a/lib/SP/Repositories/Account/AccountRepository.php +++ b/lib/SP/Repositories/Account/AccountRepository.php @@ -58,7 +58,7 @@ class AccountRepository extends Repository implements RepositoryItemInterface /** * Devolver el número total de cuentas * - * @return int + * @return \stdClass */ public function getTotalNumAccounts() { @@ -66,10 +66,10 @@ class AccountRepository extends Repository implements RepositoryItemInterface 'SELECT SUM(n) AS num FROM (SELECT COUNT(*) AS n FROM Account UNION SELECT COUNT(*) AS n FROM AccountHistory) a'; - $Data = new QueryData(); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setQuery($query); - return (int)DbWrapper::getResults($Data)->num; + return DbWrapper::getResults($queryData, $this->db); } /** @@ -301,18 +301,15 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function delete($id) { - $Data = new QueryData(); + $queryData = new QueryData(); - $query = /** @lang SQL */ - 'DELETE FROM Account WHERE id = ? LIMIT 1'; + $queryData->setQuery('DELETE FROM Account WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar la cuenta')); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar la cuenta')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -385,16 +382,13 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function getById($id) { - $query = /** @lang SQL */ - 'SELECT * FROM account_data_v WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setMapClassName(AccountVData::class); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery('SELECT * FROM account_data_v WHERE id = ? LIMIT 1'); + $queryData->setMapClassName(AccountVData::class); + $queryData->addParam($id); /** @var AccountVData|array $queryRes */ - $queryRes = DbWrapper::getResults($Data); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('No se pudieron obtener los datos de la cuenta'), SPException::CRITICAL); @@ -414,12 +408,9 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function getAll() { - $query = /** @lang SQL */ - 'SELECT * FROM Account A ORDER BY id'; - $queryData = new QueryData(); $queryData->setMapClassName(AccountData::class); - $queryData->setQuery($query); + $queryData->setQuery('SELECT * FROM Account A ORDER BY id'); return DbWrapper::getResultsArray($queryData, $this->db); } @@ -438,10 +429,21 @@ class AccountRepository extends Repository implements RepositoryItemInterface * Deletes all the items for given ids * * @param array $ids + * @return int + * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException */ public function deleteByIdBatch(array $ids) { - throw new \RuntimeException('Not implemented'); + $queryData = new QueryData(); + + $queryData->setQuery('DELETE FROM Account WHERE id IN (' . $this->getParamsFromArray($ids) . ') LIMIT 1'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar las cuentas')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -482,28 +484,28 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setSelect('A.id, A.name, C.name AS clientName'); - $Data->setFrom('Account A INNER JOIN Client C ON A.clientId = C.id'); - $Data->setOrder('A.name'); + $queryData = new QueryData(); + $queryData->setSelect('A.id, A.name, C.name AS clientName'); + $queryData->setFrom('Account A INNER JOIN Client C ON A.clientId = C.id'); + $queryData->setOrder('A.name'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('A.name LIKE ? OR C.name LIKE ?'); + $queryData->setWhere('A.name LIKE ? OR C.name LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } @@ -518,14 +520,11 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function incrementViewCounter($id = null) { - $query = /** @lang SQL */ - 'UPDATE Account SET countView = (countView + 1) WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('UPDATE Account SET countView = (countView + 1) WHERE id = ? LIMIT 1'); + $queryData->addParam($id); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -551,13 +550,13 @@ class AccountRepository extends Repository implements RepositoryItemInterface INNER JOIN Category C2 ON A.categoryId = C2.id WHERE A.id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setMapClassName(AccountExtData::class); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setMapClassName(AccountExtData::class); + $queryData->addParam($id); /** @var AccountExtData|array $queryRes */ - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('No se pudieron obtener los datos de la cuenta'), SPException::ERROR); @@ -707,12 +706,9 @@ class AccountRepository extends Repository implements RepositoryItemInterface */ public function getAccountsPassData() { - $query = /** @lang SQL */ - 'SELECT id, name, pass, `key` FROM Account WHERE BIT_LENGTH(pass) > 0'; - $queryData = new QueryData(); - $queryData->setQuery($query); + $queryData->setQuery('SELECT id, name, pass, `key` FROM Account WHERE BIT_LENGTH(pass) > 0'); - return DbWrapper::getResultsArray($queryData); + return DbWrapper::getResultsArray($queryData, $this->db); } } \ No newline at end of file diff --git a/lib/SP/Repositories/Account/AccountToTagRepository.php b/lib/SP/Repositories/Account/AccountToTagRepository.php index 61ee4e7c..b49b6d1a 100644 --- a/lib/SP/Repositories/Account/AccountToTagRepository.php +++ b/lib/SP/Repositories/Account/AccountToTagRepository.php @@ -54,11 +54,11 @@ class AccountToTagRepository extends Repository WHERE AT.accountId = ? ORDER BY T.name'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); - return DbWrapper::getResultsArray($Data); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -74,16 +74,16 @@ class AccountToTagRepository extends Repository $query = /** @lang SQL */ 'INSERT INTO AccountToTag (accountId, tagId) VALUES ' . $this->getParamsFromArray($accountRequest->tags, '(?,?)'); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setOnErrorMessage(__u('Error al añadir las etiquetas de la cuenta')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setOnErrorMessage(__u('Error al añadir las etiquetas de la cuenta')); foreach ($accountRequest->tags as $tag) { - $Data->addParam($accountRequest->id); - $Data->addParam($tag); + $queryData->addParam($accountRequest->id); + $queryData->addParam($tag); } - return DbWrapper::getQuery($Data); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -96,16 +96,12 @@ class AccountToTagRepository extends Repository */ public function deleteByAccountId($id) { - $Data = new QueryData(); - $query = /** @lang SQL */ - 'DELETE FROM AccountToTag WHERE accountId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountToTag WHERE accountId = ?'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar las etiquetas de la cuenta')); - $Data->addParam($id); - - $Data->setQuery($query); - $Data->setOnErrorMessage(__u('Error al eliminar las etiquetas de la cuenta')); - - return DbWrapper::getQuery($Data); + return DbWrapper::getQuery($queryData,$this->db); } /** diff --git a/lib/SP/Repositories/Account/AccountToUserGroupRepository.php b/lib/SP/Repositories/Account/AccountToUserGroupRepository.php index dd20b949..72d27ae7 100644 --- a/lib/SP/Repositories/Account/AccountToUserGroupRepository.php +++ b/lib/SP/Repositories/Account/AccountToUserGroupRepository.php @@ -55,11 +55,11 @@ class AccountToUserGroupRepository extends Repository WHERE AUG.accountId = ? ORDER BY G.name'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); - return DbWrapper::getResultsArray($Data); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -77,11 +77,11 @@ class AccountToUserGroupRepository extends Repository WHERE AUG.userGroupId = ? ORDER BY G.name'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); - return DbWrapper::getResultsArray($Data); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -92,15 +92,12 @@ class AccountToUserGroupRepository extends Repository */ public function deleteByUserGroupId($id) { - $query = /** @lang SQL */ - 'DELETE FROM AccountToUserGroup WHERE userGroupId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountToUserGroup WHERE userGroupId = ?'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); - - return DbWrapper::getQuery($Data); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -125,15 +122,12 @@ class AccountToUserGroupRepository extends Repository */ public function deleteByAccountId($id) { - $query = /** @lang SQL */ - 'DELETE FROM AccountToUserGroup WHERE accountId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountToUserGroup WHERE accountId = ?'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); - - return DbWrapper::getQuery($Data); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -147,16 +141,16 @@ class AccountToUserGroupRepository extends Repository $query = /** @lang SQL */ 'INSERT INTO AccountToUserGroup (accountId, userGroupId) VALUES ' . $this->getParamsFromArray($accountRequest->userGroups, '(?,?)'); - $Data = new QueryData(); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setQuery($query); foreach ($accountRequest->userGroups as $userGroup) { - $Data->addParam($accountRequest->id); - $Data->addParam($userGroup); + $queryData->addParam($accountRequest->id); + $queryData->addParam($userGroup); } - $Data->setOnErrorMessage(__u('Error al actualizar los grupos secundarios')); + $queryData->setOnErrorMessage(__u('Error al actualizar los grupos secundarios')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } } \ No newline at end of file diff --git a/lib/SP/Repositories/Account/AccountToUserRepository.php b/lib/SP/Repositories/Account/AccountToUserRepository.php index 00d71bdf..f6b70c3b 100644 --- a/lib/SP/Repositories/Account/AccountToUserRepository.php +++ b/lib/SP/Repositories/Account/AccountToUserRepository.php @@ -59,23 +59,20 @@ class AccountToUserRepository extends Repository * Eliminar la asociación de grupos con cuentas. * * @param int $id con el Id de la cuenta - * @return bool + * @return int * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\ConstraintException */ public function deleteByAccountId($id) { - $Data = new QueryData(); + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AccountToUser WHERE accountId = ?'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar usuarios asociados a la cuenta')); - $query = /** @lang SQL */ - 'DELETE FROM AccountToUser WHERE accountId = ?'; + DbWrapper::getQuery($queryData, $this->db); - $Data->addParam($id); - - $Data->setQuery($query); - $Data->setOnErrorMessage(__u('Error al eliminar usuarios asociados a la cuenta')); - - return DbWrapper::getQuery($Data); + return $this->db->getNumRows(); } /** @@ -91,16 +88,16 @@ class AccountToUserRepository extends Repository $query = /** @lang SQL */ 'INSERT INTO AccountToUser (accountId, userId) VALUES ' . $this->getParamsFromArray($accountRequest->users, '(?,?)'); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setOnErrorMessage(__u('Error al actualizar los usuarios de la cuenta')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setOnErrorMessage(__u('Error al actualizar los usuarios de la cuenta')); foreach ($accountRequest->users as $user) { - $Data->addParam($accountRequest->id); - $Data->addParam($user); + $queryData->addParam($accountRequest->id); + $queryData->addParam($user); } - return DbWrapper::getQuery($Data); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -118,10 +115,10 @@ class AccountToUserRepository extends Repository WHERE AU.accountId = ? ORDER BY U.name'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); - return DbWrapper::getResultsArray($Data); + return DbWrapper::getResultsArray($queryData, $this->db); } } \ No newline at end of file diff --git a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php index cacb8d0d..d0773507 100644 --- a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php +++ b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php @@ -53,17 +53,14 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface */ public function delete($id) { - $query = /** @lang SQL */ - 'DELETE FROM AuthToken WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AuthToken WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error interno')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error interno')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -84,12 +81,12 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface FROM AuthToken WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(AuthTokenData::class); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); + $queryData->setMapClassName(AuthTokenData::class); - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -123,15 +120,14 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface */ public function deleteByIdBatch(array $ids) { - $query = /** @lang SQL */ - 'DELETE FROM AuthToken WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM AuthToken WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error interno')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setParams($ids); - $Data->setOnErrorMessage(__u('Error interno')); + DbWrapper::getQuery($queryData, $this->db); - return DbWrapper::getQuery($Data, $this->db); + return $this->db->getNumRows(); } /** @@ -162,32 +158,32 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface FROM AuthToken AT INNER JOIN User U ON userid = U.id'; - $Data = new QueryData(); + $queryData = new QueryData(); if ($SearchData->getSeachString() !== '') { $search = '%' . $SearchData->getSeachString() . '%'; $query .= ' WHERE U.login LIKE ?'; - $Data->addParam($search); + $queryData->addParam($search); } $query .= ' ORDER BY U.login'; $query .= ' LIMIT ?, ?'; - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); - $Data->setQuery($query); + $queryData->setQuery($query); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); foreach ($queryRes as $token) { $token->actionId = Acl::getActionInfo($token->actionId); } - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } @@ -217,17 +213,17 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface `hash` = ?, startDate = UNIX_TIMESTAMP()'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserId()); - $Data->addParam($itemData->getActionId()); - $Data->addParam($itemData->getCreatedBy()); - $Data->addParam($itemData->getToken()); - $Data->addParam($itemData->getVault()); - $Data->addParam($itemData->getHash()); - $Data->setOnErrorMessage(__u('Error interno')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getUserId()); + $queryData->addParam($itemData->getActionId()); + $queryData->addParam($itemData->getCreatedBy()); + $queryData->addParam($itemData->getToken()); + $queryData->addParam($itemData->getVault()); + $queryData->addParam($itemData->getHash()); + $queryData->setOnErrorMessage(__u('Error interno')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -245,14 +241,14 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface WHERE userId = ? AND actionId = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserId()); - $Data->addParam($itemData->getActionId()); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getUserId()); + $queryData->addParam($itemData->getActionId()); - DbWrapper::getResults($Data, $this->db); + DbWrapper::getResults($queryData, $this->db); - return $Data->getQueryNumRows() === 1; + return $queryData->getQueryNumRows() === 1; } /** @@ -263,16 +259,13 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface */ public function getTokenByUserId($id) { - $query = /** @lang SQL */ - 'SELECT token FROM AuthToken WHERE userId = ? AND token <> \'\' LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT token FROM AuthToken WHERE userId = ? AND token <> \'\' LIMIT 1'); + $queryData->addParam($id); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryRes = DbWrapper::getResults($queryData, $this->db); - $queryRes = DbWrapper::getResults($Data, $this->db); - - return $Data->getQueryNumRows() === 1 ? $queryRes->token : null; + return $queryData->getQueryNumRows() === 1 ? $queryRes->token : null; } /** @@ -301,18 +294,18 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface startDate = UNIX_TIMESTAMP() WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserId()); - $Data->addParam($itemData->getActionId()); - $Data->addParam($itemData->getCreatedBy()); - $Data->addParam($itemData->getToken()); - $Data->addParam($itemData->getVault()); - $Data->addParam($itemData->getHash()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error interno')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getUserId()); + $queryData->addParam($itemData->getActionId()); + $queryData->addParam($itemData->getCreatedBy()); + $queryData->addParam($itemData->getToken()); + $queryData->addParam($itemData->getVault()); + $queryData->addParam($itemData->getHash()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error interno')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -329,15 +322,15 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface AND actionId = ? AND id <> ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserId()); - $Data->addParam($itemData->getActionId()); - $Data->addParam($itemData->getId()); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getUserId()); + $queryData->addParam($itemData->getActionId()); + $queryData->addParam($itemData->getId()); - DbWrapper::getResults($Data, $this->db); + DbWrapper::getResults($queryData, $this->db); - return $Data->getQueryNumRows() === 1; + return $queryData->getQueryNumRows() === 1; } /** @@ -357,13 +350,13 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface startDate = UNIX_TIMESTAMP() WHERE userId = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($token); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error interno')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($token); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error interno')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -385,14 +378,14 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface startDate = UNIX_TIMESTAMP() WHERE userId = ? AND vault IS NOT NULL'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($vault); - $Data->addParam($hash); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error interno')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($vault); + $queryData->addParam($hash); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error interno')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -403,16 +396,13 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface */ public function getUserIdForToken($token) { - $query = /** @lang SQL */ - 'SELECT userId FROM AuthToken WHERE token = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT userId FROM AuthToken WHERE token = ? LIMIT 1'); + $queryData->addParam($token); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($token); + $queryRes = DbWrapper::getResults($queryData, $this->db); - $queryRes = DbWrapper::getResults($Data, $this->db); - - return $Data->getQueryNumRows() === 1 ? $queryRes->userId : false; + return $queryData->getQueryNumRows() === 1 ? $queryRes->userId : false; } /** @@ -430,14 +420,14 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface WHERE actionId = ? AND token = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(AuthTokenData::class); - $Data->setQuery($query); - $Data->addParam($actionId); - $Data->addParam($token); + $queryData = new QueryData(); + $queryData->setMapClassName(AuthTokenData::class); + $queryData->setQuery($query); + $queryData->addParam($actionId); + $queryData->addParam($token); - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); - return $Data->getQueryNumRows() === 1 ? $queryRes : false; + return $queryData->getQueryNumRows() === 1 ? $queryRes : false; } } \ No newline at end of file diff --git a/lib/SP/Repositories/Category/CategoryRepository.php b/lib/SP/Repositories/Category/CategoryRepository.php index 23b0ecc9..1ee0d8d8 100644 --- a/lib/SP/Repositories/Category/CategoryRepository.php +++ b/lib/SP/Repositories/Category/CategoryRepository.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. @@ -211,15 +211,20 @@ class CategoryRepository extends Repository implements RepositoryItemInterface * Deletes all the items for given ids * * @param array $ids - * @return void - * @throws SPException - * @throws \SP\Core\Dic\ContainerException + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - foreach ($ids as $id) { - $this->delete($id); - } + $Data = new QueryData(); + $Data->setQuery('DELETE FROM Category WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $Data->setParams($ids); + $Data->setOnErrorMessage(__u('Error al eliminar la categorías')); + + DbWrapper::getQuery($Data, $this->db); + + return $this->db->getNumRows(); } /** @@ -229,7 +234,6 @@ class CategoryRepository extends Repository implements RepositoryItemInterface * @return int * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Core\Dic\ContainerException */ public function delete($id) { diff --git a/lib/SP/Repositories/Client/ClientRepository.php b/lib/SP/Repositories/Client/ClientRepository.php index b262a94e..e15404ac 100644 --- a/lib/SP/Repositories/Client/ClientRepository.php +++ b/lib/SP/Repositories/Client/ClientRepository.php @@ -64,15 +64,15 @@ class ClientRepository extends Repository implements RepositoryItemInterface isGlobal = ?, `hash` = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getDescription()); - $Data->addParam($itemData->getIsGlobal()); - $Data->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); - $Data->setOnErrorMessage(__u('Error al crear el cliente')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getDescription()); + $queryData->addParam($itemData->getIsGlobal()); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->setOnErrorMessage(__u('Error al crear el cliente')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -87,16 +87,13 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function checkDuplicatedOnAdd($itemData) { - $query = /** @lang SQL */ - 'SELECT id FROM Client WHERE `hash` = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id FROM Client WHERE `hash` = ? LIMIT 1'); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -122,16 +119,16 @@ class ClientRepository extends Repository implements RepositoryItemInterface `hash` = ? WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getDescription()); - $Data->addParam($itemData->getIsGlobal()); - $Data->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar el cliente')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getDescription()); + $queryData->addParam($itemData->getIsGlobal()); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar el cliente')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this; } @@ -146,17 +143,14 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function checkDuplicatedOnUpdate($itemData) { - $query = /** @lang SQL */ - 'SELECT id FROM Client WHERE `hash` = ? AND id <> ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id FROM Client WHERE `hash` = ? AND id <> ? LIMIT 1'); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->addParam($itemData->getId()); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); - $Data->addParam($itemData->getId()); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -167,15 +161,12 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function getById($id) { - $query = /** @lang SQL */ - 'SELECT id, name, description, isGlobal FROM Client WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, description, isGlobal FROM Client WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setMapClassName(ClientData::class); - $Data = new QueryData(); - $Data->setMapClassName(ClientData::class); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -185,14 +176,11 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function getAll() { - $query = /** @lang SQL */ - 'SELECT id, name, description, isGlobal FROM Client ORDER BY name'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, description, isGlobal FROM Client ORDER BY name'); + $queryData->setMapClassName(ClientData::class); - $Data = new QueryData(); - $Data->setMapClassName(ClientData::class); - $Data->setQuery($query); - - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -206,26 +194,32 @@ class ClientRepository extends Repository implements RepositoryItemInterface $query = /** @lang SQL */ 'SELECT id, name, description, isGlobal FROM Client WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(ClientData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setParams($ids); + $queryData->setMapClassName(ClientData::class); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** * Deletes all the items for given ids * * @param array $ids - * @return void - * @throws SPException + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - foreach ($ids as $id) { - $this->delete($id); - } + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Client WHERE id IN ('. $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar los clientes')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -237,17 +231,14 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function delete($id) { - $query = /** @lang SQL */ - 'DELETE FROM Client WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Client WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar el cliente')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el cliente')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -269,29 +260,29 @@ class ClientRepository extends Repository implements RepositoryItemInterface */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setMapClassName(ClientData::class); - $Data->setSelect('id, name, description, isGlobal'); - $Data->setFrom('Client'); - $Data->setOrder('name'); + $queryData = new QueryData(); + $queryData->setMapClassName(ClientData::class); + $queryData->setSelect('id, name, description, isGlobal'); + $queryData->setFrom('Client'); + $queryData->setOrder('name'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('name LIKE ? OR description LIKE ?'); + $queryData->setWhere('name LIKE ? OR description LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } diff --git a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php b/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php index 56a8b1cc..eae7c636 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php +++ b/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. @@ -86,17 +86,17 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter $query = /** @lang SQL */ 'INSERT INTO CustomFieldDefinition SET name = ?, moduleId = ?, required = ?, help = ?, showInList = ?, typeId = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getModuleId()); - $Data->addParam($itemData->getRequired()); - $Data->addParam($itemData->getHelp()); - $Data->addParam($itemData->getShowInList()); - $Data->addParam($itemData->getTypeId()); - $Data->setOnErrorMessage(__u('Error al crear el campo personalizado')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getModuleId()); + $queryData->addParam($itemData->getRequired()); + $queryData->addParam($itemData->getHelp()); + $queryData->addParam($itemData->getShowInList()); + $queryData->addParam($itemData->getTypeId()); + $queryData->setOnErrorMessage(__u('Error al crear el campo personalizado')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -116,18 +116,18 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter SET name = ?, moduleId = ?, required = ?, help = ?, showInList = ?, typeId = ? WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getModuleId()); - $Data->addParam($itemData->getRequired()); - $Data->addParam($itemData->getHelp()); - $Data->addParam($itemData->getShowInList()); - $Data->addParam($itemData->getTypeId()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar el campo personalizado')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getModuleId()); + $queryData->addParam($itemData->getRequired()); + $queryData->addParam($itemData->getHelp()); + $queryData->addParam($itemData->getShowInList()); + $queryData->addParam($itemData->getTypeId()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar el campo personalizado')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -143,12 +143,12 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter FROM CustomFieldDefinition WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefinitionData::class); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setMapClassName(CustomFieldDefinitionData::class); + $queryData->setQuery($query); + $queryData->addParam($id); - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -163,11 +163,11 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter FROM CustomFieldDefinition ORDER BY moduleId'; - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefinitionData::class); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setMapClassName(CustomFieldDefinitionData::class); + $queryData->setQuery($query); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -183,28 +183,59 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter FROM CustomFieldDefinition WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefinitionData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setMapClassName(CustomFieldDefinitionData::class); + $queryData->setQuery($query); + $queryData->setParams($ids); - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** * Deletes all the items for given ids * * @param array $ids - * @return void + * @return int * @throws SPException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - foreach ($ids as $id) { - $this->delete($id); + if ($this->deleteItemsDataForDefinitionBatch($ids) === false) { + throw new SPException(__u('Error al eliminar los campos personalizados'), SPException::ERROR); } + + $query = /** @lang SQL */ + 'DELETE FROM CustomFieldDefinition WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar los campos personalizados')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Eliminar los datos de los elementos de una definición + * + * @param array $ids + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + protected function deleteItemsDataForDefinitionBatch(array $ids) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM CustomFieldData WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -222,15 +253,12 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter throw new SPException(__u('Error al eliminar el campo personalizado'), SPException::ERROR); } - $query = /** @lang SQL */ - 'DELETE FROM CustomFieldDefinition WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM CustomFieldDefinition WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar el campo personalizado')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el campo personalizado')); - - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -242,13 +270,11 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter */ protected function deleteItemsDataForDefinition($id) { - $query = /** @lang SQL */ - 'DELETE FROM CustomFieldData WHERE id = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM CustomFieldData WHERE id = ?'); + $queryData->addParam($id); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -289,22 +315,22 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefinitionData::class); - $Data->setSelect('CFD.id, CFD.name, CFD.moduleId, CFD.required, CFD.help, CFD.showInList, CFD.typeId, CFT.name AS typeName'); - $Data->setFrom('CustomFieldDefinition CFD INNER JOIN CustomFieldType CFT ON CFD.typeId = CFT.id'); - $Data->setOrder('CFD.moduleId'); + $queryData = new QueryData(); + $queryData->setMapClassName(CustomFieldDefinitionData::class); + $queryData->setSelect('CFD.id, CFD.name, CFD.moduleId, CFD.required, CFD.help, CFD.showInList, CFD.typeId, CFT.name AS typeName'); + $queryData->setFrom('CustomFieldDefinition CFD INNER JOIN CustomFieldType CFT ON CFD.typeId = CFT.id'); + $queryData->setOrder('CFD.moduleId'); - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); /** @var CustomFieldDefinitionData[] $queryRes */ - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } diff --git a/lib/SP/Repositories/CustomField/CustomFieldRepository.php b/lib/SP/Repositories/CustomField/CustomFieldRepository.php index 4c24968e..84b9e5e8 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldRepository.php +++ b/lib/SP/Repositories/CustomField/CustomFieldRepository.php @@ -29,6 +29,7 @@ use SP\DataModel\CustomFieldData; use SP\DataModel\ItemSearchData; use SP\Repositories\Repository; use SP\Repositories\RepositoryItemInterface; +use SP\Repositories\RepositoryItemTrait; use SP\Storage\DbWrapper; use SP\Storage\QueryData; @@ -39,6 +40,8 @@ use SP\Storage\QueryData; */ class CustomFieldRepository extends Repository implements RepositoryItemInterface { + use RepositoryItemTrait; + /** * Updates an item * @@ -104,7 +107,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function delete($id) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -151,7 +154,35 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac $Data->addParam($id); $Data->addParam($moduleId); - return DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($Data, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int[] $ids + * @param int $moduleId + * @return int + * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function deleteCustomFieldDataBatch(array $ids, $moduleId) + { + $query = /** @lang SQL */ + 'DELETE FROM CustomFieldData + WHERE itemId IN (' . $this->getParamsFromArray($ids) . ') + AND moduleId = ?'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->setParams($ids); + $Data->addParam($moduleId); + + DbWrapper::getQuery($Data, $this->db); + + return $this->db->getNumRows(); } /** @@ -162,7 +193,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function getById($id) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -190,7 +221,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function getByIdBatch(array $ids) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -201,7 +232,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function deleteByIdBatch(array $ids) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -212,7 +243,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function checkInUse($id) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -223,7 +254,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function search(ItemSearchData $SearchData) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -270,7 +301,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function checkDuplicatedOnUpdate($itemData) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } /** @@ -281,6 +312,6 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac */ public function checkDuplicatedOnAdd($itemData) { - throw new \RuntimeException('Unimplemented'); + throw new \RuntimeException('Not implemented'); } } \ No newline at end of file diff --git a/lib/SP/Repositories/Notification/NotificationRepository.php b/lib/SP/Repositories/Notification/NotificationRepository.php new file mode 100644 index 00000000..c2a89b70 --- /dev/null +++ b/lib/SP/Repositories/Notification/NotificationRepository.php @@ -0,0 +1,510 @@ +. + */ + +namespace SP\Repositories\Notification; + +use SP\DataModel\ItemSearchData; +use SP\DataModel\NotificationData; +use SP\Repositories\Repository; +use SP\Repositories\RepositoryItemInterface; +use SP\Repositories\RepositoryItemTrait; +use SP\Storage\DbWrapper; +use SP\Storage\QueryData; + +/** + * Class NotificationRepository + * + * @package SP\Repositories\Notification + */ +class NotificationRepository extends Repository implements RepositoryItemInterface +{ + use RepositoryItemTrait; + + /** + * Creates an item + * + * @param NotificationData $itemData + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function create($itemData) + { + $query = /** @lang SQL */ + 'INSERT INTO Notification + SET type = ?, + component = ?, + description = ?, + `date` = UNIX_TIMESTAMP(), + checked = 0, + userId = ?, + sticky = ?, + onlyAdmin = ?'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getType()); + $queryData->addParam($itemData->getComponent()); + $queryData->addParam($itemData->getDescription()); + $queryData->addParam($itemData->getUserId() ?: null); + $queryData->addParam($itemData->isSticky()); + $queryData->addParam($itemData->isOnlyAdmin()); + $queryData->setOnErrorMessage(__u('Error al crear la notificación')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getLastId(); + } + + /** + * Updates an item + * + * @param NotificationData $itemData + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function update($itemData) + { + $query = /** @lang SQL */ + 'UPDATE Notification + SET type = ?, + component = ?, + description = ?, + `date` = UNIX_TIMESTAMP(), + checked = ?, + userId = ?, + sticky = ?, + onlyAdmin = ? + WHERE id = ? LIMIT 1'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getType()); + $queryData->addParam($itemData->getComponent()); + $queryData->addParam($itemData->getDescription()); + $queryData->addParam($itemData->isChecked()); + $queryData->addParam($itemData->getUserId() ?: null); + $queryData->addParam($itemData->isSticky()); + $queryData->addParam($itemData->isOnlyAdmin()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al modificar la notificación')); + + DbWrapper::getQuery($queryData, $this->db); + + return $queryData->getQueryNumRows(); + } + + /** + * Deletes an item + * + * @param $id + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete($id) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Notification WHERE id = ? AND sticky = 0 LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar la notificación')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Deletes an item + * + * @param $id + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteAdmin($id) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Notification WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar la notificación')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Deletes an item + * + * @param array $ids + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteAdminBatch(array $ids) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar las notificaciones')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Returns the item for given id + * + * @param int $id + * @return NotificationData + */ + public function getById($id) + { + $query = /** @lang SQL */ + 'SELECT id, + type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification + WHERE id = ? LIMIT 1'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); + $queryData->setMapClassName(NotificationData::class); + $queryData->setOnErrorMessage(__u('Error al obtener la notificación')); + + return DbWrapper::getResults($queryData, $this->db); + } + + /** + * Returns all the items + * + * @return NotificationData[] + */ + public function getAll() + { + $query = /** @lang SQL */ + 'SELECT id + notice_type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setMapClassName(NotificationData::class); + $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones')); + + return DbWrapper::getResultsArray($queryData, $this->db); + } + + /** + * Returns all the items for given ids + * + * @param array $ids + * @return NotificationData[] + */ + public function getByIdBatch(array $ids) + { + $query = /** @lang SQL */ + 'SELECT id, + type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification + WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setParams($ids); + $queryData->setMapClassName(NotificationData::class); + + return DbWrapper::getResultsArray($queryData, $this->db); + } + + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ') AND sticky = 0'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar las notificaciones')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); + } + + /** + * Checks whether the item is in use or not + * + * @param $id int + */ + public function checkInUse($id) + { + throw new \RuntimeException('Not implemented'); + } + + /** + * Checks whether the item is duplicated on updating + * + * @param mixed $itemData + */ + public function checkDuplicatedOnUpdate($itemData) + { + throw new \RuntimeException('Not implemented'); + } + + /** + * Checks whether the item is duplicated on adding + * + * @param mixed $itemData + */ + public function checkDuplicatedOnAdd($itemData) + { + throw new \RuntimeException('Not implemented'); + } + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @return mixed + */ + public function search(ItemSearchData $itemSearchData) + { + $queryData = new QueryData(); + $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin'); + $queryData->setFrom('Notification'); + $queryData->setOrder('`date` DESC'); + + if ($itemSearchData->getSeachString() !== '') { + $queryData->setWhere('type LIKE ? OR component LIKE ? OR description LIKE ?'); + + $search = '%' . $itemSearchData->getSeachString() . '%'; + $queryData->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); + } + + $queryData->setLimit('?,?'); + $queryData->addParam($itemSearchData->getLimitStart()); + $queryData->addParam($itemSearchData->getLimitCount()); + + DbWrapper::setFullRowCount(); + + /** @var array $queryRes */ + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); + + $queryRes['count'] = $queryData->getQueryNumRows(); + + return $queryRes; + } + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @param int $userId + * @return mixed + */ + public function searchForUserId(ItemSearchData $itemSearchData, $userId) + { + $queryData = new QueryData(); + $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin'); + $queryData->setFrom('Notification'); + $queryData->setOrder('`date` DESC'); + + $filterUser = '(userId = ? OR (userId = NULL AND onlyAdmin = 0) OR sticky = 1)'; + + if ($itemSearchData->getSeachString() !== '') { + $queryData->setWhere('(type LIKE ? OR component LIKE ? OR description LIKE ?) AND ' . $filterUser); + + $search = '%' . $itemSearchData->getSeachString() . '%'; + $queryData->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); + $queryData->addParam($userId); + } else { + $queryData->setWhere($filterUser); + $queryData->addParam($userId); + } + + $queryData->setLimit('?,?'); + $queryData->addParam($itemSearchData->getLimitStart()); + $queryData->addParam($itemSearchData->getLimitCount()); + + DbWrapper::setFullRowCount(); + + /** @var array $queryRes */ + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); + + $queryRes['count'] = $queryData->getQueryNumRows(); + + return $queryRes; + } + + /** + * Marcar una notificación como leída + * + * @param $id + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function setCheckedById($id) + { + $query = /** @lang SQL */ + 'UPDATE Notification SET checked = 1 WHERE id = ? LIMIT 1'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al modificar la notificación')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getLastId(); + } + + /** + * Devolver las notificaciones de un usuario para una fecha y componente determinados + * + * @param $component + * @param $id + * @return NotificationData[] + */ + public function getForUserIdByDate($component, $id) + { + $query = /** @lang SQL */ + 'SELECT type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification + WHERE component = ? AND + (UNIX_TIMESTAMP() - date) <= 86400 AND + userId = ?'; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($component); + $queryData->addParam($id); + $queryData->setMapClassName(NotificationData::class); + $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones')); + + return DbWrapper::getResultsArray($queryData, $this->db); + } + + /** + * @param $id + * @return NotificationData[] + */ + public function getAllForUserId($id) + { + $query = /** @lang SQL */ + 'SELECT id, + type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification + WHERE (userId = ? OR userId IS NULL OR sticky = 1) + AND onlyAdmin = 0 + ORDER BY date DESC '; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); + $queryData->setMapClassName(NotificationData::class); + $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones')); + + return DbWrapper::getResultsArray($queryData, $this->db); + } + + /** + * @param $id + * @return NotificationData[] + */ + public function getAllActiveForUserId($id) + { + $query = /** @lang SQL */ + 'SELECT id, + type, + component, + description, + `date`, + userId, + checked, + sticky, + onlyAdmin + FROM Notification + WHERE (userId = ? OR sticky = 1) + AND onlyAdmin = 0 + AND checked = 0 + ORDER BY date DESC '; + + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($id); + $queryData->setMapClassName(NotificationData::class); + $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones')); + + return DbWrapper::getResultsArray($queryData, $this->db); + } +} \ No newline at end of file diff --git a/lib/SP/Repositories/Plugin/PluginRepository.php b/lib/SP/Repositories/Plugin/PluginRepository.php index aa22d9f7..cbc218fc 100644 --- a/lib/SP/Repositories/Plugin/PluginRepository.php +++ b/lib/SP/Repositories/Plugin/PluginRepository.php @@ -273,7 +273,7 @@ class PluginRepository extends Repository implements RepositoryItemInterface DbWrapper::setFullRowCount(); /** @var array $queryRes */ - $queryRes = DbWrapper::getResultsArray($Data); + $queryRes = DbWrapper::getResultsArray($Data, $this->db); $queryRes['count'] = $Data->getQueryNumRows(); diff --git a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php index a24ab888..1465e85c 100644 --- a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php +++ b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php @@ -55,17 +55,14 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface */ public function delete($id) { - $query = /** @lang SQL */ - 'DELETE FROM PublicLink WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM PublicLink WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar enlace')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar enlace')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -97,11 +94,11 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface INNER JOIN User U ON PL.userId = U.id INNER JOIN Account A ON itemId = A.id'; - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkListData::class); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setMapClassName(PublicLinkListData::class); + $queryData->setQuery($query); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -135,12 +132,12 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface INNER JOIN Account A ON itemId = A.id WHERE PL.id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkListData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setMapClassName(PublicLinkListData::class); + $queryData->setQuery($query); + $queryData->setParams($ids); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -153,14 +150,13 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface */ public function deleteByIdBatch(array $ids) { - $query = /** @lang SQL */ - 'DELETE FROM PublicLink WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM PublicLink WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setParams($ids); + DbWrapper::getQuery($queryData, $this->db); - return DbWrapper::getQuery($Data, $this->db); + return $this->db->getNumRows(); } /** @@ -182,9 +178,9 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkListData::class); - $Data->setSelect('PL.id, + $queryData = new QueryData(); + $queryData->setMapClassName(PublicLinkListData::class); + $queryData->setSelect('PL.id, PL.itemId, PL.hash, PL.data, @@ -202,30 +198,30 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface U.login AS userLogin, A.name AS accountName, C.name AS clientName'); - $Data->setFrom('PublicLink PL + $queryData->setFrom('PublicLink PL INNER JOIN User U ON PL.userId = U.id INNER JOIN Account A ON itemId = A.id INNER JOIN Client C ON A.clientId = C.id'); - $Data->setOrder('PL.dateExpire DESC'); + $queryData->setOrder('PL.dateExpire DESC'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('U.login LIKE ? OR A.name LIKE ? OR C.name LIKE ?'); + $queryData->setWhere('U.login LIKE ? OR A.name LIKE ? OR C.name LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); - $Data->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } @@ -257,19 +253,19 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface dateExpire = ?, maxCountViews = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getItemId()); - $Data->addParam($itemData->getHash()); - $Data->addParam($itemData->getData()); - $Data->addParam($itemData->getUserId()); - $Data->addParam($itemData->getTypeId()); - $Data->addParam((int)$itemData->isNotify()); - $Data->addParam($itemData->getDateExpire()); - $Data->addParam($itemData->getMaxCountViews()); - $Data->setOnErrorMessage(__u('Error al crear enlace')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getItemId()); + $queryData->addParam($itemData->getHash()); + $queryData->addParam($itemData->getData()); + $queryData->addParam($itemData->getUserId()); + $queryData->addParam($itemData->getTypeId()); + $queryData->addParam((int)$itemData->isNotify()); + $queryData->addParam($itemData->getDateExpire()); + $queryData->addParam($itemData->getMaxCountViews()); + $queryData->setOnErrorMessage(__u('Error al crear enlace')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -282,16 +278,13 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface */ public function checkDuplicatedOnAdd($itemData) { - $query = /** @lang SQL */ - 'SELECT id FROM PublicLink WHERE itemId = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id FROM PublicLink WHERE itemId = ? LIMIT 1'); + $queryData->addParam($itemData->getItemId()); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getItemId()); + DbWrapper::getResults($queryData, $this->db); - DbWrapper::getResults($Data, $this->db); - - return ($Data->getQueryNumRows() === 1); + return ($queryData->getQueryNumRows() === 1); } /** @@ -322,13 +315,13 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface useInfo = ? WHERE `hash` = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($publicLinkData->getUseInfo()); - $Data->addParam($publicLinkData->getHash()); - $Data->setOnErrorMessage(__u('Error al actualizar enlace')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($publicLinkData->getUseInfo()); + $queryData->addParam($publicLinkData->getHash()); + $queryData->setOnErrorMessage(__u('Error al actualizar enlace')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -351,17 +344,17 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface maxCountViews = ? WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getHash()); - $Data->addParam($itemData->getData()); - $Data->addParam((int)$itemData->isNotify()); - $Data->addParam($itemData->getDateExpire()); - $Data->addParam($itemData->getMaxCountViews()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar enlace')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getHash()); + $queryData->addParam($itemData->getData()); + $queryData->addParam((int)$itemData->isNotify()); + $queryData->addParam($itemData->getDateExpire()); + $queryData->addParam($itemData->getMaxCountViews()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar enlace')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -384,16 +377,16 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface maxCountViews = ? WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($publicLinkData->getHash()); - $Data->addParam($publicLinkData->getData()); - $Data->addParam($publicLinkData->getDateExpire()); - $Data->addParam($publicLinkData->getMaxCountViews()); - $Data->addParam($publicLinkData->getId()); - $Data->setOnErrorMessage(__u('Error al renovar enlace')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($publicLinkData->getHash()); + $queryData->addParam($publicLinkData->getData()); + $queryData->addParam($publicLinkData->getDateExpire()); + $queryData->addParam($publicLinkData->getMaxCountViews()); + $queryData->addParam($publicLinkData->getId()); + $queryData->setOnErrorMessage(__u('Error al renovar enlace')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -427,18 +420,18 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface INNER JOIN Account A ON PL.itemId = A.id WHERE PL.id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkListData::class); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setMapClassName(PublicLinkListData::class); + $queryData->setQuery($query); + $queryData->addParam($id); - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('Error al obtener enlace'), SPException::ERROR); } - if ($Data->getQueryNumRows() === 0) { + if ($queryData->getQueryNumRows() === 0) { throw new SPException(__u('El enlace no existe'), SPException::ERROR); } @@ -475,19 +468,19 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface INNER JOIN Account A ON itemId = A.id WHERE PL.hash = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkData::class); - $Data->setQuery($query); - $Data->addParam($hash); + $queryData = new QueryData(); + $queryData->setMapClassName(PublicLinkData::class); + $queryData->setQuery($query); + $queryData->addParam($hash); /** @var PublicLinkData $queryRes */ - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('Error al obtener enlace'), SPException::ERROR); } - if ($Data->getQueryNumRows() === 0) { + if ($queryData->getQueryNumRows() === 0) { throw new SPException(__u('El enlace no existe'), SPException::ERROR); } @@ -503,15 +496,12 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface */ public function getHashForItem($itemId) { - $query = /** @lang SQL */ - 'SELECT id, `hash` FROM PublicLink WHERE itemId = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, `hash` FROM PublicLink WHERE itemId = ? LIMIT 1'); + $queryData->addParam($itemId); + $queryData->setMapClassName(PublicLinkData::class); - $Data = new QueryData(); - $Data->setMapClassName(PublicLinkData::class); - $Data->setQuery($query); - $Data->addParam($itemId); - - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('Error al obtener enlace'), SPException::ERROR); diff --git a/lib/SP/Repositories/Tag/TagRepository.php b/lib/SP/Repositories/Tag/TagRepository.php index c5a60269..c65d83d3 100644 --- a/lib/SP/Repositories/Tag/TagRepository.php +++ b/lib/SP/Repositories/Tag/TagRepository.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. @@ -24,7 +24,6 @@ namespace SP\Repositories\Tag; - use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; @@ -58,16 +57,13 @@ class TagRepository extends Repository implements RepositoryItemInterface throw new SPException(__u('Etiqueta duplicada'), SPException::INFO); } - $query = /** @lang SQL */ - 'INSERT INTO Tag SET name = ?, `hash` = ?'; + $queryData = new QueryData(); + $queryData->setQuery('INSERT INTO Tag SET name = ?, `hash` = ?'); + $queryData->addParam($itemData->getName()); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->setOnErrorMessage(__u('Error al crear etiqueta')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getHash()); - $Data->setOnErrorMessage(__u('Error al crear etiqueta')); - - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -75,22 +71,20 @@ class TagRepository extends Repository implements RepositoryItemInterface /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param TagData $itemData * @return bool * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function checkDuplicatedOnAdd($itemData) { - $query = /** @lang SQL */ - 'SELECT id FROM Tag WHERE `hash` = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getTagHash()); + $queryData = new QueryData(); + $queryData->setQuery('SELECT id FROM Tag WHERE `hash` = ?'); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); - DbWrapper::getQuery($Data); + DbWrapper::getQuery($queryData); - return $Data->getQueryNumRows() > 0; + return $this->db->getNumRows() > 0; } /** @@ -108,39 +102,34 @@ class TagRepository extends Repository implements RepositoryItemInterface throw new SPException(__u('Etiqueta duplicada'), SPException::INFO); } - $query = /** @lang SQL */ - 'UPDATE Tag SET name = ?, `hash` = ? WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('UPDATE Tag SET name = ?, `hash` = ? WHERE id = ? LIMIT 1'); + $queryData->addParam($itemData->getName()); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar etiqueta')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getHash()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar etiqueta')); - - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param TagData $itemData * @return bool * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function checkDuplicatedOnUpdate($itemData) { - $query = /** @lang SQL */ - 'SELECT hash FROM Tag WHERE `hash` = ? AND id <> ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getTagHash()); - $Data->addParam($itemData->getTagId()); + $queryData = new QueryData(); + $queryData->setQuery('SELECT hash FROM Tag WHERE `hash` = ? AND id <> ?'); + $queryData->addParam($this->makeItemHash($itemData->getName(), $this->db->getDbHandler())); + $queryData->addParam($itemData->getId()); - DbWrapper::getQuery($Data); + DbWrapper::getQuery($queryData); - return $Data->getQueryNumRows() > 0; + return $this->db->getNumRows() > 0; } /** @@ -151,15 +140,12 @@ class TagRepository extends Repository implements RepositoryItemInterface */ public function getById($id) { - $query = /** @lang SQL */ - 'SELECT id, name FROM Tag WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name FROM Tag WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setMapClassName(TagData::class); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setMapClassName(TagData::class); - - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -169,14 +155,11 @@ class TagRepository extends Repository implements RepositoryItemInterface */ public function getAll() { - $query = /** @lang SQL */ - 'SELECT id, name, `hash` FROM Tag ORDER BY name'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, `hash` FROM Tag ORDER BY name'); + $queryData->setMapClassName(TagData::class); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setMapClassName(TagData::class); - - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -190,26 +173,31 @@ class TagRepository extends Repository implements RepositoryItemInterface $query = /** @lang SQL */ 'SELECT id, name FROM Tag WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(TagData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setMapClassName(TagData::class); + $queryData->setQuery($query); + $queryData->setParams($ids); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** * Deletes all the items for given ids * * @param array $ids - * @return void + * @return int * @throws SPException */ public function deleteByIdBatch(array $ids) { - foreach ($ids as $id) { - $this->delete($id); - } + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Tag WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar etiquetas')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -222,17 +210,14 @@ class TagRepository extends Repository implements RepositoryItemInterface */ public function delete($id) { - $query = /** @lang SQL */ - 'DELETE FROM Tag WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM Tag WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar etiqueta')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar etiqueta')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -245,47 +230,44 @@ class TagRepository extends Repository implements RepositoryItemInterface */ public function checkInUse($id) { - $query = /** @lang SQL */ - 'SELECT tagId FROM AccountToTag WHERE tagId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT tagId FROM AccountToTag WHERE tagId = ?'); + $queryData->addParam($id); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() > 0; + return $this->db->getNumRows() > 0; } /** * Searches for items by a given filter * - * @param ItemSearchData $SearchData + * @param ItemSearchData $itemSearchData * @return mixed */ - public function search(ItemSearchData $SearchData) + public function search(ItemSearchData $itemSearchData) { - $Data = new QueryData(); - $Data->setSelect('id, name'); - $Data->setFrom('Tag'); - $Data->setOrder('name'); + $queryData = new QueryData(); + $queryData->setSelect('id, name'); + $queryData->setFrom('Tag'); + $queryData->setOrder('name'); - if ($SearchData->getSeachString() !== '') { - $Data->setWhere('name LIKE ?'); + if ($itemSearchData->getSeachString() !== '') { + $queryData->setWhere('name LIKE ?'); - $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); + $search = '%' . $itemSearchData->getSeachString() . '%'; + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($itemSearchData->getLimitStart()); + $queryData->addParam($itemSearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $this->db->getNumRows(); return $queryRes; } diff --git a/lib/SP/Repositories/User/UserRepository.php b/lib/SP/Repositories/User/UserRepository.php index 5dc923b1..1325b4ab 100644 --- a/lib/SP/Repositories/User/UserRepository.php +++ b/lib/SP/Repositories/User/UserRepository.php @@ -24,11 +24,9 @@ namespace SP\Repositories\User; -use SP\Core\Acl\Acl; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; -use SP\Log\Log; use SP\Repositories\NoSuchItemException; use SP\Repositories\Repository; use SP\Repositories\RepositoryItemInterface; @@ -78,26 +76,26 @@ class UserRepository extends Repository implements RepositoryItemInterface lastUpdate = NOW() WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getLogin()); - $Data->addParam($itemData->getSsoLogin()); - $Data->addParam($itemData->getEmail()); - $Data->addParam($itemData->getNotes()); - $Data->addParam($itemData->getUserGroupId()); - $Data->addParam($itemData->getUserProfileId()); - $Data->addParam($itemData->isIsAdminApp()); - $Data->addParam($itemData->isIsAdminAcc()); - $Data->addParam($itemData->isIsDisabled()); - $Data->addParam($itemData->isIsChangePass()); - $Data->addParam($itemData->isIsLdap()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar el usuario')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getLogin()); + $queryData->addParam($itemData->getSsoLogin()); + $queryData->addParam($itemData->getEmail()); + $queryData->addParam($itemData->getNotes()); + $queryData->addParam($itemData->getUserGroupId()); + $queryData->addParam($itemData->getUserProfileId()); + $queryData->addParam($itemData->isIsAdminApp()); + $queryData->addParam($itemData->isIsAdminAcc()); + $queryData->addParam($itemData->isIsDisabled()); + $queryData->addParam($itemData->isIsChangePass()); + $queryData->addParam($itemData->isIsLdap()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar el usuario')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - if ($Data->getQueryNumRows() > 0) { + if ($queryData->getQueryNumRows() > 0) { $itemData->setId(DbWrapper::getLastId()); } @@ -121,16 +119,16 @@ class UserRepository extends Repository implements RepositoryItemInterface OR (ssoLogin <> "" AND UPPER(ssoLogin) = UPPER(?)) OR UPPER(email) = UPPER(?))'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getId()); - $Data->addParam($itemData->getLogin()); - $Data->addParam($itemData->getSsoLogin()); - $Data->addParam($itemData->getEmail()); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getId()); + $queryData->addParam($itemData->getLogin()); + $queryData->addParam($itemData->getSsoLogin()); + $queryData->addParam($itemData->getEmail()); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -154,42 +152,35 @@ class UserRepository extends Repository implements RepositoryItemInterface lastUpdate = NOW() WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($passRequest->getPass()); - $Data->addParam($passRequest->getisChangePass()); - $Data->addParam($passRequest->getisChangedPass()); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al modificar la clave')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($passRequest->getPass()); + $queryData->addParam($passRequest->getisChangePass()); + $queryData->addParam($passRequest->getisChangedPass()); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al modificar la clave')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** * Deletes an item * * @param $id - * @return UserRepository - * @throws SPException + * @return int * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function delete($id) { - $query = 'DELETE FROM User WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM User WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar el usuario')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el usuario')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - if ($Data->getQueryNumRows() === 0) { - throw new SPException(__u('Usuario no encontrado'), SPException::INFO); - } - - return $this; + return $this->db->getNumRows(); } /** @@ -231,12 +222,12 @@ class UserRepository extends Repository implements RepositoryItemInterface INNER JOIN UserGroup UG ON U.userGroupId = UG.id WHERE U.id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setMapClassName(UserData::class); + $queryData->setQuery($query); + $queryData->addParam($id); - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('Error al obtener los datos del usuario'), SPException::ERROR); @@ -279,11 +270,11 @@ class UserRepository extends Repository implements RepositoryItemInterface U.isMigrate FROM User U'; - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setMapClassName(UserData::class); + $queryData->setQuery($query); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -328,23 +319,32 @@ class UserRepository extends Repository implements RepositoryItemInterface INNER JOIN UserGroup UG ON U.userGroupId = UG.id WHERE U.id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setMapClassName(UserData::class); + $queryData->setQuery($query); + $queryData->setParams($ids); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** * Deletes all the items for given ids * * @param array $ids - * @return void + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - throw new \RuntimeException('Not implemented'); + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM User WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar los usuarios')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -366,8 +366,8 @@ class UserRepository extends Repository implements RepositoryItemInterface */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setSelect('U.id, + $queryData = new QueryData(); + $queryData->setSelect('U.id, U.name, U.login, UP.name AS userProfileName, @@ -377,64 +377,36 @@ class UserRepository extends Repository implements RepositoryItemInterface U.isLdap, U.isDisabled, U.isChangePass'); - $Data->setFrom('User U INNER JOIN UserProfile UP ON U.userProfileId = UP.id INNER JOIN UserGroup UG ON U.userGroupId = UG.id'); - $Data->setOrder('U.name'); + $queryData->setFrom('User U INNER JOIN UserProfile UP ON U.userProfileId = UP.id INNER JOIN UserGroup UG ON U.userGroupId = UG.id'); + $queryData->setOrder('U.name'); if ($SearchData->getSeachString() !== '') { if ($this->session->getUserData()->getIsAdminApp()) { - $Data->setWhere('U.name LIKE ? OR U.login LIKE ?'); + $queryData->setWhere('U.name LIKE ? OR U.login LIKE ?'); } else { - $Data->setWhere('U.name LIKE ? OR U.login LIKE ? AND U.isAdminApp = 0'); + $queryData->setWhere('U.name LIKE ? OR U.login LIKE ? AND U.isAdminApp = 0'); } $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); } elseif (!$this->session->getUserData()->getIsAdminApp()) { - $Data->setWhere('U.isAdminApp = 0'); + $queryData->setWhere('U.isAdminApp = 0'); } - $Data->setLimit('?, ?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?, ?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } - /** - * Logs user action - * - * @param int $id - * @param int $actionId - * @return \SP\Core\Messages\LogMessage - */ - public function logAction($id, $actionId) - { - $query = /** @lang SQL */ - 'SELECT id, login, name FROM User WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - $user = DbWrapper::getResults($Data, $this->db); - - $Log = new Log(); - $LogMessage = $Log->getLogMessage(); - $LogMessage->setAction(Acl::getActionInfo($actionId)); - $LogMessage->addDetails(__u('Usuario'), sprintf('%s (%s)', $user->name, $user->login)); - $LogMessage->addDetails(__u('ID'), $id); - $Log->writeLog(); - - return $LogMessage; - } - /** * Creates an item * @@ -468,27 +440,27 @@ class UserRepository extends Repository implements RepositoryItemInterface pass = ?, hashSalt = \'\''; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getLogin()); - $Data->addParam($itemData->getSsoLogin()); - $Data->addParam($itemData->getEmail()); - $Data->addParam($itemData->getNotes()); - $Data->addParam($itemData->getUserGroupId()); - $Data->addParam($itemData->getUserProfileId()); - $Data->addParam($itemData->getMPass()); - $Data->addParam($itemData->getMKey()); - $Data->addParam($itemData->getLastUpdateMPass()); - $Data->addParam($itemData->isIsAdminApp()); - $Data->addParam($itemData->isIsAdminAcc()); - $Data->addParam($itemData->isIsDisabled()); - $Data->addParam($itemData->isIsChangePass()); - $Data->addParam($itemData->isIsLdap()); - $Data->addParam($itemData->getPass()); - $Data->setOnErrorMessage(__u('Error al crear el usuario')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getLogin()); + $queryData->addParam($itemData->getSsoLogin()); + $queryData->addParam($itemData->getEmail()); + $queryData->addParam($itemData->getNotes()); + $queryData->addParam($itemData->getUserGroupId()); + $queryData->addParam($itemData->getUserProfileId()); + $queryData->addParam($itemData->getMPass()); + $queryData->addParam($itemData->getMKey()); + $queryData->addParam($itemData->getLastUpdateMPass()); + $queryData->addParam($itemData->isIsAdminApp()); + $queryData->addParam($itemData->isIsAdminAcc()); + $queryData->addParam($itemData->isIsDisabled()); + $queryData->addParam($itemData->isIsChangePass()); + $queryData->addParam($itemData->isIsLdap()); + $queryData->addParam($itemData->getPass()); + $queryData->setOnErrorMessage(__u('Error al crear el usuario')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -510,15 +482,15 @@ class UserRepository extends Repository implements RepositoryItemInterface OR UPPER(ssoLogin) = UPPER(?) OR UPPER(email) = UPPER(?)'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getLogin()); - $Data->addParam($itemData->getSsoLogin()); - $Data->addParam($itemData->getEmail()); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getLogin()); + $queryData->addParam($itemData->getSsoLogin()); + $queryData->addParam($itemData->getEmail()); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -558,19 +530,19 @@ class UserRepository extends Repository implements RepositoryItemInterface INNER JOIN UserGroup UG ON U.userGroupId = UG.id WHERE U.login = ? OR U.ssoLogin = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->addParam($login); - $Data->addParam($login); + $queryData = new QueryData(); + $queryData->setMapClassName(UserData::class); + $queryData->setQuery($query); + $queryData->addParam($login); + $queryData->addParam($login); - $queryRes = DbWrapper::getResults($Data, $this->db); + $queryRes = DbWrapper::getResults($queryData, $this->db); if ($queryRes === false) { throw new SPException(__u('Error al obtener los datos del usuario'), SPException::ERROR); } - if ($Data->getQueryNumRows() === 0) { + if ($queryData->getQueryNumRows() === 0) { throw new NoSuchItemException(__u('El usuario no existe')); } @@ -597,11 +569,11 @@ class UserRepository extends Repository implements RepositoryItemInterface U.isDisabled FROM User U'; - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->setMapClassName(UserData::class); + $queryData->setQuery($query); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -625,13 +597,13 @@ class UserRepository extends Repository implements RepositoryItemInterface isChangedPass = 0 WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($pass); - $Data->addParam($key); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($pass); + $queryData->addParam($key); + $queryData->addParam($id); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -644,11 +616,11 @@ class UserRepository extends Repository implements RepositoryItemInterface */ public function updateLastLoginById($id) { - $Data = new QueryData(); - $Data->setQuery('UPDATE User SET lastLogin = NOW(), loginCount = loginCount + 1 WHERE id = ? LIMIT 1'); - $Data->addParam($id); + $queryData = new QueryData(); + $queryData->setQuery('UPDATE User SET lastLogin = NOW(), loginCount = loginCount + 1 WHERE id = ? LIMIT 1'); + $queryData->addParam($id); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } /** @@ -659,14 +631,14 @@ class UserRepository extends Repository implements RepositoryItemInterface */ public function checkExistsByLogin($login) { - $Data = new QueryData(); - $Data->setQuery('SELECT id FROM User WHERE UPPER(login) = UPPER(?) OR UPPER(ssoLogin) = UPPER(?) LIMIT 1'); - $Data->addParam($login); - $Data->addParam($login); + $queryData = new QueryData(); + $queryData->setQuery('SELECT id FROM User WHERE UPPER(login) = UPPER(?) OR UPPER(ssoLogin) = UPPER(?) LIMIT 1'); + $queryData->addParam($login); + $queryData->addParam($login); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -687,16 +659,16 @@ class UserRepository extends Repository implements RepositoryItemInterface isLdap = ? WHERE UPPER(login) = UPPER(?) OR UPPER(ssoLogin) = UPPER(?) LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getPass()); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getEmail()); - $Data->addParam($itemData->isIsLdap()); - $Data->addParam($itemData->getLogin()); - $Data->addParam($itemData->getLogin()); - $Data->setOnErrorMessage(__u('Error al actualizar el usuario')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getPass()); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getEmail()); + $queryData->addParam($itemData->isIsLdap()); + $queryData->addParam($itemData->getLogin()); + $queryData->addParam($itemData->getLogin()); + $queryData->setOnErrorMessage(__u('Error al actualizar el usuario')); - return DbWrapper::getQuery($Data, $this->db); + return DbWrapper::getQuery($queryData, $this->db); } } \ No newline at end of file diff --git a/lib/SP/Repositories/UserGroup/UserGroupRepository.php b/lib/SP/Repositories/UserGroup/UserGroupRepository.php index 745bad97..3abbf21a 100644 --- a/lib/SP/Repositories/UserGroup/UserGroupRepository.php +++ b/lib/SP/Repositories/UserGroup/UserGroupRepository.php @@ -24,11 +24,9 @@ namespace SP\Repositories\UserGroup; -use SP\Core\Acl\Acl; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; -use SP\Log\Log; use SP\Repositories\Repository; use SP\Repositories\RepositoryItemInterface; use SP\Repositories\RepositoryItemTrait; @@ -57,17 +55,14 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface throw new SPException(__u('Grupo en uso'), SPException::WARNING); } - $query = /** @lang SQL */ - 'DELETE FROM UserGroup WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM UserGroup WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar el grupo')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el grupo')); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $queryData->getQueryNumRows(); } /** @@ -87,13 +82,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface SELECT userGroupId FROM Account WHERE userGroupId = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParams(array_fill(0, 2, (int)$id)); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setParams([(int)$id, (int)$id]); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -105,23 +100,23 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface public function getUsage($id) { $query = /** @lang SQL */ - 'SELECT userGroupId, "User" as ref + 'SELECT userGroupId, "User" AS ref FROM User WHERE userGroupId = ? UNION ALL - SELECT userGroupId, "UserGroup" as ref + SELECT userGroupId, "UserGroup" AS ref FROM UserToUserGroup WHERE userGroupId = ? UNION ALL - SELECT userGroupId, "AccountToUserGroup" as ref + SELECT userGroupId, "AccountToUserGroup" AS ref FROM AccountToUserGroup WHERE userGroupId = ? UNION ALL - SELECT userGroupId, "Account" as ref + SELECT userGroupId, "Account" AS ref FROM Account WHERE userGroupId = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParams(array_fill(0, 4, (int)$id)); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParams(array_fill(0, 4, (int)$id)); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -132,15 +127,12 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function getById($id) { - $query = /** @lang SQL */ - 'SELECT id, name, description FROM UserGroup WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, description FROM UserGroup WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setMapClassName(UserGroupData::class); - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -151,15 +143,12 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function getByName($name) { - $query = /** @lang SQL */ - 'SELECT id, name, description FROM UserGroup WHERE name = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, description FROM UserGroup WHERE name = ? LIMIT 1'); + $queryData->addParam($name); + $queryData->setMapClassName(UserGroupData::class); - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setQuery($query); - $Data->addParam($name); - - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -169,14 +158,11 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function getAll() { - $query = /** @lang SQL */ - 'SELECT id, name, description FROM UserGroup ORDER BY name'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, description FROM UserGroup ORDER BY name'); + $queryData->setMapClassName(UserGroupData::class); - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setQuery($query); - - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -194,12 +180,12 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface $query = /** @lang SQL */ 'SELECT id, name, description FROM UserGroup WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setMapClassName(UserGroupData::class); + $queryData->setQuery($query); + $queryData->setParams($ids); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -212,17 +198,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function deleteByIdBatch(array $ids) { - $query = /** @lang SQL */ - 'DELETE FROM UserGroup WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM UserGroup WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setQuery($query); - $Data->setParams($ids); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -233,29 +215,29 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setMapClassName(UserGroupData::class); - $Data->setSelect('id, name, description'); - $Data->setFrom('UserGroup'); - $Data->setOrder('name'); + $queryData = new QueryData(); + $queryData->setMapClassName(UserGroupData::class); + $queryData->setSelect('id, name, description'); + $queryData->setFrom('UserGroup'); + $queryData->setOrder('name'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('name LIKE ? OR description LIKE ?'); + $queryData->setWhere('name LIKE ? OR description LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); + $queryData->addParam($search); + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } @@ -278,13 +260,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface $query = /** @lang SQL */ 'INSERT INTO UserGroup SET name = ?, description = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getDescription()); - $Data->setOnErrorMessage(__u('Error al crear el grupo')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getDescription()); + $queryData->setOnErrorMessage(__u('Error al crear el grupo')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -299,15 +281,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function checkDuplicatedOnAdd($itemData) { - $query = /** @lang SQL */ - 'SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?)'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); + $queryData = new QueryData(); + $queryData->setQuery('SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?)'); + $queryData->addParam($itemData->getName()); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -325,17 +305,14 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface throw new SPException(__u('Nombre de grupo duplicado'), SPException::INFO); } - $query = /** @lang SQL */ - 'UPDATE UserGroup SET name = ?, description = ? WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('UPDATE UserGroup SET name = ?, description = ? WHERE id = ? LIMIT 1'); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getDescription()); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al actualizar el grupo')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getDescription()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al actualizar el grupo')); - - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this; } @@ -350,43 +327,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface */ public function checkDuplicatedOnUpdate($itemData) { - $query = /** @lang SQL */ - 'SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?) AND id <> ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getId()); + $queryData = new QueryData(); + $queryData->setQuery('SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?) AND id <> ?'); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getId()); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return $Data->getQueryNumRows() > 0; - } - - /** - * Logs group action - * - * @param int $id - * @param int $actionId - * @return \SP\Core\Messages\LogMessage - */ - public function logAction($id, $actionId) - { - $query = /** @lang SQL */ - 'SELECT name FROM UserGroup WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - $usergroup = DbWrapper::getResults($Data, $this->db); - - $Log = new Log(); - $LogMessage = $Log->getLogMessage(); - $LogMessage->setAction(Acl::getActionInfo($actionId)); - $LogMessage->addDetails(__u('Grupo'), $usergroup->name); - $LogMessage->addDetails(__u('ID'), $id); - $Log->writeLog(); - - return $LogMessage; + return $queryData->getQueryNumRows() > 0; } } \ No newline at end of file diff --git a/lib/SP/Repositories/UserProfile/UserProfileRepository.php b/lib/SP/Repositories/UserProfile/UserProfileRepository.php index 33ea5590..7cecc842 100644 --- a/lib/SP/Repositories/UserProfile/UserProfileRepository.php +++ b/lib/SP/Repositories/UserProfile/UserProfileRepository.php @@ -24,12 +24,10 @@ namespace SP\Repositories\UserProfile; -use SP\Core\Acl\Acl; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; use SP\DataModel\UserProfileData; -use SP\Log\Log; use SP\Repositories\Repository; use SP\Repositories\RepositoryItemInterface; use SP\Repositories\RepositoryItemTrait; @@ -53,14 +51,11 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function getUsersForProfile($id) { - $query = /** @lang SQL */ - 'SELECT login FROM User WHERE userProfileId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT login FROM User WHERE userProfileId = ?'); + $queryData->addParam($id); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -78,17 +73,14 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac throw new SPException(__u('Perfil en uso'), SPException::INFO); } - $query = /** @lang SQL */ - 'DELETE FROM UserProfile WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM UserProfile WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setOnErrorMessage(__u('Error al eliminar perfil')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__('Error al eliminar perfil', false)); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows(); + return $this->db->getNumRows(); } /** @@ -101,16 +93,13 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function checkInUse($id) { - $query = /** @lang SQL */ - 'SELECT userProfileId FROM User WHERE userProfileId = ?'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT userProfileId FROM User WHERE userProfileId = ?'); + $queryData->addParam($id); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return ($Data->getQueryNumRows() > 0); + return $queryData->getQueryNumRows() > 0; } /** @@ -121,15 +110,12 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function getById($id) { - $query = /** @lang SQL */ - 'SELECT id, name, profile FROM UserProfile WHERE id = ? LIMIT 1'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name, profile FROM UserProfile WHERE id = ? LIMIT 1'); + $queryData->addParam($id); + $queryData->setMapClassName(UserProfileData::class); - $Data = new QueryData(); - $Data->setMapClassName(UserProfileData::class); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getResults($Data, $this->db); + return DbWrapper::getResults($queryData, $this->db); } /** @@ -139,14 +125,11 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function getAll() { - $query = /** @lang SQL */ - 'SELECT id, name FROM UserProfile ORDER BY name'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT id, name FROM UserProfile ORDER BY name'); + $queryData->setMapClassName(UserProfileData::class); - $Data = new QueryData(); - $Data->setMapClassName(UserProfileData::class); - $Data->setQuery($query); - - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** @@ -164,23 +147,32 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac $query = /** @lang SQL */ 'SELECT id, name FROM UserProfile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - $Data = new QueryData(); - $Data->setMapClassName(ProfileData::class); - $Data->setQuery($query); - $Data->setParams($ids); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->setParams($ids); + $queryData->setMapClassName(ProfileData::class); - return DbWrapper::getResultsArray($Data, $this->db); + return DbWrapper::getResultsArray($queryData, $this->db); } /** * Deletes all the items for given ids * * @param array $ids - * @return void + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - throw new \RuntimeException('Not implemented'); + $queryData = new QueryData(); + $queryData->setQuery('DELETE FROM UserProfile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setParams($ids); + $queryData->setOnErrorMessage(__u('Error al eliminar los perfiles')); + + DbWrapper::getQuery($queryData, $this->db); + + return $this->db->getNumRows(); } /** @@ -191,27 +183,27 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function search(ItemSearchData $SearchData) { - $Data = new QueryData(); - $Data->setSelect('id, name'); - $Data->setFrom('UserProfile'); - $Data->setOrder('name'); + $queryData = new QueryData(); + $queryData->setSelect('id, name'); + $queryData->setFrom('UserProfile'); + $queryData->setOrder('name'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('name LIKE ?'); + $queryData->setWhere('name LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); + $queryData->addParam($search); } - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); + $queryData->setLimit('?,?'); + $queryData->addParam($SearchData->getLimitStart()); + $queryData->addParam($SearchData->getLimitCount()); DbWrapper::setFullRowCount(); - $queryRes = DbWrapper::getResultsArray($Data, $this->db); + $queryRes = DbWrapper::getResultsArray($queryData, $this->db); - $queryRes['count'] = $Data->getQueryNumRows(); + $queryRes['count'] = $queryData->getQueryNumRows(); return $queryRes; } @@ -231,18 +223,13 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac throw new SPException(__u('Nombre de perfil duplicado'), SPException::INFO); } - $query = /** @lang SQL */ - 'INSERT INTO UserProfile SET - name = ?, - profile = ?'; + $queryData = new QueryData(); + $queryData->setQuery('INSERT INTO UserProfile SET name = ?, profile = ?'); + $queryData->addParam($itemData->getName()); + $queryData->addParam(serialize($itemData->getProfile())); + $queryData->setOnErrorMessage(__u('Error al crear perfil')); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getProfile()); - $Data->setOnErrorMessage(__u('Error al crear perfil')); - - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); return $this->db->getLastId(); } @@ -257,18 +244,13 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac */ public function checkDuplicatedOnAdd($itemData) { - $query = /** @lang SQL */ - 'SELECT name - FROM UserProfile - WHERE UPPER(name) = ?'; + $queryData = new QueryData(); + $queryData->setQuery('SELECT name FROM UserProfile WHERE UPPER(name) = ?'); + $queryData->addParam($itemData->getName()); - $Data = new QueryData(); - $Data->addParam($itemData->getName()); - $Data->setQuery($query); + DbWrapper::getQuery($queryData, $this->db); - DbWrapper::getQuery($Data, $this->db); - - return ($Data->getQueryNumRows() > 0); + return $queryData->getQueryNumRows() > 0; } /** @@ -289,20 +271,16 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac $query = /** @lang SQL */ 'UPDATE UserProfile SET name = ?, profile = ? WHERE id = ? LIMIT 1'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getProfile()); - $Data->addParam($itemData->getId()); - $Data->setOnErrorMessage(__u('Error al modificar perfil')); + $queryData = new QueryData(); + $queryData->setQuery($query); + $queryData->addParam($itemData->getName()); + $queryData->addParam(serialize($itemData->getProfile())); + $queryData->addParam($itemData->getId()); + $queryData->setOnErrorMessage(__u('Error al modificar perfil')); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); -// if ($Data->getQueryNumRows() > 0) { -// $this->updateSessionProfile(); -// } - - return $Data->getQueryNumRows() > 0; + return $queryData->getQueryNumRows() > 0; } /** @@ -321,41 +299,13 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac WHERE UPPER(name) = ? AND id <> ?'; - $Data = new QueryData(); - $Data->addParam($itemData->getName()); - $Data->addParam($itemData->getId()); - $Data->setQuery($query); + $queryData = new QueryData(); + $queryData->addParam($itemData->getName()); + $queryData->addParam($itemData->getId()); + $queryData->setQuery($query); - DbWrapper::getQuery($Data, $this->db); + DbWrapper::getQuery($queryData, $this->db); - return ($Data->getQueryNumRows() > 0); - } - - /** - * Logs profile action - * - * @param int $id - * @param int $actionId - * @return \SP\Core\Messages\LogMessage - */ - public function logAction($id, $actionId) - { - $query = /** @lang SQL */ - 'SELECT name FROM UserProfile WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - $userprofile = DbWrapper::getResults($Data, $this->db); - - $Log = new Log(); - $LogMessage = $Log->getLogMessage(); - $LogMessage->setAction(Acl::getActionInfo($actionId)); - $LogMessage->addDetails(__u('Perfil'), $userprofile->name); - $LogMessage->addDetails(__u('ID'), $id); - $Log->writeLog(); - - return $LogMessage; + return ($queryData->getQueryNumRows() > 0); } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountFavoriteService.php b/lib/SP/Services/Account/AccountFavoriteService.php new file mode 100644 index 00000000..f74d142c --- /dev/null +++ b/lib/SP/Services/Account/AccountFavoriteService.php @@ -0,0 +1,88 @@ +. + */ + +namespace SP\Services\Account; + +use SP\Repositories\Account\AccountFavoriteRepository; +use SP\Services\Service; + +/** + * Class AccountFavoriteService + * + * @package SP\Services\Account + */ +class AccountFavoriteService extends Service +{ + /** + * @var AccountFavoriteRepository + */ + protected $accountFavoriteRepository; + + /** + * Obtener un array con los Ids de cuentas favoritas + * + * @param $id int El Id de usuario + * @return array + */ + public function getForUserId($id) + { + return $this->accountFavoriteRepository->getForUserId($id); + } + + /** + * Añadir una cuenta a la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * @return bool + * @throws \SP\Core\Exceptions\SPException + */ + public function add($accountId, $userId) + { + return $this->accountFavoriteRepository->add($accountId, $userId); + } + + /** + * Eliminar una cuenta de la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete($accountId, $userId) + { + return $this->accountFavoriteRepository->delete($accountId, $userId); + } + + /** + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function initialize() + { + $this->accountFavoriteRepository = $this->dic->get(AccountFavoriteRepository::class); + } +} \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountFileService.php b/lib/SP/Services/Account/AccountFileService.php index dfbbdf96..a875a19f 100644 --- a/lib/SP/Services/Account/AccountFileService.php +++ b/lib/SP/Services/Account/AccountFileService.php @@ -32,6 +32,7 @@ use SP\DataModel\ItemSearchData; use SP\Mgmt\Files\FileUtil; use SP\Repositories\Account\AccountFileRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Util\ImageUtil; /** @@ -62,6 +63,7 @@ class AccountFileService extends Service * * @param FileData $itemData * @return mixed + * @throws SPException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ @@ -121,26 +123,35 @@ class AccountFileService extends Service * Deletes all the items for given ids * * @param array $ids - * @return void - * @throws SPException + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function deleteByIdBatch(array $ids) { - foreach ($ids as $id) { - $this->delete($id); + if (($count = $this->accountFileRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar archivos'), ServiceException::WARNING); } + + return $count; } /** * Deletes an item * * @param $id - * @return AccountFileRepository + * @return AccountFileService * @throws SPException + * @throws ServiceException */ public function delete($id) { - return $this->accountFileRepository->delete($id); + if ($this->accountFileRepository->delete($id) === 0) { + throw new ServiceException(__u('Archivo no encontrado'), ServiceException::INFO); + } + + return $this; } /** diff --git a/lib/SP/Services/Account/AccountSearchService.php b/lib/SP/Services/Account/AccountSearchService.php index 0d42cdc5..551dfc7c 100644 --- a/lib/SP/Services/Account/AccountSearchService.php +++ b/lib/SP/Services/Account/AccountSearchService.php @@ -25,7 +25,6 @@ namespace SP\Services\Account; use SP\Account\AccountAcl; -use SP\Account\AccountFavorites; use SP\Account\AccountSearchFilter; use SP\Account\AccountSearchItem; use SP\Config\ConfigData; @@ -132,8 +131,7 @@ class AccountSearchService extends Service $maxTextLength = $this->configData->isResultsAsCards() ? 40 : 60; $accountLinkEnabled = $this->session->getUserData()->getPreferences()->isAccountLink() || $this->configData->isAccountLink(); - // FIXME - $favorites = AccountFavorites::getFavorites($this->session->getUserData()->getId()); + $favorites = $this->dic->get(AccountFavoriteService::class)->getForUserId($this->session->getUserData()->getId()); foreach ($accountSearchResponse->getData() as $accountSearchData) { $cache = $this->getCacheForAccount($accountSearchData); diff --git a/lib/SP/Services/Account/AccountService.php b/lib/SP/Services/Account/AccountService.php index 7e71ccc4..d6c0e81c 100644 --- a/lib/SP/Services/Account/AccountService.php +++ b/lib/SP/Services/Account/AccountService.php @@ -377,12 +377,32 @@ class AccountService extends Service implements AccountServiceInterface /** * @param $id - * @return bool + * @return AccountService * @throws SPException + * @throws ServiceException */ public function delete($id) { - return $this->accountRepository->delete($id); + if ($this->accountRepository->delete($id) === 0) { + throw new ServiceException(__u('Cuenta no encontrada'), ServiceException::INFO); + } + + return $this; + } + + /** + * @param array $ids + * @return AccountService + * @throws SPException + * @throws ServiceException + */ + public function deleteByIdBatch(array $ids) + { + if ($this->accountRepository->deleteByIdBatch($ids) === 0) { + throw new ServiceException(__u('Error al eliminar las cuentas'), ServiceException::WARNING); + } + + return $this; } /** @@ -467,7 +487,7 @@ class AccountService extends Service implements AccountServiceInterface /** * Devolver el número total de cuentas * - * @return int + * @return \stdClass */ public function getTotalNumAccounts() { diff --git a/lib/SP/Services/Auth/LoginService.php b/lib/SP/Services/Auth/LoginService.php index dcb7a05b..3f9bb0af 100644 --- a/lib/SP/Services/Auth/LoginService.php +++ b/lib/SP/Services/Auth/LoginService.php @@ -133,7 +133,8 @@ class LoginService extends Service $this->userLoginData->setLoginPass(Request::analyzeEncrypted('pass')); try { - $this->checkTracking(); + // FIXME: add service +// $this->checkTracking(); $auth = new Auth($this->userLoginData, $this->configData); @@ -380,7 +381,7 @@ class LoginService extends Service // Cargar las variables de ussuario en la sesión $this->session->setUserData($userLoginResponse); - $this->session->setUserProfile($this->dic->get(UserProfileService::class)->getById($userLoginResponse->getUserProfileId())); + $this->session->setUserProfile($this->dic->get(UserProfileService::class)->getById($userLoginResponse->getUserProfileId())->getProfile()); if ($this->configData->isDemoEnabled()) { $userLoginResponse->setPreferences(new UserPreferencesData()); diff --git a/lib/SP/Services/AuthToken/AuthTokenService.php b/lib/SP/Services/AuthToken/AuthTokenService.php index fe65ebf1..7189fe2b 100644 --- a/lib/SP/Services/AuthToken/AuthTokenService.php +++ b/lib/SP/Services/AuthToken/AuthTokenService.php @@ -33,6 +33,7 @@ use SP\DataModel\AuthTokenData; use SP\DataModel\ItemSearchData; use SP\Repositories\AuthToken\AuthTokenRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; use SP\Util\Util; @@ -94,6 +95,24 @@ class AuthTokenService extends Service return $this; } + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return bool + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->authTokenRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar tokens'), ServiceException::WARNING); + } + + return $count; + } + /** * @param $itemData * @return mixed diff --git a/lib/SP/Services/Category/CategoryService.php b/lib/SP/Services/Category/CategoryService.php index 1d104d5c..6b90a976 100644 --- a/lib/SP/Services/Category/CategoryService.php +++ b/lib/SP/Services/Category/CategoryService.php @@ -29,6 +29,7 @@ use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; use SP\Repositories\Category\CategoryRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; /** @@ -78,17 +79,34 @@ class CategoryService extends Service * @throws SPException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Core\Dic\ContainerException */ public function delete($id) { if ($this->categoryRepository->delete($id) === 0) { - throw new SPException(__u('Categoría no encontrada'), SPException::INFO); + throw new ServiceException(__u('Categoría no encontrada'), ServiceException::INFO); } return $this; } + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->categoryRepository->deleteByIdBatch($ids)) === count($ids)) { + throw new ServiceException(__u('Error al eliminar la categoría'), ServiceException::WARNING); + } + + return $count; + } + /** * @param $itemData * @return mixed diff --git a/lib/SP/Services/Client/ClientService.php b/lib/SP/Services/Client/ClientService.php index 71c60082..7fe4d114 100644 --- a/lib/SP/Services/Client/ClientService.php +++ b/lib/SP/Services/Client/ClientService.php @@ -31,6 +31,7 @@ use SP\DataModel\ClientData; use SP\DataModel\ItemSearchData; use SP\Repositories\Client\ClientRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; /** @@ -86,12 +87,28 @@ class ClientService extends Service public function delete($id) { if ($this->clientRepository->delete($id) === 0) { - throw new SPException(__u('Cliente no encontrado'), SPException::INFO); + throw new ServiceException(__u('Cliente no encontrado'), ServiceException::INFO); } return $this; } + /** + * @param array $ids + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->clientRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar los clientes'), ServiceException::WARNING); + } + + return $count; + } + /** * @param $itemData * @return mixed diff --git a/lib/SP/Services/CustomField/CustomFieldDefService.php b/lib/SP/Services/CustomField/CustomFieldDefService.php index b943a2c3..62374670 100644 --- a/lib/SP/Services/CustomField/CustomFieldDefService.php +++ b/lib/SP/Services/CustomField/CustomFieldDefService.php @@ -27,6 +27,7 @@ namespace SP\Services\CustomField; use SP\DataModel\ItemSearchData; use SP\Repositories\CustomField\CustomFieldDefRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; /** @@ -72,14 +73,38 @@ class CustomFieldDefService extends Service /** * @param $id - * @return bool + * @return CustomFieldDefService + * @throws ServiceException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException */ public function delete($id) { - return $this->customFieldDefRepository->delete($id); + if ($this->customFieldDefRepository->delete($id) === 0) { + throw new ServiceException(__u('Campo no encontrado'), ServiceException::INFO); + } + + return $this; + } + + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->customFieldDefRepository->deleteByIdBatch($ids)) !== count($ids)){ + throw new ServiceException(__u('Error al eliminar los campos'), ServiceException::WARNING); + } + + return $count; } /** diff --git a/lib/SP/Services/CustomField/CustomFieldService.php b/lib/SP/Services/CustomField/CustomFieldService.php index 07b209cf..cd3e13b6 100644 --- a/lib/SP/Services/CustomField/CustomFieldService.php +++ b/lib/SP/Services/CustomField/CustomFieldService.php @@ -184,6 +184,20 @@ class CustomFieldService extends Service $customFieldData->setKey($securedKey); } + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int[] $ids + * @param int $moduleId + * @return bool + * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function deleteCustomFieldDataBatch(array $ids, $moduleId) + { + return $this->customFieldRepository->deleteCustomFieldDataBatch($ids, $moduleId); + } + /** * Updates an item * diff --git a/lib/SP/Services/Notification/NotificationService.php b/lib/SP/Services/Notification/NotificationService.php new file mode 100644 index 00000000..6a5589ed --- /dev/null +++ b/lib/SP/Services/Notification/NotificationService.php @@ -0,0 +1,255 @@ +. + */ + +namespace SP\Services\Notification; + +use SP\DataModel\ItemSearchData; +use SP\DataModel\NotificationData; +use SP\Repositories\Notification\NotificationRepository; +use SP\Services\Service; +use SP\Services\ServiceException; + +/** + * Class NotificationService + * + * @package SP\Services\Notification + */ +class NotificationService extends Service +{ + /** + * @var NotificationRepository + */ + protected $notificationRepository; + + /** + * Creates an item + * + * @param NotificationData $itemData + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function create(NotificationData $itemData) + { + return $this->notificationRepository->create($itemData); + } + + /** + * Updates an item + * + * @param NotificationData $itemData + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function update(NotificationData $itemData) + { + return $this->notificationRepository->update($itemData); + } + + /** + * Devolver los elementos con los ids especificados + * + * @param array $ids + * @return mixed + */ + public function getByIdBatch(array $ids) + { + return $this->notificationRepository->getByIdBatch($ids); + } + + /** + * Deletes an item preserving the sticky ones + * + * @param $id + * @return NotificationService + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete($id) + { + if ($this->notificationRepository->delete($id) === 0) { + throw new ServiceException(__u('Notificación no encontrada'), ServiceException::INFO); + } + + return $this; + } + + /** + * Deletes an item + * + * @param $id + * @return NotificationService + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteAdmin($id) + { + if ($this->notificationRepository->deleteAdmin($id) === 0) { + throw new ServiceException(__u('Notificación no encontrada'), ServiceException::INFO); + } + + return $this; + } + + /** + * Deletes an item + * + * @param array $ids + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws ServiceException + */ + public function deleteAdminBatch(array $ids) + { + if (($count = $this->notificationRepository->deleteAdminBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar las notificaciones'), ServiceException::WARNING); + } + + return $count; + } + + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws ServiceException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->notificationRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar las notificaciones'), ServiceException::WARNING); + } + + return $count; + } + + /** + * Returns the item for given id + * + * @param int $id + * @return NotificationData + */ + public function getById($id) + { + return $this->notificationRepository->getById($id); + } + + /** + * Returns all the items + * + * @return NotificationData[] + */ + public function getAll() + { + return $this->notificationRepository->getAll(); + } + + /** + * Marcar una notificación como leída + * + * @param $id + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function setCheckedById($id) + { + return $this->notificationRepository->setCheckedById($id); + } + + /** + * Devolver las notificaciones de un usuario para una fecha y componente determinados + * + * @param $component + * @param $id + * @return NotificationData[] + */ + public function getForUserIdByDate($component, $id) + { + return $this->notificationRepository->getForUserIdByDate($component, $id); + } + + /** + * @param $id + * @return NotificationData[] + */ + public function getAllForUserId($id) + { + return $this->notificationRepository->getAllForUserId($id); + } + + /** + * @param $id + * @return NotificationData[] + */ + public function getAllActiveForUserId($id) + { + return $this->notificationRepository->getAllForUserId($id); + } + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @return mixed + */ + public function search(ItemSearchData $itemSearchData) + { + $userData = $this->session->getUserData(); + + if ($userData->getIsAdminApp()) { + return $this->notificationRepository->search($itemSearchData); + } + + return $this->notificationRepository->searchForUserId($itemSearchData, $userData->getId()); + } + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @param int $userId + * @return mixed + */ + public function searchForUserId(ItemSearchData $itemSearchData, $userId) + { + return $this->notificationRepository->searchForUserId($itemSearchData, $userId); + } + + /** + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function initialize() + { + $this->notificationRepository = $this->dic->get(NotificationRepository::class); + } +} \ No newline at end of file diff --git a/lib/SP/Services/PublicLink/PublicLinkService.php b/lib/SP/Services/PublicLink/PublicLinkService.php index 38cc1afd..f3b5340d 100644 --- a/lib/SP/Services/PublicLink/PublicLinkService.php +++ b/lib/SP/Services/PublicLink/PublicLinkService.php @@ -36,6 +36,7 @@ use SP\Http\Request; use SP\Repositories\PublicLink\PublicLinkRepository; use SP\Services\Account\AccountService; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; use SP\Util\Checks; use SP\Util\HttpUtil; @@ -197,12 +198,30 @@ class PublicLinkService extends Service public function delete($id) { if ($this->publicLinkRepository->delete($id) === 0) { - throw new SPException(__u('Enlace no encontrado'), SPException::INFO); + throw new ServiceException(__u('Enlace no encontrado'), ServiceException::INFO); } return $this; } + /** + * Deletes all the items for given ids + * + * @param array $ids + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws ServiceException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->publicLinkRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar los enlaces'), ServiceException::WARNING); + } + + return $count; + } + /** * @param PublicLinkData $itemData * @return int diff --git a/lib/SP/Services/Tag/TagService.php b/lib/SP/Services/Tag/TagService.php index 9cd09c34..0b5a455b 100644 --- a/lib/SP/Services/Tag/TagService.php +++ b/lib/SP/Services/Tag/TagService.php @@ -29,6 +29,7 @@ use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; use SP\Repositories\Tag\TagRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; /** @@ -45,15 +46,6 @@ class TagService extends Service */ protected $tagRepository; - /** - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface - */ - protected function initialize() - { - $this->tagRepository = $this->dic->get(TagRepository::class); - } - /** * @param ItemSearchData $itemSearchData * @return \SP\DataModel\ClientData[] @@ -80,7 +72,21 @@ class TagService extends Service public function delete($id) { if ($this->tagRepository->delete($id) === 0) { - throw new SPException(__u('Etiqueta no encontrada'), SPException::INFO); + throw new ServiceException(__u('Etiqueta no encontrada'), ServiceException::INFO); + } + + return $this; + } + + /** + * @param array $ids + * @return $this + * @throws SPException + */ + public function deleteByIdBatch(array $ids) + { + if ($this->tagRepository->deleteByIdBatch($ids) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar etiquetas'), ServiceException::WARNING); } return $this; @@ -117,4 +123,13 @@ class TagService extends Service { return $this->tagRepository->getAll(); } + + /** + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function initialize() + { + $this->tagRepository = $this->dic->get(TagRepository::class); + } } \ No newline at end of file diff --git a/lib/SP/Services/User/UserService.php b/lib/SP/Services/User/UserService.php index 1e2ba170..c1ca343b 100644 --- a/lib/SP/Services/User/UserService.php +++ b/lib/SP/Services/User/UserService.php @@ -31,6 +31,7 @@ use SP\DataModel\UserData; use SP\DataModel\UserPreferencesData; use SP\Repositories\User\UserRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; use SP\Util\Util; @@ -153,14 +154,34 @@ class UserService extends Service * Deletes an item * * @param $id - * @return UserRepository + * @return UserService * @throws SPException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function delete($id) { - return $this->userRepository->delete($id); + if ($this->userRepository->delete($id) === 0) { + throw new ServiceException(__u('Usuario no encontrado'), ServiceException::INFO); + } + + return $this; + } + + /** + * @param array $ids + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->userRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar los usuarios'), ServiceException::WARNING); + } + + return $count; } /** diff --git a/lib/SP/Services/UserGroup/UserGroupService.php b/lib/SP/Services/UserGroup/UserGroupService.php index 21cbb3bb..049b0b1d 100644 --- a/lib/SP/Services/UserGroup/UserGroupService.php +++ b/lib/SP/Services/UserGroup/UserGroupService.php @@ -30,6 +30,7 @@ use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; use SP\Repositories\UserGroup\UserGroupRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; /** @@ -45,15 +46,10 @@ class UserGroupService extends Service * @var UserGroupRepository */ protected $userGroupRepository; - /** - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface + * @var UserToUserGroupService */ - protected function initialize() - { - $this->userGroupRepository = $this->dic->get(UserGroupRepository::class); - } + protected $userToUserGroupService; /** * @param ItemSearchData $itemSearchData @@ -81,32 +77,57 @@ class UserGroupService extends Service public function delete($id) { if ($this->userGroupRepository->delete($id) === 0) { - throw new SPException(__u('Grupo no encontrado'), SPException::INFO); + throw new ServiceException(__u('Grupo no encontrado'), ServiceException::INFO); } return $this; } /** - * @param $itemData + * @param array $ids * @return int - * @throws SPException + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ - public function create($itemData) + public function deleteByIdBatch(array $ids) { - return $this->userGroupRepository->create($itemData); + if (($count = $this->userGroupRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar los grupos'), ServiceException::WARNING); + } + + return $count; } /** - * @param $itemData - * @return mixed + * @param $itemData + * @param array $users + * @return int + * @throws SPException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function create($itemData, array $users) + { + $userGroupId = $this->userGroupRepository->create($itemData); + + if (count($users) > 0) { + $this->userToUserGroupService->add($userGroupId, $users); + } + + return $userGroupId; + } + + /** + * @param UserGroupData $itemData * @throws SPException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function update($itemData) { - return $this->userGroupRepository->update($itemData); + $this->userGroupRepository->update($itemData); + $this->userToUserGroupService->update($itemData->getId(), $itemData->getUsers()); } /** @@ -129,4 +150,14 @@ class UserGroupService extends Service { return $this->userGroupRepository->getByName($name); } + + /** + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function initialize() + { + $this->userGroupRepository = $this->dic->get(UserGroupRepository::class); + $this->userToUserGroupService = $this->dic->get(UserToUserGroupService::class); + } } \ No newline at end of file diff --git a/lib/SP/Services/UserProfile/UserProfileService.php b/lib/SP/Services/UserProfile/UserProfileService.php index bc19f02d..ac21b000 100644 --- a/lib/SP/Services/UserProfile/UserProfileService.php +++ b/lib/SP/Services/UserProfile/UserProfileService.php @@ -28,8 +28,10 @@ use SP\Core\Exceptions\SPException; use SP\Core\Traits\InjectableTrait; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; +use SP\DataModel\UserProfileData; use SP\Repositories\UserProfile\UserProfileRepository; use SP\Services\Service; +use SP\Services\ServiceException; use SP\Services\ServiceItemTrait; use SP\Util\Util; @@ -59,11 +61,14 @@ class UserProfileService extends Service /** * @param $id - * @return mixed + * @return UserProfileData */ public function getById($id) { - return Util::unserialize(ProfileData::class, $this->userProfileRepository->getById($id)->getProfile()); + $userProfileData = $this->userProfileRepository->getById($id); + $userProfileData->setProfile(Util::unserialize(ProfileData::class, $userProfileData->getProfile())); + + return $userProfileData; } /** @@ -83,12 +88,28 @@ class UserProfileService extends Service public function delete($id) { if ($this->userProfileRepository->delete($id) === 0) { - throw new SPException(__u('Perfil no encontrado'), SPException::INFO); + throw new ServiceException(__u('Perfil no encontrado'), ServiceException::INFO); } return $this; } + /** + * @param array $ids + * @return int + * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByIdBatch(array $ids) + { + if (($count = $this->userProfileRepository->deleteByIdBatch($ids)) !== count($ids)) { + throw new ServiceException(__u('Error al eliminar los perfiles'), ServiceException::WARNING); + } + + return $count; + } + /** * @param $itemData * @return int diff --git a/lib/SP/Storage/Database.php b/lib/SP/Storage/Database.php index 98a76918..781015b9 100644 --- a/lib/SP/Storage/Database.php +++ b/lib/SP/Storage/Database.php @@ -127,6 +127,7 @@ class Database implements DatabaseInterface $queryData->setQueryNumRows($this->numRows); } else { + $this->numRows = $stmt->rowCount(); $queryData->setQueryNumRows($stmt->rowCount()); } diff --git a/lib/SP/Storage/DbWrapper.php b/lib/SP/Storage/DbWrapper.php index 5e6317e3..719d2a22 100644 --- a/lib/SP/Storage/DbWrapper.php +++ b/lib/SP/Storage/DbWrapper.php @@ -25,7 +25,6 @@ namespace SP\Storage; use PDOStatement; -use SP\Bootstrap; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; @@ -63,12 +62,6 @@ class DbWrapper */ public static function getResultsArray(QueryData $queryData, DatabaseInterface $db = null) { - // FIXME: remove - if ($db === null) { - /** @var Database $db */ - $db = Bootstrap::getContainer()->get(Database::class); - } - $results = self::getResults($queryData, $db); if ($results === false) { @@ -93,22 +86,15 @@ class DbWrapper } try { - // FIXME: remove - if ($db === null) { - /** @var Database $db */ - $db = Bootstrap::getContainer()->get(Database::class); - } - $db->doQuery($queryData); if (self::$fullRowCount === true) { $db->getFullRowCount($queryData); } } catch (\Exception $e) { - $queryData->setQueryStatus($e->getCode()); + processException($e); - self::logDBException($queryData->getQuery(), $e, __FUNCTION__); - return false; + $queryData->setQueryStatus($e->getCode()); } self::resetVars(); @@ -162,21 +148,14 @@ class DbWrapper * @param QueryData $queryData * @param DatabaseInterface $db * @return PDOStatement|false - * @throws SPException - * @throws \SP\Core\Dic\ContainerException + * @throws \Exception */ public static function getResultsRaw(QueryData $queryData, DatabaseInterface $db = null) { try { - // FIXME: remove - if ($db === null) { - /** @var Database $db */ - $db = Bootstrap::getContainer()->get(Database::class); - } - return $db->doQuery($queryData, true); - } catch (SPException $e) { - self::logDBException($queryData->getQuery(), $e, __FUNCTION__); + } catch (\Exception $e) { + processException($e); throw $e; } @@ -204,19 +183,13 @@ class DbWrapper } try { - // FIXME: remove - if ($db === null) { - /** @var Database $db */ - $db = Bootstrap::getContainer()->get(Database::class); - } - $db->doQuery($queryData); return true; } catch (\Exception $e) { - $queryData->setQueryStatus($e->getCode()); + processException($e); - self::logDBException($queryData->getQuery(), $e, __FUNCTION__); + $queryData->setQueryStatus($e->getCode()); switch ($e->getCode()) { case 23000: diff --git a/public/js/app-actions.js b/public/js/app-actions.js index f0f99af5..e607cc33 100644 --- a/public/js/app-actions.js +++ b/public/js/app-actions.js @@ -619,7 +619,7 @@ sysPass.Actions = function (Common) { * * @type {{logout: main.logout, login: main.login, install: main.install, twofa: main.twofa}} */ - var main = { + const main = { logout: function () { Common.redirect("index.php?r=login/logout"); }, @@ -1208,57 +1208,27 @@ sysPass.Actions = function (Common) { tabs.state.update($obj); - const atext = "

      " + Common.config().LANG[12] + "

      "; - const selection = $obj.data("selection"); - const items = []; + grid.delete($obj, function (items) { + const itemId = $obj.data("item-id"); - // FIXME - if (selection) { - $(selection).find(".is-selected").each(function () { - const $this = $(this); + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint; + opts.method = "get"; + opts.data = { + r: $obj.data("action-route") + (itemId ? "/" + itemId : ''), + items: items, + sk: Common.sk.get(), + isAjax: 1 + }; - items.push($this.data("item-id")); + Common.appRequests().getActionCall(opts, function (json) { + Common.msg.out(json); + + getContent({ + r: tabs.state.tab.route, + tabIndex: tabs.state.tab.index + }); }); - - if (items.length === 0) { - return; - } - } - - mdlDialog().show({ - text: atext, - negative: { - title: Common.config().LANG[44], - onClick: function (e) { - e.preventDefault(); - - Common.msg.error(Common.config().LANG[44]); - } - }, - positive: { - title: Common.config().LANG[43], - onClick: function (e) { - e.preventDefault(); - - const opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.entrypoint; - opts.method = "get"; - opts.data = { - r: $obj.data("action-route") + "/" + $obj.data("item-id"), - sk: Common.sk.get(), - isAjax: 1 - }; - - Common.appRequests().getActionCall(opts, function (json) { - Common.msg.out(json); - - getContent({ - r: tabs.state.tab.route, - tabIndex: tabs.state.tab.index - }); - }); - } - } }); }, save: function ($obj) { @@ -1286,32 +1256,12 @@ sysPass.Actions = function (Common) { search: function ($obj) { log.info("appMgmt:search"); - const $target = $($obj.data("target")); - const opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data("action-route"); - opts.method = "get"; - opts.data = $obj.serialize(); - - Common.appRequests().getActionCall(opts, function (json) { - if (json.status === 0) { - $target.html(json.data.html); - } else { - $target.html(Common.msg.html.error(json.description)); - } - - Common.sk.set(json.csrf); - }); + grid.search($obj); }, nav: function ($obj) { log.info("appMgmt:nav"); - const $form = $("#" + $obj.data("action-form")); - - $form.find("[name='start']").val($obj.data("start")); - $form.find("[name='count']").val($obj.data("count")); - $form.find("[name='sk']").val(Common.sk.get()); - - appMgmt.search($form); + grid.nav($obj); }, ldapSync: function ($obj) { log.info("appMgmt:ldapSync"); @@ -1360,32 +1310,12 @@ sysPass.Actions = function (Common) { search: function ($obj) { log.info("eventlog:search"); - const $target = $($obj.data("target")); - const opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data("action-route"); - opts.method = "get"; - opts.data = $obj.serialize(); - - Common.appRequests().getActionCall(opts, function (json) { - if (json.status === 0) { - $target.html(json.data.html); - } else { - $target.html(Common.msg.html.error(json.description)); - } - - Common.sk.set(json.csrf); - }); + grid.search($obj); }, nav: function ($obj) { log.info("eventlog:nav"); - const $form = $("#" + $obj.data("action-form")); - - $form.find("[name='start']").val($obj.data("start")); - $form.find("[name='count']").val($obj.data("count")); - $form.find("[name='sk']").val(Common.sk.get()); - - eventlog.search($form); + grid.nav($obj); }, clear: function ($obj) { const atext = "

      " + Common.config().LANG[20] + "

      "; @@ -1405,7 +1335,6 @@ sysPass.Actions = function (Common) { onClick: function (e) { e.preventDefault(); - const $target = $($obj.data("target")); const opts = Common.appRequests().getRequestOpts(); opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data("action-route"); opts.method = "get"; @@ -1415,7 +1344,7 @@ sysPass.Actions = function (Common) { Common.msg.out(json); if (json.status === 0) { - getContent({r: $obj.data("action-next")}); + getContent({r: $obj.data("nextaction")}); } Common.sk.set(json.csrf); @@ -1529,34 +1458,112 @@ sysPass.Actions = function (Common) { /** * Objeto para las acciones de las notificaciones */ - var notice = { + const notification = { check: function ($obj) { - log.info("notice:check"); + log.info("notification:check"); - var data = { - "itemId": $obj.data("item-id"), - "actionId": $obj.data("action-id"), - "sk": Common.sk.get() + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint; + opts.method = "get"; + opts.data = { + r: $obj.data("action-route") + "/" + $obj.data("item-id"), + sk: Common.sk.get(), + isAjax: 1 }; - var opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.appMgmt.save; - opts.data = data; - Common.appRequests().getActionCall(opts, function (json) { Common.msg.out(json); if (json.status === 0) { - doAction({actionId: $obj.data("nextaction-id"), itemId: $obj.data("activetab")}); + getContent({r: $obj.data("nextaction")}); } + + Common.sk.set(json.csrf); }); }, search: function ($obj) { - log.info("notice:search"); + log.info("notification:search"); - var $target = $($obj.data("target")); - var opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.notice.search; + grid.search($obj); + }, + show: function ($obj) { + log.info("notification:show"); + + appMgmt.show($obj); + }, + save: function ($obj) { + log.info("notification:save"); + + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data("route"); + opts.data = $obj.serialize(); + + Common.appRequests().getActionCall(opts, function (json) { + Common.msg.out(json); + + if (json.status === 0) { + getContent({r: $obj.data("nextaction")}); + + $.magnificPopup.close(); + } + }); + }, + delete: function ($obj) { + log.info("notification:delete"); + + grid.delete($obj, function (items) { + if (items.length > 0) { + items.join(","); + } else { + items = $obj.data("item-id"); + } + + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint; + opts.method = "get"; + opts.data = { + r: $obj.data("action-route") + "/" + items, + sk: Common.sk.get(), + isAjax: 1 + }; + + Common.appRequests().getActionCall(opts, function (json) { + Common.msg.out(json); + + getContent({r: $obj.data("nextaction")}); + }); + }); + }, + getActive: function () { + log.info("notification:getActive"); + + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint; + opts.method = "get"; + opts.data = { + r: "items/notifications", + sk: Common.sk.get(), + isAjax: 1 + }; + + Common.appRequests().getActionCall(opts, function (json) { + return json; + }); + }, + nav: function ($obj) { + log.info("eventlog:nav"); + + grid.nav($obj); + } + }; + + const grid = { + search: function ($obj) { + log.info("appMgmt:search"); + + const $target = $($obj.data("target")); + const opts = Common.appRequests().getRequestOpts(); + opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data("action-route"); opts.method = "get"; opts.data = $obj.serialize(); @@ -1570,25 +1577,55 @@ sysPass.Actions = function (Common) { Common.sk.set(json.csrf); }); }, - show: function ($obj) { - log.info("notice:show"); + nav: function ($obj, callback) { + log.info("grid:nav"); - var opts = Common.appRequests().getRequestOpts(); - opts.url = ajaxUrl.notice.show; - opts.method = "get"; - opts.data = { - itemId: $obj.data("item-id"), - actionId: $obj.data("action-id"), - activeTab: $obj.data("activetab"), - sk: Common.sk.get(), - isAjax: 1 - }; + const $form = $("#" + $obj.data("action-form")); - Common.appRequests().getActionCall(opts, function (json) { - if (json.status !== 0) { - Common.msg.out(json); - } else { - showFloatingBox(json.data.html); + $form.find("[name='start']").val($obj.data("start")); + $form.find("[name='count']").val($obj.data("count")); + $form.find("[name='sk']").val(Common.sk.get()); + + if (typeof callback === "function") { + callback($form); + } else { + grid.search($obj); + } + }, + delete: function ($obj, onAccept) { + const atext = "

      " + Common.config().LANG[12] + "

      "; + const selection = $obj.data("selection"); + const items = []; + + if (selection) { + $(selection).find(".is-selected").each(function () { + items.push($(this).data("item-id")); + }); + + if (items.length === 0) { + return; + } + } + + mdlDialog().show({ + text: atext, + negative: { + title: Common.config().LANG[44], + onClick: function (e) { + e.preventDefault(); + + Common.msg.error(Common.config().LANG[44]); + } + }, + positive: { + title: Common.config().LANG[43], + onClick: function (e) { + e.preventDefault(); + + if (typeof onAccept === "function") { + onAccept(items); + } + } } }); } @@ -1607,7 +1644,7 @@ sysPass.Actions = function (Common) { eventlog: eventlog, ajaxUrl: ajaxUrl, plugin: plugin, - notice: notice, + notification: notification, wiki: wiki, items: items }; diff --git a/public/js/app-actions.min.js b/public/js/app-actions.min.js index 9696f15e..e2373264 100644 --- a/public/js/app-actions.min.js +++ b/public/js/app-actions.min.js @@ -1,47 +1,48 @@ -var $jscomp={scope:{},findInternal:function(c,e,k){c instanceof String&&(c=String(c));for(var f=c.length,m=0;m'+b+"
      "),g=d.find("img");if(0===g.length)return n(b);g.hide();$.magnificPopup.open({items:{src:d,type:"inline"},callbacks:{open:function(){var a=this;g.on("click",function(){a.close()});setTimeout(function(){var a=c.resizeImage(g);d.css({backgroundColor:"#fff",width:a.width,height:"auto"});g.show("slow")}, -500)}}})},p={view:function(a){e.info("account:show");l(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},viewHistory:function(a){e.info("account:showHistory");l(c.appRequests().getRouteForQuery(a.data("action-route"),a.val()),"account")},edit:function(a){e.info("account:edit");l(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},"delete":function(a){e.info("account:delete");var b='

      '+c.config().LANG[3]+ -"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(d){d=c.appRequests().getRequestOpts();d.url=f.account.save;d.data={r:"account/saveDelete/"+a.data("item-id"),sk:c.sk.get()};c.appRequests().getActionCall(d,function(a){c.msg.out(a);p.search()})}}})},viewPass:function(a){e.info("account:showpass");var b=a.data("parent-id")||0,b=0===b?a.data("item-id"): -b,d=a.data("history")||0,g=c.appRequests().getRequestOpts();g.url=f.entrypoint;g.method="get";g.data={r:a.data("action-route")+"/"+b+"/"+d,sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(g,function(a){0!==a.status?c.msg.out(a):(a=$(a.data.html),n(a),k=setTimeout(function(){$.magnificPopup.close()},3E4),a.on("mouseleave",function(){clearTimeout(k);k=setTimeout(function(){$.magnificPopup.close()},3E4)}).on("mouseenter",function(){0!==k&&clearTimeout(k)}))})},copyPass:function(a){e.info("account:copypass"); -var b=a.data("parent-id"),b=0===b?a.data("item-id"):b,d=c.appRequests().getRequestOpts();d.url=f.entrypoint;d.method="get";d.async=!1;d.data={r:a.data("action-route")+"/"+b+"/"+a.data("history"),sk:c.sk.get(),isAjax:1};return c.appRequests().getActionCall(d)},copy:function(a){e.info("account:copy");l(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},saveFavorite:function(a,b){e.info("account:saveFavorite");var d="on"===a.data("status"),g={r:(d?a.data("action-id-off"): -a.data("action-id-on"))+"/"+a.data("item-id"),sk:c.sk.get(),isAjax:1},q=c.appRequests().getRequestOpts();q.url=f.account.saveFavorite;q.data=g;c.appRequests().getActionCall(q,function(g){c.msg.out(g);0===g.status&&(a.data("status",d?"off":"on"),"function"===typeof b&&b())})},request:function(a){e.info("account:request");var b=c.appRequests().getRequestOpts();b.url=f.account.request;b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a)})},menu:function(a){a.hide();a.parent().children(".actions-optional").show(250)}, -sort:function(a){e.info("account:sort");var c=$("#frmSearch");c.find('input[name="skey"]').val(a.data("key"));c.find('input[name="sorder"]').val(a.data("dir"));c.find('input[name="start"]').val(a.data("start"));p.search()},editPass:function(a){e.info("account:editpass");var b=a.data("parent-id"),b=void 0===b?a.data("item-id"):b;l(c.appRequests().getRouteForQuery(a.data("action-route"),b),"account")},saveEditRestore:function(a){e.info("account:restore");var b=c.appRequests().getRequestOpts();b.url= -f.entrypoint+"?r="+a.data("action-route")+"/"+a.data("history-id")+"/"+a.data("item-id");b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);void 0!==a.data.itemId&&void 0!==a.data.nextAction&&l(c.appRequests().getRouteForQuery(a.data.nextAction,a.data.itemId),"account")})},listFiles:function(a){e.info("account:getfiles");var b=c.appRequests().getRequestOpts();b.method="get";b.type="html";b.url=f.entrypoint;b.data={r:a.data("action-route")+"/"+a.data("item-id"),del:a.data("delete"), -sk:c.sk.get()};c.appRequests().getActionCall(b,function(c){a.html(c)})},search:function(a){e.info("account:search");var b=$("#frmSearch");b.find("input[name='sk']").val(c.sk.get());b.find("input[name='skey']").val();b.find("input[name='sorder']").val();void 0!==a&&b.find("input[name='start']").val(0);a=c.appRequests().getRequestOpts();a.url=f.account.search;a.method="get";a.data=b.serialize();c.appRequests().getActionCall(a,function(a){10===a.status&&c.msg.out(a);c.sk.set(a.data.sk);$("#res-content").empty().html(a.data.html)})}, -save:function(a){e.info("account:save");var b=c.appRequests().getRequestOpts();b.url=f.account.save+"?r="+a.data("action-route")+"/"+a.data("item-id");b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);void 0!==a.data.itemId&&void 0!==a.data.nextAction&&l(c.appRequests().getRouteForQuery(a.data.nextAction,a.data.itemId),"account")})}},r={get:function(a){e.info("items:get");var b=a[0].selectize;b.clearOptions();b.load(function(d){var g=c.appRequests().getRequestOpts();g.url= -f.updateItems;g.method="get";g.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:a.data("sk")};c.appRequests().getActionCall(g,function(g){d(g.data);b.setValue(a.data("selected-id"),!0);c.appTriggers().updateFormHash()})})},update:function(a){e.info("items:update");var b=$("#"+a.data("item-dst"))[0].selectize;b.clearOptions();b.load(function(b){var d=c.appRequests().getRequestOpts();d.url=f.updateItems;d.method="get";d.data={r:a.data("item-route"),sk:c.sk.get()};c.appRequests().getActionCall(d, -function(a){b(a)})})}},t={logout:function(){c.redirect("index.php?r=login/logout")},login:function(a){e.info("main:login");var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("route");b.method="get";b.data=a.serialize();c.appRequests().getActionCall(b,function(d){var b=$(".extra-hidden");switch(d.status){case 0:c.redirect(d.data.url);break;case 2:c.msg.out(d);a.find("input[type='text'],input[type='password']").val("");a.find("input:first").focus();0";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b=a.find("input[name='useTask']");var d=$("#taskStatus");d.empty().html(c.config().LANG[62]); -if(0",d=a.data("selection"),g=[];if(d&&($(d).find(".is-selected").each(function(){var a=$(this);g.push(a.data("item-id"))}),0===g.length))return;mdlDialog().show({text:b,negative:{title:c.config().LANG[44], -onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b.preventDefault();b=c.appRequests().getRequestOpts();b.url=f.entrypoint;b.method="get";b.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b,function(a){c.msg.out(a);l({r:h.state.tab.route,tabIndex:h.state.tab.index})})}}})},save:function(a){e.info("appMgmt:save");var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+ -"?r="+a.data("route");b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);0===a.status&&(!0===h.state.tab.refresh&&l({r:h.state.tab.route,tabIndex:h.state.tab.index}),$.magnificPopup.close())})},search:function(a){e.info("appMgmt:search");var b=$(a.data("target")),d=c.appRequests().getRequestOpts();d.url=f.entrypoint+"?r="+a.data("action-route");d.method="get";d.data=a.serialize();c.appRequests().getActionCall(d,function(a){0===a.status?b.html(a.data.html):b.html(c.msg.html.error(a.description)); -c.sk.set(a.csrf)})},nav:function(a){e.info("appMgmt:nav");var b=$("#"+a.data("action-form"));b.find("[name='start']").val(a.data("start"));b.find("[name='count']").val(a.data("count"));b.find("[name='sk']").val(c.sk.get());u.search(b)},ldapSync:function(a){e.info("appMgmt:ldapSync");var b='

      '+c.config().LANG[57]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43], -onClick:function(b){b=c.appRequests().getRequestOpts();b.url=f.appMgmt.save;b.data={actionId:a.data("action-id"),sk:c.sk.get(),isAjax:1,ldap_loginattribute:$("#ldap_loginattribute").val(),ldap_nameattribute:$("#ldap_nameattribute").val(),ldap_ads:$("#ldap_ads").prop("checked")};c.appRequests().getActionCall(b,function(a){c.msg.out(a)})}}})}},v={search:function(a){e.info("eventlog:search");var b=$(a.data("target")),d=c.appRequests().getRequestOpts();d.url=f.entrypoint+"?r="+a.data("action-route"); -d.method="get";d.data=a.serialize();c.appRequests().getActionCall(d,function(a){0===a.status?b.html(a.data.html):b.html(c.msg.html.error(a.description));c.sk.set(a.csrf)})},nav:function(a){e.info("eventlog:nav");var b=$("#"+a.data("action-form"));b.find("[name='start']").val(a.data("start"));b.find("[name='count']").val(a.data("count"));b.find("[name='sk']").val(c.sk.get());v.search(b)},clear:function(a){var b='

      '+c.config().LANG[20]+"

      ";mdlDialog().show({text:b, -negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b.preventDefault();$(a.data("target"));b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("action-route");b.method="get";b.data={sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b,function(b){c.msg.out(b);0===b.status&&l({r:a.data("action-next")});c.sk.set(b.csrf)})}}})}};return{doAction:m,appMgmt:u,account:p,file:{view:function(a){e.info("file:view"); -var b=c.appRequests().getRequestOpts();b.url=f.entrypoint;b.method="get";b.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get()};c.appRequests().getActionCall(b,function(b){if(1===b.status)return c.msg.out(b);w(a,b.data.html)})},download:function(a){e.info("file:download");a={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get()};$.fileDownload(f.entrypoint,{httpMethod:"GET",data:a})},"delete":function(a){e.info("file:delete");var b='

      '+c.config().LANG[15]+ -"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b=c.appRequests().getRequestOpts();b.url=f.entrypoint;b.method="get";b.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get()};c.appRequests().getActionCall(b,function(a){c.msg.out(a);0===a.status&&p.listFiles($("#list-account-files"))})}}})}},checks:{ldap:function(a){e.info("checks:ldap"); -a=$(a.data("src"));a.find("[name='sk']").val(c.sk.get());var b=c.appRequests().getRequestOpts();b.url=f.checks;b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);var b=$("#ldap-results");b.find(".list-wrap").html(c.appTheme().html.getList(a.data));b.show("slow")})},wiki:function(a){e.info("checks:wiki");a=$(a.data("src"));a.find("[name='sk']").val(c.sk.get());var b=c.appRequests().getRequestOpts();b.url=f.checks;b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a); -0===a.status&&$("#dokuWikiResCheck").html(a.data)})}},config:{save:function(a){e.info("config:save");h.state.update(a);var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("action-route");b.data=a.serialize();c.appRequests().getActionCall(b,function(b){c.msg.out(b);0===b.status&&(!0===h.state.tab.refresh?l({r:h.state.tab.route,tabIndex:h.state.tab.index}):void 0!==a.data("reload")&&setTimeout(function(){c.redirect("index.php")},2E3))})},masterpass:function(a){var b='

      '+ -c.config().LANG[59]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(b){b.preventDefault();c.msg.error(c.config().LANG[44]);a.find(":input[type=password]").val("")}},positive:{title:c.config().LANG[43],onClick:function(b){b=a.find("input[name='useTask']");var d=$("#taskStatus");d.empty().html(c.config().LANG[62]);0";mdlDialog().show({text:g, -negative:{title:c.config().LANG[44],onClick:function(e){e.preventDefault();c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&l({r:a.data("action-next")+"/"+b})})}},positive:{title:c.config().LANG[43],onClick:function(e){e.preventDefault();d.data.notify=1;c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&l({r:a.data("action-next")+"/"+b})})}}})},refresh:function(a){e.info("link:refresh");h.state.update(a);var b=a.data("item-id"),d=c.appRequests().getRequestOpts(); -d.url=f.entrypoint;d.data={r:a.data("action-route")+"/"+b,sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&((d=a.data("action-next"))?l({r:d+"/"+b}):l({r:h.state.tab.route,tabIndex:h.state.tab.index}))})}},eventlog:v,ajaxUrl:f,plugin:{toggle:function(a){e.info("plugin:enable");a={itemId:a.data("item-id"),actionId:a.data("action-id"),sk:c.sk.get(),activeTab:a.data("activetab")};var b=c.appRequests().getRequestOpts();b.url=f.appMgmt.save;b.data=a;c.appRequests().getActionCall(b, -function(a){c.msg.out(a);0===a.status&&setTimeout(function(){c.redirect("index.php")},2E3)})},reset:function(a){e.info("plugin:reset");var b='

      '+c.config().LANG[58]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b.preventDefault();b={itemId:a.data("item-id"),actionId:a.data("action-id"),sk:c.sk.get(),activeTab:a.data("activetab")}; -var d=c.appRequests().getRequestOpts();d.url=f.appMgmt.save;d.data=b;c.appRequests().getActionCall(d,function(a){c.msg.out(a)})}}})}},notice:{check:function(a){e.info("notice:check");var b={itemId:a.data("item-id"),actionId:a.data("action-id"),sk:c.sk.get()},d=c.appRequests().getRequestOpts();d.url=f.appMgmt.save;d.data=b;c.appRequests().getActionCall(d,function(b){c.msg.out(b);0===b.status&&m({actionId:a.data("nextaction-id"),itemId:a.data("activetab")})})},search:function(a){e.info("notice:search"); -var b=$(a.data("target")),d=c.appRequests().getRequestOpts();d.url=f.notice.search;d.method="get";d.data=a.serialize();c.appRequests().getActionCall(d,function(a){0===a.status?b.html(a.data.html):b.html(c.msg.html.error(a.description));c.sk.set(a.csrf)})},show:function(a){e.info("notice:show");var b=c.appRequests().getRequestOpts();b.url=f.notice.show;b.method="get";b.data={itemId:a.data("item-id"),actionId:a.data("action-id"),activeTab:a.data("activetab"),sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b, -function(a){0!==a.status?c.msg.out(a):n(a.data.html)})}},wiki:{show:function(a){e.info("wiki:show");var b=c.appRequests().getRequestOpts();b.url=f.wiki.show;b.method="get";b.data={pageName:a.data("pagename"),actionId:a.data("action-id"),sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b,function(a){0!==a.status?c.msg.out(a):n(a.data.html)})}},items:r}}; +Object.freeze(f);var g=function(a,b){e.info("getContent");a.isAjax=1;var d=c.appRequests().getRequestOpts();d.url=f.doAction;d.method="get";d.type="html";d.addHistory=!0;d.data=a;c.appRequests().getActionCall(d,function(a){var d=$("#content");d.empty().html(a);a=c.triggers().views;a.common(d);if(void 0!==b&&"function"===typeof a[b])a[b]();d=$(".mdl-layout__content");0'+b+""),k=d.find("img");if(0===k.length)return n(b);k.hide();$.magnificPopup.open({items:{src:d,type:"inline"},callbacks:{open:function(){var a=this;k.on("click",function(){a.close()});setTimeout(function(){var a= +c.resizeImage(k);d.css({backgroundColor:"#fff",width:a.width,height:"auto"});k.show("slow")},500)}}})},p={view:function(a){e.info("account:show");g(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},viewHistory:function(a){e.info("account:showHistory");g(c.appRequests().getRouteForQuery(a.data("action-route"),a.val()),"account")},edit:function(a){e.info("account:edit");g(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},"delete":function(a){e.info("account:delete"); +var b='

      '+c.config().LANG[3]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(d){d=c.appRequests().getRequestOpts();d.url=f.account.save;d.data={r:"account/saveDelete/"+a.data("item-id"),sk:c.sk.get()};c.appRequests().getActionCall(d,function(a){c.msg.out(a);p.search()})}}})},viewPass:function(a){e.info("account:showpass"); +var b=a.data("parent-id")||0,b=0===b?a.data("item-id"):b,d=a.data("history")||0,k=c.appRequests().getRequestOpts();k.url=f.entrypoint;k.method="get";k.data={r:a.data("action-route")+"/"+b+"/"+d,sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(k,function(a){0!==a.status?c.msg.out(a):(a=$(a.data.html),n(a),l=setTimeout(function(){$.magnificPopup.close()},3E4),a.on("mouseleave",function(){clearTimeout(l);l=setTimeout(function(){$.magnificPopup.close()},3E4)}).on("mouseenter",function(){0!==l&&clearTimeout(l)}))})}, +copyPass:function(a){e.info("account:copypass");var b=a.data("parent-id"),b=0===b?a.data("item-id"):b,d=c.appRequests().getRequestOpts();d.url=f.entrypoint;d.method="get";d.async=!1;d.data={r:a.data("action-route")+"/"+b+"/"+a.data("history"),sk:c.sk.get(),isAjax:1};return c.appRequests().getActionCall(d)},copy:function(a){e.info("account:copy");g(c.appRequests().getRouteForQuery(a.data("action-route"),a.data("item-id")),"account")},saveFavorite:function(a,b){e.info("account:saveFavorite");var d= +"on"===a.data("status"),k={r:(d?a.data("action-id-off"):a.data("action-id-on"))+"/"+a.data("item-id"),sk:c.sk.get(),isAjax:1},q=c.appRequests().getRequestOpts();q.url=f.account.saveFavorite;q.data=k;c.appRequests().getActionCall(q,function(k){c.msg.out(k);0===k.status&&(a.data("status",d?"off":"on"),"function"===typeof b&&b())})},request:function(a){e.info("account:request");var b=c.appRequests().getRequestOpts();b.url=f.account.request;b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a)})}, +menu:function(a){a.hide();a.parent().children(".actions-optional").show(250)},sort:function(a){e.info("account:sort");var c=$("#frmSearch");c.find('input[name="skey"]').val(a.data("key"));c.find('input[name="sorder"]').val(a.data("dir"));c.find('input[name="start"]').val(a.data("start"));p.search()},editPass:function(a){e.info("account:editpass");var b=a.data("parent-id"),b=void 0===b?a.data("item-id"):b;g(c.appRequests().getRouteForQuery(a.data("action-route"),b),"account")},saveEditRestore:function(a){e.info("account:restore"); +var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("action-route")+"/"+a.data("history-id")+"/"+a.data("item-id");b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);void 0!==a.data.itemId&&void 0!==a.data.nextAction&&g(c.appRequests().getRouteForQuery(a.data.nextAction,a.data.itemId),"account")})},listFiles:function(a){e.info("account:getfiles");var b=c.appRequests().getRequestOpts();b.method="get";b.type="html";b.url=f.entrypoint;b.data={r:a.data("action-route")+ +"/"+a.data("item-id"),del:a.data("delete"),sk:c.sk.get()};c.appRequests().getActionCall(b,function(c){a.html(c)})},search:function(a){e.info("account:search");var b=$("#frmSearch");b.find("input[name='sk']").val(c.sk.get());b.find("input[name='skey']").val();b.find("input[name='sorder']").val();void 0!==a&&b.find("input[name='start']").val(0);a=c.appRequests().getRequestOpts();a.url=f.account.search;a.method="get";a.data=b.serialize();c.appRequests().getActionCall(a,function(a){10===a.status&&c.msg.out(a); +c.sk.set(a.data.sk);$("#res-content").empty().html(a.data.html)})},save:function(a){e.info("account:save");var b=c.appRequests().getRequestOpts();b.url=f.account.save+"?r="+a.data("action-route")+"/"+a.data("item-id");b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);void 0!==a.data.itemId&&void 0!==a.data.nextAction&&g(c.appRequests().getRouteForQuery(a.data.nextAction,a.data.itemId),"account")})}},r={get:function(a){e.info("items:get");var b=a[0].selectize;b.clearOptions(); +b.load(function(d){var k=c.appRequests().getRequestOpts();k.url=f.updateItems;k.method="get";k.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:a.data("sk")};c.appRequests().getActionCall(k,function(k){d(k.data);b.setValue(a.data("selected-id"),!0);c.appTriggers().updateFormHash()})})},update:function(a){e.info("items:update");var b=$("#"+a.data("item-dst"))[0].selectize;b.clearOptions();b.load(function(b){var d=c.appRequests().getRequestOpts();d.url=f.updateItems;d.method="get";d.data={r:a.data("item-route"), +sk:c.sk.get()};c.appRequests().getActionCall(d,function(a){b(a)})})}},t={logout:function(){c.redirect("index.php?r=login/logout")},login:function(a){e.info("main:login");var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("route");b.method="get";b.data=a.serialize();c.appRequests().getActionCall(b,function(b){var d=$(".extra-hidden");switch(b.status){case 0:c.redirect(b.data.url);break;case 2:c.msg.out(b);a.find("input[type='text'],input[type='password']").val("");a.find("input:first").focus(); +0";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b=a.find("input[name='useTask']"); +var d=$("#taskStatus");d.empty().html(c.config().LANG[62]);if(0";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b=c.appRequests().getRequestOpts();b.url=f.appMgmt.save;b.data={actionId:a.data("action-id"),sk:c.sk.get(),isAjax:1,ldap_loginattribute:$("#ldap_loginattribute").val(),ldap_nameattribute:$("#ldap_nameattribute").val(),ldap_ads:$("#ldap_ads").prop("checked")}; +c.appRequests().getActionCall(b,function(a){c.msg.out(a)})}}})}},m={search:function(a){e.info("appMgmt:search");var b=$(a.data("target")),d=c.appRequests().getRequestOpts();d.url=f.entrypoint+"?r="+a.data("action-route");d.method="get";d.data=a.serialize();c.appRequests().getActionCall(d,function(a){0===a.status?b.html(a.data.html):b.html(c.msg.html.error(a.description));c.sk.set(a.csrf)})},nav:function(a,b){e.info("grid:nav");var d=$("#"+a.data("action-form"));d.find("[name='start']").val(a.data("start")); +d.find("[name='count']").val(a.data("count"));d.find("[name='sk']").val(c.sk.get());"function"===typeof b?b(d):m.search(a)},"delete":function(a,b){var d='

      '+c.config().LANG[12]+"

      ",e=a.data("selection"),f=[];if(e&&($(e).find(".is-selected").each(function(){f.push($(this).data("item-id"))}),0===f.length))return;mdlDialog().show({text:d,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43], +onClick:function(a){a.preventDefault();"function"===typeof b&&b(f)}}})}};return{doAction:function(a,b){var d={r:a.r+(void 0!==a.itemId?"/"+a.itemId:""),isAjax:1},e=c.appRequests().getRequestOpts();e.url=f.doAction;e.method="get";e.type="html";e.addHistory=!0;e.data=d;c.appRequests().getActionCall(e,function(a){var d=$("#content");d.empty().html(a);a=c.triggers().views;a.common(d);if(void 0!==b&&"function"===typeof a[b])a[b]();d=$(".mdl-layout__content");0";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b=c.appRequests().getRequestOpts();b.url=f.entrypoint;b.method="get";b.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get()};c.appRequests().getActionCall(b,function(a){c.msg.out(a);0===a.status&&p.listFiles($("#list-account-files"))})}}})}}, +checks:{ldap:function(a){e.info("checks:ldap");a=$(a.data("src"));a.find("[name='sk']").val(c.sk.get());var b=c.appRequests().getRequestOpts();b.url=f.checks;b.data=a.serialize();c.appRequests().getActionCall(b,function(a){c.msg.out(a);var b=$("#ldap-results");b.find(".list-wrap").html(c.appTheme().html.getList(a.data));b.show("slow")})},wiki:function(a){e.info("checks:wiki");a=$(a.data("src"));a.find("[name='sk']").val(c.sk.get());var b=c.appRequests().getRequestOpts();b.url=f.checks;b.data=a.serialize(); +c.appRequests().getActionCall(b,function(a){c.msg.out(a);0===a.status&&$("#dokuWikiResCheck").html(a.data)})}},config:{save:function(a){e.info("config:save");h.state.update(a);var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("action-route");b.data=a.serialize();c.appRequests().getActionCall(b,function(b){c.msg.out(b);0===b.status&&(!0===h.state.tab.refresh?g({r:h.state.tab.route,tabIndex:h.state.tab.index}):void 0!==a.data("reload")&&setTimeout(function(){c.redirect("index.php")}, +2E3))})},masterpass:function(a){var b='

      '+c.config().LANG[59]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(b){b.preventDefault();c.msg.error(c.config().LANG[44]);a.find(":input[type=password]").val("")}},positive:{title:c.config().LANG[43],onClick:function(b){b=a.find("input[name='useTask']");var d=$("#taskStatus");d.empty().html(c.config().LANG[62]);0

      '+c.config().LANG[48]+"

      ";mdlDialog().show({text:k,negative:{title:c.config().LANG[44],onClick:function(e){e.preventDefault();c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&g({r:a.data("action-next")+"/"+b})})}},positive:{title:c.config().LANG[43],onClick:function(e){e.preventDefault();d.data.notify=1;c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&g({r:a.data("action-next")+"/"+b})})}}})},refresh:function(a){e.info("link:refresh"); +h.state.update(a);var b=a.data("item-id"),d=c.appRequests().getRequestOpts();d.url=f.entrypoint;d.data={r:a.data("action-route")+"/"+b,sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(d,function(d){c.msg.out(d);0===d.status&&((d=a.data("action-next"))?g({r:d+"/"+b}):g({r:h.state.tab.route,tabIndex:h.state.tab.index}))})}},eventlog:{search:function(a){e.info("eventlog:search");m.search(a)},nav:function(a){e.info("eventlog:nav");m.nav(a)},clear:function(a){var b='

      '+ +c.config().LANG[20]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44],onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b.preventDefault();b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("action-route");b.method="get";b.data={sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b,function(b){c.msg.out(b);0===b.status&&g({r:a.data("nextaction")});c.sk.set(b.csrf)})}}})}},ajaxUrl:f, +plugin:{toggle:function(a){e.info("plugin:enable");a={itemId:a.data("item-id"),actionId:a.data("action-id"),sk:c.sk.get(),activeTab:a.data("activetab")};var b=c.appRequests().getRequestOpts();b.url=f.appMgmt.save;b.data=a;c.appRequests().getActionCall(b,function(a){c.msg.out(a);0===a.status&&setTimeout(function(){c.redirect("index.php")},2E3)})},reset:function(a){e.info("plugin:reset");var b='

      '+c.config().LANG[58]+"

      ";mdlDialog().show({text:b,negative:{title:c.config().LANG[44], +onClick:function(a){a.preventDefault();c.msg.error(c.config().LANG[44])}},positive:{title:c.config().LANG[43],onClick:function(b){b.preventDefault();b={itemId:a.data("item-id"),actionId:a.data("action-id"),sk:c.sk.get(),activeTab:a.data("activetab")};var d=c.appRequests().getRequestOpts();d.url=f.appMgmt.save;d.data=b;c.appRequests().getActionCall(d,function(a){c.msg.out(a)})}}})}},notification:{check:function(a){e.info("notification:check");var b=c.appRequests().getRequestOpts();b.url=f.entrypoint; +b.method="get";b.data={r:a.data("action-route")+"/"+a.data("item-id"),sk:c.sk.get(),isAjax:1};c.appRequests().getActionCall(b,function(b){c.msg.out(b);0===b.status&&g({r:a.data("nextaction")});c.sk.set(b.csrf)})},search:function(a){e.info("notification:search");m.search(a)},show:function(a){e.info("notification:show");u.show(a)},save:function(a){e.info("notification:save");var b=c.appRequests().getRequestOpts();b.url=f.entrypoint+"?r="+a.data("route");b.data=a.serialize();c.appRequests().getActionCall(b, +function(b){c.msg.out(b);0===b.status&&(g({r:a.data("nextaction")}),$.magnificPopup.close())})},"delete":function(a){e.info("notification:delete");m["delete"](a,function(b){0c.MAX_FILE_SIZE)e.error(c.LANG[18]+ "
      "+d.name+" (Max: "+c.MAX_FILE_SIZE+")");else{var g;a:{g=d.name.toUpperCase();var f=void 0;for(f in k.allowedExts)if(-1!==g.indexOf(k.allowedExts[f])){g=!0;break a}g=!1}g?h(a[b]):e.error(c.LANG[19]+"
      "+d.name)}}};window.File&&window.FileList&&window.FileReader?function(){f.info("fileUpload:init");var d=b(!1);a.on("dragover dragenter",function(a){f.info("fileUpload:drag");a.stopPropagation();a.preventDefault()});a.on("drop",function(a){f.info("fileUpload:drop");a.stopPropagation();a.preventDefault(); -"function"===typeof k.beforeSendAction&&k.beforeSendAction();l(a.originalEvent.dataTransfer.files)});a.on("click",function(){d.click()})}():b(!0);return k},A=function(a){window.location.replace(a)},I=function(){f.info("checkLogout");return"login/logout"===parseInt(H("r"))?(e.sticky(c.LANG[61],function(){A("index.php?r=login")}),!0):!1},J=function(){$("html, body").animate({scrollTop:0},"slow")},K=function(){var a=$("#container");a.hasClass("content-no-auto-resize")||a.css("height",$("#content").height()+ -200)},x={get:function(){f.info("sk:get");return $("#container").attr("data-sk")},set:function(a){f.info("sk:set");f.debug(a);$("#container").attr("data-sk",a)}},c={APP_ROOT:"",LANG:[],PK:"",MAX_FILE_SIZE:1024,CRYPT:new JSEncrypt,CHECK_UPDATES:!1,TIMEZONE:"",LOCALE:"",DEBUG:"",COOKIES_ENABLED:!1,PLUGINS:[],LOGGEDIN:!1,AUTHBASIC_AUTOLOGIN:!1,FILES_ALLOWED_EXTS:"",IMPORT_ALLOWED_EXTS:[]},u={passLength:0,minPasswordLength:8,complexity:{chars:!0,numbers:!0,symbols:!0,uppercase:!0,numlength:12}};Object.seal(u); +"function"===typeof k.beforeSendAction&&k.beforeSendAction();l(a.originalEvent.dataTransfer.files)});a.on("click",function(){d.click()})}():b(!0);return k},A=function(a){window.location.replace(a)},I=function(){f.info("checkLogout");return"login/logout"===H("r")?(e.sticky(c.LANG[61],function(){A("index.php?r=login")}),!0):!1},J=function(){$("html, body").animate({scrollTop:0},"slow")},K=function(){var a=$("#container");a.hasClass("content-no-auto-resize")||a.css("height",$("#content").height()+200)}, +x={get:function(){f.info("sk:get");return $("#container").attr("data-sk")},set:function(a){f.info("sk:set");f.debug(a);$("#container").attr("data-sk",a)}},c={APP_ROOT:"",LANG:[],PK:"",MAX_FILE_SIZE:1024,CRYPT:new JSEncrypt,CHECK_UPDATES:!1,TIMEZONE:"",LOCALE:"",DEBUG:"",COOKIES_ENABLED:!1,PLUGINS:[],LOGGEDIN:!1,AUTHBASIC_AUTOLOGIN:!1,FILES_ALLOWED_EXTS:"",IMPORT_ALLOWED_EXTS:[]},u={passLength:0,minPasswordLength:8,complexity:{chars:!0,numbers:!0,symbols:!0,uppercase:!0,numlength:12}};Object.seal(u); var B={},q={},p={},v={},t={},y={},r={},f={log:function(a){!0===c.DEBUG&&console.log(a)},info:function(a){!0===c.DEBUG&&console.info(a)},error:function(a){console.error(a)},warn:function(a){console.warn(a)},debug:function(a){!0===c.DEBUG&&console.debug(a)}};Object.freeze(f);toastr.options={closeButton:!0,debug:!1,newestOnTop:!1,progressBar:!1,positionClass:"toast-top-center",preventDuplicates:!1,onclick:null,showDuration:"300",hideDuration:"1000",timeOut:"5000",extendedTimeOut:"1000",showEasing:"swing", hideEasing:"linear",showMethod:"fadeIn",hideMethod:"fadeOut"};var L=function(){f.info("setupCallbacks");var a=$("#container").data("page");if(""!==a&&"function"===typeof q.views[a])q.views[a]();0<$("footer").length&&q.views.footer();$("#btnBack").click(function(){A("index.php")});q.bodyHooks()},e={ok:function(a){toastr.success(a)},error:function(a){toastr.error(a)},warn:function(a){toastr.warning(a)},info:function(a){toastr.info(a)},sticky:function(a,b){var d={timeOut:0};"function"===typeof b&&(d.onHidden= b);toastr.warning(a,c.LANG[60],d)},out:function(a){if("object"===typeof a){var b=a.status,d=a.description;void 0!==a.messages&&0"+a.messages.join("
      "));switch(b){case 0:e.ok(d);break;case 1:e.error(d);break;case 2:e.warn(d);break;case 10:p.main.logout();break;case 100:e.ok(d);e.sticky(d);break;case 101:e.error(d);e.sticky(d);break;case 102:e.warn(d);e.sticky(d);break;default:e.error(d)}}},html:{error:function(a){return'

      Oops...
      '+c.LANG[1]+ diff --git a/public/js/app-triggers.js b/public/js/app-triggers.js index 2556f627..d841d3d5 100644 --- a/public/js/app-triggers.js +++ b/public/js/app-triggers.js @@ -215,6 +215,10 @@ sysPass.Triggers = function (Common) { Common.appActions().doAction({actionId: $(this).data("route")}); }); + // setInterval(function () { + // Common.appActions().notification.getActive(); + // }, 60000); + Common.appActions().doAction({r: "account/index"}, "search"); if (typeof Common.appTheme().viewsTriggers.main === "function") { @@ -361,6 +365,7 @@ sysPass.Triggers = function (Common) { const upload = Common.fileUpload($dropFiles); upload.url = Common.appActions().ajaxUrl.entrypoint + "?r=" + $dropFiles.data("action-route") + "/" + $dropFiles.data("item-id"); + upload.allowedExts = Common.config().FILES_ALLOWED_EXTS; upload.requestDoneAction = function () { Common.appActions().account.listFiles($listFiles); diff --git a/public/js/app-triggers.min.js b/public/js/app-triggers.min.js index 5786fcde..b05b092c 100644 --- a/public/js/app-triggers.min.js +++ b/public/js/app-triggers.min.js @@ -1,5 +1,5 @@ var $jscomp={scope:{},findInternal:function(b,d,f){b instanceof String&&(b=String(b));for(var a=b.length,c=0;cform").each(function(){var a= $(this);a.find("button.btn-clear").on("click",function(b){b.preventDefault();a.trigger("reset")})})},config:function(){d.info("views:config");var a=$("#drop-import-files");if(0