diff --git a/ajax/ajax_accountSave.php b/ajax/ajax_accountSave.php
index 5bd93d08..33905edf 100644
--- a/ajax/ajax_accountSave.php
+++ b/ajax/ajax_accountSave.php
@@ -1,5 +1,4 @@
accountCustomerId = SP_Customer::$customerLastId;
+ $account->setAccountCustomerId(SP\Customer::$customerLastId);
} else {
- $account->accountCustomerId = $frmSelCustomer;
+ $account->setAccountCustomerId($customerId);
}
- $account->accountName = $frmName;
- $account->accountCategoryId = $frmCategoryId;
- $account->accountLogin = $frmLogin;
- $account->accountUrl = $frmUrl;
- $account->accountPass = $accountPass;
- $account->accountIV = $accountIV;
- $account->accountNotes = $frmNotes;
- $account->accountUserId = $userId;
- $account->accountUserGroupId = $groupId;
- $account->accountUserGroupsId = $frmOtherGroups;
- $account->accountUsersId = $frmOtherUsers;
- $account->accountOtherUserEdit = $frmUserEditEnabled;
- $account->accountOtherGroupEdit = $frmGroupEditEnabled;
+ $account->setAccountName($accountName);
+ $account->setAccountCategoryId($categoryId);
+ $account->setAccountLogin($accountLogin);
+ $account->setAccountUrl($accountUrl);
+ $account->setAccountPass($accountPass);
+ $account->setAccountIV($accountIV);
+ $account->setAccountNotes($accountNotes);
+ $account->setAccountUserId($currentUserId);
+ $account->setAccountUserGroupId($currentGroupId);
+ $account->setAccountUsersId($accountOtherUsers);
+ $account->setAccountUserGroupsId($accountOtherGroups);
+ $account->setAccountOtherUserEdit($accountUserEditEnabled);
+ $account->setAccountOtherGroupEdit($accountGroupEditEnabled);
// Crear cuenta
if ($account->createAccount()) {
- SP_Common::printJSON(_('Cuenta creada'), 0);
+ SP\Common::printJSON(_('Cuenta creada'), 0);
}
- SP_Common::printJSON(_('Error al crear la cuenta'), 0);
+ SP\Common::printJSON(_('Error al crear la cuenta'), 0);
break;
- case 2: // Modificar Cuenta
- SP_Customer::$customerName = $frmNewCustomer;
- $account->accountId = $frmAccountId;
- $account->accountName = $frmName;
- $account->accountCategoryId = $frmCategoryId;
- $account->accountLogin = $frmLogin;
- $account->accountUrl = $frmUrl;
- $account->accountNotes = $frmNotes;
- $account->accountUserEditId = $userId;
- $account->accountUserGroupsId = $frmOtherGroups;
- $account->accountUsersId = $frmOtherUsers;
- $account->accountOtherUserEdit = $frmUserEditEnabled;
- $account->accountOtherGroupEdit = $frmGroupEditEnabled;
+ case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT:
+ SP\Customer::$customerName = $newCustomer;
+
+ $account->setAccountId($accountId);
+ $account->setAccountName($accountName);
+ $account->setAccountCategoryId($categoryId);
+ $account->setAccountLogin($accountLogin);
+ $account->setAccountUrl($accountUrl);
+ $account->setAccountNotes($accountNotes);
+ $account->setAccountUserEditId($currentUserId);
+ $account->setAccountUsersId($accountOtherUsers);
+ $account->setAccountUserGroupsId($accountOtherGroups);
+ $account->setAccountOtherUserEdit($accountUserEditEnabled);
+ $account->setAccountOtherGroupEdit($accountGroupEditEnabled);
// Comprobar si se ha introducido un nuevo cliente
- if ($frmNewCustomer) {
- if (SP_Customer::checkDupCustomer()) {
- SP_Common::printJSON(_('Cliente duplicado'));
+ if ($newCustomer) {
+ if (SP\Customer::checkDupCustomer()) {
+ SP\Common::printJSON(_('Cliente duplicado'));
+ } elseif (!SP\Customer::addCustomer()) {
+ SP\Common::printJSON(_('Error al crear el cliente'));
}
- if (!SP_Customer::addCustomer()) {
- SP_Common::printJSON(_('Error al crear el cliente'));
- }
-
- $account->accountCustomerId = SP_Customer::$customerLastId;
+ $account->setAccountCustomerId(SP\Customer::$customerLastId);
} else {
- $account->accountCustomerId = $frmSelCustomer;
+ $account->setAccountCustomerId($customerId);
}
// Comprobar si han habido cambios
- if ($frmChangesHash == $account->calcChangesHash()) {
- SP_Common::printJSON(_('Sin cambios'), 0);
+ if ($accountChangesHash == $account->calcChangesHash()) {
+ SP\Common::printJSON(_('Sin cambios'), 0);
}
// Actualizar cuenta
if ($account->updateAccount()) {
- SP_Common::printJSON(_('Cuenta actualizada'), 0);
+ SP\Common::printJSON(_('Cuenta actualizada'), 0);
}
- SP_Common::printJSON(_('Error al modificar la cuenta'));
+ SP\Common::printJSON(_('Error al modificar la cuenta'));
break;
- case 3: // Eliminar Cuenta
- $account->accountId = $frmAccountId;
+ case \SP\Controller\ActionsInterface::ACTION_ACC_DELETE:
+ $account->setAccountId($accountId);
// Eliminar cuenta
if ($account->deleteAccount()) {
- SP_Common::printJSON(_('Cuenta eliminada'), 0, "doAction('accsearch');");
+ SP\Common::printJSON(_('Cuenta eliminada'), 0, "doAction('accsearch');");
}
- SP_Common::printJSON(_('Error al eliminar la cuenta'));
+ SP\Common::printJSON(_('Error al eliminar la cuenta'));
break;
- case 4: // Modificar Clave
- $account->accountId = $frmAccountId;
- $account->accountPass = $accountPass;
- $account->accountIV = $accountIV;
- $account->accountUserEditId = $userId;
+ case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_PASS:
+ $account->setAccountId($accountId);
+ $account->setAccountPass($accountPass);
+ $account->setAccountIV($accountIV);
+ $account->setAccountUserEditId($currentUserId);
// Actualizar clave de cuenta
if ($account->updateAccountPass()) {
- SP_Common::printJSON(_('Clave actualizada'), 0);
+ SP\Common::printJSON(_('Clave actualizada'), 0);
}
- SP_Common::printJSON(_('Error al actualizar la clave'));
+ SP\Common::printJSON(_('Error al actualizar la clave'));
break;
- case 5: // Restaurar Cuenta
- $account->accountId = $frmAccountId;
- $accountHistData = $account->getAccountHistory();
+ case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_RESTORE:
+ $account->setAccountId(SP\AccountHistory::getAccountIdFromId($accountId));
+ $account->setAccountUserEditId($currentUserId);
- $account->accountId = $accountHistData->account_id;
- $account->accountName = $accountHistData->account_name;
- $account->accountCategoryId = $accountHistData->account_categoryId;
- $account->accountCustomerId = $accountHistData->account_customerId;
- $account->accountLogin = $accountHistData->account_login;
- $account->accountUrl = $accountHistData->account_url;
- $account->accountPass = $accountHistData->account_pass;
- $account->accountIV = $accountHistData->account_IV;
- $account->accountNotes = $accountHistData->account_notes;
- $account->accountUserId = $accountHistData->account_userId;
- $account->accountUserGroupId = $accountHistData->account_userGroupId;
- $account->accountOtherUserEdit = $accountHistData->account_otherUserEdit;
- $account->accountOtherGroupEdit = $accountHistData->account_otherGroupEdit;
- $account->accountUserEditId = $userId;
-
- // Restaurar cuenta y clave
- if ($account->updateAccount(true) && $account->updateAccountPass(false, true)) {
- SP_Common::printJSON(_('Cuenta restaurada'), 0);
+ if ($account->restoreFromHistory($accountId)) {
+ SP\Common::printJSON(_('Cuenta restaurada'), 0);
}
- SP_Common::printJSON(_('Error al restaurar cuenta'));
+ SP\Common::printJSON(_('Error al restaurar cuenta'));
+
break;
default:
- SP_Common::printJSON(_('Acción Inválida'));
+ SP\Common::printJSON(_('Acción Inválida'));
}
\ No newline at end of file
diff --git a/ajax/ajax_appMgmtData.php b/ajax/ajax_appMgmtData.php
index e5d57516..5bbf283b 100644
--- a/ajax/ajax_appMgmtData.php
+++ b/ajax/ajax_appMgmtData.php
@@ -24,122 +24,123 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Util::logout();
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Util::logout();
}
-if (!SP_Common::parseParams('p', 'itemId', false, true)
- || !SP_Common::parseParams('p', 'actionId', false, true)
+if (!SP\Common::parseParams('p', 'itemId', false, true)
+ || !SP\Common::parseParams('p', 'actionId', false, true)
) {
exit();
}
-$actionId = SP_Common::parseParams('p', 'actionId', 0);
+$actionId = SP\Common::parseParams('p', 'actionId', 0);
-$tpl = new SP_Template();
-$tpl->assign('itemId', SP_Common::parseParams('p', 'itemId', 0));
-$tpl->assign('activeTab', SP_Common::parseParams('p', 'activeTab', 0));
+$tpl = new SP\Template();
+$tpl->assign('itemId', SP\Common::parseParams('p', 'itemId', 0));
+$tpl->assign('activeTab', SP\Common::parseParams('p', 'activeTab', 0));
$tpl->assign('actionId', $actionId);
$tpl->assign('isView', false);
switch ($actionId) {
-case \Controller\ActionsInterface::ACTION_USR_USERS_VIEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_USERS_VIEW:
$tpl->assign('header', _('Ver Usuario'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
$tpl->assign('isView', true);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getUser();
break;
-case \Controller\ActionsInterface::ACTION_USR_USERS_EDIT:
+case \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDIT:
$tpl->assign('header', _('Editar Usuario'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getUser();
break;
-case \Controller\ActionsInterface::ACTION_USR_USERS_NEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW:
$tpl->assign('header', _('Nuevo Usuario'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getUser();
break;
-case \Controller\ActionsInterface::ACTION_USR_GROUPS_VIEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_VIEW:
$tpl->assign('header', _('Ver Grupo'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
$tpl->assign('isView', true);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getGroup();
break;
-case \Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT:
+case \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT:
$tpl->assign('header', _('Editar Grupo'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getGroup();
break;
-case \Controller\ActionsInterface::ACTION_USR_GROUPS_NEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW:
$tpl->assign('header', _('Nuevo Grupo'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getGroup();
break;
-case \Controller\ActionsInterface::ACTION_USR_PROFILES_VIEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_VIEW:
$tpl->assign('header', _('Ver Perfil'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
$tpl->assign('isView', true);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getProfile();
break;
-case \Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT:
+case \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT:
$tpl->assign('header', _('Editar Perfil'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getProfile();
break;
-case \Controller\ActionsInterface::ACTION_USR_PROFILES_NEW:
+case \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW:
$tpl->assign('header', _('Nuevo Perfil'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_USR);
- $controller = new \Controller\UsersMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_USR);
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getProfile();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_VIEW:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_VIEW:
$tpl->assign('header', _('Ver Cliente'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
$tpl->assign('isView', true);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCustomer();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT:
$tpl->assign('header', _('Editar Cliente'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCustomer();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW:
$tpl->assign('header', _('Nuevo Cliente'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCustomer();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_VIEW:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_VIEW:
$tpl->assign('header', _('Ver Categoría'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
$tpl->assign('isView', true);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCategory();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT:
$tpl->assign('header', _('Editar Categoría'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCategory();
break;
-case \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW:
+case \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW:
$tpl->assign('header', _('Nueva Categoría'));
- $tpl->assign('onCloseAction', \Controller\ActionsInterface::ACTION_MGM);
- $controller = new \Controller\AccountsMgmtC($tpl);
+ $tpl->assign('onCloseAction', \SP\Controller\ActionsInterface::ACTION_MGM);
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->getCategory();
break;
default :
diff --git a/ajax/ajax_appMgmtSave.php b/ajax/ajax_appMgmtSave.php
index b74cc615..c06a15cf 100644
--- a/ajax/ajax_appMgmtSave.php
+++ b/ajax/ajax_appMgmtSave.php
@@ -1,5 +1,4 @@
userId = $itemId;
- $objUser->userName = $frmUsrName;
- $objUser->userLogin = $frmUsrLogin;
- $objUser->userEmail = $frmUsrEmail;
- $objUser->userNotes = $frmUsrNotes;
- $objUser->userGroupId = $frmUsrGroup;
- $objUser->userProfileId = $frmUsrProfile;
- $objUser->userIsAdminApp = $frmAdminApp;
- $objUser->userIsAdminAcc = $frmAdminAcc;
- $objUser->userIsDisabled = $frmDisabled;
- $objUser->userChangePass = $frmChangePass;
- $objUser->userPass = $frmUsrPass;
+ $user->userId = $itemId;
+ $user->userName = $userName;
+ $user->userLogin = $userLogin;
+ $user->userEmail = $userEmail;
+ $user->userNotes = $userNotes;
+ $user->userGroupId = $userGroup;
+ $user->userProfileId = $userProfile;
+ $user->userIsAdminApp = $userIsAdminApp;
+ $user->userIsAdminAcc = $userIsAdminAcc;
+ $user->userIsDisabled = $userIsDisabled;
+ $user->userChangePass = $userIsChangePass;
+ $user->userPass = $userPass;
- switch ($objUser->checkUserExist()) {
+ switch ($user->checkUserExist()) {
case 1:
- SP_Common::printJSON(_('Login de usuario duplicado'), 2);
+ SP\Common::printJSON(_('Login de usuario duplicado'), 2);
break;
case 2:
- SP_Common::printJSON(_('Email de usuario duplicado'), 2);
+ SP\Common::printJSON(_('Email de usuario duplicado'), 2);
break;
}
- if ($actionId === \Controller\ActionsInterface::ACTION_USR_USERS_NEW) {
- if (!$frmUsrPass && !$frmUsrPassV) {
- SP_Common::printJSON(_('La clave no puede estar en blanco'), 2);
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW) {
+ if (!$userPass && !$userPassV) {
+ SP\Common::printJSON(_('La clave no puede estar en blanco'), 2);
}
- if ($frmUsrPass != $frmUsrPassV) {
- SP_Common::printJSON(_('Las claves no coinciden'), 2);
+ if ($userPass != $userPassV) {
+ SP\Common::printJSON(_('Las claves no coinciden'), 2);
}
- if ($objUser->addUser()) {
- SP_Common::printJSON(_('Usuario creado'), 0, $doActionOnClose);
+ if ($user->addUser()) {
+ SP\Common::printJSON(_('Usuario creado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al crear el usuario'));
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_USERS_EDIT) {
- if ($objUser->updateUser()) {
- SP_Common::printJSON(_('Usuario actualizado'), 0, $doActionOnClose);
+ SP\Common::printJSON(_('Error al crear el usuario'));
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDIT) {
+ if ($user->updateUser()) {
+ SP\Common::printJSON(_('Usuario actualizado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al actualizar el usuario'));
+ SP\Common::printJSON(_('Error al actualizar el usuario'));
}
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_USERS_EDITPASS) {
- if (SP_Util::demoIsEnabled() && $userLogin == 'demo') {
- SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDITPASS) {
+ if ( SP\Util::demoIsEnabled() && $userLogin == 'demo') {
+ SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
}
- if (!$frmUsrPass || !$frmUsrPassV) {
- SP_Common::printJSON(_('La clave no puede estar en blanco'), 2);
+ if (!$userPass || !$userPassV) {
+ SP\Common::printJSON(_('La clave no puede estar en blanco'), 2);
}
- if ($frmUsrPass != $frmUsrPassV) {
- SP_Common::printJSON(_('Las claves no coinciden'), 2);
+ if ($userPass != $userPassV) {
+ SP\Common::printJSON(_('Las claves no coinciden'), 2);
}
- $objUser->userId = $itemId;
- $objUser->userPass = $frmUsrPass;
+ $user->userId = $itemId;
+ $user->userPass = $userPass;
- if ($objUser->updateUserPass()) {
- SP_Common::printJSON(_('Clave actualizada'), 0);
+ if ($user->updateUserPass()) {
+ SP\Common::printJSON(_('Clave actualizada'), 0);
}
- SP_Common::printJSON(_('Error al modificar la clave'));
+ SP\Common::printJSON(_('Error al modificar la clave'));
// Eliminar usuario
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_USERS_DELETE) {
- if (SP_Util::demoIsEnabled() && $userLogin == 'demo') {
- SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_DELETE) {
+ if ( SP\Util::demoIsEnabled() && $userLogin == 'demo') {
+ SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
}
- $objUser->userId = $itemId;
+ $user->userId = $itemId;
- if ($itemId == SP_Session::getUserId()) {
- SP_Common::printJSON(_('No es posible eliminar, usuario en uso'));
+ if ($itemId == SP\Session::getUserId()) {
+ SP\Common::printJSON(_('No es posible eliminar, usuario en uso'));
}
- if ($objUser->deleteUser()) {
- SP_Common::printJSON(_('Usuario eliminado'), 0, $doActionOnClose);
+ if ($user->deleteUser()) {
+ SP\Common::printJSON(_('Usuario eliminado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al eliminar el usuario'));
+ SP\Common::printJSON(_('Error al eliminar el usuario'));
}
- SP_Common::printJSON(_('Acción Inválida'));
-} elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
- || $actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_DELETE
+ SP\Common::printJSON(_('Acción Inválida'));
+} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_DELETE
) {
// Variables POST del formulario
- $frmGrpName = SP_Common::parseParams('p', 'name');
- $frmGrpDesc = SP_Common::parseParams('p', 'description');
+ $frmGrpName = SP\Common::parseParams('p', 'name');
+ $frmGrpDesc = SP\Common::parseParams('p', 'description');
- if ($actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
) {
if (!$frmGrpName) {
- SP_Common::printJSON(_('Es necesario un nombre de grupo'), 2);
+ SP\Common::printJSON(_('Es necesario un nombre de grupo'), 2);
}
- SP_Groups::$groupId = $itemId;
- SP_Groups::$groupName = $frmGrpName;
- SP_Groups::$groupDescription = $frmGrpDesc;
+ SP\Groups::$groupId = $itemId;
+ SP\Groups::$groupName = $frmGrpName;
+ SP\Groups::$groupDescription = $frmGrpDesc;
- if (SP_Groups::checkGroupExist()) {
- SP_Common::printJSON(_('Nombre de grupo duplicado'), 2);
+ if (SP\Groups::checkGroupExist()) {
+ SP\Common::printJSON(_('Nombre de grupo duplicado'), 2);
}
- if ($actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_NEW) {
- if (SP_Groups::addGroup()) {
- SP_Common::printJSON(_('Grupo creado'), 0, $doActionOnClose);
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW) {
+ if (SP\Groups::addGroup()) {
+ SP\Common::printJSON(_('Grupo creado'), 0, $doActionOnClose);
} else {
- SP_Common::printJSON(_('Error al crear el grupo'));
+ SP\Common::printJSON(_('Error al crear el grupo'));
}
- } else if ($actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT) {
- if (SP_Groups::updateGroup()) {
- SP_Common::printJSON(_('Grupo actualizado'), 0, $doActionOnClose);
+ } else if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT) {
+ if (SP\Groups::updateGroup()) {
+ SP\Common::printJSON(_('Grupo actualizado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al actualizar el grupo'));
+ SP\Common::printJSON(_('Error al actualizar el grupo'));
}
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_GROUPS_DELETE) {
- SP_Groups::$groupId = $itemId;
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_DELETE) {
+ SP\Groups::$groupId = $itemId;
- $resGroupUse = SP_Groups::checkGroupInUse();
+ $resGroupUse = SP\Groups::checkGroupInUse();
if ($resGroupUse['users'] > 0 || $resGroupUse['accounts'] > 0) {
if ($resGroupUse['users'] > 0) {
@@ -232,204 +231,204 @@ if ($actionId === \Controller\ActionsInterface::ACTION_USR_USERS_NEW
$uses[] = _('Cuentas') . " (" . $resGroupUse['accounts'] . ")";
}
- SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Grupo en uso por:') . ';;' . implode(';;', $uses));
+ SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Grupo en uso por:') . ';;' . implode(';;', $uses));
} else {
- $groupName = SP_Groups::getGroupNameById($itemId);
+ $groupName = SP\Groups::getGroupNameById($itemId);
- if (SP_Groups::deleteGroup()) {
- SP_Common::printJSON(_('Grupo eliminado'), 0, $doActionOnClose);
+ if (SP\Groups::deleteGroup()) {
+ SP\Common::printJSON(_('Grupo eliminado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al eliminar el grupo'));
+ SP\Common::printJSON(_('Error al eliminar el grupo'));
}
}
- SP_Common::printJSON(_('Acción Inválida'));
-} elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT
- || $actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_DELETE
+ SP\Common::printJSON(_('Acción Inválida'));
+} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_DELETE
) {
$profileProp = array();
// Variables POST del formulario
- $frmProfileName = SP_Common::parseParams('p', 'profile_name');
- SP_Profiles::$profileId = $itemId;
+ $frmProfileName = SP\Common::parseParams('p', 'profile_name');
+ SP\Profiles::$profileId = $itemId;
// Profile properties Array
- $profileProp["pAccView"] = SP_Common::parseParams('p', 'profile_accview', 0, false, 1);
- $profileProp["pAccViewPass"] = SP_Common::parseParams('p', 'profile_accviewpass', 0, false, 1);
- $profileProp["pAccViewHistory"] = SP_Common::parseParams('p', 'profile_accviewhistory', 0, false, 1);
- $profileProp["pAccEdit"] = SP_Common::parseParams('p', 'profile_accedit', 0, false, 1);
- $profileProp["pAccEditPass"] = SP_Common::parseParams('p', 'profile_acceditpass', 0, false, 1);
- $profileProp["pAccAdd"] = SP_Common::parseParams('p', 'profile_accadd', 0, false, 1);
- $profileProp["pAccDel"] = SP_Common::parseParams('p', 'profile_accdel', 0, false, 1);
- $profileProp["pAccFiles"] = SP_Common::parseParams('p', 'profile_accfiles', 0, false, 1);
- $profileProp["pConfig"] = SP_Common::parseParams('p', 'profile_config', 0, false, 1);
- $profileProp["pAppMgmtCat"] = SP_Common::parseParams('p', 'profile_categories', 0, false, 1);
- $profileProp["pAppMgmtCust"] = SP_Common::parseParams('p', 'profile_customers', 0, false, 1);
- $profileProp["pConfigMpw"] = SP_Common::parseParams('p', 'profile_configmpw', 0, false, 1);
- $profileProp["pConfigBack"] = SP_Common::parseParams('p', 'profile_configback', 0, false, 1);
- $profileProp["pUsers"] = SP_Common::parseParams('p', 'profile_users', 0, false, 1);
- $profileProp["pGroups"] = SP_Common::parseParams('p', 'profile_groups', 0, false, 1);
- $profileProp["pProfiles"] = SP_Common::parseParams('p', 'profile_profiles', 0, false, 1);
- $profileProp["pEventlog"] = SP_Common::parseParams('p', 'profile_eventlog', 0, false, 1);
+ $profileProp["pAccView"] = SP\Common::parseParams('p', 'profile_accview', 0, false, 1);
+ $profileProp["pAccViewPass"] = SP\Common::parseParams('p', 'profile_accviewpass', 0, false, 1);
+ $profileProp["pAccViewHistory"] = SP\Common::parseParams('p', 'profile_accviewhistory', 0, false, 1);
+ $profileProp["pAccEdit"] = SP\Common::parseParams('p', 'profile_accedit', 0, false, 1);
+ $profileProp["pAccEditPass"] = SP\Common::parseParams('p', 'profile_acceditpass', 0, false, 1);
+ $profileProp["pAccAdd"] = SP\Common::parseParams('p', 'profile_accadd', 0, false, 1);
+ $profileProp["pAccDel"] = SP\Common::parseParams('p', 'profile_accdel', 0, false, 1);
+ $profileProp["pAccFiles"] = SP\Common::parseParams('p', 'profile_accfiles', 0, false, 1);
+ $profileProp["pConfig"] = SP\Common::parseParams('p', 'profile_config', 0, false, 1);
+ $profileProp["pAppMgmtCat"] = SP\Common::parseParams('p', 'profile_categories', 0, false, 1);
+ $profileProp["pAppMgmtCust"] = SP\Common::parseParams('p', 'profile_customers', 0, false, 1);
+ $profileProp["pConfigMpw"] = SP\Common::parseParams('p', 'profile_configmpw', 0, false, 1);
+ $profileProp["pConfigBack"] = SP\Common::parseParams('p', 'profile_configback', 0, false, 1);
+ $profileProp["pUsers"] = SP\Common::parseParams('p', 'profile_users', 0, false, 1);
+ $profileProp["pGroups"] = SP\Common::parseParams('p', 'profile_groups', 0, false, 1);
+ $profileProp["pProfiles"] = SP\Common::parseParams('p', 'profile_profiles', 0, false, 1);
+ $profileProp["pEventlog"] = SP\Common::parseParams('p', 'profile_eventlog', 0, false, 1);
- if ($actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT
) {
if (!$frmProfileName) {
- SP_Common::printJSON(_('Es necesario un nombre de perfil'), 2);
+ SP\Common::printJSON(_('Es necesario un nombre de perfil'), 2);
}
- SP_Profiles::$profileName = $frmProfileName;
+ SP\Profiles::$profileName = $frmProfileName;
- if (SP_Profiles::checkProfileExist()) {
- SP_Common::printJSON(_('Nombre de perfil duplicado'), 2);
+ if (SP\Profiles::checkProfileExist()) {
+ SP\Common::printJSON(_('Nombre de perfil duplicado'), 2);
}
- if ($actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_NEW) {
- if (SP_Profiles::addProfile($profileProp)) {
- SP_Common::printJSON(_('Perfil creado'), 0, $doActionOnClose);
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW) {
+ if (SP\Profiles::addProfile($profileProp)) {
+ SP\Common::printJSON(_('Perfil creado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al crear el perfil'));
- } else if ($actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT) {
- if (SP_Profiles::updateProfile($profileProp)) {
- SP_Common::printJSON(_('Perfil actualizado'), 0, $doActionOnClose);
+ SP\Common::printJSON(_('Error al crear el perfil'));
+ } else if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT) {
+ if (SP\Profiles::updateProfile($profileProp)) {
+ SP\Common::printJSON(_('Perfil actualizado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al actualizar el perfil'));
+ SP\Common::printJSON(_('Error al actualizar el perfil'));
}
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_USR_PROFILES_DELETE) {
- $resProfileUse = SP_Profiles::checkProfileInUse();
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_DELETE) {
+ $resProfileUse = SP\Profiles::checkProfileInUse();
if ($resProfileUse['users'] > 0) {
$uses[] = _('Usuarios') . " (" . $resProfileUse['users'] . ")";
- SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Perfil en uso por:') . ';;' . implode(';;', $uses));
+ SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Perfil en uso por:') . ';;' . implode(';;', $uses));
} else {
- $profileName = SP_Profiles::getProfileNameById($itemId);
+ $profileName = SP\Profiles::getProfileNameById($itemId);
- if (SP_Profiles::deleteProfile()) {
+ if (SP\Profiles::deleteProfile()) {
$message['action'] = _('Eliminar Perfil');
- $message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . $profileName;
+ $message['text'][] = SP\Html::strongText(_('Perfil') . ': ') . $profileName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::sendEmail($message);
- SP_Common::printJSON(_('Perfil eliminado'), 0, $doActionOnClose);
+ SP\Common::printJSON(_('Perfil eliminado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al eliminar el perfil'));
+ SP\Common::printJSON(_('Error al eliminar el perfil'));
}
}
- SP_Common::printJSON(_('Acción Inválida'));
-} elseif ($actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_DELETE
+ SP\Common::printJSON(_('Acción Inválida'));
+} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_DELETE
) {
// Variables POST del formulario
- $frmCustomerName = SP_Common::parseParams('p', 'name');
- $frmCustomerDesc = SP_Common::parseParams('p', 'description');
+ $frmCustomerName = SP\Common::parseParams('p', 'name');
+ $frmCustomerDesc = SP\Common::parseParams('p', 'description');
- if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT
) {
if (!$frmCustomerName) {
- SP_Common::printJSON(_('Es necesario un nombre de cliente'), 2);
+ SP\Common::printJSON(_('Es necesario un nombre de cliente'), 2);
}
- SP_Customer::$customerName = $frmCustomerName;
- SP_Customer::$customerDescription = $frmCustomerDesc;
+ SP\Customer::$customerName = $frmCustomerName;
+ SP\Customer::$customerDescription = $frmCustomerDesc;
- if (SP_Customer::checkDupCustomer($itemId)) {
- SP_Common::printJSON(_('Nombre de cliente duplicado'), 2);
+ if (SP\Customer::checkDupCustomer($itemId)) {
+ SP\Common::printJSON(_('Nombre de cliente duplicado'), 2);
}
- if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW) {
- if (SP_Customer::addCustomer()) {
- SP_Common::printJSON(_('Cliente creado'), 0, $doActionOnClose);
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW) {
+ if (SP\Customer::addCustomer()) {
+ SP\Common::printJSON(_('Cliente creado'), 0, $doActionOnClose);
} else {
- SP_Common::printJSON(_('Error al crear el cliente'));
+ SP\Common::printJSON(_('Error al crear el cliente'));
}
- } else if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT) {
- if (SP_Customer::updateCustomer($itemId)) {
- SP_Common::printJSON(_('Cliente actualizado'), 0, $doActionOnClose);
+ } else if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT) {
+ if (SP\Customer::updateCustomer($itemId)) {
+ SP\Common::printJSON(_('Cliente actualizado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al actualizar el cliente'));
+ SP\Common::printJSON(_('Error al actualizar el cliente'));
}
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_DELETE) {
- $resCustomerUse = SP_Customer::checkCustomerInUse($itemId);
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_DELETE) {
+ $resCustomerUse = SP\Customer::checkCustomerInUse($itemId);
if ($resCustomerUse['accounts'] > 0) {
$uses[] = _('Cuentas') . " (" . $resCustomerUse['accounts'] . ")";
- SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Cliente en uso por:') . ';;' . implode(';;', $uses));
+ SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Cliente en uso por:') . ';;' . implode(';;', $uses));
} else {
- if (SP_Customer::delCustomer($itemId)) {
- SP_Common::printJSON(_('Cliente eliminado'), 0, $doActionOnClose);
+ if (SP\Customer::delCustomer($itemId)) {
+ SP\Common::printJSON(_('Cliente eliminado'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al eliminar el cliente'));
+ SP\Common::printJSON(_('Error al eliminar el cliente'));
}
}
- SP_Common::printJSON(_('Acción Inválida'));
-} elseif ($actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_DELETE
+ SP\Common::printJSON(_('Acción Inválida'));
+} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_DELETE
) {
// Variables POST del formulario
- $frmCategoryName = SP_Common::parseParams('p', 'name');
- $frmCategoryDesc = SP_Common::parseParams('p', 'description');
+ $frmCategoryName = SP\Common::parseParams('p', 'name');
+ $frmCategoryDesc = SP\Common::parseParams('p', 'description');
- if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW
- || $actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW
+ || $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
) {
if (!$frmCategoryName) {
- SP_Common::printJSON(_('Es necesario un nombre de categoría'), 2);
+ SP\Common::printJSON(_('Es necesario un nombre de categoría'), 2);
}
- SP_Category::$categoryName = $frmCategoryName;
- SP_Category::$categoryDescription = $frmCategoryDesc;
+ SP\Category::$categoryName = $frmCategoryName;
+ SP\Category::$categoryDescription = $frmCategoryDesc;
- if (SP_Category::checkDupCategory($itemId)) {
- SP_Common::printJSON(_('Nombre de categoría duplicado'), 2);
+ if (SP\Category::checkDupCategory($itemId)) {
+ SP\Common::printJSON(_('Nombre de categoría duplicado'), 2);
}
- if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW) {
- if (SP_Category::addCategory()) {
- SP_Common::printJSON(_('Categoría creada'), 0, $doActionOnClose);
+ if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW) {
+ if (SP\Category::addCategory()) {
+ SP\Common::printJSON(_('Categoría creada'), 0, $doActionOnClose);
} else {
- SP_Common::printJSON(_('Error al crear la categoría'));
+ SP\Common::printJSON(_('Error al crear la categoría'));
}
- } else if ($actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT) {
- if (SP_Category::updateCategory($itemId)) {
- SP_Common::printJSON(_('Categoría actualizada'), 0, $doActionOnClose);
+ } else if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT) {
+ if (SP\Category::updateCategory($itemId)) {
+ SP\Common::printJSON(_('Categoría actualizada'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al actualizar la categoría'));
+ SP\Common::printJSON(_('Error al actualizar la categoría'));
}
- } elseif ($actionId === \Controller\ActionsInterface::ACTION_MGM_CATEGORIES_DELETE) {
- $resCategoryUse = SP_Category::checkCategoryInUse($itemId);
+ } elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_DELETE) {
+ $resCategoryUse = SP\Category::checkCategoryInUse($itemId);
if ($resCategoryUse !== true) {
- SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Categoría en uso por:') . ';;' . $resCategoryUse);
+ SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Categoría en uso por:') . ';;' . $resCategoryUse);
} else {
- if (SP_Category::delCategory($itemId)) {
- SP_Common::printJSON(_('Categoría eliminada'), 0, $doActionOnClose);
+ if (SP\Category::delCategory($itemId)) {
+ SP\Common::printJSON(_('Categoría eliminada'), 0, $doActionOnClose);
}
- SP_Common::printJSON(_('Error al eliminar la categoría'));
+ SP\Common::printJSON(_('Error al eliminar la categoría'));
}
}
- SP_Common::printJSON(_('Acción Inválida'));
+ SP\Common::printJSON(_('Acción Inválida'));
}
\ No newline at end of file
diff --git a/ajax/ajax_backup.php b/ajax/ajax_backup.php
index b8abf3e0..367ac373 100644
--- a/ajax/ajax_backup.php
+++ b/ajax/ajax_backup.php
@@ -24,36 +24,37 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
-$sk = SP_Common::parseParams('p', 'sk', false);
+$sk = SP\Common::parseParams('p', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
- SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
+ SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
-$doBackup = SP_Common::parseParams('p', 'backup', 0);
-$frmOnCloseAction = SP_Common::parseParams('p', 'onCloseAction');
-$frmActiveTab = SP_Common::parseParams('p', 'activeTab', 0);
+$actionId = SP\Common::parseParams('p', 'actionId', 0);
+$onCloseAction = SP\Common::parseParams('p', 'onCloseAction');
+$activeTab = SP\Common::parseParams('p', 'activeTab', 0);
-$doActionOnClose = "doAction('$frmOnCloseAction','',$frmActiveTab);";
+$doActionOnClose = "doAction('$actionId','',$activeTab);";
-if ($doBackup) {
- if (!SP_Backup::doBackup()) {
- SP_Common::printJSON(_('Error al realizar el backup') . ';;' . _('Revise el registro de eventos para más detalles'));
+if ($actionId === \SP\Controller\ActionsInterface::ACTION_CFG_BACKUP) {
+ if (!SP\Backup::doBackup()) {
+ SP\Common::printJSON(_('Error al realizar el backup') . ';;' . _('Revise el registro de eventos para más detalles'));
}
$message['action'] = _('Realizar Backup');
$message['text'][] = _('Copia de la aplicación y base de datos realizada correctamente');
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::sendEmail($message);
- SP_Common::printJSON(_('Proceso de backup finalizado'), 0, $doActionOnClose);
+ SP\Common::printJSON(_('Proceso de backup finalizado'), 0, $doActionOnClose);
}
\ No newline at end of file
diff --git a/ajax/ajax_checkLdap.php b/ajax/ajax_checkLdap.php
index f3724d2b..bb2f666d 100644
--- a/ajax/ajax_checkLdap.php
+++ b/ajax/ajax_checkLdap.php
@@ -24,34 +24,35 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
-$sk = SP_Common::parseParams('p', 'sk', false);
+$sk = SP\Common::parseParams('p', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
- SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
+ SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
-$frmLdapServer = SP_Common::parseParams('p', 'ldap_server');
-$frmLdapBase = SP_Common::parseParams('p', 'ldap_base');
-$frmLdapGroup = SP_Common::parseParams('p', 'ldap_group');
-$frmLdapBindUser = SP_Common::parseParams('p', 'ldap_binduser');
-$frmLdapBindPass = SP_Common::parseParams('p', 'ldap_bindpass');
+$frmLdapServer = SP\Common::parseParams('p', 'ldap_server');
+$frmLdapBase = SP\Common::parseParams('p', 'ldap_base');
+$frmLdapGroup = SP\Common::parseParams('p', 'ldap_group');
+$frmLdapBindUser = SP\Common::parseParams('p', 'ldap_binduser');
+$frmLdapBindPass = SP\Common::parseParams('p', 'ldap_bindpass');
if (!$frmLdapServer || !$frmLdapBase || !$frmLdapBindUser || !$frmLdapBindPass) {
- SP_Common::printJSON(_('Los parámetros de LDAP no están configurados'));
+ SP\Common::printJSON(_('Los parámetros de LDAP no están configurados'));
}
-$resCheckLdap = SP_Ldap::checkLDAPConn($frmLdapServer, $frmLdapBindUser, $frmLdapBindPass, $frmLdapBase, $frmLdapGroup);
+$resCheckLdap = SP\Ldap::checkLDAPConn($frmLdapServer, $frmLdapBindUser, $frmLdapBindPass, $frmLdapBase, $frmLdapGroup);
if ($resCheckLdap === false) {
- SP_Common::printJSON(_('Error de conexión a LDAP') . ';;' . _('Revise el registro de eventos para más detalles'));
+ SP\Common::printJSON(_('Error de conexión a LDAP') . ';;' . _('Revise el registro de eventos para más detalles'));
} else {
- SP_Common::printJSON(_('Conexión a LDAP correcta') . ';;' . _('Objetos encontrados') . ': ' . $resCheckLdap, 0);
+ SP\Common::printJSON(_('Conexión a LDAP correcta') . ';;' . _('Objetos encontrados') . ': ' . $resCheckLdap, 0);
}
\ No newline at end of file
diff --git a/ajax/ajax_checkUpds.php b/ajax/ajax_checkUpds.php
index 08760160..f0b6b130 100644
--- a/ajax/ajax_checkUpds.php
+++ b/ajax/ajax_checkUpds.php
@@ -24,15 +24,16 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('GET');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-$checkVersion = SP_Common::parseParams('s', 'UPDATED', false, true);
+SP\Util::checkReferer('GET');
+
+$checkVersion = SP\Common::parseParams('s', 'UPDATED', false, true);
// Una vez por sesión
if (!$checkVersion) {
- $_SESSION["UPDATED"] = $checkVersion = SP_Util::checkUpdates();
+ $_SESSION["UPDATED"] = $checkVersion = SP\Util::checkUpdates();
}
session_write_close();
diff --git a/ajax/ajax_configSave.php b/ajax/ajax_configSave.php
index 425848d4..a343f8b5 100644
--- a/ajax/ajax_configSave.php
+++ b/ajax/ajax_configSave.php
@@ -1,12 +1,11 @@
16384) {
- SP_Common::printJSON(_('El tamaño máximo de archivo es de 16MB'));
- }
+ if ($filesEnabled && $filesAllowedSize > 16384) {
+ SP\Common::printJSON(_('El tamaño máximo de archivo es de 16MB'));
+ }
- SP_Config::setValue("allowed_exts", $frmAllowedExts);
- SP_Config::setValue("account_link", $frmAccountLink);
- SP_Config::setValue("account_count", $frmAccountCount);
- SP_Config::setValue("sitelang", $frmSiteLang);
- SP_Config::setValue("session_timeout", $frmSessionTimeout);
- SP_Config::setValue("log_enabled", $frmLog);
- SP_Config::setValue("debug", $frmDebug);
- SP_Config::setValue("maintenance", $frmMaintenance);
- SP_Config::setValue("checkupdates", $frmCheckUpdates);
- SP_Config::setValue("files_enabled", $frmFiles);
- SP_Config::setValue("resultsascards", $frmResultsAsCards);
- SP_Config::setValue("globalsearch", $frmGlobalSearch);
- SP_Config::setValue("files_allowed_size", $frmAllowedSize);
+ SP\Config::setValue('account_link', $accountLinkEnabled);
+ SP\Config::setValue('account_count', $accountCount);
+ SP\Config::setValue('sitelang', $siteLang);
+ SP\Config::setValue('session_timeout', $sessionTimeout);
+ SP\Config::setValue('log_enabled', $logEnabled);
+ SP\Config::setValue('debug', $debugEnabled);
+ SP\Config::setValue('maintenance', $maintenanceEnabled);
+ SP\Config::setValue('checkupdates', $checkUpdatesEnabled);
+ SP\Config::setValue('files_enabled', $filesEnabled);
+ SP\Config::setValue('files_allowed_exts', $filesAllowedExts);
+ SP\Config::setValue('files_allowed_size', $filesAllowedSize);
+ SP\Config::setValue('resultsascards', $resultsAsCardsEnabled);
+ SP\Config::setValue('globalsearch', $globalSearchEnabled);
$message['action'] = _('Modificar Configuración');
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::sendEmail($message);
// Recargar la aplicación completa para establecer nuevos valores
- SP_Util::reload();
+ SP\Util::reload();
- SP_Common::printJSON(_('Configuración actualizada'), 0, $doActionOnClose);
-} elseif ($frmAction == SP_Acl::ACTION_CFG_ENCRYPTION) {
- $currentMasterPass = SP_Common::parseParams('p', 'curMasterPwd', '', false, false, false);
- $newMasterPass = SP_Common::parseParams('p', 'newMasterPwd', '', false, false, false);
- $newMasterPassR = SP_Common::parseParams('p', 'newMasterPwdR', '', false, false, false);
- $confirmPassChange = SP_Common::parseParams('p', 'confirmPassChange', 0, false, 1);
- $noAccountPassChange = SP_Common::parseParams('p', 'chkNoAccountChange', 0, false, 1);
+ SP\Common::printJSON(_('Configuración actualizada'), 0, $doActionOnClose);
+} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION) {
+ $currentMasterPass = SP\Common::parseParams('p', 'curMasterPwd', '', false, false, false);
+ $newMasterPass = SP\Common::parseParams('p', 'newMasterPwd', '', false, false, false);
+ $newMasterPassR = SP\Common::parseParams('p', 'newMasterPwdR', '', false, false, false);
+ $confirmPassChange = SP\Common::parseParams('p', 'confirmPassChange', 0, false, 1);
+ $noAccountPassChange = SP\Common::parseParams('p', 'chkNoAccountChange', 0, false, 1);
- if (!SP_Users::checkUserUpdateMPass()) {
- SP_Common::printJSON(_('Clave maestra actualizada') . ';;' . _('Reinicie la sesión para cambiarla'));
+ if (!SP\Users::checkUserUpdateMPass()) {
+ SP\Common::printJSON(_('Clave maestra actualizada') . ';;' . _('Reinicie la sesión para cambiarla'));
+ } elseif ($newMasterPass == '' && $currentMasterPass == '') {
+ SP\Common::printJSON(_('Clave maestra no indicada'));
+ } elseif ($confirmPassChange == 0) {
+ SP\Common::printJSON(_('Se ha de confirmar el cambio de clave'));
+ } elseif ($newMasterPass == $currentMasterPass) {
+ SP\Common::printJSON(_('Las claves son idénticas'));
+ } elseif ($newMasterPass != $newMasterPassR) {
+ SP\Common::printJSON(_('Las claves maestras no coinciden'));
+ } elseif (!SP\Crypt::checkHashPass($currentMasterPass, SP\Config::getConfigDbValue('masterPwd'))) {
+ SP\Common::printJSON(_('La clave maestra actual no coincide'));
}
- if ($newMasterPass == "" && $currentMasterPass == "") {
- SP_Common::printJSON(_('Clave maestra no indicada'));
- }
+ $hashMPass = SP\Crypt::mkHashPassword($newMasterPass);
- if ($confirmPassChange == 0) {
- SP_Common::printJSON(_('Se ha de confirmar el cambio de clave'));
- }
-
- if ($newMasterPass == $currentMasterPass) {
- SP_Common::printJSON(_('Las claves son idénticas'));
- }
-
- if ($newMasterPass != $newMasterPassR) {
- SP_Common::printJSON(_('Las claves maestras no coinciden'));
- }
-
- if (!SP_Crypt::checkHashPass($currentMasterPass, SP_Config::getConfigDbValue("masterPwd"))) {
- SP_Common::printJSON(_('La clave maestra actual no coincide'));
- }
-
- $hashMPass = SP_Crypt::mkHashPassword($newMasterPass);
-
if (!$noAccountPassChange) {
- $objAccount = new SP_Accounts;
+ $account = new SP\Account();
- if (!$objAccount->updateAllAccountsMPass($currentMasterPass, $newMasterPass)) {
- SP_Common::printJSON(_('Errores al actualizar las claves de las cuentas'));
+ if (!$account->updateAccountsMasterPass($currentMasterPass, $newMasterPass)) {
+ SP\Common::printJSON(_('Errores al actualizar las claves de las cuentas'));
+ }
+
+ $accountHistory = new SP\AccountHistory();
+
+ if (!$accountHistory->updateAccountsMasterPass($currentMasterPass, $newMasterPass, $hashMPass)) {
+ SP\Common::printJSON(_('Errores al actualizar las claves de las cuentas del histórico'));
}
-
- $objAccount->updateAllAccountsHistoryMPass($currentMasterPass, $newMasterPass, $hashMPass);
}
- if (SP_Util::demoIsEnabled()) {
- SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
+ if (SP\Util::demoIsEnabled()) {
+ SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
}
- SP_Config::$arrConfigValue["masterPwd"] = $hashMPass;
- SP_Config::$arrConfigValue["lastupdatempass"] = time();
-
- if (SP_Config::writeConfigDb()) {
+ SP\Config::getConfigDb();
+ SP\Config::setArrConfigValue('masterPwd', $hashMPass);
+ SP\Config::setArrConfigValue('lastupdatempass', time());
+
+ if (SP\Config::writeConfigDb()) {
$message['action'] = _('Actualizar Clave Maestra');
- SP_Common::sendEmail($message);
- SP_Common::printJSON(_('Clave maestra actualizada'), 0);
+ SP\Common::sendEmail($message);
+ SP\Common::printJSON(_('Clave maestra actualizada'), 0);
+ } else {
+ SP\Common::printJSON(_('Error al guardar el hash de la clave maestra'));
}
-
- SP_Common::printJSON(_('Error al guardar el hash de la clave maestra'));
-} elseif ($frmAction == SP_Acl::ACTION_CFG_ENCRYPTION_TEMPPASS) {
- $tempMasterMaxTime = SP_Common::parseParams('p', 'tmpass_maxtime', 3600);
- $tempMasterPass = SP_Config::setTempMasterPass($tempMasterMaxTime);
+
+} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION_TEMPPASS) {
+ $tempMasterMaxTime = SP\Common::parseParams('p', 'tmpass_maxtime', 3600);
+ $tempMasterPass = SP\Config::setTempMasterPass($tempMasterMaxTime);
if (!empty($tempMasterPass)) {
$message['action'] = _('Generar Clave Temporal');
- $message['text'][] = SP_Html::strongText(_('Clave') . ': ') . $tempMasterPass;
+ $message['text'][] = SP\Html::strongText(_('Clave') . ': ') . $tempMasterPass;
- SP_Common::sendEmail($message);
- SP_Common::printJSON(_('Clave Temporal Generada'), 0, $doActionOnClose);
+ SP\Common::sendEmail($message);
+ SP\Common::printJSON(_('Clave Temporal Generada'), 0, $doActionOnClose);
}
} else {
- SP_Common::printJSON(_('Acción Inválida'));
+ SP\Common::printJSON(_('Acción Inválida'));
}
\ No newline at end of file
diff --git a/ajax/ajax_doLogin.php b/ajax/ajax_doLogin.php
index 30a409ec..04399d74 100644
--- a/ajax/ajax_doLogin.php
+++ b/ajax/ajax_doLogin.php
@@ -1,5 +1,4 @@
userLogin = $userLogin;
$objUser->userPass = $userPass;
-$objUser->userName = SP_Auth::$userName;
-$objUser->userEmail = SP_Auth::$userEmail;
+$objUser->userName = SP\Auth::$userName;
+$objUser->userEmail = SP\Auth::$userEmail;
// Autentificamos por LDAP
if ($resLdap === true) {
@@ -58,95 +58,95 @@ if ($resLdap === true) {
// Creamos el usuario de LDAP en MySQL
if (!$objUser->newUserLDAP()) {
$message['text'][] = _('Error al guardar los datos de LDAP');
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Error interno'));
+ SP\Common::printJSON(_('Error interno'));
}
} else {
// Actualizamos la clave del usuario en MySQL
if (!$objUser->updateLDAPUserInDB()) {
$message['text'][] = _('Error al actualizar la clave del usuario en la BBDD');
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Error interno'));
+ SP\Common::printJSON(_('Error interno'));
}
}
} else if ($resLdap == 49) {
$message['action'] = _('Inicio sesión (LDAP)');
$message['text'][] = _('Login incorrecto');
$message['text'][] = _('Usuario') . ": " . $userLogin;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Usuario/Clave incorrectos'));
+ SP\Common::printJSON(_('Usuario/Clave incorrectos'));
} else if ($resLdap === 701) {
$message['action'] = _('Inicio sesión (LDAP)');
$message['text'][] = _('Cuenta expirada');
$message['text'][] = _('Usuario') . ": " . $userLogin;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Cuenta expirada'));
+ SP\Common::printJSON(_('Cuenta expirada'));
} else if ($resLdap === 702) {
$message['action'] = _('Inicio sesión (LDAP)');
$message['text'][] = _('El usuario no tiene grupos asociados');
$message['text'][] = _('Usuario') . ": " . $userLogin;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Usuario/Clave incorrectos'));
+ SP\Common::printJSON(_('Usuario/Clave incorrectos'));
} else { // Autentificamos por MySQL (ha fallado LDAP)
$message['action'] = _('Inicio sesión (MySQL)');
// Autentificamos con la BBDD
- if (!SP_Auth::authUserMySQL($userLogin, $userPass)) {
+ if (!SP\Auth::authUserMySQL($userLogin, $userPass)) {
$message['text'][] = _('Login incorrecto');
$message['text'][] = _('Usuario') . ": " . $userLogin;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Usuario/Clave incorrectos'));
+ SP\Common::printJSON(_('Usuario/Clave incorrectos'));
}
}
// Comprobar si el usuario está deshabilitado
-if (SP_Users::checkUserIsDisabled($userLogin)) {
+if (SP\Users::checkUserIsDisabled($userLogin)) {
$message['text'][] = _('Usuario deshabilitado');
$message['text'][] = _('Usuario') . ": " . $userLogin;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Usuario deshabilitado'));
+ SP\Common::printJSON(_('Usuario deshabilitado'));
}
// Obtenemos los datos del usuario
if (!$objUser->getUserInfo()) {
$message['text'][] = _('Error al obtener los datos del usuario de la BBDD');
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Error interno'));
+ SP\Common::printJSON(_('Error interno'));
}
// Comprobamos que la clave maestra del usuario es correcta y está actualizada
if (!$masterPass && (!$objUser->checkUserMPass()
- || !SP_Users::checkUserUpdateMPass($userLogin))
+ || !SP\Users::checkUserUpdateMPass($userLogin))
) {
- SP_Common::printJSON(_('La clave maestra no ha sido guardada o es incorrecta'), 3);
+ SP\Common::printJSON(_('La clave maestra no ha sido guardada o es incorrecta'), 3);
} elseif ($masterPass) {
- if (SP_Config::checkTempMasterPass($masterPass)) {
- $masterPass = SP_Config::getTempMasterPass($masterPass);
+ if (SP\Config::checkTempMasterPass($masterPass)) {
+ $masterPass = SP\Config::getTempMasterPass($masterPass);
}
if (!$objUser->updateUserMPass($masterPass)) {
$message['text'][] = _('Clave maestra incorrecta');
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
- SP_Common::printJSON(_('Clave maestra incorrecta'), 4);
+ SP\Common::printJSON(_('Clave maestra incorrecta'), 4);
}
}
// Comprobar si se ha forzado un cambio de clave
if ($objUser->userChangePass) {
- $hash = SP_Util::generate_random_bytes();
+ $hash = SP\Util::generate_random_bytes();
- if (SP_Users::addPassRecover($userLogin, $hash)) {
- $url = SP_Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time() . '&f=1';
- SP_Common::printJSON($url, 0);
+ if (SP\Users::addPassRecover($userLogin, $hash)) {
+ $url = SP\Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time() . '&f=1';
+ SP\Common::printJSON($url, 0);
}
}
@@ -156,10 +156,10 @@ if ($objUser->getUserMPass()) {
$objUser->setUserSession();
$message['text'][] = _('Usuario') . ": " . $userLogin;
- $message['text'][] = _('Perfil') . ": " . SP_Profiles::getProfileNameById($objUser->userProfileId);
- $message['text'][] = _('Grupo') . ": " . SP_Groups::getGroupNameById($objUser->userGroupId);
+ $message['text'][] = _('Perfil') . ": " . SP\Profiles::getProfileNameById($objUser->userProfileId);
+ $message['text'][] = _('Grupo') . ": " . SP\Groups::getGroupNameById($objUser->userGroupId);
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
// Comprobar si existen parámetros adicionales en URL via GET
foreach ($_POST as $param => $value) {
@@ -170,5 +170,5 @@ if ($objUser->getUserMPass()) {
$urlParams = isset($params) ? '?' . implode('&', $params) : '';
- SP_Common::printJSON('index.php' . $urlParams, 0);
+ SP\Common::printJSON('index.php' . $urlParams, 0);
}
\ No newline at end of file
diff --git a/ajax/ajax_eventlog.php b/ajax/ajax_eventlog.php
index bc20e69e..eca3c53b 100644
--- a/ajax/ajax_eventlog.php
+++ b/ajax/ajax_eventlog.php
@@ -24,23 +24,24 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Util::logout();
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Util::logout();
}
-$start = SP_Common::parseParams('p', 'start', 0);
-$clear = SP_Common::parseParams('p', 'clear', 0);
-$sk = SP_Common::parseParams('p', 'sk', false);
+$start = SP\Common::parseParams('p', 'start', 0);
+$clear = SP\Common::parseParams('p', 'clear', 0);
+$sk = SP\Common::parseParams('p', 'sk', false);
-$tpl = new SP_Template();
-$tpl->assign('start', $start);
+$tpl = new SP\Template();
+$tpl->assign('limitStart', $start);
$tpl->assign('clear', $clear);
$tpl->assign('sk', $sk);
-$controller = new EventlogController($tpl);
+$controller = new SP\Controller\EventlogC($tpl);
$controller->checkClear();
$controller->getEventlog();
echo $tpl->render();
\ No newline at end of file
diff --git a/ajax/ajax_files.php b/ajax/ajax_files.php
index c20488e9..f57a8f65 100644
--- a/ajax/ajax_files.php
+++ b/ajax/ajax_files.php
@@ -1,12 +1,11 @@
.
*
*/
-// TODO: comprobar permisos para eliminar archivos
define('APP_ROOT', '..');
-require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Util::logout();
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Util::logout();
}
-$sk = SP_Common::parseParams('p', 'sk', false);
+$sk = SP\Common::parseParams('p', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
die(_('CONSULTA INVÁLIDA'));
}
-if (!SP_Util::fileIsEnabled()) {
+if (!SP\Util::fileIsEnabled()) {
exit(_('Gestión de archivos deshabilitada'));
}
-$action = SP_Common::parseParams('p', 'action');
-$accountId = SP_Common::parseParams('p', 'accountId', 0);
-$fileId = SP_Common::parseParams('p', 'fileId', 0);
+$action = SP\Common::parseParams('p', 'action');
+$accountId = SP\Common::parseParams('p', 'accountId', 0);
+$fileId = SP\Common::parseParams('p', 'fileId', 0);
if ($action == 'upload') {
if (!is_array($_FILES["inFile"]) || !$accountId === 0) {
exit();
}
- $allowedExts = strtoupper(SP_Config::getValue('files_allowed_exts'));
- $allowedSize = SP_Config::getValue('files_allowed_size');
+ $allowedExts = strtoupper(SP\Config::getValue('files_allowed_exts'));
+ $allowedSize = SP\Config::getValue('files_allowed_size');
if ($allowedExts) {
// Extensiones aceptadas
@@ -75,14 +74,14 @@ if ($action == 'upload') {
}
// Variables con información del archivo
- $fileData['name'] = SP_Html::sanitize($_FILES['inFile']['name']);
- $tmpName = SP_Html::sanitize($_FILES['inFile']['tmp_name']);
+ $fileData['name'] = SP\Html::sanitize($_FILES['inFile']['name']);
+ $tmpName = SP\Html::sanitize($_FILES['inFile']['tmp_name']);
$fileData['size'] = $_FILES['inFile']['size'];
$fileData['type'] = $_FILES['inFile']['type'];
if (!file_exists($tmpName)) {
// Registramos el máximo tamaño permitido por PHP
- SP_Util::getMaxUpload();
+ SP\Util::getMaxUpload();
exit(_('Error interno al leer el archivo'));
}
@@ -98,12 +97,12 @@ if ($action == 'upload') {
$message['action'] = _('Subir Archivo');
$message['text'][] = _('Error interno al leer el archivo');
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
exit(_('Error interno al leer el archivo'));
}
- if (SP_Files::fileUpload($accountId, $fileData)) {
+ if (SP\Files::fileUpload($accountId, $fileData)) {
exit(_('Archivo guardado'));
} else {
exit(_('No se pudo guardar el archivo'));
@@ -116,9 +115,9 @@ if ($action == 'download' || $action == 'view') {
exit(_('No es un ID de archivo válido'));
}
- $isView = ( $action == 'view' ) ? true : false;
+ $isView = ($action == 'view') ? true : false;
- $file = SP_Files::fileDownload($fileId);
+ $file = SP\Files::fileDownload($fileId);
if (!$file) {
exit(_('El archivo no existe'));
@@ -137,8 +136,8 @@ if ($action == 'download' || $action == 'view') {
$message['text'][] = _('Tamaño') . ": " . round($fileSize / 1024, 2) . " KB";
if (!$isView) {
- SP_Log::wrLogInfo($message);
-
+ SP\Log::wrLogInfo($message);
+
// Enviamos el archivo al navegador
header('Set-Cookie: fileDownload=true; path=/');
header('Cache-Control: max-age=60, must-revalidate');
@@ -152,15 +151,15 @@ if ($action == 'download' || $action == 'view') {
} else {
$extsOkImg = array("JPG", "GIF", "PNG");
if (in_array(strtoupper($fileExt), $extsOkImg)) {
- SP_Log::wrLogInfo($message);
-
+ SP\Log::wrLogInfo($message);
+
$imgData = chunk_split(base64_encode($fileData));
exit('
');
// } elseif ( strtoupper($fileExt) == "PDF" ){
// echo '';
} elseif (strtoupper($fileExt) == "TXT") {
- SP_Log::wrLogInfo($message);
-
+ SP\Log::wrLogInfo($message);
+
exit('
');
} else {
exit();
@@ -174,7 +173,7 @@ if ($action == "delete") {
exit(_('No es un ID de archivo válido'));
}
- if (SP_Files::fileDelete($fileId)) {
+ if (SP\Files::fileDelete($fileId)) {
exit(_('Archivo eliminado'));
} else {
exit(_('Error al eliminar el archivo'));
diff --git a/ajax/ajax_getContent.php b/ajax/ajax_getContent.php
index b1d0791c..abed7f74 100644
--- a/ajax/ajax_getContent.php
+++ b/ajax/ajax_getContent.php
@@ -1,5 +1,4 @@
' . _('Parámetros incorrectos') . '');
}
-$actionId = SP_Common::parseParams('p', 'action');
-$lastAction = filter_var(SP_Common::parseParams('p', 'lastAction', \Controller\ActionsInterface::ACTION_ACC_SEARCH, false, false, false), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
+$actionId = SP\Common::parseParams('p', 'actionId');
+$itemId = SP\Common::parseParams('p', 'itemId', 0);
+$lastAction = filter_var(SP\Common::parseParams('p', 'lastAction', \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH, false, false, false), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
-$tpl = new SP_Template();
-// FIXME: cambiar action por actionId
-$tpl->assign('action', $actionId);
+$tpl = new SP\Template();
$tpl->assign('actionId', $actionId);
-$tpl->assign('id', SP_Common::parseParams('p', 'id', 0));
+$tpl->assign('id', $itemId);
$tpl->assign('queryTimeStart', microtime());
-$tpl->assign('userId', SP_Common::parseParams('s', 'uid', 0));
-$tpl->assign('userGroupId', SP_Common::parseParams('s', 'ugroup', 0));
-$tpl->assign('userIsAdminApp', SP_Common::parseParams('s', 'uisadminapp', 0));
-$tpl->assign('userIsAdminAcc', SP_Common::parseParams('s', 'uisadminacc', 0));
+$tpl->assign('userId', SP\Session::getUserId());
+$tpl->assign('userGroupId', SP\Session::getUserGroupId());
+$tpl->assign('userIsAdminApp', SP\Session::getUserIsAdminApp());
+$tpl->assign('userIsAdminAcc', SP\Session::getUserIsAdminAcc());
// Control de ruta de acciones
-if ($action != \Controller\ActionsInterface::ACTION_ACC_SEARCH) {
+if ($actionId != \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH) {
$actionsPath = &$_SESSION['actionsPath'];
- $actionsPath[] = $action;
+ $actionsPath[] = $actionId;
$actions = count($actionsPath);
// Se eliminan las acciones ya realizadas
- if ($actions > 2 && $actionsPath[$actions - 3] == $action) {
+ if ($actions > 2 && $actionsPath[$actions - 3] == $actionId) {
unset($actionsPath[$actions - 3]);
unset($actionsPath[$actions - 2]);
$actionsPath = array_values($actionsPath);
@@ -72,65 +70,70 @@ if ($action != \Controller\ActionsInterface::ACTION_ACC_SEARCH) {
}
switch ($actionId) {
- case \Controller\ActionsInterface::ACTION_ACC_SEARCH:
- $_SESSION['actionsPath'] = array(\Controller\ActionsInterface::ACTION_ACC_SEARCH);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH:
+ $_SESSION['actionsPath'] = array(\SP\Controller\ActionsInterface::ACTION_ACC_SEARCH);
$tpl->assign('lastAction', $lastAction);
- $controller = new \Controller\SearchC($tpl);
+ $controller = new SP\Controller\SearchC($tpl);
$controller->getSearchBox();
$controller->getSearch();
break;
- case \Controller\ActionsInterface::ACTION_ACC_NEW:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_NEW:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getNewAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_COPY:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_COPY:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getCopyAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_EDIT:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getEditAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_EDIT_PASS:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_PASS:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getEditPassAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_VIEW:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_VIEW:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getViewAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_VIEW_HISTORY:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_VIEW_HISTORY:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getViewHistoryAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_DELETE:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_DELETE:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getDeleteAccount();
break;
- case \Controller\ActionsInterface::ACTION_ACC_REQUEST:
- $controller = new Controller\AccountC($tpl, null, $itemId);
+ case \SP\Controller\ActionsInterface::ACTION_ACC_REQUEST:
+ $controller = new SP\Controller\AccountC($tpl, null, $itemId);
$controller->getRequestAccountAccess();
break;
- case \Controller\ActionsInterface::ACTION_USR:
- $controller = new Controller\UsersMgmtC($tpl);
+ case \SP\Controller\ActionsInterface::ACTION_USR:
+ $controller = new SP\Controller\UsersMgmtC($tpl);
$controller->useTabs();
$controller->getUsersList();
$controller->getGroupsList();
$controller->getProfilesList();
break;
- case \Controller\ActionsInterface::ACTION_MGM:
- $controller = new Controller\AccountsMgmtC($tpl);
+ case \SP\Controller\ActionsInterface::ACTION_MGM:
+ $controller = new SP\Controller\AccountsMgmtC($tpl);
$controller->useTabs();
$controller->getCategories();
$controller->getCustomers();
break;
- case \Controller\ActionsInterface::ACTION_CFG:
+ case \SP\Controller\ActionsInterface::ACTION_CFG:
+ case \SP\Controller\ActionsInterface::ACTION_CFG_GENERAL:
+ case \SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION:
+ case \SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION_TEMPPASS:
+ case \SP\Controller\ActionsInterface::ACTION_CFG_BACKUP:
+ case \SP\Controller\ActionsInterface::ACTION_CFG_IMPORT:
$tpl->assign('onCloseAction', $action);
$tpl->addTemplate('tabs-start');
- $controller = new Controller\ConfigC($tpl);
+ $controller = new SP\Controller\ConfigC($tpl);
$controller->getConfigTab();
$controller->getEncryptionTab();
$controller->getBackupTab();
@@ -139,21 +142,24 @@ switch ($actionId) {
$tpl->addTemplate('tabs-end');
break;
- case \Controller\ActionsInterface::ACTION_EVL:
- $controller = new Controller\EventlogC($tpl);
+ case \SP\Controller\ActionsInterface::ACTION_EVL:
+ $controller = new SP\Controller\EventlogC($tpl);
$controller->getEventlog();
break;
}
// Se comprueba si se debe de mostrar la vista de depuración
-if (isset($_SESSION["uisadminapp"]) && SP_Config::getValue('debug')) {
+if (isset($_SESSION["uisadminapp"]) && SP\Config::getValue('debug')) {
$controller->getDebug();
}
// Se comprueba si hay actualizaciones.
// Es necesario que se haga al final de obtener el contenido ya que la
// consulta ajax detiene al resto si se ejecuta antes
-if ($_SESSION['uisadminapp'] && SP_Config::getValue('checkupdates') === true && !SP_Common::parseParams('s', 'UPDATED', false, true)) {
+if ($_SESSION['uisadminapp']
+ && SP\Config::getValue('checkupdates') === true
+ && !SP\Common::parseParams('s', 'UPDATED', false, true)
+) {
echo '';
}
diff --git a/ajax/ajax_getFiles.php b/ajax/ajax_getFiles.php
index 17420d58..dd87bade 100644
--- a/ajax/ajax_getFiles.php
+++ b/ajax/ajax_getFiles.php
@@ -24,25 +24,26 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('GET');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
+SP\Util::checkReferer('GET');
+
+if (!SP\Init::isLoggedIn()) {
return;
}
-if (!SP_Util::fileIsEnabled()) {
+if (!SP\Util::fileIsEnabled()) {
echo _('Gestión de archivos deshabilitada');
return false;
}
-$sk = SP_Common::parseParams('g', 'sk', false);
+$sk = SP\Common::parseParams('g', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
- SP_Common::printXML(_('CONSULTA INVÁLIDA'));
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
+ SP\Common::printXML(_('CONSULTA INVÁLIDA'));
}
-$controller = new \Controller\AccountsMgmtC();
+$controller = new SP\Controller\AccountsMgmtC();
$controller->getFiles();
$controller->view();
\ No newline at end of file
diff --git a/ajax/ajax_import.php b/ajax/ajax_import.php
index 4734ab46..42d35cef 100644
--- a/ajax/ajax_import.php
+++ b/ajax/ajax_import.php
@@ -1 +1 @@
-.
*
*/
define('APP_ROOT', '..');
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
SP_Util::checkReferer('POST');
if (!SP_Init::isLoggedIn()) {
SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP_Util::demoIsEnabled()) {
SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$res = SP_Import::doImport($_FILES["inFile"]);
if (isset($res['error']) && is_array($res['error'])) {
foreach ($res['error'] as $error) {
$errors [] = $error['description'];
$errors [] = $error['hint'];
error_log($error['hint']);
}
$out = implode('\n\n', $errors);
SP_Common::printJSON($out);
} else if (is_array($res['ok'])) {
$out = implode('\n\n', $res['ok']);
SP_Common::printJSON($out, 0);
}
\ No newline at end of file
+.
*
*/
define('APP_ROOT', '..');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
SP\Util::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP\Util::demoIsEnabled()) {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP\Common::parseParams('p', 'sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$res = SP\Import::doImport($_FILES["inFile"]);
if (isset($res['error']) && is_array($res['error'])) {
foreach ($res['error'] as $error) {
$errors [] = $error['description'];
$errors [] = $error['hint'];
error_log($error['hint']);
}
$out = implode('\n\n', $errors);
SP\Common::printJSON($out);
} else if (is_array($res['ok'])) {
$out = implode('\n\n', $res['ok']);
SP\Common::printJSON($out, 0);
}
\ No newline at end of file
diff --git a/ajax/ajax_migrate.php b/ajax/ajax_migrate.php
index c4fca2f1..e91628f8 100644
--- a/ajax/ajax_migrate.php
+++ b/ajax/ajax_migrate.php
@@ -1 +1 @@
-.
*
*/
define('APP_ROOT', '..');
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
SP_Util::checkReferer('POST');
if (!SP_Init::isLoggedIn()) {
SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP_Util::demoIsEnabled()) {
SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$frmDBUser = SP_Common::parseParams('p', 'dbuser');
$frmDBPass = SP_Common::parseParams('p', 'dbpass');
$frmDBName = SP_Common::parseParams('p', 'dbname');
$frmDBHost = SP_Common::parseParams('p', 'dbhost');
$frmMigrateEnabled = SP_Common::parseParams('p', 'chkmigrate', 0, false, 1);
if (!$frmMigrateEnabled) {
SP_Common::printJSON(_('Confirmar la importación de cuentas'));
}
if (!$frmDBUser) {
SP_Common::printJSON(_('Es necesario un usuario de conexión'));
}
if (!$frmDBPass) {
SP_Common::printJSON(_('Es necesaria una clave de conexión'));
}
if (!$frmDBName) {
SP_Common::printJSON(_('Es necesario el nombre de la BBDD'));
}
if (!$frmDBHost) {
SP_Common::printJSON(_('Es necesario un nombre de host'));
}
$options['dbhost'] = $frmDBHost;
$options['dbname'] = $frmDBName;
$options['dbuser'] = $frmDBUser;
$options['dbpass'] = $frmDBPass;
$res = SP_Migrate::migrate($options);
if (is_array($res['error'])) {
foreach ($res['error'] as $error) {
$errors [] = $error['description'];
$errors [] = $error['hint'];
error_log($error['hint']);
}
$out = implode('
', $errors);
SP_Common::printJSON($out);
} else if (is_array($res['ok'])) {
$out = implode('
', $res['ok']);
SP_Common::printJSON($out, 0);
}
\ No newline at end of file
+.
*
*/
define('APP_ROOT', '..');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
SP\Util::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP\Util::demoIsEnabled()) {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP\Common::parseParams('p', 'sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$frmDBUser = SP\Common::parseParams('p', 'dbuser');
$frmDBPass = SP\Common::parseParams('p', 'dbpass');
$frmDBName = SP\Common::parseParams('p', 'dbname');
$frmDBHost = SP\Common::parseParams('p', 'dbhost');
$frmMigrateEnabled = SP\Common::parseParams('p', 'chkmigrate', 0, false, 1);
if (!$frmMigrateEnabled) {
SP\Common::printJSON(_('Confirmar la importación de cuentas'));
} elseif (!$frmDBUser) {
SP\Common::printJSON(_('Es necesario un usuario de conexión'));
} elseif (!$frmDBPass) {
SP\Common::printJSON(_('Es necesaria una clave de conexión'));
} elseif (!$frmDBName) {
SP\Common::printJSON(_('Es necesario el nombre de la BBDD'));
} elseif (!$frmDBHost) {
SP\Common::printJSON(_('Es necesario un nombre de host'));
}
$options['dbhost'] = $frmDBHost;
$options['dbname'] = $frmDBName;
$options['dbuser'] = $frmDBUser;
$options['dbpass'] = $frmDBPass;
$res = SP\Migrate::migrate($options);
if (is_array($res['error'])) {
foreach ($res['error'] as $error) {
$errors [] = $error['description'];
$errors [] = $error['hint'];
error_log($error['hint']);
}
$out = implode('
', $errors);
SP\Common::printJSON($out);
} elseif (is_array($res['ok'])) {
$out = implode('
', $res['ok']);
SP\Common::printJSON($out, 0);
}
\ No newline at end of file
diff --git a/ajax/ajax_passReset.php b/ajax/ajax_passReset.php
index 5a40f5a5..31aaa0fe 100644
--- a/ajax/ajax_passReset.php
+++ b/ajax/ajax_passReset.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -24,63 +24,64 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-$sk = SP_Common::parseParams('p', 'sk', false);
+SP\Util::checkReferer('POST');
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
- SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
+$sk = SP\Common::parseParams('p', 'sk', false);
+
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
+ SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
-$userLogin = SP_Common::parseParams('p', 'login');
-$userEmail = SP_Common::parseParams('p', 'email');
-$userPass = SP_Common::parseParams('p', 'pass');
-$userPassV = SP_Common::parseParams('p', 'passv');
-$hash = SP_Common::parseParams('p', 'hash');
-$time = SP_Common::parseParams('p', 'time');
+$userLogin = SP\Common::parseParams('p', 'login');
+$userEmail = SP\Common::parseParams('p', 'email');
+$userPass = SP\Common::parseParams('p', 'pass');
+$userPassV = SP\Common::parseParams('p', 'passv');
+$hash = SP\Common::parseParams('p', 'hash');
+$time = SP\Common::parseParams('p', 'time');
$message['action'] = _('Recuperación de Clave');
if ($userLogin && $userEmail) {
- if (SP_Auth::mailPassRecover($userLogin, $userEmail)) {
- $message['text'][] = SP_Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
+ if (SP\Auth::mailPassRecover($userLogin, $userEmail)) {
+ $message['text'][] = SP\Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
- SP_Common::sendEmail($message);
- SP_Log::wrLogInfo($message);
- SP_Common::printJSON(_('Solicitud enviada') . ';;' . _('En breve recibirá un correo para completar la solicitud.'), 0, 'goLogin();');
+ SP\Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::printJSON(_('Solicitud enviada') . ';;' . _('En breve recibirá un correo para completar la solicitud.'), 0, 'goLogin();');
} else {
$message['text'][] = 'ERROR';
- $message['text'][] = SP_Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
+ $message['text'][] = SP\Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
- SP_Common::sendEmail($message);
- SP_Log::wrLogInfo($message);
- SP_Common::printJSON(_('No se ha podido realizar la solicitud. Consulte con el administrador.'));
+ SP\Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::printJSON(_('No se ha podido realizar la solicitud. Consulte con el administrador.'));
}
}
if ($userPass && $userPassV && $userPass === $userPassV) {
- $userId = SP_Users::checkHashPassRecover($hash);
+ $userId = SP\Users::checkHashPassRecover($hash);
if ($userId) {
- $user = new SP_Users();
+ $user = new SP\Users();
$user->userId = $userId;
$user->userPass = $userPass;
- if ($user->updateUserPass() && SP_Users::updateHashPassRecover($hash)) {
+ if ($user->updateUserPass() && SP\Users::updateHashPassRecover($hash)) {
$message['action'] = _('Modificar Clave Usuario');
- $message['text'][] = SP_Html::strongText(_('Login') . ': ') . $user->getUserLoginById($userId);
+ $message['text'][] = SP\Html::strongText(_('Login') . ': ') . $user->getUserLoginById($userId);
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ SP\Log::wrLogInfo($message);
+ SP\Common::sendEmail($message);
- SP_Common::printJSON(_('Clave actualizada'), 0, 'goLogin();');
+ SP\Common::printJSON(_('Clave actualizada'), 0, 'goLogin();');
}
}
- SP_Common::printJSON(_('Error al modificar la clave'));
+ SP\Common::printJSON(_('Error al modificar la clave'));
} else {
- SP_Common::printJSON(_('La clave es incorrecta o no coincide'));
+ SP\Common::printJSON(_('La clave es incorrecta o no coincide'));
}
\ No newline at end of file
diff --git a/ajax/ajax_search.php b/ajax/ajax_search.php
index dabd34b7..ca189714 100644
--- a/ajax/ajax_search.php
+++ b/ajax/ajax_search.php
@@ -24,20 +24,21 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Util::logout();
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Util::logout();
}
-$sk = SP_Common::parseParams('p', 'sk', false);
+$sk = SP\Common::parseParams('p', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
die('' . _('CONSULTA INVÁLIDA') . '
');
}
-$controller = new \Controller\SearchC();
+$controller = new SP\Controller\SearchC();
$controller->getSearch();
$controller->view();
\ No newline at end of file
diff --git a/ajax/ajax_sendRequest.php b/ajax/ajax_sendRequest.php
index 34f7c9b9..719dcd05 100644
--- a/ajax/ajax_sendRequest.php
+++ b/ajax/ajax_sendRequest.php
@@ -1,10 +1,9 @@
.
*
*/
+
define('APP_ROOT', '..');
-require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
-SP_Util::checkReferer('POST');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if (!SP_Init::isLoggedIn()) {
- SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
+SP\Util::checkReferer('POST');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
-$sk = SP_Common::parseParams('p', 'sk', false);
+$sk = SP\Common::parseParams('p', 'sk', false);
-if (!$sk || !SP_Common::checkSessionKey($sk)) {
- SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
+if (!$sk || !SP\Common::checkSessionKey($sk)) {
+ SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
}
-$frmAccountId = SP_Common::parseParams('p', 'accountid', 0);
-$frmDescription = SP_Common::parseParams('p', 'description');
+$frmAccountId = SP\Common::parseParams('p', 'accountid', 0);
+$frmDescription = SP\Common::parseParams('p', 'description');
if (!$frmDescription) {
- SP_Common::printJSON(_('Es necesaria una descripción'));
+ SP\Common::printJSON(_('Es necesaria una descripción'));
}
-$accountRequestData = SP_Accounts::getAccountRequestData($frmAccountId);
+$accountRequestData = SP\Account::getAccountRequestData($frmAccountId);
$recipients = array(
- SP_Users::getUserEmail($accountRequestData->account_userId),
- SP_Users::getUserEmail($accountRequestData->account_userEditId)
+ SP\Users::getUserEmail($accountRequestData->account_userId),
+ SP\Users::getUserEmail($accountRequestData->account_userEditId)
);
-$requestUsername = SP_Common::parseParams('s', 'uname');
-$requestLogin = SP_Common::parseParams('s', 'ulogin');
+$requestUsername = SP\Common::parseParams('s', 'uname');
+$requestLogin = SP\Common::parseParams('s', 'ulogin');
$message['action'] = _('Solicitud de Modificación de Cuenta');
-$message['text'][] = SP_Html::strongText(_('Solicitante') . ': ') . $requestUsername . ' (' . $requestLogin . ')';
-$message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $accountRequestData->account_name;
-$message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $accountRequestData->customer_name;
-$message['text'][] = SP_Html::strongText(_('Descripción') . ': ') . $frmDescription;
+$message['text'][] = SP\Html::strongText(_('Solicitante') . ': ') . $requestUsername . ' (' . $requestLogin . ')';
+$message['text'][] = SP\Html::strongText(_('Cuenta') . ': ') . $accountRequestData->account_name;
+$message['text'][] = SP\Html::strongText(_('Cliente') . ': ') . $accountRequestData->customer_name;
+$message['text'][] = SP\Html::strongText(_('Descripción') . ': ') . $frmDescription;
$mailto = implode(',', $recipients);
if ($mailto
- && SP_Util::mailrequestIsEnabled()
- && SP_Common::sendEmail($message, $mailto)
+ && SP\Util::mailrequestIsEnabled()
+ && SP\Common::sendEmail($message, $mailto)
) {
- SP_Log::wrLogInfo($message);
- SP_Common::printJSON(_('Solicitud enviada'), 0, "doAction('accsearch');");
+ SP\Log::wrLogInfo($message);
+ SP\Common::printJSON(_('Solicitud enviada'), 0, "doAction('" . \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH . "');");
}
-SP_Common::printJSON(_('Error al enviar la solicitud'));
\ No newline at end of file
+SP\Common::printJSON(_('Error al enviar la solicitud'));
\ No newline at end of file
diff --git a/ajax/ajax_usrpass.php b/ajax/ajax_usrpass.php
index 47e167f4..b6b016a9 100644
--- a/ajax/ajax_usrpass.php
+++ b/ajax/ajax_usrpass.php
@@ -1,45 +1,46 @@
.
-*
-*/
+/**
+ * sysPass
+ *
+ * @author nuxsmin
+ * @link http://syspass.org
+ * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
+ *
+ * This file is part of sysPass.
+ *
+ * sysPass is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * sysPass is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with sysPass. If not, see .
+ *
+ */
define('APP_ROOT', '..');
-require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'Init.php';
-SP_Util::checkReferer('GET');
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
-if ( ! SP_Init::isLoggedIn() ){
- SP_Util::logout();
+SP\Util::checkReferer('GET');
+
+if (!SP\Init::isLoggedIn()) {
+ SP\Util::logout();
}
-$userId = SP_Common::parseParams('g', 'userId', false);
+$userId = SP\Common::parseParams('g', 'userId', false);
-if ( ! $userId ) {
+if (!$userId) {
return;
}
-$tpl = new SP_Template();
+$tpl = new SP\Template();
$tpl->assign('userId', $userId);
-$controller = new \Controller\UsersMgmtC($tpl);
+$controller = new SP\Controller\UsersMgmtC($tpl);
$controller->getUserPass();
$controller->view();
\ No newline at end of file
diff --git a/ajax/ajax_viewpass.php b/ajax/ajax_viewpass.php
index 16f06cef..dd4a666e 100644
--- a/ajax/ajax_viewpass.php
+++ b/ajax/ajax_viewpass.php
@@ -1,11 +1,11 @@
accountParentId = ( isset($_SESSION["accParentId"]) ) ? $_SESSION["accParentId"] : "";
-$account->accountId = $accountId;
-//$account->accountIsHistory = $isHistory;
+$account = (!$isHistory) ? new SP\Account() : new SP\AccountHistory();
-$accountData = $account->getAccountPass($isHistory);
+$account->setAccountParentId((isset($_SESSION["accParentId"])) ? $_SESSION["accParentId"] : "");
+$account->setAccountId($accountId);
-if ($isHistory && !$account->checkAccountMPass()){
- SP_Common::printJSON(_('La clave maestra no coincide'));
+$accountData = $account->getAccountPassData();
+
+if ($isHistory && !$account->checkAccountMPass()) {
+ SP\Common::printJSON(_('La clave maestra no coincide'));
}
-$accountData = $account->getAccountPass($isHistory);
-
-if (!SP_Acl::checkAccountAccess(SP_Acl::ACTION_ACC_VIEW_PASS, $account->getAccountDataForACL()) || !SP_Acl::checkUserAccess(SP_Acl::ACTION_ACC_VIEW_PASS)) {
- SP_Common::printJSON(_('No tiene permisos para acceder a esta cuenta'));
+if (!SP\Acl::checkAccountAccess(SP\Acl::ACTION_ACC_VIEW_PASS, $account->getAccountDataForACL()) || !SP\Acl::checkUserAccess(SP\Acl::ACTION_ACC_VIEW_PASS)) {
+ SP\Common::printJSON(_('No tiene permisos para acceder a esta cuenta'));
}
-if (!SP_Users::checkUserUpdateMPass()) {
- SP_Common::printJSON(_('Clave maestra actualizada') . '
' . _('Reinicie la sesión para cambiarla'));
+if (!SP\Users::checkUserUpdateMPass()) {
+ SP\Common::printJSON(_('Clave maestra actualizada') . '
' . _('Reinicie la sesión para cambiarla'));
}
-$masterPass = SP_Crypt::getSessionMasterPass();
-$accountClearPass = SP_Crypt::getDecrypt($accountData->pass, $masterPass, $accountData->iv);
+$masterPass = SP\Crypt::getSessionMasterPass();
+$accountClearPass = SP\Crypt::getDecrypt($accountData->pass, $masterPass, $accountData->iv);
if (!$isHistory) {
$account->incrementDecryptCounter();
@@ -70,10 +69,10 @@ if (!$isHistory) {
$message['text'][] = _('ID') . ': ' . $accountId;
$message['text'][] = _('Cuenta') . ': ' . $accountData->customer_name . " / " . $accountData->name;
- SP_Log::wrLogInfo($message);
+ SP\Log::wrLogInfo($message);
}
-$accountPass = htmlentities(trim($accountClearPass),ENT_COMPAT,'UTF-8');
+$accountPass = htmlentities(trim($accountClearPass), ENT_COMPAT, 'UTF-8');
$data = array(
'title' => _('Clave de Cuenta'),
@@ -81,4 +80,4 @@ $data = array(
'accpass' => $accountPass
);
-SP_Common::printJSON($data, 0);
\ No newline at end of file
+SP\Common::printJSON($data, 0);
\ No newline at end of file
diff --git a/css/css.php b/css/css.php
index a0240676..5db107c2 100644
--- a/css/css.php
+++ b/css/css.php
@@ -24,7 +24,8 @@
*/
define('APP_ROOT', '..');
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Init.php';
+
+require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
$cssFiles = array(
array('href' => 'css/reset.css', 'min' => true),
@@ -39,8 +40,8 @@ $cssFiles = array(
array('href' => 'css/styles.css', 'min' => true)
);
-if (!SP_Util::resultsCardsIsEnabled()) {
+if (!SP\Util::resultsCardsIsEnabled()) {
array_push($cssFiles, array('href' => 'css/search-grid.css', 'min' => true));
}
-SP_Util::getMinified('css', $cssFiles);
\ No newline at end of file
+SP\Util::getMinified('css', $cssFiles);
\ No newline at end of file
diff --git a/inc/Account.class.php b/inc/Account.class.php
new file mode 100644
index 00000000..def19310
--- /dev/null
+++ b/inc/Account.class.php
@@ -0,0 +1,674 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+/**
+ * Esta clase es la encargada de realizar las operaciones sobre las cuentas de sysPass.
+ */
+class Account extends AccountBase implements AccountInterface
+{
+ /**
+ * @var array Variable para la caché de parámetros de una cuenta.
+ */
+ private $_cacheParams;
+
+ /**
+ * Obtener los datos de usuario y modificador de una cuenta.
+ *
+ * @param int $accountId con el Id de la cuenta
+ * @return false|object con el id de usuario y modificador.
+ */
+ public static function getAccountRequestData($accountId)
+ {
+ $query = 'SELECT account_userId,'
+ . 'account_userEditId,'
+ . 'account_name,'
+ . 'customer_name '
+ . 'FROM accounts '
+ . 'LEFT JOIN customers ON account_customerId = customer_id '
+ . 'WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $accountId;
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ return $queryRes;
+ }
+
+ /**
+ * Obtiene el listado con el nombre de los usuaios de una cuenta.
+ *
+ * @param int $accountId con el Id de la cuenta
+ * @return false|array con los nombres de los usuarios ordenados
+ */
+ public static function getAccountUsersName($accountId)
+ {
+ $query = 'SELECT user_name '
+ . 'FROM accUsers '
+ . 'JOIN usrData ON accuser_userId = user_id '
+ . 'WHERE accuser_accountId = :id';
+
+ $data['id'] = $accountId;
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ if (!is_array($queryRes)) {
+ return false;
+ }
+
+ foreach ($queryRes as $users) {
+ $usersName[] = $users->user_name;
+ }
+
+ sort($usersName, SORT_STRING);
+
+ return $usersName;
+ }
+
+ /**
+ * Actualiza los datos de una cuenta en la BBDD.
+ *
+ * @return bool
+ */
+ public function updateAccount()
+ {
+ $message['action'] = __FUNCTION__;
+
+ // Guardamos una copia de la cuenta en el histórico
+ if (!AccountHistory::addHistory($this->getAccountId(), false)) {
+ $message['text'][] = _('Error al actualizar el historial');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ $message['action'] = _('Actualizar Cuenta');
+
+ if (!Groups::updateGroupsForAccount($this->getAccountId(), $this->getAccountUserGroupsId())) {
+ $message['text'][] = _('Error al actualizar los grupos secundarios');
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ if (!Users::updateUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
+ $message['text'][] = _('Error al actualizar los usuarios de la cuenta');
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ $query = 'UPDATE accounts SET '
+ . 'account_customerId = :accountCustomerId,'
+ . 'account_categoryId = :accountCategoryId,'
+ . 'account_name = :accountName,'
+ . 'account_login = :accountLogin,'
+ . 'account_url = :accountUrl,'
+ . 'account_notes = :accountNotes,'
+ . 'account_userEditId = :accountUserEditId,'
+ . 'account_dateEdit = NOW(),'
+ . 'account_otherUserEdit = :accountOtherUserEdit,'
+ . 'account_otherGroupEdit = :accountOtherGroupEdit '
+ . 'WHERE account_id = :accountId';
+
+ $data['accountCustomerId'] = $this->getAccountCustomerId();
+ $data['accountCategoryId'] = $this->getAccountCategoryId();
+ $data['accountName'] = $this->getAccountName();
+ $data['accountLogin'] = $this->getAccountLogin();
+ $data['accountUrl'] = $this->getAccountUrl();
+ $data['accountNotes'] = $this->getAccountNotes();
+ $data['accountUserEditId'] = $this->getAccountUserEditId();
+ $data['accountOtherUserEdit'] = intval($this->getAccountOtherUserEdit());
+ $data['accountOtherGroupEdit'] = intval($this->getAccountOtherGroupEdit());
+ $data['accountId'] = $this->getAccountId();
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ $accountInfo = array('customer_name');
+ $this->getAccountInfoById($accountInfo);
+
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $this->_cacheParams['customer_name'];
+ $message['text'][] = Html::strongText(_('Cuenta') . ': ') . $this->getAccountName() . " (" . $this->getAccountId() . ")";
+
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+
+ return true;
+ }
+
+ /**
+ * Restaurar una cuenta desde el histórico.
+ *
+ * @param $id int El Id del registro en el histórico
+ * @return bool
+ */
+ public function restoreFromHistory($id)
+ {
+ $message['action'] = __FUNCTION__;
+
+ // Guardamos una copia de la cuenta en el histórico
+ if (!AccountHistory::addHistory($this->getAccountId(), false)) {
+ $message['text'][] = _('Error al actualizar el historial');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ $query = 'UPDATE accounts dst, '
+ . '(SELECT * FROM accHistory WHERE acchistory_id = :id) src SET '
+ . 'dst.account_customerId = src.acchistory_customerId,'
+ . 'dst.account_categoryId = src.acchistory_categoryId,'
+ . 'dst.account_name = src.acchistory_name,'
+ . 'dst.account_login = src.acchistory_login,'
+ . 'dst.account_url = src.acchistory_url,'
+ . 'dst.account_notes = src.acchistory_notes,'
+ . 'dst.account_userEditId = :accountUserEditId,'
+ . 'dst.account_dateEdit = NOW(),'
+ . 'dst.account_otherUserEdit = src.acchistory_otherUserEdit + 0,'
+ . 'dst.account_otherGroupEdit = src.acchistory_otherGroupEdit + 0,'
+ . 'dst.account_pass = src.acchistory_pass,'
+ . 'dst.account_IV = src.acchistory_IV '
+ . 'WHERE dst.account_id = :accountId';
+
+ $data['id'] = $id;
+ $data['accountId'] = $this->getAccountId();
+ $data['accountUserEditId'] = $this->getAccountUserEditId();
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ $accountInfo = array('customer_name', 'account_name');
+ $this->getAccountInfoById($accountInfo);
+
+ $message['action'] = _('Restaurar Cuenta');
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $this->_cacheParams['customer_name'];
+ $message['text'][] = Html::strongText(_('Cuenta') . ': ') . $this->_cacheParams['account_name'] . " (" . $this->getAccountId() . ")";
+
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+
+ return true;
+ }
+
+ /**
+ * Obtener los datos de una cuenta con el id.
+ * Se guardan los datos en la variable $cacheParams de la clase para consultarlos
+ * posteriormente.
+ *
+ * @param array $params con los campos de la BBDD a obtener
+ * @return bool
+ */
+ private function getAccountInfoById($params)
+ {
+ if (!is_array($params)) {
+ return false;
+ }
+
+ if (is_array($this->_cacheParams)) {
+ $cache = true;
+
+ foreach ($params as $param) {
+ if (!array_key_exists($param, $this->_cacheParams)) {
+ $cache = false;
+ }
+ }
+
+ if ($cache) {
+ return true;
+ }
+ }
+
+ $query = 'SELECT ' . implode(',', $params) . ' '
+ . 'FROM accounts '
+ . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
+ . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id '
+ . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id '
+ . 'LEFT JOIN customers ON account_customerId = customer_id '
+ . 'WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ foreach ($queryRes as $param => $value) {
+ $this->_cacheParams[$param] = $value;
+ }
+
+ return true;
+ }
+
+ /**
+ * Obtener los datos de una cuenta.
+ * Esta funcion realiza la consulta a la BBDD y guarda los datos en las variables de la clase.
+ *
+ * @return object
+ * @throws Exception
+ */
+ public function getAccountData()
+ {
+ $query = 'SELECT account_id,'
+ . 'account_name,'
+ . 'account_categoryId,'
+ . 'account_userId,'
+ . 'account_customerId,'
+ . 'account_userGroupId,'
+ . 'account_userEditId,'
+ . 'category_name,'
+ . 'account_login,'
+ . 'account_url,'
+ . 'account_pass,'
+ . 'account_IV,'
+ . 'account_notes,'
+ . 'account_countView,'
+ . 'account_countDecrypt,'
+ . 'account_dateAdd,'
+ . 'account_dateEdit,'
+ . 'BIN(account_otherUserEdit) AS account_otherUserEdit,'
+ . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,'
+ . 'u1.user_name,'
+ . 'u1.user_login,'
+ . 'u2.user_name as user_editName,'
+ . 'u2.user_login as user_editLogin,'
+ . 'usergroup_name,'
+ . 'customer_name, '
+ . 'CONCAT(account_name,account_categoryId,account_customerId,account_login,account_url,account_notes,BIN(account_otherUserEdit),BIN(account_otherGroupEdit)) as modHash '
+ . 'FROM accounts '
+ . 'LEFT JOIN categories ON account_categoryId = category_id '
+ . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
+ . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id '
+ . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id '
+ . 'LEFT JOIN customers ON account_customerId = customer_id '
+ . 'WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ throw new Exception(_('No se pudieron obtener los datos de la cuenta'));
+ }
+
+ $this->setAccountUserId($queryRes->account_userId);
+ $this->setAccountUserGroupId($queryRes->account_userGroupId);
+ $this->setAccountOtherUserEdit($queryRes->account_otherUserEdit);
+ $this->setAccountOtherGroupEdit($queryRes->account_otherGroupEdit);
+ $this->setAccountModHash($queryRes->modHash);
+
+ return $queryRes;
+ }
+
+ /**
+ * Crea una nueva cuenta en la BBDD
+ *
+ * @return bool
+ */
+ public function createAccount()
+ {
+ $query = 'INSERT INTO accounts SET '
+ . 'account_customerId = :accountCustomerId,'
+ . 'account_categoryId = :accountCategoryId,'
+ . 'account_name = :accountName,'
+ . 'account_login = :accountLogin,'
+ . 'account_url = :accountUrl,'
+ . 'account_pass = :accountPass,'
+ . 'account_IV = :accountIV,'
+ . 'account_notes = :accountNotes,'
+ . 'account_dateAdd = NOW(),'
+ . 'account_userId = :accountUserId,'
+ . 'account_userGroupId = :accountUserGroupId,'
+ . 'account_otherUserEdit = :accountOtherUserEdit,'
+ . 'account_otherGroupEdit = :accountOtherGroupEdit';
+
+ $data['accountCustomerId'] = $this->getAccountCustomerId();
+ $data['accountCategoryId'] = $this->getAccountCategoryId();
+ $data['accountName'] = $this->getAccountName();
+ $data['accountLogin'] = $this->getAccountLogin();
+ $data['accountUrl'] = $this->getAccountUrl();
+ $data['accountPass'] = $this->getAccountPass();
+ $data['accountIV'] = $this->getAccountIV();
+ $data['accountNotes'] = $this->getAccountNotes();
+ $data['accountUserId'] = $this->getAccountUserId();
+ $data['accountUserGroupId'] = $this->getAccountUserGroupId();
+ $data['accountOtherUserEdit'] = $this->getAccountOtherUserEdit();
+ $data['accountOtherGroupEdit'] = $this->getAccountOtherGroupEdit();
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ $this->setAccountId(DB::$lastId);
+
+ $message['action'] = __FUNCTION__;
+
+ if (is_array($this->getAccountUserGroupsId())) {
+ if (!Groups::addGroupsForAccount($this->getAccountId(), $this->getAccountUserGroupsId())) {
+ $message['text'][] = _('Error al actualizar los grupos secundarios');
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+ }
+
+ if (is_array($this->getAccountUsersId())) {
+ if (!Users::addUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
+ $message['text'][] = _('Error al actualizar los usuarios de la cuenta');
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+ }
+
+ $accountInfo = array('customer_name');
+ $this->getAccountInfoById($accountInfo);
+
+ $message['action'] = _('Nueva Cuenta');
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $this->_cacheParams['customer_name'];
+ $message['text'][] = Html::strongText(_('Cuenta') . ': ') . $this->getAccountName() . " (" . $this->getAccountId() . ")";
+
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+
+ return true;
+ }
+
+ /**
+ * Elimina los datos de una cuenta en la BBDD.
+ *
+ * @return bool
+ */
+ public function deleteAccount()
+ {
+ // Guardamos una copia de la cuenta en el histórico
+ AccountHistory::addHistory($this->getAccountId(), true) || die (_('ERROR: Error en la operación.'));
+
+ $accountInfo = array('account_name,customer_name');
+ $this->getAccountInfoById($accountInfo);
+
+ $message['action'] = _('Eliminar Cuenta');
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $this->_cacheParams['customer_name'];
+ $message['text'][] = Html::strongText(_('Cuenta') . ': ') . $this->_cacheParams['account_name'] . " (" . $this->getAccountId() . ")";
+
+ $query = 'DELETE FROM accounts WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ if (!Groups::deleteGroupsForAccount($this->getAccountId())) {
+ $message['text'][] = _('Error al eliminar grupos asociados a la cuenta');
+ }
+
+ if (!Users::deleteUsersForAccount($this->getAccountId())) {
+ $message['text'][] = _('Error al eliminar usuarios asociados a la cuenta');
+ }
+
+ if (!Files::deleteAccountFiles($this->getAccountId())) {
+ $message['text'][] = _('Error al eliminar archivos asociados a la cuenta');
+ }
+
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+
+ return true;
+ }
+
+ /**
+ * Incrementa el contador de visitas de una cuenta en la BBDD
+ *
+ * @return bool
+ */
+ public function incrementViewCounter()
+ {
+ $query = 'UPDATE accounts SET account_countView = (account_countView + 1) WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ return DB::getQuery($query, __FUNCTION__, $data);
+ }
+
+ /**
+ * Incrementa el contador de vista de clave de una cuenta en la BBDD
+ *
+ * @return bool
+ */
+ public function incrementDecryptCounter()
+ {
+ $query = 'UPDATE accounts SET account_countDecrypt = (account_countDecrypt + 1) WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ return DB::getQuery($query, __FUNCTION__, $data);
+ }
+
+ /**
+ * Actualiza las claves de todas las cuentas con la nueva clave maestra.
+ *
+ * @param string $currentMasterPass con la clave maestra actual
+ * @param string $newMasterPass con la nueva clave maestra
+ * @param string $newHash con el nuevo hash de la clave maestra
+ * @return bool
+ */
+ public function updateAccountsMasterPass($currentMasterPass, $newMasterPass, $newHash = null)
+ {
+ $accountsOk = array();
+ $userId = Session::getUserId();
+ $demoEnabled = Util::demoIsEnabled();
+ $errorCount = 0;
+
+ $message['action'] = _('Actualizar Clave Maestra');
+ $message['text'][] = _('Inicio');
+
+ Log::wrLogInfo($message);
+
+ // Limpiar 'text' para los próximos mensajes
+ $message['text'] = array();
+
+ if (!Crypt::checkCryptModule()) {
+ $message['text'][] = _('Error en el módulo de encriptación');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ $accountsPass = $this->getAccountsPassData();
+
+ if (!$accountsPass) {
+ $message['text'][] = _('Error al obtener las claves de las cuentas');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ foreach ($accountsPass as $account) {
+ $this->setAccountId($account->account_id);
+ $this->setAccountUserEditId($userId);
+
+ // No realizar cambios si está en modo demo
+ if ($demoEnabled) {
+ $accountsOk[] = $this->getAccountId();
+ continue;
+ }
+
+ if (strlen($account->account_IV) < 32) {
+ $errorCount++;
+ $message['text'][] = _('IV de encriptación incorrecto') . " (" . $account->account_id . ")";
+ continue;
+ }
+
+ $decryptedPass = Crypt::getDecrypt($account->account_pass, $currentMasterPass, $account->account_IV);
+ $this->setAccountPass(Crypt::mkEncrypt($decryptedPass, $newMasterPass));
+ $this->setAccountIV(Crypt::$strInitialVector);
+
+ if ($this->getAccountPass() === false) {
+ $errorCount++;
+ continue;
+ }
+
+ if (!$this->updateAccountPass(true)) {
+ $errorCount++;
+ $message['text'][] = _('Fallo al actualizar la clave de la cuenta') . '(' . $this->getAccountId() . ')';
+ continue;
+ }
+
+ $accountsOk[] = $this->getAccountId();
+ }
+
+ // Vaciar el array de mensaje de log
+ if (count($message['text']) > 0) {
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ if ($accountsOk) {
+ $message['text'][] = _('Cuentas actualizadas') . ': ' . implode(',', $accountsOk);
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ $message['text'][] = _('Fin');
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+
+ if ($errorCount > 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Obtener los datos relativos a la clave de todas las cuentas.
+ *
+ * @return false|array Con los datos de la clave
+ */
+ protected function getAccountsPassData()
+ {
+ $query = 'SELECT account_id, account_pass, account_IV FROM accounts';
+
+ return DB::getResults($query, __FUNCTION__);
+ }
+
+ /**
+ * Obtener los datos de una cuenta para mostrar la clave
+ * Esta funcion realiza la consulta a la BBDD y devuelve los datos.
+ *
+ * @return object|false
+ */
+ public function getAccountPassData()
+ {
+ $query = 'SELECT account_name AS name,'
+ . 'account_userId AS userId,'
+ . 'account_userGroupId AS groupId,'
+ . 'account_login AS login,'
+ . 'account_pass AS pass,'
+ . 'account_IV AS iv,'
+ . 'customer_name '
+ . 'FROM accounts '
+ . 'LEFT JOIN customers ON account_customerId = customer_id '
+ . 'WHERE account_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ $this->setAccountUserId($queryRes->userId);
+ $this->setAccountUserGroupId($queryRes->groupId);
+ $this->setAccountPass($queryRes->pass);
+ $this->setAccountIV($queryRes->iv);
+
+ return $queryRes;
+ }
+
+ /**
+ * Actualiza la clave de una cuenta en la BBDD.
+ *
+ * @param bool $isMassive para no actualizar el histórico ni enviar mensajes
+ * @param bool $isRestore indica si es una restauración
+ * @return bool
+ */
+ public function updateAccountPass($isMassive = false, $isRestore = false)
+ {
+ $message['action'] = __FUNCTION__;
+
+ // No actualizar el histórico si es por cambio de clave maestra o restauración
+ if (!$isMassive && !$isRestore) {
+ // Guardamos una copia de la cuenta en el histórico
+ if (!AccountHistory::addHistory($this->getAccountId(), false)) {
+ $message['text'][] = _('Error al actualizar el historial');
+ Log::wrLogInfo($message);
+ return false;
+ }
+ }
+
+ $query = 'UPDATE accounts SET '
+ . 'account_pass = :accountPass,'
+ . 'account_IV = :accountIV,'
+ . 'account_userEditId = :accountUserEditId,'
+ . 'account_dateEdit = NOW() '
+ . 'WHERE account_id = :accountId';
+
+ $data['accountPass'] = $this->getAccountPass();
+ $data['accountIV'] = $this->getAccountIV();
+ $data['accountUserEditId'] = $this->getAccountUserEditId();
+ $data['accountId'] = $this->getAccountId();
+
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ // No escribir en el log ni enviar correos si la actualización es
+ // por cambio de clave maestra o restauración
+ if (!$isMassive && !$isRestore) {
+ $accountInfo = array('customer_name', 'account_name');
+ $this->getAccountInfoById($accountInfo);
+
+ $message['action'] = _('Modificar Clave');
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $this->_cacheParams['customer_name'];
+ $message['text'][] = Html::strongText(_('Cuenta') . ': ') . $this->_cacheParams['account_name'] . " (" . $this->getAccountId() . ")";
+
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
+ }
+
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/inc/AccountBase.class.php b/inc/AccountBase.class.php
new file mode 100644
index 00000000..85963b53
--- /dev/null
+++ b/inc/AccountBase.class.php
@@ -0,0 +1,578 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+/**
+ * Clase abstracta para definición de métodos comunes a las cuentas
+ */
+abstract class AccountBase
+{
+ /**
+ * Tiempo de expiración de la caché de ACLde usuarios/grupos de cuentas
+ */
+ const CACHE_EXPIRE_TIME = 300;
+ /**
+ * @var int Id de la cuenta padre.
+ */
+ private $_accountParentId;
+ /**
+ * @var string Hash con los datos de la cuenta para verificación de cambios.
+ */
+ private $_accountModHash;
+ /**
+ * @var int Indica si la cuenta es un registro del hitórico.
+ */
+ private $_accountIsHistory = 0;
+ /**
+ * @var int Id de la cuenta.
+ */
+ private $_accountId;
+ /**
+ * @var int Id del usuario principal de la cuenta.
+ */
+ private $_accountUserId;
+ /**
+ * @var array Los Ids de los usuarios secundarios de la cuenta.
+ */
+ private $_accountUsersId;
+ /**
+ * @var array Id del grupo principal de la cuenta.
+ */
+ private $_accountUserGroupId;
+ /**
+ * @var array Los Ids de los grupos secundarios de la cuenta.
+ */
+ private $_accountUserGroupsId;
+ /**
+ * @var int Id del usuario que editó la cuenta.
+ */
+ private $_accountUserEditId;
+ /**
+ * @var string El nombre de la cuenta.
+ */
+ private $_accountName;
+ /**
+ * @var int Id del cliente de la cuenta.
+ */
+ private $_accountCustomerId;
+ /**
+ * @var int Id de la categoría de la cuenta.
+ */
+ private $_accountCategoryId;
+ /**
+ * @var string El nombre de usuario de la cuenta.
+ */
+ private $_accountLogin;
+ /**
+ * @var string La URL de la cuenta.
+ */
+ private $_accountUrl;
+ /**
+ * @var string La clave de la cuenta.
+ */
+ private $_accountPass;
+ /**
+ * @var string El vector de inicialización de la cuenta.
+ */
+ private $_accountIV;
+ /**
+ * @var string Las nosta de la cuenta.
+ */
+ private $_accountNotes;
+ /**
+ * @var bool Si se permite la edición por los usuarios secundarios.
+ */
+ private $_accountOtherUserEdit;
+ /**
+ * @var bool Si se permita la edición por los grupos secundarios.
+ */
+ private $_accountOtherGroupEdit;
+ /**
+ * @var array Los Ids de los grupos con acceso a la cuenta
+ */
+ private $_cacheUserGroupsId;
+ /**
+ * @var array Los Ids de los usuarios con acceso a la cuenta
+ */
+ private $_cacheUsersId;
+
+ /**
+ * Constructor
+ *
+ * @param int $id con el Id de la cuenta a obtener
+ */
+ public function __construct($id = null)
+ {
+ if (!is_null($id)) {
+ $this->setAccountId($id);
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountUserEditId()
+ {
+ return $this->_accountUserEditId;
+ }
+
+ /**
+ * @param int $accountUserEditId
+ */
+ public function setAccountUserEditId($accountUserEditId)
+ {
+ $this->_accountUserEditId = $accountUserEditId;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountPass()
+ {
+ return $this->_accountPass;
+ }
+
+ /**
+ * @param string $accountPass
+ */
+ public function setAccountPass($accountPass)
+ {
+ $this->_accountPass = $accountPass;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountIV()
+ {
+ return $this->_accountIV;
+ }
+
+ /**
+ * @param string $accountIV
+ */
+ public function setAccountIV($accountIV)
+ {
+ $this->_accountIV = $accountIV;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountIsHistory()
+ {
+ return $this->_accountIsHistory;
+ }
+
+ /**
+ * @param int $accountIsHistory
+ */
+ public function setAccountIsHistory($accountIsHistory)
+ {
+ $this->_accountIsHistory = $accountIsHistory;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountParentId()
+ {
+ return $this->_accountParentId;
+ }
+
+ /**
+ * @param int $accountParentId
+ */
+ public function setAccountParentId($accountParentId)
+ {
+ $this->_accountParentId = $accountParentId;
+ }
+
+ /**
+ * Devolver datos de la cuenta para comprobación de accesos.
+ *
+ * @param int $accountId con el id de la cuenta
+ * @return array con los datos de la cuenta
+ */
+ public function getAccountDataForACL($accountId = null)
+ {
+ $accId = (!is_null($accountId)) ? $accountId : $this->getAccountId();
+
+ return array(
+ 'id' => $accId,
+ 'user_id' => $this->getAccountUserId(),
+ 'group_id' => $this->getAccountUserGroupId(),
+ 'users_id' => $this->getUsersAccount(),
+ 'groups_id' => $this->getGroupsAccount(),
+ 'otheruser_edit' => $this->getAccountOtherUserEdit(),
+ 'othergroup_edit' => $this->getAccountOtherGroupEdit()
+ );
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getAccountId()
+ {
+ return $this->_accountId;
+ }
+
+ /**
+ * @param int $accountId
+ */
+ public function setAccountId($accountId)
+ {
+ $this->_accountId = (int)$accountId;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountUserId()
+ {
+ return $this->_accountUserId;
+ }
+
+ /**
+ * @param int $accountUserId
+ */
+ public function setAccountUserId($accountUserId)
+ {
+ $this->_accountUserId = $accountUserId;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountUserGroupId()
+ {
+ return $this->_accountUserGroupId;
+ }
+
+ /**
+ * @param int $accountUserGroupId
+ */
+ public function setAccountUserGroupId($accountUserGroupId)
+ {
+ $this->_accountUserGroupId = $accountUserGroupId;
+ }
+
+ /**
+ * Obtiene el listado usuarios con acceso a una cuenta.
+ * Lo almacena en la cache de sesión como array de cuentas
+ *
+ * @return array Con los registros con id de cuenta como clave e id de usuario como valor
+ */
+ public function getUsersAccount()
+ {
+ $accId = $this->getAccountId();
+
+ $cacheUsers = &$_SESSION['cache']['usersId'];
+
+ if (!is_array($cacheUsers)) {
+ $cacheUsers = array($accId => array(), 'expires' => 0);
+ }
+
+ if (!isset($cacheUsers[$accId])
+ || time() > $cacheUsers['expires']
+ ) {
+ $cacheUsers[$accId] = Users::getUsersForAccount($accId);
+ $cacheUsers['expires'] = time() + self::CACHE_EXPIRE_TIME;
+ }
+
+ return $cacheUsers[$accId];
+ }
+
+ /**
+ * Obtiene el listado de grupos secundarios de una cuenta.
+ * Lo almacena en la cache de sesión como array de cuentas
+ *
+ * @return array con los registros con id de cuenta como clave e id de grupo como valor
+ */
+ public function getGroupsAccount()
+ {
+ $accId = $this->getAccountId();
+ $cacheUserGroups = &$_SESSION['cache']['userGroupsId'];
+
+ if (!is_array($cacheUserGroups)) {
+ $cacheUserGroups = array($accId => array(), 'expires' => 0);
+ }
+
+ if (!isset($cacheUserGroups[$accId])
+ || time() > $cacheUserGroups['expires']
+ ) {
+ $cacheUserGroups[$accId] = Groups::getGroupsForAccount($accId);
+ $cacheUserGroups['expires'] = time() + self::CACHE_EXPIRE_TIME;
+ }
+
+ return $cacheUserGroups[$accId];
+ }
+
+ /**
+ * @return bool
+ */
+ public function getAccountOtherUserEdit()
+ {
+ return $this->_accountOtherUserEdit;
+ }
+
+ /**
+ * @param bool $accountOtherUserEdit
+ */
+ public function setAccountOtherUserEdit($accountOtherUserEdit)
+ {
+ $this->_accountOtherUserEdit = $accountOtherUserEdit;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getAccountOtherGroupEdit()
+ {
+ return $this->_accountOtherGroupEdit;
+ }
+
+ /**
+ * @param bool $accountOtherGroupEdit
+ */
+ public function setAccountOtherGroupEdit($accountOtherGroupEdit)
+ {
+ $this->_accountOtherGroupEdit = $accountOtherGroupEdit;
+ }
+
+ /**
+ * Calcular el hash de los datos de una cuenta.
+ * Esta función se utiliza para verificar si los datos de un formulario han sido cambiados
+ * con respecto a los guardados
+ *
+ * @return string con el hash
+ */
+ public function calcChangesHash()
+ {
+ $groups = 0;
+ $users = 0;
+
+ if (is_array($this->getAccountUserGroupsId())) {
+ $groups = implode($this->getAccountUserGroupsId());
+ } elseif (is_array($this->_cacheUserGroupsId)) {
+ foreach ($this->_cacheUserGroupsId as $group) {
+ if (is_array($group)) {
+ // Ordenar el array para que el hash sea igual
+ sort($group, SORT_NUMERIC);
+ $groups = implode($group);
+ }
+ }
+ }
+
+ if (is_array($this->getAccountUsersId())) {
+ $users = implode($this->getAccountUsersId());
+ } elseif (is_array($this->_cacheUsersId)) {
+ foreach ($this->_cacheUsersId as $user) {
+ if (is_array($user)) {
+ // Ordenar el array para que el hash sea igual
+ sort($user, SORT_NUMERIC);
+ $users = implode($user);
+ }
+ }
+ }
+
+ if ($this->getAccountModHash()) {
+ $hashItems = $this->getAccountModHash() . (int)$users . (int)$groups;
+ //error_log("HASH MySQL: ".$hashItems);
+ } else {
+ $hashItems = $this->getAccountName() .
+ $this->getAccountCategoryId() .
+ $this->getAccountCustomerId() .
+ $this->getAccountLogin() .
+ $this->getAccountUrl() .
+ $this->getAccountNotes() .
+ $this->getAccountOtherUserEdit() .
+ $this->getAccountOtherGroupEdit() .
+ (int)$users .
+ (int)$groups;
+ //error_log("HASH PHP: ".$hashItems);
+ }
+
+ return md5($hashItems);
+ }
+
+ /**
+ * @return array
+ */
+ public function getAccountUserGroupsId()
+ {
+ return $this->_accountUserGroupsId;
+ }
+
+ /**
+ * @param array $accountUserGroupsId
+ */
+ public function setAccountUserGroupsId($accountUserGroupsId)
+ {
+ $this->_accountUserGroupsId = $accountUserGroupsId;
+ }
+
+ /**
+ * @return array
+ */
+ public function getAccountUsersId()
+ {
+ return $this->_accountUsersId;
+ }
+
+ /**
+ * @param array $accountUsersId
+ */
+ public function setAccountUsersId($accountUsersId)
+ {
+ $this->_accountUsersId = $accountUsersId;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountModHash()
+ {
+ return $this->_accountModHash;
+ }
+
+ /**
+ * @param string $accountModHash
+ */
+ public function setAccountModHash($accountModHash)
+ {
+ $this->_accountModHash = $accountModHash;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountName()
+ {
+ return $this->_accountName;
+ }
+
+ /**
+ * @param string $accountName
+ */
+ public function setAccountName($accountName)
+ {
+ $this->_accountName = $accountName;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountCategoryId()
+ {
+ return $this->_accountCategoryId;
+ }
+
+ /**
+ * @param int $accountCategoryId
+ */
+ public function setAccountCategoryId($accountCategoryId)
+ {
+ $this->_accountCategoryId = $accountCategoryId;
+ }
+
+ /**
+ * @return int
+ */
+ public function getAccountCustomerId()
+ {
+ return $this->_accountCustomerId;
+ }
+
+ /**
+ * @param int $accountCustomerId
+ */
+ public function setAccountCustomerId($accountCustomerId)
+ {
+ $this->_accountCustomerId = $accountCustomerId;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountLogin()
+ {
+ return $this->_accountLogin;
+ }
+
+ /**
+ * @param string $accountLogin
+ */
+ public function setAccountLogin($accountLogin)
+ {
+ $this->_accountLogin = $accountLogin;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountUrl()
+ {
+ return $this->_accountUrl;
+ }
+
+ /**
+ * @param string $accountUrl
+ */
+ public function setAccountUrl($accountUrl)
+ {
+ $this->_accountUrl = $accountUrl;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountNotes()
+ {
+ return $this->_accountNotes;
+ }
+
+ /**
+ * @param string $accountNotes
+ */
+ public function setAccountNotes($accountNotes)
+ {
+ $this->_accountNotes = $accountNotes;
+ }
+
+ /**
+ * Obtener los datos de una cuenta para mostrar la clave
+ * Esta funcion realiza la consulta a la BBDD y devuelve los datos.
+ */
+ protected abstract function getAccountPassData();
+
+ /**
+ * Obtener los datos relativos a la clave de todas las cuentas.
+ */
+ protected abstract function getAccountsPassData();
+}
\ No newline at end of file
diff --git a/inc/AccountHistory.class.php b/inc/AccountHistory.class.php
new file mode 100644
index 00000000..428df54c
--- /dev/null
+++ b/inc/AccountHistory.class.php
@@ -0,0 +1,510 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+class AccountHistory extends AccountBase implements AccountInterface
+{
+ private $_isDelete = false;
+ private $_isModify = false;
+
+ /**
+ * Obtiene el listado del histórico de una cuenta.
+ *
+ * @return false|array Con los registros con id como clave y fecha - usuario como valor
+ */
+ public static function getAccountList($accountId)
+ {
+ $query = '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 = :id '
+ . 'ORDER BY acchistory_id DESC';
+
+ $data['id'] = $accountId;
+
+ DB::setReturnArray();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ $arrHistory = array();
+
+ foreach ($queryRes as $history) {
+ // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición)
+ if ($history->acchistory_dateEdit === null || $history->acchistory_dateEdit == '0000-00-00 00:00:00') {
+ $arrHistory[$history->acchistory_id] = $history->acchistory_dateAdd . ' - ' . $history->user_add;
+ } else {
+ $arrHistory[$history->acchistory_id] = $history->acchistory_dateEdit . ' - ' . $history->user_edit;
+ }
+ }
+
+ return $arrHistory;
+ }
+
+ /**
+ * @return boolean
+ */
+ public function isIsDelete()
+ {
+ return $this->_isDelete;
+ }
+
+ /**
+ * @param boolean $isDelete
+ */
+ public function setIsDelete($isDelete)
+ {
+ $this->_isDelete = $isDelete;
+ }
+
+ /**
+ * @return boolean
+ */
+ public function isIsModify()
+ {
+ return $this->_isModify;
+ }
+
+ /**
+ * @param boolean $isModify
+ */
+ public function setIsModify($isModify)
+ {
+ $this->_isModify = $isModify;
+ }
+
+ /**
+ * Actualiza las claves de todas las cuentas en el histórico con la nueva clave maestra.
+ *
+ * @param string $currentMasterPass con la clave maestra actual
+ * @param string $newMasterPass con la nueva clave maestra
+ * @param string $newHash con el nuevo hash de la clave maestra
+ * @return bool
+ */
+ public function updateAccountsMasterPass($currentMasterPass, $newMasterPass, $newHash = null)
+ {
+ $idOk = array();
+ $errorCount = 0;
+ $demoEnabled = Util::demoIsEnabled();
+
+ $message['action'] = _('Actualizar Clave Maestra (H)');
+ $message['text'][] = _('Inicio');
+
+ Log::wrLogInfo($message);
+
+ // Limpiar 'text' para los próximos mensajes
+ $message['text'] = array();
+
+ if (!Crypt::checkCryptModule()) {
+ $message['text'][] = _('Error en el módulo de encriptación');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ $accountsPass = $this->getAccountsPassData();
+
+ if (!$accountsPass) {
+ $message['text'][] = _('Error al obtener las claves de las cuentas');
+ Log::wrLogInfo($message);
+ return false;
+ }
+
+ foreach ($accountsPass as $account) {
+ $this->setAccountId($account->acchistory_id);
+
+ // No realizar cambios si está en modo demo
+ if ($demoEnabled) {
+ $idOk[] = $account->acchistory_id;
+ continue;
+ }
+
+ if (!$this->checkAccountMPass()) {
+ $errorCount++;
+ $message['text'][] = _('La clave maestra del registro no coincide') . ' (' . $account->acchistory_id . ')';
+ continue;
+ }
+
+ if (strlen($account->acchistory_IV) < 32) {
+ $message['text'][] = _('IV de encriptación incorrecto') . ' (' . $account->acchistory_id . ')';
+ continue;
+ }
+
+ $decryptedPass = Crypt::getDecrypt($account->acchistory_pass, $currentMasterPass, $account->acchistory_IV);
+ $this->setAccountPass(Crypt::mkEncrypt($decryptedPass, $newMasterPass));
+ $this->setAccountIV(Crypt::$strInitialVector);
+
+ if ($this->getAccountPass() === false) {
+ $errorCount++;
+ continue;
+ }
+
+ if (!$this->updateAccountPass($account->acchistory_id, $newHash)) {
+ $errorCount++;
+ $message['text'][] = _('Fallo al actualizar la clave del histórico') . ' (' . $account->acchistory_id . ')';
+ continue;
+ }
+
+ $idOk[] = $account->acchistory_id;
+ }
+
+ // Vaciar el array de mensaje de log
+ if (count($message['text']) > 0) {
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ if ($idOk) {
+ $message['text'][] = _('Registros actualizados') . ': ' . implode(',', $idOk);
+ Log::wrLogInfo($message);
+ $message['text'] = array();
+ }
+
+ $message['text'][] = _('Fin');
+ Log::wrLogInfo($message);
+
+ if ($errorCount > 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Obtener los datos relativos a la clave de todas las cuentas del histórico.
+ *
+ * @return false|array con los datos de la clave
+ */
+ protected function getAccountsPassData()
+ {
+ $query = 'SELECT acchistory_id, acchistory_pass, acchistory_IV FROM accHistory';
+
+ DB::setReturnArray();
+
+ return DB::getResults($query, __FUNCTION__);
+ }
+
+ /**
+ * Comprueba el hash de la clave maestra del registro de histórico de una cuenta.
+ *
+ * @param int $id opcional, con el Id del registro a comprobar
+ * @return bool
+ */
+ public function checkAccountMPass($id = null)
+ {
+ $query = 'SELECT acchistory_mPassHash ' .
+ 'FROM accHistory ' .
+ 'WHERE acchistory_id = :id ' .
+ 'AND acchistory_mPassHash = :mPassHash';
+
+ $data['id'] = (is_null($id)) ? $this->getAccountId() : $id;
+ $data['mPassHash'] = Config::getConfigDbValue('masterPwd');
+
+ return (DB::getResults($query, __FUNCTION__, $data) !== false);
+ }
+
+ /**
+ * Obtener los datos de una cuenta para mostrar la clave
+ * Esta funcion realiza la consulta a la BBDD y devuelve los datos.
+ *
+ * @return object|false
+ */
+ public function getAccountPassData()
+ {
+ $query = 'SELECT acchistory_name AS name,'
+ . 'acchistory_userId AS userId,'
+ . 'acchistory_userGroupId AS groupId,'
+ . 'acchistory_login AS login,'
+ . 'acchistory_pass AS pass,'
+ . 'acchistory_IV AS iv '
+ . 'FROM accHistory '
+ . 'WHERE acchistory_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ $this->setAccountUserId($queryRes->userId);
+ $this->setAccountUserGroupId($queryRes->groupId);
+ $this->setAccountPass($queryRes->pass);
+ $this->setAccountIV($queryRes->iv);
+
+ return $queryRes;
+ }
+
+ /**
+ * Actualiza la clave del histórico de una cuenta en la BBDD.
+ *
+ * @param int $id con el id del registro a actualizar
+ * @param string $newHash con el hash de la clave maestra
+ * @return bool
+ */
+ public function updateAccountPass($id, $newHash)
+ {
+ $query = 'UPDATE accHistory SET '
+ . 'acchistory_pass = :accountPass,'
+ . 'acchistory_IV = :accountIV,'
+ . 'acchistory_mPassHash = :newHash '
+ . 'WHERE acchistory_id = :id';
+
+ $data['accountPass'] = $this->getAccountPass();
+ $data['accountIV'] = $this->getAccountIV();
+ $data['newHash'] = $newHash;
+ $data['id'] = $id;
+
+ return DB::getQuery($query, __FUNCTION__, $data);
+ }
+
+ /**
+ * Obtener los datos del histórico de una cuenta.
+ * Esta funcion realiza la consulta a la BBDD y guarda los datos del histórico
+ * en las variables de la clase.
+ *
+ * @return object
+ * @throws Exception
+ */
+ public function getAccountData()
+ {
+ $query = '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_IV as account_IV,'
+ . '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,'
+ . '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 = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ throw new Exception(_('No se pudieron obtener los datos de la cuenta'));
+ }
+
+ $this->setAccountUserId($queryRes->account_userId);
+ $this->setAccountUserGroupId($queryRes->account_userGroupId);
+ $this->setAccountOtherUserEdit($queryRes->account_otherUserEdit);
+ $this->setAccountOtherGroupEdit($queryRes->account_otherGroupEdit);
+
+ return $queryRes;
+ }
+
+ /**
+ * Crear una cuenta en el historial
+ *
+ * @return bool
+ */
+ public function createAccount()
+ {
+ // FIXME: continuar
+
+ $query = 'INSERT INTO accHistory SET '
+ . 'acchistory_accountId = :account_id,'
+ . 'acchistory_customerId = :accountCustomerId,'
+ . 'acchistory_categoryId = :accountCategoryId,'
+ . 'acchistory_name = :accountName,'
+ . 'acchistory_login = :accountLogin,'
+ . 'acchistory_url = :accountUrl,'
+ . 'acchistory_pass = :accountPass,'
+ . 'acchistory_IV = :accountIV,'
+ . 'acchistory_notes = :accountNotes,'
+ . 'acchistory_dateAdd = :accountDateAdd,'
+ . 'acchistory_dateEdit = :accountDateEdit,'
+ . 'acchistory_countView = :accountCountView,'
+ . 'acchistory_countDecrypt = :accountCountDecrypt,'
+ . 'acchistory_userId = :accountUserId,'
+ . 'acchistory_userGroupId = :accountUserGroupId,'
+ . 'acchistory_otherUserEdit = :accountOtherUserEdit,'
+ . 'acchistory_otherGroupEdit = :accountOtherGroupEdit,'
+ . 'acchistory_isModify = :isModify,'
+ . 'acchistory_isDeleted = :isDelete,'
+ . 'acchistory_mPassHash = :masterPwd';
+
+ $data['account_id'] = $this->getAccountId();
+ $data['accountCustomerId'] = $this->getAccountCustomerId();
+ $data['accountCategoryId'] = $this->getAccountCategoryId();
+ $data['accountName'] = $this->getAccountName();
+ $data['accountLogin'] = $this->getAccountLogin();
+ $data['accountUrl'] = $this->getAccountUrl();
+ $data['accountPass'] = $this->getAccountPass();
+ $data['accountIV'] = $this->getAccountIV();
+ $data['accountNotes'] = $this->getAccountNotes();
+ $data['accountUserId'] = $this->getAccountUserId();
+ $data['accountUserGroupId'] = $this->getAccountUserGroupId();
+ $data['accountOtherUserEdit'] = $this->getAccountOtherUserEdit();
+ $data['accountOtherGroupEdit'] = $this->getAccountOtherGroupEdit();
+ $data['isModify'] = $this->isIsModify();
+ $data['isDelete'] = $this->isIsDelete();
+ $data['masterPwd'] = Config::getConfigDbValue('masterPwd');
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Eliminar una cuenta del historial
+ *
+ * @return bool
+ */
+ public function deleteAccount()
+ {
+ $query = 'DELETE FROM accHistory WHERE acchistory_id = :id LIMIT 1';
+
+ $data['id'] = $this->getAccountId();
+
+ if (DB::getQuery($query, __FUNCTION__, $data) === false) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Crear un nuevo registro de histório de cuenta en la BBDD.
+ *
+ * @param int $id el id de la cuenta primaria
+ * @param bool $isDelete indica que la cuenta es eliminada
+ * @return bool
+ */
+ public static function addHistory($id, $isDelete = false)
+ {
+ $query = 'INSERT INTO accHistory '
+ . '(acchistory_accountId,'
+ . 'acchistory_categoryId,'
+ . 'acchistory_customerId,'
+ . 'acchistory_name,'
+ . 'acchistory_login,'
+ . 'acchistory_url,'
+ . 'acchistory_pass,'
+ . 'acchistory_IV,'
+ . 'acchistory_notes,'
+ . 'acchistory_countView,'
+ . 'acchistory_countDecrypt,'
+ . 'acchistory_dateAdd,'
+ . 'acchistory_dateEdit,'
+ . 'acchistory_userId,'
+ . 'acchistory_userGroupId,'
+ . 'acchistory_userEditId,'
+ . 'acchistory_otherUserEdit,'
+ . 'acchistory_otherGroupEdit,'
+ . 'acchistory_isModify,'
+ . 'acchistory_isDeleted,'
+ . 'acchistory_mPassHash) '
+ . 'SELECT account_id,'
+ . 'account_categoryId,'
+ . 'account_customerId,'
+ . 'account_name,'
+ . 'account_login,'
+ . 'account_url,'
+ . 'account_pass,'
+ . 'account_IV,'
+ . 'account_notes,'
+ . 'account_countView,'
+ . 'account_countDecrypt,'
+ . 'account_dateAdd,'
+ . 'account_dateEdit,'
+ . 'account_userId,'
+ . 'account_userGroupId,'
+ . 'account_userEditId,'
+ . 'account_otherUserEdit,'
+ . 'account_otherGroupEdit,'
+ . ':isModify,'
+ . ':isDelete,'
+ . ':masterPwd '
+ . 'FROM accounts WHERE account_id = :account_id';
+
+ $data['account_id'] = $id;
+ $data['isModify'] = ($isDelete === false) ? 1 : 0;
+ $data['isDelete'] = ($isDelete === false) ? 0 : 1;
+ $data['masterPwd'] = Config::getConfigDbValue('masterPwd');
+
+ return DB::getQuery($query, __FUNCTION__, $data);
+ }
+
+ /**
+ * Obtener el Id padre de una cuenta en el histórico.
+ *
+ * @param $historyId int El id de la cuenta en el histórico
+ * @return int El id de la cuenta padre
+ * @throws SPException
+ */
+ public static function getAccountIdFromId($historyId)
+ {
+ $query = 'SELECT acchistory_accountId FROM accHistory WHERE acchistory_id = :id LIMIT 1';
+
+ $data['id'] = $historyId;
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ throw new SPException(SPException::SP_CRITICAL, _('No se pudieron obtener los datos de la cuenta'), 0);
+ }
+
+ return $queryRes->acchistory_accountId;
+ }
+}
\ No newline at end of file
diff --git a/inc/AccountInterface.class.php b/inc/AccountInterface.class.php
new file mode 100644
index 00000000..5877a215
--- /dev/null
+++ b/inc/AccountInterface.class.php
@@ -0,0 +1,42 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+/**
+ * Interface AccountInterface con la definición de métodos comunes a las cuentas
+ */
+interface AccountInterface
+{
+ public function getAccountData();
+
+ public function createAccount();
+
+ public function deleteAccount();
+
+ public function updateAccountsMasterPass($currentMasterPass, $newMasterPass, $newHash = null);
+}
\ No newline at end of file
diff --git a/inc/AccountSearch.class.php b/inc/AccountSearch.class.php
new file mode 100644
index 00000000..77bc8451
--- /dev/null
+++ b/inc/AccountSearch.class.php
@@ -0,0 +1,225 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+/**
+ * Class AccountSearch para la gestión de búsquedas de cuentas
+ */
+class AccountSearch
+{
+ /**
+ * @var int El número de registros de la última consulta
+ */
+ public static $queryNumRows;
+
+ /**
+ * Obtener las cuentas de una búsqueda.
+ *
+ * @param array $searchFilter Filtros de búsqueda
+ * @return bool Resultado de la consulta
+ */
+ public static function getAccounts($searchFilter)
+ {
+ $isAdmin = ($_SESSION['uisadminapp'] || $_SESSION['uisadminacc']);
+ $globalSearch = ($searchFilter['globalSearch'] === 1 && Config::getValue('globalsearch', 0));
+
+ $arrFilterCommon = array();
+ $arrFilterSelect = array();
+ $arrFilterUser = array();
+ $arrQueryWhere = array();
+
+ switch ($searchFilter['keyId']) {
+ case 1:
+ $orderKey = 'account_name';
+ break;
+ case 2:
+ $orderKey = 'category_name';
+ break;
+ case 3:
+ $orderKey = 'account_login';
+ break;
+ case 4:
+ $orderKey = 'account_url';
+ break;
+ case 5:
+ $orderKey = 'customer_name';
+ break;
+ default :
+ $orderKey = 'customer_name, account_name';
+ break;
+ }
+
+ $querySelect = 'SELECT DISTINCT '
+ . 'account_id,'
+ . 'account_customerId,'
+ . 'category_name,'
+ . 'account_name,'
+ . 'account_login,'
+ . 'account_url,'
+ . 'account_notes,'
+ . 'account_userId,'
+ . 'account_userGroupId,'
+ . 'BIN(account_otherUserEdit) AS account_otherUserEdit,'
+ . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,'
+ . 'usergroup_name,'
+ . 'customer_name '
+ . 'FROM accounts '
+ . 'LEFT JOIN categories ON account_categoryId = category_id '
+ . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
+ . 'LEFT JOIN customers ON customer_id = account_customerId '
+ . 'LEFT JOIN accUsers ON accuser_accountId = account_id '
+ . 'LEFT JOIN accGroups ON accgroup_accountId = account_id';
+
+ if ($searchFilter['txtSearch']) {
+ $arrFilterCommon[] = 'account_name LIKE :name';
+ $arrFilterCommon[] = 'account_login LIKE :login';
+ $arrFilterCommon[] = 'account_url LIKE :url';
+ $arrFilterCommon[] = 'account_notes LIKE :notes';
+
+ $data['name'] = '%' . $searchFilter['txtSearch'] . '%';
+ $data['login'] = '%' . $searchFilter['txtSearch'] . '%';
+ $data['url'] = '%' . $searchFilter['txtSearch'] . '%';
+ $data['notes'] = '%' . $searchFilter['txtSearch'] . '%';
+ }
+
+ if ($searchFilter['categoryId'] != 0) {
+ $arrFilterSelect[] = 'category_id = :categoryId';
+
+ $data['categoryId'] = $searchFilter['categoryId'];
+ }
+ if ($searchFilter['customerId'] != 0) {
+ $arrFilterSelect[] = 'account_customerId = :customerId';
+
+ $data['customerId'] = $searchFilter['customerId'];
+ }
+
+ if (count($arrFilterCommon) > 0) {
+ $arrQueryWhere[] = '(' . implode(' OR ', $arrFilterCommon) . ')';
+ }
+
+ if (count($arrFilterSelect) > 0) {
+ $arrQueryWhere[] = '(' . implode(' AND ', $arrFilterSelect) . ')';
+ }
+
+ if (!$isAdmin && !$globalSearch) {
+ $arrFilterUser[] = 'account_userGroupId = :userGroupId';
+ $arrFilterUser[] = 'account_userId = :userId';
+ $arrFilterUser[] = 'accgroup_groupId = :accgroup_groupId';
+ $arrFilterUser[] = 'accuser_userId = :accuser_userId';
+
+ $data['userGroupId'] = $searchFilter['groupId'];
+ $data['userId'] = $searchFilter['userId'];
+ $data['accgroup_groupId'] = $searchFilter['groupId'];
+ $data['accuser_userId'] = $searchFilter['userId'];
+
+ //$arrQueryWhere[] = '(' . implode(' OR ', $arrFilterUser) . ')';
+ $arrQueryWhere[] = implode(' OR ', $arrFilterUser);
+ }
+
+ $orderDir = ($searchFilter["txtOrder"] == 0) ? 'ASC' : 'DESC';
+ $queryOrder = 'ORDER BY ' . $orderKey . ' ' . $orderDir;
+
+ if ($searchFilter['limitCount'] != 99) {
+ $queryLimit = 'LIMIT :limitStart,:limitCount';
+
+ $data['limitStart'] = $searchFilter['limitStart'];
+ $data['limitCount'] = $searchFilter['limitCount'];
+ }
+
+ if (count($arrQueryWhere) === 1) {
+ $query = $querySelect . ' WHERE ' . implode($arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit;
+ } elseif (count($arrQueryWhere) > 1) {
+ $query = $querySelect . ' WHERE ' . implode(' AND ', $arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit;
+ } else {
+ $query = $querySelect . ' ' . $queryOrder . ' ' . $queryLimit;
+ }
+
+ // Obtener el número total de cuentas visibles por el usuario
+ DB::setFullRowCount();
+
+ // Obtener los resultados siempre en array de objetos
+ DB::setReturnArray();
+
+ // Consulta de la búsqueda de cuentas
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+// print_r($query);
+// var_dump($data);
+ return false;
+ }
+
+ // Obtenemos el número de registros totales de la consulta sin contar el LIMIT
+ self::$queryNumRows = DB::$last_num_rows;
+
+ $_SESSION["accountSearchTxt"] = $searchFilter["txtSearch"];
+ $_SESSION["accountSearchCustomer"] = $searchFilter["customerId"];
+ $_SESSION["accountSearchCategory"] = $searchFilter["categoryId"];
+ $_SESSION["accountSearchOrder"] = $searchFilter["txtOrder"];
+ $_SESSION["accountSearchKey"] = $searchFilter["keyId"];
+ $_SESSION["accountSearchStart"] = $searchFilter["limitStart"];
+ $_SESSION["accountSearchLimit"] = $searchFilter["limitCount"];
+ $_SESSION["accountGlobalSearch"] = $searchFilter["globalSearch"];
+
+ return $queryRes;
+ }
+
+ /**
+ * Obtiene el número de cuentas que un usuario puede ver.
+ *
+ * @return false|int con el número de registros
+ */
+ public function getAccountMax()
+ {
+ $data = null;
+
+ if (!Session::getUserIsAdminApp() && !Session::getUserIsAdminAcc()) {
+ $query = 'SELECT COUNT(DISTINCT account_id) as numacc '
+ . 'FROM accounts '
+ . 'LEFT JOIN accGroups ON account_id = accgroup_accountId '
+ . 'WHERE account_userGroupId = :userGroupId '
+ . 'OR account_userId = :userId '
+ . 'OR accgroup_groupId = :groupId';
+
+ $data['userGroupId'] = Session::getUserGroupId();
+ $data['groupId'] = Session::getUserGroupId();
+ $data['userId'] = Session::getUserId();
+
+ } else {
+ $query = "SELECT COUNT(*) as numacc FROM accounts";
+ }
+
+ $queryRes = DB::getResults($query, __FUNCTION__, $data);
+
+ if ($queryRes === false) {
+ return false;
+ }
+
+ return $queryRes->numacc;
+ }
+}
\ No newline at end of file
diff --git a/inc/Accounts.class.php b/inc/Accounts.class.php
deleted file mode 100644
index 7d2b9d93..00000000
--- a/inc/Accounts.class.php
+++ /dev/null
@@ -1,1314 +0,0 @@
-.
- *
- */
-
-defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
-
-/**
- * Esta clase es la encargada de realizar las operaciones sobre las cuentas de sysPass.
- */
-class SP_Accounts
-{
- static $queryNumRows;
- var $accountId;
- var $accountParentId;
- var $accountUserId;
- var $accountUsersId;
- var $accountUserGroupId;
- var $accountUserGroupsId;
- var $accountUserEditId;
- var $accountName;
- var $accountCustomerId;
- var $accountCategoryId;
- var $accountLogin;
- var $accountUrl;
- var $accountPass;
- var $accountIV;
- var $accountNotes;
- var $accountOtherUserEdit;
- var $accountOtherGroupEdit;
- var $accountModHash;
- var $lastAction;
- var $lastId; // Variable de consulta
- var $query;
- var $accountIsHistory = 0; // Variable para indicar si la cuenta es desde el histórico
- var $accountCacheUserGroupsId; // Cache para grupos de usuarios de las cuentas
- var $accountCacheUsersId; // Cache para usuarios de las cuentas
-
- // Variable para la caché de parámetros
- var $cacheParams;
-
- /**
- * Constructor
- *
- * @param int $id con el Id de la cuenta a obtener
- * @param string $lastAction con la accion anterior
- */
- public function __construct($id = null, $lastAction = null)
- {
- if (!is_null($id)) {
- $this->accountId = $id;
- $this->lastAction = $lastAction;
- }
- }
-
- /**
- * Obtener los datos de usuario y modificador de una cuenta.
- *
- * @param int $accountId con el Id de la cuenta
- * @return false|object con el id de usuario y modificador.
- */
- public static function getAccountRequestData($accountId)
- {
- $query = 'SELECT account_userId,'
- . 'account_userEditId,'
- . 'account_name,'
- . 'customer_name '
- . 'FROM accounts '
- . 'LEFT JOIN customers ON account_customerId = customer_id '
- . 'WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- return $queryRes;
- }
-
- /**
- * Obtiene el listado con el nombre de los usuaios de una cuenta.
- *
- * @param int $accountId con el Id de la cuenta
- * @return false|array con los nombres de los usuarios ordenados
- */
- public static function getAccountUsersName($accountId)
- {
- $query = 'SELECT user_name '
- . 'FROM accUsers '
- . 'JOIN usrData ON accuser_userId = user_id '
- . 'WHERE accuser_accountId = :id';
-
- $data['id'] = $accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- if (!is_array($queryRes)) {
- return false;
- }
-
- foreach ($queryRes as $users) {
- $usersName[] = $users->user_name;
- }
-
- sort($usersName, SORT_STRING);
-
- return $usersName;
- }
-
- /**
- * Obtener las cuentas de una búsqueda.
- *
- * @param array $searchFilter Filtros de búsqueda
- * @return bool Resultado de la consulta
- */
- public static function getAccounts($searchFilter)
- {
- $isAdmin = ($_SESSION['uisadminapp'] || $_SESSION['uisadminacc']);
- $globalSearch = ($searchFilter['globalSearch'] === 1 && SP_Config::getValue('globalsearch', 0));
-
- $arrFilterCommon = array();
- $arrFilterSelect = array();
- $arrFilterUser = array();
- $arrQueryWhere = array();
-
- switch ($searchFilter['keyId']) {
- case 1:
- $orderKey = 'account_name';
- break;
- case 2:
- $orderKey = 'category_name';
- break;
- case 3:
- $orderKey = 'account_login';
- break;
- case 4:
- $orderKey = 'account_url';
- break;
- case 5:
- $orderKey = 'customer_name';
- break;
- default :
- $orderKey = 'customer_name, account_name';
- break;
- }
-
- $querySelect = 'SELECT DISTINCT '
- . 'account_id,'
- . 'account_customerId,'
- . 'category_name,'
- . 'account_name,'
- . 'account_login,'
- . 'account_url,'
- . 'account_notes,'
- . 'account_userId,'
- . 'account_userGroupId,'
- . 'BIN(account_otherUserEdit) AS account_otherUserEdit,'
- . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,'
- . 'usergroup_name,'
- . 'customer_name '
- . 'FROM accounts '
- . 'LEFT JOIN categories ON account_categoryId = category_id '
- . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
- . 'LEFT JOIN customers ON customer_id = account_customerId '
- . 'LEFT JOIN accUsers ON accuser_accountId = account_id '
- . 'LEFT JOIN accGroups ON accgroup_accountId = account_id';
-
- if ($searchFilter['txtSearch']) {
- $arrFilterCommon[] = 'account_name LIKE :name';
- $arrFilterCommon[] = 'account_login LIKE :login';
- $arrFilterCommon[] = 'account_url LIKE :url';
- $arrFilterCommon[] = 'account_notes LIKE :notes';
-
- $data['name'] = '%' . $searchFilter['txtSearch'] . '%';
- $data['login'] = '%' . $searchFilter['txtSearch'] . '%';
- $data['url'] = '%' . $searchFilter['txtSearch'] . '%';
- $data['notes'] = '%' . $searchFilter['txtSearch'] . '%';
- }
-
- if ($searchFilter['categoryId'] != 0) {
- $arrFilterSelect[] = 'category_id = :categoryId';
-
- $data['categoryId'] = $searchFilter['categoryId'];
- }
- if ($searchFilter['customerId'] != 0) {
- $arrFilterSelect[] = 'account_customerId = :customerId';
-
- $data['customerId'] = $searchFilter['customerId'];
- }
-
- if (count($arrFilterCommon) > 0) {
- $arrQueryWhere[] = '(' . implode(' OR ', $arrFilterCommon) . ')';
- }
-
- if (count($arrFilterSelect) > 0) {
- $arrQueryWhere[] = '(' . implode(' AND ', $arrFilterSelect) . ')';
- }
-
- if (!$isAdmin && !$globalSearch) {
- $arrFilterUser[] = 'account_userGroupId = :userGroupId';
- $arrFilterUser[] = 'account_userId = :userId';
- $arrFilterUser[] = 'accgroup_groupId = :accgroup_groupId';
- $arrFilterUser[] = 'accuser_userId = :accuser_userId';
-
- $data['userGroupId'] = $searchFilter['groupId'];
- $data['userId'] = $searchFilter['userId'];
- $data['accgroup_groupId'] = $searchFilter['groupId'];
- $data['accuser_userId'] = $searchFilter['userId'];
-
- //$arrQueryWhere[] = '(' . implode(' OR ', $arrFilterUser) . ')';
- $arrQueryWhere[] = implode(' OR ', $arrFilterUser);
- }
-
- $orderDir = ($searchFilter["txtOrder"] == 0) ? 'ASC' : 'DESC';
- $queryOrder = 'ORDER BY ' . $orderKey . ' ' . $orderDir;
-
- if ($searchFilter['limitCount'] != 99) {
- $queryLimit = 'LIMIT :limitStart,:limitCount';
-
- $data['limitStart'] = $searchFilter['limitStart'];
- $data['limitCount'] = $searchFilter['limitCount'];
- }
-
- if (count($arrQueryWhere) === 1) {
- $query = $querySelect . ' WHERE ' . implode($arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit;
- } elseif (count($arrQueryWhere) > 1) {
- $query = $querySelect . ' WHERE ' . implode(' AND ', $arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit;
- } else {
- $query = $querySelect . ' ' . $queryOrder . ' ' . $queryLimit;
- }
-
-// $this->query = $query;
-
- // Obtener el número total de cuentas visibles por el usuario
- DB::setFullRowCount();
-
- // Obtener los resultados siempre en array de objetos
- DB::setReturnArray();
-
- // Consulta de la búsqueda de cuentas
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
-// print_r($query);
-// var_dump($data);
- return false;
- }
-
-
- // Obtenemos el número de registros totales de la consulta sin contar el LIMIT
- self::$queryNumRows = DB::$last_num_rows;
-
- $_SESSION["accountSearchTxt"] = $searchFilter["txtSearch"];
- $_SESSION["accountSearchCustomer"] = $searchFilter["customerId"];
- $_SESSION["accountSearchCategory"] = $searchFilter["categoryId"];
- $_SESSION["accountSearchOrder"] = $searchFilter["txtOrder"];
- $_SESSION["accountSearchKey"] = $searchFilter["keyId"];
- $_SESSION["accountSearchStart"] = $searchFilter["limitStart"];
- $_SESSION["accountSearchLimit"] = $searchFilter["limitCount"];
- $_SESSION["accountGlobalSearch"] = $searchFilter["globalSearch"];
-
- return $queryRes;
- }
-
- /**
- * Obtener los datos del histórico de una cuenta.
- * Esta funcion realiza la consulta a la BBDD y guarda los datos del histórico
- * en las variables de la clase.
- *
- * @return object
- * @throws Exception
- */
- public function getAccountHistory()
- {
- $query = '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_IV as account_IV,'
- . '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,'
- . '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 = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- throw new Exception(_('No se pudieron obtener los datos de la cuenta'));
-// return false;
- }
-
- $this->accountUserId = $queryRes->account_userId;
- $this->accountUserGroupId = $queryRes->account_userGroupId;
- $this->accountOtherUserEdit = $queryRes->account_otherUserEdit;
- $this->accountOtherGroupEdit = $queryRes->account_otherGroupEdit;
-
- return $queryRes;
- }
-
- /**
- * Actualiza los datos de una cuenta en la BBDD.
- *
- * @param bool $isRestore si es una restauración de cuenta
- * @return bool
- */
- public function updateAccount($isRestore = false)
- {
- $message['action'] = __FUNCTION__;
-
- // Guardamos una copia de la cuenta en el histórico
- if (!$this->addHistory($this->accountId, $this->accountUserEditId, false)) {
- $message['text'][] = _('Error al actualizar el historial');
- SP_Log::wrLogInfo($message);
- return false;
- }
-
- if (!$isRestore) {
- $message['action'] = _('Actualizar Cuenta');
-
- if (!SP_Groups::updateGroupsForAccount($this->accountId, $this->accountUserGroupsId)) {
- $message['text'][] = _('Error al actualizar los grupos secundarios');
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
-
- if (!SP_Users::updateUsersForAccount($this->accountId, $this->accountUsersId)) {
- $message['text'][] = _('Error al actualizar los usuarios de la cuenta');
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
- } else {
- $message['action'] = _('Restaurar Cuenta');
- }
-
- $query = 'UPDATE accounts SET '
- . 'account_customerId = :accountCustomerId,'
- . 'account_categoryId = :accountCategoryId,'
- . 'account_name = :accountName,'
- . 'account_login = :accountLogin,'
- . 'account_url = :accountUrl,'
- . 'account_notes = :accountNotes,'
- . 'account_userEditId = :accountUserEditId,'
- . 'account_dateEdit = NOW(),'
- . 'account_otherUserEdit = :accountOtherUserEdit,'
- . 'account_otherGroupEdit = :accountOtherGroupEdit '
- . 'WHERE account_id = :accountId';
-
- $data['accountCustomerId'] = $this->accountCustomerId;
- $data['accountCategoryId'] = $this->accountCategoryId;
- $data['accountName'] = $this->accountName;
- $data['accountLogin'] = $this->accountLogin;
- $data['accountUrl'] = $this->accountUrl;
- $data['accountNotes'] = $this->accountNotes;
- $data['accountUserEditId'] = $this->accountUserEditId;
- $data['accountOtherUserEdit'] = intval($this->accountOtherUserEdit);
- $data['accountOtherGroupEdit'] = intval($this->accountOtherGroupEdit);
- $data['accountId'] = $this->accountId;
-
- if (DB::getQuery($query, __FUNCTION__, $data) === false) {
- return false;
- }
-
- $accountInfo = array('customer_name');
- $this->getAccountInfoById($accountInfo);
-
- $message['action'] = _('Cuenta actualizada');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name'];
- $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . "$this->accountName ($this->accountId)";
-
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
-
- return true;
- }
-
- /**
- * Crear un nuevo registro de histório de cuenta en la BBDD.
- *
- * @param bool $isDelete indica que la cuenta es eliminada
- * @return bool
- */
- private function addHistory($isDelete = false)
- {
- $query = 'INSERT INTO accHistory '
- . '(acchistory_accountId,'
- . 'acchistory_categoryId,'
- . 'acchistory_customerId,'
- . 'acchistory_name,'
- . 'acchistory_login,'
- . 'acchistory_url,'
- . 'acchistory_pass,'
- . 'acchistory_IV,'
- . 'acchistory_notes,'
- . 'acchistory_countView,'
- . 'acchistory_countDecrypt,'
- . 'acchistory_dateAdd,'
- . 'acchistory_dateEdit,'
- . 'acchistory_userId,'
- . 'acchistory_userGroupId,'
- . 'acchistory_userEditId,'
- . 'acchistory_otherUserEdit,'
- . 'acchistory_otherGroupEdit,'
- . 'acchistory_isModify,'
- . 'acchistory_isDeleted,'
- . 'acchistory_mPassHash) '
- . 'SELECT account_id,'
- . 'account_categoryId,'
- . 'account_customerId,'
- . 'account_name,'
- . 'account_login,'
- . 'account_url,'
- . 'account_pass,'
- . 'account_IV,'
- . 'account_notes,'
- . 'account_countView,'
- . 'account_countDecrypt,'
- . 'account_dateAdd,'
- . 'account_dateEdit,'
- . 'account_userId,'
- . 'account_userGroupId,'
- . 'account_userEditId,'
- . 'account_otherUserEdit,'
- . 'account_otherGroupEdit,'
- . ':isModify,'
- . ':isDelete,'
- . ':masterPwd '
- . 'FROM accounts WHERE account_id = :account_id';
-
- $data['account_id'] = $this->accountId;
- $data['isModify'] = ($isDelete === false) ? 1 : 0;
- $data['isDelete'] = ($isDelete === false) ? 0 : 1;
- $data['masterPwd'] = SP_Config::getConfigDbValue('masterPwd');
-
- return DB::getQuery($query, __FUNCTION__, $data);
- }
-
- /**
- * Obtener los datos de una cuenta con el id.
- * Se guardan los datos en la variable $cacheParams de la clase para consultarlos
- * posteriormente.
- *
- * @param array $params con los campos de la BBDD a obtener
- * @return bool
- */
- private function getAccountInfoById($params)
- {
- if (!is_array($params)) {
- return false;
- }
-
- if (is_array($this->cacheParams)) {
- $cache = true;
-
- foreach ($params as $param) {
- if (!array_key_exists($param, $this->cacheParams)) {
- $cache = false;
- }
- }
-
- if ($cache) {
- return true;
- }
- }
-
- $query = 'SELECT ' . implode(',', $params) . ' '
- . 'FROM accounts '
- . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
- . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id '
- . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id '
- . 'LEFT JOIN customers ON account_customerId = customer_id '
- . 'WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- foreach ($queryRes as $param => $value) {
- $this->cacheParams[$param] = $value;
- }
-
- return true;
- }
-
- /**
- * Obtener los datos de una cuenta para mostrar la clave
- * Esta funcion realiza la consulta a la BBDD y devuelve los datos.
- *
- * @return object|false
- */
- public function getAccountPass($isHistory = false)
- {
- if (!$isHistory) {
- $query = 'SELECT account_name AS name,'
- . 'account_userId AS userId,'
- . 'account_userGroupId AS groupId,'
- . 'account_login AS login,'
- . 'account_pass AS pass,'
- . 'account_IV AS iv,'
- . 'customer_name '
- . 'FROM accounts '
- . 'LEFT JOIN customers ON account_customerId = customer_id '
- . 'WHERE account_id = :id LIMIT 1';
- } else {
- $query = 'SELECT acchistory_name AS name,'
- . 'acchistory_userId AS userId,'
- . 'acchistory_userGroupId AS groupId,'
- . 'acchistory_login AS login,'
- . 'acchistory_pass AS pass,'
- . 'acchistory_IV AS iv,'
- . 'customer_name '
- . 'FROM accHistory '
- . 'LEFT JOIN customers ON acchistory_customerId = customer_id '
- . 'WHERE acchistory_id = :id LIMIT 1';
- }
-
- $data['id'] = $this->accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- $this->accountUserId = $queryRes->userId;
- $this->accountUserGroupId = $queryRes->groupId;
- $this->accountPass = $queryRes->pass;
- $this->accountIV = $queryRes->iv;
-
- return $queryRes;
- }
-
- /**
- * Obtener los datos de una cuenta.
- * Esta funcion realiza la consulta a la BBDD y guarda los datos en las variables de la clase.
- *
- * @return object
- * @throws Exception
- */
- public function getAccount()
- {
- $query = 'SELECT account_id,'
- . 'account_name,'
- . 'account_categoryId,'
- . 'account_userId,'
- . 'account_customerId,'
- . 'account_userGroupId,'
- . 'account_userEditId,'
- . 'category_name,'
- . 'account_login,'
- . 'account_url,'
- . 'account_pass,'
- . 'account_IV,'
- . 'account_notes,'
- . 'account_countView,'
- . 'account_countDecrypt,'
- . 'account_dateAdd,'
- . 'account_dateEdit,'
- . 'BIN(account_otherUserEdit) AS account_otherUserEdit,'
- . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,'
- . 'u1.user_name,'
- . 'u1.user_login,'
- . 'u2.user_name as user_editName,'
- . 'u2.user_login as user_editLogin,'
- . 'usergroup_name,'
- . 'customer_name, '
- . 'CONCAT(account_name,account_categoryId,account_customerId,account_login,account_url,account_notes,BIN(account_otherUserEdit),BIN(account_otherGroupEdit)) as modHash '
- . 'FROM accounts '
- . 'LEFT JOIN categories ON account_categoryId = category_id '
- . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id '
- . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id '
- . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id '
- . 'LEFT JOIN customers ON account_customerId = customer_id '
- . 'WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- throw new Exception(_('No se pudieron obtener los datos de la cuenta'));
-// return false;
- }
-
- $this->accountUserId = $queryRes->account_userId;
- $this->accountUserGroupId = $queryRes->account_userGroupId;
- $this->accountOtherUserEdit = $queryRes->account_otherUserEdit;
- $this->accountOtherGroupEdit = $queryRes->account_otherGroupEdit;
- $this->accountModHash = $queryRes->modHash;
-
- return $queryRes;
- }
-
- /**
- * Crea una nueva cuenta en la BBDD
- *
- * @return bool
- */
- public function createAccount()
- {
- $query = 'INSERT INTO accounts SET '
- . 'account_customerId = :accountCustomerId,'
- . 'account_categoryId = :accountCategoryId,'
- . 'account_name = :accountName,'
- . 'account_login = :accountLogin,'
- . 'account_url = :accountUrl,'
- . 'account_pass = :accountPass,'
- . 'account_IV = :accountIV,'
- . 'account_notes = :accountNotes,'
- . 'account_dateAdd = NOW(),'
- . 'account_userId = :accountUserId,'
- . 'account_userGroupId = :accountUserGroupId,'
- . 'account_otherUserEdit = :accountOtherUserEdit,'
- . 'account_otherGroupEdit = :accountOtherGroupEdit';
-
- $data['accountCustomerId'] = $this->accountCustomerId;
- $data['accountCategoryId'] = $this->accountCategoryId;
- $data['accountName'] = $this->accountName;
- $data['accountLogin'] = $this->accountLogin;
- $data['accountUrl'] = $this->accountUrl;
- $data['accountPass'] = $this->accountPass;
- $data['accountIV'] = $this->accountIV;
- $data['accountNotes'] = $this->accountNotes;
- $data['accountUserId'] = $this->accountUserId;
- $data['accountUserGroupId'] = $this->accountUserGroupId;
- $data['accountOtherUserEdit'] = $this->accountOtherUserEdit;
- $data['accountOtherGroupEdit'] = $this->accountOtherGroupEdit;
-
- if (DB::getQuery($query, __FUNCTION__, $data) === false) {
- return false;
- }
-
- $this->accountId = DB::$lastId;
-
- $message['action'] = __FUNCTION__;
-
- if (is_array($this->accountUserGroupsId)) {
- if (!SP_Groups::addGroupsForAccount($this->accountId, $this->accountUserGroupsId)) {
- $message['text'][] = _('Error al actualizar los grupos secundarios');
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
- }
-
- if (is_array($this->accountUsersId)) {
- if (!SP_Users::addUsersForAccount($this->accountId, $this->accountUsersId)) {
- $message['text'][] = _('Error al actualizar los usuarios de la cuenta');
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
- }
-
- $accountInfo = array('customer_name');
- $this->getAccountInfoById($accountInfo);
-
- $message['action'] = _('Nueva Cuenta');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name'];
- $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . "$this->accountName ($this->accountId)";
-
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
-
- return true;
- }
-
- /**
- * Elimina los datos de una cuenta en la BBDD.
- *
- * @return bool
- */
- public function deleteAccount()
- {
- // Guardamos una copia de la cuenta en el histórico
- $this->addHistory(true) || die (_('ERROR: Error en la operación.'));
-
- $accountInfo = array('account_name,customer_name');
- $this->getAccountInfoById($accountInfo);
-
- $message['action'] = _('Eliminar Cuenta');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name'];
- $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $this->cacheParams['account_name'] . " ($this->accountId)";
-
- $query = 'DELETE FROM accounts WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- if (DB::getQuery($query, __FUNCTION__, $data) === false) {
- return false;
- }
-
- if (!SP_Groups::deleteGroupsForAccount($this->accountId)) {
- $message['text'][] = _('Error al eliminar grupos asociados a la cuenta');
- }
-
- if (!SP_Users::deleteUsersForAccount($this->accountId)) {
- $message['text'][] = _('Error al eliminar usuarios asociados a la cuenta');
- }
-
- if (!SP_Files::deleteAccountFiles($this->accountId)) {
- $message['text'][] = _('Error al eliminar archivos asociados a la cuenta');
- }
-
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
-
- return true;
- }
-
- /**
- * Obtiene el listado del histórico de una cuenta.
- *
- * @return false|array Con los registros con id como clave y fecha - usuario como valor
- */
- public function getAccountHistoryList()
- {
- $query = '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 = :id '
- . 'ORDER BY acchistory_id DESC';
-
- $data['id'] = $_SESSION["accParentId"];
-
- DB::setReturnArray();
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- $arrHistory = array();
-
- foreach ($queryRes as $history) {
- // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición)
- if ($history->acchistory_dateEdit === null || $history->acchistory_dateEdit == '0000-00-00 00:00:00') {
- $arrHistory[$history->acchistory_id] = $history->acchistory_dateAdd . ' - ' . $history->user_add;
- } else {
- $arrHistory[$history->acchistory_id] = $history->acchistory_dateEdit . ' - ' . $history->user_edit;
- }
- }
-
- return $arrHistory;
- }
-
- /**
- * Incrementa el contador de visitas de una cuenta en la BBDD
- *
- * @return bool
- */
- public function incrementViewCounter()
- {
- $query = 'UPDATE accounts SET account_countView = (account_countView + 1) WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- return DB::getQuery($query, __FUNCTION__, $data);
- }
-
- /**
- * Incrementa el contador de vista de clave de una cuenta en la BBDD
- *
- * @return bool
- */
- public function incrementDecryptCounter()
- {
- $query = 'UPDATE accounts SET account_countDecrypt = (account_countDecrypt + 1) WHERE account_id = :id LIMIT 1';
-
- $data['id'] = $this->accountId;
-
- return DB::getQuery($query, __FUNCTION__, $data);
- }
-
- /**
- * Obtiene el número de cuentas que un usuario puede ver.
- *
- * @return false|int con el número de registros
- */
- public function getAccountMax()
- {
- $userGroupId = $_SESSION["ugroup"];
- $userId = $_SESSION["uid"];
- $userIsAdminApp = $_SESSION['uisadminapp'];
- $userIsAdminAcc = $_SESSION['uisadminacc'];
-
- $data = null;
-
- if (!$userIsAdminApp && !$userIsAdminAcc) {
- $query = 'SELECT COUNT(DISTINCT account_id) as numacc '
- . 'FROM accounts '
- . 'LEFT JOIN accGroups ON account_id = accgroup_accountId '
- . 'WHERE account_userGroupId = :userGroupId '
- . 'OR account_userId = :userId '
- . 'OR accgroup_groupId = :groupId';
-
- $data['userGroupId'] = $userGroupId;
- $data['groupId'] = $userGroupId;
- $data['userId'] = $userId;
-
- } else {
- $query = "SELECT COUNT(*) as numacc FROM accounts";
- }
-
- $queryRes = DB::getResults($query, __FUNCTION__, $data);
-
- if ($queryRes === false) {
- return false;
- }
-
- return $queryRes->numacc;
- }
-
- /**
- * Actualiza las claves de todas las cuentas con la nueva clave maestra.
- *
- * @param string $currentMasterPass con la clave maestra actual
- * @param string $newMasterPass con la nueva clave maestra
- * @return bool
- */
- public function updateAllAccountsMPass($currentMasterPass, $newMasterPass)
- {
- $accountsOk = array();
- $userId = $_SESSION['uid'];
- $errorCount = 0;
- $demoEnabled = SP_Util::demoIsEnabled();
-
- $message['action'] = _('Actualizar Clave Maestra');
- $message['text'][] = _('Inicio');
-
- SP_Log::wrLogInfo($message);
-
- // Limpiar 'text' para los próximos mensajes
- $message['text'] = array();
-
- if (!SP_Crypt::checkCryptModule()) {
- $message['text'][] = _('Error en el módulo de encriptación');
- SP_Log::wrLogInfo($message);
- return false;
- }
-
- $accountsPass = $this->getAccountsPassData();
-
- if (!$accountsPass) {
- $message['text'][] = _('Error al obtener las claves de las cuentas');
- SP_Log::wrLogInfo($message);
- return false;
- }
-
- foreach ($accountsPass as $account) {
- $this->accountId = $account->account_id;
- $this->accountUserEditId = $userId;
-
- // No realizar cambios si está en modo demo
- if ($demoEnabled) {
- $accountsOk[] = $this->accountId;
- continue;
- }
-
- if (strlen($account->account_IV) < 32) {
- $errorCount++;
- $message['text'][] = _('IV de encriptación incorrecto') . " (" . $account->account_id . ")";
- continue;
- }
-
- $decryptedPass = SP_Crypt::getDecrypt($account->account_pass, $currentMasterPass, $account->account_IV);
- $this->accountPass = SP_Crypt::mkEncrypt($decryptedPass, $newMasterPass);
- $this->accountIV = SP_Crypt::$strInitialVector;
-
- if ($this->accountPass === false) {
- $errorCount++;
- continue;
- }
-
- if (!$this->updateAccountPass(true)) {
- $errorCount++;
- $message['text'][] = _('Fallo al actualizar la clave de la cuenta') . '(' . $this->accountId . ')';
- continue;
- }
-
- $accountsOk[] = $this->accountId;
- }
-
- // Vaciar el array de mensaje de log
- if (count($message['text']) > 0) {
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
-
- if ($accountsOk) {
- $message['text'][] = _('Cuentas actualizadas') . ': ' . implode(',', $accountsOk);
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
-
- $message['text'][] = _('Fin');
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
-
- if ($errorCount > 0) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Obtener los datos relativos a la clave de todas las cuentas.
- *
- * @return false|array Con los datos de la clave
- */
- private function getAccountsPassData()
- {
- $query = 'SELECT account_id, account_pass, account_IV FROM accounts';
-
- return DB::getResults($query, __FUNCTION__);
- }
-
- /**
- * Actualiza la clave de una cuenta en la BBDD.
- *
- * @param bool $isMassive para no actualizar el histórico ni enviar mensajes
- * @param bool $isRestore indica si es una restauración
- * @return bool
- */
- public function updateAccountPass($isMassive = false, $isRestore = false)
- {
- $message['action'] = __FUNCTION__;
-
- // No actualizar el histórico si es por cambio de clave maestra o restauración
- if (!$isMassive && !$isRestore) {
- // Guardamos una copia de la cuenta en el histórico
- if (!$this->addHistory($this->accountId, $this->accountUserEditId, false)) {
- $message['text'][] = _('Error al actualizar el historial');
- SP_Log::wrLogInfo($message);
- return false;
- }
- }
-
- $query = 'UPDATE accounts SET '
- . 'account_pass = :accountPass,'
- . 'account_IV = :accountIV,'
- . 'account_userEditId = :accountUserEditId,'
- . 'account_dateEdit = NOW() '
- . 'WHERE account_id = :accountId';
-
- $data['accountPass'] = $this->accountPass;
- $data['accountIV'] = $this->accountIV;
- $data['accountUserEditId'] = $this->accountUserEditId;
- $data['accountId'] = $this->accountId;
-
-
- if (DB::getQuery($query, __FUNCTION__, $data) === false) {
- return false;
- }
-
- // No escribir en el log ni enviar correos si la actualización es
- // por cambio de clave maestra o restauración
- if (!$isMassive && !$isRestore) {
- $accountInfo = array('customer_name', 'account_name');
- $this->getAccountInfoById($accountInfo);
-
- $message['action'] = _('Modificar Clave');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name'];
- $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $this->cacheParams['account_name'] . " ($this->accountId)";
-
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
- }
-
- return true;
- }
-
- /**
- * Actualiza las claves de todas las cuentas en el histórico con la nueva clave maestra.
- *
- * @param string $currentMasterPass con la clave maestra actual
- * @param string $newMasterPass con la nueva clave maestra
- * @param string $newHash con el nuevo hash de la clave maestra
- * @return bool
- */
- public function updateAllAccountsHistoryMPass($currentMasterPass, $newMasterPass, $newHash)
- {
- $idOk = array();
- $errorCount = 0;
- $demoEnabled = SP_Util::demoIsEnabled();
-
- $message['action'] = _('Actualizar Clave Maestra (H)');
- $message['text'][] = _('Inicio');
-
- SP_Log::wrLogInfo($message);
-
- // Limpiar 'text' para los próximos mensajes
- $message['text'] = array();
-
- if (!SP_Crypt::checkCryptModule()) {
- $message['text'][] = _('Error en el módulo de encriptación');
- SP_Log::wrLogInfo($message);
- return false;
- }
-
- $accountsPass = $this->getAccountsHistoryPassData();
-
- if (!$accountsPass) {
- $message['text'][] = _('Error al obtener las claves de las cuentas');
- SP_Log::wrLogInfo($message);
- return false;
- }
-
- foreach ($accountsPass as $account) {
- // No realizar cambios si está en modo demo
- if ($demoEnabled) {
- $idOk[] = $account->acchistory_id;
- continue;
- }
-
- if (!$this->checkAccountMPass($account->acchistory_id)) {
- $errorCount++;
- $message['text'][] = _('La clave maestra del registro no coincide') . ' (' . $account->acchistory_id . ')';
- continue;
- }
-
- if (strlen($account->acchistory_IV) < 32) {
- $errorCount++;
- $message['text'][] = _('IV de encriptación incorrecto') . ' (' . $account->acchistory_id . ')';
- continue;
- }
-
- $decryptedPass = SP_Crypt::getDecrypt($account->acchistory_pass, $currentMasterPass, $account->acchistory_IV);
-
- $this->accountPass = SP_Crypt::mkEncrypt($decryptedPass, $newMasterPass);
- $this->accountIV = SP_Crypt::$strInitialVector;
-
- if ($this->accountPass === false) {
- $errorCount++;
- continue;
- }
-
- if (!$this->updateAccountHistoryPass($account->acchistory_id, $newHash)) {
- $errorCount++;
- $message['text'][] = _('Fallo al actualizar la clave del histórico') . ' (' . $account->acchistory_id . ')';
- continue;
- }
-
- $idOk[] = $account->acchistory_id;
- }
-
- // Vaciar el array de mensaje de log
- if (count($message['text']) > 0) {
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
-
- if ($idOk) {
- $message['text'][] = _('Registros actualizados') . ': ' . implode(',', $idOk);
- SP_Log::wrLogInfo($message);
- $message['text'] = array();
- }
-
- $message['text'][] = _('Fin');
- SP_Log::wrLogInfo($message);
-
- if ($errorCount > 0) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Obtener los datos relativo a la clave de todas las cuentas del histórico.
- *
- * @return false|array con los datos de la clave
- */
- private function getAccountsHistoryPassData()
- {
- $query = 'SELECT acchistory_id, acchistory_pass, acchistory_IV FROM accHistory';
-
- DB::setReturnArray();
-
- return DB::getResults($query, __FUNCTION__);
- }
-
- /**
- * Comprueba el hash de la clave maestra del registro de histórico de una cuenta.
- *
- * @param int $id opcional, con el Id del registro a comprobar
- * @return bool
- */
- public function checkAccountMPass($id = null)
- {
- $query = 'SELECT acchistory_mPassHash ' .
- 'FROM accHistory ' .
- 'WHERE acchistory_id = :id AND acchistory_mPassHash = :mPassHash';
-
- $data['id'] = (is_null($id)) ? $this->accountId : $id;
- $data['mPassHash'] = SP_Config::getConfigDbValue('masterPwd');
-
- return (DB::getResults($query, __FUNCTION__, $data) !== false);
- }
-
- /**
- * Actualiza la clave del histórico de una cuenta en la BBDD.
- *
- * @param int $id con el id del registro a actualizar
- * @param string $newHash con el hash de la clave maestra
- * @return bool
- */
- public function updateAccountHistoryPass($id, $newHash)
- {
- $query = 'UPDATE accHistory SET '
- . 'acchistory_pass = :accountPass,'
- . 'acchistory_IV = :accountIV,'
- . 'acchistory_mPassHash = :newHash '
- . 'WHERE acchistory_id = :id';
-
- $data['accountPass'] = $this->accountPass;
- $data['accountIV'] = $this->accountIV;
- $data['newHash'] = $newHash;
- $data['id'] = $id;
-
- return DB::getQuery($query, __FUNCTION__, $data);
- }
-
- /**
- * Calcular el hash de los datos de una cuenta.
- * Esta función se utiliza para verificar si los datos de un formulario han sido cambiados
- * con respecto a los guardados
- *
- * @return string con el hash
- */
- public function calcChangesHash()
- {
- $groups = 0;
- $users = 0;
-
- if (is_array($this->accountUserGroupsId)) {
- $groups = implode($this->accountUserGroupsId);
- } elseif (is_array($this->accountCacheUserGroupsId)) {
- foreach ($this->accountCacheUserGroupsId as $group) {
- if (is_array($group)) {
- // Ordenar el array para que el hash sea igual
- sort($group, SORT_NUMERIC);
- $groups = implode($group);
- }
- }
- }
-
- if (is_array($this->accountUsersId)) {
- $users = implode($this->accountUsersId);
- } elseif (is_array($this->accountCacheUsersId)) {
- foreach ($this->accountCacheUsersId as $user) {
- if (is_array($user)) {
- // Ordenar el array para que el hash sea igual
- sort($user, SORT_NUMERIC);
- $users = implode($user);
- }
- }
- }
-
- if (!empty($this->accountModHash)) {
- $hashItems = $this->accountModHash . (int)$users . (int)$groups;
- //error_log("HASH MySQL: ".$hashItems);
- } else {
- $hashItems = $this->accountName .
- $this->accountCategoryId .
- $this->accountCustomerId .
- $this->accountLogin .
- $this->accountUrl .
- $this->accountNotes .
- $this->accountOtherUserEdit .
- $this->accountOtherGroupEdit .
- (int)$users .
- (int)$groups;
- //error_log("HASH PHP: ".$hashItems);
- }
-
- return md5($hashItems);
- }
-
- /**
- * Devolver datos de la cuenta para comprobación de accesos.
- *
- * @param int $accountId con el id de la cuenta
- * @return array con los datos de la cuenta
- */
- public function getAccountDataForACL($accountId = null)
- {
- $accId = (!is_null($accountId)) ? $accountId : $this->accountId;
-
- return array(
- 'id' => $accId,
- 'user_id' => $this->accountUserId,
- 'group_id' => $this->accountUserGroupId,
- 'users_id' => $this->getUsersAccount(),
- 'groups_id' => $this->getGroupsAccount(),
- 'otheruser_edit' => $this->accountOtherUserEdit,
- 'othergroup_edit' => $this->accountOtherGroupEdit
- );
- }
-
- /**
- * Obtiene el listado usuarios con acceso a una cuenta.
- * Lo almacena en la cache de sesión como array de cuentas
- *
- * @return array Con los registros con id de cuenta como clave e id de usuario como valor
- */
- public function getUsersAccount()
- {
- $accId = ($this->accountIsHistory && $this->accountParentId) ? $this->accountParentId : $this->accountId;
-
- $cacheUsers = &$_SESSION['cache']['usersId'];
-
- if (!is_array($cacheUsers)) {
- $cacheUsers = array($accId => array(), 'expires' => 0);
- }
-
- if (!isset($cacheUsers[$accId])
- || time() > $cacheUsers['expires']
- ) {
- $cacheUsers[$accId] = SP_Users::getUsersForAccount($accId);
- $cacheUsers['expires'] = time() + 300;
- }
-
- return $cacheUsers[$accId];
- }
-
- /**
- * Obtiene el listado de grupos secundarios de una cuenta.
- * Lo almacena en la cache de sesión como array de cuentas
- *
- * @return array con los registros con id de cuenta como clave e id de grupo como valor
- */
- public function getGroupsAccount()
- {
- $accId = ($this->accountIsHistory && $this->accountParentId) ? $this->accountParentId : $this->accountId;
-
- $cacheUserGroups = &$_SESSION['cache']['userGroupsId'];
-
- if (!is_array($cacheUserGroups)) {
- //error_log('Groups cache NO_INIT');
- $cacheUserGroups = array($accId => array(), 'expires' => 0);
- }
-
- if (!isset($cacheUserGroups[$accId])
- || time() > $cacheUserGroups['expires']
- ) {
- $cacheUserGroups[$accId] = SP_Groups::getGroupsForAccount($accId);
- $cacheUserGroups['expires'] = time() + 300;
- }
-
- return $cacheUserGroups[$accId];
- }
-}
\ No newline at end of file
diff --git a/inc/Acl.class.php b/inc/Acl.class.php
index 9f471d4c..068747f5 100644
--- a/inc/Acl.class.php
+++ b/inc/Acl.class.php
@@ -3,8 +3,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -24,12 +24,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de calcular las access lists de acceso a usuarios.
*/
-class SP_Acl implements \Controller\ActionsInterface
+class Acl implements Controller\ActionsInterface
{
/**
* Comprobar los permisos de acceso del usuario a los módulos de la aplicación.
@@ -38,7 +40,7 @@ class SP_Acl implements \Controller\ActionsInterface
* en la variable de sesión.
*
* @param string $action con el nombre de la acción
- * @param int $userId opcional, con el Id del usuario
+ * @param int $userId opcional, con el Id del usuario
* @return bool
*/
public static function checkUserAccess($action, $userId = 0)
@@ -49,64 +51,64 @@ class SP_Acl implements \Controller\ActionsInterface
return false;
}
- $curUserIsAdminApp = SP_Session::getUserIsAdminApp();
- $curUserIsAdminAcc = SP_Session::getUserIsAdminAcc();
- $curUserProfile = SP_Session::getUserProfileId();
- $curUserId = SP_Session::getUserId();
+ $curUserIsAdminApp = Session::getUserIsAdminApp();
+ $curUserIsAdminAcc = Session::getUserIsAdminAcc();
+ $curUserProfile = Session::getUserProfile();
+ $curUserId = Session::getUserId();
switch ($action) {
case self::ACTION_ACC_VIEW:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pView);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pView || $curUserProfile->pEdit);
case self::ACTION_ACC_VIEW_PASS:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pViewPass);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pViewPass);
case self::ACTION_ACC_VIEW_HISTORY:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pViewHistory);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pViewHistory);
case self::ACTION_ACC_EDIT:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pEdit);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pEdit);
case self::ACTION_ACC_EDIT_PASS:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pEditPass || $userId == $_SESSION["uid"]);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pEditPass);
case self::ACTION_ACC_NEW:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pAdd);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pAdd);
case self::ACTION_ACC_COPY:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || ($curUserProfile->userProfile_pAdd && $curUserProfile->userProfile_pView));
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || ($curUserProfile->pAdd && $curUserProfile->pView));
case self::ACTION_ACC_DELETE:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pDelete);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pDelete);
case self::ACTION_ACC_FILES:
- return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->userProfile_pFiles);
+ return ($curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->pFiles);
case self::ACTION_MGM:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pAppMgmtMenu);
+ return ($curUserIsAdminApp || $curUserProfile->pAppMgmtMenu);
case self::ACTION_CFG:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pConfigMenu);
+ return ($curUserIsAdminApp || $curUserProfile->pConfigMenu);
case self::ACTION_CFG_GENERAL:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pConfig);
+ return ($curUserIsAdminApp || $curUserProfile->pConfig);
case self::ACTION_CFG_IMPORT:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pConfig);
+ return ($curUserIsAdminApp || $curUserProfile->pConfig);
case self::ACTION_MGM_CATEGORIES:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pAppMgmtCategories);
+ return ($curUserIsAdminApp || $curUserProfile->pAppMgmtCategories);
case self::ACTION_MGM_CUSTOMERS:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pAppMgmtCustomers);
+ return ($curUserIsAdminApp || $curUserProfile->pAppMgmtCustomers);
case self::ACTION_CFG_ENCRYPTION:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pConfigMasterPass);
+ return ($curUserIsAdminApp || $curUserProfile->pConfigMasterPass);
case self::ACTION_CFG_BACKUP:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pConfigBackup);
+ return ($curUserIsAdminApp || $curUserProfile->pConfigBackup);
case self::ACTION_USR:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pUsersMenu);
+ return ($curUserIsAdminApp || $curUserProfile->pUsersMenu);
case self::ACTION_USR_USERS:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pUsers);
+ return ($curUserIsAdminApp || $curUserProfile->pUsers);
case self::ACTION_USR_USERS_EDITPASS:
- return ($userId == $curUserId || $curUserIsAdminApp || $curUserProfile->userProfile_pUsers);
+ return ($userId == $curUserId || $curUserIsAdminApp || $curUserProfile->pUsers);
case self::ACTION_USR_GROUPS:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pGroups);
+ return ($curUserIsAdminApp || $curUserProfile->pGroups);
case self::ACTION_USR_PROFILES:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pProfiles);
+ return ($curUserIsAdminApp || $curUserProfile->pProfiles);
case self::ACTION_EVL:
- return ($curUserIsAdminApp || $curUserProfile->userProfile_pEventlog);
+ return ($curUserIsAdminApp || $curUserProfile->pEventlog);
}
$message['action'] = __FUNCTION__;
$message['text'][] = _('Denegado acceso a') . " '" . self::getActionName($action) . "'";
- SP_Log::wrLogInfo($message);
+ Log::wrLogInfo($message);
return false;
}
@@ -114,16 +116,16 @@ class SP_Acl implements \Controller\ActionsInterface
/**
* Comprueba los permisos de acceso a una cuenta.
*
- * @param string $module con la acción realizada
- * @param array $accountData con los datos de la cuenta a verificar
+ * @param string $module con la acción realizada
+ * @param array $accountData con los datos de la cuenta a verificar
* @return bool
*/
public static function checkAccountAccess($module, $accountData)
{
- $userGroupId = SP_Session::getUserGroupId();
- $userId = SP_Session::getUserId();
- $userIsAdminApp = SP_Session::getUserIsAdminApp();
- $userIsAdminAcc = SP_Session::getUserIsAdminAcc();
+ $userGroupId = Session::getUserGroupId();
+ $userId = Session::getUserId();
+ $userIsAdminApp = Session::getUserIsAdminApp();
+ $userIsAdminAcc = Session::getUserIsAdminAcc();
$okView = ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
@@ -143,7 +145,7 @@ class SP_Acl implements \Controller\ActionsInterface
case self::ACTION_ACC_VIEW:
return $okView;
case self::ACTION_ACC_VIEW_PASS:
- return $okView;;
+ return $okView;
case self::ACTION_ACC_VIEW_HISTORY:
return $okView;
case self::ACTION_ACC_EDIT:
@@ -165,7 +167,8 @@ class SP_Acl implements \Controller\ActionsInterface
* @param int $action El id de la acción
* @return string
*/
- public static function getActionName($action){
+ public static function getActionName($action)
+ {
$actionName = array(
self::ACTION_ACC_SEARCH => 'acc_search',
self::ACTION_ACC_VIEW => 'acc_view',
@@ -193,7 +196,7 @@ class SP_Acl implements \Controller\ActionsInterface
self::ACTION_EVL => 'evl'
);
- if (!isset($actionName[$action])){
+ if (!isset($actionName[$action])) {
return 'action';
}
diff --git a/inc/ActionsInterface.class.php b/inc/ActionsInterface.class.php
new file mode 100644
index 00000000..59797312
--- /dev/null
+++ b/inc/ActionsInterface.class.php
@@ -0,0 +1,81 @@
+.
+ *
+ */
+
+namespace SP\Controller;
+
+/**
+ * Interface ActionsInterface para la definición de constantes de acciones disponibles.
+ *
+ * @package Controller
+ */
+interface ActionsInterface {
+ const ACTION_ACC_SEARCH = 1;
+ const ACTION_ACC_VIEW = 2;
+ const ACTION_ACC_VIEW_PASS = 3;
+ const ACTION_ACC_VIEW_HISTORY = 4;
+ const ACTION_ACC_EDIT = 10;
+ const ACTION_ACC_EDIT_PASS = 11;
+ const ACTION_ACC_EDIT_RESTORE = 12;
+ const ACTION_ACC_NEW = 20;
+ const ACTION_ACC_COPY = 30;
+ const ACTION_ACC_DELETE = 40;
+ const ACTION_ACC_FILES = 50;
+ const ACTION_ACC_REQUEST = 51;
+ const ACTION_MGM = 60;
+ const ACTION_MGM_CATEGORIES = 61;
+ const ACTION_MGM_CATEGORIES_VIEW = 610;
+ const ACTION_MGM_CATEGORIES_NEW = 611;
+ const ACTION_MGM_CATEGORIES_EDIT = 612;
+ const ACTION_MGM_CATEGORIES_DELETE = 613;
+ const ACTION_MGM_CUSTOMERS = 62;
+ const ACTION_MGM_CUSTOMERS_VIEW = 620;
+ const ACTION_MGM_CUSTOMERS_NEW = 621;
+ const ACTION_MGM_CUSTOMERS_EDIT = 622;
+ const ACTION_MGM_CUSTOMERS_DELETE = 623;
+ const ACTION_USR = 70;
+ const ACTION_USR_USERS = 71;
+ const ACTION_USR_USERS_VIEW= 710;
+ const ACTION_USR_USERS_NEW = 711;
+ const ACTION_USR_USERS_EDIT = 712;
+ const ACTION_USR_USERS_DELETE = 713;
+ const ACTION_USR_USERS_EDITPASS = 714;
+ const ACTION_USR_GROUPS = 72;
+ const ACTION_USR_GROUPS_VIEW = 720;
+ const ACTION_USR_GROUPS_NEW = 721;
+ const ACTION_USR_GROUPS_EDIT = 722;
+ const ACTION_USR_GROUPS_DELETE = 723;
+ const ACTION_USR_PROFILES = 73;
+ const ACTION_USR_PROFILES_VIEW = 730;
+ const ACTION_USR_PROFILES_NEW = 731;
+ const ACTION_USR_PROFILES_EDIT = 732;
+ const ACTION_USR_PROFILES_DELETE = 733;
+ const ACTION_CFG = 80;
+ const ACTION_CFG_GENERAL = 81;
+ const ACTION_CFG_ENCRYPTION = 82;
+ const ACTION_CFG_ENCRYPTION_TEMPPASS = 83;
+ const ACTION_CFG_BACKUP = 84;
+ const ACTION_CFG_IMPORT = 85;
+ const ACTION_EVL = 90;
+}
\ No newline at end of file
diff --git a/inc/Auth.class.php b/inc/Auth.class.php
index c3ebc35a..84981628 100644
--- a/inc/Auth.class.php
+++ b/inc/Auth.class.php
@@ -3,8 +3,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -24,12 +24,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar la autentificación de usuarios de sysPass.
*/
-class SP_Auth
+class Auth
{
static $userName;
static $userEmail;
@@ -38,12 +40,12 @@ class SP_Auth
* Autentificación de usuarios con LDAP.
*
* @param string $userLogin con el login del usuario
- * @param string $userPass con la clave del usuario
+ * @param string $userPass con la clave del usuario
* @return int|bool Número de error o boolean
*/
public static function authUserLDAP($userLogin, $userPass)
{
- if (!SP_Util::ldapIsAvailable() || !SP_Util::ldapIsEnabled() || !SP_Ldap::checkLDAPParams()) {
+ if (!Util::ldapIsAvailable() || !Util::ldapIsEnabled() || !Ldap::checkLDAPParams()) {
return false;
}
@@ -52,14 +54,14 @@ class SP_Auth
// Conectamos al servidor realizamos la conexión con el usuario proxy
try {
- SP_Ldap::ldapConnect();
- SP_Ldap::ldapBind();
- SP_Ldap::getUserDN($userLogin);
+ Ldap::ldapConnect();
+ Ldap::ldapBind();
+ Ldap::getUserDN($userLogin);
} catch (Exception $e) {
return false;
}
- $userDN = SP_Ldap::$ldapSearchData[0]['dn'];
+ $userDN = Ldap::$ldapSearchData[0]['dn'];
// Mapeo de los atributos
$attribsMap = array(
'groupMembership' => 'group',
@@ -71,10 +73,10 @@ class SP_Auth
// Realizamos la conexión con el usuario real y obtenemos los atributos
try {
- SP_Ldap::ldapBind($userDN, $userPass);
- $attribs = SP_Ldap::getLDAPAttr($attribsMap);
+ Ldap::ldapBind($userDN, $userPass);
+ $attribs = Ldap::getLDAPAttr($attribsMap);
} catch (Exception $e) {
- return ldap_errno(SP_Ldap::getConn());
+ return ldap_errno(Ldap::getConn());
}
// Comprobamos si la cuenta está bloqueada o expirada
@@ -101,7 +103,7 @@ class SP_Auth
}
// Comprobamos que el usuario está en el grupo indicado buscando en los atributos del grupo
} else {
- $ldapGroupAccess = SP_Ldap::searchUserInGroup($userDN);
+ $ldapGroupAccess = Ldap::searchUserInGroup($userDN);
}
if ($ldapGroupAccess == false) {
@@ -122,7 +124,7 @@ class SP_Auth
*/
private static function checkLDAPGroup($group)
{
- $ldapGroup = strtolower(SP_Config::getValue('ldap_group'));
+ $ldapGroup = strtolower(Config::getValue('ldap_group'));
$groupName = array();
preg_match('/^cn=([\w\s-]+),.*/i', $group, $groupName);
@@ -141,13 +143,13 @@ class SP_Auth
* se ejecuta el proceso para actualizar la clave.
*
* @param string $userLogin con el login del usuario
- * @param string $userPass con la clave del usuario
+ * @param string $userPass con la clave del usuario
* @return bool
*/
public static function authUserMySQL($userLogin, $userPass)
{
- if (SP_Users::checkUserIsMigrate($userLogin)) {
- if (!SP_Users::migrateUser($userLogin, $userPass)) {
+ if (Users::checkUserIsMigrate($userLogin)) {
+ if (!Users::migrateUser($userLogin, $userPass)) {
return false;
}
}
@@ -173,23 +175,23 @@ class SP_Auth
*/
public static function mailPassRecover($login, $email)
{
- if (SP_Users::checkUserMail($login, $email)
- && !SP_Users::checkUserIsDisabled($login)
- && !SP_Users::checkUserIsLDAP($login)
- && !SP_Users::checkPassRecoverLimit($login)
+ if (Users::checkUserMail($login, $email)
+ && !Users::checkUserIsDisabled($login)
+ && !Users::checkUserIsLDAP($login)
+ && !Users::checkPassRecoverLimit($login)
) {
- $hash = SP_Util::generate_random_bytes();
+ $hash = Util::generate_random_bytes();
$message['action'] = _('Cambio de Clave');
- $message['text'][] = SP_Html::strongText(_('Se ha solicitado el cambio de su clave de usuario.'));
+ $message['text'][] = Html::strongText(_('Se ha solicitado el cambio de su clave de usuario.'));
$message['text'][] = '';
$message['text'][] = _('Para completar el proceso es necesario que acceda a la siguiente URL:');
$message['text'][] = '';
- $message['text'][] = SP_Html::anchorText(SP_Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time());
+ $message['text'][] = Html::anchorText(Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time());
$message['text'][] = '';
$message['text'][] = _('Si no ha solicitado esta acción, ignore este mensaje.');
- return (SP_Common::sendEmail($message, $email, false) && SP_Users::addPassRecover($login, $hash));
+ return (Common::sendEmail($message, $email, false) && Users::addPassRecover($login, $hash));
} else {
return false;
}
diff --git a/inc/Backup.class.php b/inc/Backup.class.php
index cc4c0234..52712410 100644
--- a/inc/Backup.class.php
+++ b/inc/Backup.class.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -23,12 +23,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar la copia y restauración de sysPass.
*/
-class SP_Backup
+class Backup
{
/**
* Realizar backup de la BBDD y aplicación.
@@ -37,8 +39,8 @@ class SP_Backup
*/
public static function doBackup()
{
- $siteName = SP_Util::getAppInfo('appname');
- $backupDir = SP_Init::$SERVERROOT;
+ $siteName = Util::getAppInfo('appname');
+ $backupDir = Init::$SERVERROOT;
$backupDstDir = $backupDir . DIRECTORY_SEPARATOR . 'backup';
$bakFileApp = $backupDstDir . DIRECTORY_SEPARATOR . $siteName . '.tar';
$bakFileDB = $backupDstDir . DIRECTORY_SEPARATOR . $siteName . '_db.sql';
@@ -47,13 +49,13 @@ class SP_Backup
self::checkBackupDir($backupDstDir);
self::backupTables('*', $bakFileDB);
self::backupApp($bakFileApp);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$message['action'] = __FUNCTION__;
$message['text'][] = $e->getMessage();
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return false;
}
@@ -67,12 +69,12 @@ class SP_Backup
*
* @param string $tables
* @param string $backupFile
- * @throws Exception
+ * @throws SPException
* @return bool
*/
private static function backupTables($tables = '*', $backupFile)
{
- $dbname = SP_Config::getValue("dbname");
+ $dbname = Config::getValue("dbname");
try {
$handle = fopen($backupFile, 'w');
@@ -105,14 +107,14 @@ class SP_Backup
$sqlOut .= $txtCreate->{'Create Table'} . ';' . PHP_EOL . PHP_EOL;
fwrite($handle, $sqlOut);
- DB::setUnbuffered();
+ DB::setReturnRawData();
// Consulta para obtener los registros de la tabla
$queryRes = DB::getResults('SELECT * FROM ' . $tableName, __FUNCTION__);
$numColumns = $queryRes->columnCount();
- while ($row = $queryRes->fetch(PDO::FETCH_NUM)) {
+ while ($row = $queryRes->fetch(\PDO::FETCH_NUM)) {
fwrite($handle, 'INSERT INTO `' . $tableName . '` VALUES(');
$field = 1;
@@ -133,7 +135,7 @@ class SP_Backup
}
fwrite($handle, PHP_EOL . PHP_EOL);
- DB::setUnbuffered(false);
+ DB::setReturnRawData(false);
}
$sqlOut = '--' . PHP_EOL;
@@ -144,8 +146,8 @@ class SP_Backup
fwrite($handle, $sqlOut);
fclose($handle);
- } catch (Exception $e) {
- throw new Exception($e->getMessage());
+ } catch (\Exception $e) {
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
}
return true;
@@ -161,12 +163,10 @@ class SP_Backup
private static function backupApp($backupFile)
{
if (!class_exists('PharData')) {
- if(SP_Util::runningOnWindows()){
- throw new Exception(_('Esta operación sólo es posible en entornos Linux'));
- }
-
- if(!self::backupAppLegacyLinux($backupFile)){
- throw new Exception(_('Error al realizar backup en modo compatibilidad'));
+ if (Util::runningOnWindows()) {
+ throw new SPException(SPException::SP_CRITICAL, _('Esta operación sólo es posible en entornos Linux'));
+ } elseif (!self::backupAppLegacyLinux($backupFile)) {
+ throw new SPException(SPException::SP_CRITICAL, _('Error al realizar backup en modo compatibilidad'));
}
return true;
@@ -175,17 +175,17 @@ class SP_Backup
$compressedFile = $backupFile . '.gz';
try {
- if (file_exists($compressedFile)){
+ if (file_exists($compressedFile)) {
unlink($compressedFile);
}
- $archive = new PharData($backupFile);
- $archive->buildFromDirectory(SP_Init::$SERVERROOT);
- $archive->compress(Phar::GZ);
+ $archive = new \PharData($backupFile);
+ $archive->buildFromDirectory(Init::$SERVERROOT);
+ $archive->compress(\Phar::GZ);
unlink($backupFile);
- } catch (Exception $e) {
- throw new Exception($e->getMessage());
+ } catch (\Exception $e) {
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
}
return file_exists($backupFile);
@@ -200,7 +200,7 @@ class SP_Backup
private static function backupAppLegacyLinux($backupFile)
{
$compressedFile = $backupFile . '.gz';
- $backupDir = SP_Init::$SERVERROOT;
+ $backupDir = Init::$SERVERROOT;
$bakDstDir = $backupDir . '/backup';
$command = 'tar czf ' . $compressedFile . ' ' . $backupDir . ' --exclude "' . $bakDstDir . '" 2>&1';
@@ -213,21 +213,21 @@ class SP_Backup
* Comprobar y crear el directorio de backups.
*
* @param string $backupDir ruta del directorio de backup
- * @throws Exception
+ * @throws SPException
* @return bool
*/
private static function checkBackupDir($backupDir)
{
if (!is_dir($backupDir)) {
if (!@mkdir($backupDir, 0550)) {
- throw new Exception(('No es posible crear el directorio de backups') . ' (' . $backupDir . ')');
+ throw new SPException(SPException::SP_CRITICAL, _('No es posible crear el directorio de backups') . ' (' . $backupDir . ')');
}
}
if (!is_writable($backupDir)) {
- throw new Exception(_('Compruebe los permisos del directorio de backups'));
+ throw new SPException(SPException::SP_CRITICAL, _('Compruebe los permisos del directorio de backups'));
}
return true;
}
-}
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/inc/Base.php b/inc/Base.php
new file mode 100644
index 00000000..0bc0daf5
--- /dev/null
+++ b/inc/Base.php
@@ -0,0 +1,38 @@
+.
+ *
+ */
+
+define('MODEL_PATH', __DIR__);
+define('CONTROLLER_PATH', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'web');
+define('VIEW_PATH', __DIR__ . DIRECTORY_SEPARATOR . 'tpl');
+define('EXTENSIONS_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ext');
+
+require_once MODEL_PATH . DIRECTORY_SEPARATOR . 'Init.class.php';
+
+// Empezar a calcular el tiempo y memoria utilizados
+$memInit = memory_get_usage();
+$timeStart = \SP\Init::microtime_float();
+
+// Inicializar sysPass
+\SP\Init::start();
\ No newline at end of file
diff --git a/inc/Cache.class.php b/inc/Cache.class.php
index d391ad10..42a4e7a5 100644
--- a/inc/Cache.class.php
+++ b/inc/Cache.class.php
@@ -23,10 +23,12 @@
*
*/
+namespace SP;
+
/**
* Clase base para guardar/obtener elementos de la caché
*/
-class SP_Cache
+class Cache
{
/**
* Tiempo de expiración de la cache en segundos
@@ -48,7 +50,7 @@ class SP_Cache
}
// FIXME
- error_log('CONFIG_CACHE_VALUE_MISS');
+// error_log('CONFIG_CACHE_VALUE_MISS');
return null;
}
@@ -79,9 +81,9 @@ class SP_Cache
public static function setSessionCacheConfig()
{
// FIXME
- error_log('CONFIG_CACHE_MISS');
+// error_log('CONFIG_CACHE_MISS');
- $_SESSION['cache']['config'] = SP_Config::getConfig();
+ $_SESSION['cache']['config'] = Config::getConfig();
$_SESSION['cache']['config']['expires'] = time() + self::EXPIRE_TIME;
}
}
\ No newline at end of file
diff --git a/inc/Category.class.php b/inc/Category.class.php
index 1f757e11..26f092fb 100644
--- a/inc/Category.class.php
+++ b/inc/Category.class.php
@@ -3,8 +3,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -24,12 +24,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones sobre las categorías de sysPass.
*/
-class SP_Category
+class Category
{
public static $categoryName;
public static $categoryDescription;
@@ -75,10 +77,10 @@ class SP_Category
self::$categoryLastId = DB::$lastId;
$message['action'] = _('Nueva Categoría');
- $message['text'][] = SP_Html::strongText(_('Categoría') . ': ') . self::$categoryName;
+ $message['text'][] = Html::strongText(_('Categoría') . ': ') . self::$categoryName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -124,10 +126,10 @@ class SP_Category
}
$message['action'] = _('Eliminar Categoría');
- $message['text'][] = SP_Html::strongText(_('Categoría') . ': ') . $categoryName . ' (' . $id . ')';
+ $message['text'][] = Html::strongText(_('Categoría') . ': ') . $categoryName . ' (' . $id . ')';
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -176,10 +178,10 @@ class SP_Category
}
$message['action'] = _('Modificar Categoría');
- $message['text'][] = SP_Html::strongText(_('Categoría') . ': ') . $categoryName . ' > ' . self::$categoryName;
+ $message['text'][] = Html::strongText(_('Categoría') . ': ') . $categoryName . ' > ' . self::$categoryName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -214,7 +216,7 @@ class SP_Category
/**
* Obtiene el listado de categorías.
*
- * @param int $id con el Id de la categoría
+ * @param int $id con el Id de la categoría
* @param bool $retAssocArray para devolver un array asociativo
* @return array con en id de categorioa como clave y en nombre como valor
*/
diff --git a/inc/Common.class.php b/inc/Common.class.php
index 7f2b58be..174e723c 100644
--- a/inc/Common.class.php
+++ b/inc/Common.class.php
@@ -23,24 +23,26 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es encargada de ejecutar acciones comunes para las funciones
*/
-class SP_Common
+class Common
{
/**
* Enviar un email utilizando la clase PHPMailer.
*
- * @param array $message con el nombre de la accióm y el texto del mensaje
- * @param string $mailTo con el destinatario
- * @param bool $isEvent para indicar si es um
+ * @param array $message con el nombre de la accióm y el texto del mensaje
+ * @param string $mailTo con el destinatario
+ * @param bool $isEvent para indicar si es um
* @return bool
*/
public static function sendEmail($message, $mailTo = '', $isEvent = true)
{
- if (!SP_Util::mailIsEnabled()) {
+ if (!Util::mailIsEnabled()) {
return false;
}
@@ -59,17 +61,17 @@ class SP_Common
if ($isEvent === true) {
$performer = (isset($_SESSION["ulogin"])) ? $_SESSION["ulogin"] : _('N/D');
- $body[] = SP_Html::strongText(_('Acción') . ": ") . $message['action'];
- $body[] = SP_Html::strongText(_('Realizado por') . ": ") . $performer . ' (' . $_SERVER['REMOTE_ADDR'] . ')';
+ $body[] = Html::strongText(_('Acción') . ": ") . $message['action'];
+ $body[] = Html::strongText(_('Realizado por') . ": ") . $performer . ' (' . $_SERVER['REMOTE_ADDR'] . ')';
- $mail->addCC(SP_Config::getValue('mail_from'));
+ $mail->addCC(Config::getValue('mail_from'));
}
$body[] = (is_array($message['text'])) ? implode($newline, $message['text']) : '';
$body[] = '';
$body[] = '--';
- $body[] = SP_Util::getAppInfo('appname') . ' - ' . SP_Util::getAppInfo('appdesc');
- $body[] = SP_Html::anchorText(SP_Init::$WEBURI);
+ $body[] = Util::getAppInfo('appname') . ' - ' . Util::getAppInfo('appdesc');
+ $body[] = Html::anchorText(Init::$WEBURI);
$mail->Body = implode($newline, $body);
@@ -86,11 +88,11 @@ class SP_Common
$log['text'][] = '';
$log['text'][] = _('Destinatario') . ": $mailTo";
- $log['text'][] = ($isEvent === true) ? _('CC') . ": " . SP_Config::getValue('mail_from') : '';
+ $log['text'][] = ($isEvent === true) ? _('CC') . ": " . Config::getValue('mail_from') : '';
$log['action'] = _('Enviar Email');
- SP_Log::wrLogInfo($log);
+ Log::wrLogInfo($log);
return $sendMail;
}
@@ -103,15 +105,15 @@ class SP_Common
*/
public static function getEmailObject($mailTo, $action)
{
- $appName = SP_Util::getAppInfo('appname');
- $mailFrom = SP_Config::getValue('mail_from');
- $mailServer = SP_Config::getValue('mail_server');
- $mailPort = SP_Config::getValue('mail_port', 25);
- $mailAuth = SP_Config::getValue('mail_authenabled', FALSE);
+ $appName = Util::getAppInfo('appname');
+ $mailFrom = Config::getValue('mail_from');
+ $mailServer = Config::getValue('mail_server');
+ $mailPort = Config::getValue('mail_port', 25);
+ $mailAuth = Config::getValue('mail_authenabled', FALSE);
if ($mailAuth) {
- $mailUser = SP_Config::getValue('mail_user');
- $mailPass = SP_Config::getValue('mail_pass');
+ $mailUser = Config::getValue('mail_user');
+ $mailPass = Config::getValue('mail_pass');
}
if (!$mailServer) {
@@ -135,7 +137,7 @@ class SP_Common
$mail->Port = $mailPort;
$mail->Username = $mailUser;
$mail->Password = $mailPass;
- $mail->SMTPSecure = strtolower(SP_Config::getValue('mail_security'));
+ $mail->SMTPSecure = strtolower(Config::getValue('mail_security'));
//$mail->SMTPDebug = 2;
//$mail->Debugoutput = 'error_log';
@@ -152,7 +154,7 @@ class SP_Common
* Devuelve una respuesta en formato XML con el estado y el mensaje.
*
* @param string $description mensaje a devolver
- * @param int $status devuelve el estado
+ * @param int $status devuelve el estado
* @return bool
*/
public static function printXML($description, $status = 1)
@@ -176,9 +178,9 @@ class SP_Common
/**
* Devuelve una respuesta en formato JSON con el estado y el mensaje.
*
- * @param string|array $data mensaje a devolver
- * @param int $status devuelve el estado
- * @param string $action con la accion a realizar
+ * @param string|array $data mensaje a devolver
+ * @param int $status devuelve el estado
+ * @param string $action con la accion a realizar
* @return bool
*/
public static function printJSON($data, $status = 1, $action = '')
@@ -198,7 +200,7 @@ class SP_Common
);
} else {
array_walk($data,
- function (&$value, &$key, $arrStrFrom, $arrStrTo) {
+ function (&$value, &$key) use ($arrStrFrom, $arrStrTo) {
return str_replace($arrStrFrom, $arrStrTo, $value);
}
);
@@ -295,12 +297,12 @@ class SP_Common
* Obtener los valores de variables $_GET, $_POST, $_REQUEST o $_SESSION
* y devolverlos limpios con el tipo correcto o esperado.
*
- * @param string $method con el método a utilizar
- * @param string $param con el parámetro a consultar
- * @param mixed $default opcional, valor por defecto a devolver
- * @param bool $onlyCHeck opcional, comprobar si el parámetro está presente
- * @param mixed $force opcional, valor devuelto si el parámeto está definido
- * @param bool $sanitize opcional, escapar/eliminar carácteres especiales
+ * @param string $method con el método a utilizar
+ * @param string $param con el parámetro a consultar
+ * @param mixed $default opcional, valor por defecto a devolver
+ * @param bool $onlyCHeck opcional, comprobar si el parámetro está presente
+ * @param mixed $force opcional, valor devuelto si el parámeto está definido
+ * @param bool $sanitize opcional, escapar/eliminar carácteres especiales
* @return bool|string si está presente el parámeto en la petición devuelve bool. Si lo está, devuelve el valor.
*/
public static function parseParams($method, $param, $default = '', $onlyCHeck = false, $force = false, $sanitize = true)
@@ -349,7 +351,7 @@ class SP_Common
}
if (is_string($out)) {
- return ($method != 's' && $sanitize === true) ? SP_Html::sanitize($out) : $out;
+ return ($method != 's' && $sanitize === true) ? Html::sanitize($out) : $out;
}
if (is_array($out)) {
diff --git a/inc/Config.class.php b/inc/Config.class.php
index dac79720..2e1b8d9c 100644
--- a/inc/Config.class.php
+++ b/inc/Config.class.php
@@ -23,30 +23,44 @@
*
*/
-defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+namespace SP;
-/*
- * "mysql",
- * "firstrun" => false,
- * "pi" => 3.14
- * );
- * ?>
- *
- */
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es responsable de leer y escribir la configuración del archivo config.php
* y en la base de datos
*/
-class SP_Config
+class Config
{
// Array asociativo clave => valor
- static $arrConfigValue;
+ private static $_config;
+ private static $_cache = array();
+ private static $_init = false;
- private static $cache = array(); // Configuracion actual en array
- private static $init = false; // La caché está llena??
+ /**
+ * @param null $key La clave a obtener
+ * @return mixed
+ */
+ public static function getArrConfigValue($key = null)
+ {
+ if (!is_null($key) && isset(self::$_config[$key])) {
+ return self::$_config[$key];
+ }
+
+ return self::$_config;
+ }
+
+ /**
+ * @param $key string La clave a actualizar
+ * @param $value mixed El valor a actualizar
+ */
+ public static function setArrConfigValue($key, $value)
+ {
+ if (isset(self::$_config[$key])) {
+ self::$_config[$key] = $value;
+ }
+ }
/**
* Obtener un array con la configuración almacenada en la BBDD.
@@ -64,9 +78,7 @@ class SP_Config
}
foreach ($queryRes as $config) {
- $strKey = $config->config_parameter;
- $strValue = $config->config_value;
- self::$arrConfigValue[$strKey] = $strValue;
+ self::$_config[$config->config_parameter] = $config->config_value;
}
}
@@ -78,7 +90,7 @@ class SP_Config
*/
public static function writeConfigDb($mkInsert = false)
{
- foreach (self::$arrConfigValue as $param => $value) {
+ foreach (self::$_config as $param => $value) {
if ($mkInsert) {
$query = 'INSERT INTO config VALUES (:param,:value) ON DUPLICATE KEY UPDATE config_value = :valuedup';
@@ -98,8 +110,8 @@ class SP_Config
$message['action'] = _('Configuración');
$message['text'][] = _('Modificar configuración');
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -149,13 +161,9 @@ class SP_Config
*/
public static function getValue($key, $default = null)
{
- $param = SP_Cache::getSessionCacheConfigValue($key);
+ $param = Cache::getSessionCacheConfigValue($key);
- if (!is_null($param)) {
- return $param;
- }
-
- return $default;
+ return (!is_null($param)) ? $param : $default;
}
/**
@@ -169,10 +177,10 @@ class SP_Config
self::readData();
if ($full) {
- return self::$cache;
+ return self::$_cache;
}
- return array_keys(self::$cache);
+ return array_keys(self::$_cache);
}
/**
@@ -182,7 +190,7 @@ class SP_Config
*/
private static function readData()
{
- if (self::$init) {
+ if (self::$_init) {
return true;
}
@@ -196,15 +204,25 @@ class SP_Config
include_once $configFile;
if (isset($CONFIG) && is_array($CONFIG)) {
- self::$cache = $CONFIG;
+ self::$_cache = $CONFIG;
}
// We cached everything
- self::$init = true;
+ self::$_init = true;
return true;
}
+ /**
+ * Devolver la ruta al archivo de configuración
+ *
+ * @return string Con la ruta
+ */
+ private static function getConfigFile()
+ {
+ return Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
+ }
+
/**
* Elimina una clave de la configuración.
* Esta función elimina una clave de configmgmt.php. Si no tiene permiso
@@ -217,9 +235,9 @@ class SP_Config
{
self::readData();
- if (isset(self::$cache[$key])) {
+ if (isset(self::$_cache[$key])) {
// Eliminar la clave de la caché
- unset(self::$cache[$key]);
+ unset(self::$_cache[$key]);
// Guardar los cambios en la configuración
self::writeData();
@@ -236,13 +254,13 @@ class SP_Config
public static function writeData()
{
// Ordenar las claves de la configuración
- ksort(self::$cache);
+ ksort(self::$_cache);
$content = "_action;
+ }
+
+ /**
+ * Establecer el módulo a presentar.
+ *
+ * @param int $action El id de la acción
+ */
+ public function setAction($action)
+ {
+ $this->_action = $action;
}
/**
@@ -87,23 +106,27 @@ abstract class SP_Controller
}
/**
- * Establecer la instancia del motor de plantillas a utilizar.
- *
- * @param SP_Template $template
+ * Obtener los datos para la vista de depuración
*/
- protected function setTemplate(SP_Template $template)
+ public function getDebug()
{
- $this->view = $template;
+ global $memInit;
+
+ $this->view->addTemplate('debug');
+
+ $this->view->assign('time', (\SP\Init::microtime_float() - $this->view->timeStart));
+ $this->view->assign('memInit', $memInit / 1000);
+ $this->view->assign('memEnd', memory_get_usage() / 1000);
}
/**
- * Establecer el módulo a presentar.
+ * Establecer la instancia del motor de plantillas a utilizar.
*
- * @param $action int con el número de módulo
+ * @param \SP\Template $template
*/
- protected function setAction($action)
+ protected function setTemplate(\SP\Template $template)
{
- $this->_action = $action;
+ $this->view = $template;
}
/**
@@ -113,7 +136,7 @@ abstract class SP_Controller
*/
protected function checkAccess()
{
- if (!\SP_Acl::checkUserAccess($this->_action)) {
+ if (!\SP\Acl::checkUserAccess($this->_action)) {
$this->showError(self::ERR_PAGE_NO_PERMISSION);
return false;
}
@@ -140,7 +163,7 @@ abstract class SP_Controller
$this->view->resetTemplates();
}
- if ($fancy){
+ if ($fancy) {
$this->view->addTemplate('errorfancy');
} else {
$this->view->addTemplate('error');
@@ -153,18 +176,4 @@ abstract class SP_Controller
'hint' => $errorsTypes[$type]['hint'])
);
}
-
- /**
- * Obtener los datos para la vista de depuración
- */
- public function getDebug()
- {
- global $memInit;
-
- $this->view->addTemplate('debug');
-
- $this->view->assign('time', (SP_Init::microtime_float() - $this->view->timeStart));
- $this->view->assign('memInit', $memInit / 1000);
- $this->view->assign('memEnd', memory_get_usage() / 1000);
- }
}
\ No newline at end of file
diff --git a/inc/Crypt.class.php b/inc/Crypt.class.php
index 6774f51b..94cb4fa0 100644
--- a/inc/Crypt.class.php
+++ b/inc/Crypt.class.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -23,12 +23,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar el encriptad/desencriptado de claves
*/
-class SP_Crypt
+class Crypt
{
public static $strInitialVector;
@@ -59,7 +61,7 @@ class SP_Crypt
/**
* Comprobar el hash de una clave.
*
- * @param string $pwd con la clave a comprobar
+ * @param string $pwd con la clave a comprobar
* @param string $correctHash con el hash a comprobar
* @return bool
*/
@@ -95,7 +97,7 @@ class SP_Crypt
* Generar una clave encriptada.
* Esta función llama a los métodos privados para encriptar datos.
*
- * @param string $pwd con la clave a encriptar
+ * @param string $pwd con la clave a encriptar
* @param string $masterPwd con la clave maestra
* @return bool
*/
@@ -123,8 +125,8 @@ class SP_Crypt
* Desencriptar datos con la clave maestra.
*
* @param string $strEncrypted con los datos a desencriptar
- * @param string $strPassword con la clave maestra
- * @param string $cryptIV con el IV
+ * @param string $strPassword con la clave maestra
+ * @param string $cryptIV con el IV
* @return string con los datos desencriptados
*/
public static function getDecrypt($strEncrypted, $strPassword, $cryptIV)
@@ -149,7 +151,7 @@ class SP_Crypt
$source = MCRYPT_DEV_URANDOM;
$mcryptRes = self::getMcryptResource();
- if (SP_Util::runningOnWindows() && (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300)) {
+ if (Util::runningOnWindows() && (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300)) {
$source = MCRYPT_RAND;
}
@@ -166,9 +168,9 @@ class SP_Crypt
/**
* Encriptar datos con la clave maestra.
*
- * @param string $strValue con los datos a encriptar
+ * @param string $strValue con los datos a encriptar
* @param string $strPassword con la clave maestra
- * @param string $cryptIV con el IV
+ * @param string $cryptIV con el IV
* @return string con los datos encriptados
*/
private static function encrypt($strValue, $strPassword, $cryptIV)
@@ -204,7 +206,8 @@ class SP_Crypt
*
* @return resource
*/
- private static function getMcryptResource(){
+ private static function getMcryptResource()
+ {
return mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
}
}
\ No newline at end of file
diff --git a/inc/Customer.class.php b/inc/Customer.class.php
index 644f5ec6..3c0af96a 100644
--- a/inc/Customer.class.php
+++ b/inc/Customer.class.php
@@ -24,14 +24,15 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones sobre los clientes de sysPass
*/
-class SP_Customer
+class Customer
{
-
public static $customerName;
public static $customerDescription;
public static $customerLastId;
@@ -57,10 +58,10 @@ class SP_Customer
self::$customerLastId = DB::$lastId;
$message['action'] = _('Nuevo Cliente');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . self::$customerName;
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . self::$customerName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -109,10 +110,10 @@ class SP_Customer
}
$message['action'] = _('Actualizar Cliente');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $customerName . ' > ' . self::$customerName;
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $customerName . ' > ' . self::$customerName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -157,10 +158,10 @@ class SP_Customer
}
$message['action'] = _('Eliminar Cliente');
- $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $customerName;
+ $message['text'][] = Html::strongText(_('Cliente') . ': ') . $customerName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -238,7 +239,7 @@ class SP_Customer
/**
* Obtener el listado de clientes.
*
- * @param int $customerId con el Id del cliente
+ * @param int $customerId con el Id del cliente
* @param bool $retAssocArray para devolver un array asociativo
* @return array con el id de cliente como clave y el nombre como valor
*/
diff --git a/inc/DB.class.php b/inc/DB.class.php
index 2b799d96..c6bd7c61 100644
--- a/inc/DB.class.php
+++ b/inc/DB.class.php
@@ -1,5 +1,4 @@
db) {
-// FIXME
-// error_log('NEW DB_CONNECTION');
- $isInstalled = SP_Config::getValue('installed');
-
- $dbhost = SP_Config::getValue('dbhost');
- $dbuser = SP_Config::getValue('dbuser');
- $dbpass = SP_Config::getValue('dbpass');
- $dbname = SP_Config::getValue('dbname');
- $dbport = SP_Config::getValue('dbport', 3306);
-
- if (empty($dbhost) || empty($dbuser) || empty($dbpass) || empty($dbname)) {
- if ($isInstalled) {
- SP_Init::initError(_('No es posible conectar con la BD'), _('Compruebe los datos de conexión'));
- } else {
- throw new SPDatabaseException(_('No es posible conectar con la BD'), 1);
- }
- }
-
- try {
- $dsn = 'mysql:host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname . ';charset=utf8';
-// $this->db = new PDO($dsn, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
- $this->db = new PDO($dsn, $dbuser, $dbpass);
- } catch (PDOException $e) {
- if ($isInstalled) {
- if ($this->db->connect_errno === 1049) {
- SP_Config::setValue('installed', '0');
- }
-
- SP_Init::initError(_('No es posible conectar con la BD'), 'Error ' . $e->getCode() . ': ' . $e->getMessage());
- } else {
- throw new SPDatabaseException($e->getMessage(), $e->getCode());
- }
- }
- }
-
- $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- return $this->db;
- }
-}
-
-/**
- * Class SPDatabaseException
- *
- * Clase para excepciones de BD de sysPass
- */
-class SPDatabaseException extends Exception
-{
-}
-
/**
* Esta clase es la encargada de realizar las operaciones con la BBDD de sysPass.
*/
@@ -116,27 +36,27 @@ class DB
static $numError = 0;
static $last_num_rows = 0;
static $lastId = null;
- private static $retArray = false;
- private static $unbuffered = false;
- private static $fullRowCount = false;
+ private static $_retArray = false;
+ private static $_returnRawData = false;
+ private static $_fullRowCount = false;
public $num_rows = 0;
public $num_fields = 0;
- private $last_result = null;
- private $querySource;
+ private $_last_result = null;
+ private $_querySource;
/**
* Datos para el objeto PDOStatement
*
* @var array
*/
- private $stData;
+ private $_stData;
/**
* Comprobar que la base de datos existe.
*
* @return bool
- * @throws SPDatabaseException
+ * @throws SPException
*/
public static function checkDatabaseExist()
{
@@ -145,14 +65,14 @@ class DB
$query = 'SELECT COUNT(*) '
. 'FROM information_schema.tables '
- . 'WHERE table_schema=\'' . SP_Config::getValue("dbname") . '\' '
+ . 'WHERE table_schema=\'' . Config::getValue("dbname") . '\' '
. 'AND table_name = \'usrData\'';
if ($db->query($query)->fetchColumn() !== 0) {
return true;
}
- } catch (PDOException $e) {
- throw new SPDatabaseException($e->getMessage(), $e->getCode());
+ } catch (\Exception $e) {
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode());
}
return false;
@@ -161,17 +81,17 @@ class DB
/**
* Obtener los datos para generar un select.
*
- * @param string $tblName con el nombre de la tabla a cunsultar
- * @param string $tblColId con el nombre de la columna del tipo Id a mostrar
- * @param string $tblColName con el nombre de la columna del tipo Name a mostrar
- * @param array $arrFilter con las columnas a filtrar
- * @param array $arrOrder con el orden de las columnas
+ * @param $tblName string con el nombre de la tabla a cunsultar
+ * @param $tblColId string con el nombre de la columna del tipo Id a mostrar
+ * @param $tblColName string con el nombre de la columna del tipo Name a mostrar
+ * @param $arrFilter array con las columnas a filtrar
+ * @param $arrOrder array con el orden de las columnas
* @return false|array con los valores del select con el Id como clave y el nombre como valor
*/
public static function getValuesForSelect($tblName, $tblColId, $tblColName, $arrFilter = NULL, $arrOrder = NULL)
{
if (!$tblName || !$tblColId || !$tblColName) {
- return;
+ return false;
}
$strFilter = (is_array($arrFilter)) ? " WHERE " . implode(" OR ", $arrFilter) : "";
@@ -195,17 +115,20 @@ class DB
return $arrValues;
}
+ /**
+ * Establecer si se devuelve un array de objetos siempre
+ */
public static function setReturnArray()
{
- self::$retArray = true;
+ self::$_retArray = true;
}
/**
* Obtener los resultados de una consulta.
*
- * @param string $query con la consulta a realizar
- * @param string $querySource con el nombre de la función que realiza la consulta
- * @param array $data con los datos de la consulta
+ * @param $query string con la consulta a realizar
+ * @param $querySource string con el nombre de la función que realiza la consulta
+ * @param $data array con los datos de la consulta
* @return bool|array devuelve bool si hay un error. Devuelve array con el array de registros devueltos
*/
public static function getResults($query, $querySource, &$data = null)
@@ -217,87 +140,87 @@ class DB
try {
$db = new DB();
- $db->querySource = $querySource;
- $db->stData = $data;
- $doQuery = $db->doQuery($query, $querySource, self::$unbuffered);
- } catch (SPDatabaseException $e) {
- $db->logDBException($query, $e->getMessage(), $e->getCode());
+ $db->_querySource = $querySource;
+ $db->_stData = $data;
+ $doQuery = $db->doQuery($query, $querySource, self::$_returnRawData);
+ } catch (SPException $e) {
+ self::logDBException($query, $e->getMessage(), $e->getCode(), $querySource);
return false;
}
- if (self::$unbuffered && is_object($doQuery) && get_class($doQuery) == "PDOStatement") {
+ if (self::$_returnRawData && is_object($doQuery) && get_class($doQuery) == "PDOStatement") {
return $doQuery;
}
- DB::$last_num_rows = (self::$fullRowCount === false) ? $db->num_rows : $db->getFullRowCount($query);
+ DB::$last_num_rows = (self::$_fullRowCount === false) ? $db->num_rows : $db->getFullRowCount($query);
if ($db->num_rows == 0) {
self::resetVars();
return false;
}
- if ($db->num_rows == 1 && self::$retArray === false) {
+ if ($db->num_rows == 1 && self::$_retArray === false) {
self::resetVars();
- return $db->last_result[0];
+ return $db->_last_result[0];
}
self::resetVars();
- return $db->last_result;
+ return $db->_last_result;
}
+ /**
+ * Restablecer los atributos estáticos
+ */
private static function resetVars()
{
- self::$unbuffered = false;
- self::$fullRowCount = false;
- self::$retArray = false;
+ self::$_returnRawData = false;
+ self::$_fullRowCount = false;
+ self::$_retArray = false;
}
/**
* Realizar una consulta a la BBDD.
*
- * @param string $query con la consulta a realizar
- * @param string $querySource con el nombre de la función que realiza la consulta
- * @param bool $unbuffered realizar la consulta para obtener registro a registro
+ * @param $query string con la consulta a realizar
+ * @param $querySource string con el nombre de la función que realiza la consulta
+ * @param $getRawData bool realizar la consulta para obtener registro a registro
* @return false|int devuelve bool si hay un error. Devuelve int con el número de registros
- * @throws SPDatabaseException
+ * @throws SPException
*/
- public function doQuery(&$query, $querySource, $unbuffered = false)
+ public function doQuery(&$query, $querySource, $getRawData = false)
{
$isSelect = preg_match("/^(select|show)\s/i", $query);
// Limpiar valores de caché y errores
- $this->last_result = array();
+ $this->_last_result = array();
try {
$queryRes = $this->prepareQueryData($query);
- } catch (SPDatabaseException $e) {
- throw new SPDatabaseException($e->getMessage(), $e->getCode());
+ } catch (SPException $e) {
+ throw $e;
}
if ($isSelect) {
- if (!$unbuffered) {
+ if (!$getRawData) {
$this->num_fields = $queryRes->columnCount();
- $this->last_result = $queryRes->fetchAll(PDO::FETCH_OBJ);
+ $this->_last_result = $queryRes->fetchAll(\PDO::FETCH_OBJ);
} else {
return $queryRes;
}
- $queryRes->closeCursor();
+// $queryRes->closeCursor();
-// $this->num_rows = $this->getFullRowCount($query);
- $this->num_rows = count($this->last_result);
-
-// return $this->num_rows;
+ $this->num_rows = count($this->_last_result);
}
}
/**
* Asociar los parámetros de la consulta utilizando el tipo adecuado
*
- * @param &$query
- * @param $isCount
+ * @param &$query string La consulta a realizar
+ * @param $isCount bool Indica si es una consulta de contador de registros
* @return bool
- * @throws SPDatabaseException
+ * @throws SPException
*/
private function prepareQueryData(&$query, $isCount = false)
{
@@ -313,11 +236,11 @@ class DB
try {
$db = DBConnectionFactory::getFactory()->getConnection();
- if (is_array($this->stData)) {
+ if (is_array($this->_stData)) {
$sth = $db->prepare($query);
$paramIndex = 0;
- foreach ($this->stData as $param => $value) {
+ foreach ($this->_stData as $param => $value) {
// Si la clave es un número utilizamos marcadores de posición "?" en
// la consulta. En caso contrario marcadores de nombre
$param = (is_int($param)) ? $param + 1 : ':' . $param;
@@ -327,13 +250,13 @@ class DB
}
if ($param == 'blobcontent') {
- $sth->bindValue($param, $value, PDO::PARAM_LOB);
+ $sth->bindValue($param, $value, \PDO::PARAM_LOB);
} elseif (is_int($value)) {
- //error_log("INT: " . $param . " -> " . $value);
- $sth->bindValue($param, $value, PDO::PARAM_INT);
+// error_log("INT: " . $param . " -> " . $value);
+ $sth->bindValue($param, $value, \PDO::PARAM_INT);
} else {
- //error_log("STR: " . $param . " -> " . $value);
- $sth->bindValue($param, $value, PDO::PARAM_STR);
+// error_log("STR: " . $param . " -> " . $value);
+ $sth->bindValue($param, $value, \PDO::PARAM_STR);
}
$paramIndex++;
@@ -347,26 +270,24 @@ class DB
DB::$lastId = $db->lastInsertId();
return $sth;
- } catch (PDOException $e) {
+ } catch (\Exception $e) {
error_log("Exception: " . $e->getMessage());
- throw new SPDatabaseException($e->getMessage());
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode());
}
-
- return false;
}
/**
* Método para registar los eventos de BD en el log
*
- * @param $query
- * @param $errorMsg
- * @param $errorCode
+ * @param $query string La consulta que genera el error
+ * @param $errorMsg string El mensaje de error
+ * @param $errorCode int El código de error
*/
- private function logDBException($query, $errorMsg, $errorCode)
+ private static function logDBException($query, $errorMsg, $errorCode, $querySource)
{
- $message['action'] = $this->querySource;
+ $message['action'] = $querySource;
$message['text'][] = $errorMsg . '(' . $errorCode . ')';
- $message['text'][] = "SQL: " . DB::escape($query);
+ $message['text'][] = "SQL: " . self::escape($query);
error_log($query);
error_log($errorMsg);
@@ -375,7 +296,7 @@ class DB
/**
* Escapar una cadena de texto con funciones de mysqli.
*
- * @param string $str con la cadena a escapar
+ * @param $str string con la cadena a escapar
* @return string con la cadena escapada
*/
public static function escape($str)
@@ -384,7 +305,7 @@ class DB
$db = DBConnectionFactory::getFactory()->getConnection();
return $db->quote(trim($str));
- } catch (SPDatabaseException $e) {
+ } catch (SPException $e) {
return $str;
}
}
@@ -392,8 +313,9 @@ class DB
/**
* Obtener el número de filas de una consulta realizada
*
+ * @param &$query string La consulta para contar los registros
* @return int Número de files de la consulta
- * @throws SPDatabaseException
+ * @throws SPException
*/
private function getFullRowCount(&$query)
{
@@ -401,6 +323,7 @@ class DB
return 0;
}
+ $num = 0;
$patterns = array(
'/(LIMIT|ORDER BY|GROUP BY).*/i',
'/SELECT DISTINCT\s([\w_]+),.* FROM/i',
@@ -413,7 +336,7 @@ class DB
try {
$db = DBConnectionFactory::getFactory()->getConnection();
- if (!is_array($this->stData)) {
+ if (!is_array($this->_stData)) {
$queryRes = $db->query($query);
$num = intval($queryRes->fetchColumn());
} else {
@@ -425,23 +348,21 @@ class DB
$queryRes->closeCursor();
return $num;
- } catch (PDOException $e) {
+ } catch (SPException $e) {
error_log("Exception: " . $e->getMessage());
- throw new SPDatabaseException($e->getMessage());
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode());
}
-
- return 0;
}
/**
* Realizar una consulta y devolver el resultado sin datos
*
- * @param $query
- * @param $querySource
- * @param bool $unbuffered
+ * @param $query string La consulta a realizar
+ * @param $querySource string La función orígen de la consulta
+ * @param $getRawData bool Si se deben de obtener los datos como PDOStatement
* @return bool
*/
- public static function getQuery($query, $querySource, &$data = null, $unbuffered = false)
+ public static function getQuery($query, $querySource, &$data = null, $getRawData = false)
{
if (empty($query)) {
return false;
@@ -449,15 +370,14 @@ class DB
try {
$db = new DB();
- $db->querySource = $querySource;
- $db->stData = $data;
- $db->doQuery($query, $querySource, $unbuffered);
+ $db->_querySource = $querySource;
+ $db->_stData = $data;
+ $db->doQuery($query, $querySource, $getRawData);
DB::$last_num_rows = $db->num_rows;
- } catch (SPDatabaseException $e) {
- $db->logDBException($query, $e->getMessage(), $e->getCode());
-
- DB::$txtError = $e->getMessage();
- DB::$numError = $e->getCode();
+ } catch (SPException $e) {
+ self::logDBException($query, $e->getMessage(), $e->getCode(), $querySource);
+ self::$txtError = $e->getMessage();
+ self::$numError = $e->getCode();
return false;
}
@@ -465,14 +385,22 @@ class DB
return true;
}
- public static function setUnbuffered($on = true)
+ /**
+ * Establecer si se devuelven los datos obtenidos como PDOStatement
+ *
+ * @param bool $on
+ */
+ public static function setReturnRawData($on = true)
{
- self::$unbuffered = (bool)$on;
+ self::$_returnRawData = (bool)$on;
}
+ /**
+ * Establecer si es necesario contar el número total de resultados devueltos
+ */
public static function setFullRowCount()
{
- self::$fullRowCount = true;
+ self::$_fullRowCount = true;
}
/**
@@ -498,7 +426,7 @@ class DB
$dbinfo[$val] = $db->getAttribute(constant('PDO::ATTR_' . $val));
}
- } catch (SPDatabaseException $e) {
+ } catch (SPException $e) {
return $dbinfo;
}
@@ -512,6 +440,6 @@ class DB
*/
public function setParamData(&$data)
{
- $this->stData = $data;
+ $this->_stData = $data;
}
}
diff --git a/inc/DBConnectionFactory.class.php b/inc/DBConnectionFactory.class.php
new file mode 100644
index 00000000..be026bda
--- /dev/null
+++ b/inc/DBConnectionFactory.class.php
@@ -0,0 +1,105 @@
+.
+ *
+ */
+
+namespace SP;
+
+defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
+
+/**
+ * Class DBConnectionFactory
+ *
+ * Esta clase se encarga de crear las conexiones a la BD
+ */
+class DBConnectionFactory
+{
+ private static $_factory;
+ private $_db;
+
+ /**
+ * Obtener una instancia de la clase
+ *
+ * @return DBConnectionFactory
+ */
+ public static function getFactory()
+ {
+ if (!self::$_factory) {
+// FIXME
+// error_log('NEW FACTORY');
+ self::$_factory = new DBConnectionFactory();
+ }
+
+ return self::$_factory;
+ }
+
+ /**
+ * Realizar la conexión con la BBDD.
+ * Esta función utiliza PDO para conectar con la base de datos.
+ *
+ * @throws SPException
+ * @return object|bool
+ */
+
+ public function getConnection()
+ {
+ if (!$this->_db) {
+// FIXME
+// error_log('NEW DB_CONNECTION');
+ $isInstalled = Config::getValue('installed');
+
+ $dbhost = Config::getValue('dbhost');
+ $dbuser = Config::getValue('dbuser');
+ $dbpass = Config::getValue('dbpass');
+ $dbname = Config::getValue('dbname');
+ $dbport = Config::getValue('dbport', 3306);
+
+ if (empty($dbhost) || empty($dbuser) || empty($dbpass) || empty($dbname)) {
+ if ($isInstalled) {
+ Init::initError(_('No es posible conectar con la BD'), _('Compruebe los datos de conexión'));
+ } else {
+ throw new SPException(SPException::SP_CRITICAL, _('No es posible conectar con la BD'), _('Compruebe los datos de conexión'));
+ }
+ }
+
+ try {
+ $dsn = 'mysql:host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname . ';charset=utf8';
+// $this->db = new PDO($dsn, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
+ $this->_db = new \PDO($dsn, $dbuser, $dbpass);
+ } catch (\Exception $e) {
+ if ($isInstalled) {
+ if ($this->_db->connect_errno === 1049) {
+ Config::setValue('installed', '0');
+ }
+
+ Init::initError(_('No es posible conectar con la BD'), 'Error ' . $e->getCode() . ': ' . $e->getMessage());
+ } else {
+ throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode());
+ }
+ }
+ }
+
+ $this->_db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+ return $this->_db;
+ }
+}
\ No newline at end of file
diff --git a/inc/Files.class.php b/inc/Files.class.php
index 36738e69..b604d4ed 100644
--- a/inc/Files.class.php
+++ b/inc/Files.class.php
@@ -3,8 +3,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
@@ -24,17 +24,19 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar operaciones con archivos de las cuentas de sysPass
*/
-class SP_Files
+class Files
{
/**
* Guardar un archivo en la BBDD.
*
- * @param int $accountId
+ * @param int $accountId
* @param array $fileData con los datos y el contenido del archivo
* @return bool
*/
@@ -62,8 +64,8 @@ class SP_Files
$message['text'][] = _('Tipo') . ": " . $fileData['type'];
$message['text'][] = _('Tamaño') . ": " . round($fileData['size'] / 1024, 2) . " KB";
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -110,8 +112,8 @@ class SP_Files
$message['text'][] = _('Tipo') . ": " . $fileInfo->accfile_type;
$message['text'][] = _('Tamaño') . ": " . round($fileInfo->accfile_size / 1024, 2) . " KB";
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
diff --git a/inc/Groups.class.php b/inc/Groups.class.php
index c11f4038..d99ee0e3 100644
--- a/inc/Groups.class.php
+++ b/inc/Groups.class.php
@@ -24,12 +24,14 @@
*
*/
+namespace SP;
+
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones sobre los grupos de usuarios.
*/
-class SP_Groups
+class Groups
{
static $queryRes;
static $groupId;
@@ -67,7 +69,7 @@ class SP_Groups
/**
* Obtener los grupos de usuarios.
*
- * @param int $groupId opcional, con el Id del grupo a consultar
+ * @param int $groupId opcional, con el Id del grupo a consultar
* @param bool $returnArray opcional, si se debe de devolver un array asociativo
* @return false|array con la lista de grupos
*/
@@ -147,10 +149,10 @@ class SP_Groups
self::$queryLastId = DB::$lastId;
$message['action'] = _('Nuevo Grupo');
- $message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . self::$groupName;
+ $message['text'][] = Html::strongText(_('Grupo') . ': ') . self::$groupName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -177,10 +179,10 @@ class SP_Groups
self::$queryLastId = DB::$lastId;
$message['action'] = _('Modificar Grupo');
- $message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . $groupName . ' > ' . self::$groupName;
+ $message['text'][] = Html::strongText(_('Grupo') . ': ') . $groupName . ' > ' . self::$groupName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -226,10 +228,10 @@ class SP_Groups
self::$queryLastId = DB::$lastId;
$message['action'] = _('Eliminar Grupo');
- $message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . $groupName;
+ $message['text'][] = Html::strongText(_('Grupo') . ': ') . $groupName;
- SP_Log::wrLogInfo($message);
- SP_Common::sendEmail($message);
+ Log::wrLogInfo($message);
+ Common::sendEmail($message);
return true;
}
@@ -330,8 +332,8 @@ class SP_Groups
/**
* Actualizar la asociación de grupos con cuentas.
*
- * @param int $accountId con el Id de la cuenta
- * @param array $groupsId con los grupos de la cuenta
+ * @param int $accountId con el Id de la cuenta
+ * @param array $groupsId con los grupos de la cuenta
* @return bool
*/
public static function updateGroupsForAccount($accountId, $groupsId)
@@ -346,8 +348,8 @@ class SP_Groups
/**
* Eliminar la asociación de grupos con cuentas.
*
- * @param int $accountId con el Id de la cuenta
- * @param array $groupsId opcional con los grupos de la cuenta
+ * @param int $accountId con el Id de la cuenta
+ * @param array $groupsId opcional con los grupos de la cuenta
* @return bool
*/
public static function deleteGroupsForAccount($accountId, $groupsId = null)
@@ -371,13 +373,13 @@ class SP_Groups
/**
* Crear asociación de grupos con cuentas.
*
- * @param int $accountId con el Id de la cuenta
- * @param array $groupsId con los grupos de la cuenta
+ * @param int $accountId con el Id de la cuenta
+ * @param array $groupsId con los grupos de la cuenta
* @return bool
*/
public static function addGroupsForAccount($accountId, $groupsId)
{
- if(!is_array($groupsId)){
+ if (!is_array($groupsId)) {
return true;
}
@@ -420,12 +422,12 @@ class SP_Groups
$queryRes = DB::getResults($query, __FUNCTION__, $data);
- if ($queryRes === false){
- return false;
+ if ($queryRes === false) {
+ return array();
}
foreach ($queryRes as $group) {
- $groups[]= $group->accgroup_groupId;
+ $groups[] = $group->accgroup_groupId;
}
return $groups;
diff --git a/inc/Html.class.php b/inc/Html.class.php
index 1dcf7a32..b9437cf6 100644
--- a/inc/Html.class.php
+++ b/inc/Html.class.php
@@ -1,10 +1,9 @@
' . $arrSelectProp["label"] . '';
- echo '