From 17d2b08809200f97f1d0d98428eb53685ee7d741 Mon Sep 17 00:00:00 2001 From: nuxsmin Date: Tue, 16 Jan 2018 00:07:10 +0100 Subject: [PATCH] * [ADD] Code refactoring in order to implement DDD. Work in progress. --- ajax/ajax_getContent.php | 8 +- .../Controllers/AccessManagerController.php | 20 +- .../web/Controllers/AccountController.php | 172 ++- .../web/Controllers/BootstrapController.php | 4 +- .../web/Controllers/CategoryController.php | 6 +- .../Helpers/AccountSearchHelper.php | 139 +- .../Controllers/Helpers/ItemsGridHelper.php | 86 +- .../web/Controllers/PublicLinkController.php | 8 +- .../web/Controllers/UserGroupController.php | 37 +- .../web/Controllers/UserProfileController.php | 6 +- .../views/account/linkedAccounts.inc | 4 +- .../views/account/search-index.inc | 4 +- .../views/itemshow/publiclink.inc | 8 +- .../material-blue/views/itemshow/tag.inc | 2 +- lib/Base.php | 93 +- lib/Definitions.php | 51 + lib/SP/Account/Account.php | 156 +- lib/SP/Account/AccountSearch.php | 753 ---------- lib/SP/Account/AccountUtil.php | 112 +- lib/SP/Auth/Browser/BrowserAuthData.php | 37 - lib/SP/Auth/Ldap/LdapInterface.php | 55 - lib/SP/Auth/Ldap/LdapMsAds.php | 177 --- lib/SP/Config/Config.php | 2 +- lib/SP/Controller/Grids/Items.php | 20 +- lib/SP/Controller/WikiController.php | 4 +- lib/SP/Core/Dic/DicInterface.php | 1 - lib/SP/Core/Init.php | 12 +- lib/SP/Core/Language.php | 4 +- lib/SP/Core/Plugin/PluginUtil.php | 6 +- lib/SP/Core/Session/Session.php | 74 +- lib/SP/Core/Upgrade/Check.php | 16 +- lib/SP/DataModel/AccountExtData.php | 36 +- lib/SP/DataModel/AccountToUserGroupData.php | 104 ++ lib/SP/DataModel/PluginData.php | 72 +- lib/SP/DataModel/ProfileBaseData.php | 112 -- lib/SP/DataModel/ProfileData.php | 2 +- lib/SP/DataModel/PublicLinkData.php | 222 ++- lib/SP/DataModel/UserData.php | 282 ++-- lib/SP/DataModel/UserPassRecoverData.php | 48 +- ...pUsersData.php => UserToUserGroupData.php} | 26 +- lib/SP/Forms/CustomFieldDefForm.php | 8 +- lib/SP/Mgmt/Categories/Category.php | 54 +- lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php | 22 +- lib/SP/Mgmt/Groups/GroupAccountsBase.php | 4 +- lib/SP/Mgmt/Groups/GroupUsers.php | 22 +- lib/SP/Mgmt/Tracks/Track.php | 84 +- lib/SP/Mgmt/Users/UserLdapSync.php | 16 +- lib/SP/Mgmt/Users/UserPreferencesUtil.php | 20 +- .../Account/AccountRepository.php | 685 +++++++++ .../Account/AccountToUserGroupRepository.php | 162 +++ .../Account/AccountHistoryService.php | 427 ------ lib/SP/Services/Auth/LoginService.php | 574 ++++++++ .../CustomField/CustomFieldDefService.php | 311 ---- lib/SP/Services/ServiceItemTrait.php | 97 +- lib/SP/Services/User/UserPassResponse.php | 126 ++ lib/SP/Services/User/UserPassService.php | 255 ++++ lib/SP/Services/User/UserService.php | 685 +++------ lib/SP/Storage/DBUtil.php | 52 +- lib/SP/Storage/Database.php | 2 + lib/SP/Storage/DbWrapper.php | 8 +- schemas/dbstructure.sql | 1280 +++++++++-------- 61 files changed, 3838 insertions(+), 4037 deletions(-) create mode 100644 lib/Definitions.php delete mode 100644 lib/SP/Account/AccountSearch.php delete mode 100644 lib/SP/Auth/Browser/BrowserAuthData.php delete mode 100644 lib/SP/Auth/Ldap/LdapInterface.php delete mode 100644 lib/SP/Auth/Ldap/LdapMsAds.php create mode 100644 lib/SP/DataModel/AccountToUserGroupData.php delete mode 100644 lib/SP/DataModel/ProfileBaseData.php rename lib/SP/DataModel/{GroupUsersData.php => UserToUserGroupData.php} (71%) create mode 100644 lib/SP/Repositories/Account/AccountRepository.php create mode 100644 lib/SP/Repositories/Account/AccountToUserGroupRepository.php delete mode 100644 lib/SP/Services/Account/AccountHistoryService.php create mode 100644 lib/SP/Services/Auth/LoginService.php delete mode 100644 lib/SP/Services/CustomField/CustomFieldDefService.php create mode 100644 lib/SP/Services/User/UserPassResponse.php create mode 100644 lib/SP/Services/User/UserPassService.php diff --git a/ajax/ajax_getContent.php b/ajax/ajax_getContent.php index b1e3341d..e8964156 100644 --- a/ajax/ajax_getContent.php +++ b/ajax/ajax_getContent.php @@ -69,10 +69,10 @@ $Tpl->assign('actionId', $actionId); $Tpl->assign('id', $itemId); $Tpl->assign('activeTabId', $itemId); $Tpl->assign('queryTimeStart', microtime()); -$Tpl->assign('userId', $UserData->getUserId()); +$Tpl->assign('userId', $UserData->getId()); $Tpl->assign('userGroupId', $UserData->getUserGroupId()); -$Tpl->assign('userIsAdminApp', $UserData->isUserIsAdminApp()); -$Tpl->assign('userIsAdminAcc', $UserData->isUserIsAdminAcc()); +$Tpl->assign('userIsAdminApp', $UserData->isIsAdminApp()); +$Tpl->assign('userIsAdminAcc', $UserData->isIsAdminAcc()); $Tpl->assign('themeUri', $theme->getThemeUri()); switch ($actionId) { @@ -144,7 +144,7 @@ switch ($actionId) { $ConfigData = $dic->get(\SP\Config\ConfigData::class); // Se comprueba si se debe de mostrar la vista de depuración -if ($UserData->isUserIsAdminApp() && $ConfigData->isDebug()) { +if ($UserData->isIsAdminApp() && $ConfigData->isDebug()) { $Controller->getDebug(); } diff --git a/app/modules/web/Controllers/AccessManagerController.php b/app/modules/web/Controllers/AccessManagerController.php index 68d07ca2..f0fec5ba 100644 --- a/app/modules/web/Controllers/AccessManagerController.php +++ b/app/modules/web/Controllers/AccessManagerController.php @@ -31,11 +31,11 @@ use SP\DataModel\ItemSearchData; use SP\Http\Request; use SP\Modules\Web\Controllers\Helpers\ItemsGridHelper; use SP\Modules\Web\Controllers\Helpers\TabsGridHelper; -use SP\Services\ApiToken\ApiTokenService; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; +use SP\Repositories\ApiToken\ApiTokenRepository; +use SP\Repositories\PublicLink\PublicLinkRepository; +use SP\Repositories\User\UserRepository; +use SP\Repositories\UserGroup\UserGroupRepository; +use SP\Repositories\UserProfile\UserProfileRepository; /** * Class AccessMgmtController @@ -111,7 +111,7 @@ class AccessManagerController extends ControllerBase */ protected function getUsersList() { - $service = new UserService(); + $service = new UserRepository(); return $this->itemsGridHelper->getUsersGrid($service->search($this->itemSearchData))->updatePager(); } @@ -121,7 +121,7 @@ class AccessManagerController extends ControllerBase */ protected function getUsersGroupList() { - $service = new UserGroupService(); + $service = new UserGroupRepository(); return $this->itemsGridHelper->getUserGroupsGrid($service->search($this->itemSearchData))->updatePager(); } @@ -131,7 +131,7 @@ class AccessManagerController extends ControllerBase */ protected function getUsersProfileList() { - $service = new UserProfileService(); + $service = new UserProfileRepository(); return $this->itemsGridHelper->getUserProfilesGrid($service->search($this->itemSearchData))->updatePager(); } @@ -141,7 +141,7 @@ class AccessManagerController extends ControllerBase */ protected function getApiTokensList() { - $service = new ApiTokenService(); + $service = new ApiTokenRepository(); return $this->itemsGridHelper->getApiTokensGrid($service->search($this->itemSearchData))->updatePager(); } @@ -151,7 +151,7 @@ class AccessManagerController extends ControllerBase */ protected function getPublicLinksList() { - $service = new PublicLinkService(); + $service = new PublicLinkRepository(); return $this->itemsGridHelper->getPublicLinksGrid($service->search($this->itemSearchData))->updatePager(); } diff --git a/app/modules/web/Controllers/AccountController.php b/app/modules/web/Controllers/AccountController.php index 392e568b..4d45e8f5 100644 --- a/app/modules/web/Controllers/AccountController.php +++ b/app/modules/web/Controllers/AccountController.php @@ -33,6 +33,7 @@ use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\Core\SessionUtil; use SP\DataModel\AccountExtData; +use SP\DataModel\Dto\AccountDetailsResponse; use SP\Forms\AccountForm; use SP\Http\JsonResponse; use SP\Http\Request; @@ -44,8 +45,10 @@ use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\ItemTrait; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\CrudControllerInterface; +use SP\Repositories\Account\AccountRepository; +use SP\Repositories\PublicLink\PublicLinkRepository; +use SP\Services\Account\AccountFileService; use SP\Services\Account\AccountService; -use SP\Services\PublicLink\PublicLinkService; use SP\Util\ErrorUtil; use SP\Util\ImageUtil; use SP\Util\Util; @@ -59,6 +62,10 @@ class AccountController extends ControllerBase implements CrudControllerInterfac { use JsonTrait; use ItemTrait; + /** + * @var AccountService + */ + protected $accountService; /** * Index action @@ -70,7 +77,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac try { $AccountSearchHelper = new AccountSearchHelper($this->view, $this->config, $this->session, $this->eventDispatcher); $AccountSearchHelper->getSearchBox(); - $AccountSearchHelper->getSearch(); + $AccountSearchHelper->getAccountSearch(); $this->eventDispatcher->notifyEvent('show.account.search', $this); } catch (\Exception $e) { @@ -91,7 +98,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac { try { $AccountSearchHelper = new AccountSearchHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountSearchHelper->getSearch(); + $AccountSearchHelper->getAccountSearch(); $this->eventDispatcher->notifyEvent('show.account.search', $this); @@ -117,11 +124,21 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function viewAction($id) { try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountData($id, ActionsInterface::ACCOUNT_VIEW); + $AccountHelper->setAccount( + $accountDetailsResponse, + $this->accountService, + ActionsInterface::ACCOUNT_VIEW + ); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -136,7 +153,8 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $this->view->assign('isView', true); - $AccountHelper->getAccountService()->incrementViewCounter(); + $this->accountService->incrementViewCounter($id); + $AccountHelper->setCommonData(); $this->eventDispatcher->notifyEvent('show.account', $this); @@ -160,11 +178,11 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $LayoutHelper->getPublicLayout('account-link', 'account'); try { - $publicLinkService = new PublicLinkService(); + $publicLinkService = new PublicLinkRepository(); $publicLinkData = $publicLinkService->getByHash($hash); - if (time() < $publicLinkData->getPublicLinkDateExpire() - && $publicLinkData->getPublicLinkCountViews() < $publicLinkData->getPublicLinkMaxCountViews() + if (time() < $publicLinkData->getDateExpire() + && $publicLinkData->getCountViews() < $publicLinkData->getMaxCountViews() ) { $publicLinkService->addLinkView($publicLinkData); @@ -186,15 +204,14 @@ class AccountController extends ControllerBase implements CrudControllerInterfac // Notice::getItem($NoticeData)->add(); // } - $accountService = new AccountService(); - $accountService->incrementViewCounter($publicLinkData->getPublicLinkItemId()); - $accountService->incrementDecryptCounter($publicLinkData->getPublicLinkItemId()); + $this->accountService->incrementViewCounter($publicLinkData->getItemId()); + $this->accountService->incrementDecryptCounter($publicLinkData->getItemId()); /** @var Vault $vault */ - $vault = unserialize($publicLinkData->getPublicLinkData()); + $vault = unserialize($publicLinkData->getData()); /** @var AccountExtData $accountData */ - $accountData = Util::unserialize(AccountExtData::class, $vault->getData(PublicLinkService::getKeyForHash($this->config, $publicLinkData))); + $accountData = Util::unserialize(AccountExtData::class, $vault->getData(PublicLinkRepository::getKeyForHash($this->config, $publicLinkData))); $this->view->assign('title', [ @@ -208,7 +225,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $this->view->assign('useImage', $this->configData->isPublinksImageEnabled() || $this->configData->isAccountPassToImage()); if ($this->view->useImage) { - $this->view->assign('accountPassImage', ImageUtil::convertText($accountData->getAccountPass())); + $this->view->assign('accountPassImage', ImageUtil::convertText($accountData->getPass())); } else { $this->view->assign('copyPassRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW_PASS)); } @@ -245,9 +262,9 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $this->view->addTemplate('files-list', 'account'); - $this->view->assign('accountId', $id); $this->view->assign('deleteEnabled', Request::analyze('del', 0)); - $this->view->assign('files', FileUtil::getAccountFiles($id)); + + $this->view->assign('files', (new AccountFileService())->getByAccountId($id)); $this->view->assign('sk', SessionUtil::getSessionKey()); $this->view->assign('fileViewRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_FILE_VIEW)); $this->view->assign('fileDownloadRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_FILE_DOWNLOAD)); @@ -278,7 +295,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $AccountHelper->setActionId(ActionsInterface::ACCOUNT_CREATE); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -312,11 +329,21 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function copyAction($id) { try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountData($id, ActionsInterface::ACCOUNT_COPY); + $AccountHelper->setAccount( + $accountDetailsResponse, + $this->accountService, + ActionsInterface::ACCOUNT_COPY + ); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -350,11 +377,21 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function editAction($id) { try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountData($id, ActionsInterface::ACCOUNT_EDIT); + $AccountHelper->setAccount( + $accountDetailsResponse, + $this->accountService, + ActionsInterface::ACCOUNT_EDIT + ); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -368,7 +405,8 @@ class AccountController extends ControllerBase implements CrudControllerInterfac ); $this->view->assign('formRoute', 'account/saveEdit'); - $AccountHelper->getAccountService()->incrementViewCounter(); + $this->accountService->incrementViewCounter($id); + $AccountHelper->setCommonData(); $this->eventDispatcher->notifyEvent('show.account.edit', $this); @@ -389,11 +427,20 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function deleteAction($id) { try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse); + $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountData($id, ActionsInterface::ACCOUNT_DELETE); + $AccountHelper->setAccount( + $accountDetailsResponse, + $this->accountService, + ActionsInterface::ACCOUNT_DELETE + ); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -427,11 +474,20 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function editPassAction($id) { try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse); + $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountData($id, ActionsInterface::ACCOUNT_EDIT_PASS); + $AccountHelper->setAccount( + $accountDetailsResponse, + $this->accountService, + ActionsInterface::ACCOUNT_EDIT_PASS + ); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -445,7 +501,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac ); $this->view->assign('formRoute', 'account/saveEditPass'); - $this->view->assign('accountPassDateChange', gmdate('Y-m-d', $AccountHelper->getAccountData()->getAccountPassDateChange())); + $this->view->assign('accountPassDateChange', gmdate('Y-m-d', $AccountHelper->getAccountDetailsResponse()->getAccountVData()->getPassDateChange())); $this->eventDispatcher->notifyEvent('show.account.editpass', $this); } catch (\Exception $e) { @@ -466,10 +522,12 @@ class AccountController extends ControllerBase implements CrudControllerInterfac { try { $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountDataHistory($id, ActionsInterface::ACCOUNT_VIEW_HISTORY); + + // FIXME: Crear servicio AccountHistoryService + $AccountHelper->setAccountDataHistory($this->accountService->getById($id), ActionsInterface::ACCOUNT_VIEW_HISTORY); // Obtener los datos de la cuenta antes y comprobar el acceso - if (!$AccountHelper->checkAccess($this)) { + if (!$AccountHelper->checkAccess()) { return; } @@ -482,7 +540,6 @@ class AccountController extends ControllerBase implements CrudControllerInterfac ] ); $this->view->assign('formRoute', 'account/saveRestore'); - $this->view->assign('isView', true); $AccountHelper->setCommonData(); @@ -506,7 +563,11 @@ class AccountController extends ControllerBase implements CrudControllerInterfac { try { $AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $AccountHelper->setAccountDataHistory($id, ActionsInterface::ACCOUNT_REQUEST); + $AccountHelper->setAccount( + $this->accountService->getById($id), + $this->accountService, + ActionsInterface::ACCOUNT_REQUEST + ); $this->view->addTemplate('account-request'); $this->view->assign('formRoute', 'account/saveRequest'); @@ -531,13 +592,13 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function viewPassAction($id, $isHistory) { try { - $accountService = new AccountService(); $accountPassHelper = new AccountPasswordHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $account = $isHistory === 0 ? $accountService->getPasswordForId($id) : $accountService->getPasswordHistoryForId($id); + // FIXME: JS no envía isHistory + $account = $isHistory === 0 ? $this->accountService->getPasswordForId($id) : $this->accountService->getPasswordHistoryForId($id); $data = [ - 'acclogin' => $account->getAccountLogin(), + 'acclogin' => $account->getLogin(), 'accpass' => $accountPassHelper->getPassword($account, $this->acl, AccountPasswordHelper::TYPE_FULL), 'useimage' => $this->configData->isAccountPassToImage(), 'html' => $this->render() @@ -560,17 +621,14 @@ class AccountController extends ControllerBase implements CrudControllerInterfac * @param int $isHistory The account's ID refers to history * @throws Helpers\HelperException * @throws SPException - * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\CryptoException - * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException - * @throws \Psr\Container\ContainerExceptionInterface + * @throws \SP\Core\Exceptions\InvalidArgumentException */ public function copyPassAction($id, $isHistory) { - $accountService = new AccountService(); $accountPassHelper = new AccountPasswordHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $account = $isHistory === 0 ? $accountService->getPasswordForId($id) : $accountService->getPasswordHistoryForId($id); + $account = $isHistory === 0 ? $this->accountService->getPasswordForId($id) : $this->accountService->getPasswordHistoryForId($id); $data = [ 'accpass' => $accountPassHelper->getPassword($account, $this->acl, AccountPasswordHelper::TYPE_NORMAL), @@ -597,20 +655,17 @@ class AccountController extends ControllerBase implements CrudControllerInterfac try { $form = new AccountForm(); $form->validate(ActionsInterface::ACCOUNT_CREATE); - $form->getItemData()->setAccountUserId($this->userData->getUserId()); + $form->getItemData()->userId = $this->userData->getId(); - $accountService = new AccountService(); - $account = $accountService->create($form->getItemData()); + $accountId = $this->accountService->create($form->getItemData()); - $this->addCustomFieldsForItem(ActionsInterface::ACCOUNT, $account->getId()); - - $accountService->logAction($account->getId(), ActionsInterface::ACCOUNT_CREATE); + $this->addCustomFieldsForItem(ActionsInterface::ACCOUNT, $accountId); $this->eventDispatcher->notifyEvent('create.account', $this); $this->returnJsonResponseData( [ - 'itemId' => $account->getId(), + 'itemId' => $accountId, 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_EDIT) ], JsonResponse::JSON_SUCCESS, @@ -636,13 +691,10 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $form = new AccountForm($id); $form->validate(ActionsInterface::ACCOUNT_EDIT); - $accountService = new AccountService(); - $accountService->update($form->getItemData()); + $this->accountService->update($form->getItemData()); $this->updateCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); - $accountService->logAction($id, ActionsInterface::ACCOUNT_EDIT); - $this->eventDispatcher->notifyEvent('edit.account', $this); $this->returnJsonResponseData( @@ -673,10 +725,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac $form = new AccountForm($id); $form->validate(ActionsInterface::ACCOUNT_EDIT_PASS); - $accountService = new AccountService(); - $accountService->editPassword($form->getItemData()); - - $accountService->logAction($id, ActionsInterface::ACCOUNT_EDIT_PASS); + $this->accountService->editPassword($form->getItemData()); $this->eventDispatcher->notifyEvent('edit.account.pass', $this); @@ -706,10 +755,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function saveEditRestoreAction($historyId, $id) { try { - $accountService = new AccountService(); - $accountService->editRestore($historyId, $id); - - $accountService->logAction($id, ActionsInterface::ACCOUNT_EDIT_RESTORE); + $this->accountService->editRestore($historyId, $id); $this->eventDispatcher->notifyEvent('edit.account.restore', $this); @@ -736,13 +782,11 @@ class AccountController extends ControllerBase implements CrudControllerInterfac public function saveDeleteAction($id) { try { - $accountService = new AccountService(); - - if ($accountService->delete($id)) { + if ($this->accountService->delete($id)) { $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); // FIXME: obtener cuenta antes de eliminar -// $accountService->logAccountAction($id, ActionsInterface::ACCOUNT_DELETE); +// $accountRepository->logAccountAction($id, ActionsInterface::ACCOUNT_DELETE); $this->eventDispatcher->notifyEvent('delete.account', $this); @@ -767,5 +811,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac if ($this->actionName !== 'viewLinkAction') { $this->checkLoggedIn(); } + + $this->accountService = new AccountService(); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/BootstrapController.php b/app/modules/web/Controllers/BootstrapController.php index 88e7e780..0a236577 100644 --- a/app/modules/web/Controllers/BootstrapController.php +++ b/app/modules/web/Controllers/BootstrapController.php @@ -25,13 +25,13 @@ namespace SP\Modules\Web\Controllers; use Exception; -use SP\Auth\Browser\Browser; use SP\Bootstrap; use SP\Core\CryptPKI; use SP\Core\Plugin\PluginUtil; use SP\Core\SessionFactory; use SP\Http\Cookies; use SP\Http\Response; +use SP\Providers\Auth\Browser\Browser; /** * Class BootstrapController @@ -55,7 +55,7 @@ class BootstrapController extends SimpleControllerBase 'max_file_size' => $configData->getFilesAllowedSize(), 'check_updates' => $this->session->getAuthCompleted() && ($configData->isCheckUpdates() || $configData->isChecknotices()) - && ($this->session->getUserData()->isUserIsAdminApp() || $configData->isDemoEnabled()), + && ($this->session->getUserData()->getIsAdminApp() || $configData->isDemoEnabled()), 'timezone' => date_default_timezone_get(), 'debug' => DEBUG || $configData->isDebug(), 'cookies_enabled' => Cookies::checkCookies(), diff --git a/app/modules/web/Controllers/CategoryController.php b/app/modules/web/Controllers/CategoryController.php index ccb514de..d8179b3d 100644 --- a/app/modules/web/Controllers/CategoryController.php +++ b/app/modules/web/Controllers/CategoryController.php @@ -39,7 +39,7 @@ 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\Services\Category\CategoryService; +use SP\Repositories\Category\CategoryRepository; /** * Class CategoryController @@ -52,7 +52,7 @@ class CategoryController extends ControllerBase implements CrudControllerInterfa use ItemTrait; /** - * @var CategoryService + * @var CategoryRepository */ protected $categoryService; @@ -276,7 +276,7 @@ class CategoryController extends ControllerBase implements CrudControllerInterfa { $this->checkLoggedIn(); - $this->categoryService = new CategoryService(); + $this->categoryService = new CategoryRepository(); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/Helpers/AccountSearchHelper.php b/app/modules/web/Controllers/Helpers/AccountSearchHelper.php index 9a7a9a7b..29bc6442 100644 --- a/app/modules/web/Controllers/Helpers/AccountSearchHelper.php +++ b/app/modules/web/Controllers/Helpers/AccountSearchHelper.php @@ -24,8 +24,8 @@ namespace SP\Modules\Web\Controllers\Helpers; -use SP\Account\AccountSearch; -use SP\Account\AccountsSearchItem; +use SP\Account\AccountSearchFilter; +use SP\Account\AccountSearchItem; use SP\Core\Acl\ActionsInterface; use SP\Core\SessionUtil; use SP\Html\DataGrid\DataGrid; @@ -36,9 +36,10 @@ use SP\Html\DataGrid\DataGridHeaderSort; use SP\Html\DataGrid\DataGridPager; use SP\Html\DataGrid\DataGridSort; use SP\Http\Request; -use SP\Mgmt\Categories\Category; -use SP\Mgmt\Customers\Customer; -use SP\Mgmt\Tags\Tag; +use SP\Repositories\Category\CategoryRepository; +use SP\Repositories\Client\ClientRepository; +use SP\Repositories\Tag\TagRepository; +use SP\Services\Account\AccountSearchService; /** * Class AccountSearch @@ -55,8 +56,8 @@ class AccountSearchHelper extends HelperBase private $queryTimeStart = 0; /** @var bool */ private $isAjax = false; - /** @var AccountSearch */ - private $search; + /** @var AccountSearchFilter */ + private $accountSearchFilter; /** * @param boolean $isAjax @@ -73,42 +74,43 @@ class AccountSearchHelper extends HelperBase { $this->view->addTemplate('search-searchbox'); - $this->view->assign('customers', Customer::getItem()->getItemsForSelectByUser()); - $this->view->assign('categories', Category::getItem()->getItemsForSelect()); - $this->view->assign('tags', Tag::getItem()->getItemsForSelect()); + $clientService = new ClientRepository(); + + $this->view->assign('customers', $clientService->getItemsForSelectByUser()); + $this->view->assign('categories', CategoryRepository::getServiceItems()); + $this->view->assign('tags', TagRepository::getServiceItems()); } /** * Obtener los resultados de una búsqueda * - * @throws \InvalidArgumentException * @throws \Psr\Container\ContainerExceptionInterface * @throws \SP\Core\Exceptions\SPException */ - public function getSearch() + public function getAccountSearch() { $this->view->addTemplate('search-index'); $this->view->assign('isAjax', $this->isAjax); - $this->filterOn = ($this->search->getSortKey() > 1 - || $this->search->getCustomerId() - || $this->search->getCategoryId() - || $this->search->getTagsId() - || $this->search->getTxtSearch() - || $this->search->isSearchFavorites() - || $this->search->isSortViews()); + $this->filterOn = ($this->accountSearchFilter->getSortKey() > 1 + || $this->accountSearchFilter->getClientId() + || $this->accountSearchFilter->getCategoryId() + || $this->accountSearchFilter->getTagsId() + || $this->accountSearchFilter->getTxtSearch() + || $this->accountSearchFilter->isSearchFavorites() + || $this->accountSearchFilter->isSortViews()); - $UserPreferences = $this->session->getUserPreferences(); + $userPreferences = $this->session->getUserData()->getPreferences(); - AccountsSearchItem::$accountLink = $UserPreferences->isAccountLink(); - AccountsSearchItem::$topNavbar = $UserPreferences->isTopNavbar(); - AccountsSearchItem::$optionalActions = $UserPreferences->isOptionalActions(); - AccountsSearchItem::$wikiEnabled = $this->configData->isWikiEnabled(); - AccountsSearchItem::$dokuWikiEnabled = $this->configData->isDokuwikiEnabled(); - AccountsSearchItem::$isDemoMode = $this->configData->isDemoEnabled(); + AccountSearchItem::$accountLink = $userPreferences->isAccountLink(); + AccountSearchItem::$topNavbar = $userPreferences->isTopNavbar(); + AccountSearchItem::$optionalActions = $userPreferences->isOptionalActions(); + AccountSearchItem::$wikiEnabled = $this->configData->isWikiEnabled(); + AccountSearchItem::$dokuWikiEnabled = $this->configData->isDokuwikiEnabled(); + AccountSearchItem::$isDemoMode = $this->configData->isDemoEnabled(); - if (AccountsSearchItem::$wikiEnabled) { + if (AccountSearchItem::$wikiEnabled) { $wikiFilter = array_map(function ($value) { return preg_quote($value, '/'); }, $this->configData->getWikiFilter()); @@ -117,14 +119,16 @@ class AccountSearchHelper extends HelperBase $this->view->assign('wikiPageUrl', $this->configData->getWikiPageurl()); } + $accountSearchService = new AccountSearchService(); + $Grid = $this->getGrid(); - $Grid->getData()->setData($this->search->processSearchResults()); + $Grid->getData()->setData($accountSearchService->processSearchResults($this->accountSearchFilter)); $Grid->updatePager(); $Grid->setTime(round(microtime() - $this->queryTimeStart, 5)); // Establecer el filtro de búsqueda en la sesión como un objeto - $this->session->setSearchFilters($this->search); + $this->session->setSearchFilters($this->accountSearchFilter); $this->view->assign('data', $Grid); } @@ -144,7 +148,7 @@ class AccountSearchHelper extends HelperBase $GridActionOptional->setName(__('Más Acciones')); $GridActionOptional->setTitle(__('Más Acciones')); $GridActionOptional->setIcon($icons->getIconOptional()); - $GridActionOptional->setReflectionFilter(AccountsSearchItem::class, 'isShowOptional'); + $GridActionOptional->setReflectionFilter(AccountSearchItem::class, 'isShowOptional'); $GridActionOptional->addData('onclick', 'account/menu'); $GridPager = new DataGridPager(); @@ -152,17 +156,18 @@ class AccountSearchHelper extends HelperBase $GridPager->setIconNext($icons->getIconNavNext()); $GridPager->setIconFirst($icons->getIconNavFirst()); $GridPager->setIconLast($icons->getIconNavLast()); - $GridPager->setSortKey($this->search->getSortKey()); - $GridPager->setSortOrder($this->search->getSortOrder()); - $GridPager->setLimitStart($this->search->getLimitStart()); - $GridPager->setLimitCount($this->search->getLimitCount()); + $GridPager->setSortKey($this->accountSearchFilter->getSortKey()); + $GridPager->setSortOrder($this->accountSearchFilter->getSortOrder()); + $GridPager->setLimitStart($this->accountSearchFilter->getLimitStart()); + $GridPager->setLimitCount($this->accountSearchFilter->getLimitCount()); $GridPager->setOnClickFunction('account/sort'); $GridPager->setFilterOn($this->filterOn); $GridPager->setSourceAction(new DataGridActionSearch(ActionsInterface::ACCOUNT_SEARCH)); + $userPreferences = $this->session->getUserData()->getPreferences(); + $showOptionalActions = $userPreferences->isOptionalActions() || $userPreferences->isResultsAsCards() || ($userPreferences->getUserId() === 0 && $this->configData->isResultsAsCards()); + $actions = new AccountActionsHelper($this->view, $this->config, $this->session, $this->eventDispatcher); - $UserPreferences = $this->session->getUserPreferences(); - $showOptionalActions = $UserPreferences->isOptionalActions() || $UserPreferences->isResultsAsCards() || ($UserPreferences->getUserId() === 0 && $this->configData->isResultsAsCards()); $Grid = new DataGrid(); $Grid->setId('gridSearch'); @@ -195,35 +200,35 @@ class AccountSearchHelper extends HelperBase $GridSortCustomer = new DataGridSort(); $GridSortCustomer->setName(__('Cliente')) ->setTitle(__('Ordenar por Cliente')) - ->setSortKey(AccountSearch::SORT_CUSTOMER) + ->setSortKey(AccountSearchFilter::SORT_CLIENT) ->setIconUp($icons->getIconUp()) ->setIconDown($icons->getIconDown()); $GridSortName = new DataGridSort(); $GridSortName->setName(__('Nombre')) ->setTitle(__('Ordenar por Nombre')) - ->setSortKey(AccountSearch::SORT_NAME) + ->setSortKey(AccountSearchFilter::SORT_NAME) ->setIconUp($icons->getIconUp()) ->setIconDown($icons->getIconDown()); $GridSortCategory = new DataGridSort(); $GridSortCategory->setName(__('Categoría')) ->setTitle(__('Ordenar por Categoría')) - ->setSortKey(AccountSearch::SORT_CATEGORY) + ->setSortKey(AccountSearchFilter::SORT_CATEGORY) ->setIconUp($icons->getIconUp()) ->setIconDown($icons->getIconDown()); $GridSortLogin = new DataGridSort(); $GridSortLogin->setName(__('Usuario')) ->setTitle(__('Ordenar por Usuario')) - ->setSortKey(AccountSearch::SORT_LOGIN) + ->setSortKey(AccountSearchFilter::SORT_LOGIN) ->setIconUp($icons->getIconUp()) ->setIconDown($icons->getIconDown()); $GridSortUrl = new DataGridSort(); $GridSortUrl->setName(__('URL / IP')) ->setTitle(__('Ordenar por URL / IP')) - ->setSortKey(AccountSearch::SORT_URL) + ->setSortKey(AccountSearchFilter::SORT_URL) ->setIconUp($icons->getIconUp()) ->setIconDown($icons->getIconDown()); @@ -257,44 +262,50 @@ class AccountSearchHelper extends HelperBase { $userData = $this->session->getUserData(); - $this->view->assign('isAdmin', $userData->isUserIsAdminApp() || $userData->isUserIsAdminAcc()); + $this->view->assign('isAdmin', $userData->getIsAdminApp() || $userData->getIsAdminAcc()); $this->view->assign('showGlobalSearch', $this->configData->isGlobalSearch() && $this->session->getUserProfile()->isAccGlobalSearch()); // Obtener el filtro de búsqueda desde la sesión - $this->search = $this->getFilters(); + $this->accountSearchFilter = $this->getFilters(); - $this->view->assign('searchCustomer', $this->search->getCustomerId()); - $this->view->assign('searchCategory', $this->search->getCategoryId()); - $this->view->assign('searchTags', $this->search->getTagsId()); - $this->view->assign('searchTxt', $this->search->getTxtSearch()); - $this->view->assign('searchGlobal', $this->search->getGlobalSearch()); - $this->view->assign('searchFavorites', $this->search->isSearchFavorites()); + $this->view->assign('searchCustomer', $this->accountSearchFilter->getClientId()); + $this->view->assign('searchCategory', $this->accountSearchFilter->getCategoryId()); + $this->view->assign('searchTags', $this->accountSearchFilter->getTagsId()); + $this->view->assign('searchTxt', $this->accountSearchFilter->getTxtSearch()); + $this->view->assign('searchGlobal', $this->accountSearchFilter->getGlobalSearch()); + $this->view->assign('searchFavorites', $this->accountSearchFilter->isSearchFavorites()); } /** * Set search filters * - * @return AccountSearch + * @return AccountSearchFilter */ private function getFilters() { - if (empty(Request::analyze('sk'))) { + $accountSearchFilter = $this->session->getSearchFilters(); + + if ($accountSearchFilter !== null && empty(Request::analyze('sk'))) { // Obtener el filtro de búsqueda desde la sesión - return $this->session->getSearchFilters(); + return $accountSearchFilter; } - $this->search = new AccountSearch(); - $this->search->setSortKey(Request::analyze('skey', 0)); - $this->search->setSortOrder(Request::analyze('sorder', 0)); - $this->search->setLimitStart(Request::analyze('start', 0)); - $this->search->setLimitCount(Request::analyze('rpp', 0)); - $this->search->setGlobalSearch(Request::analyze('gsearch', false)); - $this->search->setCustomerId(Request::analyze('customer', 0)); - $this->search->setCategoryId(Request::analyze('category', 0)); - $this->search->setTagsId(Request::analyze('tags')); - $this->search->setSearchFavorites(Request::analyze('searchfav', false)); - $this->search->setTxtSearch(Request::analyze('search')); + $userPreferences = $this->session->getUserData()->getPreferences(); + $limitCount = ($userPreferences->getResultsPerPage() > 0) ? $userPreferences->getResultsPerPage() : $this->configData->getAccountCount(); - return $this->search; + $accountSearchFilter = new AccountSearchFilter(); + $accountSearchFilter->setSortKey(Request::analyze('skey', 0)); + $accountSearchFilter->setSortOrder(Request::analyze('sorder', 0)); + $accountSearchFilter->setLimitStart(Request::analyze('start', 0)); + $accountSearchFilter->setLimitCount(Request::analyze('rpp', $limitCount)); + $accountSearchFilter->setGlobalSearch(Request::analyze('gsearch', false)); + $accountSearchFilter->setClientId(Request::analyze('customer', 0)); + $accountSearchFilter->setCategoryId(Request::analyze('category', 0)); + $accountSearchFilter->setTagsId(Request::analyze('tags')); + $accountSearchFilter->setSearchFavorites(Request::analyze('searchfav', false)); + $accountSearchFilter->setTxtSearch(Request::analyze('search')); + $accountSearchFilter->setSortViews($userPreferences->isSortViews()); + + return $accountSearchFilter; } } \ No newline at end of file diff --git a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php index 8199694b..3c1b8bf5 100644 --- a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php +++ b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php @@ -37,7 +37,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridHeader; use SP\Html\DataGrid\DataGridPager; use SP\Html\DataGrid\DataGridTab; -use SP\Services\CustomField\CustomFieldDefService; +use SP\Repositories\CustomField\CustomFieldDefRepository; /** * Class Grids con las plantillas de tablas de datos @@ -77,9 +77,9 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('category_id'); - $GridData->addDataRowSource('category_name'); - $GridData->addDataRowSource('category_description'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('description'); $GridData->setData($data); // Grid @@ -179,10 +179,10 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('customer_id'); - $GridData->addDataRowSource('customer_name'); - $GridData->addDataRowSource('customer_description'); - $GridData->addDataRowSource('customer_isGlobal', false, function ($value) { + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('description'); + $GridData->addDataRowSource('isGlobal', false, function ($value) { return $value ? __u('SI') : __u('NO'); }); $GridData->setData($data); @@ -265,7 +265,7 @@ class ItemsGridHelper extends HelperBase $GridData->setDataRowSourceId('id'); $GridData->addDataRowSource('name'); $GridData->addDataRowSource('moduleId', false, function ($value) { - return CustomFieldDefService::getFieldModuleById($value); + return CustomFieldDefRepository::getFieldModuleById($value); }); $GridData->addDataRowSource('typeName'); $GridData->setData($data); @@ -348,8 +348,8 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); $GridData->setDataRowSourceId('id'); - $GridData->addDataRowSource('account_name'); - $GridData->addDataRowSource('customer_name'); + $GridData->addDataRowSource('accountName'); + $GridData->addDataRowSource('clientName'); $GridData->addDataRowSource('name'); $GridData->addDataRowSource('type'); $GridData->addDataRowSource('size'); @@ -417,9 +417,9 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('account_id'); - $GridData->addDataRowSource('account_name'); - $GridData->addDataRowSource('customer_name'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('clientName'); $GridData->setData($data); // Grid @@ -478,12 +478,12 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('acchistory_id'); - $GridData->addDataRowSource('acchistory_name'); - $GridData->addDataRowSource('customer_name'); - $GridData->addDataRowSource('acchistory_date'); - $GridData->addDataRowSourceWithIcon('acchistory_isModify', $iconEdit->setTitle(__('Modificada'))->setClass('opacity50')); - $GridData->addDataRowSourceWithIcon('acchistory_isDeleted', $iconDelete->setTitle(__('Eliminada'))->setClass('opacity50')); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('clientName'); + $GridData->addDataRowSource('date'); + $GridData->addDataRowSourceWithIcon('isModify', $iconEdit->setTitle(__('Modificada'))->setClass('opacity50')); + $GridData->addDataRowSourceWithIcon('isDeleted', $iconDelete->setTitle(__('Eliminada'))->setClass('opacity50')); $GridData->setData($data); // Grid @@ -550,15 +550,15 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('user_id'); - $GridData->addDataRowSource('user_name'); - $GridData->addDataRowSource('user_login'); - $GridData->addDataRowSource('userprofile_name'); - $GridData->addDataRowSource('usergroup_name'); - $GridData->addDataRowSourceWithIcon('user_isAdminApp', $this->icons->getIconAppAdmin()); - $GridData->addDataRowSourceWithIcon('user_isAdminAcc', $this->icons->getIconAccAdmin()); - $GridData->addDataRowSourceWithIcon('user_isLdap', $this->icons->getIconLdapUser()); - $GridData->addDataRowSourceWithIcon('user_isDisabled', $this->icons->getIconDisabled()); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('login'); + $GridData->addDataRowSource('userProfileName'); + $GridData->addDataRowSource('userGroupName'); + $GridData->addDataRowSourceWithIcon('isAdminApp', $this->icons->getIconAppAdmin()); + $GridData->addDataRowSourceWithIcon('isAdminAcc', $this->icons->getIconAccAdmin()); + $GridData->addDataRowSourceWithIcon('isLdap', $this->icons->getIconLdapUser()); + $GridData->addDataRowSourceWithIcon('isDisabled', $this->icons->getIconDisabled()); $GridData->setData($data); // Grid @@ -641,7 +641,7 @@ class ItemsGridHelper extends HelperBase $GridActionEditPass->setTitle(__('Cambiar Clave de Usuario')); $GridActionEditPass->setIcon($this->icons->getIconEditPass()); $GridActionEditPass->setOnClickFunction('appMgmt/show'); - $GridActionEditPass->setFilterRowSource('user_isLdap'); + $GridActionEditPass->setFilterRowSource('isLdap'); $GridActionEditPass->addData('action-route', Acl::getActionRoute(ActionsInterface::USER_EDIT_PASS)); $Grid->setDataActions($GridActionEditPass); @@ -674,9 +674,9 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('usergroup_id'); - $GridData->addDataRowSource('usergroup_name'); - $GridData->addDataRowSource('usergroup_description'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('description'); $GridData->setData($data); // Grid @@ -763,8 +763,8 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('userprofile_id'); - $GridData->addDataRowSource('userprofile_name'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); $GridData->setData($data); // Grid @@ -852,9 +852,9 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('authtoken_id'); - $GridData->addDataRowSource('user_login'); - $GridData->addDataRowSource('authtoken_actionId'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('userLogin'); + $GridData->addDataRowSource('actionId'); $GridData->setData($data); // Grid @@ -946,11 +946,11 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('publicLink_id'); - $GridData->addDataRowSource('account_name'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('accountName'); $GridData->addDataRowSource('getDateAddFormat', true); $GridData->addDataRowSource('getDateExpireFormat', true); - $GridData->addDataRowSource('user_login'); + $GridData->addDataRowSource('userLogin'); $GridData->addDataRowSource('getNotifyString', true); $GridData->addDataRowSource('getCountViewsString', true); $GridData->setData($data); @@ -1038,8 +1038,8 @@ class ItemsGridHelper extends HelperBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('tag_id'); - $GridData->addDataRowSource('tag_name'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); $GridData->setData($data); // Grid diff --git a/app/modules/web/Controllers/PublicLinkController.php b/app/modules/web/Controllers/PublicLinkController.php index 3d49325a..62a2a098 100644 --- a/app/modules/web/Controllers/PublicLinkController.php +++ b/app/modules/web/Controllers/PublicLinkController.php @@ -41,7 +41,7 @@ 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\Services\PublicLink\PublicLinkService; +use SP\Repositories\PublicLink\PublicLinkRepository; /** * Class PublicLinkController @@ -54,7 +54,7 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter use ItemTrait; /** - * @var PublicLinkService + * @var PublicLinkRepository */ protected $publicLinkService; @@ -124,7 +124,7 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter $this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ACCESS_MANAGE)); if ($this->view->isView === true) { - $this->view->assign('publicLinkURL', PublicLinkService::getLinkForHash($publicLink->getPublicLinkHash())); + $this->view->assign('publicLinkURL', PublicLinkRepository::getLinkForHash($publicLink->getHash())); $this->view->assign('disabled', 'disabled'); $this->view->assign('readonly', 'readonly'); } else { @@ -290,6 +290,6 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter { $this->checkLoggedIn(); - $this->publicLinkService = new PublicLinkService(); + $this->publicLinkService = new PublicLinkRepository(); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/UserGroupController.php b/app/modules/web/Controllers/UserGroupController.php index 98584d09..477bd858 100644 --- a/app/modules/web/Controllers/UserGroupController.php +++ b/app/modules/web/Controllers/UserGroupController.php @@ -30,7 +30,7 @@ use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\Core\SessionUtil; -use SP\DataModel\GroupData; +use SP\DataModel\UserGroupData; use SP\Forms\UserGroupForm; use SP\Http\JsonResponse; use SP\Http\Request; @@ -38,9 +38,10 @@ 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\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserGroup\UserToGroupService; +use SP\Repositories\User\UserRepository; +use SP\Repositories\UserGroup\UserGroupRepository; +use SP\Repositories\UserGroup\UserToGroupService; +use SP\Repositories\UserGroup\UserToUserGroupRepository; /** * Class GroupController @@ -53,13 +54,13 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf use ItemTrait; /** - * @var UserGroupService + * @var UserGroupRepository */ protected $userGroupService; /** - * @var UserToGroupService + * @var UserToUserGroupRepository */ - protected $userToGroupService; + protected $userToUserGroupService; /** * Search action @@ -110,19 +111,17 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf /** * Sets view data for displaying user's data * - * @param $groupId - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Defuse\Crypto\Exception\CryptoException + * @param $userGroupId */ - protected function setViewData($groupId = null) + protected function setViewData($userGroupId = null) { $this->view->addTemplate('usergroup', 'itemshow'); - $group = $groupId ? $this->userGroupService->getById($groupId) : new GroupData(); + $group = $userGroupId ? $this->userGroupService->getById($userGroupId) : new UserGroupData(); $this->view->assign('group', $group); - $this->view->assign('users', UserService::getServiceItems()); - $this->view->assign('groupUsers', $this->userToGroupService->getById($groupId)); + $this->view->assign('users', UserRepository::getServiceItems()); + $this->view->assign('groupUsers', $this->userToUserGroupService->getById($userGroupId)); $this->view->assign('sk', SessionUtil::getSessionKey(true)); $this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ACCESS_MANAGE)); @@ -135,7 +134,7 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $this->view->assign('readonly'); } - $this->view->assign('customFields', $this->getCustomFieldsForItem(ActionsInterface::GROUP, $groupId)); + $this->view->assign('customFields', $this->getCustomFieldsForItem(ActionsInterface::GROUP, $userGroupId)); } /** @@ -209,7 +208,7 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $id = $this->userGroupService->create($groupData); $this->userGroupService->logAction($id, ActionsInterface::GROUP_CREATE); - $this->userToGroupService->add($id, $groupData->getUsers()); + $this->userToUserGroupService->add($id, $groupData->getUsers()); $this->addCustomFieldsForItem(ActionsInterface::GROUP, $id); @@ -244,7 +243,7 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf $this->userGroupService->update($groupData); $this->userGroupService->logAction($id, ActionsInterface::GROUP_EDIT); - $this->userToGroupService->update($groupData->getUsergroupId(), $groupData->getUsers()); + $this->userToUserGroupService->update($groupData->getId(), $groupData->getUsers()); $this->updateCustomFieldsForItem(ActionsInterface::GROUP, $id); @@ -293,7 +292,7 @@ class UserGroupController extends ControllerBase implements CrudControllerInterf { $this->checkLoggedIn(); - $this->userGroupService = new UserGroupService(); - $this->userToGroupService = new UserToGroupService(); + $this->userGroupService = new UserGroupRepository(); + $this->userToUserGroupService = new UserToUserGroupRepository(); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/UserProfileController.php b/app/modules/web/Controllers/UserProfileController.php index 3e983200..8a6aad16 100644 --- a/app/modules/web/Controllers/UserProfileController.php +++ b/app/modules/web/Controllers/UserProfileController.php @@ -38,7 +38,7 @@ 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\Services\UserProfile\UserProfileService; +use SP\Repositories\UserProfile\UserProfileRepository; /** * Class UserProfileController @@ -51,7 +51,7 @@ class UserProfileController extends ControllerBase implements CrudControllerInte use ItemTrait; /** - * @var UserProfileService + * @var UserProfileRepository */ protected $userProfileService; @@ -285,6 +285,6 @@ class UserProfileController extends ControllerBase implements CrudControllerInte { $this->checkLoggedIn(); - $this->userProfileService = new UserProfileService(); + $this->userProfileService = new UserProfileRepository(); } } \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc b/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc index 8b96809a..5b3e689a 100644 --- a/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc +++ b/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc @@ -18,11 +18,11 @@
  • layers - account_name, $account->customer_name); ?> + name, $account->clientName); ?>
  • diff --git a/app/modules/web/themes/material-blue/views/account/search-index.inc b/app/modules/web/themes/material-blue/views/account/search-index.inc index 137c157d..1018070f 100644 --- a/app/modules/web/themes/material-blue/views/account/search-index.inc +++ b/app/modules/web/themes/material-blue/views/account/search-index.inc @@ -1,7 +1,7 @@ @@ -15,7 +15,7 @@ getDataHeaderTemplate(); ?> - +
    getDataPagerTemplate(); ?> diff --git a/app/modules/web/themes/material-blue/views/itemshow/publiclink.inc b/app/modules/web/themes/material-blue/views/itemshow/publiclink.inc index 1672f45d..4e593373 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/publiclink.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/publiclink.inc @@ -22,7 +22,7 @@ + value="id; ?>" id === $publicLink->getItemId() ? 'selected' : ''; ?>>name, $account->clientName); ?> @@ -34,7 +34,7 @@ title=""> isPublicLinkNotify() ? 'CHECKED' : ''; ?> /> + name="notify" isNotify() ? 'CHECKED' : ''; ?> /> @@ -77,7 +77,7 @@
    - getPublicLinkHash(); ?> + getHash(); ?> @@ -95,7 +95,7 @@
      - getPublicLinkUseInfo() as $useInfo): ?> + getUseInfo() as $useInfo): ?>
    • access_time diff --git a/app/modules/web/themes/material-blue/views/itemshow/tag.inc b/app/modules/web/themes/material-blue/views/itemshow/tag.inc index e6e000f9..8b254d73 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/tag.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/tag.inc @@ -19,7 +19,7 @@
      + maxlength="50" value="getName(); ?>">
      diff --git a/lib/Base.php b/lib/Base.php index 31a057ed..2dfcad93 100644 --- a/lib/Base.php +++ b/lib/Base.php @@ -62,47 +62,58 @@ require __DIR__ . DIRECTORY_SEPARATOR . 'SplClassLoader.php'; initModule(APP_MODULE); -$dic = new Container(); +//$dic = new Container(); +// +//$dic->share(\Klein\Klein::class); +// +//$dic->share(\SP\Core\Session\Session::class); +// +//$dic->share(\SP\Config\Config::class, function () { +// return new SP\Config\Config(new \SP\Storage\XmlHandler(XML_CONFIG_FILE)); +//}); +// +//$dic->share(\SP\Core\Language::class); +// +//$dic->share(\SP\Config\ConfigData::class, function ($dic) { +// /** @var \SP\Config\Config $config */ +// /** @var \SP\Core\Dic\DicInterface $dic */ +// $config = $dic->get(\SP\Config\Config::class); +// +// return $config->getConfigData(); +//}); +// +//$dic->share(\SP\Storage\Database::class, function () { +// return new \SP\Storage\Database(new \SP\Storage\MySQLHandler()); +//}); +// +//$dic->share(\SP\Core\Acl\Acl::class, function ($dic) { +// /** @var \SP\Core\Session\Session $session */ +// /** @var \SP\Core\Dic\DicInterface $dic */ +// $session = $dic->get(\SP\Core\Session\Session::class); +// +// return new \SP\Core\Acl\Acl($session, new \SP\Core\Acl\Action(new \SP\Storage\FileCache())); +//}); +// +//$dic->share(\SP\Core\UI\Theme::class, function () { +// return new \SP\Core\UI\Theme(APP_MODULE); +//}); +// +//$dic->share(\SP\Core\Events\EventDispatcher::class); +// +//$dic->add(\SP\Log\Log::class, function () { +// return new SP\Log\Log(new \SP\Core\Messages\LogMessage()); +//}); -$dic->share(\Klein\Klein::class); +try { + (new Bootstrap())->initialize(); +} catch (\Exception $e) { + debugLog($e->getMessage()); + debugLog($e->getTraceAsString()); -$dic->share(\SP\Core\Session\Session::class); + die($e->getMessage()); +} catch (\Psr\Container\ContainerExceptionInterface $e) { + debugLog($e->getMessage()); + debugLog($e->getTraceAsString()); -$dic->share(\SP\Config\Config::class, function () { - return new SP\Config\Config(new \SP\Storage\XmlHandler(XML_CONFIG_FILE)); -}); - -$dic->share(\SP\Core\Language::class); - -$dic->share(\SP\Config\ConfigData::class, function ($dic) { - /** @var \SP\Config\Config $config */ - /** @var \SP\Core\Dic\DicInterface $dic */ - $config = $dic->get(\SP\Config\Config::class); - - return $config->getConfigData(); -}); - -$dic->share(\SP\Storage\Database::class, function () { - return new \SP\Storage\Database(new \SP\Storage\MySQLHandler()); -}); - -$dic->share(\SP\Core\Acl\Acl::class, function ($dic) { - /** @var \SP\Core\Session\Session $session */ - /** @var \SP\Core\Dic\DicInterface $dic */ - $session = $dic->get(\SP\Core\Session\Session::class); - - return new \SP\Core\Acl\Acl($session, new \SP\Core\Acl\Action(new \SP\Storage\FileCache())); -}); - -$dic->share(\SP\Core\UI\Theme::class, function () { - return new \SP\Core\UI\Theme(APP_MODULE); -}); - -$dic->share(\SP\Core\Events\EventDispatcher::class); - -$dic->add(\SP\Log\Log::class, function () { - return new SP\Log\Log(new \SP\Core\Messages\LogMessage()); -}); - -$Bootstrap = new Bootstrap(); -$Bootstrap->initialize(); \ No newline at end of file + die($e->getMessage()); +} \ No newline at end of file diff --git a/lib/Definitions.php b/lib/Definitions.php new file mode 100644 index 00000000..aa2c1d85 --- /dev/null +++ b/lib/Definitions.php @@ -0,0 +1,51 @@ +. + */ + +use function DI\get; +use function DI\object; +use Interop\Container\ContainerInterface; + +return [ + \Klein\Klein::class => object(\Klein\Klein::class), + \SP\Core\Session\Session::class => object(\SP\Core\Session\Session::class), + \SP\Config\Config::class => object(\SP\Config\Config::class) + ->constructor(object(\SP\Storage\XmlHandler::class) + ->constructor(XML_CONFIG_FILE)), + \SP\Core\Language::class => object(\SP\Core\Language::class), + \SP\Config\ConfigData::class => function (ContainerInterface $c) { + $config = $c->get(\SP\Config\Config::class); + + return $config->getConfigData(); + }, + \SP\Storage\Database::class => object(\SP\Storage\Database::class) + ->constructor(object(\SP\Storage\MySQLHandler::class)), + \SP\Core\Acl\Acl::class => object(\SP\Core\Acl\Acl::class) + ->constructor(get(\SP\Core\Session\Session::class), object(\SP\Core\Acl\Action::class) + ->constructor(object(\SP\Storage\FileCache::class))), + \SP\Core\Acl\Action::class => object(\SP\Core\UI\Theme::class), + \SP\Core\UI\Theme::class => object(\SP\Core\UI\Theme::class) + ->constructor(APP_MODULE), + \SP\Core\Events\EventDispatcher::class => object(\SP\Core\Events\EventDispatcher::class), + \SP\Log\Log::class => object(\SP\Log\Log::class)->scope(\DI\Scope::PROTOTYPE) +]; \ No newline at end of file diff --git a/lib/SP/Account/Account.php b/lib/SP/Account/Account.php index 5b807cee..37c0ead0 100644 --- a/lib/SP/Account/Account.php +++ b/lib/SP/Account/Account.php @@ -32,7 +32,7 @@ use SP\Core\Exceptions\SPException; use SP\Core\SessionFactory; use SP\DataModel\AccountData; use SP\DataModel\AccountExtData; -use SP\DataModel\GroupAccountsData; +use SP\DataModel\AccountToUserGroupData; use SP\Log\Log; use SP\Mgmt\Groups\GroupAccounts; use SP\Mgmt\Groups\GroupAccountsUtil; @@ -54,19 +54,19 @@ class Account extends AccountBase implements AccountInterface */ public function updateAccount() { - $Acl = $this->session->getAccountAcl($this->accountData->getAccountId()); + $Acl = $this->session->getAccountAcl($this->accountData->getId()); // Guardamos una copia de la cuenta en el histórico - AccountHistory::addHistory($this->accountData->getAccountId(), false); + AccountHistory::addHistory($this->accountData->getId(), false); try { if ($Acl->getStoredAcl()->isShowPermission()) { - $GroupAccountsData = new GroupAccountsData(); - $GroupAccountsData->setAccgroupAccountId($this->accountData->getAccountId()); + $GroupAccountsData = new AccountToUserGroupData(); + $GroupAccountsData->setAccountId($this->accountData->getId()); $GroupAccountsData->setGroups($this->accountData->getUserGroupsId()); GroupAccounts::getItem($GroupAccountsData)->update(); - UserAccounts::updateUsersForAccount($this->accountData->getAccountId(), $this->accountData->getUsersId()); + UserAccounts::updateUsersForAccount($this->accountData->getId(), $this->accountData->getUsersId()); } } catch (SPException $e) { Log::writeNewLog(__FUNCTION__, $e->getMessage(), Log::ERROR); @@ -94,36 +94,36 @@ class Account extends AccountBase implements AccountInterface 'account_parentId = :accountParentId' ]; - if ($this->accountData->getAccountUserGroupId()) { + if ($this->accountData->getUserGroupId()) { $fields[] = 'account_userGroupId = :accountUserGroupId'; - $Data->addParam($this->accountData->getAccountUserGroupId(), 'accountUserGroupId'); + $Data->addParam($this->accountData->getUserGroupId(), 'accountUserGroupId'); } if ($Acl->getStoredAcl()->isShowPermission()) { $fields[] = 'account_otherUserEdit = :accountOtherUserEdit'; $fields[] = 'account_otherGroupEdit = :accountOtherGroupEdit'; - $Data->addParam($this->accountData->getAccountOtherUserEdit(), 'accountOtherUserEdit'); - $Data->addParam($this->accountData->getAccountOtherGroupEdit(), 'accountOtherGroupEdit'); + $Data->addParam($this->accountData->getOtherUserEdit(), 'accountOtherUserEdit'); + $Data->addParam($this->accountData->getOtherUserGroupEdit(), 'accountOtherGroupEdit'); } $query = /** @lang SQL */ - 'UPDATE accounts SET ' . implode(',', $fields) . ' WHERE account_id = :accountId'; + 'UPDATE Account SET ' . implode(',', $fields) . ' WHERE account_id = :accountId'; $Data->setQuery($query); - $Data->addParam($this->accountData->getAccountCustomerId(), 'accountCustomerId'); - $Data->addParam($this->accountData->getAccountCategoryId(), 'accountCategoryId'); - $Data->addParam($this->accountData->getAccountName(), 'accountName'); - $Data->addParam($this->accountData->getAccountLogin(), 'accountLogin'); - $Data->addParam($this->accountData->getAccountUrl(), 'accountUrl'); - $Data->addParam($this->accountData->getAccountNotes(), 'accountNotes'); - $Data->addParam($this->accountData->getAccountUserEditId(), 'accountUserEditId'); - $Data->addParam($this->accountData->getAccountPassDateChange(), 'accountPassDateChange'); - $Data->addParam($this->accountData->getAccountIsPrivate(), 'accountIsPrivate'); - $Data->addParam($this->accountData->getAccountIsPrivateGroup(), 'accountIsPrivateGroup'); - $Data->addParam($this->accountData->getAccountParentId(), 'accountParentId'); - $Data->addParam($this->accountData->getAccountId(), 'accountId'); + $Data->addParam($this->accountData->getClientId(), 'accountCustomerId'); + $Data->addParam($this->accountData->getCategoryId(), 'accountCategoryId'); + $Data->addParam($this->accountData->getName(), 'accountName'); + $Data->addParam($this->accountData->getLogin(), 'accountLogin'); + $Data->addParam($this->accountData->getUrl(), 'accountUrl'); + $Data->addParam($this->accountData->getNotes(), 'accountNotes'); + $Data->addParam($this->accountData->getUserEditId(), 'accountUserEditId'); + $Data->addParam($this->accountData->getPassDateChange(), 'accountPassDateChange'); + $Data->addParam($this->accountData->getIsPrivate(), 'accountIsPrivate'); + $Data->addParam($this->accountData->getIsPrivateGroup(), 'accountIsPrivateGroup'); + $Data->addParam($this->accountData->getParentId(), 'accountParentId'); + $Data->addParam($this->accountData->getId(), 'accountId'); $Data->setOnErrorMessage(__('Error al modificar la cuenta', false)); DbWrapper::getQuery($Data); @@ -141,10 +141,10 @@ class Account extends AccountBase implements AccountInterface public function restoreFromHistory($id) { // Guardamos una copia de la cuenta en el histórico - AccountHistory::addHistory($this->accountData->getAccountId(), false); + AccountHistory::addHistory($this->accountData->getId(), false); $query = /** @lang SQL */ - 'UPDATE accounts dst, ' + 'UPDATE Account dst, ' . '(SELECT * FROM accHistory WHERE acchistory_id = :id) src SET ' . 'dst.account_customerId = src.acchistory_customerId,' . 'dst.account_categoryId = src.acchistory_categoryId,' @@ -169,7 +169,7 @@ class Account extends AccountBase implements AccountInterface $Data = new QueryData(); $Data->setQuery($query); $Data->addParam($id, 'id'); - $Data->addParam($this->session->getUserData()->getUserId(), 'accountUserEditId'); + $Data->addParam($this->session->getUserData()->getId(), 'accountUserEditId'); $Data->setOnErrorMessage(__('Error al restaurar cuenta', false)); DbWrapper::getQuery($Data); @@ -192,7 +192,7 @@ class Account extends AccountBase implements AccountInterface $Data = new QueryData(); $Data->setQuery($query); $Data->setMapClass($this->accountData); - $Data->addParam($this->accountData->getAccountId()); + $Data->addParam($this->accountData->getId()); /** @var AccountExtData|array $queryRes */ $queryRes = DbWrapper::getResults($Data); @@ -204,8 +204,8 @@ class Account extends AccountBase implements AccountInterface } // Obtener los usuarios y grupos secundarios y las etiquetas - $this->accountData->setUsersId(UserAccounts::getUsersForAccount($this->accountData->getAccountId())); - $this->accountData->setUserGroupsId(GroupAccountsUtil::getGroupsForAccount($this->accountData->getAccountId())); + $this->accountData->setUsersId(UserAccounts::getUsersForAccount($this->accountData->getId())); + $this->accountData->setUserGroupsId(GroupAccountsUtil::getGroupsForAccount($this->accountData->getId())); $this->accountData->setTags(AccountTags::getTags($queryRes)); return $this->accountData; @@ -230,7 +230,7 @@ class Account extends AccountBase implements AccountInterface } $query = /** @lang SQL */ - 'INSERT INTO accounts SET ' + 'INSERT INTO Account SET ' . 'account_customerId = :accountCustomerId,' . 'account_categoryId = :accountCategoryId,' . 'account_name = :accountName,' @@ -253,40 +253,40 @@ class Account extends AccountBase implements AccountInterface $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->accountData->getAccountCustomerId(), 'accountCustomerId'); - $Data->addParam($this->accountData->getAccountCategoryId(), 'accountCategoryId'); - $Data->addParam($this->accountData->getAccountName(), 'accountName'); - $Data->addParam($this->accountData->getAccountLogin(), 'accountLogin'); - $Data->addParam($this->accountData->getAccountUrl(), 'accountUrl'); - $Data->addParam($this->accountData->getAccountPass(), 'accountPass'); - $Data->addParam($this->accountData->getAccountKey(), 'accountKey'); - $Data->addParam($this->accountData->getAccountNotes(), 'accountNotes'); - $Data->addParam($this->accountData->getAccountUserId(), 'accountUserId'); - $Data->addParam($this->accountData->getAccountUserGroupId() ?: $this->session->getUserData()->getUserGroupId(), 'accountUserGroupId'); - $Data->addParam($this->accountData->getAccountUserId(), 'accountUserEditId'); - $Data->addParam($this->accountData->getAccountOtherUserEdit(), 'accountOtherUserEdit'); - $Data->addParam($this->accountData->getAccountOtherGroupEdit(), 'accountOtherGroupEdit'); - $Data->addParam($this->accountData->getAccountIsPrivate(), 'accountIsPrivate'); - $Data->addParam($this->accountData->getAccountIsPrivateGroup(), 'accountIsPrivateGroup'); - $Data->addParam($this->accountData->getAccountPassDateChange(), 'accountPassDateChange'); - $Data->addParam($this->accountData->getAccountParentId(), 'accountParentId'); + $Data->addParam($this->accountData->getClientId(), 'accountCustomerId'); + $Data->addParam($this->accountData->getCategoryId(), 'accountCategoryId'); + $Data->addParam($this->accountData->getName(), 'accountName'); + $Data->addParam($this->accountData->getLogin(), 'accountLogin'); + $Data->addParam($this->accountData->getUrl(), 'accountUrl'); + $Data->addParam($this->accountData->getPass(), 'accountPass'); + $Data->addParam($this->accountData->getKey(), 'accountKey'); + $Data->addParam($this->accountData->getNotes(), 'accountNotes'); + $Data->addParam($this->accountData->getUserId(), 'accountUserId'); + $Data->addParam($this->accountData->getUserGroupId() ?: $this->session->getUserData()->getUserGroupId(), 'accountUserGroupId'); + $Data->addParam($this->accountData->getUserId(), 'accountUserEditId'); + $Data->addParam($this->accountData->getOtherUserEdit(), 'accountOtherUserEdit'); + $Data->addParam($this->accountData->getOtherUserGroupEdit(), 'accountOtherGroupEdit'); + $Data->addParam($this->accountData->getIsPrivate(), 'accountIsPrivate'); + $Data->addParam($this->accountData->getIsPrivateGroup(), 'accountIsPrivateGroup'); + $Data->addParam($this->accountData->getPassDateChange(), 'accountPassDateChange'); + $Data->addParam($this->accountData->getParentId(), 'accountParentId'); $Data->setOnErrorMessage(__('Error al crear la cuenta', false)); DbWrapper::getQuery($Data); - $this->accountData->setAccountId(DbWrapper::$lastId); + $this->accountData->setId(DbWrapper::$lastId); try { if (is_array($this->accountData->getAccountUserGroupsId())) { - $GroupAccounsData = new GroupAccountsData(); - $GroupAccounsData->setAccgroupAccountId($this->accountData->getAccountId()); + $GroupAccounsData = new AccountToUserGroupData(); + $GroupAccounsData->setAccountId($this->accountData->getId()); $GroupAccounsData->setGroups($this->accountData->getAccountUserGroupsId()); GroupAccounts::getItem($GroupAccounsData)->add(); } if (is_array($this->accountData->getAccountUsersId())) { - UserAccounts::addUsersForAccount($this->accountData->getAccountId(), $this->accountData->getAccountUsersId()); + UserAccounts::addUsersForAccount($this->accountData->getId(), $this->accountData->getAccountUsersId()); } if (is_array($this->accountData->getTags())) { @@ -314,10 +314,10 @@ class Account extends AccountBase implements AccountInterface $masterPass = $masterPass ?: CryptSession::getSessionKey(); $securedKey = Crypt::makeSecuredKey($masterPass); - $this->accountData->setAccountPass(Crypt::encrypt($this->accountData->getAccountPass(), $securedKey, $masterPass)); - $this->accountData->setAccountKey($securedKey); + $this->accountData->setPass(Crypt::encrypt($this->accountData->getPass(), $securedKey, $masterPass)); + $this->accountData->setKey($securedKey); - if (strlen($securedKey) > 1000 || strlen($this->accountData->getAccountPass()) > 1000) { + if (strlen($securedKey) > 1000 || strlen($this->accountData->getPass()) > 1000) { throw new QueryException(SPException::SP_ERROR, __('Error interno', false)); } } catch (CryptoException $e) { @@ -348,7 +348,7 @@ class Account extends AccountBase implements AccountInterface $Data = new QueryData(); $query = /** @lang SQL */ - 'DELETE FROM accounts WHERE account_id = ? LIMIT 1'; + 'DELETE FROM Account WHERE account_id = ? LIMIT 1'; $Data->setQuery($query); $Data->addParam($id); @@ -370,11 +370,11 @@ class Account extends AccountBase implements AccountInterface public function incrementViewCounter($id = null) { $query = /** @lang SQL */ - 'UPDATE accounts SET account_countView = (account_countView + 1) WHERE account_id = ? LIMIT 1'; + 'UPDATE Account SET account_countView = (account_countView + 1) WHERE account_id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($id ?: $this->accountData->getAccountId()); + $Data->addParam($id ?: $this->accountData->getId()); return DbWrapper::getQuery($Data); } @@ -390,11 +390,11 @@ class Account extends AccountBase implements AccountInterface public function incrementDecryptCounter($id = null) { $query = /** @lang SQL */ - 'UPDATE accounts SET account_countDecrypt = (account_countDecrypt + 1) WHERE account_id = ? LIMIT 1'; + 'UPDATE Account SET account_countDecrypt = (account_countDecrypt + 1) WHERE account_id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($id ?: $this->accountData->getAccountId()); + $Data->addParam($id ?: $this->accountData->getId()); return DbWrapper::getQuery($Data); } @@ -412,13 +412,13 @@ class Account extends AccountBase implements AccountInterface { // No actualizar el histórico si es por cambio de clave maestra o restauración if (!$isMassive) { - AccountHistory::addHistory($this->accountData->getAccountId(), false); + AccountHistory::addHistory($this->accountData->getId(), false); $this->setPasswordEncrypted(); } $query = /** @lang SQL */ - 'UPDATE accounts SET ' + 'UPDATE Account SET ' . 'account_pass = :accountPass,' . 'account_key = :accountKey,' . 'account_userEditId = :accountUserEditId,' @@ -429,11 +429,11 @@ class Account extends AccountBase implements AccountInterface $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->accountData->getAccountPass(), 'accountPass'); - $Data->addParam($this->accountData->getAccountKey(), 'accountKey'); - $Data->addParam($this->accountData->getAccountUserEditId(), 'accountUserEditId'); - $Data->addParam($this->accountData->getAccountPassDateChange(), 'accountPassDateChange'); - $Data->addParam($this->accountData->getAccountId(), 'accountId'); + $Data->addParam($this->accountData->getPass(), 'accountPass'); + $Data->addParam($this->accountData->getKey(), 'accountKey'); + $Data->addParam($this->accountData->getUserEditId(), 'accountUserEditId'); + $Data->addParam($this->accountData->getPassDateChange(), 'accountPassDateChange'); + $Data->addParam($this->accountData->getId(), 'accountId'); $Data->setOnErrorMessage(__('Error al actualizar la clave', false)); DbWrapper::getQuery($Data); @@ -456,19 +456,19 @@ class Account extends AccountBase implements AccountInterface . 'account_login,' . 'account_pass,' . 'account_key,' - . 'customer_name ' - . 'FROM accounts ' - . 'LEFT JOIN customers ON account_customerId = customer_id ' + . 'name ' + . 'FROM Account ' + . 'LEFT JOIN Client ON account_customerId = id ' . 'WHERE account_id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); $Data->setMapClass($this->accountData); - $Data->addParam($this->accountData->getAccountId()); + $Data->addParam($this->accountData->getId()); // Obtener los usuarios y grupos secundarios - $this->accountData->setUsersId(UserAccounts::getUsersForAccount($this->accountData->getAccountId())); - $this->accountData->setUserGroupsId(GroupAccountsUtil::getGroupsForAccount($this->accountData->getAccountId())); + $this->accountData->setUsersId(UserAccounts::getUsersForAccount($this->accountData->getId())); + $this->accountData->setUserGroupsId(GroupAccountsUtil::getGroupsForAccount($this->accountData->getId())); return DbWrapper::getResults($Data); } @@ -489,17 +489,17 @@ class Account extends AccountBase implements AccountInterface . 'account_key,' . 'account_url,' . 'account_notes,' - . 'category_name,' - . 'customer_name ' - . 'FROM accounts ' - . 'LEFT JOIN customers ON account_customerId = customer_id ' - . 'LEFT JOIN categories ON account_categoryId = category_id ' + . 'name,' + . 'name ' + . 'FROM Account ' + . 'LEFT JOIN Client ON account_customerId = id ' + . 'LEFT JOIN categories ON account_categoryId = id ' . 'WHERE account_id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); $Data->setMapClass($this->accountData); - $Data->addParam($this->accountData->getAccountId()); + $Data->addParam($this->accountData->getId()); /** @var AccountExtData|array $queryRes */ $queryRes = DbWrapper::getResults($Data); diff --git a/lib/SP/Account/AccountSearch.php b/lib/SP/Account/AccountSearch.php deleted file mode 100644 index 01381de1..00000000 --- a/lib/SP/Account/AccountSearch.php +++ /dev/null @@ -1,753 +0,0 @@ -. - */ - -namespace SP\Account; - -use SP\Config\ConfigData; -use SP\Core\Acl\Acl; -use SP\Core\Session\Session; -use SP\Core\SessionFactory; -use SP\Core\Traits\InjectableTrait; -use SP\DataModel\AccountSearchData; -use SP\Mgmt\Groups\GroupUtil; -use SP\Mgmt\Users\User; -use SP\Storage\DbWrapper; -use SP\Storage\QueryData; -use SP\Util\Filter; - -defined('APP_ROOT') || die(); - -/** - * Class AccountSearch para la gestión de búsquedas de cuentas - */ -class AccountSearch -{ - /** - * Constantes de ordenación - */ - const SORT_NAME = 1; - const SORT_CATEGORY = 2; - const SORT_LOGIN = 3; - const SORT_URL = 4; - const SORT_CUSTOMER = 5; - const SORT_DIR_ASC = 0; - const SORT_DIR_DESC = 1; - /** - * @var int El número de registros de la última consulta - */ - public static $queryNumRows; - /** - * Colores para resaltar las cuentas - * - * @var array - */ - private static $colors = [ - '2196F3', - '03A9F4', - '00BCD4', - '009688', - '4CAF50', - '8BC34A', - 'CDDC39', - 'FFC107', - '795548', - '607D8B', - '9E9E9E', - 'FF5722', - 'F44336', - 'E91E63', - '9C27B0', - '673AB7', - '3F51B5', - ]; - /** - * @var Session - */ - protected $session; - /** - * @var ConfigData - */ - protected $configData; - /** - * @var bool - */ - private $globalSearch = false; - /** - * @var string - */ - private $txtSearch; - /** - * @var int - */ - private $customerId = 0; - /** - * @var int - */ - private $categoryId = 0; - /** - * @var array - */ - private $tagsId = []; - /** - * @var int - */ - private $sortOrder = 0; - /** - * @var int - */ - private $sortKey = 0; - /** - * @var int - */ - private $limitStart = 0; - /** - * @var int - */ - private $limitCount = 12; - /** - * @var bool - */ - private $sortViews; - /** - * @var bool - */ - private $searchFavorites = false; - - use InjectableTrait; - - /** - * Constructor - */ - public function __construct() - { - $this->injectDependencies(); - - $userResultsPerPage = (SessionFactory::getSessionType() === SessionFactory::SESSION_INTERACTIVE) ? $this->session->getUserPreferences()->getResultsPerPage() : 0; - - $this->limitCount = ($userResultsPerPage > 0) ? $userResultsPerPage : $this->configData->getAccountCount(); - $this->sortViews = (SessionFactory::getSessionType() === SessionFactory::SESSION_INTERACTIVE) ? $this->session->getUserPreferences()->isSortViews() : false; - } - - /** - * @param ConfigData $configData - * @param Session $session - */ - public function inject(ConfigData $configData, Session $session) - { - $this->configData = $configData; - $this->session = $session; - } - - /** - * @return boolean - */ - public function isSearchFavorites() - { - return $this->searchFavorites; - } - - /** - * @param boolean $searchFavorites - * @return $this - */ - public function setSearchFavorites($searchFavorites) - { - $this->searchFavorites = (bool)$searchFavorites; - - return $this; - } - - /** - * @return int - */ - public function getGlobalSearch() - { - return $this->globalSearch; - } - - /** - * @param int $globalSearch - * @return $this - */ - public function setGlobalSearch($globalSearch) - { - $this->globalSearch = $globalSearch; - - return $this; - } - - /** - * @return string - */ - public function getTxtSearch() - { - return $this->txtSearch; - } - - /** - * @param string $txtSearch - * @return $this - */ - public function setTxtSearch($txtSearch) - { - $this->txtSearch = Filter::safeSearchString($txtSearch); - - return $this; - } - - /** - * @return int - */ - public function getCustomerId() - { - return $this->customerId; - } - - /** - * @param int $customerId - * @return $this - */ - public function setCustomerId($customerId) - { - $this->customerId = $customerId; - - return $this; - } - - /** - * @return int - */ - public function getCategoryId() - { - return $this->categoryId; - } - - /** - * @param int $categoryId - * @return $this - */ - public function setCategoryId($categoryId) - { - $this->categoryId = $categoryId; - - return $this; - } - - /** - * @return int - */ - public function getSortOrder() - { - return $this->sortOrder; - } - - /** - * @param int $sortOrder - * @return $this - */ - public function setSortOrder($sortOrder) - { - $this->sortOrder = $sortOrder; - - return $this; - } - - /** - * @return int - */ - public function getLimitStart() - { - return $this->limitStart; - } - - /** - * @param int $limitStart - * @return $this - */ - public function setLimitStart($limitStart) - { - $this->limitStart = $limitStart; - - return $this; - } - - /** - * @return int - */ - public function getLimitCount() - { - return $this->limitCount; - } - - /** - * @param int $limitCount - * @return $this - */ - public function setLimitCount($limitCount) - { - $this->limitCount = $limitCount; - - return $this; - } - - /** - * Procesar los resultados de la búsqueda y crear la variable que contiene los datos de cada cuenta - * a mostrar. - * - * @return array - * @throws \SP\Core\Exceptions\SPException - */ - public function processSearchResults() - { - if (!$results = $this->getAccounts()) { - return []; - } - - // Variables de configuración - $maxTextLength = $this->configData->isResultsAsCards() ? 40 : 60; - - $accountsData['count'] = self::$queryNumRows; - - $accountLinkEnabled = $this->session->getUserPreferences()->isAccountLink() || $this->configData->isAccountLink(); - $favorites = AccountFavorites::getFavorites($this->session->getUserData()->getUserId()); - - /** @var AccountSearchData $accountSearchData */ - foreach ($results as $accountSearchData) { - // Propiedades de búsqueda de cada cuenta - $accountsSearchItem = new AccountsSearchItem($accountSearchData); - - // Obtener la ACL de la cuenta - $accountAcl = new AccountAcl(Acl::ACCOUNT_SEARCH, $accountSearchData); - - if (!$accountSearchData->getAccountIsPrivate()) { - $accountSearchData->setUsersId($accountsSearchItem->getCacheUsers(true)); - $accountSearchData->setUserGroupsId($accountsSearchItem->getCacheGroups(true)); - } - - $accountSearchData->setTags(AccountTags::getTags($accountSearchData)); - - // Obtener la ACL - $acl = $accountAcl->getAcl(); - - $this->session->setAccountAcl($acl); - - $accountsSearchItem->setTextMaxLength($maxTextLength); - $accountsSearchItem->setColor($this->pickAccountColor($accountSearchData->getAccountCustomerId())); - $accountsSearchItem->setShowView($acl->isShowView()); - $accountsSearchItem->setShowViewPass($acl->isShowViewPass()); - $accountsSearchItem->setShowEdit($acl->isShowEdit()); - $accountsSearchItem->setShowCopy($acl->isShowCopy()); - $accountsSearchItem->setShowDelete($acl->isShowDelete()); - $accountsSearchItem->setLink($accountLinkEnabled); - $accountsSearchItem->setFavorite(in_array($accountSearchData->getAccountId(), $favorites, true)); - - $accountsData[] = $accountsSearchItem; - } - - return $accountsData; - } - - /** - * Obtener las cuentas de una búsqueda. - * - * @return AccountSearchData[] Resultado de la consulta - * @throws \SP\Core\Exceptions\SPException - */ - public function getAccounts() - { - $arrFilterCommon = []; - $arrFilterSelect = []; - $arrayQueryJoin = []; - $arrQueryWhere = []; - $queryLimit = ''; - - $data = new QueryData(); - $data->setMapClassName(AccountSearchData::class); - - if ($this->txtSearch !== null && $this->txtSearch !== '') { - // Analizar la cadena de búsqueda por etiquetas especiales - $stringFilters = $this->analyzeQueryString(); - - if (count($stringFilters) > 0) { - foreach ($stringFilters as $filter) { - $arrFilterCommon[] = $filter['query']; - - foreach ($filter['values'] as $value) { - $data->addParam($value); - } - } - } else { - $txtSearch = '%' . $this->txtSearch . '%'; - - $arrFilterCommon[] = 'account_name LIKE ?'; - $data->addParam($txtSearch); - - $arrFilterCommon[] = 'account_login LIKE ?'; - $data->addParam($txtSearch); - - $arrFilterCommon[] = 'account_url LIKE ?'; - $data->addParam($txtSearch); - - $arrFilterCommon[] = 'account_notes LIKE ?'; - $data->addParam($txtSearch); - } - } - - if ($this->categoryId !== 0) { - $arrFilterSelect[] = 'account_categoryId = ?'; - $data->addParam($this->categoryId); - } - - if ($this->customerId !== 0) { - $arrFilterSelect[] = 'account_customerId = ?'; - $data->addParam($this->customerId); - } - - $numTags = count($this->tagsId); - - if ($numTags > 0) { - $tags = str_repeat('?,', $numTags - 1) . '?'; - - $arrFilterSelect[] = 'account_id IN (SELECT acctag_accountId FROM accTags WHERE acctag_tagId IN (' . $tags . '))'; - - for ($i = 0; $i <= $numTags - 1; $i++) { - $data->addParam($this->tagsId[$i]); - } - } - - if ($this->searchFavorites === true) { - $arrayQueryJoin[] = 'INNER JOIN accFavorites ON (accfavorite_accountId = account_id AND accfavorite_userId = ?)'; - $data->addParam($this->session->getUserData()->getUserId()); - } - - if (count($arrFilterCommon) > 0) { - $arrQueryWhere[] = '(' . implode(' OR ', $arrFilterCommon) . ')'; - } - - if (count($arrFilterSelect) > 0) { - $arrQueryWhere[] = '(' . implode(' AND ', $arrFilterSelect) . ')'; - } - - $arrQueryWhere = array_merge($arrQueryWhere, AccountUtil::getAccountFilterUser($data, $this->session, $this->globalSearch)); - - if ($this->limitCount > 0) { - $queryLimit = '?, ?'; - - $data->addParam($this->limitStart); - $data->addParam($this->limitCount); - } - - $queryWhere = ''; - - if (count($arrQueryWhere) === 1) { - $queryWhere = implode($arrQueryWhere); - } elseif (count($arrQueryWhere) > 1) { - $queryWhere = implode(' AND ', $arrQueryWhere); - } - - $queryJoin = implode('', $arrayQueryJoin); - - $data->setSelect('*'); - $data->setFrom('account_search_v ' . $queryJoin); - $data->setWhere($queryWhere); - $data->setOrder($this->getOrderString()); - $data->setLimit($queryLimit); - - // Obtener el número total de cuentas visibles por el usuario - DbWrapper::setFullRowCount(); - -// Log::writeNewLog(__FUNCTION__, $Data->getQuery(), Log::DEBUG); -// Log::writeNewLog(__FUNCTION__, print_r($Data->getParams(), true), Log::DEBUG); - - // Consulta de la búsqueda de cuentas - $queryRes = DbWrapper::getResultsArray($data); - - // Obtenemos el número de registros totales de la consulta sin contar el LIMIT - self::$queryNumRows = $data->getQueryNumRows(); - - return $queryRes; - } - - /** - * Analizar la cadena de consulta por eqituetas especiales y devolver un array - * con las columnas y los valores a buscar. - * - * @return array|bool - * @throws \SP\Core\Exceptions\SPException - */ - private function analyzeQueryString() - { - if (!preg_match('/^(user|group|file|owner|maingroup):"([\w\.]+)"$/i', $this->txtSearch, $filters) - && !preg_match('/^(expired|private):$/i', $this->txtSearch, $filters) - ) { - return []; - } - - $filtersData = []; - - switch ($filters[1]) { - case 'user': - $UserData = User::getItem()->getByLogin($filters[2]); - - if (!is_object($UserData)) { - return []; - } - - $filtersData[] = [ - 'type' => 'user', - 'query' => 'account_userId = ? OR account_id IN (SELECT accuser_accountId AS accountId FROM accUsers WHERE accuser_accountId = account_id AND accuser_userId = ? UNION ALL SELECT accgroup_accountId AS accountId FROM accGroups WHERE accgroup_accountId = account_id AND accgroup_groupId = ?)', - 'values' => [$UserData->getUserId(), $UserData->getUserId(), $UserData->getUserGroupId()] - ]; - break; - case 'owner': - $UserData = User::getItem()->getByLogin($filters[2]); - - if (!is_object($UserData)) { - return []; - } - - $filtersData[] = [ - 'type' => 'user', - 'query' => 'account_userId = ?', - 'values' => [$UserData->getUserId()] - ]; - break; - case 'group': - $GroupData = GroupUtil::getGroupIdByName($filters[2]); - - if (!is_object($GroupData)) { - return []; - } - - $filtersData[] = [ - 'type' => 'group', - 'query' => 'account_userGroupId = ? OR account_id IN (SELECT accgroup_accountId AS accountId FROM accGroups WHERE accgroup_accountId = account_id AND accgroup_groupId = ?)', - 'values' => [$GroupData->getUsergroupId(), $GroupData->getUsergroupId()] - ]; - break; - case 'maingroup': - $GroupData = GroupUtil::getGroupIdByName($filters[2]); - - if (!is_object($GroupData)) { - return []; - } - - $filtersData[] = [ - 'type' => 'group', - 'query' => 'account_userGroupId = ?', - 'values' => [$GroupData->getUsergroupId()] - ]; - break; - case 'file': - $filtersData[] = [ - 'type' => 'file', - 'query' => 'account_id IN (SELECT accfile_accountId FROM accFiles WHERE accfile_name LIKE ?)', - 'values' => ['%' . $filters[2] . '%'] - ]; - break; - case 'expired': - $filtersData[] = - [ - 'type' => 'expired', - 'query' => 'account_passDateChange > 0 AND UNIX_TIMESTAMP() > account_passDateChange', - 'values' => [] - ]; - break; - case 'private': - $filtersData[] = - [ - 'type' => 'private', - 'query' => '(account_isPrivate = 1 AND account_userId = ?) OR (account_isPrivateGroup = 1 AND account_userGroupId = ?)', - 'values' => [$this->session->getUserData()->getUserId(), $this->session->getUserData()->getUserGroupId()] - ]; - break; - default: - return $filtersData; - } - - return $filtersData; - } - - /** - * Devuelve la cadena de ordenación de la consulta - * - * @return string - */ - private function getOrderString() - { - switch ($this->sortKey) { - case self::SORT_NAME: - $orderKey[] = 'account_name'; - break; - case self::SORT_CATEGORY: - $orderKey[] = 'category_name'; - break; - case self::SORT_LOGIN: - $orderKey[] = 'account_login'; - break; - case self::SORT_URL: - $orderKey[] = 'account_url'; - break; - case self::SORT_CUSTOMER: - $orderKey[] = 'customer_name'; - break; - default : - $orderKey[] = 'customer_name'; - $orderKey[] = 'account_name'; - break; - } - - if ($this->isSortViews() && !$this->getSortKey()) { - array_unshift($orderKey, 'account_countView DESC'); - $this->setSortOrder(self::SORT_DIR_DESC); - } - - $orderDir = ($this->sortOrder === self::SORT_DIR_ASC) ? 'ASC' : 'DESC'; - return sprintf('%s %s', implode(',', $orderKey), $orderDir); - } - - /** - * @return boolean - */ - public function isSortViews() - { - return $this->sortViews; - } - - /** - * @param boolean $sortViews - * @return $this - */ - public function setSortViews($sortViews) - { - $this->sortViews = $sortViews; - - return $this; - } - - /** - * @return int - */ - public function getSortKey() - { - return $this->sortKey; - } - - /** - * @param int $sortKey - * @return $this - */ - public function setSortKey($sortKey) - { - $this->sortKey = $sortKey; - - return $this; - } - - /** - * Seleccionar un color para la cuenta - * - * @param int $id El id del elemento a asignar - * @return mixed - */ - private function pickAccountColor($id) - { - $accountColor = SessionFactory::getAccountColor(); - - if (!is_array($accountColor) - || !isset($accountColor, $accountColor[$id]) - ) { - // Se asigna el color de forma aleatoria a cada id - $color = array_rand(self::$colors); - - $accountColor[$id] = '#' . self::$colors[$color]; - SessionFactory::setAccountColor($accountColor); - } - - return $accountColor[$id]; - } - - /** - * @return array - */ - public function getTagsId() - { - return $this->tagsId; - } - - /** - * @param array $tagsId - * @return $this - */ - public function setTagsId($tagsId) - { - if (is_array($tagsId)) { - $this->tagsId = $tagsId; - } - - return $this; - } - - /** - * unserialize() checks for the presence of a function with the magic name __wakeup. - * If present, this function can reconstruct any resources that the object may have. - * The intended use of __wakeup is to reestablish any database connections that may have been lost during - * serialization and perform other reinitialization tasks. - * - * @return void - * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep - */ - public function __wakeup() - { - $this->injectDependencies(); - } - - /** - * serialize() checks if your class has a function with the magic name __sleep. - * If so, that function is executed prior to any serialization. - * It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. - * If the method doesn't return anything then NULL is serialized and E_NOTICE is issued. - * The intended use of __sleep is to commit pending data or perform similar cleanup tasks. - * Also, the function is useful if you have very large objects which do not need to be saved completely. - * - * @return string[] - * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep - */ - public function __sleep() - { - unset($this->dic, $this->configData, $this->session); - - $props = []; - - foreach ((array)$this as $prop => $value) { - if ($prop !== "\0*\0configData" - && $prop !== "\0*\0dic" - && $prop !== "\0*\0session") { - $props[] = $prop; - } - } - - return $props; - } -} \ No newline at end of file diff --git a/lib/SP/Account/AccountUtil.php b/lib/SP/Account/AccountUtil.php index c9dc8d60..262e1e43 100644 --- a/lib/SP/Account/AccountUtil.php +++ b/lib/SP/Account/AccountUtil.php @@ -53,13 +53,13 @@ class AccountUtil public static function getAccountRequestData($id) { $query = /** @lang SQL */ - 'SELECT account_userId, - account_userEditId, - account_name, - customer_name - FROM accounts - LEFT JOIN customers ON account_customerId = customer_id - WHERE account_id = ? LIMIT 1'; + 'SELECT A.userId, + A.userEditId, + A.name, + C.name AS clientName + FROM Account A + LEFT JOIN Client C ON A.clientId = C.id + WHERE A.id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); @@ -83,10 +83,10 @@ class AccountUtil public static function getAccountUsersName($accountId) { $query = /** @lang SQL */ - 'SELECT user_name - FROM accUsers - JOIN usrData ON accuser_userId = user_id - WHERE accuser_accountId = ?'; + 'SELECT U.name + FROM AccountToUser AU + INNER JOIN User U ON AU.userId = U.id + WHERE AU.accountId = ?'; $Data = new QueryData(); $Data->setQuery($query); @@ -125,7 +125,7 @@ class AccountUtil account_pass, account_key, account_notes - FROM accounts'; + FROM Account'; $Data = new QueryData(); $Data->setQuery($query); @@ -146,7 +146,7 @@ class AccountUtil public static function getAccountNameById($accountId) { $query = /** @lang SQL */ - 'SELECT account_name FROM accounts WHERE account_id = ? LIMIT 1'; + 'SELECT account_name FROM Account WHERE account_id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); @@ -167,7 +167,7 @@ class AccountUtil public static function getAccountNameByIdBatch(array $ids) { $query = /** @lang SQL */ - 'SELECT account_name FROM accounts WHERE account_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')'; + 'SELECT account_name FROM Account WHERE account_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')'; $Data = new QueryData(); $Data->setQuery($query); @@ -185,12 +185,12 @@ class AccountUtil public static function getAccountsMgmtSearch(ItemSearchData $SearchData) { $Data = new QueryData(); - $Data->setSelect('account_id, account_name, customer_name'); - $Data->setFrom('accounts LEFT JOIN customers ON account_customerId = customer_id'); + $Data->setSelect('account_id, account_name, name'); + $Data->setFrom('accounts LEFT JOIN customers ON account_customerId = id'); $Data->setOrder('account_name'); if ($SearchData->getSeachString() !== '') { - $Data->setWhere('account_name LIKE ? OR customer_name LIKE ?'); + $Data->setWhere('account_name LIKE ? OR name LIKE ?'); $search = '%' . $SearchData->getSeachString() . '%'; $Data->addParam($search); @@ -227,14 +227,14 @@ class AccountUtil $queryWhere = self::getAccountFilterUser($Data, $session); - $queryWhere[] = 'account_parentId = ?'; + $queryWhere[] = 'A.parentId = ?'; $Data->addParam($accountId); $query = /** @lang SQL */ - 'SELECT account_id, account_name, customer_name - FROM accounts - LEFT JOIN customers ON customer_id = account_customerId - WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY customer_name'; + 'SELECT A.id, A.name, C.name AS clientName + FROM Account A + INNER JOIN Client C ON Account.clientId = C.id + WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY name'; $Data->setQuery($query); @@ -254,41 +254,41 @@ class AccountUtil $configData = $session->getConfig(); $userData = $session->getUserData(); - if (!$userData->isUserIsAdminApp() - && !$userData->isUserIsAdminAcc() + if (!$userData->getIsAdminApp() + && !$userData->getIsAdminAcc() && !($useGlobalSearch && $session->getUserProfile()->isAccGlobalSearch() && $configData->isGlobalSearch()) ) { // Filtro usuario y grupo - $filterUser[] = 'account_userId = ?'; - $Data->addParam($userData->getUserId()); + $filterUser[] = 'userId = ?'; + $Data->addParam($userData->getId()); - $filterUser[] = 'account_userGroupId = ?'; + $filterUser[] = 'userGroupId = ?'; $Data->addParam($userData->getUserGroupId()); // Filtro de cuenta en usuarios y grupos secundarios $filterUser[] = /** @lang SQL */ - 'account_id IN (SELECT accuser_accountId AS accountId FROM accUsers WHERE accuser_accountId = account_id AND accuser_userId = ? UNION ALL SELECT accgroup_accountId AS accountId FROM accGroups WHERE accgroup_accountId = account_id AND accgroup_groupId = ?)'; - $Data->addParam($userData->getUserId()); + 'A.id IN (SELECT accountId AS accountId FROM AccountToUser WHERE accountId = A.id AND userId = ? UNION ALL SELECT accountId FROM AccountToUserGroup WHERE accountId = A.id AND userGroupId = ?)'; + $Data->addParam($userData->getId()); $Data->addParam($userData->getUserGroupId()); // Filtro de grupo principal de cuenta en grupos que incluyen al usuario $filterUser[] = /** @lang SQL */ - 'account_userGroupId IN (SELECT usertogroup_groupId FROM usrToGroups WHERE usertogroup_groupId = account_userGroupId AND usertogroup_userId = ?)'; - $Data->addParam($userData->getUserId()); + 'A.userGroupId IN (SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = Account.userGroupId AND userId = ?)'; + $Data->addParam($userData->getId()); if ($configData->isAccountFullGroupAccess()) { // Filtro de grupos secundarios en grupos que incluyen al usuario $filterUser[] = /** @lang SQL */ - 'account_id = (SELECT accgroup_accountId AS accountId FROM accGroups INNER JOIN usrToGroups ON usertogroup_groupId = accgroup_groupId WHERE accgroup_accountId = account_id AND usertogroup_userId = ? LIMIT 1)'; - $Data->addParam($userData->getUserId()); + 'A.id = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = A.id AND uug.userId = ? LIMIT 1)'; + $Data->addParam($userData->getId()); } $queryWhere[] = '(' . implode(' OR ', $filterUser) . ')'; } - $queryWhere[] = '(account_isPrivate = 0 OR (account_isPrivate = 1 AND account_userId = ?))'; - $Data->addParam($userData->getUserId()); - $queryWhere[] = '(account_isPrivateGroup = 0 OR (account_isPrivateGroup = 1 AND account_userGroupId = ?))'; + $queryWhere[] = '(isPrivate = 0 OR (isPrivate = 1 AND userId = ?))'; + $Data->addParam($userData->getId()); + $queryWhere[] = '(isPrivateGroup = 0 OR (isPrivateGroup = 1 AND userGroupId = ?))'; $Data->addParam($userData->getUserGroupId()); return $queryWhere; @@ -307,41 +307,41 @@ class AccountUtil $configData = $session->getConfig(); $userData = $session->getUserData(); - if (!$userData->isUserIsAdminApp() - && !$userData->isUserIsAdminAcc() + if (!$userData->getIsAdminApp() + && !$userData->getIsAdminAcc() && !($useGlobalSearch && $session->getUserProfile()->isAccGlobalSearch() && $configData->isGlobalSearch()) ) { // Filtro usuario y grupo - $filterUser[] = 'acchistory_userId = ?'; - $Data->addParam($userData->getUserId()); + $filterUser[] = 'AH.userId = ?'; + $Data->addParam($userData->getId()); - $filterUser[] = 'acchistory_userGroupId = ?'; + $filterUser[] = 'AH.userGroupId = ?'; $Data->addParam($userData->getUserGroupId()); // Filtro de cuenta en usuarios y grupos secundarios $filterUser[] = /** @lang SQL */ - 'acchistory_accountId IN (SELECT accuser_accountId AS accountId FROM accUsers WHERE accuser_accountId = account_id AND accuser_userId = ? UNION ALL SELECT accgroup_accountId AS accountId FROM accGroups WHERE accgroup_accountId = account_id AND accgroup_groupId = ?)'; - $Data->addParam($userData->getUserId()); + 'AH.accountId IN (SELECT accountId FROM AccountToUser WHERE accountId = AH.accountId AND userId = ? UNION ALL SELECT accountId FROM AccountToUserGroup WHERE accountId = account_id AND AH.accountId = ?)'; + $Data->addParam($userData->getId()); $Data->addParam($userData->getUserGroupId()); // Filtro de grupo principal de cuenta en grupos que incluyen al usuario $filterUser[] = /** @lang SQL */ - 'acchistory_userGroupId IN (SELECT usertogroup_groupId FROM usrToGroups WHERE usertogroup_groupId = account_userGroupId AND usertogroup_userId = ?)'; - $Data->addParam($userData->getUserId()); + 'AH.userGroupId IN (SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = AH.userGroupId AND userId = ?)'; + $Data->addParam($userData->getId()); if ($configData->isAccountFullGroupAccess()) { // Filtro de grupos secundarios en grupos que incluyen al usuario $filterUser[] = /** @lang SQL */ - 'acchistory_accountId = (SELECT accgroup_accountId AS accountId FROM accGroups INNER JOIN usrToGroups ON usertogroup_groupId = accgroup_groupId WHERE accgroup_accountId = account_id AND usertogroup_userId = ? LIMIT 1)'; - $Data->addParam($userData->getUserId()); + 'AH.accountId = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = AH.accountId AND uug.userId = ? LIMIT 1)'; + $Data->addParam($userData->getId()); } $queryWhere[] = '(' . implode(' OR ', $filterUser) . ')'; } - $queryWhere[] = '(acchistory_isPrivate = 0 OR (acchistory_isPrivate = 1 AND acchistory_userId = ?))'; - $Data->addParam($userData->getUserId()); - $queryWhere[] = '(acchistory_isPrivateGroup = 0 OR (acchistory_isPrivateGroup = 1 AND acchistory_userGroupId = ?))'; + $queryWhere[] = '(AH.isPrivate = 0 OR (AH.isPrivate = 1 AND AH.userId = ?))'; + $Data->addParam($userData->getId()); + $queryWhere[] = '(AH.isPrivateGroup = 0 OR (AH.isPrivateGroup = 1 AND AH.userGroupId = ?))'; $Data->addParam($userData->getUserGroupId()); return $queryWhere; @@ -361,15 +361,15 @@ class AccountUtil $queryWhere = self::getAccountFilterUser($Data, $session); if (null !== $accountId) { - $queryWhere[] = 'account_id <> ? AND (account_parentId = 0 OR account_parentId IS NULL)'; + $queryWhere[] = 'A.id <> ? AND (A.parentId = 0 OR A.parentId IS NULL)'; $Data->addParam($accountId); } $query = /** @lang SQL */ - 'SELECT account_id, account_name, customer_name - FROM accounts - LEFT JOIN customers ON customer_id = account_customerId - WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY customer_name'; + 'SELECT A.id, A.name, C.name AS clientName + FROM Account A + LEFT JOIN Client C ON A.clientId = C.id + WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY name'; $Data->setQuery($query); @@ -384,7 +384,7 @@ class AccountUtil public static function getTotalNumAccounts() { $query = /** @lang SQL */ - 'SELECT SUM(n) AS num FROM (SELECT COUNT(*) AS n FROM accounts UNION SELECT COUNT(*) AS n FROM accHistory) a'; + '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); diff --git a/lib/SP/Auth/Browser/BrowserAuthData.php b/lib/SP/Auth/Browser/BrowserAuthData.php deleted file mode 100644 index 3eeb1970..00000000 --- a/lib/SP/Auth/Browser/BrowserAuthData.php +++ /dev/null @@ -1,37 +0,0 @@ -. - */ - -namespace SP\Auth\Browser; - -use SP\Auth\AuthDataBase; - -/** - * Class BrowserAuthData - * - * @package SP\Auth\Browser - */ -class BrowserAuthData extends AuthDataBase -{ - -} \ No newline at end of file diff --git a/lib/SP/Auth/Ldap/LdapInterface.php b/lib/SP/Auth/Ldap/LdapInterface.php deleted file mode 100644 index 0eaa35db..00000000 --- a/lib/SP/Auth/Ldap/LdapInterface.php +++ /dev/null @@ -1,55 +0,0 @@ -. - */ - -namespace SP\Auth\Ldap; - -/** - * Interface LdapInterface - * - * @package Auth\Ldap - */ -interface LdapInterface -{ - /** - * Comprobar la conexión al servidor de LDAP. - * - * @return bool - */ - public function checkConnection(); - - - /** - * Comprobar si los parámetros necesarios de LDAP están establecidos. - * - * @return bool - */ - public function checkParams(); - - /** - * Obtener los atributos del usuario. - * - * @return LdapAuthData - */ - public function getAttributes(); -} \ No newline at end of file diff --git a/lib/SP/Auth/Ldap/LdapMsAds.php b/lib/SP/Auth/Ldap/LdapMsAds.php deleted file mode 100644 index 43cb8f9f..00000000 --- a/lib/SP/Auth/Ldap/LdapMsAds.php +++ /dev/null @@ -1,177 +0,0 @@ -. - */ - -namespace SP\Auth\Ldap; - -use SP\Config\Config; -use SP\Core\Exceptions\SPException; -use SP\Log\Log; - -/** - * Class LdapAds - * - * Autentificación basada en Active Directory - * - * @package SP\Auth\Ldap - */ -class LdapMsAds extends LdapBase -{ - - /** - * Devolver el filtro para comprobar la pertenecia al grupo - * - * @return mixed - * @throws \SP\Core\Exceptions\SPException - */ - protected function getGroupDnFilter() - { - if (empty($this->group)) { - return '(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject))'; - } - - $groupDN = ldap_escape($this->searchGroupDN()); - - return '(&(|(memberOf=' . $groupDN . ')(groupMembership=' . $groupDN . ')(memberof:1.2.840.113556.1.4.1941:=' . $groupDN . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))'; - } - - /** - * Obtener el servidor de LDAP a utilizar - * - * @return mixed - */ - protected function pickServer() - { - $server = $this->ConfigData->getLdapServer(); - - if (preg_match('/[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}/', $server)) { - return $server; - } - - $serverDomain = ''; - $serverFQDN = explode('.', $server); - - for ($i = 1; $i <= count($serverFQDN) - 1; $i++) { - $serverDomain .= $serverFQDN[$i] . '.'; - } - - $dnsServerQuery = '_msdcs.' . $serverDomain; - $records = dns_get_record($dnsServerQuery, DNS_NS); - - if (count($records) === 0) { - return $server; - } - - $ads = []; - - foreach ($records as $record) { - $ads[] = $record['target']; - }; - - $nAds = count($ads); - - return $nAds > 0 ? $ads[mt_rand(0, $nAds)] : $server; - } - - /** - * Obtener el filtro para buscar el usuario - * - * @return mixed - */ - protected function getUserDnFilter() - { - $userLogin = ldap_escape($this->userLogin); - - return '(&(|(samaccountname=' . $userLogin . ')(cn=' . $userLogin . ')(uid=' . $userLogin . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject))(objectCategory=person))'; - } - - /** - * Buscar al usuario en un grupo. - * - * @throws SPException - * @return bool - */ - protected function searchUserInGroup() - { - $this->LogMessage->setAction(__FUNCTION__); - - // Comprobar si está establecido el filtro de grupo o el grupo coincide con - // los grupos del usuario - if (!$this->group - || $this->group === '*' - || in_array($this->LdapAuthData->getGroupDn(), $this->LdapAuthData->getGroups()) - ) { - $this->LogMessage->addDescription(__('Usuario verificado en grupo', false)); - $this->writeLog(Log::INFO); - - return true; - } - - $groupDN = $this->LdapAuthData->getGroupDn(); - $filter = '(memberof:1.2.840.113556.1.4.1941:=' . ldap_escape($groupDN) . ')'; - - $searchResults = $this->getResults($filter, ['sAMAccountName']); - - if ($searchResults === false) { - $this->LogMessage->addDescription(__('Error al buscar el grupo de usuarios', false)); - $this->LogMessage->addDetails(__('Grupo', false), $groupDN); - $this->LogMessage->addDetails('LDAP ERROR', sprintf('%s (%d)', ldap_error($this->ldapHandler), ldap_errno($this->ldapHandler))); - $this->LogMessage->addDetails('LDAP FILTER', $filter); - $this->writeLog(); - - throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription()); - } - - foreach ($searchResults as $entry) { - if (is_array($entry)) { - if ($this->userLogin === strtolower($entry['samaccountname'][0])) { - $this->LogMessage->addDescription(__('Usuario verificado en grupo', false)); - $this->LogMessage->addDetails(__('Grupo', false), $groupDN); - $this->writeLog(Log::INFO); - - return true; - } - } - } - - $this->LogMessage->addDescription(__('Usuario no pertenece al grupo', false)); - $this->LogMessage->addDetails(__('Usuario', false), $this->LdapAuthData->getDn()); - $this->LogMessage->addDetails(__('Grupo', false), $groupDN); - $this->writeLog(); - - return false; - } - - /** - * @return bool - * @throws \SP\Core\Exceptions\SPException - */ - protected function connect() - { - parent::connect(); - - @ldap_set_option($this->ldapHandler, LDAP_OPT_REFERRALS, 0); - - return true; - } -} \ No newline at end of file diff --git a/lib/SP/Config/Config.php b/lib/SP/Config/Config.php index 55510269..18b860b8 100644 --- a/lib/SP/Config/Config.php +++ b/lib/SP/Config/Config.php @@ -164,7 +164,7 @@ class Config { $ConfigData = null === $Config ? $this->configData : $Config; $ConfigData->setConfigDate(time()); - $ConfigData->setConfigSaver($this->session->getUserData()->getUserLogin()); + $ConfigData->setConfigSaver($this->session->getUserData()->getLogin()); $ConfigData->setConfigHash(); $this->fileStorage->setItems($ConfigData); diff --git a/lib/SP/Controller/Grids/Items.php b/lib/SP/Controller/Grids/Items.php index 50675527..31a0e3c7 100644 --- a/lib/SP/Controller/Grids/Items.php +++ b/lib/SP/Controller/Grids/Items.php @@ -58,9 +58,9 @@ class Items extends GridBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('category_id'); - $GridData->addDataRowSource('category_name'); - $GridData->addDataRowSource('category_description'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('description'); // Grid $Grid = new DataGridTab(); @@ -132,9 +132,9 @@ class Items extends GridBase // Grid Data $GridData = new DataGridData(); - $GridData->setDataRowSourceId('customer_id'); - $GridData->addDataRowSource('customer_name'); - $GridData->addDataRowSource('customer_description'); + $GridData->setDataRowSourceId('id'); + $GridData->addDataRowSource('name'); + $GridData->addDataRowSource('description'); // Grid $Grid = new DataGridTab(); @@ -287,7 +287,7 @@ class Items extends GridBase $GridData = new DataGridData(); $GridData->setDataRowSourceId('accfile_id'); $GridData->addDataRowSource('account_name'); - $GridData->addDataRowSource('customer_name'); + $GridData->addDataRowSource('name'); $GridData->addDataRowSource('accfile_name'); $GridData->addDataRowSource('accfile_type'); $GridData->addDataRowSource('accfile_size'); @@ -353,7 +353,7 @@ class Items extends GridBase $GridData = new DataGridData(); $GridData->setDataRowSourceId('account_id'); $GridData->addDataRowSource('account_name'); - $GridData->addDataRowSource('customer_name'); + $GridData->addDataRowSource('name'); // Grid $Grid = new DataGridTab(); @@ -411,7 +411,7 @@ class Items extends GridBase $GridData = new DataGridData(); $GridData->setDataRowSourceId('acchistory_id'); $GridData->addDataRowSource('acchistory_name'); - $GridData->addDataRowSource('customer_name'); + $GridData->addDataRowSource('name'); $GridData->addDataRowSource('acchistory_date'); $GridData->addDataRowSourceWithIcon('acchistory_isModify', $iconEdit->setTitle(__('Modificada'))->setClass('opacity50')); $GridData->addDataRowSourceWithIcon('acchistory_isDeleted', $iconDelete->setTitle(__('Eliminada'))->setClass('opacity50')); @@ -752,7 +752,7 @@ class Items extends GridBase $GridData = new DataGridData(); $GridData->setDataRowSourceId('authtoken_id'); $GridData->addDataRowSource('user_login'); - $GridData->addDataRowSource('authtoken_actionId'); + $GridData->addDataRowSource('actionId'); // Grid $Grid = new DataGridTab(); diff --git a/lib/SP/Controller/WikiController.php b/lib/SP/Controller/WikiController.php index faa6cdb8..9484b8e4 100644 --- a/lib/SP/Controller/WikiController.php +++ b/lib/SP/Controller/WikiController.php @@ -58,8 +58,8 @@ class WikiController extends ControllerBase implements ActionsInterface $this->init(); $this->view->assign('sk', SessionUtil::getSessionKey(true)); - $this->view->assign('isDemoMode', $this->configData->isDemoEnabled() && !SessionFactory::getUserData()->isUserIsAdminApp()); - $this->view->assign('isDisabled', ($this->configData->isDemoEnabled() && !SessionFactory::getUserData()->isUserIsAdminApp()) ? 'DISABLED' : ''); + $this->view->assign('isDemoMode', $this->configData->isDemoEnabled() && !SessionFactory::getUserData()->isIsAdminApp()); + $this->view->assign('isDisabled', ($this->configData->isDemoEnabled() && !SessionFactory::getUserData()->isIsAdminApp()) ? 'DISABLED' : ''); } /** diff --git a/lib/SP/Core/Dic/DicInterface.php b/lib/SP/Core/Dic/DicInterface.php index eac904ef..b48e6fd0 100644 --- a/lib/SP/Core/Dic/DicInterface.php +++ b/lib/SP/Core/Dic/DicInterface.php @@ -38,7 +38,6 @@ interface DicInterface extends ContainerInterface * * @param string $name * @param callable $callable - * @return */ public function share($name, $callable = null); diff --git a/lib/SP/Core/Init.php b/lib/SP/Core/Init.php index 720355b9..ab299d67 100644 --- a/lib/SP/Core/Init.php +++ b/lib/SP/Core/Init.php @@ -26,7 +26,7 @@ namespace SP\Core; use Defuse\Crypto\Exception\CryptoException; use SP\Account\AccountAcl; -use SP\Auth\Browser\Browser; +use SP\Providers\Auth\Browser\Browser; use SP\Config\Config; use SP\Modules\Web\Controllers\MainController; use SP\Core\Crypt\CryptSessionHandler; @@ -213,8 +213,8 @@ class Init $AuthBrowser = new Browser(); // Comprobar si se ha identificado mediante el servidor web y el usuario coincide - if ($AuthBrowser->checkServerAuthUser(SessionFactory::getUserData()->getUserLogin()) === false - && $AuthBrowser->checkServerAuthUser(SessionFactory::getUserData()->getUserSsoLogin()) === false + if ($AuthBrowser->checkServerAuthUser(SessionFactory::getUserData()->getLogin()) === false + && $AuthBrowser->checkServerAuthUser(SessionFactory::getUserData()->getSsoLogin()) === false ) { self::goLogout(); } @@ -566,7 +566,7 @@ class Init || Checks::isAjax() || Request::analyze('nodbupgrade', 0) === 1 || (Request::analyze('a') === 'upgrade' && Request::analyze('type') !== '') - || (self::$LOCK > 0 && Util::isLoggedIn() && self::$LOCK === SessionFactory::getUserData()->getUserId()) + || (self::$LOCK > 0 && Util::isLoggedIn() && self::$LOCK === SessionFactory::getUserData()->getId()) ) { return true; } @@ -613,7 +613,7 @@ class Init $Log = new Log(); $LogMessage = $Log->getLogMessage(); $LogMessage->setAction(__('Finalizar sesión', false)); - $LogMessage->addDetails(__('Usuario', false), SessionFactory::getUserData()->getUserLogin()); + $LogMessage->addDetails(__('Usuario', false), SessionFactory::getUserData()->getLogin()); $LogMessage->addDetails(__('Tiempo inactivo', false), $inactiveTime . ' min.'); $LogMessage->addDetails(__('Tiempo total', false), $totalTime . ' min.'); $Log->writeLog(); @@ -673,7 +673,7 @@ class Init SessionFactory::setStartActivity(time()); } else if (!$inMaintenance && time() - $sidStartTime > 120 - && SessionFactory::getUserData()->getUserId() > 0 + && SessionFactory::getUserData()->getId() > 0 ) { try { CryptSession::reKey(); diff --git a/lib/SP/Core/Language.php b/lib/SP/Core/Language.php index 4185f991..2c2cb584 100644 --- a/lib/SP/Core/Language.php +++ b/lib/SP/Core/Language.php @@ -121,7 +121,9 @@ class Language */ private function getUserLang() { - return ($this->session->getUserData()->getUserId() > 0) ? $this->session->getUserPreferences()->getLang() : ''; + $userData = $this->session->getUserData(); + + return ($userData->getId() > 0) ? $userData->getPreferences()->getLang() : ''; } /** diff --git a/lib/SP/Core/Plugin/PluginUtil.php b/lib/SP/Core/Plugin/PluginUtil.php index 387ff7ab..5a3a82e6 100644 --- a/lib/SP/Core/Plugin/PluginUtil.php +++ b/lib/SP/Core/Plugin/PluginUtil.php @@ -186,13 +186,13 @@ class PluginUtil public static function checkEnabledPlugins() { $PluginData = new PluginData(); - $PluginData->setPluginAvailable(false); - $PluginData->setPluginEnabled(false); + $PluginData->setAvailable(false); + $PluginData->setEnabled(false); foreach (self::getEnabledPlugins() as $plugin) { if (!in_array($plugin, self::$loadedPlugins)) { $PluginClone = clone $PluginData; - $PluginClone->setPluginName($plugin); + $PluginClone->setName($plugin); Plugin::getItem($PluginClone)->toggleAvaliableByName(); } diff --git a/lib/SP/Core/Session/Session.php b/lib/SP/Core/Session/Session.php index 710a6a3b..232bc564 100644 --- a/lib/SP/Core/Session/Session.php +++ b/lib/SP/Core/Session/Session.php @@ -25,12 +25,10 @@ namespace SP\Core\Session; use SP\Account\AccountAcl; -use SP\Account\AccountSearch; +use SP\Account\AccountSearchFilter; use SP\Config\ConfigData; use SP\DataModel\ProfileData; -use SP\DataModel\UserData; -use SP\DataModel\UserPreferencesData; -use SP\Mgmt\Users\UserPreferences; +use SP\Services\User\UserLoginResponse; /** * Class Session @@ -129,11 +127,11 @@ class Session /** * Establece los datos del usuario en la sesión. * - * @param UserData $UserData + * @param UserLoginResponse $userLoginResponse */ - public function setUserData(UserData $UserData = null) + public function setUserData(UserLoginResponse $userLoginResponse = null) { - $this->setSessionKey('userData', $UserData); + $this->setSessionKey('userData', $userLoginResponse); } /** @@ -143,7 +141,7 @@ class Session */ public function getUserProfile() { - return $this->getSessionKey('usrprofile'); + return $this->getSessionKey('userProfile'); } /** @@ -153,35 +151,25 @@ class Session */ public function setUserProfile(ProfileData $ProfileData) { - $this->setSessionKey('usrprofile', $ProfileData); + $this->setSessionKey('userProfile', $ProfileData); } /** - * @return AccountSearch + * @return AccountSearchFilter */ public function getSearchFilters() { - return $this->getSessionKey('searchFilters', new AccountSearch()); + return $this->getSessionKey('searchFilters', null); } /** - * @param AccountSearch $searchFilters + * @param AccountSearchFilter $searchFilters */ - public function setSearchFilters(AccountSearch $searchFilters) + public function setSearchFilters(AccountSearchFilter $searchFilters) { $this->setSessionKey('searchFilters', $searchFilters); } - /** - * Establece el objeto de preferencias de usuario en la sesión. - * - * @param UserPreferencesData|UserPreferences $preferences - */ - public function setUserPreferences(UserPreferencesData $preferences) - { - $this->setSessionKey('userpreferences', $preferences); - } - /** * Establecer la ACL de una cuenta * @@ -215,28 +203,20 @@ class Session */ public function isLoggedIn() { - return $this->getUserData()->getUserLogin() - && is_object($this->getUserPreferences()); + $userData = $this->getUserData(); + + return $userData->getLogin() + && is_object($userData->getPreferences()); } /** * Devuelve los datos del usuario en la sesión. * - * @return UserData + * @return UserLoginResponse */ public function getUserData() { - return $this->getSessionKey('userData', new UserData()); - } - - /** - * Obtiene el objeto de preferencias de usuario de la sesión. - * - * @return UserPreferencesData - */ - public function getUserPreferences() - { - return $this->getSessionKey('userpreferences'); + return $this->getSessionKey('userData', new UserLoginResponse()); } /** @@ -256,4 +236,24 @@ class Session { return $this->getSessionKey('authCompleted', false); } + + /** + * Devolver la clave maestra temporal + * + * @return string + */ + public function getTemporaryMasterPass() + { + return $this->getSessionKey('tempmasterpass'); + } + + /** + * Establece la clave maestra temporal + * + * @param string $password + */ + public function setTemporaryMasterPass($password) + { + $this->setSessionKey('tempmasterpass', $password); + } } \ No newline at end of file diff --git a/lib/SP/Core/Upgrade/Check.php b/lib/SP/Core/Upgrade/Check.php index 22d88244..4be69061 100644 --- a/lib/SP/Core/Upgrade/Check.php +++ b/lib/SP/Core/Upgrade/Check.php @@ -42,18 +42,18 @@ class Check { $query = /** @lang SQL */ 'SELECT * FROM - (SELECT COUNT(*) AS accounts_user FROM accounts WHERE account_userId NOT IN (SELECT user_id FROM usrData) OR account_userId IS NULL) au, - (SELECT COUNT(*) AS accounts_group FROM accounts WHERE account_userGroupId NOT IN (SELECT usergroup_id FROM usrGroups) OR account_userGroupId IS NULL) ag, - (SELECT COUNT(*) AS accounts_useredit FROM accounts WHERE account_userEditId NOT IN (SELECT user_id FROM usrData) OR account_userEditId IS NULL) b, - (SELECT COUNT(*) AS accounts_category FROM accounts WHERE account_categoryId NOT IN (SELECT category_id FROM categories) OR account_categoryId IS NULL) c, - (SELECT COUNT(*) AS accounts_customer FROM accounts WHERE account_customerId NOT IN (SELECT customer_id FROM customers) OR account_customerId IS NULL) d, + (SELECT COUNT(*) AS accounts_user FROM Account WHERE account_userId NOT IN (SELECT user_id FROM usrData) OR account_userId IS NULL) au, + (SELECT COUNT(*) AS accounts_group FROM Account WHERE account_userGroupId NOT IN (SELECT usergroup_id FROM usrGroups) OR account_userGroupId IS NULL) ag, + (SELECT COUNT(*) AS accounts_useredit FROM Account WHERE account_userEditId NOT IN (SELECT user_id FROM usrData) OR account_userEditId IS NULL) b, + (SELECT COUNT(*) AS accounts_category FROM Account WHERE account_categoryId NOT IN (SELECT id FROM Category) OR account_categoryId IS NULL) c, + (SELECT COUNT(*) AS accounts_customer FROM Account WHERE account_customerId NOT IN (SELECT id FROM customers) OR account_customerId IS NULL) d, (SELECT COUNT(*) AS accountshistory_user FROM accHistory WHERE acchistory_userId NOT IN (SELECT user_id FROM usrData) OR acchistory_userId IS NULL) eu, (SELECT COUNT(*) AS accountshistory_group FROM accHistory WHERE acchistory_userGroupId NOT IN (SELECT usergroup_id FROM usrGroups) OR acchistory_userGroupId IS NULL) eg, (SELECT COUNT(*) AS accountshistory_useredit FROM accHistory WHERE acchistory_userEditId NOT IN (SELECT user_id FROM usrData) OR acchistory_userEditId IS NULL) f, - (SELECT COUNT(*) AS accountshistory_category FROM accHistory WHERE acchistory_categoryId NOT IN (SELECT category_id FROM categories) OR acchistory_categoryId IS NULL) g, - (SELECT COUNT(*) AS accountshistory_customer FROM accHistory WHERE acchistory_customerId NOT IN (SELECT customer_id FROM customers) OR acchistory_customerId IS NULL) h, + (SELECT COUNT(*) AS accountshistory_category FROM accHistory WHERE acchistory_categoryId NOT IN (SELECT id FROM Category) OR acchistory_categoryId IS NULL) g, + (SELECT COUNT(*) AS accountshistory_customer FROM accHistory WHERE acchistory_customerId NOT IN (SELECT id FROM customers) OR acchistory_customerId IS NULL) h, (SELECT COUNT(*) AS users_group FROM usrData WHERE user_groupId NOT IN (SELECT usergroup_id FROM usrGroups) OR user_groupId IS NULL) i, - (SELECT COUNT(*) AS users_profile FROM usrData WHERE user_profileId NOT IN (SELECT userprofile_id FROM usrProfiles) OR user_profileId IS NULL) j'; + (SELECT COUNT(*) AS users_profile FROM usrData WHERE user_profileId NOT IN (SELECT id FROM UserProfile) OR user_profileId IS NULL) j'; $Data = new QueryData(); $Data->setQuery($query); diff --git a/lib/SP/DataModel/AccountExtData.php b/lib/SP/DataModel/AccountExtData.php index 2916e3a1..8bb5c3cb 100644 --- a/lib/SP/DataModel/AccountExtData.php +++ b/lib/SP/DataModel/AccountExtData.php @@ -46,42 +46,42 @@ class AccountExtData extends AccountData /** * @var string */ - public $category_name = ''; + public $categoryName = ''; /** * @var string */ - public $customer_name = ''; + public $clientName = ''; /** * @var string */ - public $usergroup_name = ''; + public $userGroupName = ''; /** * @var string */ - public $user_name = ''; + public $userName = ''; /** * @var string */ - public $user_login = ''; + public $userLogin = ''; /** * @var string */ - public $user_editName = ''; + public $userEditName = ''; /** * @var string */ - public $user_editLogin = ''; + public $userEditLogin = ''; /** * @var string */ - public $publicLink_hash = ''; + public $publicLinkHash = ''; /** * @return string */ public function getUserEditName() { - return $this->user_editName; + return $this->userEditName; } /** @@ -89,7 +89,7 @@ class AccountExtData extends AccountData */ public function getUserEditLogin() { - return $this->user_editLogin; + return $this->userEditLogin; } /** @@ -97,7 +97,7 @@ class AccountExtData extends AccountData */ public function getPublicLinkHash() { - return $this->publicLink_hash; + return $this->publicLinkHash; } /** @@ -137,23 +137,23 @@ class AccountExtData extends AccountData */ public function getCategoryName() { - return $this->category_name; + return $this->categoryName; } /** * @return string */ - public function getCustomerName() + public function getClientName() { - return $this->customer_name; + return $this->clientName; } /** * @return string */ - public function getUsergroupName() + public function getUserGroupName() { - return $this->usergroup_name; + return $this->userGroupName; } /** @@ -161,7 +161,7 @@ class AccountExtData extends AccountData */ public function getUserName() { - return $this->user_name; + return $this->userName; } /** @@ -169,7 +169,7 @@ class AccountExtData extends AccountData */ public function getUserLogin() { - return $this->user_login; + return $this->userLogin; } /** diff --git a/lib/SP/DataModel/AccountToUserGroupData.php b/lib/SP/DataModel/AccountToUserGroupData.php new file mode 100644 index 00000000..418306dc --- /dev/null +++ b/lib/SP/DataModel/AccountToUserGroupData.php @@ -0,0 +1,104 @@ +. + */ + +namespace SP\DataModel; + +defined('APP_ROOT') || die(); + +/** + * Class GroupAccountsData + * + * @package SP\DataModel + */ +class AccountToUserGroupData extends DataModelBase +{ + /** + * @var int + */ + public $userGroupId = 0; + /** + * @var int + */ + public $accountId = 0; + /** + * @var array + */ + protected $groups = []; + + /** + * @return int + */ + public function getUserGroupId() + { + return $this->userGroupId; + } + + /** + * @param int $userGroupId + */ + public function setUserGroupId($userGroupId) + { + $this->userGroupId = $userGroupId; + } + + /** + * @return int + */ + public function getAccountId() + { + return $this->accountId; + } + + /** + * @param int $accountId + */ + public function setAccountId($accountId) + { + $this->accountId = $accountId; + } + + /** + * @return array + */ + public function getGroups() + { + return $this->groups; + } + + /** + * @param array $groups + */ + public function setGroups(array $groups) + { + $this->groups = $groups; + } + + /** + * @param int $group + */ + public function addGroup($group) + { + $this->groups[] = (int)$group; + } +} \ No newline at end of file diff --git a/lib/SP/DataModel/PluginData.php b/lib/SP/DataModel/PluginData.php index a5efc805..76b518d3 100644 --- a/lib/SP/DataModel/PluginData.php +++ b/lib/SP/DataModel/PluginData.php @@ -34,30 +34,30 @@ class PluginData extends DataModelBase implements DataModelInterface /** * @var int */ - public $plugin_id; + public $id; /** * @var string */ - public $plugin_name; + public $name; /** * @var string */ - public $plugin_data; + public $data; /** * @var int */ - public $plugin_enabled = 0; + public $enabled = 0; /** * @var int */ - public $plugin_available = 1; + public $available = 1; /** * @return int */ public function getId() { - return (int)$this->plugin_id; + return (int)$this->id; } /** @@ -65,86 +65,70 @@ class PluginData extends DataModelBase implements DataModelInterface */ public function getName() { - return $this->plugin_name; + return $this->name; } /** - * @return int + * @param int $id */ - public function getPluginId() + public function setId($id) { - return (int)$this->plugin_id; + $this->id = (int)$id; } /** - * @param int $plugin_id + * @param string $name */ - public function setPluginId($plugin_id) + public function setName($name) { - $this->plugin_id = (int)$plugin_id; + $this->name = $name; } /** * @return string */ - public function getPluginName() + public function getData() { - return $this->plugin_name; + return $this->data; } /** - * @param string $plugin_name + * @param string $data */ - public function setPluginName($plugin_name) + public function setData($data) { - $this->plugin_name = $plugin_name; - } - - /** - * @return string - */ - public function getPluginData() - { - return $this->plugin_data; - } - - /** - * @param string $plugin_data - */ - public function setPluginData($plugin_data) - { - $this->plugin_data = $plugin_data; + $this->data = $data; } /** * @return int */ - public function getPluginEnabled() + public function getEnabled() { - return (int)$this->plugin_enabled; + return (int)$this->enabled; } /** - * @param int $plugin_enabled + * @param int $enabled */ - public function setPluginEnabled($plugin_enabled) + public function setEnabled($enabled) { - $this->plugin_enabled = (int)$plugin_enabled; + $this->enabled = (int)$enabled; } /** * @return int */ - public function getPluginAvailable() + public function getAvailable() { - return (int)$this->plugin_available; + return (int)$this->available; } /** - * @param int $plugin_available + * @param int $available */ - public function setPluginAvailable($plugin_available) + public function setAvailable($available) { - $this->plugin_available = (int)$plugin_available; + $this->available = (int)$available; } } \ No newline at end of file diff --git a/lib/SP/DataModel/ProfileBaseData.php b/lib/SP/DataModel/ProfileBaseData.php deleted file mode 100644 index bca857e7..00000000 --- a/lib/SP/DataModel/ProfileBaseData.php +++ /dev/null @@ -1,112 +0,0 @@ -. - */ - -namespace SP\DataModel; - -defined('APP_ROOT') || die(); - -/** - * Class ProfileBaseData - * - * @package SP\DataModel - */ -class ProfileBaseData extends DataModelBase implements DataModelInterface -{ - /** - * @var int - */ - public $userprofile_id = 0; - /** - * @var string - */ - public $userprofile_name = ''; - /** - * @var ProfileData - */ - public $userprofile_profile; - - /** - * @return string - */ - public function getUserprofileName() - { - return $this->userprofile_name; - } - - /** - * @param string $userprofile_name - */ - public function setUserprofileName($userprofile_name) - { - $this->userprofile_name = $userprofile_name; - } - - /** - * @return int - */ - public function getUserprofileId() - { - return $this->userprofile_id; - } - - /** - * @param int $userprofile_id - */ - public function setUserprofileId($userprofile_id) - { - $this->userprofile_id = $userprofile_id; - } - - /** - * @return ProfileData - */ - public function getUserprofileProfile() - { - return $this->userprofile_profile; - } - - /** - * @param ProfileData $userprofile_profile - */ - public function setUserprofileProfile($userprofile_profile) - { - $this->userprofile_profile = $userprofile_profile; - } - - /** - * @return int - */ - public function getId() - { - return $this->userprofile_id; - } - - /** - * @return string - */ - public function getName() - { - return $this->userprofile_name; - } -} \ No newline at end of file diff --git a/lib/SP/DataModel/ProfileData.php b/lib/SP/DataModel/ProfileData.php index 774ac5e3..8d60b43b 100644 --- a/lib/SP/DataModel/ProfileData.php +++ b/lib/SP/DataModel/ProfileData.php @@ -31,7 +31,7 @@ defined('APP_ROOT') || die(); * * @package SP\DataModel */ -class ProfileData extends ProfileBaseData +class ProfileData extends UserProfileData { /** * @var bool diff --git a/lib/SP/DataModel/PublicLinkData.php b/lib/SP/DataModel/PublicLinkData.php index 8bf1f60a..e6cfa8de 100644 --- a/lib/SP/DataModel/PublicLinkData.php +++ b/lib/SP/DataModel/PublicLinkData.php @@ -36,118 +36,70 @@ class PublicLinkData extends DataModelBase implements DataModelInterface /** * @var int */ - public $publicLink_id = 0; + public $id = 0; /** * @var int */ - public $publicLink_itemId = 0; + public $itemId = 0; /** * @var string */ - public $publicLink_hash = ''; + public $hash = ''; /** * @var int */ - public $publicLink_userId = 0; + public $userId = 0; /** * @var int */ - public $publicLink_typeId = 0; + public $typeId = 0; /** * @var bool */ - public $publicLink_notify = false; + public $notify = false; /** * @var int */ - public $publicLink_dateAdd = 0; + public $dateAdd = 0; /** * @var int */ - public $publicLink_dateExpire = 0; + public $dateExpire = 0; /** * @var int */ - public $publicLink_countViews = 0; + public $countViews = 0; /** * @var int */ - public $publicLink_totalCountViews = 0; + public $totalCountViews = 0; /** * @var int */ - public $publicLink_maxCountViews = 0; + public $maxCountViews = 0; /** * @var array|string */ - public $publicLink_useInfo; + public $useInfo; /** * @var string */ - public $publicLink_data; + public $data; /** * @return string */ - public function getPublicLinkData() + public function getData() { - return $this->publicLink_data; + return $this->data; } /** - * @param string $publicLink_data + * @param string $data */ - public function setPublicLinkData($publicLink_data) + public function setData($data) { - $this->publicLink_data = $publicLink_data; - } - - /** - * @return int - */ - public function getPublicLinkId() - { - return (int)$this->publicLink_id; - } - - /** - * @param int $publicLink_id - */ - public function setPublicLinkId($publicLink_id) - { - $this->publicLink_id = (int)$publicLink_id; - } - - /** - * @return string - */ - public function getPublicLinkHash() - { - return $this->publicLink_hash; - } - - /** - * @param string $publicLink_hash - */ - public function setPublicLinkHash($publicLink_hash) - { - $this->publicLink_hash = $publicLink_hash; - } - - /** - * @return int - */ - public function getPublicLinkItemId() - { - return (int)$this->publicLink_itemId; - } - - /** - * @param int $publicLink_itemId - */ - public function setPublicLinkItemId($publicLink_itemId) - { - $this->publicLink_itemId = (int)$publicLink_itemId; + $this->data = $data; } /** @@ -155,111 +107,143 @@ class PublicLinkData extends DataModelBase implements DataModelInterface */ public function getId() { - return (int)$this->publicLink_id; + return (int)$this->id; + } + + /** + * @param int $id + */ + public function setId($id) + { + $this->id = (int)$id; } /** * @return string */ - public function getName() + public function getHash() { - return ''; + return $this->hash; + } + + /** + * @param string $hash + */ + public function setHash($hash) + { + $this->hash = $hash; } /** * @return int */ - public function getPublicLinkUserId() + public function getItemId() { - return (int)$this->publicLink_userId; + return (int)$this->itemId; } /** - * @param int $publicLink_userId + * @param int $itemId */ - public function setPublicLinkUserId($publicLink_userId) + public function setItemId($itemId) { - $this->publicLink_userId = (int)$publicLink_userId; + $this->itemId = (int)$itemId; } /** * @return int */ - public function getPublicLinkTypeId() + public function getUserId() { - return (int)$this->publicLink_typeId; + return (int)$this->userId; } /** - * @param int $publicLink_typeId + * @param int $userId */ - public function setPublicLinkTypeId($publicLink_typeId) + public function setUserId($userId) { - $this->publicLink_typeId = (int)$publicLink_typeId; + $this->userId = (int)$userId; + } + + /** + * @return int + */ + public function getTypeId() + { + return (int)$this->typeId; + } + + /** + * @param int $typeId + */ + public function setTypeId($typeId) + { + $this->typeId = (int)$typeId; } /** * @return boolean */ - public function isPublicLinkNotify() + public function isNotify() { - return (bool)$this->publicLink_notify; + return (bool)$this->notify; } /** - * @param boolean $publicLink_notify + * @param boolean $notify */ - public function setPublicLinkNotify($publicLink_notify) + public function setNotify($notify) { - $this->publicLink_notify = (bool)$publicLink_notify; + $this->notify = (bool)$notify; } /** * @return int */ - public function getPublicLinkDateAdd() + public function getDateAdd() { - return (int)$this->publicLink_dateAdd; + return (int)$this->dateAdd; } /** - * @param int $publicLink_dateAdd + * @param int $dateAdd */ - public function setPublicLinkDateAdd($publicLink_dateAdd) + public function setDateAdd($dateAdd) { - $this->publicLink_dateAdd = (int)$publicLink_dateAdd; + $this->dateAdd = (int)$dateAdd; } /** * @return int */ - public function getPublicLinkDateExpire() + public function getDateExpire() { - return (int)$this->publicLink_dateExpire; + return (int)$this->dateExpire; } /** - * @param int $publicLink_dateExpire + * @param int $dateExpire */ - public function setPublicLinkDateExpire($publicLink_dateExpire) + public function setDateExpire($dateExpire) { - $this->publicLink_dateExpire = (int)$publicLink_dateExpire; + $this->dateExpire = (int)$dateExpire; } /** * @return int */ - public function getPublicLinkCountViews() + public function getCountViews() { - return (int)$this->publicLink_countViews; + return (int)$this->countViews; } /** - * @param int $publicLink_countViews + * @param int $countViews */ - public function setPublicLinkCountViews($publicLink_countViews) + public function setCountViews($countViews) { - $this->publicLink_countViews = (int)$publicLink_countViews; + $this->countViews = (int)$countViews; } /** @@ -267,51 +251,51 @@ class PublicLinkData extends DataModelBase implements DataModelInterface */ public function addCountViews() { - return $this->publicLink_countViews++; + return $this->countViews++; } /** * @return int */ - public function getPublicLinkMaxCountViews() + public function getMaxCountViews() { - return (int)$this->publicLink_maxCountViews; + return (int)$this->maxCountViews; } /** - * @param int $publicLink_maxCountViews + * @param int $maxCountViews */ - public function setPublicLinkMaxCountViews($publicLink_maxCountViews) + public function setMaxCountViews($maxCountViews) { - $this->publicLink_maxCountViews = (int)$publicLink_maxCountViews; + $this->maxCountViews = (int)$maxCountViews; } /** * @return array */ - public function getPublicLinkUseInfo() + public function getUseInfo() { - if (is_string($this->publicLink_useInfo)) { - return unserialize($this->publicLink_useInfo); + if (is_string($this->useInfo)) { + return unserialize($this->useInfo); } - return (array)$this->publicLink_useInfo; + return (array)$this->useInfo; } /** - * @param array $publicLink_useInfo + * @param array $useInfo */ - public function setPublicLinkUseInfo(array $publicLink_useInfo) + public function setUseInfo(array $useInfo) { - $this->publicLink_useInfo = $publicLink_useInfo; + $this->useInfo = $useInfo; } /** * @return int */ - public function getPublicLinkTotalCountViews() + public function getTotalCountViews() { - return (int)$this->publicLink_totalCountViews; + return (int)$this->totalCountViews; } /** @@ -319,6 +303,14 @@ class PublicLinkData extends DataModelBase implements DataModelInterface */ public function addTotalCountViews() { - return $this->publicLink_totalCountViews++; + return $this->totalCountViews++; + } + + /** + * @return string + */ + public function getName() + { + // TODO: Implement getName() method. } } \ No newline at end of file diff --git a/lib/SP/DataModel/UserData.php b/lib/SP/DataModel/UserData.php index 89e6f4d3..42c0d833 100644 --- a/lib/SP/DataModel/UserData.php +++ b/lib/SP/DataModel/UserData.php @@ -36,190 +36,190 @@ class UserData extends UserPassData implements DataModelInterface /** * @var string */ - public $user_login = ''; + public $login = ''; /** * @var string */ - public $user_ssoLogin = ''; + public $ssoLogin = ''; /** * @var string */ - public $user_name = ''; + public $name = ''; /** * @var string */ - public $user_email = ''; + public $email = ''; /** * @var string */ - public $user_notes = ''; + public $notes = ''; /** * @var int */ - public $user_groupId = 0; + public $userGroupId = 0; /** * @var int */ - public $user_profileId = 0; + public $userProfileId = 0; /** * @var bool */ - public $user_isAdminApp = 0; + public $isAdminApp = 0; /** * @var bool */ - public $user_isAdminAcc = 0; + public $isAdminAcc = 0; /** * @var bool */ - public $user_isDisabled = 0; + public $isDisabled = 0; /** * @var bool */ - public $user_isChangePass = 0; + public $isChangePass = 0; /** * @var bool */ - public $user_isChangedPass = 0; + public $isChangedPass = 0; /** * @var bool */ - public $user_isLdap = 0; + public $isLdap = 0; /** * @var int */ - public $user_count = 0; + public $loginCount = 0; /** * @var string */ - public $user_lastLogin = ''; + public $lastLogin = ''; /** * @var string */ - public $user_lastUpdate = ''; + public $lastUpdate = ''; /** * @var bool */ - public $user_isMigrate = 0; + public $isMigrate = 0; /** * @var */ - public $user_preferences; + public $preferences; /** * @var string */ - public $usergroup_name = ''; + public $userGroupName = ''; /** * @return int */ - public function getUserCount() + public function getLoginCount() { - return (int)$this->user_count; + return (int)$this->loginCount; } /** - * @param int $user_count + * @param int $loginCount */ - public function setUserCount($user_count) + public function setLoginCount($loginCount) { - $this->user_count = (int)$user_count; + $this->loginCount = (int)$loginCount; } /** * @return string */ - public function getUserLastLogin() + public function getLastLogin() { - return $this->user_lastLogin; + return $this->lastLogin; } /** - * @param string $user_lastLogin + * @param string $lastLogin */ - public function setUserLastLogin($user_lastLogin) + public function setLastLogin($lastLogin) { - $this->user_lastLogin = $user_lastLogin; + $this->lastLogin = $lastLogin; } /** * @return string */ - public function getUserLastUpdate() + public function getLastUpdate() { - return $this->user_lastUpdate; + return $this->lastUpdate; } /** - * @param string $user_lastUpdate + * @param string $lastUpdate */ - public function setUserLastUpdate($user_lastUpdate) + public function setLastUpdate($lastUpdate) { - $this->user_lastUpdate = $user_lastUpdate; + $this->lastUpdate = $lastUpdate; } /** * @return boolean */ - public function isUserIsMigrate() + public function isIsMigrate() { - return (int)$this->user_isMigrate; + return (int)$this->isMigrate; } /** - * @param boolean $user_isMigrate + * @param boolean $isMigrate */ - public function setUserIsMigrate($user_isMigrate) + public function setIsMigrate($isMigrate) { - $this->user_isMigrate = (int)$user_isMigrate; + $this->isMigrate = (int)$isMigrate; } /** * @return mixed */ - public function getUserPreferences() + public function getPreferences() { - return $this->user_preferences; + return $this->preferences; } /** - * @param mixed $user_preferences + * @param mixed $preferences */ - public function setUserPreferences($user_preferences) + public function setPreferences($preferences) { - $this->user_preferences = $user_preferences; + $this->preferences = $preferences; } /** * @return string */ - public function getUserEmail() + public function getEmail() { - return $this->user_email; + return $this->email; } /** - * @param string $user_email + * @param string $email */ - public function setUserEmail($user_email) + public function setEmail($email) { - $this->user_email = $user_email; + $this->email = $email; } /** * @return string */ - public function getUserNotes() + public function getNotes() { - return $this->user_notes; + return $this->notes; } /** - * @param string $user_notes + * @param string $notes */ - public function setUserNotes($user_notes) + public function setNotes($notes) { - $this->user_notes = $user_notes; + $this->notes = $notes; } /** @@ -227,15 +227,15 @@ class UserData extends UserPassData implements DataModelInterface */ public function getUserGroupId() { - return (int)$this->user_groupId; + return (int)$this->userGroupId; } /** - * @param int $user_groupId + * @param int $userGroupId */ - public function setUserGroupId($user_groupId) + public function setUserGroupId($userGroupId) { - $this->user_groupId = (int)$user_groupId; + $this->userGroupId = (int)$userGroupId; } /** @@ -243,151 +243,111 @@ class UserData extends UserPassData implements DataModelInterface */ public function getUserProfileId() { - return (int)$this->user_profileId; + return (int)$this->userProfileId; } /** - * @param int $user_profileId + * @param int $userProfileId */ - public function setUserProfileId($user_profileId) + public function setUserProfileId($userProfileId) { - $this->user_profileId = (int)$user_profileId; + $this->userProfileId = (int)$userProfileId; } /** * @return boolean */ - public function isUserIsAdminApp() + public function isIsAdminApp() { - return (int)$this->user_isAdminApp; + return (int)$this->isAdminApp; } /** - * @param boolean $user_isAdminApp + * @param boolean $isAdminApp */ - public function setUserIsAdminApp($user_isAdminApp) + public function setIsAdminApp($isAdminApp) { - $this->user_isAdminApp = (int)$user_isAdminApp; + $this->isAdminApp = (int)$isAdminApp; } /** * @return boolean */ - public function isUserIsAdminAcc() + public function isIsAdminAcc() { - return (int)$this->user_isAdminAcc; + return (int)$this->isAdminAcc; } /** - * @param boolean $user_isAdminAcc + * @param boolean $isAdminAcc */ - public function setUserIsAdminAcc($user_isAdminAcc) + public function setIsAdminAcc($isAdminAcc) { - $this->user_isAdminAcc = (int)$user_isAdminAcc; + $this->isAdminAcc = (int)$isAdminAcc; } /** * @return boolean */ - public function isUserIsDisabled() + public function isIsDisabled() { - return (int)$this->user_isDisabled; + return (int)$this->isDisabled; } /** - * @param boolean $user_isDisabled + * @param boolean $isDisabled */ - public function setUserIsDisabled($user_isDisabled) + public function setIsDisabled($isDisabled) { - $this->user_isDisabled = (int)$user_isDisabled; + $this->isDisabled = (int)$isDisabled; } /** * @return boolean */ - public function isUserIsChangePass() + public function isIsChangePass() { - return (int)$this->user_isChangePass; + return (int)$this->isChangePass; } /** - * @param boolean $user_isChangePass + * @param boolean $isChangePass */ - public function setUserIsChangePass($user_isChangePass) + public function setIsChangePass($isChangePass) { - $this->user_isChangePass = (int)$user_isChangePass; + $this->isChangePass = (int)$isChangePass; } /** * @return boolean */ - public function isUserIsLdap() + public function isIsLdap() { - return (int)$this->user_isLdap; + return (int)$this->isLdap; } /** - * @param boolean $user_isLdap + * @param boolean $isLdap */ - public function setUserIsLdap($user_isLdap) + public function setIsLdap($isLdap) { - $this->user_isLdap = (int)$user_isLdap; + $this->isLdap = (int)$isLdap; } /** * @return string */ - public function getUserLogin() + public function getLogin() { - return $this->user_login; + return $this->login; } /** - * @param string $user_login + * @param string $login */ - public function setUserLogin($user_login) + public function setLogin($login) { - $this->user_login = $user_login; - } - - /** - * @return string - */ - public function getUserName() - { - return $this->user_name; - } - - /** - * @param string $user_name - */ - public function setUserName($user_name) - { - $this->user_name = $user_name; - } - - /** - * @return string - */ - public function getUsergroupName() - { - return $this->usergroup_name; - } - - /** - * @param string $usergroup_name - */ - public function setUsergroupName($usergroup_name) - { - $this->usergroup_name = $usergroup_name; - } - - /** - * @return int - */ - public function getId() - { - return (int)$this->user_id; + $this->login = $login; } /** @@ -395,38 +355,62 @@ class UserData extends UserPassData implements DataModelInterface */ public function getName() { - return $this->user_name; + return $this->name; } /** - * @return bool + * @param string $name */ - public function isUserIsChangedPass() + public function setName($name) { - return (int)$this->user_isChangedPass; - } - - /** - * @param bool $user_isChangedPass - */ - public function setUserIsChangedPass($user_isChangedPass) - { - $this->user_isChangedPass = (int)$user_isChangedPass; + $this->name = $name; } /** * @return string */ - public function getUserSsoLogin() + public function getUserGroupName() { - return $this->user_ssoLogin; + return $this->userGroupName; } /** - * @param string $user_ssoLogin + * @param string $userGroupName */ - public function setUserSsoLogin($user_ssoLogin) + public function setUserGroupName($userGroupName) { - $this->user_ssoLogin = $user_ssoLogin; + $this->userGroupName = $userGroupName; + } + + /** + * @return bool + */ + public function isIsChangedPass() + { + return (int)$this->isChangedPass; + } + + /** + * @param int $isChangedPass + */ + public function setIsChangedPass($isChangedPass) + { + $this->isChangedPass = (int)$isChangedPass; + } + + /** + * @return string + */ + public function getSsoLogin() + { + return $this->ssoLogin; + } + + /** + * @param string $ssoLogin + */ + public function setSsoLogin($ssoLogin) + { + $this->ssoLogin = $ssoLogin; } } \ No newline at end of file diff --git a/lib/SP/DataModel/UserPassRecoverData.php b/lib/SP/DataModel/UserPassRecoverData.php index 772737c2..ca4c74ed 100644 --- a/lib/SP/DataModel/UserPassRecoverData.php +++ b/lib/SP/DataModel/UserPassRecoverData.php @@ -34,82 +34,82 @@ class UserPassRecoverData extends DataModelBase /** * @var int */ - public $userpassr_userId = 0; + public $userId = 0; /** * @var string */ - public $userpassr_hash = ''; + public $hash = ''; /** * @var int */ - public $userpassr_date = 0; + public $date = 0; /** * @var bool */ - public $userpassr_used = 0; + public $used = 0; /** * @return int */ - public function getUserpassrUserId() + public function getUserId() { - return (int)$this->userpassr_userId; + return (int)$this->userId; } /** - * @param int $userpassr_userId + * @param int $userId */ - public function setUserpassrUserId($userpassr_userId) + public function setUserId($userId) { - $this->userpassr_userId = (int)$userpassr_userId; + $this->userId = (int)$userId; } /** * @return string */ - public function getUserpassrHash() + public function getHash() { - return $this->userpassr_hash; + return $this->hash; } /** - * @param string $userpassr_hash + * @param string $hash */ - public function setUserpassrHash($userpassr_hash) + public function setHash($hash) { - $this->userpassr_hash = $userpassr_hash; + $this->hash = $hash; } /** * @return int */ - public function getUserpassrDate() + public function getDate() { - return $this->userpassr_date; + return $this->date; } /** - * @param int $userpassr_date + * @param int $date */ - public function setUserpassrDate($userpassr_date) + public function setDate($date) { - $this->userpassr_date = $userpassr_date; + $this->date = $date; } /** * @return boolean */ - public function isUserpassrUsed() + public function isUsed() { - return (int)$this->userpassr_used; + return (int)$this->used; } /** - * @param boolean $userpassr_used + * @param boolean $used */ - public function setUserpassrUsed($userpassr_used) + public function setUsed($used) { - $this->userpassr_used = (int)$userpassr_used; + $this->used = (int)$used; } } \ No newline at end of file diff --git a/lib/SP/DataModel/GroupUsersData.php b/lib/SP/DataModel/UserToUserGroupData.php similarity index 71% rename from lib/SP/DataModel/GroupUsersData.php rename to lib/SP/DataModel/UserToUserGroupData.php index a2b7ebfe..0e21ce05 100644 --- a/lib/SP/DataModel/GroupUsersData.php +++ b/lib/SP/DataModel/UserToUserGroupData.php @@ -31,16 +31,16 @@ defined('APP_ROOT') || die(); * * @package SP\DataModel */ -class GroupUsersData extends DataModelBase +class UserToUserGroupData extends DataModelBase { /** * @var int */ - public $usertogroup_groupId = 0; + public $userGroupId = 0; /** * @var int */ - public $usertogroup_userId = 0; + public $userId = 0; /** * @var array */ @@ -49,33 +49,33 @@ class GroupUsersData extends DataModelBase /** * @return int */ - public function getUsertogroupGroupId() + public function getUserGroupId() { - return (int)$this->usertogroup_groupId; + return (int)$this->userGroupId; } /** - * @param int $usertogroup_groupId + * @param int $userGroupId */ - public function setUsertogroupGroupId($usertogroup_groupId) + public function setUserGroupId($userGroupId) { - $this->usertogroup_groupId = $usertogroup_groupId; + $this->userGroupId = $userGroupId; } /** * @return int */ - public function getUsertogroupUserId() + public function getUserId() { - return (int)$this->usertogroup_userId; + return (int)$this->userId; } /** - * @param int $usertogroup_userId + * @param int $userId */ - public function setUsertogroupUserId($usertogroup_userId) + public function setUserId($userId) { - $this->usertogroup_userId = $usertogroup_userId; + $this->userId = $userId; } /** diff --git a/lib/SP/Forms/CustomFieldDefForm.php b/lib/SP/Forms/CustomFieldDefForm.php index ae634c64..e3f55f67 100644 --- a/lib/SP/Forms/CustomFieldDefForm.php +++ b/lib/SP/Forms/CustomFieldDefForm.php @@ -26,7 +26,7 @@ namespace SP\Forms; use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\ValidationException; -use SP\DataModel\CustomFieldDefData; +use SP\DataModel\CustomFieldDefinitionData; use SP\Http\Request; /** @@ -37,7 +37,7 @@ use SP\Http\Request; class CustomFieldDefForm extends FormBase implements FormInterface { /** - * @var CustomFieldDefData + * @var CustomFieldDefinitionData */ protected $customFieldDefData; @@ -68,7 +68,7 @@ class CustomFieldDefForm extends FormBase implements FormInterface */ protected function analyzeRequestData() { - $this->customFieldDefData = new CustomFieldDefData(); + $this->customFieldDefData = new CustomFieldDefinitionData(); $this->customFieldDefData->setId($this->itemId); $this->customFieldDefData->setName(Request::analyze('name')); $this->customFieldDefData->setTypeId(Request::analyze('type', 0)); @@ -96,7 +96,7 @@ class CustomFieldDefForm extends FormBase implements FormInterface } /** - * @return CustomFieldDefData + * @return CustomFieldDefinitionData */ public function getItemData() { diff --git a/lib/SP/Mgmt/Categories/Category.php b/lib/SP/Mgmt/Categories/Category.php index 82052493..31c52937 100644 --- a/lib/SP/Mgmt/Categories/Category.php +++ b/lib/SP/Mgmt/Categories/Category.php @@ -55,18 +55,18 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac } $query = /** @lang SQL */ - 'INSERT INTO categories SET category_name = ?, category_description = ?, category_hash = ?'; + 'INSERT INTO Category SET name = ?, description = ?, hash = ?'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->itemData->getCategoryName()); - $Data->addParam($this->itemData->getCategoryDescription()); - $Data->addParam($this->makeItemHash($this->itemData->getCategoryName())); + $Data->addParam($this->itemData->getName()); + $Data->addParam($this->itemData->getDescription()); + $Data->addParam($this->makeItemHash($this->itemData->getName())); $Data->setOnErrorMessage(__('Error al crear la categoría', false)); DbWrapper::getQuery($Data); - $this->itemData->setCategoryId(DbWrapper::$lastId); + $this->itemData->setId(DbWrapper::$lastId); return $this; } @@ -80,12 +80,12 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function checkDuplicatedOnAdd() { $query = /** @lang SQL */ - 'SELECT category_id FROM categories WHERE category_hash = ? OR category_name = ?'; + 'SELECT id FROM Category WHERE hash = ? OR name = ?'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->makeItemHash($this->itemData->getCategoryName())); - $Data->addParam($this->itemData->getCategoryName()); + $Data->addParam($this->makeItemHash($this->itemData->getName())); + $Data->addParam($this->itemData->getName()); $queryRes = DbWrapper::getResults($Data); @@ -93,7 +93,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac if ($Data->getQueryNumRows() === 0) { return false; } elseif ($Data->getQueryNumRows() === 1) { - $this->itemData->setCategoryId($queryRes->category_id); + $this->itemData->setId($queryRes->category_id); } } @@ -111,7 +111,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function delete($id) { $query = /** @lang SQL */ - 'DELETE FROM categories WHERE category_id = ? LIMIT 1'; + 'DELETE FROM Category WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); @@ -136,7 +136,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function checkInUse($id) { $query = /** @lang SQL */ - 'SELECT account_id FROM accounts WHERE account_categoryId = ?'; + 'SELECT account_id FROM Account WHERE account_categoryId = ?'; $Data = new QueryData(); $Data->setQuery($query); @@ -154,7 +154,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function getById($id) { $query = /** @lang SQL */ - 'SELECT category_id, category_name, category_description FROM categories WHERE category_id = ? LIMIT 1'; + 'SELECT id, name, description FROM Category WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); @@ -175,18 +175,18 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac } $query = /** @lang SQL */ - 'UPDATE categories - SET category_name = ?, - category_description = ?, - category_hash = ? - WHERE category_id = ? LIMIT 1'; + 'UPDATE Category + SET name = ?, + description = ?, + hash = ? + WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->itemData->getCategoryName()); - $Data->addParam($this->itemData->getCategoryDescription()); - $Data->addParam($this->makeItemHash($this->itemData->getCategoryName())); - $Data->addParam($this->itemData->getCategoryId()); + $Data->addParam($this->itemData->getName()); + $Data->addParam($this->itemData->getDescription()); + $Data->addParam($this->makeItemHash($this->itemData->getName())); + $Data->addParam($this->itemData->getId()); $Data->setOnErrorMessage(__('Error al actualizar la categoría', false)); DbWrapper::getQuery($Data); @@ -202,13 +202,13 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function checkDuplicatedOnUpdate() { $query = /** @lang SQL */ - 'SELECT category_id FROM categories WHERE (category_hash = ? OR category_name = ?) AND category_id <> ?'; + 'SELECT id FROM Category WHERE (hash = ? OR name = ?) AND id <> ?'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->makeItemHash($this->itemData->getCategoryName())); - $Data->addParam($this->itemData->getCategoryName()); - $Data->addParam($this->itemData->getCategoryId()); + $Data->addParam($this->makeItemHash($this->itemData->getName())); + $Data->addParam($this->itemData->getName()); + $Data->addParam($this->itemData->getId()); DbWrapper::getQuery($Data); @@ -221,7 +221,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac public function getAll() { $query = /** @lang SQL */ - 'SELECT category_id, category_name, category_description, category_hash FROM categories ORDER BY category_name'; + 'SELECT id, name, description, hash FROM Category ORDER BY name'; $Data = new QueryData(); $Data->setMapClassName($this->getDataModel()); @@ -243,7 +243,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac } $query = /** @lang SQL */ - 'SELECT category_id, category_name, category_description FROM categories WHERE category_id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, name, description FROM Category WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; $Data = new QueryData(); $Data->setQuery($query); diff --git a/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php b/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php index 629a8709..0f01e345 100644 --- a/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php +++ b/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php @@ -32,7 +32,7 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\Core\OldCrypt; use SP\DataModel\CustomFieldData; -use SP\DataModel\CustomFieldDefData; +use SP\DataModel\CustomFieldDefinitionData; use SP\Log\Log; use SP\Storage\DbWrapper; use SP\Storage\QueryData; @@ -59,7 +59,7 @@ class CustomFieldsUtil $LogMessage->setAction(__('Campos Personalizados', false)); $query = /** @lang SQL */ - 'SELECT customfielddata_id, customfielddata_data, customfielddata_key FROM customFieldsData'; + 'SELECT customfielddata_id, customfielddata_data, customfielddata_key FROM CustomFieldData'; $Data = new QueryData(); $Data->setMapClassName(CustomFieldData::class); @@ -89,7 +89,7 @@ class CustomFieldsUtil } $query = /** @lang SQL */ - 'UPDATE customFieldsData SET + 'UPDATE CustomFieldData SET customfielddata_data = ?, customfielddata_key = ? WHERE customfielddata_id = ?'; @@ -130,7 +130,7 @@ class CustomFieldsUtil $LogMessage->setAction(__('Campos Personalizados', false)); $query = /** @lang SQL */ - 'SELECT customfielddata_id, customfielddata_data, customfielddata_key FROM customFieldsData'; + 'SELECT customfielddata_id, customfielddata_data, customfielddata_key FROM CustomFieldData'; $Data = new QueryData(); $Data->setMapClassName(CustomFieldData::class); @@ -160,7 +160,7 @@ class CustomFieldsUtil } $query = /** @lang SQL */ - 'UPDATE customFieldsData SET + 'UPDATE CustomFieldData SET customfielddata_data = ?, customfielddata_key = ? WHERE customfielddata_id = ?'; @@ -243,20 +243,20 @@ class CustomFieldsUtil $query = /** @lang SQL */ 'SELECT DISTINCT customfielddef_id, customfielddef_field - FROM customFieldsData - LEFT JOIN customFieldsDef ON customfielddef_id = customfielddata_defId + FROM CustomFieldData + LEFT JOIN CustomFieldDefinition ON customfielddef_id = customfielddata_defId WHERE customfielddata_moduleId = 20'; $Data = new QueryData(); $Data->setQuery($query); - /** @var CustomFieldDefData[] $oldDefs */ + /** @var CustomFieldDefinitionData[] $oldDefs */ $oldDefs = DbWrapper::getResultsArray($Data); try { if (count($oldDefs) > 0) { $query = /** @lang SQL */ - 'UPDATE customFieldsData SET customfielddata_moduleId = 10 WHERE customfielddata_moduleId = 20'; + 'UPDATE CustomFieldData SET customfielddata_moduleId = 10 WHERE customfielddata_moduleId = 20'; $Data = new QueryData(); $Data->setQuery($query); @@ -265,13 +265,13 @@ class CustomFieldsUtil DbWrapper::getQuery($Data); $query = /** @lang SQL */ - 'UPDATE customFieldsDef SET + 'UPDATE CustomFieldDefinition SET customfielddef_module = ?, customfielddef_field = ? WHERE customfielddef_id = ? LIMIT 1'; foreach ($oldDefs as $cf) { - $CustomFieldDef = Util::unserialize(CustomFieldDefData::class, $cf->customfielddef_field); + $CustomFieldDef = Util::unserialize(CustomFieldDefinitionData::class, $cf->customfielddef_field); $CustomFieldDef->setId($cf->customfielddef_id); $CustomFieldDef->setModule(10); $CustomFieldDef->setCustomfielddefModule(10); diff --git a/lib/SP/Mgmt/Groups/GroupAccountsBase.php b/lib/SP/Mgmt/Groups/GroupAccountsBase.php index 8eab0489..240a9a94 100644 --- a/lib/SP/Mgmt/Groups/GroupAccountsBase.php +++ b/lib/SP/Mgmt/Groups/GroupAccountsBase.php @@ -25,7 +25,7 @@ namespace SP\Mgmt\Groups; use SP\Core\Exceptions\InvalidClassException; -use SP\DataModel\GroupAccountsData; +use SP\DataModel\AccountToUserGroupData; use SP\Mgmt\ItemBaseInterface; use SP\Mgmt\ItemBaseTrait; @@ -48,6 +48,6 @@ abstract class GroupAccountsBase implements ItemBaseInterface */ protected function init() { - $this->setDataModel(GroupAccountsData::class); + $this->setDataModel(AccountToUserGroupData::class); } } \ No newline at end of file diff --git a/lib/SP/Mgmt/Groups/GroupUsers.php b/lib/SP/Mgmt/Groups/GroupUsers.php index c4cf848c..b971667e 100644 --- a/lib/SP/Mgmt/Groups/GroupUsers.php +++ b/lib/SP/Mgmt/Groups/GroupUsers.php @@ -27,7 +27,7 @@ namespace SP\Mgmt\Groups; defined('APP_ROOT') || die(); use SP\Core\Exceptions\SPException; -use SP\DataModel\GroupUsersData; +use SP\DataModel\UserToUserGroupData; use SP\Mgmt\ItemInterface; use SP\Mgmt\ItemSelectInterface; use SP\Mgmt\ItemTrait; @@ -38,7 +38,7 @@ use SP\Storage\QueryData; * Class GroupUser * * @package SP\Mgmt\Groups - * @property GroupUsersData $itemData + * @property UserToUserGroupData $itemData */ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInterface { @@ -50,7 +50,7 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte */ public function update() { - $this->delete($this->itemData->getUsertogroupGroupId()); + $this->delete($this->itemData->getUserGroupId()); $this->add(); return $this; @@ -64,7 +64,7 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte public function delete($id) { $query = /** @lang SQL */ - 'DELETE FROM usrToGroups WHERE usertogroup_groupId = ?'; + 'DELETE FROM UserToGroup WHERE userGroupId = ?'; $Data = new QueryData(); $Data->setQuery($query); @@ -89,14 +89,14 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte } $query = /** @lang SQL */ - 'INSERT INTO usrToGroups (usertogroup_userId, usertogroup_groupId) VALUES ' . $this->getParamsFromArray($this->itemData->getUsers(), '(?,?)'); + 'INSERT INTO UserToGroup (userId, userGroupId) VALUES ' . $this->getParamsFromArray($this->itemData->getUsers(), '(?,?)'); $Data = new QueryData(); $Data->setQuery($query); foreach ($this->itemData->getUsers() as $user) { $Data->addParam($user); - $Data->addParam($this->itemData->getUsertogroupGroupId()); + $Data->addParam($this->itemData->getUserGroupId()); } $Data->setOnErrorMessage(__('Error al asignar los usuarios al grupo', false)); @@ -108,12 +108,12 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte /** * @param $id int - * @return GroupUsersData[] + * @return UserToUserGroupData[] */ public function getById($id) { $query = /** @lang SQL */ - 'SELECT usertogroup_groupId, usertogroup_userId FROM usrToGroups WHERE usertogroup_groupId = ?'; + 'SELECT userGroupId, userId FROM UserToGroup WHERE userGroupId = ?'; $Data = new QueryData(); $Data->setMapClassName($this->getDataModel()); @@ -140,7 +140,7 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte public function checkInUse($id) { $query = /** @lang SQL */ - 'SELECT usertogroup_groupId FROM usrToGroups WHERE usertogroup_groupId = ?'; + 'SELECT userGroupId FROM UserToGroup WHERE userGroupId = ?'; $Data = new QueryData(); $Data->setQuery($query); @@ -188,7 +188,7 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte public function checkUserInGroup($groupId, $userId) { $query = /** @lang SQL */ - 'SELECT usertogroup_groupId FROM usrToGroups WHERE usertogroup_groupId = ? AND usertogroup_userId = ?'; + 'SELECT userGroupId FROM UserToGroup WHERE userGroupId = ? AND userId = ?'; $Data = new QueryData(); $Data->setQuery($query); @@ -209,7 +209,7 @@ class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInte public function getGroupsForUser($userId) { $query = /** @lang SQL */ - 'SELECT usertogroup_groupId AS groupId FROM usrToGroups WHERE usertogroup_userId = ?'; + 'SELECT userGroupId AS groupId FROM UserToGroup WHERE userId = ?'; $Data = new QueryData(); $Data->setQuery($query); diff --git a/lib/SP/Mgmt/Tracks/Track.php b/lib/SP/Mgmt/Tracks/Track.php index 59507b9c..e3bf2b50 100644 --- a/lib/SP/Mgmt/Tracks/Track.php +++ b/lib/SP/Mgmt/Tracks/Track.php @@ -45,24 +45,24 @@ class Track extends TrackBase implements ItemInterface public function add() { $query = /** @lang SQL */ - 'INSERT INTO track SET - track_userId = ?, - track_source = ?, - track_time = UNIX_TIMESTAMP(), - track_ipv4 = ?, - track_ipv6 = ?'; + 'INSERT INTO Track SET + userId = ?, + source = ?, + time = UNIX_TIMESTAMP(), + ipv4 = ?, + ipv6 = ?'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->itemData->getTrackUserId()); - $Data->addParam($this->itemData->getTrackSource()); + $Data->addParam($this->itemData->getUserId()); + $Data->addParam($this->itemData->getSource()); $Data->addParam($this->itemData->getTrackIpv4Bin()); $Data->addParam($this->itemData->getTrackIpv6Bin()); $Data->setOnErrorMessage(__('Error al crear track', false)); DbWrapper::getQuery($Data); - $this->itemData->setTrackId(DbWrapper::$lastId); + $this->itemData->setId(DbWrapper::$lastId); return $this; } @@ -76,11 +76,11 @@ class Track extends TrackBase implements ItemInterface public function delete($id) { $query = /** @lang SQL */ - 'DELETE FROM track WHERE track_id = ? LIMIT 1'; + 'DELETE FROM Track WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->itemData->getTrackId()); + $Data->addParam($this->itemData->getId()); $Data->setOnErrorMessage(__('Error al eliminar track', false)); return DbWrapper::getQuery($Data); @@ -94,21 +94,21 @@ class Track extends TrackBase implements ItemInterface public function update() { $query = /** @lang SQL */ - 'UPDATE track SET + 'UPDATE Track SET track_userId = ?, - track_source = ?, - track_time = UNIX_TIMESTAMP(), - track_ipv4 = ?, - track_ipv6 = ? - WHERE track_id = ? LIMIT 1'; + source = ?, + time = UNIX_TIMESTAMP(), + ipv4 = ?, + ipv6 = ? + WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setQuery($query); - $Data->addParam($this->itemData->getTrackUserId()); - $Data->addParam($this->itemData->getTrackSource()); + $Data->addParam($this->itemData->getUserId()); + $Data->addParam($this->itemData->getSource()); $Data->addParam($this->itemData->getTrackIpv4Bin()); $Data->addParam($this->itemData->getTrackIpv6Bin()); - $Data->addParam($this->itemData->getTrackId()); + $Data->addParam($this->itemData->getId()); $Data->setOnErrorMessage(__('Error al actualizar track', false)); return DbWrapper::getQuery($Data); @@ -123,19 +123,19 @@ class Track extends TrackBase implements ItemInterface public function getById($id) { $query = /** @lang SQL */ - 'SELECT track_id, - track_userId, - track_source, - track_time, - track_ipv4, - track_ipv6 - FROM track - WHERE track_id = ? LIMIT 1'; + 'SELECT id, + userId, + source, + time, + ipv4, + ipv6 + FROM Track + WHERE id = ? LIMIT 1'; $Data = new QueryData(); $Data->setMapClassName($this->getDataModel()); $Data->setQuery($query); - $Data->addParam($this->itemData->getTrackId()); + $Data->addParam($this->itemData->getId()); $Data->setOnErrorMessage(__('Error al obtener track', false)); return DbWrapper::getResults($Data); @@ -149,17 +149,17 @@ class Track extends TrackBase implements ItemInterface public function getAll() { $query = /** @lang SQL */ - 'SELECT track_id, - track_userId, - track_source, - track_time, - track_ipv4, - track_ipv6 FROM track'; + 'SELECT id, + userId, + source, + time, + ipv4, + ipv6 FROM Track'; $Data = new QueryData(); $Data->setMapClassName($this->getDataModel()); $Data->setQuery($query); - $Data->addParam($this->itemData->getTrackId()); + $Data->addParam($this->itemData->getId()); $Data->setOnErrorMessage(__('Error al obtener tracks', false)); return DbWrapper::getResultsArray($Data); @@ -222,11 +222,11 @@ class Track extends TrackBase implements ItemInterface public function getTracksForClientFromTime($time) { $query = /** @lang SQL */ - 'SELECT track_id, track_userId - FROM track - WHERE track_time >= ? - AND (track_ipv4 = ? OR track_ipv6 = ?) - AND track_source = ?'; + 'SELECT id, userId + FROM Track + WHERE time >= ? + AND (ipv4 = ? OR ipv6 = ?) + AND source = ?'; $Data = new QueryData(); $Data->setMapClassName($this->getDataModel()); @@ -234,7 +234,7 @@ class Track extends TrackBase implements ItemInterface $Data->addParam($time); $Data->addParam($this->itemData->getTrackIpv4Bin()); $Data->addParam($this->itemData->getTrackIpv6Bin()); - $Data->addParam($this->itemData->getTrackSource()); + $Data->addParam($this->itemData->getSource()); $Data->setOnErrorMessage(__('Error al obtener tracks', false)); return DbWrapper::getResultsArray($Data); diff --git a/lib/SP/Mgmt/Users/UserLdapSync.php b/lib/SP/Mgmt/Users/UserLdapSync.php index dcf81664..3bf8c88d 100644 --- a/lib/SP/Mgmt/Users/UserLdapSync.php +++ b/lib/SP/Mgmt/Users/UserLdapSync.php @@ -61,7 +61,7 @@ class UserLdapSync */ public static function run(array &$options) { - $ConfigData = Bootstrap::getDic()['configData']; + $ConfigData = Bootstrap::getContainer()['configData']; $Log = new Log(); $LogMessage = $Log->getLogMessage(); @@ -92,24 +92,24 @@ class UserLdapSync switch (strtolower($attribute)) { case $options['nameAttribute']: - $User->setUserName($value); + $User->setName($value); break; case $options['loginAttribute']: - $User->setUserLogin($value); + $User->setLogin($value); break; case 'mail': - $User->setUserEmail($value); + $User->setEmail($value); break; } } - if (!empty($User->getUserName()) - && !empty($User->getUserLogin()) + if (!empty($User->getName()) + && !empty($User->getLogin()) ) { - $User->setUserPass(Util::generateRandomBytes()); + $User->setPass(Util::generateRandomBytes()); try { - $LogMessage->addDetails(__('Usuario', false), sprintf('%s (%s)', $User->getUserName(), $User->getUserLogin())); + $LogMessage->addDetails(__('Usuario', false), sprintf('%s (%s)', $User->getName(), $User->getLogin())); UserLdap::getItem($User)->add(); self::$syncedObjects++; diff --git a/lib/SP/Mgmt/Users/UserPreferencesUtil.php b/lib/SP/Mgmt/Users/UserPreferencesUtil.php index 28a9a4a3..11399b19 100644 --- a/lib/SP/Mgmt/Users/UserPreferencesUtil.php +++ b/lib/SP/Mgmt/Users/UserPreferencesUtil.php @@ -54,7 +54,7 @@ class UserPreferencesUtil */ public static function migrate() { - $Container = Bootstrap::getDic(); + $Container = Bootstrap::getContainer(); /** @var ConfigData $ConfigData */ $ConfigData = $Container->get(ConfigData::class); /** @var Log $Log */ @@ -66,14 +66,14 @@ class UserPreferencesUtil foreach (User::getItem()->getAll() as $User) { try { - $Preferences = $User->getUserPreferences(); + $Preferences = $User->getPreferences(); if (!empty($Preferences)) { - $LogMessage->addDetails(__('Usuario', false), $User->getUserLogin()); + $LogMessage->addDetails(__('Usuario', false), $User->getLogin()); /** @var UserPreferencesData $Preferences */ $Preferences = Util::unserialize(UserPreferencesData::class, $Preferences, 'SP\UserPreferences'); - $User->setUserPreferences($Preferences); + $User->setPreferences($Preferences); // FIXME $Preferences->setTheme($ConfigData->getSiteTheme()); @@ -84,7 +84,7 @@ class UserPreferencesUtil $Preferences->setUse2Fa(0); } - $Preferences->setUserId($User->getUserId()); + $Preferences->setUserId($User->getId()); UserPreferences::getItem($Preferences)->update(); } @@ -113,17 +113,17 @@ class UserPreferencesUtil /** @var AuthenticatorData $AuthenticatorData */ $AuthenticatorData = new AuthenticatorData(); - $AuthenticatorData->setUserId($UserData->getUserId()); + $AuthenticatorData->setUserId($UserData->getId()); $AuthenticatorData->setIV(UserPass::getUserIVById($UserData->getId())); $AuthenticatorData->setTwofaEnabled(1); $AuthenticatorData->setDate(time()); - $data[$UserData->getUserId()] = $AuthenticatorData; + $data[$UserData->getId()] = $AuthenticatorData; $PluginData = new PluginData(); - $PluginData->setPluginName(AuthenticatorPlugin::PLUGIN_NAME); - $PluginData->setPluginEnabled(1); - $PluginData->setPluginData(serialize($data)); + $PluginData->setName(AuthenticatorPlugin::PLUGIN_NAME); + $PluginData->setEnabled(1); + $PluginData->setData(serialize($data)); Plugin::getItem($PluginData)->update(); } diff --git a/lib/SP/Repositories/Account/AccountRepository.php b/lib/SP/Repositories/Account/AccountRepository.php new file mode 100644 index 00000000..149a33fa --- /dev/null +++ b/lib/SP/Repositories/Account/AccountRepository.php @@ -0,0 +1,685 @@ +. + */ + +namespace SP\Repositories\Account; + +use SP\Account\AccountRequest; +use SP\Account\AccountSearchFilter; +use SP\Account\AccountUtil; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\AccountExtData; +use SP\DataModel\AccountPassData; +use SP\DataModel\AccountSearchVData; +use SP\DataModel\AccountVData; +use SP\DataModel\Dto\AccountSearchResponse; +use SP\DataModel\ItemSearchData; +use SP\Repositories\Repository; +use SP\Repositories\RepositoryItemInterface; +use SP\Repositories\RepositoryItemTrait; +use SP\Storage\DbWrapper; +use SP\Storage\QueryData; + +/** + * Class AccountRepository + * + * @package Services + */ +class AccountRepository extends Repository implements RepositoryItemInterface +{ + use RepositoryItemTrait; + + /** + * @param $id + * @return AccountPassData + */ + public function getPasswordForId($id) + { + $Data = new QueryData(); + $Data->setMapClassName(AccountPassData::class); + $Data->setLimit(1); + + $Data->setSelect('A.id, A.name, A.login, A.pass, A.key, A.parentId'); + $Data->setFrom('Account A'); + + $queryWhere = AccountUtil::getAccountFilterUser($Data, $this->session); + $queryWhere[] = 'A.id = ?'; + $Data->addParam($id); + + $Data->setWhere($queryWhere); + + return DbWrapper::getResults($Data, $this->db); + } + + /** + * @param $id + * @return AccountPassData + */ + public function getPasswordHistoryForId($id) + { + $Data = new QueryData(); + $Data->setMapClassName(AccountPassData::class); + $Data->setLimit(1); + + $Data->setSelect('AH.id, AH.name, AH.login, AH.pass, AH.key, AH.parentId'); + $Data->setFrom('AccountHistory AH'); + + $queryWhere = AccountUtil::getAccountHistoryFilterUser($Data, $this->session); + $queryWhere[] = 'AH.id = ?'; + $Data->addParam($id); + + $Data->setWhere($queryWhere); + + return DbWrapper::getResults($Data, $this->db); + } + + /** + * Incrementa el contador de vista de clave de una cuenta en la BBDD + * + * @param int $id + * @return bool + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function incrementDecryptCounter($id) + { + $query = /** @lang SQL */ + 'UPDATE Account SET countDecrypt = (countDecrypt + 1) WHERE id = ? LIMIT 1'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + + return DbWrapper::getQuery($Data, $this->db); + } + + /** + * Crea una nueva cuenta en la BBDD + * + * @param AccountRequest $itemData + * @return int + * @throws QueryException + * @throws SPException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function create($itemData) + { + $query = /** @lang SQL */ + 'INSERT INTO Account SET + clientId = :clientId, + categoryId = :categoryId, + name = :name, + login = :login, + url = :url, + pass = :pass, + `key` = :key, + notes = :notes, + dateAdd = NOW(), + userId = :userId, + userGroupId = :userGroupId, + userEditId = :userEditId, + otherUserEdit = :otherUserEdit, + otherUserGroupEdit = :otherGroupEdit, + isPrivate = :isPrivate, + isPrivateGroup = :isPrivateGroup, + passDate = UNIX_TIMESTAMP(), + passDateChange = :passDateChange, + parentId = :parentId'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($itemData->clientId, 'clientId'); + $Data->addParam($itemData->categoryId, 'aategoryId'); + $Data->addParam($itemData->name, 'name'); + $Data->addParam($itemData->login, 'login'); + $Data->addParam($itemData->url, 'url'); + $Data->addParam($itemData->pass, 'pass'); + $Data->addParam($itemData->key, 'key'); + $Data->addParam($itemData->notes, 'notes'); + $Data->addParam($itemData->userId, 'userId'); + $Data->addParam($itemData->userGroupId ?: $this->session->getUserData()->getUserGroupId(), 'userGroupId'); + $Data->addParam($itemData->userId, 'userEditId'); + $Data->addParam($itemData->otherUserEdit, 'otherUserEdit'); + $Data->addParam($itemData->otherUserGroupEdit, 'otherGroupEdit'); + $Data->addParam($itemData->isPrivate, 'isPrivate'); + $Data->addParam($itemData->isPrivateGroup, 'isPrivateGroup'); + $Data->addParam($itemData->passDateChange, 'passDateChange'); + $Data->addParam($itemData->parentId, 'parentId'); + $Data->setOnErrorMessage(__u('Error al crear la cuenta')); + + DbWrapper::getQuery($Data, $this->db); + + return $this->db->getLastId(); + } + + /** + * Actualiza la clave de una cuenta en la BBDD. + * + * @param AccountRequest $accountRequest + * @return bool + * @throws QueryException + * @throws SPException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function editPassword(AccountRequest $accountRequest) + { + $query = /** @lang SQL */ + 'UPDATE Account SET + pass = :pass, + `key` = :key, + userEditId = :userEditId, + dateEdit = NOW(), + passDate = UNIX_TIMESTAMP(), + passDateChange = :passDateChange + WHERE id = :id'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($accountRequest->pass, 'pass'); + $Data->addParam($accountRequest->key, 'key'); + $Data->addParam($accountRequest->userEditId, 'userEditId'); + $Data->addParam($accountRequest->passDateChange, 'passDateChange'); + $Data->addParam($accountRequest->id, 'id'); + $Data->setOnErrorMessage(__u('Error al actualizar la clave')); + + return DbWrapper::getQuery($Data, $this->db); + } + + /** + * Restaurar una cuenta desde el histórico. + * + * @param int $historyId El Id del registro en el histórico + * @return bool + * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function editRestore($historyId) + { + $query = /** @lang SQL */ + 'UPDATE Account dst, + (SELECT * FROM AccountHistory AH WHERE AH.id = :id) src SET + dst.clientId = src.clientId, + dst.categoryId = src.categoryId, + dst.name = src.name, + dst.login = src.login, + dst.url = src.url, + dst.notes = src.notes, + dst.userGroupId = src.userGroupId, + dst.userEditId = :userEditId, + dst.dateEdit = NOW(), + dst.otherUserEdit = src.otherUserEdit + 0, + dst.otherUserGroupEdit = src.otherUserGroupEdit + 0, + dst.pass = src.pass, + dst.key = src.key, + dst.passDate = src.passDate, + dst.passDateChange = src.passDateChange, + dst.parentId = src.parentId, + dst.isPrivate = src.isPrivate, + dst.isPrivateGroup = src.isPrivateGroup + WHERE dst.id = src.accountId'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($historyId, 'id'); + $Data->addParam($this->session->getUserData()->getId(), 'userEditId'); + $Data->setOnErrorMessage(__u('Error al restaurar cuenta')); + + return DbWrapper::getQuery($Data, $this->db); + } + + /** + * Elimina los datos de una cuenta en la BBDD. + * + * @param int $id + * @return bool Los ids de las cuentas eliminadas + * @throws SPException + */ + public function delete($id) + { + $Data = new QueryData(); + + $query = /** @lang SQL */ + 'DELETE FROM Account WHERE id = ? LIMIT 1'; + + $Data->setQuery($query); + $Data->addParam($id); + $Data->setOnErrorMessage(__u('Error al eliminar la cuenta')); + + DbWrapper::getQuery($Data, $this->db); + + return $Data->getQueryNumRows(); + } + + /** + * Updates an item + * + * @param AccountRequest $itemData + * @return mixed + * @throws SPException + */ + public function update($itemData) + { + $Data = new QueryData(); + + $fields = [ + 'clientId = :clientId', + 'categoryId = :categoryId', + 'name = :name', + 'login = :login', + 'url = :url', + 'notes = :notes', + 'userEditId = :userEditId', + 'dateEdit = NOW()', + 'passDateChange = :passDateChange', + 'isPrivate = :isPrivate', + 'isPrivateGroup = :isPrivateGroup', + 'parentId = :parentId' + ]; + + if ($itemData->changeUserGroup) { + $fields[] = 'userGroupId = :userGroupId'; + + $Data->addParam($itemData->userGroupId, 'userGroupId'); + } + + if ($itemData->changePermissions) { + $fields[] = 'otherUserEdit = :otherUserEdit'; + $fields[] = 'otherUserGroupEdit = :otherUserGroupEdit'; + + $Data->addParam($itemData->otherUserEdit, 'otherUserEdit'); + $Data->addParam($itemData->otherUserGroupEdit, 'otherUserGroupEdit'); + } + + $query = /** @lang SQL */ + 'UPDATE Account SET ' . implode(',', $fields) . ' WHERE id = :accountId'; + + $Data->setQuery($query); + $Data->addParam($itemData->clientId, 'clientId'); + $Data->addParam($itemData->categoryId, 'categoryId'); + $Data->addParam($itemData->name, 'name'); + $Data->addParam($itemData->login, 'login'); + $Data->addParam($itemData->url, 'url'); + $Data->addParam($itemData->notes, 'notes'); + $Data->addParam($itemData->userEditId, 'userEditId'); + $Data->addParam($itemData->passDateChange, 'passDateChange'); + $Data->addParam($itemData->isPrivate, 'isPrivate'); + $Data->addParam($itemData->isPrivateGroup, 'isPrivateGroup'); + $Data->addParam($itemData->parentId, 'parentId'); + $Data->addParam($itemData->id, 'id'); + $Data->setOnErrorMessage(__u('Error al modificar la cuenta')); + + return DbWrapper::getQuery($Data, $this->db); + } + + /** + * Returns the item for given id + * + * @param int $id + * @return AccountVData + * @throws SPException + */ + 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); + + /** @var AccountVData|array $queryRes */ + $queryRes = DbWrapper::getResults($Data); + + if ($queryRes === false) { + throw new SPException(SPException::SP_CRITICAL, __u('No se pudieron obtener los datos de la cuenta')); + } + + if (is_array($queryRes) && count($queryRes) === 0) { + throw new SPException(SPException::SP_CRITICAL, __u('La cuenta no existe')); + } + + return $queryRes; + } + + /** + * Returns all the items + * + */ + public function getAll() + { + throw new \RuntimeException('Not implemented'); + } + + /** + * Returns all the items for given ids + * + * @param array $ids + */ + public function getByIdBatch(array $ids) + { + throw new \RuntimeException('Not implemented'); + } + + /** + * Deletes all the items for given ids + * + * @param array $ids + */ + public function deleteByIdBatch(array $ids) + { + throw new \RuntimeException('Not implemented'); + } + + /** + * 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 $SearchData + * @return mixed + */ + 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'); + + if ($SearchData->getSeachString() !== '') { + $Data->setWhere('A.name LIKE ? OR C.name LIKE ?'); + + $search = '%' . $SearchData->getSeachString() . '%'; + $Data->addParam($search); + $Data->addParam($search); + } + + $Data->setLimit('?,?'); + $Data->addParam($SearchData->getLimitStart()); + $Data->addParam($SearchData->getLimitCount()); + + DbWrapper::setFullRowCount(); + + $queryRes = DbWrapper::getResultsArray($Data, $this->db); + + $queryRes['count'] = $Data->getQueryNumRows(); + + return $queryRes; + } + + /** + * Incrementa el contador de visitas de una cuenta en la BBDD + * + * @param int $id + * @return bool + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function incrementViewCounter($id = null) + { + $query = /** @lang SQL */ + 'UPDATE Account SET countView = (countView + 1) WHERE id = ? LIMIT 1'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + + return DbWrapper::getQuery($Data, $this->db); + } + + /** + * Obtener los datos de una cuenta. + * + * @param $id + * @return AccountExtData + * @throws SPException + */ + public function getDataForLink($id) + { + $query = /** @lang SQL */ + 'SELECT A.name, + A.login, + A.pass, + A.key, + A.url, + A.notes, + C.name AS clientName, + C2.name AS categoryName + FROM Account A + INNER JOIN Client C ON A.clientId = C.id + 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); + + /** @var AccountExtData|array $queryRes */ + $queryRes = DbWrapper::getResults($Data, $this->db); + + if ($queryRes === false) { + throw new SPException(SPException::SP_ERROR, __u('No se pudieron obtener los datos de la cuenta')); + } + + if (is_array($queryRes) && count($queryRes) === 0) { + throw new SPException(SPException::SP_ERROR, __u('La cuenta no existe')); + } + + return $queryRes; + } + + /** + * Obtener las cuentas de una búsqueda. + * + * @param AccountSearchFilter $accountSearchFilter + * @return AccountSearchResponse + */ + public function getByFilter(AccountSearchFilter $accountSearchFilter) + { + $arrFilterCommon = []; + $arrFilterSelect = []; + $arrayQueryJoin = []; + $arrQueryWhere = []; + $queryLimit = ''; + + $data = new QueryData(); + + $txtSearch = $accountSearchFilter->getTxtSearch(); + + if ($txtSearch !== null && $txtSearch !== '') { + // Analizar la cadena de búsqueda por etiquetas especiales + $stringFilter = $accountSearchFilter->getStringFilters(); + + if (!empty($stringFilter)) { + $arrFilterCommon[] = $stringFilter['query']; + + foreach ($stringFilter['values'] as $value) { + $data->addParam($value); + } + } else { + $txtSearch = '%' . $txtSearch . '%'; + + $arrFilterCommon[] = 'name LIKE ?'; + $data->addParam($txtSearch); + + $arrFilterCommon[] = 'login LIKE ?'; + $data->addParam($txtSearch); + + $arrFilterCommon[] = 'url LIKE ?'; + $data->addParam($txtSearch); + + $arrFilterCommon[] = 'notes LIKE ?'; + $data->addParam($txtSearch); + } + } + + if ($accountSearchFilter->getCategoryId() !== 0) { + $arrFilterSelect[] = 'categoryId = ?'; + $data->addParam($accountSearchFilter->getCategoryId()); + } + + if ($accountSearchFilter->getClientId() !== 0) { + $arrFilterSelect[] = 'clientId = ?'; + $data->addParam($accountSearchFilter->getClientId()); + } + + $tagsId = $accountSearchFilter->getTagsId(); + $numTags = count($tagsId); + + if ($numTags > 0) { + $tags = str_repeat('?,', $numTags - 1) . '?'; + + $arrFilterSelect[] = 'id IN (SELECT accountId FROM AccountToTag WHERE tagId IN (' . $tags . '))'; + + foreach ($tagsId as $tag) { + $data->addParam($tag); + } + } + + if ($accountSearchFilter->isSearchFavorites() === true) { + $arrayQueryJoin[] = 'INNER JOIN AccountToFavorite AF ON (AF.accountId = id AND AF.userId = ?)'; + $data->addParam($this->session->getUserData()->getId()); + } + + if (count($arrFilterCommon) > 0) { + $arrQueryWhere[] = '(' . implode(' OR ', $arrFilterCommon) . ')'; + } + + if (count($arrFilterSelect) > 0) { + $arrQueryWhere[] = '(' . implode(' AND ', $arrFilterSelect) . ')'; + } + + $arrQueryWhere = array_merge($arrQueryWhere, AccountUtil::getAccountFilterUser($data, $this->session, $accountSearchFilter->getGlobalSearch())); + + if ($accountSearchFilter->getLimitCount() > 0) { + $queryLimit = '?, ?'; + + $data->addParam($accountSearchFilter->getLimitStart()); + $data->addParam($accountSearchFilter->getLimitCount()); + } + + $queryWhere = ''; + + if (count($arrQueryWhere) === 1) { + $queryWhere = implode($arrQueryWhere); + } elseif (count($arrQueryWhere) > 1) { + $queryWhere = implode(' AND ', $arrQueryWhere); + } + + $queryJoin = implode('', $arrayQueryJoin); + + $data->setSelect('*'); + $data->setFrom('account_search_v ' . $queryJoin); + $data->setWhere($queryWhere); + $data->setOrder($accountSearchFilter->getOrderString()); + $data->setLimit($queryLimit); + +// Log::writeNewLog(__FUNCTION__, $Data->getQuery(), Log::DEBUG); +// Log::writeNewLog(__FUNCTION__, print_r($Data->getParams(), true), Log::DEBUG); + + $data->setMapClassName(AccountSearchVData::class); + + return new AccountSearchResponse($this->db->getFullRowCount($data), DbWrapper::getResultsArray($data, $this->db)); + } + + /** + * @param $accountId + * @return array + */ + public function getForUser($accountId) + { + $Data = new QueryData(); + + $queryWhere = AccountUtil::getAccountFilterUser($Data, $this->session); + + if (null !== $accountId) { + $queryWhere[] = 'A.id <> ? AND (A.parentId = 0 OR A.parentId IS NULL)'; + $Data->addParam($accountId); + } + + $query = /** @lang SQL */ + 'SELECT A.id, A.name, C.name AS clientName + FROM Account A + LEFT JOIN Client C ON A.clientId = C.id + WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY name'; + + $Data->setQuery($query); + + return DbWrapper::getResultsArray($Data); + } + + + /** + * @param $accountId + * @return array + */ + public function getLinked($accountId) + { + $Data = new QueryData(); + + $queryWhere = AccountUtil::getAccountFilterUser($Data, $this->session); + + $queryWhere[] = 'A.parentId = ?'; + $Data->addParam($accountId); + + $query = /** @lang SQL */ + 'SELECT A.id, A.name, C.name AS clientName + FROM Account A + INNER JOIN Client C ON A.clientId = C.id + WHERE ' . implode(' AND ', $queryWhere) . ' ORDER BY name'; + + $Data->setQuery($query); + + return DbWrapper::getResultsArray($Data); + } +} \ No newline at end of file diff --git a/lib/SP/Repositories/Account/AccountToUserGroupRepository.php b/lib/SP/Repositories/Account/AccountToUserGroupRepository.php new file mode 100644 index 00000000..661cce0b --- /dev/null +++ b/lib/SP/Repositories/Account/AccountToUserGroupRepository.php @@ -0,0 +1,162 @@ +. + */ + +namespace SP\Repositories\Account; + +use SP\Account\AccountRequest; +use SP\DataModel\UserGroupData; +use SP\Repositories\Repository; +use SP\Repositories\RepositoryItemTrait; +use SP\Storage\DbWrapper; +use SP\Storage\QueryData; + +/** + * Class AccountToUserGroupRepository + * + * @package SP\Repositories\Account + */ +class AccountToUserGroupRepository extends Repository +{ + use RepositoryItemTrait; + + /** + * Obtiene el listado con el nombre de los grupos de una cuenta. + * + * @param int $id con el Id de la cuenta + * @return UserGroupData[] + */ + public function getUserGroupsByAccountId($id) + { + $query = /** @lang SQL */ + 'SELECT G.id, G.name + FROM AccountToUserGroup AUG + INNER JOIN UserGroup G ON AUG.userGroupId = G.id + WHERE AUG.accountId = ? + ORDER BY G.name'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + + return DbWrapper::getResultsArray($Data); + } + + /** + * Obtiene el listado con el nombre de los grupos de una cuenta. + * + * @param $id + * @return UserGroupData[] + */ + public function getUserGroupsByUserGroupId($id) + { + $query = /** @lang SQL */ + 'SELECT G.id, G.name + FROM AccountToUserGroup AUG + INNER JOIN UserGroup G ON AUG.userGroupId = G.id + WHERE AUG.userGroupId = ? + ORDER BY G.name'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + + return DbWrapper::getResultsArray($Data); + } + + /** + * @param $id int + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByUserGroupId($id) + { + $query = /** @lang SQL */ + 'DELETE FROM AccountToUserGroup WHERE userGroupId = ?'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + $Data->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); + + return DbWrapper::getQuery($Data); + } + + /** + * @param AccountRequest $accountRequest + * @return $this + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function update(AccountRequest $accountRequest) + { + $this->deleteByAccountId($accountRequest->id); + $this->add($accountRequest); + + return $this; + } + + /** + * @param $id int + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByAccountId($id) + { + $query = /** @lang SQL */ + 'DELETE FROM AccountToUserGroup WHERE accountId = ?'; + + $Data = new QueryData(); + $Data->setQuery($query); + $Data->addParam($id); + $Data->setOnErrorMessage(__u('Error al eliminar grupos asociados a la cuenta')); + + return DbWrapper::getQuery($Data); + } + + /** + * @param AccountRequest $accountRequest + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function add(AccountRequest $accountRequest) + { + $query = /** @lang SQL */ + 'INSERT INTO AccountToUserGroup (accountId, userGroupId) VALUES ' . $this->getParamsFromArray($accountRequest->userGroups, '(?,?)'); + + $Data = new QueryData(); + $Data->setQuery($query); + + foreach ($accountRequest->userGroups as $userGroup) { + $Data->addParam($accountRequest->id); + $Data->addParam($userGroup); + } + + $Data->setOnErrorMessage(__u('Error al actualizar los grupos secundarios')); + + return DbWrapper::getQuery($Data, $this->db); + } +} \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountHistoryService.php b/lib/SP/Services/Account/AccountHistoryService.php deleted file mode 100644 index a3b89c2e..00000000 --- a/lib/SP/Services/Account/AccountHistoryService.php +++ /dev/null @@ -1,427 +0,0 @@ -. - */ - -namespace SP\Services\Account; - -use SP\Account\AccountUtil; -use SP\Config\ConfigDB; -use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SPException; -use SP\DataModel\AccountHistoryData; -use SP\DataModel\AccountPassData; -use SP\DataModel\ItemSearchData; -use SP\Services\Service; -use SP\Services\ServiceItemInterface; -use SP\Services\ServiceItemTrait; -use SP\Storage\DbWrapper; -use SP\Storage\QueryData; - -/** - * Class AccountHistoryService - * - * @package Services - */ -class AccountHistoryService extends Service implements ServiceItemInterface -{ - use ServiceItemTrait; - - /** - * Obtiene el listado del histórico de una cuenta. - * - * @param $id - * @return array|false Con los registros con id como clave y fecha - usuario como valor - */ - public function getHistoryForAccount($id) - { - $query = /** @lang SQL */ - 'SELECT acchistory_id,' - . 'acchistory_dateEdit,' - . 'u1.user_login AS user_edit,' - . 'u2.user_login AS user_add,' - . 'acchistory_dateAdd ' - . 'FROM accHistory ' - . 'LEFT JOIN usrData u1 ON acchistory_userEditId = u1.user_id ' - . 'LEFT JOIN usrData u2 ON acchistory_userId = u2.user_id ' - . 'WHERE acchistory_accountId = ? ' - . 'ORDER BY acchistory_id DESC'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - $items = []; - - foreach (DbWrapper::getResultsArray($Data, $this->db) as $history) { - // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición) - if (empty($history->acchistory_dateEdit) || $history->acchistory_dateEdit === '0000-00-00 00:00:00') { - $date = $history->acchistory_dateAdd . ' - ' . $history->user_add; - } else { - $date = $history->acchistory_dateEdit . ' - ' . $history->user_edit; - } - - $items[$history->acchistory_id] = $date; - } - - return $items; - } - - /** - * @param $id - * @return AccountPassData - */ - public function getPasswordForHistoryId($id) - { - $Data = new QueryData(); - $Data->setMapClassName(AccountPassData::class); - $Data->setLimit(1); - - $Data->setSelect('acchistory_id AS account_id, acchistory_name AS account_name, acchistory_login AS account_login, acchistory_pass AS account_pass, acchistory_key AS account_key, acchistory_parentId AS account_parentId'); - $Data->setFrom('accHistory'); - - $queryWhere = AccountUtil::getAccountHistoryFilterUser($Data, $this->session); - $queryWhere[] = 'acchistory_id = ?'; - $Data->addParam($id); - - $Data->setWhere($queryWhere); - - return DbWrapper::getResults($Data, $this->db); - } - - /** - * @param array $items array of ['id' => , 'isDelete' => ] - * @throws QueryException - * @throws \SP\Core\Exceptions\ConstraintException - */ - public function createBatch(array $items) - { - foreach ($items as $item) { - $this->create($item); - } - } - - /** - * Crea una nueva cuenta en la BBDD - * - * @param array $itemData ['id' => , 'isDelete' => ] - * @return bool - * @throws QueryException - * @throws \SP\Core\Exceptions\ConstraintException - */ - public function create($itemData) - { - $Data = new QueryData(); - $Data->addParam(($itemData['isDelete'] === false) ? 1 : 0); - $Data->addParam(($itemData['isDelete'] === true) ? 1 : 0); - $Data->addParam(ConfigDB::getValue('masterPwd')); - - - $querySelect = /** @lang SQL */ - 'SELECT account_id,' - . 'account_categoryId,' - . 'account_customerId,' - . 'account_name,' - . 'account_login,' - . 'account_url,' - . 'account_pass,' - . 'account_key,' - . 'account_notes,' - . 'account_countView,' - . 'account_countDecrypt,' - . 'account_dateAdd,' - . 'account_dateEdit,' - . 'account_userId,' - . 'account_userGroupId,' - . 'account_userEditId,' - . 'account_otherUserEdit,' - . 'account_otherGroupEdit,' - . 'account_isPrivate,' - . 'account_isPrivateGroup,' - . '?,?,? ' - . 'FROM accounts WHERE account_id = ?'; - - $Data->addParam($itemData['id']); - - $query = /** @lang SQL */ - 'INSERT INTO accHistory ' - . '(acchistory_accountId,' - . 'acchistory_categoryId,' - . 'acchistory_customerId,' - . 'acchistory_name,' - . 'acchistory_login,' - . 'acchistory_url,' - . 'acchistory_pass,' - . 'acchistory_key,' - . 'acchistory_notes,' - . 'acchistory_countView,' - . 'acchistory_countDecrypt,' - . 'acchistory_dateAdd,' - . 'acchistory_dateEdit,' - . 'acchistory_userId,' - . 'acchistory_userGroupId,' - . 'acchistory_userEditId,' - . 'acchistory_otherUserEdit,' - . 'acchistory_otherGroupEdit,' - . 'accHistory_isPrivate,' - . 'accHistory_isPrivateGroup,' - . 'acchistory_isModify,' - . 'acchistory_isDeleted,' - . 'acchistory_mPassHash)'; - - $Data->setQuery($query . ' ' . $querySelect); - $Data->setOnErrorMessage(__u('Error al actualizar el historial')); - - return DbWrapper::getQuery($Data, $this->db); - } - - /** - * @param array $ids - * @throws SPException - */ - public function deleteBatch(array $ids) - { - foreach ($ids as $id) { - $this->delete($id); - } - } - - /** - * Elimina los datos de una cuenta en la BBDD. - * - * @param array|int $id - * @return bool Los ids de las cuentas eliminadas - * @throws SPException - */ - public function delete($id) - { - $Data = new QueryData(); - - $query = /** @lang SQL */ - 'DELETE FROM accHistory WHERE acchistory_id = ? LIMIT 1'; - - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar la cuenta')); - - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() === 1; - } - - /** - * Updates an item - * - * @param mixed $itemData - * @return mixed - */ - public function update($itemData) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Returns the item for given id - * - * @param int $id - * @return AccountHistoryData - * @throws SPException - */ - public function getById($id) - { - $query = /** @lang SQL */ - 'SELECT acchistory_accountId AS account_id,' - . 'acchistory_customerId AS account_customerId,' - . 'acchistory_categoryId AS account_categoryId,' - . 'acchistory_name AS account_name,' - . 'acchistory_login AS account_login,' - . 'acchistory_url AS account_url,' - . 'acchistory_pass AS account_pass,' - . 'acchistory_key AS account_key,' - . 'acchistory_notes AS account_notes,' - . 'acchistory_countView AS account_countView,' - . 'acchistory_countDecrypt AS account_countDecrypt,' - . 'acchistory_dateAdd AS account_dateAdd,' - . 'acchistory_dateEdit AS account_dateEdit,' - . 'acchistory_userId AS account_userId,' - . 'acchistory_userGroupId AS account_userGroupId,' - . 'acchistory_userEditId AS account_userEditId,' - . 'acchistory_isModify,' - . 'acchistory_isDeleted,' - . 'acchistory_otherUserEdit + 0 AS account_otherUserEdit,' - . 'acchistory_otherGroupEdit + 0 AS account_otherGroupEdit,' - . 'acchistory_isPrivate + 0 AS account_isPrivate,' - . 'acchistory_isPrivateGroup + 0 AS account_isPrivateGroup,' - . 'u1.user_name,' - . 'u1.user_login,' - . 'usergroup_name,' - . 'u2.user_name AS user_editName,' - . 'u2.user_login AS user_editLogin,' - . 'category_name, customer_name ' - . 'FROM accHistory ' - . 'LEFT JOIN categories ON acchistory_categoryId = category_id ' - . 'LEFT JOIN usrGroups ON acchistory_userGroupId = usergroup_id ' - . 'LEFT JOIN usrData u1 ON acchistory_userId = u1.user_id ' - . 'LEFT JOIN usrData u2 ON acchistory_userEditId = u2.user_id ' - . 'LEFT JOIN customers ON acchistory_customerId = customer_id ' - . 'WHERE acchistory_id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->setMapClassName(AccountHistoryData::class); - $Data->addParam($id); - - $queryRes = DbWrapper::getResults($Data, $this->db); - - if ($queryRes === false) { - throw new SPException(SPException::SP_CRITICAL, __u('No se pudieron obtener los datos de la cuenta')); - } - - return $queryRes; - } - - /** - * Returns all the items - * - * @return array - */ - public function getAll() - { - $query = /** @lang SQL */ - 'SELECT acchistory_id,' - . 'acchistory_dateEdit,' - . 'u1.user_login AS user_edit,' - . 'u2.user_login AS user_add,' - . 'acchistory_dateAdd ' - . 'FROM accHistory ' - . 'LEFT JOIN usrData u1 ON acchistory_userEditId = u1.user_id ' - . 'LEFT JOIN usrData u2 ON acchistory_userId = u2.user_id ' - . 'ORDER BY acchistory_id DESC'; - - $Data = new QueryData(); - $Data->setQuery($query); - - $items = []; - - foreach (DbWrapper::getResultsArray($Data, $this->db) as $history) { - // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición) - if (empty($history->acchistory_dateEdit) || $history->acchistory_dateEdit === '0000-00-00 00:00:00') { - $date = $history->acchistory_dateAdd . ' - ' . $history->user_add; - } else { - $date = $history->acchistory_dateEdit . ' - ' . $history->user_edit; - } - - $items[$history->acchistory_id] = $date; - } - - return $items; - } - - /** - * Returns all the items for given ids - * - * @param array $ids - * @return void - */ - public function getByIdBatch(array $ids) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Deletes all the items for given ids - * - * @param array $ids - * @return void - */ - public function deleteByIdBatch(array $ids) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Checks whether the item is in use or not - * - * @param $id int - * @return void - */ - public function checkInUse($id) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Checks whether the item is duplicated on updating - * - * @param mixed $itemData - * @return void - */ - public function checkDuplicatedOnUpdate($itemData) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Checks whether the item is duplicated on adding - * - * @param mixed $itemData - * @return void - */ - public function checkDuplicatedOnAdd($itemData) - { - throw new \RuntimeException('Not implemented'); - } - - /** - * Searches for items by a given filter - * - * @param ItemSearchData $SearchData - * @return mixed - */ - public function search(ItemSearchData $SearchData) - { - $Data = new QueryData(); - $Data->setSelect('acchistory_id, acchistory_name, customer_name, IFNULL(acchistory_dateEdit,acchistory_dateAdd) as acchistory_date, BIN(acchistory_isModify) as acchistory_isModify, BIN(acchistory_isDeleted) as acchistory_isDeleted'); - $Data->setFrom('accHistory LEFT JOIN customers ON acchistory_customerId = customer_id'); - $Data->setOrder('acchistory_name, customer_name, acchistory_id DESC'); - - if ($SearchData->getSeachString() !== '') { - $Data->setWhere('acchistory_name LIKE ? OR customer_name LIKE ?'); - - $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); - } - - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); - - DbWrapper::setFullRowCount(); - - $queryRes = DbWrapper::getResultsArray($Data, $this->db); - - $queryRes['count'] = $Data->getQueryNumRows(); - - return $queryRes; - } -} \ No newline at end of file diff --git a/lib/SP/Services/Auth/LoginService.php b/lib/SP/Services/Auth/LoginService.php new file mode 100644 index 00000000..f667667b --- /dev/null +++ b/lib/SP/Services/Auth/LoginService.php @@ -0,0 +1,574 @@ +. + */ + +namespace SP\Services\Auth; + +defined('APP_ROOT') || die(); + +use Defuse\Crypto\Exception\BadFormatException; +use Defuse\Crypto\Exception\CryptoException; +use SP\Providers\Auth\Auth; +use SP\Providers\Auth\AuthResult; +use SP\Providers\Auth\AuthUtil; +use SP\Providers\Auth\Browser\BrowserAuthData; +use SP\Providers\Auth\Database\DatabaseAuthData; +use SP\Providers\Auth\Ldap\LdapAuthData; +use SP\Bootstrap; +use SP\Config\Config; +use SP\Core\Events\EventDispatcher; +use SP\Core\Exceptions\AuthException; +use SP\Core\Exceptions\SPException; +use SP\Core\Language; +use SP\Core\Messages\LogMessage; +use SP\Core\Session\Session; +use SP\Core\Traits\InjectableTrait; +use SP\Core\UI\Theme; +use SP\Crypt\TemporaryMasterPass; +use SP\DataModel\TrackData; +use SP\DataModel\UserLoginData; +use SP\DataModel\UserPreferencesData; +use SP\Http\JsonResponse; +use SP\Http\Request; +use SP\Log\Log; +use SP\Mgmt\Tracks\Track; +use SP\Services\Service; +use SP\Services\User\UserLoginRequest; +use SP\Services\User\UserPassService; +use SP\Services\User\UserService; +use SP\Services\UserPassRecover\UserPassRecoverService; +use SP\Services\UserProfile\UserProfileService; +use SP\Util\HttpUtil; +use SP\Util\Json; +use SP\Util\Util; + +/** + * Class LoginService + * + * @package SP\Services + */ +class LoginService +{ + use InjectableTrait; + + /** + * Estados + */ + const STATUS_INVALID_LOGIN = 1; + const STATUS_INVALID_MASTER_PASS = 2; + const STATUS_USER_DISABLED = 3; + const STATUS_NEED_OLD_PASS = 5; + const STATUS_MAX_ATTEMPTS_EXCEEDED = 6; + + /** + * Tiempo para contador de intentos + */ + const TIME_TRACKING = 600; + const TIME_TRACKING_MAX_ATTEMPTS = 5; + + /** + * @var JsonResponse + */ + protected $jsonResponse; + /** + * @var UserLoginData + */ + protected $userLoginData; + /** + * @var LogMessage + */ + protected $LogMessage; + /** + * @var $ConfigData + */ + protected $configData; + /** + * @var Config + */ + protected $config; + /** + * @var Theme + */ + protected $theme; + /** + * @var UserService + */ + protected $userService; + /** + * @var Session + */ + private $session; + /** + * @var EventDispatcher + */ + private $eventDispatcher; + + /** + * LoginController constructor. + * + * @param Config $config + * @param Session $session + * @param Theme $theme + * @param EventDispatcher $eventDispatcher + */ + public function __construct(Config $config, Session $session, Theme $theme, EventDispatcher $eventDispatcher) + { + $this->injectDependencies(); + + $this->config = $config; + $this->configData = $config->getConfigData(); + $this->theme = $theme; + $this->session = $session; + $this->eventDispatcher = $eventDispatcher; + + $this->userService = new UserService(); + $this->jsonResponse = new JsonResponse(); + $this->LogMessage = new LogMessage(); + $this->userLoginData = new UserLoginData(); + $this->LogMessage->setAction(__u('Inicio sesión')); + } + + /** + * Ejecutar las acciones de login + * + * @return JsonResponse + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + public function doLogin() + { + $this->userLoginData->setLoginUser(Request::analyze('user')); + $this->userLoginData->setLoginPass(Request::analyzeEncrypted('pass')); + + $Log = new Log($this->LogMessage); + + try { + $this->checkTracking(); + + $auth = new Auth($this->userLoginData, $this->configData); + + if (($result = $auth->doAuth()) !== false) { + // Ejecutar la acción asociada al tipo de autentificación + + /** @var AuthResult $authResult */ + foreach ($result as $authResult) { + if ($authResult->isAuthGranted() === true + && $this->{$authResult->getAuth()}($authResult->getData()) === true) { + break; + } + } + } else { + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, __u('Login incorrecto'), '', self::STATUS_INVALID_LOGIN); + } + + $this->checkUser(); + $this->loadMasterPass(); + $this->setUserSession(); + $this->loadUserPreferences(); + $this->cleanUserData(); + } catch (SPException $e) { + $Log->setLogLevel(Log::ERROR); + $Log->writeLog(); + + $this->jsonResponse->setDescription($e->getMessage()); + $this->jsonResponse->setStatus($e->getCode()); + + Json::returnJson($this->jsonResponse); + } + + $forward = Request::getRequestHeaders('X-Forwarded-For'); + + if ($forward) { + $this->LogMessage->addDetails('X-Forwarded-For', $this->configData->isDemoEnabled() ? '***' : $forward); + } + + $Log->writeLog(); + +// $data = ['url' => 'index.php' . Request::importUrlParamsToGet()]; + $data = ['url' => 'index.php?r=index']; + $this->jsonResponse->setStatus(JsonResponse::JSON_SUCCESS); + $this->jsonResponse->setData($data); + + return $this->jsonResponse; + } + + /** + * Comprobar los intentos de login + * + * @throws \SP\Core\Exceptions\AuthException + */ + private function checkTracking() + { + try { + $TrackData = new TrackData(); + $TrackData->setSource('Login'); + $TrackData->setTrackIp(HttpUtil::getClientAddress()); + + $attempts = count(Track::getItem($TrackData)->getTracksForClientFromTime(time() - self::TIME_TRACKING)); + } catch (SPException $e) { + $this->LogMessage->addDescription($e->getMessage()); + $this->LogMessage->addDescription($e->getHint()); + + throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR); + } + + if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) { + $this->addTracking(); + + sleep(0.3 * $attempts); + + $this->LogMessage->addDescription(sprintf(__('Intentos excedidos (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS)); + + throw new AuthException(SPException::SP_INFO, __u('Intentos excedidos'), '', self::STATUS_MAX_ATTEMPTS_EXCEEDED); + } + } + + /** + * Añadir un seguimiento + * + * @throws \SP\Core\Exceptions\AuthException + */ + private function addTracking() + { + try { + $TrackData = new TrackData(); + $TrackData->setSource('Login'); + $TrackData->setTrackIp(HttpUtil::getClientAddress()); + + Track::getItem($TrackData)->add(); + } catch (SPException $e) { + throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR); + } + } + + /** + * Comprobar estado del usuario + * + * @throws \SP\Core\Exceptions\SPException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \SP\Core\Exceptions\AuthException + */ + protected function checkUser() + { + $userLoginResponse = $this->userLoginData->getUserLoginResponse(); + + // Comprobar si el usuario está deshabilitado + if ($userLoginResponse->getIsDisabled()) { + $this->LogMessage->addDescription(__u('Usuario deshabilitado')); + $this->LogMessage->addDetails(__u('Usuario'), $userLoginResponse->getLogin()); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, __u('Usuario deshabilitado'), '', self::STATUS_USER_DISABLED); + } + + // Comprobar si se ha forzado un cambio de clave + if ($userLoginResponse->getIsChangePass()) { + $hash = Util::generateRandomBytes(16); + + (new UserPassRecoverService())->add($userLoginResponse->getId(), $hash); + + $this->jsonResponse->setData(['url' => Bootstrap::$WEBURI . '/index.php?u=userPassReset/change/' . $hash]); + $this->jsonResponse->setStatus(0); + Json::returnJson($this->jsonResponse); + } + } + + /** + * Cargar la clave maestra o solicitarla + * + * @throws AuthException + * @throws SPException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + protected function loadMasterPass() + { + $temporaryMasterPass = new TemporaryMasterPass(); + $userPassService = new UserPassService(); + + $masterPass = Request::analyzeEncrypted('mpass'); + $oldPass = Request::analyzeEncrypted('oldpass'); + + try { + if ($masterPass) { + if ($temporaryMasterPass->check($masterPass)) { + $this->LogMessage->addDescription(__u('Usando clave temporal')); + + $masterPass = $temporaryMasterPass->getUsingKey($masterPass); + } + + if ($userPassService->updateMasterPass($masterPass, $this->userLoginData)->getStatus() !== UserPassService::MPASS_OK) { + $this->LogMessage->addDescription(__u('Clave maestra incorrecta')); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS); + } + + $this->LogMessage->addDescription(__u('Clave maestra actualizada')); + } else if ($oldPass) { + if (!$userPassService->updateMasterPassFromOldPass($oldPass, $this->userLoginData)->getStatus() !== UserPassService::MPASS_OK) { + $this->LogMessage->addDescription(__u('Clave maestra incorrecta')); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS); + } + + $this->LogMessage->addDescription(__u('Clave maestra actualizada')); + } else { + switch ($userPassService->loadUserMPass($this->userLoginData)->getStatus()) { + case UserPassService::MPASS_CHECKOLD: + throw new AuthException(SPException::SP_INFO, __u('Es necesaria su clave anterior'), '', self::STATUS_NEED_OLD_PASS); + break; + case UserPassService::MPASS_NOTSET: + case UserPassService::MPASS_CHANGED: + case UserPassService::MPASS_WRONG: + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, __u('La clave maestra no ha sido guardada o es incorrecta'), '', self::STATUS_INVALID_MASTER_PASS); + break; + } + } + } catch (BadFormatException $e) { + $this->LogMessage->addDescription(__u('Clave maestra incorrecta')); + + throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS); + } catch (CryptoException $e) { + $this->LogMessage->addDescription(__u('Error interno')); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), $e->getMessage(), Service::STATUS_INTERNAL_ERROR); + } + } + + /** + * Cargar la sesión del usuario + * + * @throws \SP\Core\Exceptions\SPException + */ + protected function setUserSession() + { + $userLoginResponse = $this->userLoginData->getUserLoginResponse(); + + // Actualizar el último login del usuario + $this->userService->updateLastLoginById($userLoginResponse->getId()); + + // Cargar las variables de ussuario en la sesión + $this->session->setUserData($userLoginResponse); + $this->session->setUserProfile((new UserProfileService())->getById($userLoginResponse->getUserProfileId())); + + if ($this->configData->isDemoEnabled()) { + $userLoginResponse->setPreferences(new UserPreferencesData()); + } + + $this->LogMessage->addDetails(__u('Usuario'), $userLoginResponse->getLogin()); + } + + /** + * Cargar las preferencias del usuario y comprobar si usa 2FA + * + * @throws \SP\Core\Exceptions\SPException + * @throws \SP\Core\Exceptions\InvalidArgumentException + */ + protected function loadUserPreferences() + { + Language::setLanguage(true); + + $this->theme->initTheme(true); + +// SessionFactory::setSessionType(SessionFactory::SESSION_INTERACTIVE); + + $this->session->setAuthCompleted(true); + + $this->eventDispatcher->notifyEvent('login.preferences', $this); + } + + /** + * Limpiar datos de usuario + */ + private function cleanUserData() + { + $this->userLoginData->setUserLoginResponse(); + } + + /** + * Autentificación LDAP + * + * @param LdapAuthData $AuthData + * @return bool + * @throws \SP\Core\Exceptions\SPException + * @throws AuthException + */ + protected function authLdap(LdapAuthData $AuthData) + { + if ($AuthData->getStatusCode() > 0) { + $this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__); + $this->LogMessage->addDetails(__u('Usuario'), $this->userLoginData->getLoginUser()); + + if ($AuthData->getStatusCode() === 49) { + $this->LogMessage->addDescription(__u('Login incorrecto')); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN); + } + + if ($AuthData->getStatusCode() === 701) { + $this->LogMessage->addDescription(__u('Cuenta expirada')); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED); + } + + if ($AuthData->getStatusCode() === 702) { + $this->LogMessage->addDescription(__u('El usuario no tiene grupos asociados')); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED); + } + + if ($AuthData->isAuthGranted() === false) { + return false; + } + + $this->LogMessage->addDescription(__u('Error interno')); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', Service::STATUS_INTERNAL_ERROR); + } + + $this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__); + $this->LogMessage->addDetails(__u('Servidor LDAP'), $AuthData->getServer()); + + try { + $userLoginRequest = new UserLoginRequest(); + $userLoginRequest->setLogin($this->userLoginData->getLoginUser()); + $userLoginRequest->setPassword($this->userLoginData->getLoginPass()); + $userLoginRequest->setEmail($AuthData->getEmail()); + $userLoginRequest->setName($AuthData->getName()); + $userLoginRequest->setIsLdap(1); + + + // Verificamos si el usuario existe en la BBDD + if ($this->userService->checkExistsByLogin($this->userLoginData->getLoginUser())) { + // Actualizamos el usuario de LDAP en MySQL + $this->userService->updateOnLogin($userLoginRequest); + } else { + // Creamos el usuario de LDAP en MySQL + $this->userService->createOnLogin($userLoginRequest); + } + } catch (SPException $e) { + $this->LogMessage->addDescription($e->getMessage()); + + throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR); + } + + return true; + } + + /** + * Autentificación en BD + * + * @param DatabaseAuthData $AuthData + * @return bool + * @throws \SP\Core\Exceptions\SPException + * @throws AuthException + */ + protected function authDatabase(DatabaseAuthData $AuthData) + { + // Autentificamos con la BBDD + if ($AuthData->getAuthenticated() === 0) { + if ($AuthData->isAuthGranted() === false) { + return false; + } + + $this->LogMessage->addDescription(__u('Login incorrecto')); + $this->LogMessage->addDetails(__u('Usuario'), $this->userLoginData->getLoginUser()); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN); + } + + if ($AuthData->getAuthenticated() === 1) { + $this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__); + } + + return true; + } + + /** + * Comprobar si el cliente ha enviado las variables de autentificación + * + * @param BrowserAuthData $AuthData + * @return mixed + * @throws AuthException + */ + protected function authBrowser(BrowserAuthData $AuthData) + { + // Comprobar si concide el login con la autentificación del servidor web + if ($AuthData->getAuthenticated() === 0) { + if ($AuthData->isAuthGranted() === false) { + return false; + } + + $this->LogMessage->addDescription(__u('Login incorrecto')); + $this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__); + $this->LogMessage->addDetails(__u('Usuario'), $this->userLoginData->getLoginUser()); + $this->LogMessage->addDetails(__u('Autentificación'), sprintf('%s (%s)', AuthUtil::getServerAuthType(), $AuthData->getName())); + + $this->addTracking(); + + throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN); + } + + $this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__); + + if ($this->configData->isAuthBasicAutoLoginEnabled()) { + try { + $userLoginRequest = new UserLoginRequest(); + $userLoginRequest->setLogin($this->userLoginData->getLoginUser()); + $userLoginRequest->setPassword($this->userLoginData->getLoginPass()); + + // Verificamos si el usuario existe en la BBDD + if ($this->userService->checkExistsByLogin($this->userLoginData->getLoginUser())) { + // Actualizamos el usuario de SSO en la BBDD + $this->userService->updateOnLogin($userLoginRequest); + } else { + // Creamos el usuario de SSO en la BBDD + $this->userService->createOnLogin($userLoginRequest); + } + } catch (SPException $e) { + throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR); + } + + $this->LogMessage->addDetails(__u('Usuario'), $this->userLoginData->getLoginUser()); + $this->LogMessage->addDetails(__u('Autentificación'), sprintf('%s (%s)', AuthUtil::getServerAuthType(), $AuthData->getName())); + + return true; + } + + return null; + } +} \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldDefService.php b/lib/SP/Services/CustomField/CustomFieldDefService.php deleted file mode 100644 index 73571741..00000000 --- a/lib/SP/Services/CustomField/CustomFieldDefService.php +++ /dev/null @@ -1,311 +0,0 @@ -. - */ - -namespace SP\Services\CustomField; - -use SP\Core\Acl\ActionsInterface; -use SP\Core\Exceptions\SPException; -use SP\DataModel\CustomFieldDefData; -use SP\DataModel\ItemSearchData; -use SP\Services\Service; -use SP\Services\ServiceItemInterface; -use SP\Services\ServiceItemTrait; -use SP\Storage\DbWrapper; -use SP\Storage\QueryData; - -/** - * Class CustomFieldDefService - * - * @package SP\Services\CustomField - */ -class CustomFieldDefService extends Service implements ServiceItemInterface -{ - use ServiceItemTrait; - - /** - * @param $id - * @return mixed - */ - public static function getFieldModuleById($id) - { - $modules = self::getFieldModules(); - - return isset($modules[$id]) ? $modules[$id] : $id; - } - - /** - * Devuelve los módulos disponibles para los campos personalizados - * - * @return array - */ - public static function getFieldModules() - { - $modules = [ - ActionsInterface::ACCOUNT => __('Cuentas'), - ActionsInterface::CATEGORY => __('Categorías'), - ActionsInterface::CLIENT => __('Clientes'), - ActionsInterface::USER => __('Usuarios'), - ActionsInterface::GROUP => __('Grupos') - - ]; - - return $modules; - } - - /** - * Creates an item - * - * @param CustomFieldDefData $itemData - * @return mixed - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function create($itemData) - { - $query = /** @lang SQL */ - 'INSERT INTO customFieldsDef 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')); - - DbWrapper::getQuery($Data, $this->db); - - return $this->db->getLastId(); - } - - /** - * Updates an item - * - * @param CustomFieldDefData $itemData - * @return mixed - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function update($itemData) - { - $query = /** @lang SQL */ - 'UPDATE customFieldsDef - 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')); - - return DbWrapper::getQuery($Data, $this->db); - } - - /** - * Returns the item for given id - * - * @param int $id - * @return CustomFieldDefData - */ - public function getById($id) - { - $query = /** @lang SQL */ - 'SELECT id, name, moduleId, required, help, showInList, typeId - FROM customFieldsDef - WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefData::class); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getResults($Data, $this->db); - } - - /** - * Returns all the items - * - * @return CustomFieldDefData[] - */ - public function getAll() - { - $query = /** @lang SQL */ - 'SELECT id, name, moduleId, required, help, showInList - FROM customFieldsDef - ORDER BY moduleId'; - - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefData::class); - $Data->setQuery($query); - - return DbWrapper::getResultsArray($Data, $this->db); - } - - /** - * Returns all the items for given ids - * - * @param array $ids - * @return array - */ - public function getByIdBatch(array $ids) - { - $query = /** @lang SQL */ - 'SELECT id, name, moduleId, required, help, showInList, typeId - FROM customFieldsDef - WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; - - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefData::class); - $Data->setQuery($query); - $Data->setParams($ids); - - return DbWrapper::getResults($Data, $this->db); - } - - /** - * Deletes all the items for given ids - * - * @param array $ids - * @return void - * @throws SPException - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function deleteByIdBatch(array $ids) - { - foreach ($ids as $id) { - $this->delete($id); - } - } - - /** - * Deletes an item - * - * @param $id - * @return bool - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Core\Exceptions\SPException - */ - public function delete($id) - { - if ($this->deleteItemsDataForDefinition($id) === false) { - throw new SPException(SPException::SP_ERROR, __u('Error al eliminar el campo personalizado')); - } - - $query = /** @lang SQL */ - 'DELETE FROM customFieldsDef WHERE id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el campo personalizado')); - - return DbWrapper::getQuery($Data, $this->db); - } - - /** - * Eliminar los datos de los elementos de una definición - * - * @param $id - * @return bool - * @throws \SP\Core\Exceptions\SPException - */ - protected function deleteItemsDataForDefinition($id) - { - $query = /** @lang SQL */ - 'DELETE FROM customFieldsData WHERE id = ?'; - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - - return DbWrapper::getQuery($Data, $this->db); - } - - /** - * 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 $SearchData - * @return CustomFieldDefData[] - */ - public function search(ItemSearchData $SearchData) - { - $Data = new QueryData(); - $Data->setMapClassName(CustomFieldDefData::class); - $Data->setSelect('a.id, a.name, a.moduleId, a.required, a.help, a.showInList, a.typeId, b.name AS typeName'); - $Data->setFrom('customFieldsDef a INNER JOIN customFieldsType b ON b.id = a.typeId'); - $Data->setOrder('moduleId'); - - $Data->setLimit('?,?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); - - DbWrapper::setFullRowCount(); - - /** @var CustomFieldDefData[] $queryRes */ - $queryRes = DbWrapper::getResultsArray($Data, $this->db); - - $queryRes['count'] = $Data->getQueryNumRows(); - - return $queryRes; - } -} \ No newline at end of file diff --git a/lib/SP/Services/ServiceItemTrait.php b/lib/SP/Services/ServiceItemTrait.php index 36f1c24c..a3ef1c7d 100644 --- a/lib/SP/Services/ServiceItemTrait.php +++ b/lib/SP/Services/ServiceItemTrait.php @@ -2,9 +2,9 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org - * @copyright 2012-2017, Rubén Domínguez nuxsmin@$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,111 +24,40 @@ namespace SP\Services; -use SP\Core\Exceptions\SPException; use SP\DataModel\DataModelInterface; -use SP\Storage\DBUtil; +use SP\Repositories\RepositoryItemInterface; /** - * Class ItemTrait + * Trait ServiceItemTrait * - * @package SP\Mgmt + * @package SP\Services */ trait ServiceItemTrait { - /** - * Cache de elementos para select - * - * @var array - */ - private static $itemsSelectCache; - - /** - * Returns service items for a select - * - * @return mixed - */ - public static function getServiceItems() - { - $service = new static(); - return $service->getItemsForSelect(); - } - /** * Devolver los elementos para un campo select * - * @param bool $useCache Usar la cache de elementos si está creada + * @param RepositoryItemInterface $repositoryItem * @return array */ - public function getItemsForSelect($useCache = true) + public function getItemsForSelect(RepositoryItemInterface $repositoryItem) { - // Usar cache si está creada - if ($useCache === true && is_array(self::$itemsSelectCache)) { - return self::$itemsSelectCache; - } - - self::$itemsSelectCache = []; + $items = []; /** @var DataModelInterface $item */ - /** @var ServiceItemInterface $this */ - foreach ($this->getAll() as $item) { + foreach ($repositoryItem->getAll() as $item) { $obj = new \stdClass(); $obj->id = (int)$item->getId(); $obj->name = $item->getName(); - self::$itemsSelectCache[] = $obj; - } - - return self::$itemsSelectCache; - } - - /** - * Eliminar elementos en lotes - * - * @param $ids - * @return array - */ - public function deleteBatch(array $ids) - { - /** @var ServiceItemInterface $this */ - $items = $this->getByIdBatch($ids); - - /** @var DataModelInterface[] $items */ - foreach ($items as $key => $item) { - try { - $this->delete($item->getId()); - } catch (SPException $e) { - unset($items[$key]); - } + $items[] = $obj; } return $items; } /** - * Crear un hash con el nombre del elemento. - * - * Esta función crear un hash para detectar nombres de elementos duplicados mediante - * la eliminación de carácteres especiales y capitalización - * - * @param $name - * @return string con el hash generado + * Returns all the items mapping fields for a select type element (id and name fields) */ - protected function makeItemHash($name) - { - $charsSrc = ['.', ' ', '_', ', ', '-', ';', '\'', '"', ':', '(', ')', '|', '/']; - - return md5(strtolower(str_replace($charsSrc, '', DBUtil::escape($name)))); - } - - /** - * Devuelve una cadena con los parámetros para una consulta SQL desde un array - * - * @param array $items - * @param string $string Cadena a utilizar para los parámetros - * @return string - */ - protected function getParamsFromArray(array $items, $string = '?') - { - return implode(',', array_fill(0, count($items), $string)); - } + abstract public function getAllItemsForSelect(); } \ No newline at end of file diff --git a/lib/SP/Services/User/UserPassResponse.php b/lib/SP/Services/User/UserPassResponse.php new file mode 100644 index 00000000..91649ab3 --- /dev/null +++ b/lib/SP/Services/User/UserPassResponse.php @@ -0,0 +1,126 @@ +. + */ + +namespace SP\Services\User; + +/** + * Class UserPassResponse + * + * @package SP\DataModel\Dto + */ +class UserPassResponse +{ + /** + * @var int + */ + private $status; + /** + * @var string + */ + private $cryptMasterPass; + /** + * @var string + */ + private $cryptSecuredKey; + /** + * @var string + */ + private $clearMasterPass; + + /** + * UserPassResponse constructor. + * + * @param int $status + * @param string $clearUserMPass + */ + public function __construct($status, $clearUserMPass = null) + { + $this->status = $status; + $this->clearMasterPass = $clearUserMPass; + } + + /** + * @return int + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param int $status + */ + public function setStatus($status) + { + $this->status = $status; + } + + /** + * @return string + */ + public function getCryptMasterPass() + { + return $this->cryptMasterPass; + } + + /** + * @param string $cryptMasterPass + */ + public function setCryptMasterPass($cryptMasterPass) + { + $this->cryptMasterPass = $cryptMasterPass; + } + + /** + * @return string + */ + public function getCryptSecuredKey() + { + return $this->cryptSecuredKey; + } + + /** + * @param string $cryptSecuredKey + */ + public function setCryptSecuredKey($cryptSecuredKey) + { + $this->cryptSecuredKey = $cryptSecuredKey; + } + + /** + * @return string + */ + public function getClearMasterPass() + { + return $this->clearMasterPass; + } + + /** + * @param string $clearMasterPass + */ + public function setClearMasterPass($clearMasterPass) + { + $this->clearMasterPass = $clearMasterPass; + } +} \ No newline at end of file diff --git a/lib/SP/Services/User/UserPassService.php b/lib/SP/Services/User/UserPassService.php new file mode 100644 index 00000000..f320f313 --- /dev/null +++ b/lib/SP/Services/User/UserPassService.php @@ -0,0 +1,255 @@ +. + */ + +namespace SP\Services\User; + +use Defuse\Crypto\Exception\CryptoException; +use SP\Config\Config; +use SP\Config\ConfigData; +use SP\Core\Crypt\Crypt; +use SP\Core\Crypt\Hash; +use SP\Core\Exceptions\SPException; +use SP\Core\Traits\InjectableTrait; +use SP\Core\Upgrade\User as UpgradeUser; +use SP\DataModel\UserLoginData; +use SP\Core\Upgrade\Crypt as CryptUpgrade; +use SP\Core\Crypt\Session as CryptSession; +use SP\Repositories\User\UserRepository; +use SP\Services\Config\ConfigService; +use SP\Services\Service; + +/** + * Class UserPassService + * + * @package SP\Services\User + */ +class UserPassService +{ + use InjectableTrait; + + // La clave maestra incorrecta + const MPASS_WRONG = 0; + // La clave maestra correcta + const MPASS_OK = 1; + // La clave maestra no está guardada + const MPASS_NOTSET = 2; + // La clave maestra ha cambiado + const MPASS_CHANGED = 3; + // Comprobar la clave maestra con la clave del usuario anterior + const MPASS_CHECKOLD = 4; + + /** + * @var ConfigData + */ + protected $configData; + /** + * @var UserRepository + */ + protected $userRepository; + /** + * @var ConfigService + */ + protected $configService; + + /** + * UserPassService constructor. + */ + public function __construct() + { + $this->injectDependencies(); + } + + /** + * @param Config $config + * @param UserRepository $userRepository + * @param ConfigService $configService + */ + public function inject(Config $config, UserRepository $userRepository, ConfigService $configService) + { + $this->configData = $config->getConfigData(); + $this->userRepository = $userRepository; + $this->configService = $configService; + } + + /** + * Actualizar la clave maestra con la clave anterior del usuario + * + * @param string $oldUserPass + * @param UserLoginData $UserData $UserData + * @return UserPassResponse + * @throws SPException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + public function updateMasterPassFromOldPass($oldUserPass, UserLoginData $UserData) + { + $response = $this->loadUserMPass($UserData, $oldUserPass); + + if ($response->getStatus() === self::MPASS_OK) { + return $this->updateMasterPass($response->getClearMasterPass(), $UserData); + } + + return new UserPassResponse(self::MPASS_WRONG); + } + + /** + * Comprueba la clave maestra del usuario. + * + * @param UserLoginData $userLoginData + * @param string $key Clave de cifrado + * @return UserPassResponse + * @throws SPException + * @throws \Psr\Container\ContainerExceptionInterface + */ + public function loadUserMPass(UserLoginData $userLoginData, $key = null) + { + $userLoginResponse = $userLoginData->getUserLoginResponse(); + + $configHashMPass = $this->configService->getByParam('masterPwd'); + + if (empty($configHashMPass) + || empty($userLoginResponse->getMPass()) + || empty($userLoginResponse->getMKey()) + ) { + return new UserPassResponse(self::MPASS_NOTSET); + } + + if ($userLoginResponse->getLastUpdateMPass() < $this->configService->getByParam('lastupdatempass')) { + return new UserPassResponse(self::MPASS_CHANGED); + } + + if ($userLoginResponse->getIsMigrate() === 1) { + return UpgradeUser::upgradeMasterKey($userLoginData, $this) ? new UserPassResponse(self::MPASS_OK) : new UserPassResponse(self::MPASS_WRONG); + } + + if ($key === null && $userLoginResponse->getIsChangedPass() === 1) { + return new UserPassResponse(self::MPASS_CHECKOLD); + } + + try { + $securedKey = Crypt::unlockSecuredKey($userLoginResponse->getMKey(), $this->getKey($userLoginData, $key)); + $cryptMPass = Crypt::decrypt($userLoginResponse->getMPass(), $securedKey, $this->getKey($userLoginData, $key)); + + // Comprobamos el hash de la clave del usuario con la guardada + if (Hash::checkHashKey($cryptMPass, $configHashMPass)) { + CryptSession::saveSessionKey($cryptMPass); + + $response = new UserPassResponse(self::MPASS_OK, $cryptMPass); + $response->setCryptMasterPass($cryptMPass); + $response->setCryptSecuredKey($securedKey); + + return $response; + } + } catch (CryptoException $e) { + return new UserPassResponse(self::MPASS_CHECKOLD); + } + + return new UserPassResponse(self::MPASS_WRONG); + } + + /** + * Obtener una clave de cifrado basada en la clave del usuario y un salt. + * + * @param UserLoginData $userLoginData + * @param string $key Clave de cifrado + * @return string con la clave de cifrado + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + private function getKey(UserLoginData $userLoginData, $key = null) + { + $pass = $key === null ? $userLoginData->getLoginPass() : $key; + + return $pass . $userLoginData->getLoginUser() . $this->configData->getPasswordSalt(); + } + + /** + * Actualizar la clave maestra del usuario en la BBDD. + * + * @param string $userMPass con la clave maestra + * @param UserLoginData $userLoginData $userLoginData + * @return UserPassResponse + * @throws SPException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + * @throws \SP\Core\Exceptions\SPException + */ + public function updateMasterPass($userMPass, UserLoginData $userLoginData) + { + $userData = $userLoginData->getUserLoginResponse(); + $configHashMPass = $this->configService->getByParam('masterPwd'); + + if ($configHashMPass === false) { + return new UserPassResponse(self::MPASS_NOTSET); + } + + if (null === $configHashMPass) { + $configHashMPass = Hash::hashKey($userMPass); + + $this->configService->save('masterPwd', $configHashMPass); + } + + if (Hash::checkHashKey($userMPass, $configHashMPass) + || CryptUpgrade::migrateHash($userMPass) + ) { + $securedKey = Crypt::makeSecuredKey($this->getKey($userLoginData)); + $cryptMPass = Crypt::encrypt($userMPass, $securedKey, $this->getKey($userLoginData)); + + if (!empty($cryptMPass)) { + if (strlen($securedKey) > 1000 || strlen($cryptMPass) > 1000) { + throw new SPException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR); + } + + $this->userRepository->updateMasterPassById($userData->getId(), $cryptMPass, $securedKey); + + CryptSession::saveSessionKey($userMPass); + +// $userData->setMPass($cryptMPass); +// $userData->setMKey($securedKey); + + $response = new UserPassResponse(self::MPASS_OK, $userMPass); + $response->setCryptMasterPass($cryptMPass); + $response->setCryptSecuredKey($securedKey); + + return $response; + } + } + + return new UserPassResponse(self::MPASS_WRONG); + } + + /** + * @param int $id + * @param string $userPass + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function migrateUserPassById($id, $userPass) + { + return $this->userRepository->updatePassById($id, new UpdatePassRequest(Hash::hashKey($userPass))); + } +} \ No newline at end of file diff --git a/lib/SP/Services/User/UserService.php b/lib/SP/Services/User/UserService.php index 382129ae..c38ee49e 100644 --- a/lib/SP/Services/User/UserService.php +++ b/lib/SP/Services/User/UserService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link http://syspass.org - * @copyright 2012-2017, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -24,28 +24,198 @@ namespace SP\Services\User; - -use SP\Core\Acl\Acl; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\SPException; +use SP\Core\Traits\InjectableTrait; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; -use SP\Log\Log; -use SP\Services\Service; -use SP\Services\ServiceItemInterface; +use SP\DataModel\UserPreferencesData; +use SP\Repositories\User\UserRepository; use SP\Services\ServiceItemTrait; -use SP\Storage\DbWrapper; -use SP\Storage\QueryData; +use SP\Util\Util; /** * Class UserService * * @package SP\Services\User */ -class UserService extends Service implements ServiceItemInterface +class UserService { + use InjectableTrait; use ServiceItemTrait; + /** + * @var UserRepository + */ + protected $userRepository; + + /** + * UserService constructor. + */ + public function __construct() + { + $this->injectDependencies(); + } + + /** + * @param UserRepository $userRepository + */ + public function inject(UserRepository $userRepository) + { + $this->userRepository = $userRepository; + } + + /** + * Returns all the items mapping fields for a select type element (id and name fields) + */ + public function getAllItemsForSelect() + { + return $this->getItemsForSelect($this->userRepository); + } + + /** + * Actualiza el último inicio de sesión del usuario en la BBDD. + * + * @param $id int El id del usuario + * @return bool + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\ConstraintException + */ + public function updateLastLoginById($id) + { + return $this->userRepository->updateLastLoginById($id); + } + + /** + * @param $login + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function checkExistsByLogin($login) + { + return $this->userRepository->checkExistsByLogin($login); + } + + /** + * Returns the item for given id + * + * @param int $id + * @return mixed + * @throws SPException + */ + public function getById($id) + { + return $this->userRepository->getById($id); + } + + /** + * Returns the item for given id + * + * @param $login + * @return UserLoginResponse + * @throws SPException + */ + public function getByLogin($login) + { + $userData = $this->userRepository->getByLogin($login); + + $userLoginResponse = new UserLoginResponse(); + $userLoginResponse->setId($userData->getId()) + ->setName($userData->getName()) + ->setLogin($userData->getLogin()) + ->setSsoLogin($userData->getSsoLogin()) + ->setEmail($userData->getEmail()) + ->setPass($userData->getPass()) + ->setHashSalt($userData->getHashSalt()) + ->setMPass($userData->getMPass()) + ->setMKey($userData->getMKey()) + ->setLastUpdateMPass($userData->getLastUpdateMPass()) + ->setUserGroupId($userData->getUserGroupId()) + ->setUserProfileId($userData->getUserProfileId()) + ->setPreferences(self::getUserPreferences($userData->getPreferences())) + ->setIsLdap($userData->isIsLdap()) + ->setIsAdminAcc($userData->isIsAdminAcc()) + ->setIsAdminApp($userData->isIsAdminApp()) + ->setIsMigrate($userData->isIsMigrate()) + ->setIsChangedPass($userData->isIsChangedPass()) + ->setIsChangePass($userData->isIsChangePass()) + ->setIsDisabled($userData->isIsDisabled()); + + return $userLoginResponse; + } + + /** + * Returns user's preferences object + * + * @param string $preferences + * @return UserPreferencesData + */ + public static function getUserPreferences($preferences) + { + if (!empty($preferences)) { + return Util::unserialize(UserPreferencesData::class, $preferences, 'SP\UserPreferences'); + } + + return new UserPreferencesData(); + } + + /** + * Deletes an item + * + * @param $id + * @return UserRepository + * @throws SPException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete($id) + { + return $this->userRepository->delete($id); + } + + /** + * Creates an item + * + * @param UserLoginRequest $userLoginRequest + * @return mixed + * @throws SPException + */ + public function createOnLogin(UserLoginRequest $userLoginRequest) + { + $userData = new UserData(); + $userData->setLogin($userLoginRequest->getLogin()); + $userData->setName($userLoginRequest->getName()); + $userData->setEmail($userLoginRequest->getEmail()); + $userData->setIsLdap($userLoginRequest->getisLdap()); + $userData->setPass(Hash::hashKey($userLoginRequest->getPassword())); + + return $this->create($userData); + } + + /** + * Creates an item + * + * @param UserData $itemData + * @return mixed + * @throws SPException + */ + public function create($itemData) + { + return $this->userRepository->create($itemData); + } + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $SearchData + * @return array + */ + public function search(ItemSearchData $SearchData) + { + return $this->userRepository->search($SearchData); + } + /** * Updates an item * @@ -57,502 +227,41 @@ class UserService extends Service implements ServiceItemInterface */ public function update($itemData) { - if ($this->checkDuplicatedOnUpdate($itemData)) { - throw new SPException(SPException::SP_INFO, __u('Login/email de usuario duplicados')); - } - - $query = /** @lang SQL */ - 'UPDATE usrData SET - user_name = ?, - user_login = ?, - user_ssoLogin = ?, - user_email = ?, - user_notes = ?, - user_groupId = ?, - user_profileId = ?, - user_isAdminApp = ?, - user_isAdminAcc = ?, - user_isDisabled = ?, - user_isChangePass = ?, - user_lastUpdate = NOW() - WHERE user_id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserName()); - $Data->addParam($itemData->getUserLogin()); - $Data->addParam($itemData->getUserSsoLogin()); - $Data->addParam($itemData->getUserEmail()); - $Data->addParam($itemData->getUserNotes()); - $Data->addParam($itemData->getUserGroupId()); - $Data->addParam($itemData->getUserProfileId()); - $Data->addParam($itemData->isUserIsAdminApp()); - $Data->addParam($itemData->isUserIsAdminAcc()); - $Data->addParam($itemData->isUserIsDisabled()); - $Data->addParam($itemData->isUserIsChangePass()); - $Data->addParam($itemData->getUserId()); - $Data->setOnErrorMessage(__u('Error al actualizar el usuario')); - - DbWrapper::getQuery($Data, $this->db); - - if ($Data->getQueryNumRows() > 0) { - $itemData->setUserId(DbWrapper::getLastId()); - } - - return $this; - } - - /** - * Checks whether the item is duplicated on updating - * - * @param UserData $itemData - * @return bool - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function checkDuplicatedOnUpdate($itemData) - { - $query = /** @lang SQL */ - 'SELECT user_login, user_email - FROM usrData - WHERE (UPPER(user_login) = UPPER(?) - OR UPPER(user_ssoLogin) = UPPER(?) - OR UPPER(user_email) = UPPER(?)) - AND user_id <> ?'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserLogin()); - $Data->addParam($itemData->getUserSsoLogin()); - $Data->addParam($itemData->getUserEmail()); - $Data->addParam($itemData->getUserId()); - - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() > 0; + return $this->userRepository->update($itemData); } /** * Updates an user's pass * * @param UserData $itemData - * @return $this - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function updatePass($itemData) - { - $query = /** @lang SQL */ - 'UPDATE usrData SET - user_pass = ?, - user_hashSalt = \'\', - user_isChangePass = 0, - user_isChangedPass = 1, - user_lastUpdate = NOW() - WHERE user_id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam(Hash::hashKey($itemData->getUserPass())); - $Data->addParam($itemData->getUserId()); - $Data->setOnErrorMessage(__u('Error al modificar la clave')); - - DbWrapper::getQuery($Data, $this->db); - - return $this; - } - - /** - * Deletes an item - * - * @param $id - * @return UserService - * @throws SPException - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - */ - public function delete($id) - { - $query = 'DELETE FROM usrData WHERE user_id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($id); - $Data->setOnErrorMessage(__u('Error al eliminar el usuario')); - - DbWrapper::getQuery($Data, $this->db); - - if ($Data->getQueryNumRows() === 0) { - throw new SPException(SPException::SP_INFO, __u('Usuario no encontrado')); - } - - return $this; - } - - /** - * Returns the item for given id - * - * @param int $id - * @return mixed - * @throws SPException - */ - public function getById($id) - { - $query = /** @lang SQL */ - 'SELECT user_id, - user_name, - user_groupId, - usergroup_name, - user_login, - user_ssoLogin, - user_email, - user_notes, - user_count, - user_profileId, - user_count, - user_lastLogin, - user_lastUpdate, - user_lastUpdateMPass, - user_preferences, - user_pass, - user_hashSalt, - user_mPass, - user_mKey, - BIN(user_isAdminApp) AS user_isAdminApp, - BIN(user_isAdminAcc) AS user_isAdminAcc, - BIN(user_isLdap) AS user_isLdap, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isChangePass) AS user_isChangePass, - BIN(user_isChangedPass) AS user_isChangedPass, - BIN(user_isMigrate) AS user_isMigrate - FROM usrData - JOIN usrGroups ON usergroup_id = user_groupId - WHERE user_id = ? LIMIT 1'; - - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->addParam($id); - - $queryRes = DbWrapper::getResults($Data, $this->db); - - if ($queryRes === false) { - throw new SPException(SPException::SP_ERROR, __u('Error al obtener los datos del usuario')); - } - - return $queryRes; - } - - /** - * Returns all the items - * - * @return mixed - */ - public function getAll() - { - $query = /** @lang SQL */ - 'SELECT user_id, - user_name, - user_groupId, - user_login, - user_ssoLogin, - user_email, - user_notes, - user_count, - user_profileId, - user_preferences, - BIN(user_isAdminApp) AS user_isAdminApp, - BIN(user_isAdminAcc) AS user_isAdminAcc, - BIN(user_isLdap) AS user_isLdap, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isChangePass) AS user_isChangePass - FROM usrData'; - - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - - return DbWrapper::getResultsArray($Data, $this->db); - } - - /** - * Returns all the items for given ids - * - * @param array $ids - * @return array - */ - public function getByIdBatch(array $ids) - { - if (count($ids) === 0) { - return []; - } - - $query = /** @lang SQL */ - 'SELECT user_id, - user_name, - user_groupId, - usergroup_name, - user_login, - user_ssoLogin, - user_email, - user_notes, - user_count, - user_profileId, - user_count, - user_lastLogin, - user_lastUpdate, - user_lastUpdateMPass, - user_preferences, - BIN(user_isAdminApp) AS user_isAdminApp, - BIN(user_isAdminAcc) AS user_isAdminAcc, - BIN(user_isLdap) AS user_isLdap, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isChangePass) AS user_isChangePass, - BIN(user_isChangedPass) AS user_isChangedPass, - BIN(user_isMigrate) AS user_isMigrate - FROM usrData - JOIN usrGroups ON usergroup_id = user_groupId - WHERE user_id IN (' . $this->getParamsFromArray($ids) . ')'; - - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->setParams($ids); - - return DbWrapper::getResultsArray($Data, $this->db); - } - - /** - * Deletes all the items for given ids - * - * @param array $ids - * @return $this - */ - public function deleteByIdBatch(array $ids) - { - // TODO: Implement deleteByIdBatch() method. - } - - /** - * Checks whether the item is in use or not - * - * @param $id int - * @return bool - */ - public function checkInUse($id) - { - // TODO: Implement checkInUse() method. - } - - /** - * Searches for items by a given filter - * - * @param ItemSearchData $SearchData - * @return array - */ - public function search(ItemSearchData $SearchData) - { - $Data = new QueryData(); - $Data->setSelect('user_id, - user_name, - user_login, - userprofile_name, - usergroup_name, - BIN(user_isAdminApp) AS user_isAdminApp, - BIN(user_isAdminAcc) AS user_isAdminAcc, - BIN(user_isLdap) AS user_isLdap, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isChangePass) AS user_isChangePass'); - $Data->setFrom('usrData LEFT JOIN usrProfiles ON user_profileId = userprofile_id LEFT JOIN usrGroups ON usrData.user_groupId = usergroup_id'); - $Data->setOrder('user_name'); - - if ($SearchData->getSeachString() !== '') { - if ($this->session->getUserData()->isUserIsAdminApp()) { - $Data->setWhere('user_name LIKE ? OR user_login LIKE ?'); - } else { - $Data->setWhere('user_name LIKE ? OR user_login LIKE ? AND user_isAdminApp = 0'); - } - - $search = '%' . $SearchData->getSeachString() . '%'; - $Data->addParam($search); - $Data->addParam($search); - } elseif (!$this->session->getUserData()->isUserIsAdminApp()) { - $Data->setWhere('user_isAdminApp = 0'); - } - - $Data->setLimit('?, ?'); - $Data->addParam($SearchData->getLimitStart()); - $Data->addParam($SearchData->getLimitCount()); - - DbWrapper::setFullRowCount(); - - $queryRes = DbWrapper::getResultsArray($Data, $this->db); - - $queryRes['count'] = $Data->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 user_id, user_login, user_name FROM usrData WHERE user_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->user_name, $user->user_login)); - $LogMessage->addDetails(__u('ID'), $id); - $Log->writeLog(); - - return $LogMessage; - } - - /** - * Creates an item - * - * @param UserData $itemData - * @return mixed - * @throws SPException - */ - public function create($itemData) - { - if ($this->checkDuplicatedOnAdd($itemData)) { - throw new SPException(SPException::SP_INFO, __u('Login/email de usuario duplicados')); - } - - $query = /** @lang SQL */ - 'INSERT INTO usrData SET - user_name = ?, - user_login = ?, - user_ssoLogin = ?, - user_email = ?, - user_notes = ?, - user_groupId = ?, - user_profileId = ?, - user_mPass = \'\', - user_mKey = \'\', - user_isAdminApp = ?, - user_isAdminAcc = ?, - user_isDisabled = ?, - user_isChangePass = ?, - user_isLdap = 0, - user_pass = ?, - user_hashSalt = \'\''; - - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserName()); - $Data->addParam($itemData->getUserLogin()); - $Data->addParam($itemData->getUserSsoLogin()); - $Data->addParam($itemData->getUserEmail()); - $Data->addParam($itemData->getUserNotes()); - $Data->addParam($itemData->getUserGroupId()); - $Data->addParam($itemData->getUserProfileId()); - $Data->addParam($itemData->isUserIsAdminApp()); - $Data->addParam($itemData->isUserIsAdminAcc()); - $Data->addParam($itemData->isUserIsDisabled()); - $Data->addParam($itemData->isUserIsChangePass()); - $Data->addParam(Hash::hashKey($itemData->getUserPass())); - $Data->setOnErrorMessage(__u('Error al crear el usuario')); - - DbWrapper::getQuery($Data, $this->db); - - return $this->db->getLastId(); - } - - /** - * Checks whether the item is duplicated on adding - * - * @param UserData $itemData * @return bool * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ - public function checkDuplicatedOnAdd($itemData) + public function updatePass(UserData $itemData) { - $query = /** @lang SQL */ - 'SELECT user_login, user_email - FROM usrData - WHERE UPPER(user_login) = UPPER(?) - OR UPPER(user_ssoLogin) = UPPER(?) - OR UPPER(user_email) = UPPER(?)'; + $passRequest = new UpdatePassRequest(Hash::hashKey($itemData->getPass())); + $passRequest->setIsChangePass(0); + $passRequest->setIsChangedPass(1); - $Data = new QueryData(); - $Data->setQuery($query); - $Data->addParam($itemData->getUserLogin()); - $Data->addParam($itemData->getUserSsoLogin()); - $Data->addParam($itemData->getUserEmail()); - - DbWrapper::getQuery($Data, $this->db); - - return $Data->getQueryNumRows() > 0; + return $this->userRepository->updatePassById($itemData->getId(), $passRequest); } /** - * @param $login string - * @return UserData - * @throws SPException + * @param UserLoginRequest $userLoginRequest + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ - public function getByLogin($login) + public function updateOnLogin(UserLoginRequest $userLoginRequest) { - $query = /** @lang SQL */ - 'SELECT user_id, - user_name, - user_groupId, - usergroup_name, - user_login, - user_ssoLogin, - user_email, - user_notes, - user_count, - user_profileId, - user_count, - user_lastLogin, - user_lastUpdate, - user_lastUpdateMPass, - user_preferences, - user_pass, - user_hashSalt, - user_mPass, - user_mKey, - BIN(user_isAdminApp) AS user_isAdminApp, - BIN(user_isAdminAcc) AS user_isAdminAcc, - BIN(user_isLdap) AS user_isLdap, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isChangePass) AS user_isChangePass, - BIN(user_isChangedPass) AS user_isChangedPass, - BIN(user_isDisabled) AS user_isDisabled, - BIN(user_isMigrate) AS user_isMigrate - FROM usrData - JOIN usrGroups ON usergroup_id = user_groupId - WHERE user_login = ? OR user_ssoLogin = ? LIMIT 1'; + $userData = new UserData(); + $userData->setLogin($userLoginRequest->getLogin()); + $userData->setName($userLoginRequest->getName()); + $userData->setEmail($userLoginRequest->getEmail()); + $userData->setIsLdap($userLoginRequest->getisLdap()); + $userData->setPass(Hash::hashKey($userLoginRequest->getPassword())); - $Data = new QueryData(); - $Data->setMapClassName(UserData::class); - $Data->setQuery($query); - $Data->addParam($login); - $Data->addParam($login); - - $queryRes = DbWrapper::getResults($Data); - - if ($queryRes === false) { - throw new SPException(SPException::SP_ERROR, __u('Error al obtener los datos del usuario')); - } - - return $queryRes; + return $this->userRepository->updateOnLogin($userData); } } \ No newline at end of file diff --git a/lib/SP/Storage/DBUtil.php b/lib/SP/Storage/DBUtil.php index a7c9db53..283bdca1 100644 --- a/lib/SP/Storage/DBUtil.php +++ b/lib/SP/Storage/DBUtil.php @@ -41,29 +41,31 @@ class DBUtil * @var array Tablas de la BBDD */ public static $tables = [ - 'customers', - 'categories', - 'tags', - 'usrGroups', - 'usrProfiles', - 'usrData', - 'accounts', - 'accFavorites', - 'accFiles', - 'accGroups', - 'accHistory', - 'accTags', - 'accUsers', - 'authTokens', - 'config', - 'customFieldsDef', - 'customFieldsData', - 'log', - 'publicLinks', - 'usrPassRecover', - 'usrToGroups', - 'plugins', - 'notices', + 'Customer', + 'Category', + 'Tag', + 'UserGroup', + 'UserProfile', + 'User', + 'Account', + 'AccountToFavorite', + 'AccountFile', + 'AccountToUserGroup', + 'AccountHistory', + 'AccountToTag', + 'AccountTouser', + 'AuthToken', + 'Config', + 'Action', + 'CustomFieldType', + 'CustomFieldDefinition', + 'customFieldData', + 'EventLog', + 'PublicLink', + 'UserPassRecover', + 'UserToUserGroup', + 'Plugin', + 'Notice', 'account_data_v', 'account_search_v' ]; @@ -122,7 +124,7 @@ class DBUtil */ public static function checkDatabaseExist() { - $dic = Bootstrap::getDic(); + $dic = Bootstrap::getContainer(); /** @var Database $Db */ $Db = $dic->get(Database::class); /** @var ConfigData $ConfigData */ @@ -133,7 +135,7 @@ class DBUtil 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = \'' . $ConfigData->getDbName() . '\' - AND table_name IN (\'customers\', \'categories\', \'accounts\', \'usrData\', \'config\', \'log\' )'; + AND table_name IN (\'Client\', \'Category\', \'Account\', \'User\', \'Config\', \'EventLog\')'; return (int)$Db->getDbHandler()->getConnection()->query($query)->fetchColumn() === 6; } catch (\Exception $e) { diff --git a/lib/SP/Storage/Database.php b/lib/SP/Storage/Database.php index 8d4f200a..285e055c 100644 --- a/lib/SP/Storage/Database.php +++ b/lib/SP/Storage/Database.php @@ -227,6 +227,8 @@ class Database implements DatabaseInterface $num = (int)$queryRes->fetchColumn(); $queryRes->closeCursor(); $queryData->setQueryNumRows($num); + + return $num; } /** diff --git a/lib/SP/Storage/DbWrapper.php b/lib/SP/Storage/DbWrapper.php index 0783246b..d16b186f 100644 --- a/lib/SP/Storage/DbWrapper.php +++ b/lib/SP/Storage/DbWrapper.php @@ -69,7 +69,7 @@ class DbWrapper // FIXME: remove if ($db === null) { /** @var Database $db */ - $db = Bootstrap::getDic()->get(Database::class); + $db = Bootstrap::getContainer()->get(Database::class); } $results = self::getResults($queryData, $db); @@ -99,7 +99,7 @@ class DbWrapper // FIXME: remove if ($db === null) { /** @var Database $db */ - $db = Bootstrap::getDic()->get(Database::class); + $db = Bootstrap::getContainer()->get(Database::class); } $db->doQuery($queryData); @@ -173,7 +173,7 @@ class DbWrapper // FIXME: remove if ($db === null) { /** @var Database $db */ - $db = Bootstrap::getDic()->get(Database::class); + $db = Bootstrap::getContainer()->get(Database::class); } return $db->doQuery($queryData, true); @@ -209,7 +209,7 @@ class DbWrapper // FIXME: remove if ($db === null) { /** @var Database $db */ - $db = Bootstrap::getDic()->get(Database::class); + $db = Bootstrap::getContainer()->get(Database::class); } $db->doQuery($queryData); diff --git a/schemas/dbstructure.sql b/schemas/dbstructure.sql index 5eece34f..537b5c7c 100644 --- a/schemas/dbstructure.sql +++ b/schemas/dbstructure.sql @@ -1,3 +1,9 @@ +-- MySQL dump 10.13 Distrib 5.5.58, for debian-linux-gnu (x86_64) +-- +-- Host: 172.18.0.2 Database: syspass +-- ------------------------------------------------------ +-- Server version 5.5.53-0+deb8u1 + /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; @@ -9,653 +15,691 @@ /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -DROP TABLE IF EXISTS `customers`; +-- +-- Table structure for table `Account` +-- + +DROP TABLE IF EXISTS `Account`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `customers` ( - `customer_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `customer_name` varchar(100) NOT NULL, - `customer_hash` varbinary(40) NOT NULL, - `customer_description` varchar(255) DEFAULT NULL, - `customer_isGlobal` bit DEFAULT b'0', - PRIMARY KEY (`customer_id`), - KEY `IDX_name` (`customer_name`,`customer_hash`) +CREATE TABLE `Account` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `userGroupId` smallint(5) unsigned NOT NULL, + `userId` smallint(5) unsigned NOT NULL, + `userEditId` smallint(5) unsigned NOT NULL, + `clientId` mediumint(8) unsigned NOT NULL, + `name` varchar(50) NOT NULL, + `categoryId` mediumint(8) unsigned NOT NULL, + `login` varchar(50) DEFAULT NULL, + `url` varchar(255) DEFAULT NULL, + `pass` varbinary(1000) NOT NULL, + `key` varbinary(1000) NOT NULL, + `notes` text, + `countView` int(10) unsigned NOT NULL DEFAULT '0', + `countDecrypt` int(10) unsigned NOT NULL DEFAULT '0', + `dateAdd` datetime NOT NULL, + `dateEdit` datetime DEFAULT NULL, + `otherUserGroupEdit` tinyint(1) DEFAULT '0', + `otherUserEdit` tinyint(1) DEFAULT '0', + `isPrivate` tinyint(1) DEFAULT '0', + `isPrivateGroup` tinyint(1) DEFAULT '0', + `passDate` int(11) unsigned DEFAULT NULL, + `passDateChange` int(11) unsigned DEFAULT NULL, + `parentId` mediumint(8) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `IDX_categoryId` (`categoryId`), + KEY `IDX_userId` (`userGroupId`,`userId`), + KEY `IDX_customerId` (`clientId`), + KEY `fk_Account_userId` (`userId`), + KEY `fk_Account_userEditId` (`userEditId`), + CONSTRAINT `fk_Account_categoryId` FOREIGN KEY (`categoryId`) REFERENCES `Category` (`id`), + CONSTRAINT `fk_Account_clientId` FOREIGN KEY (`clientId`) REFERENCES `Client` (`id`), + CONSTRAINT `fk_Account_userEditId` FOREIGN KEY (`userEditId`) REFERENCES `User` (`id`), + CONSTRAINT `fk_Account_userGroupId` FOREIGN KEY (`userGroupId`) REFERENCES `UserGroup` (`id`), + CONSTRAINT `fk_Account_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `AccountFile` +-- + +DROP TABLE IF EXISTS `AccountFile`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `AccountFile` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `accountId` mediumint(8) unsigned NOT NULL, + `name` varchar(100) NOT NULL, + `type` varchar(100) NOT NULL, + `size` int(11) NOT NULL, + `content` mediumblob NOT NULL, + `extension` varchar(10) NOT NULL, + `thumb` mediumblob, + PRIMARY KEY (`id`), + KEY `IDX_accountId` (`accountId`), + CONSTRAINT `fk_AccountFile_accountId` FOREIGN KEY (`accountId`) REFERENCES `Account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `AccountHistory` +-- + +DROP TABLE IF EXISTS `AccountHistory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `AccountHistory` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `accountId` mediumint(8) unsigned NOT NULL, + `userGroupId` smallint(5) unsigned NOT NULL, + `userId` smallint(5) unsigned NOT NULL, + `userEditId` smallint(5) unsigned NOT NULL, + `clientId` mediumint(8) unsigned NOT NULL, + `name` varchar(255) NOT NULL, + `categoryId` mediumint(8) unsigned NOT NULL, + `login` varchar(50) DEFAULT NULL, + `url` varchar(255) DEFAULT NULL, + `pass` varbinary(1000) NOT NULL, + `key` varbinary(1000) NOT NULL, + `notes` text NOT NULL, + `countView` int(10) unsigned NOT NULL DEFAULT '0', + `countDecrypt` int(10) unsigned NOT NULL DEFAULT '0', + `dateAdd` datetime NOT NULL, + `dateEdit` datetime DEFAULT NULL, + `isModify` tinyint(1) DEFAULT '0', + `isDeleted` tinyint(1) DEFAULT '0', + `mPassHash` varbinary(255) NOT NULL, + `otherUserEdit` tinyint(1) DEFAULT '0', + `otherUserGroupEdit` tinyint(1) DEFAULT '0', + `passDate` int(10) unsigned DEFAULT NULL, + `passDateChange` int(10) unsigned DEFAULT NULL, + `parentId` mediumint(8) unsigned DEFAULT NULL, + `isPrivate` tinyint(1) DEFAULT '0', + `isPrivateGroup` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + KEY `IDX_accountId` (`accountId`), + KEY `fk_AccountHistory_userGroupId` (`userGroupId`), + KEY `fk_AccountHistory_userId` (`userId`), + KEY `fk_AccountHistory_userEditId` (`userEditId`), + KEY `fk_AccountHistory_clientId` (`clientId`), + KEY `fk_AccountHistory_categoryId` (`categoryId`), + CONSTRAINT `fk_AccountHistory_categoryId` FOREIGN KEY (`categoryId`) REFERENCES `Category` (`id`), + CONSTRAINT `fk_AccountHistory_clientId` FOREIGN KEY (`clientId`) REFERENCES `Client` (`id`), + CONSTRAINT `fk_AccountHistory_userEditId` FOREIGN KEY (`userEditId`) REFERENCES `User` (`id`), + CONSTRAINT `fk_AccountHistory_userGroupId` FOREIGN KEY (`userGroupId`) REFERENCES `UserGroup` (`id`), + CONSTRAINT `fk_AccountHistory_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `AccountToFavorite` +-- + +DROP TABLE IF EXISTS `AccountToFavorite`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `AccountToFavorite` ( + `accountId` mediumint(8) unsigned NOT NULL, + `userId` smallint(5) unsigned NOT NULL, + KEY `search_idx` (`accountId`,`userId`), + KEY `fk_AccountToFavorite_userId` (`userId`), + CONSTRAINT `fk_AccountToFavorite_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_AccountToFavorite_accountId` FOREIGN KEY (`accountId`) REFERENCES `Account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -DROP TABLE IF EXISTS `categories`; +-- +-- Table structure for table `AccountToGroup` +-- + +DROP TABLE IF EXISTS `AccountToGroup`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `categories` ( - `category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `category_name` varchar(50) NOT NULL, - `category_hash` varbinary(40) NOT NULL, - `category_description` varchar(255) DEFAULT NULL - PRIMARY KEY (`category_id`) +CREATE TABLE `AccountToGroup` ( + `accountId` mediumint(8) unsigned NOT NULL, + `userGroupId` smallint(5) unsigned NOT NULL, + KEY `IDX_accountId` (`accountId`), + KEY `fk_AccountToGroup_userGroupId` (`userGroupId`), + CONSTRAINT `fk_AccountToGroup_userGroupId` FOREIGN KEY (`userGroupId`) REFERENCES `UserGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_AccountToGroup_accountId` FOREIGN KEY (`accountId`) REFERENCES `Account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -DROP TABLE IF EXISTS `usrGroups`; +-- +-- Table structure for table `AccountToTag` +-- + +DROP TABLE IF EXISTS `AccountToTag`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `usrGroups` ( - `usergroup_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `usergroup_name` varchar(50) NOT NULL, - `usergroup_description` varchar(255) DEFAULT NULL, - PRIMARY KEY (`usergroup_id`) +CREATE TABLE `AccountToTag` ( + `accountId` mediumint(8) unsigned NOT NULL, + `tagId` int(10) unsigned NOT NULL, + KEY `fk_AccountToTag_accountId` (`accountId`), + KEY `fk_AccountToTag_tagId` (`tagId`), + CONSTRAINT `fk_AccountToTag_tagId` FOREIGN KEY (`tagId`) REFERENCES `Tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_AccountToTag_accountId` FOREIGN KEY (`accountId`) REFERENCES `Account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -DROP TABLE IF EXISTS `usrProfiles`; +-- +-- Table structure for table `AccountToUser` +-- + +DROP TABLE IF EXISTS `AccountToUser`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `usrProfiles` ( - `userprofile_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `userprofile_name` varchar(45) NOT NULL, - `userProfile_profile` blob NOT NULL, - PRIMARY KEY (`userprofile_id`) +CREATE TABLE `AccountToUser` ( + `accountId` mediumint(8) unsigned NOT NULL, + `userId` smallint(5) unsigned NOT NULL, + KEY `idx_account` (`accountId`), + KEY `fk_AccountToUser_userId` (`userId`), + CONSTRAINT `fk_AccountToUser_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_AccountToUser_accountId` FOREIGN KEY (`accountId`) REFERENCES `Account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -DROP TABLE IF EXISTS `usrData`; +-- +-- Table structure for table `Action` +-- + +DROP TABLE IF EXISTS `Action`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `usrData` ( - `user_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `user_name` varchar(80) NOT NULL, - `user_groupId` smallint(3) unsigned NOT NULL, - `user_secGroupId` smallint(3) unsigned DEFAULT NULL, - `user_login` varchar(50) NOT NULL, - `user_ssoLogin` varchar(100) null, - `user_pass` varbinary(1000) NOT NULL, - `user_mPass` varbinary(1000) DEFAULT NULL, - `user_mKey` varbinary(1000) NOT NULL, - `user_email` varchar(80) DEFAULT NULL, - `user_notes` text, - `user_count` int(10) unsigned NOT NULL DEFAULT '0', - `user_profileId` smallint(5) unsigned NOT NULL, - `user_lastLogin` datetime DEFAULT NULL, - `user_lastUpdate` datetime DEFAULT NULL, - `user_lastUpdateMPass` int(11) unsigned NOT NULL DEFAULT '0', - `user_isAdminApp` bit(1) DEFAULT b'0', - `user_isAdminAcc` bit(1) DEFAULT b'0', - `user_isLdap` bit(1) DEFAULT b'0', - `user_isDisabled` bit(1) DEFAULT b'0', - `user_hashSalt` varbinary(128) NOT NULL, - `user_isMigrate` bit(1) DEFAULT b'0', - `user_isChangePass` bit(1) DEFAULT b'0', - `user_isChangedPass` bit(1) DEFAULT b'0', +CREATE TABLE `Action` ( + `id` smallint(5) unsigned NOT NULL, + `name` varchar(50) NOT NULL, + `text` varchar(100) NOT NULL, + `route` varchar(100) DEFAULT NULL, + PRIMARY KEY (`id`,`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `AuthToken` +-- + +DROP TABLE IF EXISTS `AuthToken`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `AuthToken` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userId` smallint(5) unsigned NOT NULL, + `token` varbinary(100) NOT NULL, + `actionId` smallint(5) unsigned NOT NULL, + `createdBy` smallint(5) unsigned NOT NULL, + `startDate` int(10) unsigned NOT NULL, + `vault` varbinary(2000) DEFAULT NULL, + `hash` varbinary(1000) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `unique_authtoken_id` (`id`), + KEY `IDX_checkToken` (`userId`,`actionId`,`token`), + KEY `fk_AuthToken_actionId` (`actionId`), + CONSTRAINT `fk_AuthToken_actionId` FOREIGN KEY (`actionId`) REFERENCES `Action` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_AuthToken_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Category` +-- + +DROP TABLE IF EXISTS `Category`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Category` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `hash` varbinary(40) NOT NULL, + `description` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Client` +-- + +DROP TABLE IF EXISTS `Client`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Client` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `hash` varbinary(40) NOT NULL, + `description` varchar(255) DEFAULT NULL, + `isGlobal` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + KEY `IDX_name` (`name`,`hash`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Config` +-- + +DROP TABLE IF EXISTS `Config`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Config` ( + `parameter` varchar(50) NOT NULL, + `value` varchar(2000) DEFAULT NULL, + PRIMARY KEY (`parameter`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `CustomFieldData` +-- + +DROP TABLE IF EXISTS `CustomFieldData`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `CustomFieldData` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `moduleId` smallint(5) unsigned NOT NULL, + `itemId` int(10) unsigned NOT NULL, + `definitionId` int(10) unsigned NOT NULL, + `data` longblob, + `key` varbinary(1000) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `IDX_DEFID` (`definitionId`), + KEY `IDX_DELETE` (`itemId`,`moduleId`), + KEY `IDX_UPDATE` (`moduleId`,`itemId`,`definitionId`), + KEY `IDX_ITEM` (`itemId`), + KEY `IDX_MODULE` (`moduleId`), + CONSTRAINT `fk_CustomFieldData_definitionId` FOREIGN KEY (`definitionId`) REFERENCES `CustomFieldDefinition` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `CustomFieldDefinition` +-- + +DROP TABLE IF EXISTS `CustomFieldDefinition`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `CustomFieldDefinition` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `moduleId` smallint(5) unsigned NOT NULL, + `field` blob, + `required` tinyint(1) unsigned DEFAULT NULL, + `help` varchar(255) DEFAULT NULL, + `showInList` tinyint(1) unsigned DEFAULT NULL, + `typeId` tinyint(3) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fk_CustomFieldDefinition_typeId` (`typeId`), + CONSTRAINT `fk_CustomFieldDefinition_typeId` FOREIGN KEY (`typeId`) REFERENCES `CustomFieldType` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `CustomFieldType` +-- + +DROP TABLE IF EXISTS `CustomFieldType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `CustomFieldType` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `text` varchar(50) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `EventLog` +-- + +DROP TABLE IF EXISTS `EventLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `EventLog` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `date` int(10) unsigned NOT NULL, + `login` varchar(25) NOT NULL, + `userId` smallint(5) unsigned NOT NULL, + `ipAddress` varchar(45) NOT NULL, + `action` varchar(50) NOT NULL, + `description` text, + `level` varchar(20) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Notice` +-- + +DROP TABLE IF EXISTS `Notice`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Notice` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `type` varchar(100) DEFAULT NULL, + `component` varchar(100) NOT NULL, + `description` varchar(500) NOT NULL, + `date` int(10) unsigned NOT NULL, + `checked` tinyint(1) DEFAULT '0', + `userId` smallint(5) unsigned DEFAULT NULL, + `sticky` tinyint(1) DEFAULT '0', + `onlyAdmin` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + KEY `IDX_userId` (`userId`,`checked`,`date`), + KEY `IDX_component` (`component`,`date`,`checked`,`userId`), + CONSTRAINT `fk_Notice_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Plugin` +-- + +DROP TABLE IF EXISTS `Plugin`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Plugin` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `data` varbinary(5000) DEFAULT NULL, + `enabled` tinyint(1) NOT NULL DEFAULT '0', + `available` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `plugin_name_UNIQUE` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `PublicLink` +-- + +DROP TABLE IF EXISTS `PublicLink`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `PublicLink` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemId` int(10) unsigned NOT NULL, + `hash` varbinary(100) NOT NULL, + `data` longblob, + `userId` smallint(5) unsigned NOT NULL, + `typeId` int(10) unsigned NOT NULL, + `notify` tinyint(1) unsigned NOT NULL, + `dateAdd` int(10) unsigned NOT NULL, + `dateExpire` int(10) unsigned NOT NULL, + `countViews` smallint(5) unsigned DEFAULT '0', + `totalCountViews` smallint(5) unsigned DEFAULT '0', + `maxCountViews` smallint(5) unsigned NOT NULL, + `useInfo` blob, + PRIMARY KEY (`id`), + UNIQUE KEY `IDX_hash` (`hash`), + UNIQUE KEY `unique_publicLink_hash` (`hash`), + UNIQUE KEY `unique_publicLink_accountId` (`itemId`), + KEY `IDX_itemId` (`itemId`), + KEY `fk_PublicLink_userId` (`userId`), + CONSTRAINT `fk_PublicLink_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Tag` +-- + +DROP TABLE IF EXISTS `Tag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Tag` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(45) NOT NULL, + `hash` binary(40) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `tag_hash_UNIQUE` (`hash`), + KEY `IDX_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Track` +-- + +DROP TABLE IF EXISTS `Track`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Track` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `userId` smallint(5) unsigned DEFAULT NULL, + `source` varchar(100) NOT NULL, + `time` int(10) unsigned NOT NULL, + `ipv4` binary(4) NOT NULL, + `ipv6` binary(16) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `IDX_userId` (`userId`), + KEY `IDX_time-ip-source` (`time`,`ipv4`,`ipv6`,`source`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `User` +-- + +DROP TABLE IF EXISTS `User`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `User` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(80) NOT NULL, + `userGroupId` smallint(5) unsigned NOT NULL, + `login` varchar(50) NOT NULL, + `ssoLogin` varchar(100) DEFAULT NULL, + `pass` varbinary(1000) NOT NULL, + `mPass` varbinary(1000) DEFAULT NULL, + `mKey` varbinary(1000) NOT NULL, + `email` varchar(80) DEFAULT NULL, + `notes` text, + `loginCount` int(10) unsigned NOT NULL DEFAULT '0', + `userProfileId` smallint(5) unsigned NOT NULL, + `lastLogin` datetime DEFAULT NULL, + `lastUpdate` datetime DEFAULT NULL, + `lastUpdateMPass` int(11) unsigned NOT NULL DEFAULT '0', + `isAdminApp` tinyint(1) DEFAULT '0', + `isAdminAcc` tinyint(1) DEFAULT '0', + `isLdap` tinyint(1) DEFAULT '0', + `isDisabled` tinyint(1) DEFAULT '0', + `hashSalt` varbinary(128) NOT NULL, + `isMigrate` tinyint(1) DEFAULT '0', + `isChangePass` tinyint(1) DEFAULT '0', + `isChangedPass` tinyint(1) DEFAULT '0', `user_preferences` blob, - PRIMARY KEY (`user_id`), - UNIQUE KEY `IDX_login` (`user_login`, `user_ssoLogin`), - KEY `IDX_pass` (`user_pass`), - KEY `fk_usrData_groups_id_idx` (`user_groupId`), - KEY `fk_usrData_profiles_id_idx` (`user_profileId`), - CONSTRAINT `fk_usrData_groups_id` FOREIGN KEY (`user_groupId`) REFERENCES `usrGroups` (`usergroup_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_usrData_profiles_id` FOREIGN KEY (`user_profileId`) REFERENCES `usrProfiles` (`userprofile_id`) ON DELETE RESTRICT ON UPDATE RESTRICT + PRIMARY KEY (`id`), + UNIQUE KEY `IDX_login` (`login`,`ssoLogin`), + KEY `IDX_pass` (`pass`(767)), + KEY `fk_User_userGroupId` (`userGroupId`), + KEY `fk_User_userProfileId` (`userProfileId`), + CONSTRAINT `fk_User_userProfileId` FOREIGN KEY (`userProfileId`) REFERENCES `UserProfile` (`id`), + CONSTRAINT `fk_User_userGroupId` FOREIGN KEY (`userGroupId`) REFERENCES `UserGroup` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `UserGroup` +-- + +DROP TABLE IF EXISTS `UserGroup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `UserGroup` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `description` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `UserPassRecover` +-- + +DROP TABLE IF EXISTS `UserPassRecover`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `UserPassRecover` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `userId` smallint(5) unsigned NOT NULL, + `hash` varbinary(128) NOT NULL, + `date` int(10) unsigned NOT NULL, + `used` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + KEY `IDX_userId` (`userId`,`date`), + CONSTRAINT `fk_UserPassRecover_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `UserProfile` +-- + +DROP TABLE IF EXISTS `UserProfile`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `UserProfile` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(45) NOT NULL, + `profile` blob NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `UserToGroup` +-- + +DROP TABLE IF EXISTS `UserToGroup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `UserToGroup` ( + `userId` smallint(5) unsigned NOT NULL, + `userGroupId` smallint(5) unsigned NOT NULL, + KEY `IDX_usertogroup_userId` (`userId`), + KEY `fk_UserToGroup_userGroupId` (`userGroupId`), + CONSTRAINT `fk_UserToGroup_userGroupId` FOREIGN KEY (`userGroupId`) REFERENCES `UserGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_UserToGroup_userId` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -DROP TABLE IF EXISTS `accounts`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accounts` ( - `account_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `account_userGroupId` smallint(5) unsigned NOT NULL, - `account_userId` smallint(5) unsigned NOT NULL, - `account_userEditId` smallint(5) unsigned NOT NULL, - `account_customerId` int(10) unsigned NOT NULL, - `account_name` varchar(50) NOT NULL, - `account_categoryId` smallint(5) unsigned NOT NULL, - `account_login` varchar(50) DEFAULT NULL, - `account_url` varchar(255) DEFAULT NULL, - `account_pass` varbinary(1000) NOT NULL, - `account_key` varbinary(1000) NOT NULL, - `account_notes` text, - `account_countView` int(10) unsigned NOT NULL DEFAULT '0', - `account_countDecrypt` int(10) unsigned NOT NULL DEFAULT '0', - `account_dateAdd` datetime NOT NULL, - `account_dateEdit` datetime DEFAULT NULL, - `account_otherGroupEdit` bit(1) DEFAULT b'0', - `account_otherUserEdit` bit(1) DEFAULT b'0', - `account_isPrivate` bit(1) DEFAULT b'0', - `account_isPrivateGroup` BIT(1) NULL DEFAULT b'0', - `account_passDate` int(11) unsigned DEFAULT NULL, - `account_passDateChange` int(11) unsigned DEFAULT NULL, - `account_parentId` smallint(5) unsigned DEFAULT NULL, - PRIMARY KEY (`account_id`), - KEY `IDX_categoryId` (`account_categoryId`), - KEY `IDX_userId` (`account_userGroupId`,`account_userId`), - KEY `IDX_customerId` (`account_customerId`), - KEY `fk_accounts_user_id` (`account_userId`), - KEY `fk_accounts_user_edit_id` (`account_userEditId`), - CONSTRAINT `fk_accounts_user_id` FOREIGN KEY (`account_userId`) REFERENCES `usrData` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `fk_accounts_category_id` FOREIGN KEY (`account_categoryId`) REFERENCES `categories` (`category_id`) ON DELETE RESTRICT ON UPDATE CASCADE, - CONSTRAINT `fk_accounts_user_edit_id` FOREIGN KEY (`account_userEditId`) REFERENCES `usrData` (`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_accounts_customer_id` FOREIGN KEY (`account_customerId`) REFERENCES `customers` (`customer_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_accounts_userGroup_id` FOREIGN KEY (`account_userGroupId`) REFERENCES `usrGroups` (`usergroup_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accFavorites`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accFavorites` ( - `accfavorite_accountId` smallint(5) unsigned NOT NULL, - `accfavorite_userId` smallint(5) unsigned NOT NULL, - KEY `fk_accFavorites_accounts_idx` (`accfavorite_accountId`), - KEY `fk_accFavorites_users_idx` (`accfavorite_userId`), - KEY `search_idx` (`accfavorite_accountId`,`accfavorite_userId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accFiles`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accFiles` ( - `accfile_id` int(11) NOT NULL AUTO_INCREMENT, - `accfile_accountId` smallint(5) unsigned NOT NULL, - `accfile_name` varchar(100) NOT NULL, - `accfile_type` varchar(100) NOT NULL, - `accfile_size` int(11) NOT NULL, - `accfile_content` mediumblob NOT NULL, - `accfile_extension` varchar(10) NOT NULL, - `accFile_thumb` mediumblob, - PRIMARY KEY (`accfile_id`), - KEY `IDX_accountId` (`accfile_accountId`), - CONSTRAINT `fk_accFiles_accounts_id` FOREIGN KEY (`accfile_accountId`) REFERENCES `accounts` (`account_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accGroups`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accGroups` ( - `accgroup_accountId` smallint(5) unsigned NOT NULL, - `accgroup_groupId` smallint(5) unsigned NOT NULL, - KEY `IDX_accountId` (`accgroup_accountId`), - KEY `fk_accGroups_groups_id_idx` (`accgroup_groupId`), - CONSTRAINT `fk_accGroups_accounts_id` FOREIGN KEY (`accgroup_accountId`) REFERENCES `accounts` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_accGroups_groups_id` FOREIGN KEY (`accgroup_groupId`) REFERENCES `usrGroups` (`usergroup_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accHistory`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accHistory` ( - `acchistory_id` int(11) NOT NULL AUTO_INCREMENT, - `acchistory_accountId` smallint(5) unsigned NOT NULL, - `acchistory_userGroupId` smallint(5) unsigned NOT NULL, - `acchistory_userId` smallint(5) unsigned NOT NULL, - `acchistory_userEditId` smallint(5) unsigned NOT NULL, - `acchistory_customerId` int(10) unsigned NOT NULL, - `acchistory_name` varchar(255) NOT NULL, - `acchistory_categoryId` smallint(5) unsigned NOT NULL, - `acchistory_login` varchar(50) NOT NULL, - `acchistory_url` varchar(255) DEFAULT NULL, - `acchistory_pass` varbinary(1000) NOT NULL, - `acchistory_key` varbinary(1000) NOT NULL, - `acchistory_notes` text NOT NULL, - `acchistory_countView` int(10) unsigned NOT NULL DEFAULT '0', - `acchistory_countDecrypt` int(10) unsigned NOT NULL DEFAULT '0', - `acchistory_dateAdd` datetime NOT NULL, - `acchistory_dateEdit` datetime DEFAULT NULL, - `acchistory_isModify` bit(1) DEFAULT NULL, - `acchistory_isDeleted` bit(1) DEFAULT NULL, - `acchistory_mPassHash` varbinary(255) NOT NULL, - `accHistory_otherUserEdit` bit(1) DEFAULT b'0', - `accHistory_otherGroupEdit` bit(1) DEFAULT b'0', - `accHistory_passDate` int(10) unsigned DEFAULT NULL, - `accHistory_passDateChange` int(10) unsigned DEFAULT NULL, - `accHistory_parentId` smallint(5) unsigned DEFAULT NULL, - `accHistory_isPrivate` BIT(1) NULL DEFAULT b'0', - `accHistory_isPrivateGroup` BIT(1) NULL DEFAULT b'0', - PRIMARY KEY (`acchistory_id`), - KEY `IDX_accountId` (`acchistory_accountId`), - KEY `fk_accHistory_users_edit_id_idx` (`acchistory_userEditId`), - KEY `fk_accHistory_users_id` (`acchistory_userId`), - KEY `fk_accHistory_categories_id` (`acchistory_categoryId`), - KEY `fk_accHistory_customers_id` (`acchistory_customerId`), - CONSTRAINT `fk_accHistory_users_id` FOREIGN KEY (`acchistory_userId`) REFERENCES `usrData` (`user_id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `fk_accHistory_users_edit_id` FOREIGN KEY (`acchistory_userEditId`) REFERENCES `usrData` (`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_accHistory_category_id` FOREIGN KEY (`acchistory_categoryId`) REFERENCES `categories` (`category_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_accHistory_customer_id` FOREIGN KEY (`acchistory_customerId`) REFERENCES `customers` (`customer_id`) ON DELETE RESTRICT ON UPDATE RESTRICT, - CONSTRAINT `fk_accHistory_userGroup_id` FOREIGN KEY (`acchistory_userGroupId`) REFERENCES `usrGroups` (`usergroup_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `tags`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tags` ( - `tag_id` int unsigned NOT NULL AUTO_INCREMENT, - `tag_name` varchar(45) NOT NULL, - `tag_hash` binary(40) NOT NULL, - PRIMARY KEY (`tag_id`), - UNIQUE KEY `tag_hash_UNIQUE` (`tag_hash`), - KEY `IDX_name` (`tag_name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accTags`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accTags` ( - `acctag_accountId` smallint(10) unsigned NOT NULL, - `acctag_tagId` int(10) unsigned NOT NULL, - KEY `IDX_id` (`acctag_accountId`), - KEY `fk_accTags_tags_id_idx` (`acctag_tagId`), - CONSTRAINT `fk_accTags_accounts_id` FOREIGN KEY (`acctag_accountId`) REFERENCES `accounts` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_accTags_tags_id` FOREIGN KEY (`acctag_tagId`) REFERENCES `tags` (`tag_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `accUsers`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accUsers` ( - `accuser_accountId` smallint(5) unsigned NOT NULL, - `accuser_userId` smallint(5) unsigned NOT NULL, - KEY `idx_account` (`accuser_accountId`), - KEY `fk_accUsers_users_id_idx` (`accuser_userId`), - CONSTRAINT `fk_accUsers_accounts_id` FOREIGN KEY (`accuser_accountId`) REFERENCES `accounts` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_accUsers_users_id` FOREIGN KEY (`accuser_userId`) REFERENCES `usrData` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `authTokens`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `authTokens` ( - `authtoken_id` int(11) NOT NULL AUTO_INCREMENT, - `authtoken_userId` smallint(5) unsigned NOT NULL, - `authtoken_token` varbinary(100) NOT NULL, - `authtoken_actionId` smallint(5) unsigned NOT NULL, - `authtoken_createdBy` smallint(5) unsigned NOT NULL, - `authtoken_startDate` int(10) unsigned NOT NULL, - `authtoken_vault` varbinary(2000) NULL, - `authtoken_hash` varbinary(1000) NULL, - PRIMARY KEY (`authtoken_id`), - UNIQUE KEY `unique_authtoken_id` (`authtoken_id`), - KEY `IDX_checkToken` (`authtoken_userId`,`authtoken_actionId`,`authtoken_token`), - KEY `fk_authTokens_users_id_idx` (`authtoken_userId`,`authtoken_createdBy`), - KEY `fk_authTokens_users_createdby_id` (`authtoken_createdBy`), - CONSTRAINT `fk_authTokens_user_id` FOREIGN KEY (`authtoken_userId`) REFERENCES `usrData` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_authTokens_createdBy_id` FOREIGN KEY (`authtoken_createdBy`) REFERENCES `usrData` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `config`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `config` ( - `config_parameter` varchar(50) NOT NULL, - `config_value` varchar(2000) DEFAULT NULL, - UNIQUE KEY `vacParameter` (`config_parameter`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `customFieldsData`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `customFieldsData` ( - `customfielddata_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `customfielddata_moduleId` smallint(5) unsigned NOT NULL, - `customfielddata_itemId` int(10) unsigned NOT NULL, - `customfielddata_defId` int(10) unsigned NOT NULL, - `customfielddata_data` longblob, - `customfielddata_key` varbinary(1000) DEFAULT NULL, - PRIMARY KEY (`customfielddata_id`), - KEY `IDX_DEFID` (`customfielddata_defId`), - KEY `IDX_DELETE` (`customfielddata_itemId`,`customfielddata_moduleId`), - KEY `IDX_UPDATE` (`customfielddata_moduleId`,`customfielddata_itemId`,`customfielddata_defId`), - KEY `IDX_ITEM` (`customfielddata_itemId`), - KEY `IDX_MODULE` (`customfielddata_moduleId`), - CONSTRAINT `fk_customFieldsData_def_id` FOREIGN KEY (`customfielddata_defId`) REFERENCES `customFieldsDef` (`customfielddef_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `customFieldsDef`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `customFieldsDef` ( - `customfielddef_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `customfielddef_module` smallint(5) unsigned NOT NULL, - `customfielddef_field` blob NOT NULL, - PRIMARY KEY (`customfielddef_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `log`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `log` ( - `log_id` int unsigned NOT NULL AUTO_INCREMENT, - `log_date` int(10) unsigned NOT NULL, - `log_login` varchar(25) NOT NULL, - `log_userId` smallint(5) unsigned NOT NULL, - `log_ipAddress` varchar(45) NOT NULL, - `log_action` varchar(50) NOT NULL, - `log_description` text, - `log_level` varchar(20) NOT NULL, - PRIMARY KEY (`log_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `publicLinks`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `publicLinks` ( - `publicLink_id` int UNSIGNED NOT NULL AUTO_INCREMENT, - `publicLink_itemId` int UNSIGNED DEFAULT NULL, - `publicLink_hash` varbinary(100) NOT NULL, - `publicLink_linkData` longblob, - PRIMARY KEY (`publicLink_id`), - UNIQUE KEY `IDX_hash` (`publicLink_hash`), - UNIQUE KEY `unique_publicLink_hash` (`publicLink_hash`), - UNIQUE KEY `unique_publicLink_accountId` (`publicLink_itemId`), - KEY `IDX_itemId` (`publicLink_itemId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `usrPassRecover`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `usrPassRecover` ( - `userpassr_id` int unsigned NOT NULL AUTO_INCREMENT, - `userpassr_userId` smallint(5) unsigned NOT NULL, - `userpassr_hash` varbinary(40) NOT NULL, - `userpassr_date` int unsigned NOT NULL, - `userpassr_used` bit(1) DEFAULT b'0', - PRIMARY KEY (`userpassr_id`), - KEY `IDX_userId` (`userpassr_userId`,`userpassr_date`), - CONSTRAINT `fk_usrPassRecover_users` FOREIGN KEY (`userpassr_userId`) REFERENCES `usrData` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `usrToGroups`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `usrToGroups` ( - `usertogroup_userId` smallint(5) unsigned NOT NULL, - `usertogroup_groupId` smallint(5) unsigned NOT NULL, - KEY `IDX_usertogroup_userId` (`usertogroup_userId`), - KEY `fk_usrToGroups_groups_id_idx` (`usertogroup_groupId`), - CONSTRAINT `fk_usrToGroups_groups_id` FOREIGN KEY (`usertogroup_groupId`) REFERENCES `usrGroups` (`usergroup_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_usrToGroups_users_id` FOREIGN KEY (`usertogroup_userId`) REFERENCES `usrData` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `plugins`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `plugins` ( - `plugin_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, - `plugin_name` VARCHAR(100) NOT NULL, - `plugin_data` VARBINARY(5000) NULL, - `plugin_enabled` BIT(1) NOT NULL DEFAULT b'0', - PRIMARY KEY (`plugin_id`), - UNIQUE INDEX `plugin_name_UNIQUE` (`plugin_name` ASC) -) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `notices`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `notices` ( - `notice_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, - `notice_type` VARCHAR(100) NULL, - `notice_component` VARCHAR(100) NOT NULL, - `notice_description` VARCHAR(500) NOT NULL, - `notice_date` INT UNSIGNED NOT NULL, - `notice_checked` BIT(1) NULL DEFAULT b'0', - `notice_userId` SMALLINT(5) UNSIGNED NULL, - `notice_sticky` BIT(1) NULL DEFAULT b'0', - `notice_onlyAdmin` BIT(1) NULL DEFAULT b'0', - PRIMARY KEY (`notice_id`), - INDEX `IDX_userId` (`notice_userId` ASC, `notice_checked` ASC, `notice_date` ASC), - INDEX `IDX_component` (`notice_component` ASC, `notice_date` ASC, `notice_checked` ASC, `notice_userId` ASC) -) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `track`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `track` ( - `track_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, - `track_userId` SMALLINT(5) UNSIGNED NULL, - `track_source` VARCHAR(100) NOT NULL, - `track_time` INT UNSIGNED NOT NULL, - `track_ipv4` BINARY(4) NOT NULL, - `track_ipv6` BINARY(16) NULL, - PRIMARY KEY (`track_id`), - INDEX `IDX_userId` (`track_userId` ASC), - INDEX `IDX_time-ip-source` (`track_time` ASC, `track_ipv4` ASC, `track_ipv6` ASC, `track_source` ASC) -) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -DROP TABLE IF EXISTS `actions`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `actions` ( - `action_id` SMALLINT(5) UNSIGNED NOT NULL, - `action_name` VARCHAR(50) NOT NULL, - `action_text` VARCHAR(100) NOT NULL, - `action_route` VARCHAR(100), - PRIMARY KEY (`action_id`, `action_name`) -) ENGINE = InnoDB DEFAULT CHARSET = utf8; -/*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `account_data_v` +-- DROP TABLE IF EXISTS `account_data_v`; -CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `account_data_v` AS - SELECT - `accounts`.`account_id` AS `account_id`, - `accounts`.`account_name` AS `account_name`, - `accounts`.`account_categoryId` AS `account_categoryId`, - `accounts`.`account_userId` AS `account_userId`, - `accounts`.`account_customerId` AS `account_customerId`, - `accounts`.`account_userGroupId` AS `account_userGroupId`, - `accounts`.`account_userEditId` AS `account_userEditId`, - `accounts`.`account_login` AS `account_login`, - `accounts`.`account_url` AS `account_url`, - `accounts`.`account_notes` AS `account_notes`, - `accounts`.`account_countView` AS `account_countView`, - `accounts`.`account_countDecrypt` AS `account_countDecrypt`, - `accounts`.`account_dateAdd` AS `account_dateAdd`, - `accounts`.`account_dateEdit` AS `account_dateEdit`, - CONV(`accounts`.`account_otherUserEdit`, - 10, - 2) AS `account_otherUserEdit`, - CONV(`accounts`.`account_otherGroupEdit`, - 10, - 2) AS `account_otherGroupEdit`, - CONV(`accounts`.`account_isPrivate`, 10, 2) AS `account_isPrivate`, - CONV(`accounts`.`account_isPrivateGroup`, 10, 2) AS `account_isPrivateGroup`, - `accounts`.`account_passDate` AS `account_passDate`, - `accounts`.`account_passDateChange` AS `account_passDateChange`, - `accounts`.`account_parentId` AS `account_parentId`, - `categories`.`category_name` AS `category_name`, - `customers`.`customer_name` AS `customer_name`, - `ug`.`usergroup_name` AS `usergroup_name`, - `u1`.`user_name` AS `user_name`, - `u1`.`user_login` AS `user_login`, - `u2`.`user_name` AS `user_editName`, - `u2`.`user_login` AS `user_editLogin`, - `publicLinks`.`publicLink_hash` AS `publicLink_hash` - FROM - ((((((`accounts` - LEFT JOIN `categories` ON ((`accounts`.`account_categoryId` = `categories`.`category_id`))) - LEFT JOIN `usrGroups` `ug` ON ((`accounts`.`account_userGroupId` = `ug`.`usergroup_id`))) - LEFT JOIN `usrData` `u1` ON ((`accounts`.`account_userId` = `u1`.`user_id`))) - LEFT JOIN `usrData` `u2` ON ((`accounts`.`account_userEditId` = `u2`.`user_id`))) - LEFT JOIN `customers` ON ((`accounts`.`account_customerId` = `customers`.`customer_id`))) - LEFT JOIN `publicLinks` ON ((`accounts`.`account_id` = `publicLinks`.`publicLink_itemId`))); +/*!50001 DROP VIEW IF EXISTS `account_data_v`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `account_data_v` ( + `id` tinyint NOT NULL, + `name` tinyint NOT NULL, + `categoryId` tinyint NOT NULL, + `userId` tinyint NOT NULL, + `clientId` tinyint NOT NULL, + `userGroupId` tinyint NOT NULL, + `userEditId` tinyint NOT NULL, + `login` tinyint NOT NULL, + `url` tinyint NOT NULL, + `notes` tinyint NOT NULL, + `countView` tinyint NOT NULL, + `countDecrypt` tinyint NOT NULL, + `dateAdd` tinyint NOT NULL, + `dateEdit` tinyint NOT NULL, + `otherUserEdit` tinyint NOT NULL, + `otherUserGroupEdit` tinyint NOT NULL, + `isPrivate` tinyint NOT NULL, + `isPrivateGroup` tinyint NOT NULL, + `passDate` tinyint NOT NULL, + `passDateChange` tinyint NOT NULL, + `parentId` tinyint NOT NULL, + `categoryName` tinyint NOT NULL, + `clientName` tinyint NOT NULL, + `userGroupName` tinyint NOT NULL, + `userName` tinyint NOT NULL, + `userLogin` tinyint NOT NULL, + `userEditName` tinyint NOT NULL, + `userEditLogin` tinyint NOT NULL, + `publicLinkHash` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `account_search_v` +-- DROP TABLE IF EXISTS `account_search_v`; -CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `account_search_v` AS - SELECT DISTINCT - `accounts`.`account_id` AS `account_id`, - `accounts`.`account_customerId` AS `account_customerId`, - `accounts`.`account_categoryId` AS `account_categoryId`, - `accounts`.`account_name` AS `account_name`, - `accounts`.`account_login` AS `account_login`, - `accounts`.`account_url` AS `account_url`, - `accounts`.`account_notes` AS `account_notes`, - `accounts`.`account_userId` AS `account_userId`, - `accounts`.`account_userGroupId` AS `account_userGroupId`, - `accounts`.`account_otherUserEdit` AS `account_otherUserEdit`, - `accounts`.`account_otherGroupEdit` AS `account_otherGroupEdit`, - `accounts`.`account_isPrivate` AS `account_isPrivate`, - `accounts`.`account_isPrivateGroup` AS `account_isPrivateGroup`, - `accounts`.`account_passDate` AS `account_passDate`, - `accounts`.`account_passDateChange` AS `account_passDateChange`, - `accounts`.`account_parentId` AS `account_parentId`, - `accounts`.`account_countView` AS `account_countView`, - `ug`.`usergroup_name` AS `usergroup_name`, - `categories`.`category_name` AS `category_name`, - `customers`.`customer_name` AS `customer_name`, - (SELECT - COUNT(0) - FROM - `accFiles` - WHERE - (`accFiles`.accountId = `accounts`.`account_id`)) AS `num_files` - FROM - (((`accounts` - LEFT JOIN `categories` ON ((`accounts`.`account_categoryId` = `categories`.`category_id`))) - LEFT JOIN `usrGroups` `ug` ON ((`accounts`.`account_userGroupId` = `ug`.`usergroup_id`))) - LEFT JOIN `customers` ON ((`customers`.`customer_id` = `accounts`.`account_customerId`))); +/*!50001 DROP VIEW IF EXISTS `account_search_v`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `account_search_v` ( + `id` tinyint NOT NULL, + `clientId` tinyint NOT NULL, + `categoryId` tinyint NOT NULL, + `name` tinyint NOT NULL, + `login` tinyint NOT NULL, + `url` tinyint NOT NULL, + `notes` tinyint NOT NULL, + `userId` tinyint NOT NULL, + `userGroupId` tinyint NOT NULL, + `otherUserEdit` tinyint NOT NULL, + `otherUserGroupEdit` tinyint NOT NULL, + `isPrivate` tinyint NOT NULL, + `isPrivateGroup` tinyint NOT NULL, + `passDate` tinyint NOT NULL, + `passDateChange` tinyint NOT NULL, + `parentId` tinyint NOT NULL, + `countView` tinyint NOT NULL, + `userGroupName` tinyint NOT NULL, + `categoryName` tinyint NOT NULL, + `customerName` tinyint NOT NULL, + `num_files` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1, 'ACCOUNT_SEARCH', 'Buscar Cuentas', 'account/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (10, 'ACCOUNT', 'Cuentas', 'account/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (11, 'ACCOUNT_FILE', 'Archivos', 'account/listFile'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (12, 'ACCOUNT_REQUEST', 'Peticiones', 'account/request'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (13, 'ACCOUNT_FAVORITE', 'Favoritos', 'favorite/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (20, 'WIKI', 'Wiki', 'wiki/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (60, 'ITEMS_MANAGE', 'Elementos y Personalización', 'itemManager/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (61, 'CATEGORY', 'Gestión Categorías', 'category/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (62, 'CLIENT', 'Gestión Clientes', 'client/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (63, 'APITOKEN', 'Gestión Autorizaciones API', 'apiToken/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (64, 'CUSTOMFIELD', 'Gestión Campos Personalizados', 'customField/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (65, 'PUBLICLINK', 'Enlaces Públicos', 'publicLink/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (66, 'FILE', 'Gestión de Archivos', 'file/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (67, 'ACCOUNTMGR', 'Gestión de Cuentas', 'accountManager/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (68, 'TAG', 'Gestión de Etiquetas', 'tag/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (69, 'PLUGIN', 'Gestión Plugins', 'plugin/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (70, 'ACCESS_MANAGE', 'Usuarios y Accesos', 'accessManager/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (71, 'USER', 'Gestión Usuarios', 'user/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (72, 'GROUP', 'Gestión Grupos', 'group/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (73, 'PROFILE', 'Gestión Perfiles', 'profile/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (90, 'EVENTLOG', 'Registro de Eventos', 'eventlog/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (100, 'ACCOUNT_VIEW', 'Ver Cuenta', 'account/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (101, 'ACCOUNT_CREATE', 'Nueva Cuenta', 'account/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (102, 'ACCOUNT_EDIT', 'Editar Cuenta', 'account/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (103, 'ACCOUNT_DELETE', 'Eliminar Cuenta', 'account/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (104, 'ACCOUNT_VIEW_PASS', 'Ver Clave', 'account/viewPass'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (105, 'ACCOUNT_VIEW_HISTORY', 'Ver Historial', 'account/viewHistory'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (106, 'ACCOUNT_EDIT_PASS', 'Editar Clave de Cuenta', 'account/editPass'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (107, 'ACCOUNT_EDIT_RESTORE', 'Restaurar Cuenta', 'account/restore'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (108, 'ACCOUNT_COPY', 'Copiar Cuenta', 'account/copy'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (109, 'ACCOUNT_COPY_PASS', 'Copiar Clave', 'account/copyPass'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (111, 'ACCOUNT_FILE_VIEW', 'Ver Archivo', 'account/viewFile'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (112, 'ACCOUNT_FILE_UPLOAD', 'Subir Archivo', 'account/uploadFile'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (113, 'ACCOUNT_FILE_DOWNLOAD', 'Descargar Archivo', 'account/downloadFile'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (114, 'ACCOUNT_FILE_DELETE', 'Eliminar Archivo', 'account/deleteFile'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (130, 'ACCOUNT_FAVORITE_VIEW', 'Ver Favoritos', 'favorite/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (131, 'ACCOUNT_FAVORITE_ADD', 'Añadir Favorito', 'favorite/add'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (133, 'ACCOUNT_FAVORITE_DELETE', 'Eliminar Favorito', 'favorite/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (200, 'WIKI_VIEW', 'Ver Wiki', 'wiki/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (201, 'WIKI_NEW', 'Añadir Wiki', 'wiki/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (202, 'WIKI_EDIT', 'Editar Wiki', 'wiki/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (203, 'WIKI_DELETE', 'Eliminar Wiki', 'wiki/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (610, 'CATEGORY_VIEW', 'Ver Categoría', 'category/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (611, 'CATEGORY_CREATE', 'Nueva Categoría', 'category/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (612, 'CATEGORY_EDIT', 'Editar Categoría', 'category/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (613, 'CATEGORY_DELETE', 'Eliminar Categoría', 'category/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (615, 'CATEGORY_SEARCH', 'Buscar Categoría', 'category/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (620, 'CLIENT_VIEW', 'Ver Cliente', 'client/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (621, 'CLIENT_CREATE', 'Nuevo CLiente', 'client/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (622, 'CLIENT_EDIT', 'Editar Cliente', 'client/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (623, 'CLIENT_DELETE', 'Eliminar Cliente', 'client/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (625, 'CLIENT_SEARCH', 'Buscar Cliente', 'client/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (630, 'APITOKEN_CREATE', 'Nuevo Token API', 'apiToken/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (631, 'APITOKEN_VIEW', 'Ver Token API', 'apiToken/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (632, 'APITOKEN_EDIT', 'Editar Token API', 'apiToken/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (633, 'APITOKEN_DELETE', 'Eliminar Token API', 'apiToken/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (635, 'APITOKEN_SEARCH', 'Buscar Token API', 'apiToken/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (640, 'CUSTOMFIELD_CREATE', 'Nuevo Campo Personalizado', 'customField/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (641, 'CUSTOMFIELD_VIEW', 'Ver Campo Personalizado', 'customField/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (642, 'CUSTOMFIELD_EDIT', 'Editar Campo Personalizado', 'customField/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (643, 'CUSTOMFIELD_DELETE', 'Eliminar Campo Personalizado', 'customField/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (645, 'CUSTOMFIELD_SEARCH', 'Buscar Campo Personalizado', 'customField/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (650, 'PUBLICLINK_CREATE', 'Crear Enlace Público', 'publicLink/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (651, 'PUBLICLINK_VIEW', 'Ver Enlace Público', 'publicLink/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (653, 'PUBLICLINK_DELETE', 'Eliminar Enlace Público', 'publicLink/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (654, 'PUBLICLINK_REFRESH', 'Actualizar Enlace Público', 'publicLink/refresh'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (655, 'PUBLICLINK_SEARCH', 'Buscar Enlace Público', 'publicLink/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (661, 'FILE_VIEW', 'Ver Archivo', 'file/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (663, 'FILE_DELETE', 'Eliminar Archivo', 'file/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (665, 'FILE_SEARCH', 'Buscar Archivo', 'file/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (671, 'ACCOUNTMGR_VIEW', 'Ver Cuenta', 'accountManager/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (673, 'ACCOUNTMGR_DELETE', 'Eliminar Cuenta', 'accountManager/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (675, 'ACCOUNTMGR_SEARCH', 'Buscar Cuenta', 'accountManager/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (680, 'TAG_CREATE', 'Nueva Etiqueta', 'tag/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (681, 'TAG_VIEW', 'Ver Etiqueta', 'tag/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (682, 'TAG_EDIT', 'Editar Etiqueta', 'tag/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (683, 'TAG_DELETE', 'Eliminar Etiqueta', 'tag/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (685, 'TAG_SEARCH', 'Buscar Etiqueta', 'tag/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (690, 'PLUGIN_NEW', 'Nuevo Plugin', 'plugin/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (691, 'PLUGIN_VIEW', 'Ver Plugin', 'plugin/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (695, 'PLUGIN_SEARCH', 'Buscar Plugin', 'plugin/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (696, 'PLUGIN_ENABLE', 'Habilitar Plugin', 'plugin/enable'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (697, 'PLUGIN_DISABLE', 'Deshabilitar Plugin', 'plugin/disable'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (698, 'PLUGIN_RESET', 'Restablecer Plugin', 'plugin/reset'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (710, 'USER_VIEW', 'Ver Usuario', 'user/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (711, 'USER_CREATE', 'Nuevo Usuario', 'user/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (712, 'USER_EDIT', 'Editar Usuario', 'user/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (713, 'USER_DELETE', 'Eliminar Usuario', 'user/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (714, 'USER_EDIT_PASS', 'Editar Clave Usuario', 'user/editPass'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (715, 'USER_SEARCH', 'Buscar Usuario', 'user/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (720, 'GROUP_VIEW', 'Ver Grupo', 'userGroup/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (721, 'GROUP_CREATE', 'Nuevo Grupo', 'userGroup/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (722, 'GROUP_EDIT', 'Editar Grupo', 'userGroup/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (723, 'GROUP_DELETE', 'Eliminar Grupo', 'userGroup/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (725, 'GROUP_SEARCH', 'Buscar Grupo', 'userGroup/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (730, 'PROFILE_VIEW', 'Ver Perfil', 'userProfile/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (731, 'PROFILE_CREATE', 'Nuevo Perfil', 'userProfile/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (732, 'PROFILE_EDIT', 'Editar Perfil', 'userProfile/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (733, 'PROFILE_DELETE', 'Eliminar Perfil', 'userProfile/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (735, 'PROFILE_SEARCH', 'Buscar Perfil', 'userProfile/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (740, 'PREFERENCE', 'Gestión Preferencias', 'userPreference/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (741, 'PREFERENCE_GENERAL', 'Preferencias General', 'userPreference/general'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (742, 'PREFERENCE_SECURITY', 'Preferencias Seguridad', 'userPreference/security'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (760, 'NOTICE', 'Notificaciones', 'notice/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (761, 'NOTICE_USER', 'Notificaciones Usuario', 'noticeUser/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1000, 'CONFIG', 'Configuración', 'config/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1001, 'CONFIG_GENERAL', 'Configuración General', 'config/general'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1010, 'ACCOUNT_CONFIG', 'Configuración Cuentas', 'account/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1020, 'WIKI_CONFIG', 'Configuración Wiki', 'wiki/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1030, 'ENCRYPTION_CONFIG', 'Configuración Encriptación', 'encryption/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1031, 'ENCRYPTION_REFRESH', 'Actualizar Hash', 'encryption/updateHash'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1032, 'ENCRYPTION_TEMPPASS', 'Clave Maestra Temporal', 'encryption/createTempPass'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1040, 'BACKUP_CONFIG', 'Configuración Copia de Seguridad', 'backup/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1050, 'IMPORT_CONFIG', 'Configuración Importación', 'import/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1051, 'IMPORT_CSV', 'Importar CSV', 'import/csv'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1052, 'IMPORT_XML', 'Importar XML', 'import/xml'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1070, 'MAIL_CONFIG', 'Configuración Email', 'mail/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1080, 'LDAP_CONFIG', 'Configuración LDAP', 'ldap/config'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (1081, 'LDAP_SYNC', 'Sincronización LDAP', 'ldap/sync'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (6701, 'ACCOUNTMGR_HISTORY', 'Gestión de Cuenta (H)', 'accountHistoryManager/index'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (6731, 'ACCOUNTMGR_DELETE_HISTORY', 'Eliminar Cuenta', 'accountHistoryManager/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (6751, 'ACCOUNTMGR_SEARCH_HISTORY', 'Buscar Cuenta', 'accountHistoryManager/search'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (6771, 'ACCOUNTMGR_RESTORE', 'Restaurar Cuenta', 'accountManager/restore'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7610, 'NOTICE_USER_VIEW', 'Ver Notificación', 'userNotice/view'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7611, 'NOTICE_USER_CREATE', 'Crear Notificación', 'userNotice/create'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7612, 'NOTICE_USER_EDIT', 'Editar Notificación', 'userNotice/edit'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7613, 'NOTICE_USER_DELETE', 'Eliminar Notificación', 'userNotice/delete'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7614, 'NOTICE_USER_CHECK', 'Marcar Notificación', 'userNotice/check'); -INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES (7615, 'NOTICE_USER_SEARCH', 'Buscar Notificación', 'userNotice/search'); +-- +-- Final view structure for view `account_data_v` +-- + +/*!50001 DROP TABLE IF EXISTS `account_data_v`*/; +/*!50001 DROP VIEW IF EXISTS `account_data_v`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`172.18.0.1` SQL SECURITY DEFINER */ +/*!50001 VIEW `account_data_v` AS select `Account`.`id` AS `id`,`Account`.`name` AS `name`,`Account`.`categoryId` AS `categoryId`,`Account`.`userId` AS `userId`,`Account`.`clientId` AS `clientId`,`Account`.`userGroupId` AS `userGroupId`,`Account`.`userEditId` AS `userEditId`,`Account`.`login` AS `login`,`Account`.`url` AS `url`,`Account`.`notes` AS `notes`,`Account`.`countView` AS `countView`,`Account`.`countDecrypt` AS `countDecrypt`,`Account`.`dateAdd` AS `dateAdd`,`Account`.`dateEdit` AS `dateEdit`,conv(`Account`.`otherUserEdit`,10,2) AS `otherUserEdit`,conv(`Account`.`otherUserGroupEdit`,10,2) AS `otherUserGroupEdit`,conv(`Account`.`isPrivate`,10,2) AS `isPrivate`,conv(`Account`.`isPrivateGroup`,10,2) AS `isPrivateGroup`,`Account`.`passDate` AS `passDate`,`Account`.`passDateChange` AS `passDateChange`,`Account`.`parentId` AS `parentId`,`Category`.`name` AS `categoryName`,`Client`.`name` AS `clientName`,`ug`.`name` AS `userGroupName`,`u1`.`name` AS `userName`,`u1`.`login` AS `userLogin`,`u2`.`name` AS `userEditName`,`u2`.`login` AS `userEditLogin`,`PublicLink`.`hash` AS `publicLinkHash` from ((((((`Account` left join `Category` on((`Account`.`categoryId` = `Category`.`id`))) join `UserGroup` `ug` on((`Account`.`userGroupId` = `ug`.`id`))) join `User` `u1` on((`Account`.`userId` = `u1`.`id`))) join `User` `u2` on((`Account`.`userEditId` = `u2`.`id`))) left join `Client` on((`Account`.`clientId` = `Client`.`id`))) left join `PublicLink` on((`Account`.`id` = `PublicLink`.`itemId`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `account_search_v` +-- + +/*!50001 DROP TABLE IF EXISTS `account_search_v`*/; +/*!50001 DROP VIEW IF EXISTS `account_search_v`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`172.18.0.1` SQL SECURITY DEFINER */ +/*!50001 VIEW `account_search_v` AS select distinct `Account`.`id` AS `id`,`Account`.`clientId` AS `clientId`,`Account`.`categoryId` AS `categoryId`,`Account`.`name` AS `name`,`Account`.`login` AS `login`,`Account`.`url` AS `url`,`Account`.`notes` AS `notes`,`Account`.`userId` AS `userId`,`Account`.`userGroupId` AS `userGroupId`,`Account`.`otherUserEdit` AS `otherUserEdit`,`Account`.`otherUserGroupEdit` AS `otherUserGroupEdit`,`Account`.`isPrivate` AS `isPrivate`,`Account`.`isPrivateGroup` AS `isPrivateGroup`,`Account`.`passDate` AS `passDate`,`Account`.`passDateChange` AS `passDateChange`,`Account`.`parentId` AS `parentId`,`Account`.`countView` AS `countView`,`ug`.`name` AS `userGroupName`,`Category`.`name` AS `categoryName`,`Client`.`name` AS `customerName`,(select count(0) from `AccountFile` where (`AccountFile`.`accountId` = `Account`.`id`)) AS `num_files` from (((`Account` join `Category` on((`Account`.`categoryId` = `Category`.`id`))) join `UserGroup` `ug` on((`Account`.`userGroupId` = `ug`.`id`))) join `Client` on((`Client`.`id` = `Account`.`clientId`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -663,4 +707,6 @@ INSERT INTO actions (action_id, action_name, action_text, action_route) VALUES ( /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; \ No newline at end of file +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2018-01-01 13:45:54