From 399e579f9c79a7d2575473388a46ca50c3dc87a3 Mon Sep 17 00:00:00 2001 From: nuxsmin Date: Sun, 21 Jun 2015 04:45:55 +0200 Subject: [PATCH] * [ADD] Fully MVC. * [ADD] Abstract classes and interfaces for better code structure. * [MOD] Actions handled as integers not strings and are consistent accross app modules. * [MOD] Classes' names where modified. Namespaces where added for better handling. * [ADD] Common exception class for the whole app. * [ADD] New base file for app initialization. * [MOD] Speed improvements. --- ajax/ajax_accountSave.php | 299 +++---- ajax/ajax_appMgmtData.php | 111 +-- ajax/ajax_appMgmtSave.php | 445 +++++----- ajax/ajax_backup.php | 35 +- ajax/ajax_checkLdap.php | 33 +- ajax/ajax_checkUpds.php | 9 +- ajax/ajax_configSave.php | 325 ++++--- ajax/ajax_doLogin.php | 88 +- ajax/ajax_eventlog.php | 21 +- ajax/ajax_files.php | 63 +- ajax/ajax_getContent.php | 104 +-- ajax/ajax_getFiles.php | 17 +- ajax/ajax_import.php | 2 +- ajax/ajax_migrate.php | 2 +- ajax/ajax_passReset.php | 63 +- ajax/ajax_search.php | 15 +- ajax/ajax_sendRequest.php | 55 +- ajax/ajax_usrpass.php | 63 +- ajax/ajax_viewpass.php | 55 +- css/css.php | 7 +- inc/Account.class.php | 674 +++++++++++++++ inc/AccountBase.class.php | 578 +++++++++++++ inc/AccountHistory.class.php | 510 +++++++++++ inc/AccountInterface.class.php | 42 + inc/AccountSearch.class.php | 225 +++++ inc/Accounts.class.php | 1314 ----------------------------- inc/Acl.class.php | 85 +- inc/ActionsInterface.class.php | 81 ++ inc/Auth.class.php | 52 +- inc/Backup.class.php | 64 +- inc/Base.php | 38 + inc/Cache.class.php | 10 +- inc/Category.class.php | 28 +- inc/Common.class.php | 66 +- inc/Config.class.php | 125 +-- inc/Controller.class.php | 83 +- inc/Crypt.class.php | 25 +- inc/Customer.class.php | 25 +- inc/DB.class.php | 278 +++--- inc/DBConnectionFactory.class.php | 105 +++ inc/Files.class.php | 18 +- inc/Groups.class.php | 44 +- inc/Html.class.php | 250 +----- inc/Import.class.php | 245 +++--- inc/{Init.php => Init.class.php} | 264 +++--- inc/Installer.class.php | 250 +++--- inc/KeepassImport.class.php | 47 +- inc/KeepassXImport.class.php | 50 +- inc/Ldap.class.php | 152 ++-- inc/Log.class.php | 16 +- inc/Migrate.class.php | 260 +++--- inc/Profiles.class.php | 31 +- inc/SPException.class.php | 58 ++ inc/Session.class.php | 14 +- inc/Template.class.php | 132 +-- inc/Upgrade.class.php | 42 +- inc/Users.class.php | 122 +-- inc/Util.class.php | 248 +++--- inc/tpl/account.inc | 134 ++- inc/tpl/backup.inc | 7 +- inc/tpl/config.inc | 106 ++- inc/tpl/debug.inc | 9 +- inc/tpl/editpass.inc | 12 +- inc/tpl/encryption.inc | 19 +- inc/tpl/eventlog.inc | 149 ++-- inc/tpl/files.inc | 6 +- inc/tpl/import.inc | 21 +- inc/tpl/info.inc | 6 +- inc/tpl/install.inc | 26 +- inc/tpl/login.inc | 8 +- inc/tpl/menu.inc | 12 +- inc/tpl/mgmttabs.inc | 6 +- inc/tpl/passreset.inc | 15 +- inc/tpl/request.inc | 10 +- inc/tpl/search.inc | 35 +- inc/tpl/searchbox.inc | 10 +- inc/tpl/sessionbar.inc | 3 +- inc/tpl/upgrade.inc | 2 +- inc/tpl/users.inc | 11 +- inc/tpl/userspass.inc | 2 +- index.php | 5 +- js/functions.js | 4 +- js/js.php | 9 +- web/AccountC.class.php | 208 +++-- web/AccountsMgmtC.class.php | 32 +- web/ConfigC.class.php | 102 +-- web/EventlogC.class.php | 48 +- web/MainC.class.php | 56 +- web/SearchC.class.php | 146 ++-- web/UsersMgmtC.class.php | 35 +- 90 files changed, 5245 insertions(+), 4472 deletions(-) create mode 100644 inc/Account.class.php create mode 100644 inc/AccountBase.class.php create mode 100644 inc/AccountHistory.class.php create mode 100644 inc/AccountInterface.class.php create mode 100644 inc/AccountSearch.class.php delete mode 100644 inc/Accounts.class.php create mode 100644 inc/ActionsInterface.class.php create mode 100644 inc/Base.php create mode 100644 inc/DBConnectionFactory.class.php rename inc/{Init.php => Init.class.php} (75%) create mode 100644 inc/SPException.class.php 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('
' . $fileData . '
'); } 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 ''; + echo ''; echo ''; return; } - if ($arrSelectProp["label"]) { - echo ''; + if ($properties['label']) { + echo ''; } - echo ''; + echo ''; - $selectedId = (isset($arrSelectProp["selected"])) ? $arrSelectProp["selected"] : ""; + $selectedId = (isset($properties['selected'])) ? $properties['selected'] : ""; - foreach ($arrValues as $valueId => $valueName) { + foreach ($values as $valueId => $valueName) { if ($useValue) { - $selected = ($valueId == $selectedId) ? "SELECTED" : ""; + $selected = ($valueId == $selectedId) ? 'SELECTED' : ''; echo ''; } else { - $selected = ($valueName == $selectedId) ? "SELECTED" : ""; + $selected = ($valueName == $selectedId) ? 'SELECTED' : ''; echo ''; } } @@ -80,84 +80,6 @@ class SP_Html echo ''; } - /** - * Crea la barra de navegación para búsqueda de cuentas. - * - * @param int $intSortKey con el número de campo del filro - * @param int $intCur con el número de página actual - * @param int $intTotal con el número total de páginas - * @param int $intLimit con el límite de registros a mostrar - * @param int $intTime con el tiempo de carga de los resultados - * @param bool $filterOn opcional con el estado del filtrado - * @return none - */ - public static function printQuerySearchNavBar($intSortKey, $intCur, $intTotal, $intLimit, $intTime, $filterOn = false) - { -// SP_Html::printQuerySearchNavBar($sortKey, $limitStart, SP_Accounts::$queryNumRows, $limitCount, $totalTime, $filterOn); - - $firstPage = ceil(($intCur + 1) / $intLimit); - $lastPage = ceil($intTotal / $intLimit); - $globalOn = SP_Common::parseParams('p', 'gsearch', 0, false, 1); - - echo ''; - } - - /** - * Crea la barra de navegación para el registro de eventos. - * - * @param int $intCur con el número de página actual - * @param int $intTotal con el número total de páginas - * @param int $intTime con el tiempo de carga de los resultados - * @return none - */ - public static function printQueryLogNavBar($intCur, $intTotal, $intTime = 0) - { - $intLimit = 50; - $firstPage = ceil(($intCur + 1) / $intLimit); - $lastPage = ceil($intTotal / $intLimit); - - echo ''; - } - /** * Limpia los datos recibidos de un formulario. * @@ -171,7 +93,7 @@ class SP_Html } if (is_array($data)) { - array_walk_recursive($data, 'SP_Html::sanitize'); + array_walk_recursive($data, '\SP\Html::sanitize'); } else { $data = strip_tags($data); @@ -206,28 +128,11 @@ class SP_Html return $data; } - /** - * Muestra una barra de información con los registros y tiempo de la consulta. - * - * @param int $intTotal con el total de registros devueltos - * @param int $startTime con el tiempo de inicio de la consulta - * @return none - */ - public static function printQueryInfoBar($intTotal, $startTime) - { - $endTime = microtime(); - $totalTime = round($endTime - $startTime, 5); - - echo ''; - } - /** * Truncar un texto a una determinada longitud. * * @param string $str con la cadena a truncar - * @param int $len con la longitud máxima de la cadena + * @param int $len con la longitud máxima de la cadena * @return string con el texto truncado */ public static function truncate($str, $len) @@ -256,103 +161,6 @@ class SP_Html return $hex; // returns the hex value including the number sign (#) } - /** - * Devolver una tabla con el resultado de una consulta y acciones. - * - * @param array $arrTableProp con las propiedades de la tabla - * @param array $queryItems con los resultados de la consulta - * @return none - */ - public static function getQueryTable($arrTableProp, $queryItems) - { - $sk = SP_Common::getSessionKey(true); - $maxNumActions = 3; - - echo '
'; - echo '
    '; - echo '
  • '; - echo '
'; - echo '
'; - - if ($arrTableProp["header"]) { - echo '
' . $arrTableProp["header"] . '
'; - } - - echo '
'; - echo '
'; - echo '
    '; - - $cellWidth = floor(65 / count($arrTableProp["tblHeaders"])); - - foreach ($arrTableProp["tblHeaders"] as $header) { - if (is_array($header)) { - echo '
  • ' . $header['name'] . '
  • '; - } else { - echo '
  • ' . $header . '
  • '; - } - } - - echo '
'; - echo '
'; - - echo '
'; - - foreach ($queryItems as $item) { - $intId = $item->$arrTableProp["tblRowSrcId"]; - $action_check = array(); - $numActions = count($arrTableProp["actions"]); - $classActionsOptional = ($numActions > $maxNumActions) ? 'actions-optional' : ''; - - echo '
    '; - - foreach ($arrTableProp["tblRowSrc"] as $rowSrc) { - // If row is an array handle images in it - if (is_array($rowSrc)) { - echo '
  • '; - foreach ($rowSrc as $rowName => $imgProp) { - if ($item->$rowName) { - echo ''; - $action_check[$rowName] = 1; - } - } - echo '
  • '; - } else { - echo '
  • '; - echo ($item->$rowSrc) ? $item->$rowSrc : ' '; // Fix height - echo '
  • '; - } - } - - echo '
  • '; - //echo '
  • '; - foreach ($arrTableProp["actions"] as $action => $function) { - switch ($action) { - case "view": - echo ''; - break; - case "edit": - echo ''; - break; - case "del": - echo ''; - break; - case "pass": - if (isset($action_check['user_isLdap'])) { - break; - } - - echo ''; - break; - } - } - echo ($numActions > $maxNumActions) ? '' : ''; - echo '
  • '; - echo '
'; - } - - echo '
'; - } - /** * Devolver una cadena con el tag HTML strong. * @@ -367,9 +175,9 @@ class SP_Html /** * Devolver un link HTML. * - * @param string $text con la cadena de texto - * @param string $link con el destino del enlace - * @param string $title con el título del enlace + * @param string $text con la cadena de texto + * @param string $link con el destino del enlace + * @param string $title con el título del enlace * @param string $attribs con atributos del enlace * @return string */ diff --git a/inc/Import.class.php b/inc/Import.class.php index 0775ef84..35fde2c0 100644 --- a/inc/Import.class.php +++ b/inc/Import.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,48 +24,18 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); -/** - * Extender la clase Exception para mostrar ayuda en los mensajes - */ -class ImportException extends Exception -{ - private $type; - private $hint; - - public function __construct($type, $message, $hint, $code = 0, Exception $previous = null) - { - $this->type = $type; - $this->hint = $hint; - parent::__construct($message, $code, $previous); - } - - public function __toString() - { - return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; - } - - public function getHint() - { - return $this->hint; - } - - public function getType() - { - return $this->type; - } - -} - /** * Esta clase es la encargada de importar cuentas. */ -class SP_Import +class Import { - private static $result = array(); - private static $fileContent; - private static $tmpFile; + private static $_result = array(); + private static $_fileContent; + private static $_tmpFile; /** * Iniciar la importación de cuentas. @@ -77,32 +47,32 @@ class SP_Import { try { self::readDataFromFile($fileData); - } catch (ImportException $e) { + } catch (SPException $e) { $message['action'] = _('Importar Cuentas'); $message['text'][] = $e->getMessage(); - SP_Log::wrLogInfo($message); - self::$result['error'][] = array('type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint()); - return (self::$result); + Log::wrLogInfo($message); + self::$_result['error'][] = array('type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint()); + return (self::$_result); } - self::$result['ok'][] = _('Importación finalizada'); - self::$result['ok'][] = _('Revise el registro de eventos para más detalles'); + self::$_result['ok'][] = _('Importación finalizada'); + self::$_result['ok'][] = _('Revise el registro de eventos para más detalles'); - return (self::$result); + return (self::$_result); } /** * Leer los datos del archivo. * * @param array $fileData con los datos del archivo - * @throws ImportException + * @throws SPException * @return bool */ private static function readDataFromFile(&$fileData) { if (!is_array($fileData)) { - throw new ImportException('critical', _('Archivo no subido correctamente'), _('Verifique los permisos del usuario del servidor web')); + throw new SPException(SPException::SP_CRITICAL, _('Archivo no subido correctamente'), _('Verifique los permisos del usuario del servidor web')); } if ($fileData['name']) { @@ -110,7 +80,11 @@ class SP_Import $fileExtension = strtoupper(pathinfo($fileData['name'], PATHINFO_EXTENSION)); if ($fileExtension != 'CSV' && $fileExtension != 'XML') { - throw new ImportException('critical', _('Tipo de archivo no soportado'), _('Compruebe la extensión del archivo')); + throw new SPException( + SPException::SP_CRITICAL, + _('Tipo de archivo no soportado'), + _('Compruebe la extensión del archivo') + ); } } @@ -119,26 +93,38 @@ class SP_Import if (!file_exists($tmpName) || !is_readable($tmpName)) { // Registramos el máximo tamaño permitido por PHP - SP_Util::getMaxUpload(); + Util::getMaxUpload(); - throw new ImportException('critical', _('Error interno al leer el archivo'), _('Compruebe la configuración de PHP para subir archivos')); + throw new SPException( + SPException::SP_CRITICAL, + _('Error interno al leer el archivo'), + _('Compruebe la configuración de PHP para subir archivos') + ); } - if ($fileData['type'] === 'text/csv' || $fileData['type'] === 'application/vnd.ms-excel'){ + if ($fileData['type'] === 'text/csv' || $fileData['type'] === 'application/vnd.ms-excel') { // Leemos el archivo a un array - self::$fileContent = file($tmpName); + self::$_fileContent = file($tmpName); - if (!is_array(self::$fileContent)) { - throw new ImportException('critical', _('Error interno al leer el archivo'), _('Compruebe los permisos del directorio temporal')); + if (!is_array(self::$_fileContent)) { + throw new SPException( + SPException::SP_CRITICAL, + _('Error interno al leer el archivo'), + _('Compruebe los permisos del directorio temporal') + ); } // Obtenemos las cuentas desde el archivo CSV self::parseFileData(); - } elseif ($fileData['type'] === 'text/xml'){ - self::$tmpFile = $tmpName; + } elseif ($fileData['type'] === 'text/xml') { + self::$_tmpFile = $tmpName; // Analizamos el XML y seleccionamos el formato a importar self::detectXMLFormat(); - } else{ - throw new ImportException('critical', _('Tipo mime no soportado'), _('Compruebe el formato del archivo')); + } else { + throw new SPException( + SPException::SP_CRITICAL, + _('Tipo mime no soportado'), + _('Compruebe el formato del archivo') + ); } return true; @@ -147,24 +133,28 @@ class SP_Import /** * Leer los datos importados y formatearlos. * - * @throws ImportException + * @throws SPException * @return bool */ private static function parseFileData() { - foreach (self::$fileContent as $data) { + foreach (self::$_fileContent as $data) { $fields = explode(';', $data); if (count($fields) < 7) { - throw new ImportException('critical', _('El número de campos es incorrecto'), _('Compruebe el formato del archivo CSV')); + throw new SPException( + SPException::SP_CRITICAL, + _('El número de campos es incorrecto'), + _('Compruebe el formato del archivo CSV') + ); } - if (!self::addAccountData($fields)){ + if (!self::addAccountData($fields)) { $message['action'] = _('Importar Cuentas'); $message['text'][] = _('Error importando cuenta'); $message['text'][] = $data; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); unset($message); } @@ -177,48 +167,48 @@ class SP_Import * Crear una cuenta con los datos obtenidos. * * @param array $data con los datos de la cuenta - * @throws ImportException + * @throws SPException * @return bool */ public static function addAccountData($data) { // Datos del Usuario - $userId = SP_Common::parseParams('s', 'uid', 0); - $groupId = SP_Common::parseParams('s', 'ugroup', 0); + $userId = Common::parseParams('s', 'uid', 0); + $groupId = Common::parseParams('s', 'ugroup', 0); // Asignamos los valores del array a variables list($accountName, $customerName, $categoryName, $url, $username, $password, $notes) = $data; // Comprobamos si existe el cliente o lo creamos - SP_Customer::$customerName = $customerName; - if (SP_Customer::checkDupCustomer()) { - $customerId = SP_Customer::getCustomerByName(); + Customer::$customerName = $customerName; + if (Customer::checkDupCustomer()) { + $customerId = Customer::getCustomerByName(); } else { - SP_Customer::addCustomer(); - $customerId = SP_Customer::$customerLastId; + Customer::addCustomer(); + $customerId = Customer::$customerLastId; } // Comprobamos si existe la categoría o la creamos - $categoryId = SP_Category::getCategoryIdByName($categoryName); + $categoryId = Category::getCategoryIdByName($categoryName); if ($categoryId == 0) { - SP_Category::$categoryName = $categoryName; - SP_Category::addCategory($categoryName); - $categoryId = SP_Category::$categoryLastId; + Category::$categoryName = $categoryName; + Category::addCategory($categoryName); + $categoryId = Category::$categoryLastId; } $pass = self::encryptPass($password); - $account = new SP_Accounts; - $account->accountName = $accountName; - $account->accountCustomerId = $customerId; - $account->accountCategoryId = $categoryId; - $account->accountLogin = $username; - $account->accountUrl = $url; - $account->accountPass = $pass['pass']; - $account->accountIV = $pass['IV']; - $account->accountNotes = $notes; - $account->accountUserId = $userId; - $account->accountUserGroupId = $groupId; + $account = new Account; + $account->setAccountName($accountName); + $account->setAccountCustomerId($customerId); + $account->setAccountCategoryId($categoryId); + $account->setAccountLogin($username); + $account->setAccountUrl($url); + $account->setAccountPass($pass['pass']); + $account->setAccountIV($pass['IV']); + $account->setAccountNotes($notes); + $account->setAccountUserId($userId); + $account->setAccountUserGroupId($groupId); // Creamos la cuenta return $account->createAccount(); @@ -228,63 +218,55 @@ class SP_Import * Encriptar la clave de una cuenta. * * @param string $password con la clave de la cuenta - * @throws ImportException + * @throws SPException * @return array con la clave y el IV */ private static function encryptPass($password) { - if (empty($password)){ + if (empty($password)) { return array('pass' => '', 'IV' => ''); } // Comprobar el módulo de encriptación - if (!SP_Crypt::checkCryptModule()) { - throw new ImportException('critical', _('Error interno'), _('No se puede usar el módulo de encriptación')); + if (!Crypt::checkCryptModule()) { + throw new SPException( + SPException::SP_CRITICAL, + _('Error interno'), + _('No se puede usar el módulo de encriptación') + ); } // Encriptar clave - $data['pass'] = SP_Crypt::mkEncrypt($password); + $data['pass'] = Crypt::mkEncrypt($password); if (!empty($password) && ($data['pass'] === false || is_null($data['pass']))) { - throw new ImportException('critical', _('Error interno'), _('Error al generar datos cifrados')); + throw new SPException( + SPException::SP_CRITICAL, + _('Error interno'), + _('Error al generar datos cifrados') + ); } - $data['IV'] = SP_Crypt::$strInitialVector; + $data['IV'] = Crypt::$strInitialVector; return $data; } - /** - * Leer el archivo de KeePass a un objeto XML. - * - * @throws ImportException - * @return object Con los datos del archivo XML - */ - private static function readXMLFile() - { - if ($xmlFile = simplexml_load_file(self::$tmpFile)){ - return $xmlFile; - } else{ - throw new ImportException('critical', _('Error interno'), _('No es posible procesar el archivo XML')); - } - } - /** * Detectar la aplicación que generó el XML. * - * @throws ImportException - * @return none + * @throws SPException */ private static function detectXMLFormat() { $xml = self::readXMLFile(); - if ( $xml->Meta->Generator == 'KeePass' ){ - SP_KeepassImport::addKeepassAccounts($xml); - } else if ($xmlApp = self::parseFileHeader()){ + if ($xml->Meta->Generator == 'KeePass') { + KeepassImport::addKeepassAccounts($xml); + } else if ($xmlApp = self::parseFileHeader()) { switch ($xmlApp) { case 'keepassx_database': - SP_KeepassXImport::addKeepassXAccounts($xml); + KeepassXImport::addKeepassXAccounts($xml); break; case 'revelationdata': error_log('REVELATION'); @@ -292,8 +274,31 @@ class SP_Import default: break; } - } else{ - throw new ImportException('critical', _('Archivo XML no soportado'), _('No es posible detectar la aplicación que exportó los datos')); + } else { + throw new SPException( + SPException::SP_CRITICAL, + _('Archivo XML no soportado'), + _('No es posible detectar la aplicación que exportó los datos') + ); + } + } + + /** + * Leer el archivo de KeePass a un objeto XML. + * + * @throws SPException + * @return object Con los datos del archivo XML + */ + private static function readXMLFile() + { + if ($xmlFile = simplexml_load_file(self::$_tmpFile)) { + return $xmlFile; + } else { + throw new SPException( + SPException::SP_CRITICAL, + _('Error interno'), + _('No es posible procesar el archivo XML') + ); } } @@ -304,16 +309,16 @@ class SP_Import */ private static function parseFileHeader() { - $handle = @fopen(self::$tmpFile, "r"); + $handle = @fopen(self::$_tmpFile, "r"); $headersRegex = '/(KEEPASSX_DATABASE|revelationdata)/i'; - if ( $handle ){ + if ($handle) { // No. de líneas a leer como máximo $maxLines = 5; $count = 0; - while (($buffer = fgets($handle, 4096)) !== false && $count <= $maxLines){ - if ( preg_match($headersRegex,$buffer,$app) ){ + while (($buffer = fgets($handle, 4096)) !== false && $count <= $maxLines) { + if (preg_match($headersRegex, $buffer, $app)) { fclose($handle); return strtolower($app[0]); } diff --git a/inc/Init.php b/inc/Init.class.php similarity index 75% rename from inc/Init.php rename to inc/Init.class.php index f1d0c70a..f300d963 100644 --- a/inc/Init.php +++ b/inc/Init.class.php @@ -23,12 +23,17 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); -define ('EXTENSIONS_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ext'); -class SP_Init +/** + * Clase Init para la inicialización del entorno de sysPass + * + * @package SP + */ +class Init { - /** * @var array Associative array for autoloading. classname => filename */ @@ -62,23 +67,23 @@ class SP_Init /** * @var string */ - private static $SUBURI = ''; + private static $_SUBURI = ''; /** * Inicializar la aplicación. * Esta función inicializa las variables de la aplicación y muestra la página * según el estado en el que se encuentre. - * - * @return none */ - public static function init() + public static function start() { + self::setIncludes(); + if (version_compare(PHP_VERSION, '5.1.2', '>=')) { // Registro del cargador de clases (PHP >= 5.1.2) if (version_compare(PHP_VERSION, '5.3.0', '>=')) { - spl_autoload_register(array('SP_Init', 'sysPassAutoload'), true); + spl_autoload_register(array('SP\Init', 'loadClass'), true); } else { - spl_autoload_register(array('SP_Init', 'sysPassAutoload')); + spl_autoload_register(array('SP\Init', 'loadClass')); } } else { /** @@ -88,7 +93,7 @@ class SP_Init */ function __autoload($classname) { - SP_Init::sysPassAutoload($classname); + \SP\Init::loadClass($classname); } } @@ -159,6 +164,7 @@ class SP_Init // Comprobar la configuración self::checkConfig(); + // Comprobar si está instalado self::checkInstalled(); @@ -180,7 +186,7 @@ class SP_Init $sessionLifeTime = self::getSessionLifeTime(); @ini_set('gc_maxlifetime', (string)$sessionLifeTime); - if (!SP_Config::getValue("installed", false)) { + if (!Config::getValue("installed", false)) { $_SESSION['user_id'] = ''; } @@ -213,7 +219,7 @@ class SP_Init continue; } - $params[] = SP_Html::sanitize($param) . '=' . SP_Html::sanitize($value); + $params[] = Html::sanitize($param) . '=' . Html::sanitize($value); } header("Location: " . self::$WEBROOT . '/index.php?' . implode('&', $params)); @@ -230,7 +236,7 @@ class SP_Init return; } - $controller = new \Controller\MainC(); + $controller = new Controller\MainC(); $controller->getLogin(); $controller->view(); exit(); @@ -238,43 +244,6 @@ class SP_Init } - /** - * SPL autoload. - * Cargador de clases - */ - public static function sysPassAutoload($classname) - { - $classFound = false; - $class = str_ireplace('sp_', '', $classname); - $class = (strrpos($class, '\\')) ? substr($class, strrpos($class, '\\') + 1) : $class; - $classfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . $class . '.class.php'; - -// error_log($class); -// error_log($classfile); - - if (!is_readable($classfile)) { - $includePaths = explode(':', get_include_path()); - - foreach ($includePaths as $path) { - $classfile = $path . DIRECTORY_SEPARATOR . $class . '.class.php'; - if (is_readable($classfile)) { - $classFound = true; - break; - } - } - } else { - $classFound = true; - } - - - if ($classFound === false) { - error_log('Class Autoloader Error: ' . $classfile); - return false; - } - - require_once $classfile; - } - /** * Iniciar la sesión PHP */ @@ -286,7 +255,7 @@ class SP_Init // Si la sesión no puede ser iniciada, devolver un error 500 if (session_start() === false) { - SP_Log::wrLogInfo(_('Sesion'), _('La sesión no puede ser inicializada')); + Log::wrLogInfo(_('Sesion'), _('La sesión no puede ser inicializada')); header('HTTP/1.1 500 Internal Server Error'); @@ -294,39 +263,51 @@ class SP_Init } } + /** + * Devuelve un eror utilizando la plantilla de rror. + * + * @param string $str con la descripción del error + * @param string $hint opcional, con una ayuda sobre el error + */ + public static function initError($str, $hint = '') + { + $tpl = new Template(); + $tpl->append('errors', array('type' => 'critical', 'description' => $str, 'hint' => $hint)); + $controller = new Controller\MainC($tpl); + $controller->getError(true); + $controller->view(); + exit(); + } + /** * Establecer las rutas de la aplicación. * Esta función establece las rutas del sistema de archivos y web de la aplicación. * La variables de clase definidas son $SERVERROOT, $WEBROOT y $SUBURI - * - * @return none */ private static function setPaths() { // Calcular los directorios raíz - self::$SERVERROOT = str_replace("\\", DIRECTORY_SEPARATOR, substr(__DIR__, 0, -4)); +// self::$SERVERROOT = str_replace("\\", DIRECTORY_SEPARATOR, substr(__DIR__, 0, -4)); + $dir = (defined(__DIR__)) ? __DIR__ : dirname(__FILE__); - // Establecer la ruta include correcta - set_include_path(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'inc' . PATH_SEPARATOR . - self::$SERVERROOT . DIRECTORY_SEPARATOR . 'web' . PATH_SEPARATOR . - get_include_path() . PATH_SEPARATOR . self::$SERVERROOT); + self::$SERVERROOT = substr($dir, 0, strripos($dir, '/')); - self::$SUBURI = str_replace("\\", '/', substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(self::$SERVERROOT))); + self::$_SUBURI = str_replace("\\", '/', substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(self::$SERVERROOT))); $scriptName = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; if (substr($scriptName, -1) == '/') { $scriptName .= 'index.php'; // Asegurar que suburi sigue las mismas reglas que scriptName - if (substr(self::$SUBURI, -9) != 'index.php') { - if (substr(self::$SUBURI, -1) != '/') { - self::$SUBURI .= '/'; + if (substr(self::$_SUBURI, -9) != 'index.php') { + if (substr(self::$_SUBURI, -1) != '/') { + self::$_SUBURI .= '/'; } - self::$SUBURI .= 'index.php'; + self::$_SUBURI .= 'index.php'; } } - $pos = strpos($scriptName, self::$SUBURI); + $pos = strpos($scriptName, self::$_SUBURI); if ($pos === false) { $pos = strpos($scriptName, '?'); @@ -345,13 +326,11 @@ class SP_Init /** * Establece el lenguaje de la aplicación. * Esta función establece el lenguaje según esté definido en la configuración o en el navegador. - * - * @returns none */ private static function selectLang() { $browserLang = str_replace("-", "_", substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5)); - $configLang = SP_Config::getValue('sitelang'); + $configLang = Config::getValue('sitelang'); $localesDir = self::$SERVERROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'locales'; // Establecer a en_US si no existe la traducción o no es español @@ -390,8 +369,6 @@ class SP_Init /** * Comprobar el archivo de configuración. * Esta función comprueba que el archivo de configuración exista y los permisos sean correctos. - * - * @return none */ private static function checkConfig() { @@ -408,46 +385,27 @@ class SP_Init //$configPerms = substr(sprintf('%o', fileperms(self::$SERVERROOT.'/config')), -4); $configPerms = decoct(fileperms(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'config') & 0777); - if (!SP_Util::runningOnWindows() && $configPerms != "750") { + if (!Util::runningOnWindows() && $configPerms != "750") { clearstatcache(); self::initError(_('Los permisos del directorio "/config" son incorrectos'), _('Actual:') . ' ' . $configPerms . ' - ' . _('Necesario: 750')); } } - /** - * Devuelve un eror utilizando la plantilla de rror. - * - * @param string $str con la descripción del error - * @param string $hint opcional, con una ayuda sobre el error - * @returns none - */ - public static function initError($str, $hint = '') - { - $tpl = new SP_Template(); - $tpl->append('errors', array('type' => 'critical', 'description' => $str, 'hint' => $hint)); - $controller = new \Controller\MainC($tpl); - $controller->getError(true); - $controller->view(); - exit(); - } - /** * Comprueba que la aplicación esté instalada * Esta función comprueba si la aplicación está instalada. Si no lo está, redirige al instalador. - * - * @return none */ private static function checkInstalled() { // Redirigir al instalador si no está instalada - if (!SP_Config::getValue('installed', false) && self::$SUBURI != '/index.php') { + if (!Config::getValue('installed', false) && self::$_SUBURI != '/index.php') { $url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . self::$WEBROOT . '/index.php'; header("Location: $url"); exit(); - } elseif (!SP_Config::getValue('installed', false) && self::$SUBURI == '/index.php') { + } elseif (!Config::getValue('installed', false) && self::$_SUBURI == '/index.php') { // Comprobar si sysPass está instalada o en modo mantenimiento - if (!SP_Config::getValue('installed', false)) { - $controller = new \Controller\MainC(); + if (!Config::getValue('installed', false)) { + $controller = new Controller\MainC(); $controller->getInstaller(); $controller->view(); exit(); @@ -465,11 +423,11 @@ class SP_Init */ public static function checkMaintenanceMode($check = false) { - if (SP_Config::getValue('maintenance', false)) { + if (Config::getValue('maintenance', false)) { if ($check === true - || SP_Common::parseParams('r', 'isAjax', 0) === 1 - || SP_Common::parseParams('g', 'upgrade', 0) === 1 - || SP_Common::parseParams('g', 'nodbupgrade', 0) === 1 + || Common::parseParams('r', 'isAjax', 0) === 1 + || Common::parseParams('g', 'upgrade', 0) === 1 + || Common::parseParams('g', 'nodbupgrade', 0) === 1 ) { return true; } @@ -486,45 +444,43 @@ class SP_Init /** * Comrpueba y actualiza la versión de la aplicación. - * - * @returns none */ private static function checkVersion() { - if (substr(self::$SUBURI, -9) != 'index.php' || SP_Common::parseParams('g', 'logout', 0) === 1) { + if (substr(self::$_SUBURI, -9) != 'index.php' || Common::parseParams('g', 'logout', 0) === 1) { return; } $update = false; - $configVersion = (int)str_replace('.', '', SP_Config::getValue('version')); - $databaseVersion = (int)str_replace('.', '', SP_Config::getConfigDbValue('version')); - $appVersion = (int)implode(SP_Util::getVersion(true)); + $configVersion = (int)str_replace('.', '', Config::getValue('version')); + $databaseVersion = (int)str_replace('.', '', Config::getConfigDbValue('version')); + $appVersion = (int)implode(Util::getVersion(true)); if ($databaseVersion < $appVersion - && SP_Common::parseParams('g', 'nodbupgrade', 0) === 0 + && Common::parseParams('g', 'nodbupgrade', 0) === 0 ) { - if (SP_Upgrade::needDBUpgrade($databaseVersion)) { + if (Upgrade::needDBUpgrade($databaseVersion)) { if (!self::checkMaintenanceMode(true)) { - if (SP_Config::getValue('upgrade_key', 0) === 0) { - SP_Config::setValue('upgrade_key', sha1(uniqid(mt_rand(), true))); - SP_Config::setValue('maintenance', true); + if (Config::getValue('upgrade_key', 0) === 0) { + Config::setValue('upgrade_key', sha1(uniqid(mt_rand(), true))); + Config::setValue('maintenance', true); } self::initError(_('La aplicación necesita actualizarse'), _('Si es un administrador pulse en el enlace:') . ' ' . _('Actualizar') . ''); } - $action = SP_Common::parseParams('g', 'a'); - $hash = SP_Common::parseParams('g', 'h'); + $action = Common::parseParams('g', 'a'); + $hash = Common::parseParams('g', 'h'); - if ($action === 'upgrade' && $hash === SP_Config::getValue('upgrade_key', 0)) { - if (SP_Upgrade::doUpgrade($databaseVersion)) { - SP_Config::setConfigDbValue('version', $appVersion); - SP_Config::setValue('maintenance', false); - SP_Config::deleteKey('upgrade_key'); + if ($action === 'upgrade' && $hash === Config::getValue('upgrade_key', 0)) { + if (Upgrade::doUpgrade($databaseVersion)) { + Config::setConfigDbValue('version', $appVersion); + Config::setValue('maintenance', false); + Config::deleteKey('upgrade_key'); $update = true; } } else { - $controller = new \Controller\MainC(); + $controller = new Controller\MainC(); $controller->getUpgrade(); $controller->view(); exit(); @@ -533,10 +489,10 @@ class SP_Init } if ($configVersion < $appVersion - && SP_Upgrade::needConfigUpgrade($appVersion) - && SP_Upgrade::upgradeConfig($appVersion) + && Upgrade::needConfigUpgrade($appVersion) + && Upgrade::upgradeConfig($appVersion) ) { - SP_Config::setValue('version', $appVersion); + Config::setValue('version', $appVersion); $update = true; } @@ -545,8 +501,8 @@ class SP_Init $message['text'][] = _('Actualización de versión realizada.'); $message['text'][] = _('Versión') . ': ' . $appVersion; - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); self::$UPDATED = true; } @@ -554,8 +510,6 @@ class SP_Init /** * Inicialiar la sesión de usuario - * - * @return none */ private static function initSession() { @@ -569,7 +523,7 @@ class SP_Init session_regenerate_id(true); $_SESSION['SID_CREATED'] = time(); // Recargar los permisos del perfil de usuario - $_SESSION['usrprofile'] = SP_Profiles::getProfileForUser(); + $_SESSION['usrprofile'] = Profiles::getProfileForUser(); unset($_SESSION['APP_CONFIG']); } @@ -596,10 +550,10 @@ class SP_Init */ private static function getSessionLifeTime() { - $timeout = SP_Common::parseParams('s', 'session_timeout', 0); + $timeout = Common::parseParams('s', 'session_timeout', 0); if ($timeout === 0) { - $timeout = $_SESSION['session_timeout'] = SP_Config::getValue('session_timeout', 60 * 5); + $timeout = $_SESSION['session_timeout'] = Config::getValue('session_timeout', 60 * 5); } return $timeout; @@ -607,36 +561,34 @@ class SP_Init /** * Escribir la información de logout en el registro de eventos. - * - * @return none */ private static function wrLogoutInfo() { $inactiveTime = round(((time() - $_SESSION['LAST_ACTIVITY']) / 60), 2); $totalTime = round(((time() - $_SESSION['START_ACTIVITY']) / 60), 2); - $ulogin = SP_Common::parseParams('s', 'ulogin'); + $ulogin = Common::parseParams('s', 'ulogin'); $message['action'] = _('Finalizar sesión'); $message['text'][] = _('Usuario') . ": " . $ulogin; $message['text'][] = _('Tiempo inactivo') . ": " . $inactiveTime . " min."; $message['text'][] = _('Tiempo total') . ": " . $totalTime . " min."; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Comprobar si hay que ejecutar acciones de URL. * - * @return bool|none + * @return bool */ public static function checkRequestActions() { - if (!SP_Common::parseParams('r', 'a', '', true)) { - return; + if (!Common::parseParams('r', 'a', '', true)) { + return false; } - $action = SP_Common::parseParams('r', 'a'); - $controller = new \Controller\MainC(); + $action = Common::parseParams('r', 'a'); + $controller = new Controller\MainC(); switch ($action) { case 'passreset': @@ -652,8 +604,6 @@ class SP_Init /** * Deslogar el usuario actual y eliminar la información de sesión. - * - * @return none */ private static function logout() { @@ -670,13 +620,42 @@ class SP_Init */ public static function isLoggedIn() { - if (SP_Common::parseParams('s', 'ulogin')) { + if (Common::parseParams('s', 'ulogin', '', true)) { // TODO: refrescar variables de sesión. return true; } return false; } + /** + * Establecer las rutas de sysPass en el PATH de PHP + */ + public static function setIncludes() + { + set_include_path(MODEL_PATH . PATH_SEPARATOR . CONTROLLER_PATH . PATH_SEPARATOR . get_include_path()); + } + + /** + * Cargador de clases de sysPass + * + * @param $class string El nombre de la clase a cargar + */ + public static function loadClass($class) + { + // Eliminar \\ para las clases con namespace definido + $class = (strripos($class, '\\')) ? substr($class, strripos($class, '\\') + 1) : $class; + +// error_log($class); + + // Buscar la clase en los directorios de include + foreach (explode(':', get_include_path()) as $iPath) { + $classFile = $iPath . DIRECTORY_SEPARATOR . $class . '.class.php'; + if (is_readable($classFile)) { + require_once $classFile; + } + } + } + /** * Devuelve el tiempo actual en coma flotante. * Esta función se utiliza para calcular el tiempo de renderizado con coma flotante @@ -688,11 +667,4 @@ class SP_Init list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } -} - -// Empezar a calcular el tiempo y memoria utilizados -$memInit = memory_get_usage(); -$timeStart = SP_Init::microtime_float(); - -// Inicializar sysPass -SP_Init::init(); \ No newline at end of file +} \ No newline at end of file diff --git a/inc/Installer.class.php b/inc/Installer.class.php index 5d9b189e..e24467d9 100644 --- a/inc/Installer.class.php +++ b/inc/Installer.class.php @@ -24,55 +24,25 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); define('IS_INSTALLER',1); -/** - * Extender la clase Exception para mostrar ayuda en los mensajes - */ -class InstallerException extends Exception -{ - private $type; - private $hint; - - public function __construct($type, $message, $hint, $code = 0, Exception $previous = null) - { - $this->type = $type; - $this->hint = $hint; - parent::__construct($message, $code, $previous); - } - - public function __toString() - { - return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; - } - - public function getHint() - { - return $this->hint; - } - - public function getType() - { - return $this->type; - } - -} - /** * Esta clase es la encargada de instalar sysPass. */ -class SP_Installer +class Installer { - private static $dbuser; - private static $dbname; - private static $dbhost; - private static $dbc; // Database connection - private static $username; - private static $password; - private static $masterPassword; - private static $isHostingMode; + private static $_dbuser; + private static $_dbname; + private static $_dbhost; + private static $_dbc; // Database connection + private static $_username; + private static $_password; + private static $_masterPassword; + private static $_isHostingMode; /** * Iniciar instalación. @@ -86,73 +56,73 @@ class SP_Installer if (empty($options['adminlogin'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar nombre de usuario admin'), 'hint' => _('Usuario admin para acceso a la aplicación')); } if (empty($options['adminpass'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar la clave de admin'), 'hint' => _('Clave del usuario admin de la aplicación')); } if (empty($options['masterpassword'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar la clave maestra'), 'hint' => _('Clave maestra para encriptar las claves')); } if (strlen($options['masterpassword']) < 11) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Clave maestra muy corta'), 'hint' => _('La longitud de la clave maestra ha de ser mayor de 11 caracteres')); } if (empty($options['dbuser'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar el usuario de la BBDD'), 'hint' => _('Usuario con permisos de administrador de la Base de Datos')); } if (empty($options['dbpass'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar la clave de la BBDD'), 'hint' => _('Clave del usuario administrador de la Base de Datos')); } if (empty($options['dbname'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar el nombre de la BBDD'), 'hint' => _('Nombre para la BBDD de la aplicación pej. syspass')); } if (substr_count($options['dbname'], '.') >= 1) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('El nombre de la BBDD no puede contener "."'), 'hint' => _('Elimine los puntos del nombre de la Base de Datos')); } if (empty($options['dbhost'])) { $error[] = array( - 'type' => 'critical', + 'type' => SPException::SP_CRITICAL, 'description' => _('Indicar el servidor de la BBDD'), 'hint' => _('Servidor donde se instalará la Base de Datos')); } if (count($error) == 0) { //no errors, good - self::$username = htmlspecialchars_decode($options['adminlogin']); - self::$password = htmlspecialchars_decode($options['adminpass']); - self::$masterPassword = htmlspecialchars_decode($options['masterpassword']); - self::$dbname = $options['dbname']; - self::$dbhost = $options['dbhost']; + self::$_username = htmlspecialchars_decode($options['adminlogin']); + self::$_password = htmlspecialchars_decode($options['adminpass']); + self::$_masterPassword = htmlspecialchars_decode($options['masterpassword']); + self::$_dbname = $options['dbname']; + self::$_dbhost = $options['dbhost']; //generate a random salt that is used to salt the local user passwords - $salt = SP_Util::generate_random_bytes(30); - SP_Config::setValue('passwordsalt', $salt); - SP_Config::setValue('version', implode(SP_Util::getVersion(true))); + $salt = Util::generate_random_bytes(30); + Config::setValue('passwordsalt', $salt); + Config::setValue('version', implode(Util::getVersion(true))); $dbadmin = $options['dbuser']; $dbpass = $options['dbpass']; @@ -165,20 +135,20 @@ class SP_Installer $dbport = 3306; } - self::$isHostingMode = (isset($options['hostingmode'])) ? 1 : 0; + self::$_isHostingMode = (isset($options['hostingmode'])) ? 1 : 0; // Save DB connection info - SP_Config::setValue('dbhost', $dbhost); - SP_Config::setValue('dbname', self::$dbname); + Config::setValue('dbhost', $dbhost); + Config::setValue('dbname', self::$_dbname); // Set some basic configuration options - SP_Config::setDefaultValues(); + Config::setDefaultValues(); try { self::checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbport); self::setupMySQLDatabase(); self::createAdminAccount(); - } catch (InstallerException $e) { + } catch (SPException $e) { $error[] = array( 'type' => $e->getType(), 'description' => $e->getMessage(), @@ -186,8 +156,8 @@ class SP_Installer return ($error); } - SP_Config::setConfigDbValue('version', implode(SP_Util::getVersion(true))); - SP_Config::setValue('installed', 1); + Config::setConfigDbValue('version', implode(Util::getVersion(true))); + Config::setValue('installed', 1); } return ($error); @@ -202,16 +172,15 @@ class SP_Installer * @param string $dbadmin usuario de conexión * @param string $dbpass clave de conexión * @param string $dbport puerto de conexión - * @throws InstallerException - * @return none + * @throws SPException */ private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbport) { try { $dsn = 'mysql:host=' . $dbhost . ';dbport=' . $dbport . ';charset=utf8'; - self::$dbc = new PDO($dsn, $dbadmin, $dbpass); - } catch (PDOException $e){ - throw new InstallerException('critical' + self::$_dbc = new \PDO($dsn, $dbadmin, $dbpass); + } catch (\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL , _('No es posible conectar con la BD') , _('Compruebe los datos de conexión') . '
' . $e->getMessage()); } @@ -221,34 +190,33 @@ class SP_Installer * Configurar la base de datos. * Esta función crea la base de datos y el usuario necesario para sysPass. * - * @throws InstallerException - * @return none + * @throws SPException */ private static function setupMySQLDatabase() { - $oldUser = SP_Config::getValue('dbuser', false); + $oldUser = Config::getValue('dbuser', false); //this should be enough to check for admin rights in mysql $query = "SELECT user " . "FROM mysql.user " - . "WHERE user='" . self::$username . "' and host='" . self::$dbhost . "';"; + . "WHERE user='" . self::$_username . "' and host='" . self::$_dbhost . "';"; // Hash DB connection password - $dbpassword = (!self::$isHostingMode) ? md5(time() . self::$password) : self::$password; + $dbpassword = (!self::$_isHostingMode) ? md5(time() . self::$_password) : self::$_password; - self::$dbuser = (!self::$isHostingMode) ? substr('sp_' . self::$username, 0, 16) : self::$username; + self::$_dbuser = (!self::$_isHostingMode) ? substr('sp_' . self::$_username, 0, 16) : self::$_username; - if (!self::$dbc->query($query)) { - if (self::$dbuser != $oldUser) { + if (!self::$_dbc->query($query)) { + if (self::$_dbuser != $oldUser) { self::createDBUser($dbpassword); - SP_Config::setValue('dbuser', self::$dbuser); - SP_Config::setValue('dbpass', $dbpassword); + Config::setValue('dbuser', self::$_dbuser); + Config::setValue('dbpass', $dbpassword); } } else { - if (self::$username != $oldUser) { - SP_Config::setValue('dbuser', self::$dbuser); - SP_Config::setValue('dbpass', $dbpassword); + if (self::$_username != $oldUser) { + Config::setValue('dbuser', self::$_dbuser); + Config::setValue('dbpass', $dbpassword); } } @@ -257,7 +225,7 @@ class SP_Installer if (!self::checkDatabaseExist()) { self::createDBStructure(); } else { - throw new InstallerException('critical' + throw new SPException(SPException::SP_CRITICAL , _('La BBDD ya existe') , _('Indique una nueva Base de Datos o elimine la existente')); } @@ -271,22 +239,21 @@ class SP_Installer * Si se marca en modo hosting, no se crea el usuario. * * @param string $dbpassword clave del usuario de sysPass - * @throws InstallerException - * @return none + * @throws SPException */ private static function createDBUser($dbpassword) { - if (self::$isHostingMode) { + if (self::$_isHostingMode) { return; } - $query = "CREATE USER '" . self::$dbuser . "'@'localhost' IDENTIFIED BY '" . $dbpassword . "'"; + $query = "CREATE USER '" . self::$_dbuser . "'@'localhost' IDENTIFIED BY '" . $dbpassword . "'"; try { - self::$dbc->query($query); - } catch (PDOException $e){ - throw new InstallerException('critical' - , _('El usuario de MySQL ya existe') . " (" . self::$dbuser . ")" + self::$_dbc->query($query); + } catch (\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL + , _('El usuario de MySQL ya existe') . " (" . self::$_dbuser . ")" , _('Indique un nuevo usuario o elimine el existente')); } } @@ -295,28 +262,27 @@ class SP_Installer * Crear la base de datos. * * @param string $dbpassword clave del usuario de sysPass - * @throws InstallerException - * @return none + * @throws SPException */ private static function createMySQLDatabase($dbpassword) { - $query = "CREATE DATABASE IF NOT EXISTS `" . self::$dbname . "`"; + $query = "CREATE DATABASE IF NOT EXISTS `" . self::$_dbname . "`"; try { - self::$dbc->query($query); - } catch (PDOException $e){ - throw new InstallerException('critical' + self::$_dbc->query($query); + } catch (\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL , _('Error al crear la BBDD') . " (" . $e->getMessage() . ")" , _('Verifique los permisos del usuario de la Base de Datos')); } - if (!self::$isHostingMode) { - $query = "GRANT ALL PRIVILEGES ON `" . self::$dbname . "`.* TO '" . self::$dbuser . "'@'" . self::$dbhost . "' IDENTIFIED BY '$dbpassword';"; + if (!self::$_isHostingMode) { + $query = "GRANT ALL PRIVILEGES ON `" . self::$_dbname . "`.* TO '" . self::$_dbuser . "'@'" . self::$_dbhost . "' IDENTIFIED BY '$dbpassword';"; try { - self::$dbc->query($query); - } catch (PDOException $e){ - throw new InstallerException('critical' + self::$_dbc->query($query); + } catch (\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL , _('Error al establecer permisos de la BBDD') . " (" . $e->getMessage() . ")" , _('Verifique los permisos del usuario de la Base de Datos')); } @@ -332,35 +298,34 @@ class SP_Installer { $query = "SELECT COUNT(*) " . "FROM information_schema.tables " - . "WHERE table_schema = '" . self::$dbname . "' " + . "WHERE table_schema = '" . self::$_dbname . "' " . "AND table_name = 'usrData' LIMIT 1"; - return (intval(self::$dbc->query($query)->fetchColumn()) === 0); + return (intval(self::$_dbc->query($query)->fetchColumn()) === 0); } /** * Crear la estructura de la base de datos. * Esta función crea la estructura de la base de datos a partir del archivo dbsctructure.sql. * - * @throws InstallerException - * @return none + * @throws SPException */ private static function createDBStructure() { $fileName = dirname(__FILE__) . '/dbstructure.sql'; if (!file_exists($fileName)) { - throw new InstallerException('critical' + throw new SPException(SPException::SP_CRITICAL , _('El archivo de estructura de la BBDD no existe') , _('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.')); } // Usar la base de datos de sysPass try { - self::$dbc->query('USE ' . self::$dbname); - } catch (PDOException $e){ - throw new InstallerException('critical' - , _('Error al seleccionar la BBDD') . " '" . self::$dbname . "' (" . $e->getMessage() . ")" + self::$_dbc->query('USE ' . self::$_dbname); + } catch (\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL + , _('Error al seleccionar la BBDD') . " '" . self::$_dbname . "' (" . $e->getMessage() . ")" , _('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.')); } @@ -372,12 +337,12 @@ class SP_Installer $buffer = stream_get_line($handle, 1000000, ";\n"); if (strlen(trim($buffer)) > 0) { try { - self::$dbc->query($buffer); - } catch (PDOException $e) { + self::$_dbc->query($buffer); + } catch (\PDOException $e) { // drop database on error - self::$dbc->query("DROP DATABASE " . self::$dbname . ";"); + self::$_dbc->query("DROP DATABASE " . self::$_dbname . ";"); - throw new InstallerException('critical' + throw new SPException(SPException::SP_CRITICAL , _('Error al crear la BBDD') . ' (' . $e->getMessage() . ')' , _('Error al crear la estructura de la Base de Datos.')); } @@ -390,27 +355,26 @@ class SP_Installer * Crear el usuario admin de sysPass. * Esta función crea el grupo, perfil y usuario 'admin' para utilizar sysPass. * - * @throws InstallerException - * @return none + * @throws SPException */ private static function createAdminAccount() { - $user = new SP_Users; + $user = new Users; // Datos del grupo - SP_Groups::$groupName = "Admins"; - SP_Groups::$groupDescription = "Admins"; + Groups::$groupName = "Admins"; + Groups::$groupDescription = "Admins"; - if (!SP_Groups::addGroup()) { + if (!Groups::addGroup()) { self::rollback(); - throw new InstallerException("critical" + throw new SPException("critical" , _('Error al crear el grupo "admin"') , _('Informe al desarrollador')); } // Establecer el id de grupo del usuario al recién creado - $user->userGroupId = SP_Groups::$queryLastId; + $user->userGroupId = Groups::$queryLastId; $profileProp = array("pAccView" => 1, "pAccViewPass" => 1, @@ -430,22 +394,22 @@ class SP_Installer "pProfiles" => 1, "pEventlog" => 1); - SP_Profiles::$profileName = 'Admin'; + Profiles::$profileName = 'Admin'; - if (!SP_Profiles::addProfile($profileProp)) { + if (!Profiles::addProfile($profileProp)) { self::rollback(); - throw new InstallerException("critical" + throw new SPException("critical" , _('Error al crear el perfil "admin"') , _('Informe al desarrollador')); } // Establecer el id de perfil del usuario al recién creado - $user->userProfileId = SP_Profiles::$queryLastId; + $user->userProfileId = Profiles::$queryLastId; // Datos del usuario - $user->userLogin = self::$username; - $user->userPass = self::$password; + $user->userLogin = self::$_username; + $user->userPass = self::$_password; $user->userName = "Admin"; $user->userIsAdminApp = 1; @@ -453,22 +417,22 @@ class SP_Installer if (!$user->addUser()) { self::rollback(); - throw new InstallerException('critical' + throw new SPException(SPException::SP_CRITICAL , _('Error al crear el usuario "admin"') , _('Informe al desarrollador')); } // Guardar el hash de la clave maestra - SP_Config::$arrConfigValue["masterPwd"] = SP_Crypt::mkHashPassword(self::$masterPassword); - SP_Config::$arrConfigValue["lastupdatempass"] = time(); - SP_Config::writeConfigDb(true); + Config::setArrConfigValue('masterPwd', Crypt::mkHashPassword(self::$_masterPassword)); + Config::setArrConfigValue('lastupdatempass', time()); + Config::writeConfigDb(true); $user->userId = $user->queryLastId; // Needed for update user's master password - if (!$user->updateUserMPass(self::$masterPassword, false)) { + if (!$user->updateUserMPass(self::$_masterPassword, false)) { self::rollback(); - throw new InstallerException('critical' + throw new SPException(SPException::SP_CRITICAL , _('Error al actualizar la clave maestra del usuario "admin"') , _('Informe al desarrollador')); } @@ -477,18 +441,16 @@ class SP_Installer /** * Deshacer la instalación en caso de fallo. * Esta función elimina la base de datos y el usuario de sysPass - * - * @return none */ private static function rollback() { try { - self::$dbc->query("DROP DATABASE IF EXISTS " . self::$dbname . ";"); - self::$dbc->query("DROP USER '" . self::$dbuser . "'@'" . self::$dbhost . "';"); - self::$dbc->query("DROP USER '" . self::$dbuser . "'@'%';"); - } catch(PDOException $e){ - SP_Config::deleteKey('dbuser'); - SP_Config::deleteKey('dbpass'); + self::$_dbc->query("DROP DATABASE IF EXISTS " . self::$_dbname . ";"); + self::$_dbc->query("DROP USER '" . self::$_dbuser . "'@'" . self::$_dbhost . "';"); + self::$_dbc->query("DROP USER '" . self::$_dbuser . "'@'%';"); + } catch(\PDOException $e){ + Config::deleteKey('dbuser'); + Config::deleteKey('dbpass'); } } diff --git a/inc/KeepassImport.class.php b/inc/KeepassImport.class.php index 8089edd0..2d07ab47 100644 --- a/inc/KeepassImport.class.php +++ b/inc/KeepassImport.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,18 +24,19 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Esta clase es la encargada de importar cuentas desde KeePass */ -class SP_KeepassImport +class KeepassImport { - /** * Iniciar la importación desde KeePass + * * @param object $xml - * @return none */ public static function addKeepassAccounts($xml) { @@ -45,17 +46,15 @@ class SP_KeepassImport /** * Obtener los datos de las entradas de KeePass. * - * @param object $entries con el objeto XML con las entradas + * @param object $entries con el objeto XML con las entradas * @param string $groupName con nombre del grupo a procesar - * @throws ImportException - * @return none */ private static function getEntryData($entries, $groupName) { - foreach ( $entries as $entry ){ - foreach ( $entry->String as $account ){ - $value = (isset($account->Value)) ? (string) $account->Value : ''; - switch ($account->Key){ + foreach ($entries as $entry) { + foreach ($entry->String as $account) { + $value = (isset($account->Value)) ? (string)$account->Value : ''; + switch ($account->Key) { case 'Notes': $notes = $value; break; @@ -74,8 +73,8 @@ class SP_KeepassImport } } - $accountData = array($name,'KeePass',$groupName,$url,$username,$password,$notes); - SP_Import::addAccountData($accountData); + $accountData = array($name, 'KeePass', $groupName, $url, $username, $password, $notes); + Import::addAccountData($accountData); } } @@ -83,33 +82,31 @@ class SP_KeepassImport * Obtener los grupos y procesar lan entradas de KeePass. * * @param object $xml con objeto XML del archivo de KeePass - * @throws ImportException - * @return none */ private static function getGroups($xml) { - foreach($xml as $node){ - if ( $node->Group ){ - foreach ( $node->Group as $group ){ + foreach ($xml as $node) { + if ($node->Group) { + foreach ($node->Group as $group) { $groupName = $group->Name; // Analizar grupo - if ( $node->Group->Entry ){ + if ($node->Group->Entry) { // Obtener entradas - self::getEntryData($group->Entry,$groupName); + self::getEntryData($group->Entry, $groupName); } - if ( $group->Group ){ + if ($group->Group) { // Analizar subgrupo self::getGroups($group); } } } - if ( $node->Entry ){ + if ($node->Entry) { $groupName = $node->Name; // Obtener entradas - self::getEntryData($node->Entry,$groupName); + self::getEntryData($node->Entry, $groupName); } } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/inc/KeepassXImport.class.php b/inc/KeepassXImport.class.php index 4eb1c3a7..7a755cf2 100644 --- a/inc/KeepassXImport.class.php +++ b/inc/KeepassXImport.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,19 +24,19 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Esta clase es la encargada de importar cuentas desde KeePassX */ -class SP_KeepassXImport +class KeepassXImport { - /** * Iniciar la importación desde KeePass. * * @param object $xml - * @return none */ public static function addKeepassXAccounts($xml) { @@ -46,22 +46,20 @@ class SP_KeepassXImport /** * Obtener los datos de las entradas de KeePass. * - * @param object $entries con el objeto XML con las entradas + * @param object $entries con el objeto XML con las entradas * @param string $groupName con nombre del grupo a procesar - * @throws ImportException - * @return none */ private static function getEntryData($entries, $groupName) { - foreach ( $entries as $entry ){ - $notes = (isset($entry->comment)) ? (string) $entry->comment : ''; - $password = (isset($entry->password)) ? (string) $entry->password : ''; - $name = (isset($entry->title)) ? (string) $entry->title : ''; - $url = (isset($entry->url)) ? (string) $entry->url : '' ; - $username = (isset($entry->username)) ? (string) $entry->username : ''; + foreach ($entries as $entry) { + $notes = (isset($entry->comment)) ? (string)$entry->comment : ''; + $password = (isset($entry->password)) ? (string)$entry->password : ''; + $name = (isset($entry->title)) ? (string)$entry->title : ''; + $url = (isset($entry->url)) ? (string)$entry->url : ''; + $username = (isset($entry->username)) ? (string)$entry->username : ''; - $accountData = array($name,'KeePassX',$groupName,$url,$username,$password,$notes); - SP_Import::addAccountData($accountData); + $accountData = array($name, 'KeePassX', $groupName, $url, $username, $password, $notes); + Import::addAccountData($accountData); } } @@ -69,33 +67,31 @@ class SP_KeepassXImport * Obtener los grupos y procesar lan entradas de KeePass. * * @param object $xml con objeto XML del archivo de KeePass - * @throws ImportException - * @return none */ private static function getGroups($xml) { - foreach($xml as $node){ - if ( $node->group ){ - foreach ( $node->group as $group ){ + foreach ($xml as $node) { + if ($node->group) { + foreach ($node->group as $group) { $groupName = $group->title; // Analizar grupo - if ( $node->group->entry ){ + if ($node->group->entry) { // Obtener entradas - self::getEntryData($group->entry,$groupName); + self::getEntryData($group->entry, $groupName); } - if ( $group->group ){ + if ($group->group) { // Analizar subgrupo self::getGroups($group); } } } - if ( $node->entry ){ + if ($node->entry) { $groupName = $node->title; // Obtener entradas - self::getEntryData($node->entry,$groupName); + self::getEntryData($node->entry, $groupName); } } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/inc/Ldap.class.php b/inc/Ldap.class.php index 7d010d2a..4bb8aa69 100644 --- a/inc/Ldap.class.php +++ b/inc/Ldap.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,25 +24,29 @@ * */ +namespace SP; + +use Exception; + 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_Ldap +class Ldap { // Variabla que contiene los datos de una búsqueda public static $ldapSearchData; // Variable para determinar si conecta con Active Directory - private static $isADS = false; + private static $_isADS = false; // Variables de conexión con LDAP - private static $ldapConn; - private static $ldapServer; - private static $searchBase; - private static $bindDN; - private static $bindPass; - private static $ldapGroup; + private static $_ldapConn; + private static $_ldapServer; + private static $_searchBase; + private static $_bindDN; + private static $_bindPass; + private static $_ldapGroup; /** * Obtener el recurso de conexión a LDAP. @@ -51,8 +55,8 @@ class SP_Ldap */ public static function getConn() { - if (is_resource(self::$ldapConn)) { - return self::$ldapConn; + if (is_resource(self::$_ldapConn)) { + return self::$_ldapConn; } } @@ -60,19 +64,19 @@ class SP_Ldap * Comprobar la conexión al servidor de LDAP. * * @param string $ldapServer con la dirección del servidor - * @param string $bindDN con el usuario de conexión - * @param string $bindPass con la clave del usuario de conexión + * @param string $bindDN con el usuario de conexión + * @param string $bindPass con la clave del usuario de conexión * @param string $searchBase con la base para las búsquedas - * @param string $ldapGroup con el grupo con los usuarios de acceso + * @param string $ldapGroup con el grupo con los usuarios de acceso * @return false|int Con el número de entradas encontradas */ public static function checkLDAPConn($ldapServer, $bindDN, $bindPass, $searchBase, $ldapGroup) { - self::$ldapServer = $ldapServer; - self::$bindDN = $bindDN; - self::$bindPass = $bindPass; - self::$searchBase = $searchBase; - self::$ldapGroup = $ldapGroup; + self::$_ldapServer = $ldapServer; + self::$_bindDN = $bindDN; + self::$_bindPass = $bindPass; + self::$_searchBase = $searchBase; + self::$_ldapGroup = $ldapGroup; try { self::ldapConnect(); @@ -96,17 +100,17 @@ class SP_Ldap $message['action'] = __FUNCTION__; // Conexión al servidor LDAP - if (!self::$ldapConn = @ldap_connect(self::$ldapServer)) { - $message['text'][] = _('No es posible conectar con el servidor de LDAP') . " '" . self::$ldapServer . "'"; - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + if (!self::$_ldapConn = @ldap_connect(self::$_ldapServer)) { + $message['text'][] = _('No es posible conectar con el servidor de LDAP') . " '" . self::$_ldapServer . "'"; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('No es posible conectar con el servidor de LDAP')); } - @ldap_set_option(self::$ldapConn, LDAP_OPT_NETWORK_TIMEOUT, 10); // Set timeout - @ldap_set_option(self::$ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); // Set LDAP version + @ldap_set_option(self::$_ldapConn, LDAP_OPT_NETWORK_TIMEOUT, 10); // Set timeout + @ldap_set_option(self::$_ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); // Set LDAP version return true; } @@ -114,7 +118,7 @@ class SP_Ldap /** * Realizar la autentificación con el servidor de LDAP. * - * @param string $userDN con el DN del usuario + * @param string $userDN con el DN del usuario * @param string $userPass con la clave del usuario * @throws Exception * @return bool @@ -123,15 +127,15 @@ class SP_Ldap { $message['action'] = __FUNCTION__; - $dn = ($userDN) ? $userDN : self::$bindDN; - $pass = ($userPass) ? $userPass : self::$bindPass; + $dn = ($userDN) ? $userDN : self::$_bindDN; + $pass = ($userPass) ? $userPass : self::$_bindPass; - if (!@ldap_bind(self::$ldapConn, $dn, $pass)) { + if (!@ldap_bind(self::$_ldapConn, $dn, $pass)) { $message['text'][] = _('Error al conectar (BIND)'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP DN: ' . $dn; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al conectar (BIND)')); } @@ -149,23 +153,23 @@ class SP_Ldap { $message['action'] = __FUNCTION__; - $groupDN = (!empty(self::$ldapGroup)) ? self::searchGroupDN() : '*'; + $groupDN = (!empty(self::$_ldapGroup)) ? self::searchGroupDN() : '*'; $filter = '(&(|(memberOf=' . $groupDN . ')(groupMembership=' . $groupDN . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))'; $filterAttr = array("dn"); - $searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr); + $searchRes = @ldap_search(self::$_ldapConn, self::$_searchBase, $filter, $filterAttr); if (!$searchRes) { $message['text'][] = _('Error al buscar objetos en DN base'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar objetos en DN base')); } - return @ldap_count_entries(self::$ldapConn, $searchRes); + return @ldap_count_entries(self::$_ldapConn, $searchRes); } /** @@ -179,34 +183,34 @@ class SP_Ldap $message['action'] = __FUNCTION__; $groupName = array(); - if (preg_match('/^cn=([\w\s-]+),.*/i', self::$ldapGroup, $groupName)) { + if (preg_match('/^cn=([\w\s-]+),.*/i', self::$_ldapGroup, $groupName)) { $filter = '(cn=' . $groupName[1] . ')'; } else { - $filter = '(cn=' . self::$ldapGroup . ')'; + $filter = '(cn=' . self::$_ldapGroup . ')'; } $filterAttr = array("dn", "cn"); - $searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr); + $searchRes = @ldap_search(self::$_ldapConn, self::$_searchBase, $filter, $filterAttr); if (!$searchRes) { $message['text'][] = _('Error al buscar RDN de grupo'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar RDN de grupo')); } - if (@ldap_count_entries(self::$ldapConn, $searchRes) === 1) { - $ldapSearchData = @ldap_get_entries(self::$ldapConn, $searchRes); + if (@ldap_count_entries(self::$_ldapConn, $searchRes) === 1) { + $ldapSearchData = @ldap_get_entries(self::$_ldapConn, $searchRes); if (!$ldapSearchData) { $message['text'][] = _('Error al buscar RDN de grupo'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar RDN de grupo')); } @@ -214,14 +218,14 @@ class SP_Ldap $message['text'][] = _('RDN de grupo encontrado'); $message['text'][] = 'RDN: ' . $ldapSearchData[0]["dn"]; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); return $ldapSearchData[0]["dn"]; } else { $message['text'][] = _('Error al buscar RDN de grupo'); $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar RDN de grupo')); } @@ -234,18 +238,18 @@ class SP_Ldap */ public static function checkLDAPParams() { - self::$searchBase = SP_Config::getValue('ldap_base'); - self::$ldapServer = SP_Config::getValue('ldap_server'); - self::$bindDN = SP_Config::getValue('ldap_binduser'); - self::$bindPass = SP_Config::getValue('ldap_bindpass'); - self::$ldapGroup = SP_Config::getValue('ldap_group', '*'); - self::$isADS = SP_Config::getValue('ldap_ads', false); + self::$_searchBase = Config::getValue('ldap_base'); + self::$_ldapServer = Config::getValue('ldap_server'); + self::$_bindDN = Config::getValue('ldap_binduser'); + self::$_bindPass = Config::getValue('ldap_bindpass'); + self::$_ldapGroup = Config::getValue('ldap_group', '*'); + self::$_isADS = Config::getValue('ldap_ads', false); - if (!self::$searchBase || !self::$ldapServer || !self::$bindDN || !self::$bindPass) { + if (!self::$_searchBase || !self::$_ldapServer || !self::$_bindDN || !self::$_bindPass) { $message['action'] = __FUNCTION__; $message['text'][] = _('Los parámetros de LDAP no están configurados'); - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); return false; } @@ -264,7 +268,7 @@ class SP_Ldap { $message['action'] = __FUNCTION__; - if (self::$isADS === true) { + if (self::$_isADS === true) { $filter = '(&(|(samaccountname=' . $userLogin . ')(cn=' . $userLogin . ')(uid=' . $userLogin . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject))(objectCategory=person))'; } else { $filter = '(&(|(samaccountname=' . $userLogin . ')(cn=' . $userLogin . ')(uid=' . $userLogin . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))'; @@ -272,26 +276,26 @@ class SP_Ldap $filterAttr = array("dn", "displayname", "samaccountname", "mail", "memberof", "lockouttime", "fullname", "groupmembership", "mail"); - $searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr); + $searchRes = @ldap_search(self::$_ldapConn, self::$_searchBase, $filter, $filterAttr); if (!$searchRes) { $message['text'][] = _('Error al buscar el DN del usuario'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar el DN del usuario')); } - if (@ldap_count_entries(self::$ldapConn, $searchRes) === 1) { - self::$ldapSearchData = @ldap_get_entries(self::$ldapConn, $searchRes); + if (@ldap_count_entries(self::$_ldapConn, $searchRes) === 1) { + self::$ldapSearchData = @ldap_get_entries(self::$_ldapConn, $searchRes); if (!self::$ldapSearchData) { $message['text'][] = _('Error al localizar el usuario en LDAP'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al localizar el usuario en LDAP')); } @@ -299,7 +303,7 @@ class SP_Ldap $message['text'][] = _('Error al buscar el DN del usuario'); $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar el DN del usuario')); } @@ -312,7 +316,7 @@ class SP_Ldap */ public static function unbind() { - @ldap_unbind(self::$ldapConn); + @ldap_unbind(self::$_ldapConn); } /** @@ -357,10 +361,10 @@ class SP_Ldap { $message['action'] = __FUNCTION__; - $ldapGroup = SP_Config::getValue('ldap_group'); + $ldapGroup = Config::getValue('ldap_group'); // El filtro de grupo no está establecido - if (empty($ldapGroup)){ + if (empty($ldapGroup)) { return true; } @@ -374,24 +378,24 @@ class SP_Ldap $filter = '(&(' . $groupDN . ')(|(member=' . $userDN . ')(uniqueMember=' . $userDN . '))(|(objectClass=groupOfNames)(objectClass=groupOfUniqueNames)(objectClass=group)))'; $filterAttr = array("member", "uniqueMember"); - $searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr); + $searchRes = @ldap_search(self::$_ldapConn, self::$_searchBase, $filter, $filterAttr); if (!$searchRes) { $message['text'][] = _('Error al buscar el grupo de usuarios'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('Error al buscar el grupo de usuarios')); } - if (!@ldap_count_entries(self::$ldapConn, $searchRes) === 1) { + if (!@ldap_count_entries(self::$_ldapConn, $searchRes) === 1) { $message['text'][] = _('No se encontró el grupo con ese nombre'); - $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')'; + $message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$_ldapConn) . '(' . ldap_errno(self::$_ldapConn) . ')'; $message['text'][] = 'LDAP FILTER: ' . $filter; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); throw new Exception(_('No se encontró el grupo con ese nombre')); } diff --git a/inc/Log.class.php b/inc/Log.class.php index cef778db..7513ca64 100644 --- a/inc/Log.class.php +++ b/inc/Log.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 manejar el registro de eventos */ -class SP_Log +class Log { static $numRows; @@ -87,7 +89,7 @@ class SP_Log $message['text'][] = _('Vaciar registro de eventos'); self::wrLogInfo($message); - SP_Common::sendEmail($message); + Common::sendEmail($message); return true; } @@ -100,12 +102,12 @@ class SP_Log */ public static function wrLogInfo($message) { - if (!SP_Util::logIsEnabled() || !is_array($message)) { + if (!Util::logIsEnabled() || !is_array($message)) { return false; } - $login = SP_Session::getUserLogin(); - $userId = SP_Session::getUserId(); + $login = Session::getUserLogin(); + $userId = Session::getUserId(); $action = strip_tags(utf8_encode($message['action'])); $description = (isset($message['text'])) ? strip_tags(utf8_encode(implode(';;', $message['text']))) : ''; diff --git a/inc/Migrate.class.php b/inc/Migrate.class.php index 146fb649..0d52d3d9 100644 --- a/inc/Migrate.class.php +++ b/inc/Migrate.class.php @@ -23,51 +23,21 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); -/** - * Extender la clase Exception para mostrar ayuda en los mensajes - */ -class MigrateException extends Exception -{ - private $type; - private $hint; - - public function __construct($type, $message, $hint, $code = 0, Exception $previous = null) - { - $this->type = $type; - $this->hint = $hint; - parent::__construct($message, $code, $previous); - } - - public function __toString() - { - return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; - } - - public function getHint() - { - return $this->hint; - } - - public function getType() - { - return $this->type; - } - -} - /** * Esta clase es la encargada de realizar la migración de datos desde phpPMS. */ -class SP_Migrate +class Migrate { // private static $dbuser; - private static $dbc; // Database connection - private static $customersByName; - private static $currentQuery; - private static $result = array(); - private static $oldConfig = array(); + private static $_dbc; // Database connection + private static $_customersByName; + private static $_currentQuery; + private static $_result = array(); + private static $_oldConfig = array(); /** * Iniciar migración desde phpPMS. @@ -110,19 +80,19 @@ class SP_Migrate self::migrateUsers(); self::migrateUsersGroups(); self::migrateConfig(); - } catch (MigrateException $e) { - self::$result['error'][] = array( + } catch (SPException $e) { + self::$_result['error'][] = array( 'type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint() ); - return (self::$result); + return (self::$_result); } - self::$result['ok'][] = _('Importación finalizada'); - self::$result['ok'][] = _('Revise el registro de eventos para más detalles'); + self::$_result['ok'][] = _('Importación finalizada'); + self::$_result['ok'][] = _('Revise el registro de eventos para más detalles'); - return (self::$result); + return (self::$_result); } /** @@ -133,16 +103,15 @@ class SP_Migrate * @param string $dbpass clave de conexión * @param string $dbname nombre de la base de datos * @param string $dbport puerto de conexión - * @throws MigrateException - * @return none + * @throws SPException */ private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbname, $dbport) { try { $dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname . ';dbport=' . $dbport . ';charset=utf8'; - self::$dbc = new PDO($dsn, $dbadmin, $dbpass); - } catch (PDOException $e) { - throw new MigrateException('critical' + self::$_dbc = new \PDO($dsn, $dbadmin, $dbpass); + } catch (\PDOException $e) { + throw new SPException(SPException::SP_CRITICAL , _('No es posible conectar con la BD') , _('Compruebe los datos de conexión') . '
' . $e->getMessage()); } @@ -161,24 +130,23 @@ class SP_Migrate . 'WHERE table_schema = \'' . $dbname . '\' ' . 'AND table_name = \'usrData\' LIMIT 1'; - return (intval(self::$dbc->query($query)->fetchColumn()) === 0); + return (intval(self::$_dbc->query($query)->fetchColumn()) === 0); } /** * Comprobar la versión de phpPMS. * - * @throws MigrateException - * @return none + * @throws SPException */ private static function checkSourceVersion() { - if (!isset(self::$oldConfig['version'])) { + if (!isset(self::$_oldConfig['version'])) { self::getSourceConfig(); } - if (self::$oldConfig['version'] != "0.973b") { - throw new MigrateException('critical', - _('La versión no es compatible') . '(' . self::$oldConfig['version'] . ')', + if (self::$_oldConfig['version'] != "0.973b") { + throw new SPException(SPException::SP_CRITICAL, + _('La versión no es compatible') . '(' . self::$_oldConfig['version'] . ')', _('Actualice a la última versión de phpPMS')); } } @@ -186,18 +154,17 @@ class SP_Migrate /** * Obtener la configuración desde desde phpPMS. * - * @throws MigrateException - * @return none + * @throws SPException */ private static function getSourceConfig() { $query = 'SELECT vacValue as value,vacParameter as parameter FROM config'; try { - self::parseSourceConfig(self::$dbc->query($query)); - } catch (PDOException $e) { + self::parseSourceConfig(self::$_dbc->query($query)); + } catch (\PDOException $e) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener la configuración'), $e->getMessage()); } @@ -222,15 +189,14 @@ class SP_Migrate } // Guardar la configuración anterior - self::$oldConfig[$config['parameter']] = $value; + self::$_oldConfig[$config['parameter']] = $value; } /** * Limpiar los datos de sysPass. * Limpiar las tablas de la base de sysPass para la importación. * - * @throws MigrateException - * @return none + * @throws SPException */ private static function cleanCurrentDB() { @@ -241,7 +207,7 @@ class SP_Migrate $query = 'TRUNCATE TABLE ' . $table; if (DB::getQuery($query, __FUNCTION__) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al vaciar tabla') . ' (' . $table . ')', DB::$txtError); } @@ -254,12 +220,12 @@ class SP_Migrate $query = 'DELETE FROM usrData WHERE user_id != ' . $currentUserId; if (DB::getQuery($query, __FUNCTION__) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al vaciar tabla') . ' (' . $table . ')', DB::$txtError); } } else { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Usuario actual no es administrador de la aplicación'), 1); } } @@ -284,7 +250,7 @@ class SP_Migrate /** * Migrar los clientes desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateCustomers() @@ -295,15 +261,15 @@ class SP_Migrate $num = 0; foreach ($customers as $customer) { - SP_Customer::$customerName = $customer; + Customer::$customerName = $customer; - if (SP_Customer::checkDupCustomer()) { + if (Customer::checkDupCustomer()) { $num++; continue; } - if (!SP_Customer::addCustomer()) { - throw new MigrateException('critical', + if (!Customer::addCustomer()) { + throw new SPException(SPException::SP_CRITICAL, _('No es posible crear el cliente'), _('Contacte con el desarrollador')); } @@ -313,13 +279,13 @@ class SP_Migrate $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Obtener los clientes desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array con los clientes */ private static function getCustomers() @@ -327,13 +293,13 @@ class SP_Migrate $query = 'SELECT DISTINCT vacCliente FROM accounts'; try { - foreach (self::$dbc->query($query) as $row) { + foreach (self::$_dbc->query($query) as $row) { $customers[] = trim($row['vacCliente']); } return $customers; - } catch (PDOException $e) { - throw new MigrateException('critical', + } catch (\PDOException $e) { + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener los clientes'), $e->getMessage()); } @@ -342,7 +308,7 @@ class SP_Migrate /** * Migrar las cuentas desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateAccounts() @@ -368,14 +334,14 @@ class SP_Migrate $num = 0; try { - foreach (self::$dbc->query($query) as $row) { + foreach (self::$_dbc->query($query) as $row) { if (self::insertAccounts($row)) { $num++; } $totalRecords++; } - } catch (PDOException $e) { - throw new MigrateException('critical', + } catch (\PDOException $e) { + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener cuentas'), $e->getMessage()); } @@ -384,29 +350,29 @@ class SP_Migrate $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar una cuenta en sysPass. * * @param array $account con los datos de la cuenta - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertAccounts($account) { - if (!is_array(self::$customersByName)) { - $customers = SP_Customer::getCustomers(NULL, true); - self::$customersByName = array_flip($customers); + if (!is_array(self::$_customersByName)) { + $customers = Customer::getCustomers(NULL, true); + self::$_customersByName = array_flip($customers); } $customer = trim($account['vacCliente']); - if (array_key_exists($customer, self::$customersByName)) { - $customerId = self::$customersByName[$customer]; + if (array_key_exists($customer, self::$_customersByName)) { + $customerId = self::$_customersByName[$customer]; } else { - self::$result['error'][] = _('Cliente no encontrado') . ": " . $account['vacCliente']; + self::$_result['error'][] = _('Cliente no encontrado') . ": " . $account['vacCliente']; return false; } @@ -447,8 +413,8 @@ class SP_Migrate $data['dateEdit'] = $account['datChanged']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - self::$currentQuery = DB::escape($query); - throw new MigrateException('critical', + self::$_currentQuery = DB::escape($query); + throw new SPException(SPException::SP_CRITICAL, _('Error al migrar cuenta'), DB::$txtError); } @@ -459,7 +425,7 @@ class SP_Migrate /** * Migrar las grupos secundarios de las cuentas desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateAccountsGroups() @@ -470,14 +436,14 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertAccountsGroups($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener los grupos de cuentas'), $e->getMessage()); } @@ -486,14 +452,14 @@ class SP_Migrate $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar los grupos secundarios de una cuenta en sysPass. * * @param array $accountGroup con los datos de los grupos secundarios - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertAccountsGroups($accountGroup) @@ -504,7 +470,7 @@ class SP_Migrate $data['groupId'] = $accountGroup['intUGroupId']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear grupos de cuentas'), DB::$txtError); } @@ -515,7 +481,7 @@ class SP_Migrate /** * Migrar el historail de las cuentas desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateAccountsHistory() @@ -544,43 +510,43 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertAccountsHistory($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener el historico de cuentas'), - self::$dbc->error); + self::$_dbc->error); } $message['action'] = _('Importar Histórico de Cuentas'); $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar el historial de una cuenta en sysPass. * * @param array $accountHistory con los datos del historial de la cuenta - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertAccountsHistory($accountHistory) { - if (!is_array(self::$customersByName)) { - $customers = SP_Customer::getCustomers(null, true); - self::$customersByName = array_flip($customers); + if (!is_array(self::$_customersByName)) { + $customers = Customer::getCustomers(null, true); + self::$_customersByName = array_flip($customers); } $customer = trim($accountHistory['vacCliente']); - if (array_key_exists($customer, self::$customersByName)) { - $customerId = self::$customersByName[$customer]; + if (array_key_exists($customer, self::$_customersByName)) { + $customerId = self::$_customersByName[$customer]; } else { return false; } @@ -625,7 +591,7 @@ class SP_Migrate $data['isDeleted'] = $accountHistory['blnEliminada']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear historico de cuentas'), DB::$txtError); } @@ -636,7 +602,7 @@ class SP_Migrate /** * Migrar los archivos de de las cuentas desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateAcountsFiles() @@ -653,30 +619,30 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertAccountsFiles($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener los archivos de cuentas'), - self::$dbc->error); + self::$_dbc->error); } $message['action'] = _('Importar Archivos de Cuentas'); $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar los archivos de una cuenta en sysPass. * * @param array $accountFile con los datos del archivo - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertAccountsFiles($accountFile) @@ -697,7 +663,7 @@ class SP_Migrate $data['extension'] = $accountFile['vacExtension']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear archivos de cuentas'), DB::$txtError); } @@ -708,7 +674,7 @@ class SP_Migrate /** * Migrar las categorías de las cuentas desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateAccountsCategories() @@ -719,30 +685,30 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertAccountsCategories($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener las categorías de cuentas'), - self::$dbc->error); + self::$_dbc->error); } $message['action'] = _('Importar Categorías de Cuentas'); $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar las categorías en sysPass. * * @param array $accountCategory con los datos de la categoría - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertAccountsCategories($accountCategory) @@ -753,7 +719,7 @@ class SP_Migrate $data['name'] = $accountCategory['vacCategoryName']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear categorías de cuentas'), DB::$txtError); } @@ -764,7 +730,7 @@ class SP_Migrate /** * Migrar los usuarios desde desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateUsers() @@ -794,30 +760,30 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertUsers($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener los usuarios'), - self::$dbc->error); + self::$_dbc->error); } $message['action'] = _('Importar Usuarios'); $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar los usuarios en sysPass. * * @param array $users con los datos del usuario - * @throws MigrateException + * @throws SPException * @return bool * * El usuario importado está deshabilitado @@ -863,7 +829,7 @@ class SP_Migrate $data['isLdap'] = $users['blnFromLdap']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear usuarios'), DB::$txtError); } @@ -874,7 +840,7 @@ class SP_Migrate /** * Migrar los grupos de usuarios desde desde phpPMS. * - * @throws MigrateException + * @throws SPException * @return array resultado */ private static function migrateUsersGroups() @@ -885,30 +851,30 @@ class SP_Migrate $num = 0; try { - foreach(self::$dbc->query($query) as $row){ + foreach(self::$_dbc->query($query) as $row){ if (self::insertUsersGroups($row)) { $num++; } $totalRecords++; } - } catch(PDOException $e){ - throw new MigrateException('critical', + } catch(\PDOException $e){ + throw new SPException(SPException::SP_CRITICAL, _('Error al obtener los grupos de usuarios'), - self::$dbc->error); + self::$_dbc->error); } $message['action'] = _('Importar Grupos de Usuarios'); $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** * Insertar los grupos de usuarios en sysPass. * * @param array $usersGroups con los datos del grupo - * @throws MigrateException + * @throws SPException * @return bool */ private static function insertUsersGroups($usersGroups) @@ -923,7 +889,7 @@ class SP_Migrate $data['description'] = $usersGroups['vacUGroupDesc']; if (DB::getQuery($query, __FUNCTION__, $data) === false) { - throw new MigrateException('critical', + throw new SPException(SPException::SP_CRITICAL, _('Error al crear los grupos de usuarios'), DB::$txtError); } @@ -957,15 +923,15 @@ class SP_Migrate 'lastupdatempass', 'passwordsalt'); - $totalParams = count(self::$oldConfig); + $totalParams = count(self::$_oldConfig); $num = 0; // Guardar la nueva configuración - foreach (self::$oldConfig as $key => $value) { + foreach (self::$_oldConfig as $key => $value) { if (array_key_exists($key, $skip)) { continue; } - SP_Config::setValue($key, $value); + Config::setValue($key, $value); $num++; } @@ -973,6 +939,6 @@ class SP_Migrate $message['text'][] = 'OK'; $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalParams; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } } \ No newline at end of file diff --git a/inc/Profiles.class.php b/inc/Profiles.class.php index 6dba347b..ee93c41f 100644 --- a/inc/Profiles.class.php +++ b/inc/Profiles.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 los perfiles de usuarios. */ -class SP_Profiles +class Profiles { static $profileId; static $profileName; @@ -37,6 +39,7 @@ class SP_Profiles /** * Obtener los datos de un perfil + * * @param int $id con el Id del perfil a consultar * @return array con el nombre de la columna como clave y los datos como valor */ @@ -85,6 +88,7 @@ class SP_Profiles /** * Obtener los datos de un perfil + * * @param int $profileId opcional, con el Id del perfil a consultar * @return array con la lista de perfiles */ @@ -130,6 +134,7 @@ class SP_Profiles /** * Comprobar si un perfil existe + * * @return bool */ public static function checkProfileExist() @@ -157,6 +162,7 @@ class SP_Profiles /** * Añadir un nuevo perfil + * * @param array $profileProp con las propiedades del perfil * @return bool */ @@ -218,10 +224,10 @@ class SP_Profiles self::$queryLastId = DB::$lastId; $message['action'] = _('Nuevo Perfil'); - $message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . self::$profileName; + $message['text'][] = Html::strongText(_('Perfil') . ': ') . self::$profileName; - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -293,10 +299,10 @@ class SP_Profiles self::$queryLastId = DB::$lastId; $message['action'] = _('Modificar Perfil'); - $message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . $profileName . ' > ' . self::$profileName; + $message['text'][] = Html::strongText(_('Perfil') . ': ') . $profileName . ' > ' . self::$profileName; - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -378,7 +384,7 @@ class SP_Profiles */ public static function getProfileForUser($userId = 0) { - $userId = SP_Session::getUserId(); + $userId = Session::getUserId(); if (!$userId) { return false; @@ -401,7 +407,10 @@ class SP_Profiles . 'BIN(userProfile_pUsers) AS pUsers,' . 'BIN(userProfile_pGroups) AS pGroups,' . 'BIN(userProfile_pProfiles) AS pProfiles,' - . 'BIN(userProfile_pEventlog) AS pEventlog ' + . 'BIN(userProfile_pEventlog) AS pEventlog,' + . 'BIN(userProfile_pConfigMenu) AS pConfigMenu,' + . 'BIN(userProfile_pAppMgmtMenu) AS pAppMgmtMenu,' + . 'BIN(userProfile_pUsersMenu) AS pUsersMenu ' . 'FROM usrData ' . 'JOIN usrProfiles ON userProfile_Id = user_profileId ' . 'WHERE user_id = :id LIMIT 1'; diff --git a/inc/SPException.class.php b/inc/SPException.class.php new file mode 100644 index 00000000..b6e4bfca --- /dev/null +++ b/inc/SPException.class.php @@ -0,0 +1,58 @@ +. + * + */ + +namespace SP; + +/** + * Extender la clase Exception para mostrar ayuda en los mensajes + */ +class SPException extends \Exception{ + const SP_CRITICAL = 1; + const SP_WARNING = 2; + private $_type; + private $_hint; + + public function __construct($type, $message, $hint = '', $code = 0, \Exception $previous = null) + { + $this->_type = $type; + $this->_hint = $hint; + parent::__construct($message, $code, $previous); + } + + public function __toString() + { + return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->_hint})\n"; + } + + public function getHint() + { + return $this->_hint; + } + + public function getType() + { + return $this->_type; + } +} \ No newline at end of file diff --git a/inc/Session.class.php b/inc/Session.class.php index e03fdf18..b461b479 100644 --- a/inc/Session.class.php +++ b/inc/Session.class.php @@ -23,12 +23,14 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Clase para manejar la variable de sesion */ -class SP_Session +class Session { /** * Obtiene el id de usuario de la sesión. @@ -103,7 +105,7 @@ class SP_Session /** * Establece el id de perfil de usuario en la sesión. * - * @param SplInt $profileId + * @param int $profileId */ public static function setUserProfileId($profileId) { @@ -183,7 +185,7 @@ class SP_Session /** * Establece el nombre del grupo de usuario en la sesión. * - * @param SplString $groupName + * @param string $groupName */ public static function setUserGroupName($groupName) { @@ -243,10 +245,10 @@ class SP_Session /** * Establece el objeto de perfil de usuario en la sesión. * - * @param StdClass $profile + * @param \StdClass $profile */ - public static function setUserProfile(StdClass $profile) + public static function setUserProfile(\StdClass $profile) { - $_SESSION["usrprofile"] = (object)$profile; + $_SESSION["usrprofile"] = $profile; } } \ No newline at end of file diff --git a/inc/Template.class.php b/inc/Template.class.php index 18ef2352..6412ecac 100644 --- a/inc/Template.class.php +++ b/inc/Template.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. @@ -22,6 +22,9 @@ * along with sysPass. If not, see . * */ +namespace SP; + +use InvalidArgumentException; /** * Clase Template para la manipulación de plantillas @@ -32,28 +35,26 @@ * publicada en http://www.sitepoint.com/flexible-view-manipulation-1/ * */ -class SP_Template { +class Template +{ /** * @var array Variable con los archivos de plantilla a cargar */ - private $file = array(); + private $_file = array(); /** * @var array Variable con las variables a incluir en la plantilla */ - private $vars = array(); - /** - * @var null Variable con el controlador a usar - */ - private $controllers = array(); + private $_vars = array(); /** - * @param null $file Archivo de plantilla a añadir + * @param null $file Archivo de plantilla a añadir * @param array $vars Variables a inicializar */ - public function __construct($file = null, array $vars = array()) { + public function __construct($file = null, array $vars = array()) + { $this->addTemplate($file); - if(!empty($vars)){ + if (!empty($vars)) { $this->setVars($vars); } } @@ -62,12 +63,13 @@ class SP_Template { * Overloading para añadir nuevas variables en al array de variables dela plantilla * pasadas como atributos dinámicos de la clase * - * @param string $name Nombre del atributo + * @param string $name Nombre del atributo * @param string $value Valor del atributo * @return null */ - public function __set($name, $value) { - $this->vars[$name] = $value; + public function __set($name, $value) + { + $this->_vars[$name] = $value; return null; } @@ -78,12 +80,13 @@ class SP_Template { * @return null * @throws InvalidArgumentException */ - public function __get($name) { - if (!array_key_exists($name, $this->vars)) { + public function __get($name) + { + if (!array_key_exists($name, $this->_vars)) { throw new InvalidArgumentException('No es posible obtener la variable "' . $name . '"'); } - return $this->vars[$name]; + return $this->_vars[$name]; } /** @@ -93,8 +96,9 @@ class SP_Template { * @param string $name Nombre del atributo * @return bool */ - public function __isset($name) { - return array_key_exists($name, $this->vars); + public function __isset($name) + { + return array_key_exists($name, $this->_vars); } /** @@ -105,12 +109,13 @@ class SP_Template { * @return $this * @throws InvalidArgumentException */ - public function __unset($name) { - if (!isset($this->vars[$name])) { + public function __unset($name) + { + if (!isset($this->_vars[$name])) { throw new InvalidArgumentException('No es posible destruir la variable "' . $name . '"'); } - unset($this->vars[$name]); + unset($this->_vars[$name]); return $this; } @@ -120,20 +125,14 @@ class SP_Template { * * @return string Con el contenido del buffer de salida */ - public function render() { - extract($this->vars); - - // Añadimos los controladores necesarios - foreach ( $this->controllers as $controller) { -// error_log('CTRL: ' . $controller->controller); - include_once $controller->controller; - } + public function render() + { + extract($this->_vars); ob_start(); // Añadimos las plantillas - foreach ( $this->file as $template) { -// error_log('TPL: ' . $template); + foreach ($this->_file as $template) { include_once $template; } @@ -144,16 +143,20 @@ class SP_Template { * Comprobar si un archivo de plantilla existe y se puede leer * * @param string $file Con el nombre del archivo + * @return bool * @throws InvalidArgumentException */ - private function checkTemplate($file){ - $template = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR . $file . '.inc'; + private function checkTemplate($file) + { + $template = Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR . $file . '.inc'; - if (!is_file($template) || !is_readable($template)) { - throw new InvalidArgumentException('No es posible obtener la plantilla "' . $file .'"'); + if (!is_readable($template)) { + error_log('TPL: ' . $template); + throw new InvalidArgumentException('No es posible obtener la plantilla "' . $file . '"'); } $this->setTemplate($template); + return true; } /** @@ -161,8 +164,9 @@ class SP_Template { * * @param string $file Con el nombre del archivo */ - private function setTemplate($file){ - $this->file[] = $file; + private function setTemplate($file) + { + $this->_file[] = $file; } /** @@ -170,7 +174,8 @@ class SP_Template { * * @param array $vars Con los atributos de la clase */ - private function setVars(&$vars){ + private function setVars(&$vars) + { foreach ($vars as $name => $value) { $this->$name = $value; } @@ -181,64 +186,65 @@ class SP_Template { * * @param string $file Con el nombre del archivo de plantilla */ - public function addTemplate($file){ - if (!is_null($file) && $this->checkTemplate($file)){ + public function addTemplate($file) + { + if (!is_null($file) && $this->checkTemplate($file)) { $this->setTemplate($file); } } - public function setController(SP_Controller $controller){ - $this->controllers[] = $controller; - } - /** * Crear la variable y asignarle un valor en el array de variables * - * @param $name string nombre de la variable - * @param $value mixed valor de la variable + * @param $name string nombre de la variable + * @param $value mixed valor de la variable * @param null $scope string ámbito de la variable */ - public function assign($name, $value, $scope = null){ - if(!is_null($scope)){ + public function assign($name, $value, $scope = null) + { + if (!is_null($scope)) { $name = $scope . '_' . $name; } // error_log('SET: ' . $name . ' -> ' . $value); - $this->vars[$name] = $value; + $this->_vars[$name] = $value; } /** * Anexar el valor de la variable al array de la misma en el array de variables * - * @param $name string nombre de la variable - * @param $value mixed valor de la variable - * @param $index string índice del array + * @param $name string nombre de la variable + * @param $value mixed valor de la variable + * @param $index string índice del array * @param null $scope string ámbito de la variable */ - public function append($name, $value, $scope = null, $index = null){ - if(!is_null($scope)){ + public function append($name, $value, $scope = null, $index = null) + { + if (!is_null($scope)) { $name = $scope . '_' . $name; } - if (!is_null($index)){ - $this->vars[$name][$index] = $value; + if (!is_null($index)) { + $this->_vars[$name][$index] = $value; } else { - $this->vars[$name][] = $value; + $this->_vars[$name][] = $value; } } /** * Reset de las plantillas añadidas */ - public function resetTemplates(){ - $this->file = array(); + public function resetTemplates() + { + $this->_file = array(); } /** * Reset de las plantillas añadidas */ - public function resetVariables(){ - $this->vars = array(); + public function resetVariables() + { + $this->_vars = array(); } } \ No newline at end of file diff --git a/inc/Upgrade.class.php b/inc/Upgrade.class.php index 99c6c5ac..b802ea99 100644 --- a/inc/Upgrade.class.php +++ b/inc/Upgrade.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,15 +24,17 @@ * */ +namespace SP; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Esta clase es la encargada de realizar las operaciones actualización de la aplicación. */ -class SP_Upgrade +class Upgrade { - private static $dbUpgrade = array(110, 1121, 1122, 1123, 11213, 11219, 11220, 12001); - private static $cfgUpgrade = array(1124); + private static $_dbUpgrade = array(110, 1121, 1122, 1123, 11213, 11219, 11220, 12001); + private static $_cfgUpgrade = array(1124); /** * Inicia el proceso de actualización de la BBDD. @@ -42,10 +44,10 @@ class SP_Upgrade */ public static function doUpgrade($version) { - foreach (self::$dbUpgrade as $upgradeVersion) { + foreach (self::$_dbUpgrade as $upgradeVersion) { if ($version < $upgradeVersion) { if (self::upgradeTo($upgradeVersion) === false) { - SP_Init::initError( + Init::initError( _('Error al aplicar la actualización de la Base de Datos'), _('Compruebe el registro de eventos para más detalles') . '. ' . _('Acceder') . ''); } @@ -107,18 +109,18 @@ class SP_Upgrade } foreach ($queries as $query) { - try{ + try { DB::getQuery($query, __FUNCTION__); - } catch(SPDatabaseException $e){ + } catch (SPException $e) { $result['text'][] = _('Error al aplicar la actualización de la Base de Datos.') . ' (v' . $version . ')'; $result['text'][] = 'ERROR: ' . $e->getMessage() . ' (' . $e->getCode() . ')'; - SP_Log::wrLogInfo($result); + Log::wrLogInfo($result); return false; } } $result['text'][] = _('Actualización de la Base de Datos realizada correctamente.') . ' (v' . $version . ')'; - SP_Log::wrLogInfo($result); + Log::wrLogInfo($result); return true; } @@ -131,7 +133,9 @@ class SP_Upgrade */ public static function needDBUpgrade($version) { - $upgrades = array_filter(self::$dbUpgrade, function ($uVersions) use ($version){ return ($uVersions >= $version); } ); + $upgrades = array_filter(self::$_dbUpgrade, function ($uVersions) use ($version) { + return ($uVersions >= $version); + }); return (count($upgrades) > 0); } @@ -144,7 +148,7 @@ class SP_Upgrade */ public static function needConfigUpgrade($version) { - return (in_array($version, self::$cfgUpgrade)); + return (in_array($version, self::$_cfgUpgrade)); } /** @@ -181,18 +185,18 @@ class SP_Upgrade 'wiki_searchurl' => 'wikisearchurl' ); - $currData = SP_Config::getKeys(true); + $currData = Config::getKeys(true); - foreach ( $mapParams as $newParam => $oldParam){ - if ( array_key_exists($oldParam,$currData)){ - SP_Config::setValue($newParam,$currData[$oldParam]); - SP_Config::deleteKey($oldParam); + foreach ($mapParams as $newParam => $oldParam) { + if (array_key_exists($oldParam, $currData)) { + Config::setValue($newParam, $currData[$oldParam]); + Config::deleteKey($oldParam); } } $result['action'] = _('Actualizar Configuración'); $result['text'][] = _('Actualización de la Configuración realizada correctamente.') . ' (v' . $version . ')'; - SP_Log::wrLogInfo($result); + Log::wrLogInfo($result); return true; } diff --git a/inc/Users.class.php b/inc/Users.class.php index 31eaeb4b..e237a582 100644 --- a/inc/Users.class.php +++ b/inc/Users.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 osbre los usuarios de sysPass */ -class SP_Users +class Users { const USER_LOGIN_EXIST = 1; const USER_MAIL_EXIST = 2; @@ -201,7 +203,7 @@ class SP_Users */ public static function migrateUser($userLogin, $userPass) { - $passdata = SP_Users::makeUserPass($userPass); + $passdata = Users::makeUserPass($userPass); $query = 'UPDATE usrData SET ' . 'user_pass = :pass,' @@ -227,7 +229,7 @@ class SP_Users $message['text'][] = _('Usuario actualizado'); $message['text'][] = 'Login: ' . $userLogin; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); return true; } @@ -239,7 +241,7 @@ class SP_Users */ private static function makeUserPass($userPass) { - $salt = SP_Crypt::makeHashSalt(); + $salt = Crypt::makeHashSalt(); $userPass = sha1($salt . $userPass); return array('salt' => $salt, 'pass' => $userPass); @@ -265,7 +267,7 @@ class SP_Users return false; } - $configMPassTime = SP_Config::getConfigDbValue('lastupdatempass'); + $configMPassTime = Config::getConfigDbValue('lastupdatempass'); if ($configMPassTime === false) { return false; @@ -338,8 +340,8 @@ class SP_Users /** * Actualizar la asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta - * @param array $usersId con los usuarios de la cuenta + * @param int $accountId con el Id de la cuenta + * @param array $usersId con los usuarios de la cuenta * @return bool */ public static function updateUsersForAccount($accountId, $usersId) @@ -354,8 +356,8 @@ class SP_Users /** * Eliminar la asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta - * @param array $usersId opcional con los grupos de la cuenta + * @param int $accountId con el Id de la cuenta + * @param array $usersId opcional con los grupos de la cuenta * @return bool */ public static function deleteUsersForAccount($accountId, $usersId = null) @@ -378,8 +380,8 @@ class SP_Users /** * Crear asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta - * @param array $usersId con los grupos de la cuenta + * @param int $accountId con el Id de la cuenta + * @param array $usersId con los grupos de la cuenta * @return bool */ public static function addUsersForAccount($accountId, $usersId) @@ -412,10 +414,10 @@ class SP_Users } /** - * Obtiene el listado de grupos de una cuenta. + * Obtiene el listado de usuarios de una cuenta. * * @param int $accountId con el id de la cuenta - * @return object con el Id de grupo + * @return array con los id de usuarios de la cuenta */ public static function getUsersForAccount($accountId) { @@ -428,7 +430,7 @@ class SP_Users $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { - return false; + return array(); } foreach ($queryRes as $user) { @@ -682,9 +684,9 @@ class SP_Users $resUEmail = strtoupper($userData->user_email); if ($resULogin == $userLogin) { - return SP_Users::USER_LOGIN_EXIST; + return Users::USER_LOGIN_EXIST; } elseif ($resUEmail == $userEmail) { - return SP_Users::USER_MAIL_EXIST; + return Users::USER_MAIL_EXIST; } } } @@ -713,7 +715,7 @@ class SP_Users */ public function newUserLDAP() { - $passdata = SP_Users::makeUserPass($this->userPass); + $passdata = Users::makeUserPass($this->userPass); $query = 'INSERT INTO usrData SET ' . 'user_name = :name,' @@ -733,8 +735,8 @@ class SP_Users $data['hashSalt'] = $passdata['hash']; $data['email'] = $this->userEmail; $data['notes'] = 'LDAP'; - $data['groupId'] = SP_Config::getValue('ldap_defaultgroup', 0); - $data['profileId'] = SP_Config::getValue('ldap_defaultprofile', 0); + $data['groupId'] = Config::getValue('ldap_defaultgroup', 0); + $data['profileId'] = Config::getValue('ldap_defaultprofile', 0); if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; @@ -744,8 +746,8 @@ class SP_Users $message['text'][] = _('Su cuenta está pendiente de activación.'); $message['text'][] = _('En breve recibirá un email de confirmación.'); - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message, $this->userEmail, false); + Log::wrLogInfo($message); + Common::sendEmail($message, $this->userEmail, false); return true; } @@ -757,7 +759,7 @@ class SP_Users */ public function addUser() { - $passdata = SP_Users::makeUserPass($this->userPass); + $passdata = Users::makeUserPass($this->userPass); $query = 'INSERT INTO usrData SET ' . 'user_name = :name,' @@ -796,16 +798,16 @@ class SP_Users $this->queryLastId = DB::$lastId; $message['action'] = _('Nuevo Usuario'); - $message['text'][] = SP_Html::strongText(_('Usuario') . ': ') . $this->userName . ' (' . $this->userLogin . ')'; + $message['text'][] = Html::strongText(_('Usuario') . ': ') . $this->userName . ' (' . $this->userLogin . ')'; if ($this->userChangePass) { - if (!SP_Auth::mailPassRecover(DB::escape($this->userLogin), DB::escape($this->userEmail))) { - $message['text'][] = SP_Html::strongText(_('No se pudo realizar la petición de cambio de clave.')); + if (!Auth::mailPassRecover(DB::escape($this->userLogin), DB::escape($this->userEmail))) { + $message['text'][] = Html::strongText(_('No se pudo realizar la petición de cambio de clave.')); } } - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -850,16 +852,16 @@ class SP_Users $this->queryLastId = DB::$lastId; $message['action'] = _('Modificar Usuario'); - $message['text'][] = SP_Html::strongText(_('Usuario') . ': ') . $this->userName . ' (' . $this->userLogin . ')'; + $message['text'][] = Html::strongText(_('Usuario') . ': ') . $this->userName . ' (' . $this->userLogin . ')'; if ($this->userChangePass) { - if (!SP_Auth::mailPassRecover(DB::escape($this->userLogin), DB::escape($this->userEmail))) { - $message['text'][] = SP_Html::strongText(_('No se pudo realizar la petición de cambio de clave.')); + if (!Auth::mailPassRecover(DB::escape($this->userLogin), DB::escape($this->userEmail))) { + $message['text'][] = Html::strongText(_('No se pudo realizar la petición de cambio de clave.')); } } - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -871,7 +873,7 @@ class SP_Users */ public function updateUserPass() { - $passdata = SP_Users::makeUserPass($this->userPass); + $passdata = Users::makeUserPass($this->userPass); $userLogin = $this->getUserLoginById($this->userId); $query = 'UPDATE usrData SET ' @@ -892,10 +894,10 @@ class SP_Users $this->queryLastId = DB::$lastId; $message['action'] = _('Modificar Clave Usuario'); - $message['text'][] = SP_Html::strongText(_('Login') . ': ') . $userLogin; + $message['text'][] = Html::strongText(_('Login') . ': ') . $userLogin; - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -941,10 +943,10 @@ class SP_Users $this->queryLastId = DB::$lastId; $message['action'] = _('Eliminar Usuario'); - $message['text'][] = SP_Html::strongText(_('Login') . ': ') . $userLogin; + $message['text'][] = Html::strongText(_('Login') . ': ') . $userLogin; - SP_Log::wrLogInfo($message); - SP_Common::sendEmail($message); + Log::wrLogInfo($message); + Common::sendEmail($message); return true; } @@ -956,7 +958,7 @@ class SP_Users */ public function updateLDAPUserInDB() { - $passdata = SP_Users::makeUserPass($this->userPass); + $passdata = Users::makeUserPass($this->userPass); $query = 'UPDATE usrData SET ' . 'user_pass = :pass,' @@ -983,17 +985,17 @@ class SP_Users */ public function setUserSession() { - SP_Session::setUserLogin($this->userLogin); - SP_Session::setUserProfileId($this->userProfileId); - SP_Session::setUserName($this->userName); - SP_Session::setUserGroupId($this->userGroupId); - SP_Session::setUserGroupName($this->userGroupName); - SP_Session::setUserId($this->userId); - SP_Session::setUserEMail($this->userEmail); - SP_Session::setUserIsAdminApp($this->userIsAdminApp); - SP_Session::setUserIsAdminAcc($this->userIsAdminAcc); - SP_Session::setUserIsLdap($this->userIsLdap); - SP_Session::setUserProfile(SP_Profiles::getProfileForUser()); + Session::setUserLogin($this->userLogin); + Session::setUserProfileId($this->userProfileId); + Session::setUserName($this->userName); + Session::setUserGroupId($this->userGroupId); + Session::setUserGroupName($this->userGroupName); + Session::setUserId($this->userId); + Session::setUserEMail($this->userEmail); + Session::setUserIsAdminApp($this->userIsAdminApp); + Session::setUserIsAdminAcc($this->userIsAdminAcc); + Session::setUserIsLdap($this->userIsLdap); + Session::setUserProfile(Profiles::getProfileForUser()); $this->setUserLastLogin(); } @@ -1025,14 +1027,14 @@ class SP_Users return false; } - $configMPass = SP_Config::getConfigDbValue('masterPwd'); + $configMPass = Config::getConfigDbValue('masterPwd'); if ($configMPass === false) { return false; } // Comprobamos el hash de la clave del usuario con la guardada - return SP_Crypt::checkHashPass($userMPass, $configMPass); + return Crypt::checkHashPass($userMPass, $configMPass); } /** @@ -1054,7 +1056,7 @@ class SP_Users } if ($queryRes->user_mPass && $queryRes->user_mIV) { - $clearMasterPass = SP_Crypt::getDecrypt($queryRes->user_mPass, $this->getCypherPass(), $queryRes->user_mIV); + $clearMasterPass = Crypt::getDecrypt($queryRes->user_mPass, $this->getCypherPass(), $queryRes->user_mIV); if (!$clearMasterPass) { return false; @@ -1063,9 +1065,9 @@ class SP_Users if ($showPass == true) { return $clearMasterPass; } else { - $_SESSION['mPassPwd'] = SP_Util::generate_random_bytes(32); + $_SESSION['mPassPwd'] = Util::generate_random_bytes(32); - $sessionMasterPass = SP_Crypt::mkCustomMPassEncrypt($_SESSION["mPassPwd"], $clearMasterPass); + $sessionMasterPass = Crypt::mkCustomMPassEncrypt($_SESSION["mPassPwd"], $clearMasterPass); $_SESSION['mPass'] = $sessionMasterPass[0]; $_SESSION['mPassIV'] = $sessionMasterPass[1]; @@ -1083,7 +1085,7 @@ class SP_Users */ private function getCypherPass() { - $configSalt = SP_Config::getConfigDbValue('passwordsalt'); + $configSalt = Config::getConfigDbValue('passwordsalt'); $cypherPass = substr(sha1($configSalt . $this->userPass), 0, 32); return $cypherPass; @@ -1097,14 +1099,14 @@ class SP_Users */ public function updateUserMPass($masterPwd) { - $configMPass = SP_Config::getConfigDbValue('masterPwd'); + $configMPass = Config::getConfigDbValue('masterPwd'); if (!$configMPass) { return false; } - if (SP_Crypt::checkHashPass($masterPwd, $configMPass)) { - $strUserMPwd = SP_Crypt::mkCustomMPassEncrypt($this->getCypherPass(), $masterPwd); + if (Crypt::checkHashPass($masterPwd, $configMPass)) { + $strUserMPwd = Crypt::mkCustomMPassEncrypt($this->getCypherPass(), $masterPwd); if (!$strUserMPwd) { return false; diff --git a/inc/Util.class.php b/inc/Util.class.php index 4e29e46b..f81d6e89 100644 --- a/inc/Util.class.php +++ b/inc/Util.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,16 @@ * */ +namespace SP; + +use CssMin; + defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); /** * Clase con utilizades para la aplicación */ -class SP_Util +class Util { /** * Comprobar si la función de números aleatorios está disponible. @@ -110,13 +114,11 @@ class SP_Util public static function checkPhpVersion() { $error = array(); + $needsVersion = '5.3.0'; - $version = explode('.', PHP_VERSION); - $versionId = ($version[0] * 10000 + $version[1] * 100 + $version[2]); - - if ($versionId < 50100) { + if (version_compare(PHP_VERSION, $needsVersion, '>=')) { $error[] = array('type' => 'critical', - 'description' => _('Versión de PHP requerida >= 5.1'), + 'description' => _('Versión de PHP requerida >= ') . $needsVersion, 'hint' => _('Actualice la versión de PHP para que la aplicación funcione correctamente')); } @@ -130,22 +132,35 @@ class SP_Util */ public static function checkModules() { - $modsAvail = array_map('strtolower', get_loaded_extensions()); - $modsNeed = array('mysqli', 'ldap', 'mcrypt', 'curl', 'simplexml', 'phar', 'json', 'xml'); - $modsErr = array(); +// $modsAvail = array_map('strtolower', get_loaded_extensions()); + $modsNeed = array( + 'ldap', + 'mcrypt', + 'curl', + 'SimpleXML', + 'Phar', + 'json', + 'xml', + 'PDO', + 'zlib', + 'gettext', + 'openssl', + 'pcre', + 'session' + ); + $error = array(); foreach ($modsNeed as $module) { - if (!in_array($module, $modsAvail)) { - $error = array( + if (!extension_loaded($module)) { + $error[] = array( 'type' => 'warning', 'description' => _('Módulo no disponible') . " ($module)", 'hint' => _('Sin este módulo la aplicación puede no funcionar correctamente.') ); - $modsErr[] = $error; } } - return $modsErr; + return $error; } /** @@ -159,7 +174,7 @@ class SP_Util { $r = $d; if (isset($_REQUEST[$s]) && !empty($_REQUEST[$s])) { - $r = SP_Html::sanitize($_REQUEST[$s]); + $r = Html::sanitize($_REQUEST[$s]); } return $r; @@ -172,7 +187,7 @@ class SP_Util */ public static function ldapIsAvailable() { - return in_array("ldap", get_loaded_extensions()); + return extension_loaded('ldap'); } /** @@ -194,7 +209,7 @@ class SP_Util */ public static function checkUpdates() { - if (!self::curlIsAvailable() || !SP_Config::getValue('checkupdates')) { + if (!self::curlIsAvailable() || !Config::getValue('checkupdates')) { return false; } @@ -213,7 +228,7 @@ class SP_Util $message['action'] = __FUNCTION__; $message['text'][] = curl_error($ch); - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); return false; } @@ -238,7 +253,7 @@ class SP_Util preg_match("/v?(\d+)\.(\d+)\.(\d+)\.(\d+)(\-[a-z0-9.]+)?$/", $version, $realVer); - if (is_array($realVer) && SP_Init::isLoggedIn()) { + if (is_array($realVer) && Init::isLoggedIn()) { $appVersion = implode('', self::getVersion(true)); $pubVersion = $realVer[1] . $realVer[2] . $realVer[3] . $realVer[4]; @@ -295,17 +310,15 @@ class SP_Util { if ($_SERVER['REQUEST_METHOD'] !== $method || !isset($_SERVER['HTTP_REFERER']) - || !preg_match('#' . SP_Init::$WEBROOT . '/.*$#', $_SERVER['HTTP_REFERER']) + || !preg_match('#' . Init::$WEBROOT . '/.*$#', $_SERVER['HTTP_REFERER']) ) { - SP_Init::initError(_('No es posible acceder directamente a este archivo')); + Init::initError(_('No es posible acceder directamente a este archivo')); exit(); } } /** * Realiza el proceso de logout. - * - * @return none */ public static function logout() { @@ -314,8 +327,6 @@ class SP_Util /** * Obtener el tamaño máximo de subida de PHP. - * - * @return none */ public static function getMaxUpload() { @@ -327,7 +338,7 @@ class SP_Util $message['action'] = __FUNCTION__; $message['text'][] = "Max. PHP upload: " . $upload_mb . "MB"; - SP_Log::wrLogInfo($message); + Log::wrLogInfo($message); } /** @@ -337,14 +348,38 @@ class SP_Util */ public static function demoIsEnabled() { - $enabled = SP_Common::parseParams('s', 'demo_enabled', 0); - $reload = SP_Common::parseParams('s', 'reload', 0); + return self::boolval(Config::getValue('demo_enabled', false)); + } - if (!isset($_SESSION["demo_enabled"]) || $reload === 1) { - $enabled = $_SESSION['demo_enabled'] = SP_Config::getValue('demo_enabled', 0); + /** + * Checks a variable to see if it should be considered a boolean true or false. + * Also takes into account some text-based representations of true of false, + * such as 'false','N','yes','on','off', etc. + * + * @author Samuel Levy + * @param mixed $in The variable to check + * @param bool $strict If set to false, consider everything that is not false to + * be true. + * @return bool The boolean equivalent or null (if strict, and no exact equivalent) + */ + public static function boolval($in, $strict = false) + { + $out = null; + $in = (is_string($in) ? strtolower($in) : $in); + // if not strict, we only have to check if something is false + if (in_array($in, array('false', 'no', 'n', '0', 'off', false, 0), true) || !$in) { + $out = false; + } else if ($strict) { + // if strict, check the equivalent true values + if (in_array($in, array('true', 'yes', 'y', '1', 'on', true, 1), true)) { + $out = true; + } + } else { + // not strict? let the regular php bool check figure it out (will + // largely default to true) + $out = ($in ? true : false); } - - return self::boolval($enabled); + return $out; } /** @@ -354,15 +389,7 @@ class SP_Util */ public static function fileIsEnabled() { - $check = SP_Common::parseParams('s', 'files_enabled', false, true); - $enabled = SP_Common::parseParams('s', 'files_enabled', 0); - $reload = SP_Common::parseParams('s', 'reload', 0); - - if (!isset($_SESSION["files_enabled"]) || $reload === 1) { - $enabled = $_SESSION['files_enabled'] = SP_Config::getValue('files_enabled', false); - } - - return self::boolval($enabled); + return self::boolval(Config::getValue('files_enabled', false)); } /** @@ -372,14 +399,7 @@ class SP_Util */ public static function mailIsEnabled() { - $enabled = SP_Common::parseParams('s', 'mail_enabled', 0); - $reload = SP_Common::parseParams('s', 'reload', 0); - - if (!isset($_SESSION["mail_enabled"]) || $reload === 1) { - $enabled = $_SESSION['mail_enabled'] = SP_Config::getValue('mail_enabled', false); - } - - return self::boolval($enabled); + return self::boolval(Config::getValue('mail_enabled', false)); } /** @@ -389,14 +409,7 @@ class SP_Util */ public static function wikiIsEnabled() { -// $enabled = SP_Common::parseParams('s', 'wiki_enabled', 0); -// $reload = SP_Common::parseParams('s', 'reload', 0); -// -// if (!isset($_SESSION["wiki_enabled"]) || $reload === 1) { -// $enabled = $_SESSION['wiki_enabled'] = SP_Config::getValue('wiki_enabled', false); -// } - - return SP_Config::getValue('wiki_enabled', false); + return self::boolval(Config::getValue('wiki_enabled', false)); } /** @@ -406,14 +419,7 @@ class SP_Util */ public static function mailrequestIsEnabled() { -// $enabled = SP_Common::parseParams('s', 'mail_requestsenabled', 0); -// $reload = SP_Common::parseParams('s', 'reload', 0); -// -// if (!isset($_SESSION["mail_requestsenabled"]) || $reload === 1) { -// $enabled = $_SESSION['mail_requestsenabled'] = SP_Config::getValue('mail_requestsenabled', false); -// } - - return self::boolval(SP_Config::getValue('mail_requestsenabled', false)); + return self::boolval(Config::getValue('mail_requestsenabled', false)); } /** @@ -423,14 +429,7 @@ class SP_Util */ public static function ldapIsEnabled() { -// $enabled = SP_Common::parseParams('s', 'ldap_enabled', 0); -// $reload = SP_Common::parseParams('s', 'reload', 0); -// -// if (!isset($_SESSION["ldap_enabled"]) || $reload === 1) { -// $enabled = $_SESSION['ldap_enabled'] = SP_Config::getValue('ldap_enabled', false); -// } - - return self::boolval(SP_Config::getValue('ldap_enabled', false)); + return self::boolval(Config::getValue('ldap_enabled', false)); } /** @@ -440,14 +439,7 @@ class SP_Util */ public static function logIsEnabled() { -// $enabled = SP_Common::parseParams('s', 'log_enabled', 0); -// $reload = SP_Common::parseParams('s', 'reload', 0); -// -// if (!isset($_SESSION["log_enabled"]) || $reload === 1) { -// $enabled = $_SESSION['log_enabled'] = SP_Config::getValue('log_enabled', false); -// } - - return self::boolval(SP_Config::getValue('log_enabled', false)); + return self::boolval(Config::getValue('log_enabled', false)); } /** @@ -457,24 +449,15 @@ class SP_Util */ public static function resultsCardsIsEnabled() { -// $enabled = SP_Common::parseParams('s', 'resultsascards', 0); -// $reload = SP_Common::parseParams('s', 'reload', 0); -// -// if (!isset($_SESSION["resultsascards"]) || $reload === 1) { -// $enabled = $_SESSION['resultsascards'] = SP_Config::getValue('resultsascards', false); -// } - - return self::boolval(SP_Config::getValue('resultsascards', false)); + return self::boolval(Config::getValue('resultsascards', false)); } /** * Establecer variable de sesión para recargar la aplicación. - * - * @return none */ public static function reload() { - $reload = SP_Common::parseParams('s', 'reload', 0); + $reload = Common::parseParams('s', 'reload', 0); if ($reload === 0) { $_SESSION["reload"] = 1; @@ -483,12 +466,10 @@ class SP_Util /** * Comprobar si se necesita recargar la aplicación. - * - * @return none */ public static function checkReload() { - $reload = SP_Common::parseParams('s', 'reload', 0); + $reload = Common::parseParams('s', 'reload', 0); if ($reload === 1) { $_SESSION['reload'] = 0; @@ -501,9 +482,8 @@ class SP_Util * Método que devuelve un recurso CSS o JS comprimido. Si coincide el ETAG se * devuelve el código HTTP/304 * - * @param string $type tipo de recurso a devolver - * @param array $files archivos a parsear - * @return none + * @param string $type tipo de recurso a devolver + * @param array $files archivos a parsear */ public static function getMinified($type, &$files, $disableMinify = false) { @@ -527,7 +507,7 @@ class SP_Util exit; } - $path = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR; + $path = Init::$SERVERROOT . DIRECTORY_SEPARATOR; if ($type == 'js') { header("Content-type: application/x-javascript; charset: UTF-8"); @@ -537,7 +517,7 @@ class SP_Util flush(); - if(self::checkZlib() || !ob_start('ob_gzhandler')){ + if (self::checkZlib() || !ob_start('ob_gzhandler')) { ob_start(); } @@ -572,7 +552,7 @@ class SP_Util private static function getEtag(&$files) { $md5Sum = ''; - $path = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR; + $path = Init::$SERVERROOT . DIRECTORY_SEPARATOR; foreach ($files as $file) { $md5Sum .= md5_file($path . $file['href']); @@ -614,6 +594,17 @@ class SP_Util return $headers; } + /** + * Comprobar si la salida comprimida en con zlib está activada. + * No es compatible con ob_gzhandler() + * + * @return bool + */ + public static function checkZlib() + { + return self::boolval(ini_get('zlib.output_compression')); + } + /** * Comprimir código javascript. * @@ -635,57 +626,18 @@ class SP_Util return $buffer; } - /** - * Checks a variable to see if it should be considered a boolean true or false. - * Also takes into account some text-based representations of true of false, - * such as 'false','N','yes','on','off', etc. - * - * @author Samuel Levy - * @param mixed $in The variable to check - * @param bool $strict If set to false, consider everything that is not false to - * be true. - * @return bool The boolean equivalent or null (if strict, and no exact equivalent) - */ - public static function boolval($in, $strict = false) - { - $out = null; - $in = (is_string($in) ? strtolower($in) : $in); - // if not strict, we only have to check if something is false - if (in_array($in, array('false', 'no', 'n', '0', 'off', false, 0), true) || !$in) { - $out = false; - } else if ($strict) { - // if strict, check the equivalent true values - if (in_array($in, array('true', 'yes', 'y', '1', 'on', true, 1), true)) { - $out = true; - } - } else { - // not strict? let the regular php bool check figure it out (will - // largely default to true) - $out = ($in ? true : false); - } - return $out; - } - /** * Recorrer un array y escapar los carácteres no válidos en Javascript. * * @param $array * @return array */ - public static function arrayJSEscape(&$array){ - array_walk($array, function(&$value, $index) {$value = str_replace(array("'", '"'), "\\'", $value);}); - return $array; - } - - /** - * Comprobar si la salida comprimida en con zlib está activada. - * No es compatible con ob_gzhandler() - * - * @return bool - */ - public static function checkZlib() + public static function arrayJSEscape(&$array) { - return self::boolval(ini_get('zlib.output_compression')); + array_walk($array, function (&$value, $index) { + $value = str_replace(array("'", '"'), "\\'", $value); + }); + return $array; } /** @@ -694,7 +646,7 @@ class SP_Util * @param string $index con la key a devolver * @return array con las propiedades de la aplicación */ - public static function getAppInfo($index = NULL) + public static function getAppInfo($index = null) { $appinfo = array( 'appname' => 'sysPass', @@ -706,7 +658,7 @@ class SP_Util 'apphelp' => 'help.syspass.org', 'appchangelog' => ''); - if (!is_null($index) && array_key_exists($index, $appinfo)) { + if (!is_null($index) && isset($appinfo[$index])) { return $appinfo[$index]; } diff --git a/inc/tpl/account.inc b/inc/tpl/account.inc index b513e195..c3160868 100644 --- a/inc/tpl/account.inc +++ b/inc/tpl/account.inc @@ -2,7 +2,7 @@
- accountIsHistory): ?> +
@@ -23,57 +23,47 @@ @@ -114,14 +104,14 @@ $otherGroupId) { $uGroupSelected = ''; if ($gotData && $otherGroupId != $accountData->account_userGroupId) { - if (isset($account->accountUserGroupsId) && is_array($account->accountUserGroupsId)) { - $uGroupSelected = (in_array($otherGroupId, $account->accountUserGroupsId)) ? "selected" : ""; + if (is_array($accountOtherGroups)) { + $uGroupSelected = (in_array($otherGroupId, $accountOtherGroups)) ? "selected" : ""; } echo ""; } else { @@ -178,9 +168,11 @@ - - - + + + + + @@ -191,43 +183,31 @@ - + 0): ?> diff --git a/inc/tpl/install.inc b/inc/tpl/install.inc index c3dd9b42..08a3c93b 100644 --- a/inc/tpl/install.inc +++ b/inc/tpl/install.inc @@ -1,7 +1,9 @@
@@ -10,7 +12,7 @@ 'hint' => _('Actualice la versión de PHP para usar sysPass de forma segura')); ?> - + 'warning', 'description' => _('No se encuentra el generador de números aleatorios.'), 'hint' => _('Sin esta función un atacante puede utilizar su cuenta al resetear la clave')); ?> @@ -44,7 +46,7 @@ title=""/>

@@ -54,7 +56,7 @@ @@ -69,7 +71,7 @@ @@ -86,7 +88,7 @@ title=""/> + value="" autocomplete=off" required/>

@@ -94,7 +96,7 @@ alt=""/> + value="" required/>

@@ -102,7 +104,7 @@ title=""/>

@@ -111,7 +113,7 @@ title=""/> + value="" required/>


@@ -120,10 +122,10 @@ + for="hostingmode"> /> + class="checkbox" />

@@ -133,7 +135,7 @@
- +

- echo $accountData->customer_name; + customer_name; ?>
- category_name; - } - ?> + + + + category_name; ?> +
- + - account_url; - } - ?> + + account_url; ?> +
- + - account_login; - } - ?> + + account_login; ?> +
- accountIsHistory): ?> - + + - - + +
upload
- +
- "historyId", - "id" => "sel-history", - "class" => "", - "size" => 1, - "label" => "", - "selected" => ($account->accountIsHistory) ? $account->accountId : "", - "default" => "", - "js" => "OnChange=\"if ( $('#sel-history').val() > 0 ) doAction(" . SP_Acl::ACTION_ACC_VIEW_HISTORY . "," . SP_Acl::ACTION_ACC_VIEW . ", $('#sel-history').val());\"", - "attribs" => ''); - - SP_Html::printSelect($account->getAccountHistoryList(), $arrSelectProp); - ?> + \ No newline at end of file diff --git a/inc/tpl/info.inc b/inc/tpl/info.inc index 62ac86c9..5f0dfde7 100644 --- a/inc/tpl/info.inc +++ b/inc/tpl/info.inc @@ -1,5 +1,7 @@ -
+
@@ -10,7 +12,7 @@
- +