diff --git a/app/modules/api/Controllers/AccountController.php b/app/modules/api/Controllers/AccountController.php
index 0e8da722..8b7185d4 100644
--- a/app/modules/api/Controllers/AccountController.php
+++ b/app/modules/api/Controllers/AccountController.php
@@ -26,12 +26,12 @@ namespace SP\Modules\Api\Controllers;
use SP\Account\AccountRequest;
use SP\Account\AccountSearchFilter;
-use SP\Api\ApiResponse;
use SP\Core\Acl\ActionsInterface;
use SP\Core\Crypt\Crypt;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
use SP\Services\Account\AccountService;
+use SP\Services\Api\ApiResponse;
/**
* Class AccountController
@@ -53,17 +53,19 @@ class AccountController extends ControllerBase
try {
$this->setupApi(ActionsInterface::ACCOUNT_VIEW);
- $accountId = $this->apiService->getParam('id', true);
- $accountVData = $this->accountService->getById($accountId)->getAccountVData();
+ $accountId = $this->apiService->getParamInt('id', true);
+ $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+
$this->accountService->incrementViewCounter($accountId);
$this->eventDispatcher->notifyEvent('show.account',
new Event($this, EventMessage::factory()
->addDescription(__u('Cuenta visualizada'))
- ->addDetail(__u('Cuenta'), $accountVData->getName()))
+ ->addDetail(__u('Cuenta'), $accountDetails->getName())
+ ->addDetail(__u('Cliente'), $accountDetails->getClientName()))
);
- $this->returnResponse(new ApiResponse($accountVData));
+ $this->returnResponse(new ApiResponse($accountDetails));
} catch (\Exception $e) {
$this->returnResponseException($e);
@@ -72,23 +74,26 @@ class AccountController extends ControllerBase
}
/**
- * viewAction
+ * viewPassAction
*/
public function viewPassAction()
{
try {
$this->setupApi(ActionsInterface::ACCOUNT_VIEW_PASS);
- $accountId = $this->apiService->getParam('id', true);
+ $accountId = $this->apiService->getParamInt('id', true);
$accountPassData = $this->accountService->getPasswordForId($accountId);
$password = Crypt::decrypt($accountPassData->getPass(), Crypt::unlockSecuredKey($accountPassData->getKey(), $this->apiService->getMasterPass()));
$this->accountService->incrementDecryptCounter($accountId);
+ $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+
$this->eventDispatcher->notifyEvent('show.account.pass',
new Event($this, EventMessage::factory()
->addDescription(__u('Clave visualizada'))
- ->addDetail(__u('Cuenta'), $accountPassData->getName()))
+ ->addDetail(__u('Cuenta'), $accountDetails->getName())
+ ->addDetail(__u('Cliente'), $accountDetails->getClientName()))
);
$this->returnResponse(new ApiResponse(["itemId" => $accountId, "password" => $password]));
@@ -108,22 +113,22 @@ class AccountController extends ControllerBase
$this->setupApi(ActionsInterface::ACCOUNT_CREATE);
$accountRequest = new AccountRequest();
- $accountRequest->name = $this->apiService->getParam('name', true);
- $accountRequest->clientId = $this->apiService->getParam('clientId', true);
- $accountRequest->categoryId = $this->apiService->getParam('categoryId', true);
- $accountRequest->login = $this->apiService->getParam('login');
- $accountRequest->url = $this->apiService->getParam('url');
- $accountRequest->notes = $this->apiService->getParam('notes');
+ $accountRequest->name = $this->apiService->getParamString('name', true);
+ $accountRequest->clientId = $this->apiService->getParamInt('clientId', true);
+ $accountRequest->categoryId = $this->apiService->getParamInt('categoryId', true);
+ $accountRequest->login = $this->apiService->getParamString('login');
+ $accountRequest->url = $this->apiService->getParamString('url');
+ $accountRequest->notes = $this->apiService->getParamString('notes');
$accountRequest->otherUserEdit = 0;
$accountRequest->otherUserGroupEdit = 0;
- $accountRequest->isPrivate = $this->apiService->getParam('private');
- $accountRequest->isPrivateGroup = $this->apiService->getParam('privateGroup');
- $accountRequest->passDateChange = $this->apiService->getParam('expireDate');
- $accountRequest->parentId = $this->apiService->getParam('parentId');
+ $accountRequest->isPrivate = $this->apiService->getParamInt('private');
+ $accountRequest->isPrivateGroup = $this->apiService->getParamInt('privateGroup');
+ $accountRequest->passDateChange = $this->apiService->getParamInt('expireDate');
+ $accountRequest->parentId = $this->apiService->getParamInt('parentId');
$accountRequest->userGroupId = $this->context->getUserData()->getUserGroupId();
$accountRequest->userId = $this->context->getUserData()->getId();
- $pass = $this->accountService->getPasswordEncrypted($this->apiService->getParam('pass', true), $this->apiService->getMasterPass());
+ $pass = $this->accountService->getPasswordEncrypted($this->apiService->getParamRaw('pass', true), $this->apiService->getMasterPass());
$accountRequest->pass = $pass['pass'];
$accountRequest->key = $pass['key'];
@@ -155,11 +160,11 @@ class AccountController extends ControllerBase
$this->setupApi(ActionsInterface::ACCOUNT_SEARCH);
$accountSearchFilter = new AccountSearchFilter();
- $accountSearchFilter->setTxtSearch($this->apiService->getParam('text'));
- $accountSearchFilter->setCategoryId($this->apiService->getParam('categoryId'));
- $accountSearchFilter->setClientId($this->apiService->getParam('clientId'));
- $accountSearchFilter->setLimitCount($this->apiService->getParam('count', false, 50));
- $accountSearchFilter->setSortOrder($this->apiService->getParam('order', false, AccountSearchFilter::SORT_DEFAULT));
+ $accountSearchFilter->setTxtSearch($this->apiService->getParamString('text'));
+ $accountSearchFilter->setCategoryId($this->apiService->getParamInt('categoryId'));
+ $accountSearchFilter->setClientId($this->apiService->getParamInt('clientId'));
+ $accountSearchFilter->setLimitCount($this->apiService->getParamInt('count', false, 50));
+ $accountSearchFilter->setSortOrder($this->apiService->getParamInt('order', false, AccountSearchFilter::SORT_DEFAULT));
$this->returnResponse(new ApiResponse($this->accountService->getByFilter($accountSearchFilter)->getData()));
} catch (\Exception $e) {
@@ -169,6 +174,36 @@ class AccountController extends ControllerBase
}
}
+ /**
+ * deleteAction
+ */
+ public function deleteAction()
+ {
+ try {
+ $this->setupApi(ActionsInterface::ACCOUNT_DELETE);
+
+
+ $accountId = $this->apiService->getParamInt('id', true);
+
+ $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+
+ $this->accountService->delete($accountId);
+
+ $this->eventDispatcher->notifyEvent('delete.account',
+ new Event($this, EventMessage::factory()
+ ->addDescription(__u('Cuenta eliminada'))
+ ->addDetail(__u('Cuenta'), $accountDetails->getName())
+ ->addDetail(__u('Cliente'), $accountDetails->getClientName()))
+ );
+
+ $this->returnResponse(new ApiResponse(__u('Cuenta eliminada'), ApiResponse::RESULT_SUCCESS, $accountId));
+ } catch (\Exception $e) {
+ $this->returnResponseException($e);
+
+ processException($e);
+ }
+ }
+
/**
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
diff --git a/app/modules/api/Controllers/ControllerBase.php b/app/modules/api/Controllers/ControllerBase.php
index 16ef9063..8667ec1d 100644
--- a/app/modules/api/Controllers/ControllerBase.php
+++ b/app/modules/api/Controllers/ControllerBase.php
@@ -26,12 +26,13 @@ namespace SP\Modules\Api\Controllers;
use DI\Container;
use Klein\Klein;
-use SP\Api\ApiResponse;
-use SP\Api\JsonRpcResponse;
use SP\Core\Context\StatelessContext;
use SP\Core\Events\EventDispatcher;
use SP\Core\Exceptions\SPException;
+use SP\Services\Api\ApiRequest;
+use SP\Services\Api\ApiResponse;
use SP\Services\Api\ApiService;
+use SP\Services\Api\JsonRpcResponse;
/**
* Class ControllerBase
@@ -76,21 +77,20 @@ abstract class ControllerBase
/**
* Constructor
*
- * @param Container $container
- * @param string $actionName
- * @param mixed $requesData
+ * @param Container $container
+ * @param string $actionName
+ * @param ApiRequest $apiRequest
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
- public final function __construct(Container $container, $actionName, $requesData)
+ public final function __construct(Container $container, $actionName, ApiRequest $apiRequest)
{
$this->dic = $container;
$this->context = $container->get(StatelessContext::class);
$this->eventDispatcher = $container->get(EventDispatcher::class);
$this->router = $container->get(Klein::class);
- $this->apiService = $container->get(ApiService::class);
- $this->apiService->setRequestData($requesData);
+ $this->apiService = $container->get(ApiService::class)->setApiRequest($apiRequest);
$this->controllerName = $this->getControllerName();
$this->actionName = $actionName;
@@ -135,7 +135,7 @@ abstract class ControllerBase
*
* {"jsonrpc": "2.0", "result": 19, "id": 3}
*
- * @param ApiResponse $apiResponse
+ * @param \SP\Services\Api\ApiResponse $apiResponse
* @return string La cadena en formato JSON
*/
final protected function returnResponse(ApiResponse $apiResponse)
diff --git a/app/modules/api/Controllers/Traits/ResponseTrait.php b/app/modules/api/Controllers/Traits/ResponseTrait.php
deleted file mode 100644
index 1dd7bc5c..00000000
--- a/app/modules/api/Controllers/Traits/ResponseTrait.php
+++ /dev/null
@@ -1,72 +0,0 @@
-.
- */
-
-namespace SP\Modules\Api\Controllers\Traits;
-
-use Klein\Klein;
-use SP\Api\ApiResponse;
-use SP\Api\JsonRpcResponse;
-use SP\Core\Exceptions\SPException;
-
-/**
- * Trait ResponseTrait
- * @package SP\Modules\Api\Controllers\Traits
- * @property Klein $router
- */
-trait ResponseTrait
-{
- /**
- * Devuelve una respuesta en formato JSON con el estado y el mensaje.
- *
- * {"jsonrpc": "2.0", "result": 19, "id": 3}
- *
- * @param ApiResponse $apiResponse
- * @param int $id
- * @return string La cadena en formato JSON
- */
- protected function returnResponse(ApiResponse $apiResponse, $id = 0)
- {
- $this->router->response()->headers()->set('Content-type', 'application/json; charset=utf-8');
-
- try {
- exit(JsonRpcResponse::getResponse($apiResponse, $id));
- } catch (SPException $e) {
- processException($e);
-
- exit(JsonRpcResponse::getResponseException($e, $id));
- }
- }
-
- /**
- * @param \Exception $e
- * @param int $id
- * @return string
- */
- protected function returnResponseException(\Exception $e, $id = 0)
- {
- $this->router->response()->headers()->set('Content-type', 'application/json; charset=utf-8');
-
- exit(JsonRpcResponse::getResponseException($e, $id));
- }
-}
\ No newline at end of file
diff --git a/app/modules/web/Controllers/LoginController.php b/app/modules/web/Controllers/LoginController.php
index 9ee5a555..46d967fe 100644
--- a/app/modules/web/Controllers/LoginController.php
+++ b/app/modules/web/Controllers/LoginController.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link https://syspass.org
+ * @author nuxsmin
+ * @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -27,7 +27,6 @@ namespace SP\Modules\Web\Controllers;
use SP\Core\Context\SessionContext;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
-use SP\Core\SessionFactory;
use SP\Core\SessionUtil;
use SP\Http\Request;
use SP\Http\Response;
@@ -121,8 +120,8 @@ class LoginController extends ControllerBase
$layoutHelper = $this->dic->get(LayoutHelper::class);
$layoutHelper->getCustomLayout('index', 'login');
- if (SessionFactory::getLoggedOut() === true) {
- SessionFactory::setLoggedOut();
+ if ($this->session->isLoggedIn() === true) {
+ $this->session->setAppStatus(SessionContext::APP_STATUS_LOGGEDOUT);
$this->view->assign('loggedOut', 1);
} else {
@@ -130,7 +129,7 @@ class LoginController extends ControllerBase
}
$this->view->assign('mailEnabled', $this->configData->isMailEnabled());
- $this->view->assign('updated', SessionFactory::getAppUpdated());
+// $this->view->assign('updated', SessionFactory::getAppUpdated());
$this->view();
}
diff --git a/app/modules/web/Forms/UserForm.php b/app/modules/web/Forms/UserForm.php
index 520bc078..0d8f0ed9 100644
--- a/app/modules/web/Forms/UserForm.php
+++ b/app/modules/web/Forms/UserForm.php
@@ -127,7 +127,7 @@ class UserForm extends FormBase implements FormInterface
if ($this->configData->isDemoEnabled()
&& $this->userData->getLogin() === 'demo'
- && !SessionFactory::getUserData()->isAdminApp()) {
+ && !$this->userData->isAdminApp()) {
throw new ValidationException(__u('Ey, esto es una DEMO!!'));
}
}
diff --git a/app/modules/web/Init.php b/app/modules/web/Init.php
index 8dce8767..ae689bf2 100644
--- a/app/modules/web/Init.php
+++ b/app/modules/web/Init.php
@@ -36,7 +36,6 @@ use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Exceptions\InitializationException;
use SP\Core\Language;
use SP\Core\ModuleBase;
-use SP\Core\Plugin\PluginUtil;
use SP\Core\UI\Theme;
use SP\Http\Request;
use SP\Services\UserProfile\UserProfileService;
@@ -158,7 +157,7 @@ class Init extends ModuleBase
$this->initUserSession();
// Cargar los plugins
- PluginUtil::loadPlugins();
+// PluginUtil::loadPlugins();
// Comprobar acciones en URL
// $this->checkPreLoginActions();
diff --git a/app/modules/web/themes/material-blue/views/login/index.inc b/app/modules/web/themes/material-blue/views/login/index.inc
index 48902952..60232af6 100644
--- a/app/modules/web/themes/material-blue/views/login/index.inc
+++ b/app/modules/web/themes/material-blue/views/login/index.inc
@@ -72,7 +72,7 @@
-
+
diff --git a/lib/SP/Api/ApiBase.php b/lib/SP/Api/ApiBase.php
deleted file mode 100644
index d50dc1fc..00000000
--- a/lib/SP/Api/ApiBase.php
+++ /dev/null
@@ -1,255 +0,0 @@
-.
- */
-
-namespace SP\Api;
-
-defined('APP_ROOT') || die();
-
-use Defuse\Crypto\Exception\CryptoException;
-use SP\Core\Crypt\Hash;
-use SP\Core\Crypt\Vault;
-use SP\Core\Exceptions\InvalidArgumentException;
-use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\DataModel\AuthTokenData;
-use SP\DataModel\UserLoginData;
-use SP\Log\Log;
-use SP\Mgmt\ApiTokens\ApiToken;
-use SP\Mgmt\Users\User;
-use SP\Util\Json;
-
-/**
- * Class ApiBase
- *
- * @package SP\Api
- */
-abstract class ApiBase implements ApiInterface
-{
- /**
- * El ID de la acción
- *
- * @var int
- */
- protected $actionId = 0;
- /**
- * El ID de usuario resuelto
- *
- * @var int
- */
- protected $userId = 0;
- /**
- * Indica si la autentificación es correcta
- *
- * @var bool
- */
- protected $auth = false;
- /**
- * Los parámetros de la acción a ejecutar
- *
- * @var mixed
- */
- protected $data;
- /**
- * @var UserLoginData
- */
- protected $UserData;
- /**
- * @var Log
- */
- protected $Log;
- /**
- * @var AuthTokenData
- */
- protected $ApiTokenData;
-
- /**
- * @param $data
- * @throws \SP\Core\Exceptions\SPException
- */
- public function __construct($data)
- {
- $this->actionId = $this->getActionId($data->method);
- $this->ApiTokenData = ApiToken::getItem()->getTokenByToken($this->actionId, $data->params->authToken);
-
- if ($this->ApiTokenData === false) {
- ApiUtil::addTracking();
-
- throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
- }
-
- $this->data = $data;
-
- $this->userId = $this->ApiTokenData->getUserId();
-
- $this->loadUserData();
-
- if ($this->passIsNeeded()) {
- $this->doAuth();
- }
-
- SessionFactory::setSessionType(SessionFactory::SESSION_API);
-
- $this->Log = new Log();
- }
-
- /**
- * Devolver el código de acción a realizar a partir del nombre
- *
- * @param $action string El nombre de la acción
- * @return int
- */
- protected function getActionId($action)
- {
- $actions = $this->getActions();
-
- return isset($actions[$action]) ? $actions[$action]['id'] : 0;
- }
-
- /**
- * Cargar los datos del usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function loadUserData()
- {
- $this->UserData = User::getItem()->getById($this->ApiTokenData->getUserId());
-
- SessionUtil::loadUserSession($this->UserData);
- }
-
- /**
- * @return bool
- */
- protected abstract function passIsNeeded();
-
- /**
- * Realizar la autentificación del usuario
- *
- * @throws SPException
- */
- protected function doAuth()
- {
- if ($this->UserData->isIsDisabled()
- || !Hash::checkHashKey($this->getParam('tokenPass', true), $this->ApiTokenData->getHash())
- ) {
- ApiUtil::addTracking();
-
- throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
- }
- }
-
- /**
- * Devolver el valor de un parámetro
- *
- * @param string $name Nombre del parámetro
- * @param bool $required Si es requerido
- * @param mixed $default Valor por defecto
- * @return int|string
- * @throws SPException
- */
- protected function getParam($name, $required = false, $default = null)
- {
- if ($required === true && !isset($this->data->params->$name)) {
- throw new InvalidArgumentException(SPException::WARNING, __('Parámetros incorrectos', false), $this->getHelp($this->data->method));
- }
-
- if (isset($this->data->params->$name)) {
- return $this->data->params->$name;
- }
-
- return $default;
- }
-
- /**
- * Devolver la clave maestra
- *
- * @return string
- * @throws SPException
- */
- protected function getMPass()
- {
- try {
- /** @var Vault $Vault */
- $Vault = unserialize($this->ApiTokenData->getVault());
-
- if ($Vault && $pass = $Vault->getData($this->getParam('tokenPass') . $this->getParam('authToken'))) {
- return $pass;
- } else {
- throw new SPException(__('Error interno', false), SPException::ERROR, __('Datos inválidos', false));
- }
- } catch (CryptoException $e) {
- throw new SPException(__('Error interno', false), SPException::ERROR, $e->getMessage());
- }
- }
-
- /**
- * Comprobar el acceso a la acción
- *
- * @param $action
- * @throws SPException
- */
- protected function checkActionAccess($action)
- {
- if ($this->actionId !== $action) {
- ApiUtil::addTracking();
-
- throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
- }
- }
-
- /**
- * Devuelve una respuesta en formato JSON con el estado y el mensaje.
- *
- * {"jsonrpc": "2.0", "result": 19, "id": 3}
- *
- * @param string $data Los datos a devolver
- * @return string La cadena en formato JSON
- * @throws SPException
- */
- protected function wrapJSON(&$data)
- {
- $json = [
- 'jsonrpc' => '2.0',
- 'result' => $data,
- 'id' => $this->data->id
- ];
-
- return Json::getJson($json);
- }
-
- /**
- * Comprobar si se ha realizado la autentificación
- *
- * @throws SPException
- */
- protected function checkAuth()
- {
- if ($this->auth === false) {
- ApiUtil::addTracking();
-
- throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
- }
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Api/ApiInterface.php b/lib/SP/Api/ApiInterface.php
deleted file mode 100644
index bad0e95a..00000000
--- a/lib/SP/Api/ApiInterface.php
+++ /dev/null
@@ -1,48 +0,0 @@
-.
- */
-
-namespace SP\Api;
-
-/**
- * Interface ApiInterface
- *
- * @package SP\Api
- */
-interface ApiInterface
-{
- /**
- * Devuelve las acciones que implementa la API
- *
- * @return array
- */
- public function getActions();
-
- /**
- * Devuelve la ayuda para una acción
- *
- * @param string $action
- * @return array
- */
- public function getHelp($action);
-}
\ No newline at end of file
diff --git a/lib/SP/Api/ApiRequest.php b/lib/SP/Api/ApiRequest.php
deleted file mode 100644
index 857e148e..00000000
--- a/lib/SP/Api/ApiRequest.php
+++ /dev/null
@@ -1,255 +0,0 @@
-.
- */
-
-namespace SP\Api;
-
-defined('APP_ROOT') || die();
-
-use ReflectionClass;
-use SP\Core\Exceptions\InvalidArgumentException;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\TrackData;
-use SP\Http\Request;
-use SP\Mgmt\Tracks\Track;
-use SP\Util\Json;
-
-/**
- * Class ApiRequest encargada de atender la peticiones a la API de sysPass
- *
- * Procesa peticiones en formato JSON-RPC 2.0
- *
- * {"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 3}
- *
- * @see http://www.jsonrpc.org/specification
- * @package SP
- */
-class ApiRequest
-{
- /**
- * Constantes de acciones
- */
- const ACTION = 'action';
- const AUTH_TOKEN = 'authToken';
- const TIME_TRACKING_MAX_ATTEMPTS = 5;
- const TIME_TRACKING = 300;
-
- /**
- * @var \stdClass
- */
- private $data;
- /** @var string */
- private $verb;
- /** @var ReflectionClass */
- private $ApiReflection;
-
- /**
- * Devolver un error formateado en JSON-RPC 2.0
- *
- * @param \Exception|SPException $e
- * @return string
- * @throws \SP\Core\Exceptions\SPException
- */
- public function formatJsonError($e)
- {
- $data = function () use ($e) {
- $class = get_class($e);
-
- if ($class === SPException::class
- || $class === InvalidArgumentException::class
- ) {
- $hint = $e->getHint();
-
- return is_array($hint) ? $hint : __($hint);
- }
-
- return '';
- };
-
- $code = $e->getCode();
-
- $error = [
- 'jsonrpc' => '2.0',
- 'error' => [
- 'code' => $code,
- 'message' => __($e->getMessage()),
- 'data' => $data()
- ],
- 'id' => ($code === -32700 || $code === -32600) ? null : $this->getId()
- ];
-
- return Json::getJson($error);
- }
-
- /**
- * Devielve el Id de la petición
- *
- * @return int
- */
- public function getId()
- {
- return (int)$this->data->id;
- }
-
- /**
- * Obtiene una nueva instancia de la Api
- *
- * @return SyspassApi
- * @throws \SP\Core\Exceptions\SPException
- */
- public function runApi()
- {
- $this->init();
-
- return $this->ApiReflection->getMethod($this->data->method)->invoke(new SyspassApi($this->data));
- }
-
- /**
- * Inicializar la API
- *
- * @throws SPException
- */
- protected function init()
- {
- try {
- $this->checkTracking();
- $this->analyzeRequestMethod();
- $this->getRequestData();
- $this->checkBasicData();
- $this->checkAction();
- } catch (SPException $e) {
- throw $e;
- }
- }
-
- /**
- * Comprobar los intentos de login
- *
- * @throws \SP\Core\Exceptions\AuthException
- * @throws \SP\Core\Exceptions\SPException
- */
- private function checkTracking()
- {
- try {
- $TrackData = new TrackData();
- $TrackData->setSource('API');
- $TrackData->setTrackIp($_SERVER['REMOTE_ADDR']);
-
- $attempts = count(Track::getItem($TrackData)->getTracksForClientFromTime(time() - self::TIME_TRACKING));
- } catch (SPException $e) {
- throw new SPException(__('Error interno', false), SPException::ERROR, __FUNCTION__, -32601);
- }
-
- if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) {
- ApiUtil::addTracking();
-
- sleep(0.3 * $attempts);
-
- throw new SPException(__('Intentos excedidos', false), SPException::INFO, '', -32601);
- }
- }
-
- /**
- * Analizar y establecer el método HTTP a utilizar
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function analyzeRequestMethod()
- {
- $requestMethod = $_SERVER['REQUEST_METHOD'];
-
- // Sólo se permiten estos métodos
- switch ($requestMethod) {
- case 'GET':
- case 'POST':
- case 'PUT':
- case 'DELETE':
- $this->verb = $requestMethod;
- break;
- default:
- throw new SPException(__('Método inválido', false), SPException::WARNING, '', -32600);
- }
- }
-
- /**
- * Obtener los datos de la petición
- *
- * Comprueba que el JSON esté bien formado
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function getRequestData()
- {
- $request = file_get_contents('php://input');
- $data = json_decode(Request::parse($request, '', true));
-
- if (!is_object($data) || json_last_error() !== JSON_ERROR_NONE) {
- throw new SPException(__('Datos inválidos', false), SPException::WARNING, '', -32700);
- }
-
- if (!isset($data->jsonrpc, $data->method, $data->params, $data->id)) {
- throw new SPException(__('Formato incorrecto', false), SPException::WARNING, '', -32600);
- }
-
- $this->data = $data;
- }
-
- /**
- * Comprobar los datos básicos de la petición
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function checkBasicData()
- {
- if (!isset($this->data->params->authToken)) {
- throw new SPException(__('Parámetros incorrectos', false), SPException::WARNING, '', -32602);
- }
- }
-
- /**
- * Comprobar si la API tiene implementada dicha acción
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function checkAction()
- {
- $this->ApiReflection = new ReflectionClass(SyspassApi::class);
-
- if (!$this->ApiReflection->hasMethod($this->data->method)) {
- ApiUtil::addTracking();
-
- throw new SPException(__('Acción Inválida', false), SPException::WARNING, '', -32601);
- }
- }
-
-
- /**
- * Obtener el id de la acción
- *
- * @return int
- */
- public function getAction()
- {
- return $this->data->method;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Api/ApiUtil.php b/lib/SP/Api/ApiUtil.php
deleted file mode 100644
index 8255dee4..00000000
--- a/lib/SP/Api/ApiUtil.php
+++ /dev/null
@@ -1,58 +0,0 @@
-.
- */
-
-namespace SP\Api;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\TrackData;
-use SP\Mgmt\Tracks\Track;
-use SP\Util\HttpUtil;
-
-/**
- * Class ApiUtil
- *
- * @package SP\Api
- */
-class ApiUtil
-{
- /**
- * Añadir un seguimiento
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public static function addTracking()
- {
- try {
- $TrackData = new TrackData();
- $TrackData->setSource('API');
- $TrackData->setTrackIp(HttpUtil::getClientAddress());
-
- Track::getItem($TrackData)->add();
- } catch (SPException $e) {
- throw new SPException(__('Error interno', false), SPException::WARNING, '', -32601);
- }
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Bootstrap.php b/lib/SP/Bootstrap.php
index 81856f97..502af170 100644
--- a/lib/SP/Bootstrap.php
+++ b/lib/SP/Bootstrap.php
@@ -30,7 +30,6 @@ use Klein\Klein;
use Klein\Response;
use PHPMailer\PHPMailer\Exception;
use RuntimeException;
-use SP\Api\JsonRpcResponse;
use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Config\ConfigUtil;
@@ -43,7 +42,8 @@ use SP\Core\UI\Theme;
use SP\Core\Upgrade\Upgrade;
use SP\Modules\Api\Init as InitApi;
use SP\Modules\Web\Init as InitWeb;
-use SP\Services\Api\ApiService;
+use SP\Services\Api\ApiRequest;
+use SP\Services\Api\JsonRpcResponse;
use SP\Services\Upgrade\UpgradeConfigService;
use SP\Services\Upgrade\UpgradeUtil;
use SP\Util\Checks;
@@ -164,9 +164,9 @@ class Bootstrap
'@/api\.php',
function ($request, $response, $service) use ($oops) {
try {
- $requesData = ApiService::getRequestData();
+ $apiRequest = (new ApiRequest())->getRequestData();
- list($controller, $action) = explode('/', $requesData->method);
+ list($controller, $action) = explode('/', $apiRequest->getMethod());
$controllerClass = 'SP\\Modules\\' . ucfirst(APP_MODULE) . '\\Controllers\\' . ucfirst($controller) . 'Controller';
$method = $action . 'Action';
@@ -183,7 +183,7 @@ class Bootstrap
debugLog('Routing call: ' . $controllerClass . '::' . $method);
- return call_user_func([new $controllerClass(self::$container, $method, $requesData), $method]);
+ return call_user_func([new $controllerClass(self::$container, $method, $apiRequest), $method]);
} catch (\Exception $e) {
processException($e);
diff --git a/lib/SP/Controller/AccountController.php b/lib/SP/Controller/AccountController.php
deleted file mode 100644
index 76f3dc53..00000000
--- a/lib/SP/Controller/AccountController.php
+++ /dev/null
@@ -1,573 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\Account;
-use SP\Account\AccountAcl;
-use SP\Account\AccountHistory;
-use SP\Account\AccountUtil;
-use SP\Account\UserAccounts;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Crypt\Crypt;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Init;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\DataModel\AccountExtData;
-use SP\DataModel\CustomFieldData;
-use SP\DataModel\PublicLinkData;
-use SP\Mgmt\Categories\Category;
-use SP\Mgmt\Customers\Customer;
-use SP\Mgmt\CustomFields\CustomField;
-use SP\Mgmt\Groups\Group;
-use SP\Mgmt\Groups\GroupAccountsUtil;
-use SP\Mgmt\PublicLinks\PublicLink;
-use SP\Mgmt\Tags\Tag;
-use SP\Mgmt\Users\UserPass;
-use SP\Mgmt\Users\UserUtil;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-use SP\Util\ImageUtil;
-use SP\Util\Json;
-
-/**
- * Clase encargada de preparar la presentación de las vistas de una cuenta
- *
- * @package Controller
- */
-class AccountController extends ControllerBase implements ActionsInterface
-{
- /**
- * @var \SP\Account\AccountAcl
- */
- protected $AccountAcl;
- /**
- * @var Account|AccountHistory instancia para el manejo de datos de una cuenta
- */
- private $Account;
- /**
- * @var int con el id de la cuenta
- */
- private $id;
- /**
- * @var AccountExtData
- */
- private $AccountData;
-
- /**
- * Constructor
- *
- * @param \SP\Mvc\View\Template $template instancia del motor de plantillas
- * @param int $accountId int con el id de la cuenta
- * @internal param int $lastAction int con la última acción realizada
- */
- public function __construct(Template $template = null, $accountId = null)
- {
- parent::__construct($template);
-
- $this->setId($accountId);
-
- $this->view->assign('changesHash');
- $this->view->assign('chkUserEdit');
- $this->view->assign('chkGroupEdit');
- $this->view->assign('gotData', $this->isGotData());
- $this->view->assign('isView', false);
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- }
-
- /**
- * @param int $id
- */
- private function setId($id)
- {
- $this->id = $id;
- }
-
- /**
- * @return boolean
- */
- private function isGotData()
- {
- return $this->AccountData !== null;
- }
-
- /**
- * Obtener la vista de detalles de cuenta para enlaces públicos
- *
- * @param PublicLinkData $PublicLinkData
- *
- */
- public function getAccountFromLink(PublicLinkData $PublicLinkData)
- {
- $this->setAction(self::ACCOUNT_VIEW);
-
- $this->view->addTemplate('account-link');
- $this->view->assign('title',
- [
- 'class' => 'titleNormal',
- 'name' => __('Detalles de Cuenta'),
- 'icon' => $this->icons->getIconView()->getIcon()
- ]
- );
-
- try {
- $Account = new Account();
- $Account->incrementViewCounter($PublicLinkData->getItemId());
- $Account->incrementDecryptCounter($PublicLinkData->getItemId());
-
- $key = $this->configData->getPasswordSalt() . $PublicLinkData->getPublicLinkLinkHash();
- $securedKey = Crypt::unlockSecuredKey($PublicLinkData->getPassIV(), $key);
-
- /** @var AccountExtData $AccountData */
- $AccountData = unserialize(Crypt::decrypt($PublicLinkData->getData(), $securedKey, $key));
-
- $this->view->assign('useImage', $this->configData->isPublinksImageEnabled() || $this->configData->isAccountPassToImage());
-
- $accountPass = $this->view->useImage ? ImageUtil::convertText($AccountData->getPass()) : $AccountData->getPass();
-
- $this->view->assign('accountPass', $accountPass);
- $this->view->assign('accountData', $AccountData);
- } catch (\Exception $e) {
- $this->showError(self::ERR_EXCEPTION);
- }
- }
-
- /**
- * Realizar las acciones del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- try {
- switch ($type) {
- case ActionsInterface::ACCOUNT_CREATE:
- $this->getNewAccount();
- $this->eventDispatcher->notifyEvent('show.account.new', $this);
- break;
- case ActionsInterface::ACCOUNT_COPY:
- $this->getCopyAccount();
- $this->eventDispatcher->notifyEvent('show.account.copy', $this);
- break;
- case ActionsInterface::ACCOUNT_EDIT:
- $this->getEditAccount();
- $this->eventDispatcher->notifyEvent('show.account.edit', $this);
- break;
- case ActionsInterface::ACCOUNT_EDIT_PASS:
- $this->getEditPassAccount();
- $this->eventDispatcher->notifyEvent('show.account.editpass', $this);
- break;
- case ActionsInterface::ACCOUNT_VIEW:
- $this->getViewAccount();
- $this->eventDispatcher->notifyEvent('show.account.view', $this);
- break;
- case ActionsInterface::ACCOUNT_VIEW_HISTORY:
- $this->getViewHistoryAccount();
- $this->eventDispatcher->notifyEvent('show.account.viewhistory', $this);
- break;
- case ActionsInterface::ACCOUNT_DELETE:
- $this->getDeleteAccount();
- $this->eventDispatcher->notifyEvent('show.account.delete', $this);
- break;
- case ActionsInterface::ACCOUNT_REQUEST:
- $this->getRequestAccountAccess();
- $this->eventDispatcher->notifyEvent('show.account.request', $this);
- break;
- }
- } catch (SPException $e) {
- $this->showError(self::ERR_EXCEPTION);
- }
- }
-
- /**
- * Obtener los datos para mostrar el interface para nueva cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getNewAccount()
- {
- $this->setAction(self::ACCOUNT_CREATE);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleGreen',
- 'name' => __('Nueva Cuenta'),
- 'icon' => $this->icons->getIconAdd()->getIcon()
- ]
- );
-
- SessionFactory::setLastAcountId(0);
- $this->setCommonData();
- }
-
- /**
- * Comprobar si el usuario dispone de acceso al módulo
- *
- * @param null $action
- * @return bool
- */
- protected function checkAccess($action = null)
- {
- $this->view->assign('showLogo', false);
-
- $Acl = new AccountAcl($this->getAction());
- $this->AccountAcl = $Acl;
-
- if (!$this->acl->checkUserAccess($this->getAction())) {
- $this->showError(self::ERR_PAGE_NO_PERMISSION);
- return false;
- }
-
- if (!UserPass::checkUserUpdateMPass($this->userData->getId())) {
- $this->showError(self::ERR_UPDATE_MPASS);
- return false;
- }
-
- if ($this->id > 0) {
- $this->AccountAcl = $Acl->getAcl();
-
- if (!$this->AccountAcl->checkAccountAccess()) {
- $this->showError(self::ERR_ACCOUNT_NO_PERMISSION);
- return false;
- }
-
- SessionFactory::setAccountAcl($this->AccountAcl);
- }
-
- return true;
- }
-
- /**
- * Establecer variables comunes del formulario para todos los interfaces
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function setCommonData()
- {
- $this->getCustomFieldsForItem();
-
- if ($this->isGotData()) {
- $this->view->assign('accountIsHistory', $this->getAccount()->getAccountIsHistory());
- $this->view->assign('accountOtherUsers', UserAccounts::getUsersInfoForAccount($this->getId()));
- $this->view->assign('accountOtherGroups', GroupAccountsUtil::getGroupsInfoForAccount($this->getId()));
- $this->view->assign('accountTagsJson', Json::getJson(array_keys($this->getAccount()->getAccountData()->getTags())));
- $this->view->assign('historyData', AccountHistory::getAccountList($this->AccountData->getId()));
- $this->view->assign('isModified', strtotime($this->AccountData->getDateEdit()) !== false);
- $this->view->assign('maxFileSize', round($this->configData->getFilesAllowedSize() / 1024, 1));
- $this->view->assign('filesAllowedExts', implode(',', $this->configData->getFilesAllowedExts()));
-
- $PublicLinkData = PublicLink::getItem()->getHashForItem($this->getId());
-
- $publicLinkUrl = ($this->configData->isPublinksEnabled() && $PublicLinkData ? Init::$WEBURI . '/index.php?h=' . $PublicLinkData->getHash() . '&a=link' : null);
- $this->view->assign('publicLinkUrl', $publicLinkUrl);
- $this->view->assign('publicLinkId', $PublicLinkData ? $PublicLinkData->getId() : 0);
-
- $this->view->assign('accountPassDate', date('Y-m-d H:i:s', $this->AccountData->getPassDate()));
- $this->view->assign('accountPassDateChange', date('Y-m-d', $this->AccountData->getPassDateChange() ?: 0));
- } else {
- $this->view->assign('accountPassDateChange', date('Y-m-d', time() + 7776000));
- }
-
- $this->view->assign('actionId', $this->getAction());
- $this->view->assign('categories', Category::getItem()->getItemsForSelect());
- $this->view->assign('customers', Customer::getItem()->getItemsForSelectByUser());
- $this->view->assign('otherUsers', UserUtil::getUsersLogin());
- $this->view->assign('otherUsersJson', Json::getJson($this->view->otherUsers));
- $this->view->assign('otherGroups', Group::getItem()->getItemsForSelect());
- $this->view->assign('otherGroupsJson', Json::getJson($this->view->otherGroups));
- $this->view->assign('tagsJson', Json::getJson(Tag::getItem()->getItemsForSelect()));
- $this->view->assign('allowPrivate', $this->userProfileData->isAccPrivate());
- $this->view->assign('allowPrivateGroup', $this->userProfileData->isAccPrivateGroup());
- $this->view->assign('mailRequestEnabled', $this->configData->isMailRequestsEnabled());
- $this->view->assign('passToImageEnabled', $this->configData->isAccountPassToImage());
-
- $this->view->assign('otherAccounts', AccountUtil::getAccountsForUser($this->getId()));
- $this->view->assign('linkedAccounts', AccountUtil::getLinkedAccounts($this->getId()));
-
- $this->view->assign('disabled', $this->view->isView ? 'disabled' : '');
- $this->view->assign('readonly', $this->view->isView ? 'readonly' : '');
-
- $this->view->assign('showViewCustomPass', $this->AccountAcl->isShowViewPass());
- $this->view->assign('AccountAcl', $this->AccountAcl);
- }
-
- /**
- * Obtener la lista de campos personalizados y sus valores
- */
- private function getCustomFieldsForItem()
- {
- $this->view->assign('customFields', CustomField::getItem(new CustomFieldData(ActionsInterface::ACCOUNT))->getById($this->getId()));
- }
-
- /**
- * @return int
- */
- private function getId()
- {
- return $this->id;
- }
-
- /**
- * @return \SP\Account\Account|AccountHistory
- */
- private function getAccount()
- {
- return $this->Account ?: new Account(new AccountExtData());
- }
-
- /**
- * Obtener los datos para mostrar el interface para copiar cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getCopyAccount()
- {
- $this->setAction(self::ACCOUNT_COPY);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountData() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleGreen',
- 'name' => __('Copiar Cuenta'),
- 'icon' => $this->icons->getIconCopy()->getIcon()
- ]
- );
-
- $this->setCommonData();
- }
-
- /**
- * Establecer las variables que contienen la información de la cuenta.
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function setAccountData()
- {
- $Account = new Account(new AccountExtData($this->getId()));
- $this->Account = $Account;
- $this->AccountData = $Account->getData();
-
- $this->view->assign('accountId', $this->getId());
- $this->view->assign('accountData', $this->AccountData);
- $this->view->assign('gotData', $this->isGotData());
-
- return true;
- }
-
- /**
- * Obtener los datos para mostrar el interface para editar cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getEditAccount()
- {
- $this->setAction(self::ACCOUNT_EDIT);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountData() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleOrange',
- 'name' => __('Editar Cuenta'),
- 'icon' => $this->icons->getIconEdit()->getIcon()
- ]
- );
-
- $this->setCommonData();
- }
-
- /**
- * Obtener los datos para mostrar el interface para modificar la clave de cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getEditPassAccount()
- {
- $this->setAction(self::ACCOUNT_EDIT_PASS);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountData() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account-editpass');
- $this->view->assign('title',
- [
- 'class' => 'titleOrange',
- 'name' => __('Modificar Clave de Cuenta'),
- 'icon' => $this->icons->getIconEditPass()->getIcon()
- ]
- );
-
- $this->view->assign('accountPassDateChange', gmdate('Y-m-d', $this->AccountData->getPassDateChange()));
- }
-
- /**
- * Obtener los datos para mostrar el interface para ver cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getViewAccount()
- {
- $this->setAction(self::ACCOUNT_VIEW);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountData() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleNormal',
- 'name' => __('Detalles de Cuenta'),
- 'icon' => $this->icons->getIconView()->getIcon()
- ]
- );
-
- $this->view->assign('isView', true);
-
- $this->Account->incrementViewCounter();
-
- $this->setCommonData();
- }
-
- /**
- * Obtener los datos para mostrar el interface para ver cuenta en fecha concreta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getViewHistoryAccount()
- {
- $this->setAction(self::ACCOUNT_VIEW_HISTORY);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountDataHistory() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleNormal',
- 'name' => __('Detalles de Cuenta'),
- 'icon' => 'access_time'
- ]
- );
-
- $this->view->assign('isView', true);
- $this->Account->setAccountIsHistory(1);
-
- $this->setCommonData();
- }
-
- /**
- * Establecer las variables que contienen la información de la cuenta en una fecha concreta.
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- private function setAccountDataHistory()
- {
- $Account = new AccountHistory(new AccountExtData());
- $Account->setId($this->getId());
- $this->Account = $Account;
- $this->AccountData = $Account->getData();
-
- $this->view->assign('accountId', $this->AccountData->getId());
- $this->view->assign('accountData', $this->AccountData);
- $this->view->assign('gotData', $this->isGotData());
-
- $this->view->assign('accountHistoryId', $this->getId());
-
- return true;
- }
-
- /**
- * Obtener los datos para mostrar el interface de eliminar cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getDeleteAccount()
- {
- $this->setAction(self::ACCOUNT_DELETE);
-
- // Obtener los datos de la cuenta antes y comprobar el acceso
- $isOk = ($this->setAccountData() && $this->checkAccess());
-
- if (!$isOk) {
- return;
- }
-
- $this->view->addTemplate('account');
- $this->view->assign('title',
- [
- 'class' => 'titleRed',
- 'name' => __('Eliminar Cuenta'),
- 'icon' => $this->icons->getIconDelete()->getIcon()
- ]
- );
-
- $this->setCommonData();
- }
-
- /**
- * Obtener los datos para mostrar el interface de solicitud de cambios en una cuenta
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getRequestAccountAccess()
- {
- // Obtener los datos de la cuenta
- $this->setAccountData();
-
- $this->view->addTemplate('request');
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/AccountSearchController.php b/lib/SP/Controller/AccountSearchController.php
deleted file mode 100644
index 1452864c..00000000
--- a/lib/SP/Controller/AccountSearchController.php
+++ /dev/null
@@ -1,409 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\AccountSearchFilter;
-use SP\Account\AccountSearchItem;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\Html\DataGrid\DataGrid;
-use SP\Html\DataGrid\DataGridAction;
-use SP\Html\DataGrid\DataGridActionSearch;
-use SP\Html\DataGrid\DataGridActionType;
-use SP\Html\DataGrid\DataGridData;
-use SP\Html\DataGrid\DataGridHeaderSort;
-use SP\Html\DataGrid\DataGridPager;
-use SP\Html\DataGrid\DataGridSort;
-use SP\Http\Request;
-use SP\Mgmt\Categories\Category;
-use SP\Mgmt\Customers\Customer;
-use SP\Mgmt\Tags\Tag;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-use SP\Services\Account\AccountSearchService;
-
-/**
- * Clase encargada de obtener los datos para presentar la búsqueda
- *
- * @package Controller
- */
-class AccountSearchController extends ControllerBase implements ActionsInterface
-{
- /**
- * Indica si el filtrado de cuentas está activo
- *
- * @var bool
- */
- private $filterOn = false;
- /** @var string */
- private $sk;
- /** @var int */
- private $sortKey = 0;
- /** @var string */
- private $sortOrder = 0;
- /** @var bool */
- private $searchGlobal = false;
- /** @var int */
- private $limitStart = 0;
- /** @var int */
- private $limitCount = 0;
- /** @var int */
- private $queryTimeStart = 0;
- /** @var bool */
- private $isAjax = false;
-
- /**
- * Constructor
- *
- * @param $template \SP\Mvc\View\Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->queryTimeStart = microtime();
- $this->sk = SessionUtil::getSessionKey(true);
- $this->view->assign('sk', $this->sk);
- $this->setVars();
- }
-
- /**
- * Establecer las variables necesarias para las plantillas
- */
- private function setVars()
- {
- $this->view->assign('isAdmin', $this->userData->isIsAdminApp() || $this->userData->isIsAdminAcc());
- $this->view->assign('showGlobalSearch', $this->configData->isGlobalSearch() && $this->userProfileData->isAccGlobalSearch());
-
- // Obtener el filtro de búsqueda desde la sesión
- $filters = SessionFactory::getSearchFilters();
-
- // Comprobar si la búsqueda es realizada desde el formulario
- // de lo contrario, se recupera la información de filtros de la sesión
- $isSearch = (!isset($this->view->actionId));
-
- $this->sortKey = $isSearch ? Request::analyze('skey', 0) : $filters->getSortKey();
- $this->sortOrder = $isSearch ? Request::analyze('sorder', 0) : $filters->getSortOrder();
- $this->searchGlobal = $isSearch ? Request::analyze('gsearch', 0) : $filters->getGlobalSearch();
- $this->limitStart = $isSearch ? Request::analyze('start', 0) : $filters->getLimitStart();
- $this->limitCount = $isSearch ? Request::analyze('rpp', 0) : $filters->getLimitCount();
-
- // Valores POST
- $this->view->assign('searchCustomer', $isSearch ? Request::analyze('customer', 0) : $filters->getCustomerId());
- $this->view->assign('searchCategory', $isSearch ? Request::analyze('category', 0) : $filters->getCategoryId());
- $this->view->assign('searchTags', $isSearch ? Request::analyze('tags') : $filters->getTagsId());
- $this->view->assign('searchTxt', $isSearch ? Request::analyze('search') : $filters->getTxtSearch());
- $this->view->assign('searchGlobal', Request::analyze('gsearch', $filters->getGlobalSearch()));
- $this->view->assign('searchFavorites', Request::analyze('searchfav', $filters->isSearchFavorites()));
- }
-
- /**
- * @param boolean $isAjax
- */
- public function setIsAjax($isAjax)
- {
- $this->isAjax = $isAjax;
- }
-
- /**
- * Obtener los datos para la caja de búsqueda
- */
- public function getSearchBox()
- {
- $this->view->addTemplate('searchbox');
-
- $this->view->assign('customers', Customer::getItem()->getItemsForSelectByUser());
- $this->view->assign('categories', Category::getItem()->getItemsForSelect());
- $this->view->assign('tags', Tag::getItem()->getItemsForSelect());
- }
-
- /**
- * Obtener los resultados de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getSearch()
- {
- $this->view->addTemplate('index');
-
- $this->view->assign('isAjax', $this->isAjax);
-
- $Search = new AccountSearchService();
- $Search->setGlobalSearch($this->searchGlobal)
- ->setSortKey($this->sortKey)
- ->setSortOrder($this->sortOrder)
- ->setLimitStart($this->limitStart)
- ->setLimitCount($this->limitCount)
- ->setTxtSearch($this->view->searchTxt)
- ->setCategoryId($this->view->searchCategory)
- ->setClientId($this->view->searchCustomer)
- ->setTagsId($this->view->searchTags)
- ->setSearchFavorites($this->view->searchFavorites);
-
- $this->filterOn = ($this->sortKey > 1
- || $this->view->searchCustomer
- || $this->view->searchCategory
- || $this->view->searchTags
- || $this->view->searchTxt
- || $this->view->searchFavorites
- || $Search->isSortViews());
-
- $UserPreferences = SessionFactory::getUserPreferences();
-
- AccountSearchItem::$accountLink = $UserPreferences->isAccountLink();
- AccountSearchItem::$topNavbar = $UserPreferences->isTopNavbar();
- AccountSearchItem::$optionalActions = $UserPreferences->isOptionalActions();
- AccountSearchItem::$wikiEnabled = $this->configData->isWikiEnabled();
- AccountSearchItem::$dokuWikiEnabled = $this->configData->isDokuwikiEnabled();
- AccountSearchItem::$isDemoMode = $this->configData->isDemoEnabled();
-
- if (AccountSearchItem::$wikiEnabled) {
- $wikiFilter = array_map(function ($value) {
- return preg_quote($value, '/');
- }, $this->configData->getWikiFilter());
-
- $this->view->assign('wikiFilter', implode('|', $wikiFilter));
- $this->view->assign('wikiPageUrl', $this->configData->getWikiPageurl());
- }
-
- $Grid = $this->getGrid();
- $Grid->getData()->setData($Search->processSearchResults());
- $Grid->updatePager();
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
-
- // Establecer el filtro de búsqueda en la sesión como un objeto
- SessionFactory::setSearchFilters($Search->save());
-
- $this->view->assign('data', $Grid);
- }
-
- /**
- * Devuelve la matriz a utilizar en la vista
- *
- * @return DataGrid
- * @throws \ReflectionException
- */
- private function getGrid()
- {
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::ACCOUNT_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Detalles de Cuenta'));
- $GridActionView->setTitle(__('Detalles de Cuenta'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setReflectionFilter(AccountSearchItem::class, 'isShowView');
- $GridActionView->addData('action-id', self::ACCOUNT_VIEW);
- $GridActionView->addData('action-sk', $this->sk);
- $GridActionView->addData('onclick', 'account/show');
-
- $GridActionViewPass = new DataGridAction();
- $GridActionViewPass->setId(self::ACCOUNT_VIEW_PASS);
- $GridActionViewPass->setType(DataGridActionType::VIEW_ITEM);
- $GridActionViewPass->setName(__('Ver Clave'));
- $GridActionViewPass->setTitle(__('Ver Clave'));
- $GridActionViewPass->setIcon($this->icons->getIconViewPass());
- $GridActionViewPass->setReflectionFilter(AccountSearchItem::class, 'isShowViewPass');
- $GridActionViewPass->addData('action-id', self::ACCOUNT_VIEW_PASS);
- $GridActionViewPass->addData('action-full', 1);
- $GridActionViewPass->addData('action-sk', $this->sk);
- $GridActionViewPass->addData('onclick', 'account/showpass');
-
- // Añadir la clase para usar el portapapeles
- $ClipboardIcon = $this->icons->getIconClipboard()->setClass('clip-pass-button');
-
- $GridActionCopyPass = new DataGridAction();
- $GridActionCopyPass->setId(self::ACCOUNT_VIEW_PASS);
- $GridActionCopyPass->setType(DataGridActionType::VIEW_ITEM);
- $GridActionCopyPass->setName(__('Copiar Clave en Portapapeles'));
- $GridActionCopyPass->setTitle(__('Copiar Clave en Portapapeles'));
- $GridActionCopyPass->setIcon($ClipboardIcon);
- $GridActionCopyPass->setReflectionFilter(AccountSearchItem::class, 'isShowCopyPass');
- $GridActionCopyPass->addData('action-id', self::ACCOUNT_VIEW_PASS);
- $GridActionCopyPass->addData('action-full', 0);
- $GridActionCopyPass->addData('action-sk', $this->sk);
- $GridActionCopyPass->addData('useclipboard', '1');
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::ACCOUNT_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Cuenta'));
- $GridActionEdit->setTitle(__('Editar Cuenta'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setReflectionFilter(AccountSearchItem::class, 'isShowEdit');
- $GridActionEdit->addData('action-id', self::ACCOUNT_EDIT);
- $GridActionEdit->addData('action-sk', $this->sk);
- $GridActionEdit->addData('onclick', 'account/edit');
-
- $GridActionCopy = new DataGridAction();
- $GridActionCopy->setId(self::ACCOUNT_COPY);
- $GridActionCopy->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionCopy->setName(__('Copiar Cuenta'));
- $GridActionCopy->setTitle(__('Copiar Cuenta'));
- $GridActionCopy->setIcon($this->icons->getIconCopy());
- $GridActionCopy->setReflectionFilter(AccountSearchItem::class, 'isShowCopy');
- $GridActionCopy->addData('action-id', self::ACCOUNT_COPY);
- $GridActionCopy->addData('action-sk', $this->sk);
- $GridActionCopy->addData('onclick', 'account/copy');
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::ACCOUNT_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Cuenta'));
- $GridActionDel->setTitle(__('Eliminar Cuenta'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setReflectionFilter(AccountSearchItem::class, 'isShowDelete');
- $GridActionDel->addData('action-id', self::ACCOUNT_DELETE);
- $GridActionDel->addData('action-sk', $this->sk);
- $GridActionDel->addData('onclick', 'account/delete');
-
- $GridActionRequest = new DataGridAction();
- $GridActionRequest->setId(self::ACCOUNT_REQUEST);
- $GridActionRequest->setName(__('Solicitar Modificación'));
- $GridActionRequest->setTitle(__('Solicitar Modificación'));
- $GridActionRequest->setIcon($this->icons->getIconEmail());
- $GridActionRequest->setReflectionFilter(AccountSearchItem::class, 'isShowRequest');
- $GridActionRequest->addData('action-id', self::ACCOUNT_REQUEST);
- $GridActionRequest->addData('action-sk', $this->sk);
- $GridActionRequest->addData('onclick', 'account/show');
-
- $GridActionOptional = new DataGridAction();
- $GridActionOptional->setId(0);
- $GridActionOptional->setName(__('Más Acciones'));
- $GridActionOptional->setTitle(__('Más Acciones'));
- $GridActionOptional->setIcon($this->icons->getIconOptional());
- $GridActionOptional->setReflectionFilter(AccountSearchItem::class, 'isShowOptional');
- $GridActionOptional->addData('onclick', 'account/menu');
-
- $GridPager = new DataGridPager();
- $GridPager->setIconPrev($this->icons->getIconNavPrev());
- $GridPager->setIconNext($this->icons->getIconNavNext());
- $GridPager->setIconFirst($this->icons->getIconNavFirst());
- $GridPager->setIconLast($this->icons->getIconNavLast());
- $GridPager->setSortKey($this->sortKey);
- $GridPager->setSortOrder($this->sortOrder);
- $GridPager->setLimitStart($this->limitStart);
- $GridPager->setLimitCount($this->limitCount);
- $GridPager->setOnClickFunction('account/sort');
- $GridPager->setFilterOn($this->filterOn);
- $GridPager->setSourceAction(new DataGridActionSearch(self::ACCOUNT_SEARCH));
-
- $UserPreferences = SessionFactory::getUserPreferences();
-
- $showOptionalActions = $UserPreferences->isOptionalActions() || $UserPreferences->isResultsAsCards() || ($UserPreferences->getUserId() === 0 && $this->configData->isResultsAsCards());
-
- $Grid = new DataGrid();
- $Grid->setId('gridSearch');
- $Grid->setDataHeaderTemplate('header', $this->view->getBase());
- $Grid->setDataRowTemplate('rows', $this->view->getBase());
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($this->getHeaderSort());
- $Grid->setDataActions($GridActionView);
- $Grid->setDataActions($GridActionViewPass);
- $Grid->setDataActions($GridActionCopyPass);
- $Grid->setDataActions($GridActionEdit, !$showOptionalActions);
- $Grid->setDataActions($GridActionCopy, !$showOptionalActions);
- $Grid->setDataActions($GridActionDel, !$showOptionalActions);
- $Grid->setDataActions($GridActionRequest);
- $Grid->setPager($GridPager);
- $Grid->setData(new DataGridData());
-
- return $Grid;
- }
-
- /**
- * Devolver la cabecera con los campos de ordenación
- *
- * @return DataGridHeaderSort
- */
- private function getHeaderSort()
- {
- $GridSortCustomer = new DataGridSort();
- $GridSortCustomer->setName(__('Cliente'))
- ->setTitle(__('Ordenar por Cliente'))
- ->setSortKey(AccountSearchFilter::SORT_CLIENT)
- ->setIconUp($this->icons->getIconUp())
- ->setIconDown($this->icons->getIconDown());
-
- $GridSortName = new DataGridSort();
- $GridSortName->setName(__('Nombre'))
- ->setTitle(__('Ordenar por Nombre'))
- ->setSortKey(AccountSearchFilter::SORT_NAME)
- ->setIconUp($this->icons->getIconUp())
- ->setIconDown($this->icons->getIconDown());
-
- $GridSortCategory = new DataGridSort();
- $GridSortCategory->setName(__('Categoría'))
- ->setTitle(__('Ordenar por Categoría'))
- ->setSortKey(AccountSearchFilter::SORT_CATEGORY)
- ->setIconUp($this->icons->getIconUp())
- ->setIconDown($this->icons->getIconDown());
-
- $GridSortLogin = new DataGridSort();
- $GridSortLogin->setName(__('Usuario'))
- ->setTitle(__('Ordenar por Usuario'))
- ->setSortKey(AccountSearchFilter::SORT_LOGIN)
- ->setIconUp($this->icons->getIconUp())
- ->setIconDown($this->icons->getIconDown());
-
- $GridSortUrl = new DataGridSort();
- $GridSortUrl->setName(__('URL / IP'))
- ->setTitle(__('Ordenar por URL / IP'))
- ->setSortKey(AccountSearchFilter::SORT_URL)
- ->setIconUp($this->icons->getIconUp())
- ->setIconDown($this->icons->getIconDown());
-
- $GridHeaderSort = new DataGridHeaderSort();
- $GridHeaderSort->addSortField($GridSortCustomer)
- ->addSortField($GridSortName)
- ->addSortField($GridSortCategory)
- ->addSortField($GridSortLogin)
- ->addSortField($GridSortUrl);
-
- return $GridHeaderSort;
- }
-
- /**
- * Realizar las accione del controlador
- *
- * @param mixed $type Tipo de acción
- * @throws \InvalidArgumentException
- */
- public function doAction($type = null)
- {
- try {
- $this->getSearchBox();
- $this->getSearch();
-
- $this->eventDispatcher->notifyEvent('show.account.search', $this);
- } catch (SPException $e) {
- $this->showError(self::ERR_EXCEPTION);
- }
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ConfigActionController.php b/lib/SP/Controller/ConfigActionController.php
deleted file mode 100644
index 4fc7f43b..00000000
--- a/lib/SP/Controller/ConfigActionController.php
+++ /dev/null
@@ -1,763 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Account\AccountCrypt;
-use SP\Account\AccountHistoryCrypt;
-use SP\Config\ConfigDB;
-use SP\Core\ActionsInterface;
-use SP\Core\Backup;
-use SP\Core\Crypt\Hash;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\CryptMasterPass;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Init;
-use SP\Core\Messages\LogMessage;
-use SP\Core\Messages\NoticeMessage;
-use SP\Core\SessionFactory;
-use SP\Core\XmlExport;
-use SP\Http\Request;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Mgmt\CustomFields\CustomFieldsUtil;
-use SP\Mgmt\Users\UserPass;
-use SP\Mgmt\Users\UserUtil;
-use SP\Services\Import\ImportParams;
-use SP\Services\Import\ImportService;
-use SP\Services\Task\TaskFactory;
-use SP\Storage\DbWrapper;
-use SP\Util\Json;
-use SP\Util\Util;
-
-/**
- * Class ConfigActionController
- *
- * @package SP\Controller
- */
-class ConfigActionController implements ItemControllerInterface
-{
- use RequestControllerTrait;
- use SP\Core\Dic\InjectableTrait;
-
- /**
- * ConfigActionController constructor.
- */
- public function __construct()
- {
- $this->injectDependencies();
- $this->init();
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function doAction()
- {
- $this->LogMessage = new LogMessage();
-
- try {
- switch ($this->actionId) {
- case ActionsInterface::CONFIG_GENERAL:
- $this->generalAction();
- break;
- case ActionsInterface::CONFIG_ACCOUNTS:
- $this->accountsAction();
- break;
- case ActionsInterface::CONFIG_WIKI:
- $this->wikiAction();
- break;
- case ActionsInterface::CONFIG_LDAP:
- $this->ldapAction();
- break;
- case ActionsInterface::CONFIG_MAIL:
- $this->mailAction();
- break;
- case ActionsInterface::CONFIG_ENCRYPTION:
- $this->masterPassAction();
- break;
- case ActionsInterface::CONFIG_ENCRYPTION_REFRESH:
- $this->masterPassRefreshAction();
- break;
- case ActionsInterface::CONFIG_ENCRYPTION_TEMPPASS:
- $this->tempMasterPassAction();
- break;
- case ActionsInterface::IMPORT:
- $this->importAction();
- break;
- case ActionsInterface::EXPORT:
- $this->exportAction();
- break;
- case ActionsInterface::BACKUP:
- $this->backupAction();
- break;
- default:
- $this->invalidAction();
- }
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- if ($this->LogMessage->getAction() !== null) {
- $Log = new Log($this->LogMessage);
- $Log->writeLog();
-
- $this->JsonResponse->setDescription($this->LogMessage->getHtmlDescription(true));
- }
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Accion para opciones configuración general
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function generalAction()
- {
- // General
- $siteLang = Request::analyze('sitelang');
- $siteTheme = Request::analyze('sitetheme', 'material-blue');
- $sessionTimeout = Request::analyze('session_timeout', 300);
- $httpsEnabled = Request::analyze('https_enabled', false, false, true);
- $debugEnabled = Request::analyze('debug', false, false, true);
- $maintenanceEnabled = Request::analyze('maintenance', false, false, true);
- $checkUpdatesEnabled = Request::analyze('updates', false, false, true);
- $checkNoticesEnabled = Request::analyze('notices', false, false, true);
- $encryptSessionEnabled = Request::analyze('encryptsession', false, false, true);
-
- $this->ConfigData->setSiteLang($siteLang);
- $this->ConfigData->setSiteTheme($siteTheme);
- $this->ConfigData->setSessionTimeout($sessionTimeout);
- $this->ConfigData->setHttpsEnabled($httpsEnabled);
- $this->ConfigData->setDebug($debugEnabled);
- $this->ConfigData->setMaintenance($maintenanceEnabled);
- $this->ConfigData->setCheckUpdates($checkUpdatesEnabled);
- $this->ConfigData->setChecknotices($checkNoticesEnabled);
- $this->ConfigData->setEncryptSession($encryptSessionEnabled);
-
- // Events
- $logEnabled = Request::analyze('log_enabled', false, false, true);
- $syslogEnabled = Request::analyze('syslog_enabled', false, false, true);
- $remoteSyslogEnabled = Request::analyze('remotesyslog_enabled', false, false, true);
- $syslogServer = Request::analyze('remotesyslog_server');
- $syslogPort = Request::analyze('remotesyslog_port', 0);
-
- $this->ConfigData->setLogEnabled($logEnabled);
- $this->ConfigData->setSyslogEnabled($syslogEnabled);
-
- if ($remoteSyslogEnabled && (!$syslogServer || !$syslogPort)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de syslog remoto', false));
- return;
- }
-
- if ($remoteSyslogEnabled) {
- $this->ConfigData->setSyslogRemoteEnabled($remoteSyslogEnabled);
- $this->ConfigData->setSyslogServer($syslogServer);
- $this->ConfigData->setSyslogPort($syslogPort);
- } elseif ($this->ConfigData->isSyslogEnabled()) {
- $this->ConfigData->setSyslogRemoteEnabled(false);
-
- $this->LogMessage->addDescription(__('Syslog remoto deshabilitado', false));
- }
-
- // Proxy
- $proxyEnabled = Request::analyze('proxy_enabled', false, false, true);
- $proxyServer = Request::analyze('proxy_server');
- $proxyPort = Request::analyze('proxy_port', 0);
- $proxyUser = Request::analyze('proxy_user');
- $proxyPass = Request::analyzeEncrypted('proxy_pass');
-
-
- // Valores para Proxy
- if ($proxyEnabled && (!$proxyServer || !$proxyPort)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de Proxy', false));
- return;
- }
-
- if ($proxyEnabled) {
- $this->ConfigData->setProxyEnabled(true);
- $this->ConfigData->setProxyServer($proxyServer);
- $this->ConfigData->setProxyPort($proxyPort);
- $this->ConfigData->setProxyUser($proxyUser);
- $this->ConfigData->setProxyPass($proxyPass);
-
- $this->LogMessage->addDescription(__('Proxy habiltado', false));
- } elseif ($this->ConfigData->isProxyEnabled()) {
- $this->ConfigData->setProxyEnabled(false);
-
- $this->LogMessage->addDescription(__('Proxy deshabilitado', false));
- }
-
- // Autentificación
- $authBasicEnabled = Request::analyze('authbasic_enabled', false, false, true);
- $authBasicAutologinEnabled = Request::analyze('authbasic_enabled', false, false, true);
- $authBasicDomain = Request::analyze('authbasic_domain');
- $authSsoDefaultGroup = Request::analyze('sso_defaultgroup', false, false, true);
- $authSsoDefaultProfile = Request::analyze('sso_defaultprofile', false, false, true);
-
- // Valores para Autentificación
- if ($authBasicEnabled) {
- $this->ConfigData->setAuthBasicEnabled(true);
- $this->ConfigData->setAuthBasicAutoLoginEnabled($authBasicAutologinEnabled);
- $this->ConfigData->setAuthBasicDomain($authBasicDomain);
- $this->ConfigData->setSsoDefaultGroup($authSsoDefaultGroup);
- $this->ConfigData->setSsoDefaultProfile($authSsoDefaultProfile);
-
- $this->LogMessage->addDescription(__('Auth Basic habiltada', false));
- } elseif ($this->ConfigData->isAuthBasicEnabled()) {
- $this->ConfigData->setAuthBasicEnabled(false);
- $this->ConfigData->setAuthBasicAutoLoginEnabled(false);
-
- $this->LogMessage->addDescription(__('Auth Basic deshabiltada', false));
- }
-
- $this->LogMessage->addDetails(__('Sección', false), __('General', false));
-
- $this->saveConfig();
- }
-
- /**
- * Guardar la configuración
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function saveConfig()
- {
- try {
- if ($this->ConfigData->isDemoEnabled()) {
- $this->JsonResponse->setDescription(__('Ey, esto es una DEMO!!', false));
- return;
- }
-
- $this->Config->saveConfig($this->ConfigData);
-
- if ($this->ConfigData->isMaintenance()) {
- Util::lockApp(false);
- } elseif (Init::$LOCK > 0) {
- Util::unlockApp(false);
- }
-
- $this->JsonResponse->setStatus(0);
-
- $this->LogMessage->addDescription(__('Configuración actualizada', false));
- } catch (SPException $e) {
- $this->LogMessage->addDescription(__('Error al guardar la configuración', false));
- $this->LogMessage->addDetails($e->getMessage(), $e->getHint());
- }
-
- $this->LogMessage->setAction(__('Modificar Configuración', false));
-
- Email::sendEmail($this->LogMessage);
- }
-
- /**
- * Accion para opciones configuración de cuentas
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function accountsAction()
- {
- // Accounts
- $globalSearchEnabled = Request::analyze('globalsearch', false, false, true);
- $accountPassToImageEnabled = Request::analyze('account_passtoimage', false, false, true);
- $accountLinkEnabled = Request::analyze('account_link', false, false, true);
- $accountFullGroupAccessEnabled = Request::analyze('account_fullgroup_access', false, false, true);
- $accountCount = Request::analyze('account_count', 10);
- $resultsAsCardsEnabled = Request::analyze('resultsascards', false, false, true);
-
- $this->ConfigData->setGlobalSearch($globalSearchEnabled);
- $this->ConfigData->setAccountPassToImage($accountPassToImageEnabled);
- $this->ConfigData->setAccountLink($accountLinkEnabled);
- $this->ConfigData->setAccountFullGroupAccess($accountFullGroupAccessEnabled);
- $this->ConfigData->setAccountCount($accountCount);
- $this->ConfigData->setResultsAsCards($resultsAsCardsEnabled);
-
- // Files
- $filesEnabled = Request::analyze('files_enabled', false, false, true);
- $filesAllowedSize = Request::analyze('files_allowed_size', 1024);
- $filesAllowedExts = Request::analyze('files_allowed_exts');
-
- if ($filesEnabled && $filesAllowedSize >= 16384) {
- $this->JsonResponse->setDescription(__('El tamaño máximo por archivo es de 16MB', false));
- return;
- }
-
- $this->ConfigData->setFilesAllowedExts($filesAllowedExts);
- $this->ConfigData->setFilesEnabled($filesEnabled);
- $this->ConfigData->setFilesAllowedSize($filesAllowedSize);
-
- // Public Links
- $pubLinksEnabled = Request::analyze('publinks_enabled', false, false, true);
- $pubLinksImageEnabled = Request::analyze('publinks_image_enabled', false, false, true);
- $pubLinksMaxTime = Request::analyze('publinks_maxtime', 10);
- $pubLinksMaxViews = Request::analyze('publinks_maxviews', 3);
-
- $this->ConfigData->setPublinksEnabled($pubLinksEnabled);
- $this->ConfigData->setPublinksImageEnabled($pubLinksImageEnabled);
- $this->ConfigData->setPublinksMaxTime($pubLinksMaxTime * 60);
- $this->ConfigData->setPublinksMaxViews($pubLinksMaxViews);
-
- $this->LogMessage->addDetails(__('Sección', false), __('Cuentas', false));
-
- $this->saveConfig();
- }
-
- /**
- * Acción para opciones de Wiki
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function wikiAction()
- {
- // Wiki
- $wikiEnabled = Request::analyze('wiki_enabled', false, false, true);
- $wikiSearchUrl = Request::analyze('wiki_searchurl');
- $wikiPageUrl = Request::analyze('wiki_pageurl');
- $wikiFilter = Request::analyze('wiki_filter');
-
- // Valores para la conexión a la Wiki
- if ($wikiEnabled && (!$wikiSearchUrl || !$wikiPageUrl || !$wikiFilter)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de Wiki', false));
- return;
- }
-
- if ($wikiEnabled) {
- $this->ConfigData->setWikiEnabled(true);
- $this->ConfigData->setWikiSearchurl($wikiSearchUrl);
- $this->ConfigData->setWikiPageurl($wikiPageUrl);
- $this->ConfigData->setWikiFilter(explode(',', $wikiFilter));
-
- $this->LogMessage->addDescription(__('Wiki habiltada', false));
- } elseif ($this->ConfigData->isWikiEnabled()) {
- $this->ConfigData->setWikiEnabled(false);
-
- $this->LogMessage->addDescription(__('Wiki deshabilitada', false));
- }
-
- // DokuWiki
- $dokuWikiEnabled = Request::analyze('dokuwiki_enabled', false, false, true);
- $dokuWikiUrl = Request::analyze('dokuwiki_url');
- $dokuWikiUrlBase = Request::analyze('dokuwiki_urlbase');
- $dokuWikiUser = Request::analyze('dokuwiki_user');
- $dokuWikiPass = Request::analyzeEncrypted('dokuwiki_pass');
- $dokuWikiNamespace = Request::analyze('dokuwiki_namespace');
-
- // Valores para la conexión a la API de DokuWiki
- if ($dokuWikiEnabled && (!$dokuWikiUrl || !$dokuWikiUrlBase)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de DokuWiki', false));
- return;
- }
-
- if ($dokuWikiEnabled) {
- $this->ConfigData->setDokuwikiEnabled(true);
- $this->ConfigData->setDokuwikiUrl($dokuWikiUrl);
- $this->ConfigData->setDokuwikiUrlBase(trim($dokuWikiUrlBase, '/'));
- $this->ConfigData->setDokuwikiUser($dokuWikiUser);
- $this->ConfigData->setDokuwikiPass($dokuWikiPass);
- $this->ConfigData->setDokuwikiNamespace($dokuWikiNamespace);
-
- $this->LogMessage->addDescription(__('DokuWiki habiltada', false));
- } elseif ($this->ConfigData->isDokuwikiEnabled()) {
- $this->ConfigData->setDokuwikiEnabled(false);
-
- $this->LogMessage->addDescription(__('DokuWiki deshabilitada', false));
- }
-
- $this->LogMessage->addDetails(__('Sección', false), __('Wiki', false));
-
- $this->saveConfig();
- }
-
- /**
- * Acción para opciones de LDAP
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function ldapAction()
- {
- // LDAP
- $ldapEnabled = Request::analyze('ldap_enabled', false, false, true);
- $ldapADSEnabled = Request::analyze('ldap_ads', false, false, true);
- $ldapServer = Request::analyze('ldap_server');
- $ldapBase = Request::analyze('ldap_base');
- $ldapGroup = Request::analyze('ldap_group');
- $ldapDefaultGroup = Request::analyze('ldap_defaultgroup', 0);
- $ldapDefaultProfile = Request::analyze('ldap_defaultprofile', 0);
- $ldapBindUser = Request::analyze('ldap_binduser');
- $ldapBindPass = Request::analyzeEncrypted('ldap_bindpass');
-
- // Valores para la configuración de LDAP
- if ($ldapEnabled && (!$ldapServer || !$ldapBase || !$ldapBindUser)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de LDAP'));
- return;
- }
-
- if ($ldapEnabled) {
- $this->ConfigData->setLdapEnabled(true);
- $this->ConfigData->setLdapAds($ldapADSEnabled);
- $this->ConfigData->setLdapServer($ldapServer);
- $this->ConfigData->setLdapBase($ldapBase);
- $this->ConfigData->setLdapGroup($ldapGroup);
- $this->ConfigData->setLdapDefaultGroup($ldapDefaultGroup);
- $this->ConfigData->setLdapDefaultProfile($ldapDefaultProfile);
- $this->ConfigData->setLdapBindUser($ldapBindUser);
- $this->ConfigData->setLdapBindPass($ldapBindPass);
-
- $this->LogMessage->addDescription(__('LDAP habiltado', false));
- } elseif ($this->ConfigData->isLdapEnabled()) {
- $this->ConfigData->setLdapEnabled(false);
-
- $this->LogMessage->addDescription(__('LDAP deshabilitado', false));
- }
-
- $this->LogMessage->addDetails(__('Sección', false), __('LDAP', false));
- $this->JsonResponse->setStatus(0);
-
- $this->saveConfig();
- }
-
- /**
- * Accion para opciones de correo
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function mailAction()
- {
- // Mail
- $mailEnabled = Request::analyze('mail_enabled', false, false, true);
- $mailServer = Request::analyze('mail_server');
- $mailPort = Request::analyze('mail_port', 25);
- $mailUser = Request::analyze('mail_user');
- $mailPass = Request::analyzeEncrypted('mail_pass');
- $mailSecurity = Request::analyze('mail_security');
- $mailFrom = Request::analyze('mail_from');
- $mailRequests = Request::analyze('mail_requestsenabled', false, false, true);
- $mailAuth = Request::analyze('mail_authenabled', false, false, true);
-
- // Valores para la configuración del Correo
- if ($mailEnabled && (!$mailServer || !$mailFrom)) {
- $this->JsonResponse->setDescription(__('Faltan parámetros de Correo'));
- return;
- }
-
- if ($mailEnabled) {
- $this->ConfigData->setMailEnabled(true);
- $this->ConfigData->setMailRequestsEnabled($mailRequests);
- $this->ConfigData->setMailServer($mailServer);
- $this->ConfigData->setMailPort($mailPort);
- $this->ConfigData->setMailSecurity($mailSecurity);
- $this->ConfigData->setMailFrom($mailFrom);
-
- if ($mailAuth) {
- $this->ConfigData->setMailAuthenabled($mailAuth);
- $this->ConfigData->setMailUser($mailUser);
- $this->ConfigData->setMailPass($mailPass);
- }
-
- $this->LogMessage->addDescription(__('Correo habiltado', false));
- } elseif ($this->ConfigData->isMailEnabled()) {
- $this->ConfigData->setMailEnabled(false);
- $this->ConfigData->setMailRequestsEnabled(false);
- $this->ConfigData->setMailAuthenabled(false);
-
- $this->LogMessage->addDescription(__('Correo deshabilitado', false));
- }
-
- $this->LogMessage->addDetails(__('Sección', false), __('Correo', false));
- $this->JsonResponse->setStatus(0);
-
- $this->saveConfig();
- }
-
- /**
- * Acción para cambio de clave maestra
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \phpmailer\phpmailerException
- */
- protected function masterPassAction()
- {
- $currentMasterPass = Request::analyzeEncrypted('curMasterPwd');
- $newMasterPass = Request::analyzeEncrypted('newMasterPwd');
- $newMasterPassR = Request::analyzeEncrypted('newMasterPwdR');
- $confirmPassChange = Request::analyze('confirmPassChange', 0, false, 1);
- $noAccountPassChange = Request::analyze('chkNoAccountChange', 0, false, 1);
-
- if (!UserPass::checkUserUpdateMPass(SessionFactory::getUserData()->getId())) {
- $this->JsonResponse->setDescription(__('Clave maestra actualizada', false));
- $this->JsonResponse->addMessage(__('Reinicie la sesión para cambiarla', false));
- $this->JsonResponse->setStatus(100);
- return;
- }
-
- if (empty($newMasterPass) || empty($currentMasterPass)) {
- $this->JsonResponse->setDescription(__('Clave maestra no indicada'));
- return;
- }
-
- if ($confirmPassChange === false) {
- $this->JsonResponse->setDescription(__('Se ha de confirmar el cambio de clave', false));
- return;
- }
-
- if ($newMasterPass === $currentMasterPass) {
- $this->JsonResponse->setDescription(__('Las claves son idénticas', false));
- return;
- }
-
- if ($newMasterPass !== $newMasterPassR) {
- $this->JsonResponse->setDescription(__('Las claves maestras no coinciden', false));
- return;
- }
-
- if (!Hash::checkHashKey($currentMasterPass, ConfigDB::getValue('masterPwd'))) {
- $this->JsonResponse->setDescription(__('La clave maestra actual no coincide', false));
- return;
- }
-
- if ($this->ConfigData->isDemoEnabled()) {
- $this->JsonResponse->setDescription(__('Ey, esto es una DEMO!!', false));
- return;
- }
-
- if (!$noAccountPassChange) {
- Util::lockApp();
-
- if (!DbWrapper::beginTransaction()) {
- $this->JsonResponse->setDescription(__('No es posible iniciar una transacción', false));
- return;
- }
-
- TaskFactory::createTask(__FUNCTION__, Request::analyze('taskId'));
-
- $Account = new AccountCrypt();
-
- if (!$Account->updatePass($currentMasterPass, $newMasterPass)) {
- DbWrapper::rollbackTransaction();
-
- TaskFactory::endTask();
-
- $this->JsonResponse->setDescription(__('Errores al actualizar las claves de las cuentas', false));
- return;
- }
-
- $AccountHistory = new AccountHistoryCrypt();
-
- if (!$AccountHistory->updatePass($currentMasterPass, $newMasterPass)) {
- DbWrapper::rollbackTransaction();
-
- TaskFactory::endTask();
-
- $this->JsonResponse->setDescription(__('Errores al actualizar las claves de las cuentas del histórico', false));
- return;
- }
-
- if (!CustomFieldsUtil::updateCustomFieldsCrypt($currentMasterPass, $newMasterPass)) {
- DbWrapper::rollbackTransaction();
-
- TaskFactory::endTask();
-
- $this->JsonResponse->setDescription(__('Errores al actualizar datos de campos personalizados', false));
- return;
- }
-
- if (!DbWrapper::endTransaction()) {
- TaskFactory::endTask();
-
- $this->JsonResponse->setDescription(__('No es posible finalizar una transacción', false));
- return;
- }
-
- TaskFactory::endTask();
-
- Util::unlockApp();
- }
-
- ConfigDB::setCacheConfigValue('masterPwd', Hash::hashKey($newMasterPass));
- ConfigDB::setCacheConfigValue('lastupdatempass', time());
-
- $this->LogMessage->setAction(__('Actualizar Clave Maestra', false));
-
- if (ConfigDB::writeConfig()) {
- $this->LogMessage->addDescription(__('Clave maestra actualizada', false));
-
- $this->JsonResponse->addMessage(__('Reinicie la sesión para cambiarla', false));
- $this->JsonResponse->setStatus(100);
- } else {
- $this->LogMessage->addDescription(__('Error al guardar el hash de la clave maestra', false));
- }
-
- Email::sendEmail($this->LogMessage);
- }
-
- /**
- * Regenerar el hash de la clave maestra
- *
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- protected function masterPassRefreshAction()
- {
- if ($this->ConfigData->isDemoEnabled()) {
- $this->JsonResponse->setDescription(__('Ey, esto es una DEMO!!', false));
- return;
- }
-
- $this->LogMessage->setAction(__('Actualizar Clave Maestra', false));
-
- if (ConfigDB::setValue('masterPwd', Hash::hashKey(CryptSession::getSessionKey()))) {
- $this->LogMessage->addDescription(__('Hash de clave maestra actualizado', false));
-
- $this->JsonResponse->setStatus(0);
- } else {
- $this->LogMessage->addDescription(__('Error al actualizar el hash de la clave maestra', false));
- }
-
- Email::sendEmail($this->LogMessage);
- }
-
- /**
- * Acción para generar clave maestra temporal
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \phpmailer\phpmailerException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- protected function tempMasterPassAction()
- {
- $tempMasterMaxTime = Request::analyze('tmpass_maxtime', 3600);
- $tempMasterPass = CryptMasterPass::setTempMasterPass($tempMasterMaxTime);
- $tempMasterGroup = Request::analyze('tmpass_group', 0);
- $tempMasterEmail = Request::analyze('tmpass_chkSendEmail', 0, false, 1);
-
- $this->LogMessage->setAction(__('Generar Clave Temporal', false));
-
- if ($tempMasterPass !== false && !empty($tempMasterPass)) {
- $this->LogMessage->addDescription(__('Clave Temporal Generada', false));
-
- if ($tempMasterEmail) {
- $Message = new NoticeMessage();
- $Message->setTitle(sprintf(__('Clave Maestra %s'), Util::getAppInfo('appname')));
- $Message->addDescription(__('Se ha generado una nueva clave para el acceso a sysPass y se solicitará en el siguiente inicio.'));
- $Message->addDescription('');
- $Message->addDescription(sprintf(__('La nueva clave es: %s'), $tempMasterPass));
- $Message->addDescription('');
- $Message->addDescription(__('No olvide acceder lo antes posible para guardar los cambios.'));
-
- if ($tempMasterGroup !== 0) {
- Email::sendEmailBatch($Message, UserUtil::getUserGroupEmail($tempMasterGroup));
- } else {
- Email::sendEmailBatch($Message, UserUtil::getUsersEmail());
- }
- }
-
- $this->JsonResponse->setStatus(0);
- } else {
- $this->LogMessage->addDescription(__('Error al generar clave temporal', false));
- }
-
- Email::sendEmail($this->LogMessage);
- }
-
- /**
- * Acción para importar cuentas
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function importAction()
- {
- if ($this->ConfigData->isDemoEnabled()) {
- $this->JsonResponse->setDescription(__('Ey, esto es una DEMO!!', false));
- return;
- }
-
- $ImportParams = new ImportParams();
- $ImportParams->setDefaultUser(Request::analyze('import_defaultuser', SessionFactory::getUserData()->getId()));
- $ImportParams->setDefaultGroup(Request::analyze('import_defaultgroup', SessionFactory::getUserData()->getUserGroupId()));
- $ImportParams->setImportPwd(Request::analyzeEncrypted('importPwd'));
- $ImportParams->setImportMasterPwd(Request::analyzeEncrypted('importMasterPwd'));
- $ImportParams->setCsvDelimiter(Request::analyze('csvDelimiter'));
-
- $Import = new ImportService($ImportParams);
- $LogMessage = $Import->doImport($_FILES['inFile']);
-
- $this->JsonResponse->setDescription($LogMessage->getHtmlDescription(true));
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acción para exportar cuentas
- */
- protected function exportAction()
- {
- $exportPassword = Request::analyzeEncrypted('exportPwd');
- $exportPasswordR = Request::analyzeEncrypted('exportPwdR');
-
- if (!empty($exportPassword) && $exportPassword !== $exportPasswordR) {
- $this->JsonResponse->setDescription(__('Las claves no coinciden', false));
- return;
- }
-
- if (!XmlExport::doExport($exportPassword)) {
- $this->JsonResponse->setDescription(__('Error al realizar la exportación', false));
- $this->JsonResponse->addMessage(__('Revise el registro de eventos para más detalles', false));
- return;
- }
-
- $this->JsonResponse->setDescription(__('Proceso de exportación finalizado', false));
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acción para realizar el backup de sysPass
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \phpmailer\phpmailerException
- */
- protected function backupAction()
- {
- if ($this->ConfigData->isDemoEnabled()) {
- $this->JsonResponse->setDescription(__('Ey, esto es una DEMO!!', false));
- return;
- }
-
- $Backup = new Backup();
-
- if (!$Backup->doBackup()) {
- $this->JsonResponse->setDescription(__('Error al realizar el backup', false));
- $this->JsonResponse->addMessage(__('Revise el registro de eventos para más detalles', false));
- return;
- }
-
- $this->JsonResponse->setDescription(__('Proceso de backup finalizado', false));
- $this->JsonResponse->setStatus(0);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ConfigController.php b/lib/SP/Controller/ConfigController.php
deleted file mode 100644
index d16ecac3..00000000
--- a/lib/SP/Controller/ConfigController.php
+++ /dev/null
@@ -1,361 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\AccountUtil;
-use SP\Config\ConfigDB;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Crypt\CryptSessionHandler;
-use SP\Core\CryptMasterPass;
-use SP\Core\Init;
-use SP\Core\Language;
-use SP\Core\Plugin\PluginUtil;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\Mgmt\Groups\Group;
-use SP\Mgmt\Profiles\Profile;
-use SP\Mgmt\Users\User;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-use SP\Services\Task\Task;
-use SP\Storage\DBUtil;
-use SP\Util\Checks;
-use SP\Util\Util;
-
-/**
- * Clase encargada de preparar la presentación de las opciones de configuración
- *
- * @package Controller
- */
-class ConfigController extends ControllerBase implements ActionsInterface
-{
- /**
- * @var int
- */
- private $tabIndex = 0;
- /**
- * @var array
- */
- private $configDB;
-
- /**
- * Constructor
- *
- * @param $template \SP\Mvc\View\Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->configDB = ConfigDB::readConfig();
-
- $this->view->assign('tabs', []);
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->view->assign('isDemoMode', $this->configData->isDemoEnabled() && !$this->userData->isIsAdminApp());
- $this->view->assign('isDisabled', ($this->configData->isDemoEnabled() && !$this->userData->isIsAdminApp()) ? 'disabled' : '');
- $this->view->assign('ConfigData', $this->configData);
- }
-
- /**
- * Realizar las accione del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- $this->view->addTemplate('tabs-start', 'common');
-
- $this->getGeneralTab();
- $this->getAccountsTab();
- $this->getWikiTab();
- $this->getLdapTab();
- $this->getMailTab();
- $this->getEncryptionTab();
- $this->getBackupTab();
- $this->getImportTab();
- $this->getInfoTab();
-
- $this->eventDispatcher->notifyEvent('show.config', $this);
-
- $this->view->addTemplate('tabs-end', 'common');
- }
-
- /**
- * Obtener la pestaña de configuración
- *
- * @return void
- */
- protected function getGeneralTab()
- {
- $this->setAction(self::CONFIG_GENERAL);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('general');
-
- $this->view->assign('langsAvailable', Language::getAvailableLanguages());
- $this->view->assign('themesAvailable', $this->theme->getThemesAvailable());
-
- $this->view->assign('actionId', $this->getAction(), 'config');
- $this->view->append('tabs', ['title' => __('General')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'config');
- }
-
- /**
- * Obtener el índice actual de las pestañas
- *
- * @return int
- */
- private function getTabIndex()
- {
- $index = $this->tabIndex;
- $this->tabIndex++;
-
- return $index;
- }
-
- /**
- * Obtener la pestaña de cuentas
- */
- protected function getAccountsTab()
- {
- $this->setAction(self::ACCOUNT_CONFIG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('accounts');
-
- $this->view->assign('actionId', $this->getAction(), 'accounts');
- $this->view->append('tabs', ['title' => __('Cuentas')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'accounts');
- }
-
- /**
- * Obtener la pestaña de Wiki
- *
- * @return void
- */
- protected function getWikiTab()
- {
- $this->setAction(self::WIKI_CONFIG);
-
- if (!$this->checkAccess(self::CONFIG_GENERAL)) {
- return;
- }
-
- $this->view->addTemplate('wiki');
-
- $this->view->assign('actionId', $this->getAction(), 'wiki');
- $this->view->append('tabs', ['title' => __('Wiki')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'wiki');
- }
-
- /**
- * Obtener la pestaña de LDAP
- *
- * @return void
- */
- protected function getLdapTab()
- {
- $this->setAction(self::LDAP_CONFIG);
-
- if (!$this->checkAccess(self::CONFIG_GENERAL)) {
- return;
- }
-
- $this->view->addTemplate('ldap');
-
- $this->view->assign('ldapIsAvailable', Checks::ldapIsAvailable());
- $this->view->assign('groups', Group::getItem()->getItemsForSelect());
- $this->view->assign('profiles', Profile::getItem()->getItemsForSelect());
-
- $this->view->assign('actionId', $this->getAction(), 'ldap');
- $this->view->append('tabs', ['title' => __('LDAP')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'ldap');
- }
-
- /**
- * Obtener la pestaña de Correo
- *
- * @return void
- */
- protected function getMailTab()
- {
- $this->setAction(self::MAIL_CONFIG);
-
- if (!$this->checkAccess(self::CONFIG_GENERAL)) {
- return;
- }
-
- $this->view->addTemplate('mail');
-
- $this->view->assign('mailSecurity', ['SSL', 'TLS']);
-
- $this->view->assign('actionId', $this->getAction(), 'mail');
- $this->view->append('tabs', ['title' => __('Correo')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'mail');
- }
-
- /**
- * Obtener la pestaña de encriptación
- *
- * @return void
- */
- protected function getEncryptionTab()
- {
- $this->setAction(self::ENCRYPTION_CONFIG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('encryption');
-
- $this->view->assign('numAccounts', AccountUtil::getTotalNumAccounts());
- $this->view->assign('taskId', Task::genTaskId('masterpass'));
-
- $this->view->assign('lastUpdateMPass', isset($this->configDB['lastupdatempass']) ? $this->configDB['lastupdatempass'] : 0);
- $this->view->assign('tempMasterPassTime', isset($this->configDB['tempmaster_passtime']) ? $this->configDB['tempmaster_passtime'] : 0);
- $this->view->assign('tempMasterMaxTime', isset($this->configDB['tempmaster_maxtime']) ? $this->configDB['tempmaster_maxtime'] : 0);
- $this->view->assign('tempMasterAttempts', isset($this->configDB['tempmaster_attempts']) ? sprintf('%d/%d', $this->configDB['tempmaster_attempts'], CryptMasterPass::MAX_ATTEMPTS) : 0);
- $this->view->assign('tempMasterPass', SessionFactory::getTemporaryMasterPass());
- $this->view->assign('groups', Group::getItem()->getItemsForSelect());
-
- $this->view->append('tabs', ['title' => __('Encriptación')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'encryption');
- }
-
- /**
- * Obtener la pestaña de copia de seguridad
- *
- * @return void
- */
- protected function getBackupTab()
- {
- $this->setAction(self::BACKUP_CONFIG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('backup');
-
- $this->view->assign('siteName', Util::getAppInfo('appname'));
- $this->view->assign('backupDir', Init::$SERVERROOT . '/backup');
- $this->view->assign('backupPath', Init::$WEBROOT . '/backup');
- $this->view->assign('isAdminApp', $this->userData->isIsAdminApp());
-
- $backupHash = $this->configData->getBackupHash();
- $exportHash = $this->configData->getExportHash();
-
- $backupFile = $this->view->siteName . '-' . $backupHash . '.tar.gz';
-
- $this->view->assign('backupFile',
- ['absolute' => $this->view->backupDir . DIRECTORY_SEPARATOR . $backupFile,
- 'relative' => $this->view->backupPath . '/' . $backupFile,
- 'filename' => $backupFile]
- );
-
- $backupDbFile = $this->view->siteName . '_db-' . $backupHash . '.sql';
-
- $this->view->assign('backupDbFile',
- ['absolute' => $this->view->backupDir . DIRECTORY_SEPARATOR . $backupDbFile,
- 'relative' => $this->view->backupPath . '/' . $backupDbFile,
- 'filename' => $backupDbFile]
- );
-
- clearstatcache(true, $this->view->backupFile['absolute']);
- clearstatcache(true, $this->view->backupDbFile['absolute']);
- $this->view->assign('lastBackupTime', file_exists($this->view->backupFile['absolute']) ? __('Último backup') . ': ' . date('r', filemtime($this->view->backupFile['absolute'])) : __('No se encontraron backups'));
-
- $exportFile = $this->view->siteName . '-' . $exportHash . '.xml';
-
- $this->view->assign('exportFile',
- ['absolute' => $this->view->backupDir . DIRECTORY_SEPARATOR . $exportFile,
- 'relative' => $this->view->backupPath . '/' . $exportFile,
- 'filename' => $exportFile]
- );
-
- clearstatcache(true, $this->view->exportFile['absolute']);
- $this->view->assign('lastExportTime', file_exists($this->view->exportFile['absolute']) ? __('Última exportación') . ': ' . date('r', filemtime($this->view->exportFile['absolute'])) : __('No se encontró archivo de exportación'));
-
- $this->view->append('tabs', ['title' => __('Copia de Seguridad')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'backup');
- }
-
- /**
- * Obtener la pestaña de Importación
- *
- * @return void
- */
- protected function getImportTab()
- {
- $this->setAction(self::IMPORT_CONFIG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('import');
-
- $this->view->assign('groups', Group::getItem()->getItemsForSelect());
- $this->view->assign('users', User::getItem()->getItemsForSelect());
-
- $this->view->append('tabs', ['title' => __('Importar Cuentas')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'import');
- }
-
- /**
- * Obtener la pestaña de información
- *
- * @return void
- */
- protected function getInfoTab()
- {
- $this->setAction(self::CONFIG_GENERAL);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('info');
-
- $this->view->assign('dbInfo', DBUtil::getDBinfo());
- $this->view->assign('dbName', $this->configData->getDbName() . '@' . $this->configData->getDbHost());
- $this->view->assign('configBackupDate', date('r', $this->configDB['config_backupdate']));
- $this->view->assign('plugins', PluginUtil::getLoadedPlugins());
- $this->view->assign('locale', Language::$localeStatus ?: sprintf('%s (%s)', $this->configData->getSiteLang(), __('No instalado')));
- $this->view->assign('securedSession', CryptSessionHandler::$isSecured);
-
- $this->view->append('tabs', ['title' => __('Información')]);
- $this->view->assign('tabIndex', $this->getTabIndex(), 'info');
- }
-}
diff --git a/lib/SP/Controller/EventlogController.php b/lib/SP/Controller/EventlogController.php
deleted file mode 100644
index b096226b..00000000
--- a/lib/SP/Controller/EventlogController.php
+++ /dev/null
@@ -1,158 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\SessionUtil;
-use SP\Html\DataGrid\DataGridActionSearch;
-use SP\Html\DataGrid\DataGridActionType;
-use SP\Html\DataGrid\DataGridPager;
-use SP\Http\Request;
-use SP\Http\Response;
-use SP\Log\Log;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-
-/**
- * Clase encargada de preparar la presentación del registro de eventos
- *
- * @package Controller
- */
-class EventlogController extends ControllerBase implements ActionsInterface
-{
- /**
- * Número de máximo de registros por página
- */
- const MAX_ROWS = 50;
- /**
- * @var
- */
- protected $limitStart;
-
- /**
- * Constructor
- *
- * @param $template \SP\Mvc\View\Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- }
-
- /**
- * Realizar las acciones del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- $this->limitStart = Request::analyze('start', 0);
-
- $this->checkClear();
- $this->getEventlog();
-
- $this->eventDispatcher->notifyEvent('show.eventlog', $this);
- }
-
- /**
- * Comprobar si es necesario limpiar el registro de eventos
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \phpmailer\phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function checkClear()
- {
- $clear = Request::analyze('clear', 0);
-
- if ($clear === 1
- && $this->view->sk
- && SessionUtil::checkSessionKey($this->view->sk)
- ) {
- Log::clearEvents();
-
- Log::writeNewLogAndEmail(__('Vaciar Eventos', false), __('Vaciar registro de eventos', false), null);
-
- Response::printJson(__('Registro de eventos vaciado', false), 0);
- }
- }
-
- /**
- * Obtener los datos para la presentación de la tabla de eventos
- */
- public function getEventlog()
- {
- $this->setAction(self::EVENTLOG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('eventlog');
-
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::EVENTLOG);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchEvent');
- $GridActionSearch->setTitle(__('Buscar Evento'));
- $GridActionSearch->setOnSubmitFunction('eventlog/search');
-
- $this->view->assign('rowClass', 'row_even');
- $this->view->assign('isDemoMode', $this->configData->isDemoEnabled() || !$this->userData->isIsAdminApp());
- $this->view->assign('limitStart', $this->limitStart);
- $this->view->assign('events', Log::getEvents($this->limitStart, self::MAX_ROWS));
-
- $Pager = $this->getPager($GridActionSearch);
- $Pager->setTotalRows(Log::$numRows);
-
- $this->view->assign('Pager', $Pager);
- }
-
- /**
- * Devolver el paginador por defecto
- *
- * @param DataGridActionSearch $sourceAction
- * @return DataGridPager
- */
- protected function getPager(DataGridActionSearch $sourceAction)
- {
- $GridPager = new DataGridPager();
- $GridPager->setSourceAction($sourceAction);
- $GridPager->setOnClickFunction('eventlog/nav');
- $GridPager->setLimitStart($this->limitStart);
- $GridPager->setLimitCount(self::MAX_ROWS);
- $GridPager->setIconPrev($this->icons->getIconNavPrev());
- $GridPager->setIconNext($this->icons->getIconNavNext());
- $GridPager->setIconFirst($this->icons->getIconNavFirst());
- $GridPager->setIconLast($this->icons->getIconNavLast());
-
- return $GridPager;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/GridItemsSearchController.php b/lib/SP/Controller/GridItemsSearchController.php
deleted file mode 100644
index fe489de6..00000000
--- a/lib/SP/Controller/GridItemsSearchController.php
+++ /dev/null
@@ -1,64 +0,0 @@
-.
- */
-
-/**
- * Created by PhpStorm.
- * User: rdb
- * Date: 24/11/15
- * Time: 14:14
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Html\DataGrid\DataGridPagerInterface;
-use SP\Modules\Web\Controllers\ControllerBase;
-
-/**
- * Class GridItemsSearch para construcción de clases que usen el Grid de búsqueda de registros
- *
- * @package SP\Controller
- */
-abstract class GridItemsSearchController extends ControllerBase
-{
- /**
- * @var mixed
- */
- protected $grids;
-
- /**
- * Actualizar los datos del paginador
- *
- * @param DataGridPagerInterface $Pager
- * @param ItemSearchData $SearchData
- */
- protected function updatePager(DataGridPagerInterface $Pager, ItemSearchData $SearchData)
- {
- $Pager->setLimitStart($SearchData->getLimitStart());
- $Pager->setLimitCount($SearchData->getLimitCount());
- $Pager->setFilterOn($SearchData->getSeachString() !== '');
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/GridTabControllerBase.php b/lib/SP/Controller/GridTabControllerBase.php
deleted file mode 100644
index 1e19852e..00000000
--- a/lib/SP/Controller/GridTabControllerBase.php
+++ /dev/null
@@ -1,77 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Controller\Grids\Items;
-use SP\Core\SessionUtil;
-use SP\Core\Template;
-use SP\Modules\Web\Controllers\ControllerBase;
-
-/**
- * Class GridTabController para la construcción de clases que utilicen el grid de pestañas
- *
- * @package SP\Controller
- */
-abstract class GridTabControllerBase extends ControllerBase
-{
- /**
- * Máximo numero de acciones antes de agrupar
- */
- const MAX_NUM_ACTIONS = 3;
- /**
- * @var mixed
- */
- protected $Grids;
-
- /**
- * Constructor
- *
- * @param $template Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->view->assign('isDemo', $this->configData->isDemoEnabled());
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- }
-
- /**
- * Inicializar las plantillas para las pestañas
- */
- public function useTabs()
- {
- $this->Grids = new Items();
- $this->Grids->setQueryTimeStart($this->view->queryTimeStart);
-
- $this->view->addTemplate('datatabs-grid', 'grid');
-
- $this->view->assign('tabs', []);
- $this->view->assign('activeTab', 0);
- $this->view->assign('maxNumActions', self::MAX_NUM_ACTIONS);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/Grids/GridBase.php b/lib/SP/Controller/Grids/GridBase.php
deleted file mode 100644
index 6bf69769..00000000
--- a/lib/SP/Controller/Grids/GridBase.php
+++ /dev/null
@@ -1,123 +0,0 @@
-.
- */
-
-namespace SP\Controller\Grids;
-
-use SP\Config\ConfigData;
-use SP\Core\Context\SessionContext;
-use SP\Core\UI\Theme;
-use SP\Core\UI\ThemeIcons;
-use SP\Html\DataGrid\DataGridActionSearch;
-use SP\Html\DataGrid\DataGridPager;
-
-/**
- * Class GridBase
- *
- * @package SP\Controller\Grids
- */
-abstract class GridBase
-{
- /**
- * @var ThemeIcons
- */
- protected $icons;
- /**
- * @var string
- */
- protected $sk;
- /**
- * @var int
- */
- protected $queryTimeStart;
- /**
- * @var bool
- */
- protected $filter = false;
- /**
- * @var ConfigData
- */
- protected $ConfigData;
- /**
- * @var Theme
- */
- protected $theme;
-
- /**
- * Grids constructor.
- * @param Theme $theme
- * @param SessionContext $session
- */
- public function __construct(Theme $theme, SessionContext $session)
- {
- $this->sk = $session->getSecurityKey();
- $this->icons = $this->theme->getIcons();
- }
-
- /**
- * @param ConfigData $configData
- * @param Theme $theme
- */
- public function inject(ConfigData $configData, Theme $theme)
- {
- $this->ConfigData = $configData;
- $this->theme = $theme;
- }
-
- /**
- * @param boolean $filter
- */
- public function setFilter($filter)
- {
- $this->filter = $filter;
- }
-
- /**
- * @param int $queryTimeStart
- */
- public function setQueryTimeStart($queryTimeStart)
- {
- $this->queryTimeStart = $queryTimeStart;
- }
-
- /**
- * Devolver el paginador por defecto
- *
- * @param DataGridActionSearch $sourceAction
- * @return DataGridPager
- */
- protected function getPager(DataGridActionSearch $sourceAction)
- {
- $GridPager = new DataGridPager();
- $GridPager->setSourceAction($sourceAction);
- $GridPager->setOnClickFunction('appMgmt/nav');
- $GridPager->setLimitStart(0);
- $GridPager->setLimitCount($this->ConfigData->getAccountCount());
- $GridPager->setIconPrev($this->icons->getIconNavPrev());
- $GridPager->setIconNext($this->icons->getIconNavNext());
- $GridPager->setIconFirst($this->icons->getIconNavFirst());
- $GridPager->setIconLast($this->icons->getIconNavLast());
-
- return $GridPager;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/Grids/Items.php b/lib/SP/Controller/Grids/Items.php
deleted file mode 100644
index fe32d1c1..00000000
--- a/lib/SP/Controller/Grids/Items.php
+++ /dev/null
@@ -1,1061 +0,0 @@
-.
- */
-
-namespace SP\Controller\Grids;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Acl\Acl;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Exceptions\InvalidArgumentException;
-use SP\Html\Assets\FontIcon;
-use SP\Html\DataGrid\DataGridAction;
-use SP\Html\DataGrid\DataGridActionSearch;
-use SP\Html\DataGrid\DataGridActionType;
-use SP\Html\DataGrid\DataGridData;
-use SP\Html\DataGrid\DataGridHeader;
-use SP\Html\DataGrid\DataGridTab;
-
-/**
- * Class Grids con las plantillas de tablas de datos
- *
- * @package SP\Controller
- */
-class Items extends GridBase
-{
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getCategoriesGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Descripción'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('id');
- $GridData->addDataRowSource('name');
- $GridData->addDataRowSource('description');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblCategories');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Categorías'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::CATEGORY_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchCategory');
- $GridActionSearch->setTitle(__('Buscar Categoría'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::CATEGORY_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nueva Categoría'));
- $GridActionNew->setTitle(__('Nueva Categoría'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::CATEGORY_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Categoría'));
- $GridActionEdit->setTitle(__('Editar Categoría'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::CATEGORY_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Categoría'));
- $GridActionDel->setTitle(__('Eliminar Categoría'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getCustomersGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Descripción'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('id');
- $GridData->addDataRowSource('name');
- $GridData->addDataRowSource('description');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblCustomers');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Clientes'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::CLIENT_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchCustomer');
- $GridActionSearch->setTitle(__('Buscar Cliente'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::CLIENT_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nuevo Cliente'));
- $GridActionNew->setTitle(__('Nuevo Cliente'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::CLIENT_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Cliente'));
- $GridActionEdit->setTitle(__('Editar Cliente'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::CLIENT_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Cliente'));
- $GridActionDel->setTitle(__('Eliminar Cliente'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getCustomFieldsGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Módulo'));
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Tipo'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('id');
- $GridData->addDataRowSource('moduleName');
- $GridData->addDataRowSource('name');
- $GridData->addDataRowSource('typeName');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblCustomFields');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Campos Personalizados'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::CUSTOMFIELD_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchCustomField');
- $GridActionSearch->setTitle(__('Buscar Campo'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::CUSTOMFIELD_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nuevo Campo'));
- $GridActionNew->setTitle(__('Nuevo Campo'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::CUSTOMFIELD_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Campo'));
- $GridActionEdit->setTitle(__('Editar Campo'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::CUSTOMFIELD_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Campo'));
- $GridActionDel->setTitle(__('Eliminar Campo'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getFilesGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Cuenta'));
- $GridHeaders->addHeader(__('Cliente'));
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Tipo'));
- $GridHeaders->addHeader(__('Tamaño'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('accfile_id');
- $GridData->addDataRowSource('account_name');
- $GridData->addDataRowSource('name');
- $GridData->addDataRowSource('accfile_name');
- $GridData->addDataRowSource('accfile_type');
- $GridData->addDataRowSource('accfile_size');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblFiles');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Archivos'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::FILE_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchFile');
- $GridActionSearch->setTitle(__('Buscar Archivo'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::FILE_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Archivo'));
- $GridActionView->setTitle(__('Ver Archivo'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('file/view');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::FILE_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Archivo'));
- $GridActionDel->setTitle(__('Eliminar Archivo'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getAccountsGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Cliente'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('account_id');
- $GridData->addDataRowSource('account_name');
- $GridData->addDataRowSource('name');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblAccounts');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Cuentas'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::ACCOUNTMGR_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchAccount');
- $GridActionSearch->setTitle(__('Buscar Cuenta'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::ACCOUNTMGR_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Cuenta'));
- $GridActionDel->setTitle(__('Eliminar Cuenta'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getAccountsHistoryGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Cliente'));
- $GridHeaders->addHeader(__('Fecha'));
- $GridHeaders->addHeader(__('Estado'));
-
- $iconEdit = clone $this->icons->getIconEdit();
- $iconDelete = clone $this->icons->getIconDelete();
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('acchistory_id');
- $GridData->addDataRowSource('acchistory_name');
- $GridData->addDataRowSource('name');
- $GridData->addDataRowSource('acchistory_date');
- $GridData->addDataRowSourceWithIcon('acchistory_isModify', $iconEdit->setTitle(__('Modificada'))->setClass('opacity50'));
- $GridData->addDataRowSourceWithIcon('acchistory_isDeleted', $iconDelete->setTitle(__('Eliminada'))->setClass('opacity50'));
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblAccountsHistory');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Cuentas (H)'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::ACCOUNTMGR_SEARCH_HISTORY);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchAccountHistory');
- $GridActionSearch->setTitle(__('Buscar Cuenta'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionRestore = new DataGridAction();
- $GridActionRestore->setId(self::ACCOUNTMGR_EDIT_RESTORE);
- $GridActionRestore->setType(DataGridActionType::EDIT_ITEM);
- $GridActionRestore->setName(__('Restaurar Cuenta'));
- $GridActionRestore->setTitle(__('Restaurar Cuenta'));
- $GridActionRestore->setIcon($this->icons->getIconRestore());
- $GridActionRestore->setOnClickFunction('');
-
-// $Grid->setDataActions($GridActionRestore);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::ACCOUNTMGR_DELETE_HISTORY);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Cuenta'));
- $GridActionDel->setTitle(__('Eliminar Cuenta'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getUsersGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Login'));
- $GridHeaders->addHeader(__('Perfil'));
- $GridHeaders->addHeader(__('Grupo'));
- $GridHeaders->addHeader(__('Propiedades'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('user_id');
- $GridData->addDataRowSource('user_name');
- $GridData->addDataRowSource('user_login');
- $GridData->addDataRowSource('userprofile_name');
- $GridData->addDataRowSource('usergroup_name');
- $GridData->addDataRowSourceWithIcon('user_isAdminApp', $this->icons->getIconAppAdmin());
- $GridData->addDataRowSourceWithIcon('user_isAdminAcc', $this->icons->getIconAccAdmin());
- $GridData->addDataRowSourceWithIcon('user_isLdap', $this->icons->getIconLdapUser());
- $GridData->addDataRowSourceWithIcon('user_isDisabled', $this->icons->getIconDisabled());
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblUsers');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Usuarios'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::USER_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchUser');
- $GridActionSearch->setTitle(__('Buscar Usuario'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::USER_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nuevo Usuario'));
- $GridActionNew->setTitle(__('Nuevo Usuario'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- if (Acl::checkUserAccess(ActionsInterface::IMPORT_CONFIG)
- && $this->ConfigData->isLdapEnabled()
- ) {
- $GridActionLdapSync = new DataGridAction();
- $GridActionLdapSync->setId(self::LDAP_SYNC);
- $GridActionLdapSync->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionLdapSync->setName(__('Importar usuarios de LDAP'));
- $GridActionLdapSync->setTitle(__('Importar usuarios de LDAP'));
- $GridActionLdapSync->setIcon(new FontIcon('get_app'));
- $GridActionLdapSync->setSkip(true);
- $GridActionLdapSync->setOnClickFunction('appMgmt/ldapSync');
-
- $Grid->setDataActions($GridActionLdapSync);
- }
-
- // Grid item's actions
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::USER_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Detalles de Usuario'));
- $GridActionView->setTitle(__('Ver Detalles de Usuario'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::USER_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Usuario'));
- $GridActionEdit->setTitle(__('Editar Usuario'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionEditPass = new DataGridAction();
- $GridActionEditPass->setId(self::USER_EDIT_PASS);
- $GridActionEditPass->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEditPass->setName(__('Cambiar Clave de Usuario'));
- $GridActionEditPass->setTitle(__('Cambiar Clave de Usuario'));
- $GridActionEditPass->setIcon($this->icons->getIconEditPass());
- $GridActionEditPass->setOnClickFunction('appMgmt/show');
- $GridActionEditPass->setFilterRowSource('user_isLdap');
-
- $Grid->setDataActions($GridActionEditPass);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::USER_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Usuario'));
- $GridActionDel->setTitle(__('Eliminar Usuario'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getGroupsGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
- $GridHeaders->addHeader(__('Descripción'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('usergroup_id');
- $GridData->addDataRowSource('usergroup_name');
- $GridData->addDataRowSource('usergroup_description');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblGroups');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Grupos'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::GROUP_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchGroup');
- $GridActionSearch->setTitle(__('Buscar Grupo'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::GROUP_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nuevo Grupo'));
- $GridActionNew->setTitle(__('Nuevo Grupo'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::GROUP_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Grupo'));
- $GridActionEdit->setTitle(__('Editar Grupo'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::GROUP_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Grupo'));
- $GridActionDel->setTitle(__('Eliminar Grupo'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getProfilesGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('userprofile_id');
- $GridData->addDataRowSource('userprofile_name');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblProfiles');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Perfiles'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::PROFILE_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchProfile');
- $GridActionSearch->setTitle(__('Buscar Perfil'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::PROFILE_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nuevo Perfil'));
- $GridActionNew->setTitle(__('Nuevo Perfil'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::PROFILE_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Detalles de Perfil'));
- $GridActionView->setTitle(__('Ver Detalles de Perfil'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::PROFILE_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Perfil'));
- $GridActionEdit->setTitle(__('Editar Perfil'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::PROFILE_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Perfil'));
- $GridActionDel->setTitle(__('Eliminar Perfil'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getTokensGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Usuario'));
- $GridHeaders->addHeader(__('Acción'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('authtoken_id');
- $GridData->addDataRowSource('user_login');
- $GridData->addDataRowSource('actionId');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblTokens');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Autorizaciones API'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::APITOKEN_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchToken');
- $GridActionSearch->setTitle(__('Buscar Token'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::APITOKEN_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nueva Autorización'));
- $GridActionNew->setTitle(__('Nueva Autorización'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::APITOKEN_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver token de Autorización'));
- $GridActionView->setTitle(__('Ver token de Autorización'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::APITOKEN_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Autorización'));
- $GridActionEdit->setTitle(__('Editar Autorización'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::APITOKEN_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Autorización'));
- $GridActionDel->setTitle(__('Eliminar Autorización'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getPublicLinksGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Cuenta'));
- $GridHeaders->addHeader(__('Fecha Creación'));
- $GridHeaders->addHeader(__('Fecha Caducidad'));
- $GridHeaders->addHeader(__('Usuario'));
- $GridHeaders->addHeader(__('Notificar'));
- $GridHeaders->addHeader(__('Visitas'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('publicLink_id');
- $GridData->addDataRowSource('accountName');
- $GridData->addDataRowSource('publicLink_dateAdd');
- $GridData->addDataRowSource('publicLink_dateExpire');
- $GridData->addDataRowSource('userLogin');
- $GridData->addDataRowSource('notify');
- $GridData->addDataRowSource('publicLink_countViews');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblLinks');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Enlaces'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::PUBLICLINK_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchLink');
- $GridActionSearch->setTitle(__('Buscar Enlace'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::PUBLICLINK_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Enlace'));
- $GridActionView->setTitle(__('Ver Enlace'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionRefresh = new DataGridAction();
- $GridActionRefresh->setId(self::PUBLICLINK_REFRESH);
- $GridActionRefresh->setName(__('Renovar Enlace'));
- $GridActionRefresh->setTitle(__('Renovar Enlace'));
- $GridActionRefresh->setIcon($this->icons->getIconRefresh());
- $GridActionRefresh->setOnClickFunction('link/refresh');
-
- $Grid->setDataActions($GridActionRefresh);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::PUBLICLINK_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Enlace'));
- $GridActionDel->setTitle(__('Eliminar Enlace'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getTagsGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Nombre'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('tag_id');
- $GridData->addDataRowSource('tag_name');
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblTags');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Etiquetas'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::TAG_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchTag');
- $GridActionSearch->setTitle(__('Buscar Etiqueta'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::TAG_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nueva Etiqueta'));
- $GridActionNew->setTitle(__('Nueva Etiqueta'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionNew);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::TAG_EDIT);
- $GridActionEdit->setType(DataGridActionType::EDIT_ITEM);
- $GridActionEdit->setName(__('Editar Etiqueta'));
- $GridActionEdit->setTitle(__('Editar Etiqueta'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('appMgmt/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::TAG_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Etiqueta'));
- $GridActionDel->setTitle(__('Eliminar Etiqueta'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-
- /**
- * @return DataGridTab
- * @throws InvalidArgumentException
- */
- public function getPluginsGrid()
- {
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Plugin'));
- $GridHeaders->addHeader(__('Estado'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('plugin_id');
- $GridData->addDataRowSource('plugin_name');
- $GridData->addDataRowSourceWithIcon('plugin_enabled', $this->icons->getIconEnabled());
- $GridData->addDataRowSourceWithIcon('plugin_enabled', $this->icons->getIconDisabled(), 0);
- $GridData->addDataRowSourceWithIcon('plugin_available', $this->icons->getIconDelete()->setTitle(__('No disponible')), 0);
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblPlugins');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Plugins'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::PLUGIN_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchPlugin');
- $GridActionSearch->setTitle(__('Buscar Plugin'));
- $GridActionSearch->setOnSubmitFunction('appMgmt/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- // Grid item's actions
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::PLUGIN_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Plugin'));
- $GridActionView->setTitle(__('Ver Plugin'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('appMgmt/show');
- $GridActionView->setFilterRowSource('plugin_available', 0);
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionEnable = new DataGridAction();
- $GridActionEnable->setId(self::PLUGIN_ENABLE);
- $GridActionEnable->setName(__('Habilitar'));
- $GridActionEnable->setTitle(__('Habilitar'));
- $GridActionEnable->setIcon($this->icons->getIconEnabled());
- $GridActionEnable->setOnClickFunction('plugin/toggle');
- $GridActionEnable->setFilterRowSource('plugin_enabled');
- $GridActionEnable->setFilterRowSource('plugin_available', 0);
-
- $Grid->setDataActions($GridActionEnable);
-
- $GridActionDisable = new DataGridAction();
- $GridActionDisable->setId(self::PLUGIN_DISABLE);
- $GridActionDisable->setName(__('Deshabilitar'));
- $GridActionDisable->setTitle(__('Deshabilitar'));
- $GridActionDisable->setIcon($this->icons->getIconDisabled());
- $GridActionDisable->setOnClickFunction('plugin/toggle');
- $GridActionDisable->setFilterRowSource('plugin_enabled', 0);
- $GridActionDisable->setFilterRowSource('plugin_available', 0);
-
- $Grid->setDataActions($GridActionDisable);
-
- $GridActionReset = new DataGridAction();
- $GridActionReset->setId(self::PLUGIN_RESET);
- $GridActionReset->setName(__('Restablecer Datos'));
- $GridActionReset->setTitle(__('Restablecer Datos'));
- $GridActionReset->setIcon($this->icons->getIconRefresh());
- $GridActionReset->setOnClickFunction('plugin/reset');
- $GridActionReset->setFilterRowSource('plugin_available', 0);
-
- $Grid->setDataActions($GridActionReset);
-
- return $Grid;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/Grids/Notices.php b/lib/SP/Controller/Grids/Notices.php
deleted file mode 100644
index e3ecf04e..00000000
--- a/lib/SP/Controller/Grids/Notices.php
+++ /dev/null
@@ -1,152 +0,0 @@
-.
- */
-
-namespace SP\Controller\Grids;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\SessionFactory;
-use SP\Html\DataGrid\DataGridAction;
-use SP\Html\DataGrid\DataGridActionSearch;
-use SP\Html\DataGrid\DataGridActionType;
-use SP\Html\DataGrid\DataGridData;
-use SP\Html\DataGrid\DataGridHeader;
-use SP\Html\DataGrid\DataGridTab;
-
-/**
- * Class Notices
- *
- * @package SP\Controller\Grids
- */
-class Notices extends GridBase
-{
- /**
- * @return DataGridTab
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getNoticesGrid()
- {
- $isAdminApp = SessionFactory::getUserData()->isAdminApp();
-
- // Grid Header
- $GridHeaders = new DataGridHeader();
- $GridHeaders->addHeader(__('Fecha'));
- $GridHeaders->addHeader(__('Tipo'));
- $GridHeaders->addHeader(__('Componente'));
- $GridHeaders->addHeader(__('Descripción'));
- $GridHeaders->addHeader(__('Estado'));
-
- // Grid Data
- $GridData = new DataGridData();
- $GridData->setDataRowSourceId('notice_id');
- $GridData->addDataRowSource('notice_date');
- $GridData->addDataRowSource('notice_type');
- $GridData->addDataRowSource('notice_component');
- $GridData->addDataRowSource('notice_description');
- $GridData->addDataRowSourceWithIcon('notice_checked', $this->icons->getIconEnabled()->setTitle(__('Leída')));
-
- // Grid
- $Grid = new DataGridTab();
- $Grid->setId('tblNotices');
- $Grid->setDataRowTemplate('datagrid-rows', 'grid');
- $Grid->setDataPagerTemplate('datagrid-nav-full', 'grid');
- $Grid->setHeader($GridHeaders);
- $Grid->setData($GridData);
- $Grid->setTitle(__('Notificaciones'));
- $Grid->setTime(round(microtime() - $this->queryTimeStart, 5));
-
- // Grid Actions
- $GridActionSearch = new DataGridActionSearch();
- $GridActionSearch->setId(self::NOTICE_USER_SEARCH);
- $GridActionSearch->setType(DataGridActionType::SEARCH_ITEM);
- $GridActionSearch->setName('frmSearchNotice');
- $GridActionSearch->setTitle(__('Buscar Notificación'));
- $GridActionSearch->setOnSubmitFunction('notice/search');
-
- $Grid->setDataActions($GridActionSearch);
- $Grid->setPager($this->getPager($GridActionSearch));
-
- if ($isAdminApp) {
- // Grid item's actions
- $GridActionNew = new DataGridAction();
- $GridActionNew->setId(self::NOTICE_USER_CREATE);
- $GridActionNew->setType(DataGridActionType::MENUBAR_ITEM);
- $GridActionNew->setName(__('Nueva Notificación'));
- $GridActionNew->setTitle(__('Nueva Notificación'));
- $GridActionNew->setIcon($this->icons->getIconAdd());
- $GridActionNew->setSkip(true);
- $GridActionNew->setOnClickFunction('notice/show');
-
- $Grid->setDataActions($GridActionNew);
- }
-
- $GridActionView = new DataGridAction();
- $GridActionView->setId(self::NOTICE_USER_VIEW);
- $GridActionView->setType(DataGridActionType::VIEW_ITEM);
- $GridActionView->setName(__('Ver Notificación'));
- $GridActionView->setTitle(__('Ver Notificación'));
- $GridActionView->setIcon($this->icons->getIconView());
- $GridActionView->setOnClickFunction('notice/show');
-
- $Grid->setDataActions($GridActionView);
-
- $GridActionCheck = new DataGridAction();
- $GridActionCheck->setId(self::NOTICE_USER_CHECK);
- $GridActionCheck->setName(__('Marcar Notificación'));
- $GridActionCheck->setTitle(__('Marcar Notificación'));
- $GridActionCheck->setIcon($this->icons->getIconEnabled());
- $GridActionCheck->setOnClickFunction('notice/check');
- $GridActionCheck->setFilterRowSource('notice_checked');
-
- $Grid->setDataActions($GridActionCheck);
-
- $GridActionEdit = new DataGridAction();
- $GridActionEdit->setId(self::NOTICE_USER_EDIT);
- $GridActionEdit->setName(__('Editar Notificación'));
- $GridActionEdit->setTitle(__('Editar Notificación'));
- $GridActionEdit->setIcon($this->icons->getIconEdit());
- $GridActionEdit->setOnClickFunction('notice/show');
-
- $Grid->setDataActions($GridActionEdit);
-
- $GridActionDel = new DataGridAction();
- $GridActionDel->setId(self::NOTICE_USER_DELETE);
- $GridActionDel->setType(DataGridActionType::DELETE_ITEM);
- $GridActionDel->setName(__('Eliminar Notificación'));
- $GridActionDel->setTitle(__('Eliminar Notificación'));
- $GridActionDel->setIcon($this->icons->getIconDelete());
- $GridActionDel->setOnClickFunction('appMgmt/delete');
-
- if (!$isAdminApp) {
- $GridActionCheck->setFilterRowSource('notice_sticky');
- $GridActionEdit->setFilterRowSource('notice_sticky');
- $GridActionDel->setFilterRowSource('notice_sticky');
- }
-
- $Grid->setDataActions($GridActionDel);
- $Grid->setDataActions($GridActionDel, true);
-
- return $Grid;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemActionController.php b/lib/SP/Controller/ItemActionController.php
deleted file mode 100644
index 24ecc6d1..00000000
--- a/lib/SP/Controller/ItemActionController.php
+++ /dev/null
@@ -1,1213 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Account\Account;
-use SP\Account\AccountFavorites;
-use SP\Account\AccountHistory;
-use SP\Account\AccountHistoryUtil;
-use SP\Account\AccountUtil;
-use SP\Auth\AuthUtil;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Messages\LogMessage;
-use SP\Core\SessionFactory;
-use SP\DataModel\CustomFieldData;
-use SP\DataModel\NotificationData;
-use SP\DataModel\PluginData;
-use SP\DataModel\PublicLinkData;
-use SP\Forms\AccountForm;
-use SP\Forms\AuthTokenForm;
-use SP\Forms\CategoryForm;
-use SP\Forms\ClientForm;
-use SP\Forms\CustomFieldDefForm;
-use SP\Forms\NotificationForm;
-use SP\Forms\TagForm;
-use SP\Forms\UserForm;
-use SP\Forms\UserGroupForm;
-use SP\Forms\UserProfileForm;
-use SP\Http\Request;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Mgmt\ApiTokens\ApiToken;
-use SP\Mgmt\Categories\Category;
-use SP\Mgmt\Customers\Customer;
-use SP\Mgmt\CustomFields\CustomField;
-use SP\Mgmt\CustomFields\CustomFieldDef;
-use SP\Mgmt\CustomFields\CustomFieldsUtil;
-use SP\Mgmt\Files\File;
-use SP\Mgmt\Groups\Group;
-use SP\Mgmt\Notices\Notice;
-use SP\Mgmt\Plugins\Plugin;
-use SP\Mgmt\Profiles\Profile;
-use SP\Mgmt\PublicLinks\PublicLink;
-use SP\Mgmt\Tags\Tag;
-use SP\Mgmt\Users\User;
-use SP\Mgmt\Users\UserLdap;
-use SP\Mgmt\Users\UserLdapSync;
-use SP\Mgmt\Users\UserUtil;
-use SP\Util\Json;
-use SP\Util\Util;
-
-/**
- * Class AjaxSaveController
- *
- * @package SP\Controller
- */
-class ItemActionController implements ItemControllerInterface
-{
- use SP\Core\Dic\InjectableTrait;
- use RequestControllerTrait;
-
- /**
- * @var CustomFieldData
- */
- protected $CustomFieldData;
-
- /**
- * AjaxSaveController constructor.
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function __construct()
- {
- $this->injectDependencies();
- $this->init();
- }
-
- /**
- * Ejecutar la acción solicitada
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function doAction()
- {
- $this->LogMessage = new LogMessage();
-
- try {
- switch ($this->actionId) {
- case ActionsInterface::USER_CREATE:
- case ActionsInterface::USER_EDIT:
- case ActionsInterface::USER_EDIT_PASS:
- case ActionsInterface::USER_DELETE:
- $this->userAction();
- break;
- case ActionsInterface::GROUP_CREATE:
- case ActionsInterface::GROUP_EDIT:
- case ActionsInterface::GROUP_DELETE:
- $this->groupAction();
- break;
- case ActionsInterface::PROFILE_CREATE:
- case ActionsInterface::PROFILE_EDIT:
- case ActionsInterface::PROFILE_DELETE:
- $this->profileAction();
- break;
- case ActionsInterface::CLIENT_CREATE:
- case ActionsInterface::CLIENT_EDIT:
- case ActionsInterface::CLIENT_DELETE:
- $this->customerAction();
- break;
- case ActionsInterface::CATEGORY_CREATE:
- case ActionsInterface::CATEGORY_EDIT:
- case ActionsInterface::CATEGORY_DELETE:
- $this->categoryAction();
- break;
- case ActionsInterface::AUTHTOKEN_CREATE:
- case ActionsInterface::AUTHTOKEN_EDIT:
- case ActionsInterface::AUTHTOKEN_DELETE:
- $this->tokenAction();
- break;
- case ActionsInterface::CUSTOMFIELD_CREATE:
- case ActionsInterface::CUSTOMFIELD_EDIT:
- case ActionsInterface::CUSTOMFIELD_DELETE:
- $this->customFieldAction();
- break;
- case ActionsInterface::PUBLICLINK_CREATE:
- case ActionsInterface::PUBLICLINK_DELETE:
- case ActionsInterface::PUBLICLINK_REFRESH:
- $this->publicLinkAction();
- break;
- case ActionsInterface::TAG_CREATE:
- case ActionsInterface::TAG_EDIT:
- case ActionsInterface::TAG_DELETE:
- $this->tagAction();
- break;
- case ActionsInterface::FILE_DELETE:
- $this->fileAction();
- break;
- case ActionsInterface::PLUGIN_ENABLE:
- case ActionsInterface::PLUGIN_DISABLE:
- case ActionsInterface::PLUGIN_RESET:
- $this->pluginAction();
- break;
- case ActionsInterface::ACCOUNT_CREATE:
- case ActionsInterface::ACCOUNT_COPY:
- case ActionsInterface::ACCOUNT_EDIT:
- case ActionsInterface::ACCOUNT_EDIT_PASS:
- case ActionsInterface::ACCOUNT_EDIT_RESTORE:
- case ActionsInterface::ACCOUNT_DELETE:
- case ActionsInterface::ACCOUNTMGR_DELETE:
- $this->accountAction();
- break;
- case ActionsInterface::ACCOUNTMGR_DELETE_HISTORY:
- $this->accountHistoryAction();
- break;
- case ActionsInterface::ACCOUNT_FAVORITE_ADD:
- case ActionsInterface::ACCOUNT_FAVORITE_DELETE:
- $this->favoriteAction();
- break;
- case ActionsInterface::LDAP_SYNC:
- $this->ldapImportAction();
- break;
- case ActionsInterface::NOTIFICATION_CHECK:
- case ActionsInterface::NOTIFICATION_VIEW:
- case ActionsInterface::NOTIFICATION_CREATE:
- case ActionsInterface::NOTIFICATION_EDIT:
- case ActionsInterface::NOTIFICATION_DELETE:
- $this->noticeAction();
- break;
- case ActionsInterface::ACCOUNT_REQUEST:
- $this->requestAccountAction();
- break;
- default:
- $this->invalidAction();
- }
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- if ($this->LogMessage->getAction() !== null) {
- $Log = new Log($this->LogMessage);
- $Log->writeLog();
-
- $this->JsonResponse->setDescription($this->LogMessage->getHtmlDescription(true));
- }
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Acciones sobre usuarios
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- protected function userAction()
- {
- $Form = new UserForm($this->itemId);
- $Form->setIsLdap(Request::analyze('isLdap', 0));
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::USER);
-
- switch ($this->actionId) {
- case ActionsInterface::USER_CREATE:
- User::getItem($Form->getItemData())->add();
-
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Usuario', false));
- $this->LogMessage->addDescription(__('Usuario creado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- $this->LogMessage->addDetails(__('Login', false), $Form->getItemData()->getLogin());
-
- if ($Form->getItemData()->isChangePass()
- && !AuthUtil::mailPassRecover($Form->getItemData())
- ) {
- $this->LogMessage->addDescription(__('No se pudo realizar la petición de cambio de clave.', false));
- }
- break;
- case ActionsInterface::USER_EDIT:
- if ($Form->getIsLdap()) {
- UserLdap::getItem($Form->getItemData())->update();
- } else {
- User::getItem($Form->getItemData())->update();
- }
-
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Usuario', false));
- $this->LogMessage->addDescription(__('Usuario actualizado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- $this->LogMessage->addDetails(__('Login', false), $Form->getItemData()->getLogin());
- break;
- case ActionsInterface::USER_DELETE:
- if (is_array($this->itemId)) {
- $UsersData = User::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Usuarios eliminados', false));
- } else {
- $UsersData = [User::getItem()->getById($this->itemId)];
-
- User::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Usuario eliminado', false));
- }
-
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Usuario', false));
-
- foreach ($UsersData as $UserData) {
- $this->LogMessage->addDetails(__('Nombre', false), $UserData->getUserName());
- $this->LogMessage->addDetails(__('Login', false), $UserData->getUserLogin());
- }
- break;
- case ActionsInterface::USER_EDIT_PASS:
- $UserData = User::getItem()->getById($this->itemId);
-
- User::getItem($Form->getItemData())->updatePass();
-
- $this->LogMessage->setAction(__('Actualizar Clave Usuario', false));
- $this->LogMessage->addDescription(__('Clave actualizada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $UserData->getName());
- $this->LogMessage->addDetails(__('Login', false), $UserData->getLogin());
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Guardar los datos de los campos personalizados del módulo
- *
- * @param $moduleId
- */
- protected function setCustomFieldData($moduleId)
- {
- $this->CustomFieldData = new CustomFieldData();
- $this->CustomFieldData->setId($this->itemId);
- $this->CustomFieldData->setModule($moduleId);
- }
-
- /**
- * Guardar los datos de los campos personalizados del módulo
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function addCustomFieldData()
- {
- $customFields = Request::analyze('customfield');
-
- if (is_array($customFields)) {
- CustomFieldsUtil::addItemCustomFields($customFields, $this->CustomFieldData);
- }
- }
-
- /**
- * Actualizar los datos de los campos personalizados del módulo
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function updateCustomFieldData()
- {
- $customFields = Request::analyze('customfield');
-
- if (is_array($customFields)) {
- CustomFieldsUtil::updateItemCustomFields($customFields, $this->CustomFieldData);
- }
- }
-
- /**
- * Eliminar los datos de los campos personalizados del módulo
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- protected function deleteCustomFieldData()
- {
- if (is_array($this->itemId)) {
- CustomField::getItem($this->CustomFieldData)->deleteBatch($this->itemId);
- } else {
- CustomField::getItem($this->CustomFieldData)->delete($this->itemId);
- }
- }
-
- /**
- * Acciones sobre grupos
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function groupAction()
- {
- $Form = new UserGroupForm($this->itemId);
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::GROUP);
-
- switch ($this->actionId) {
- case ActionsInterface::GROUP_CREATE:
- Group::getItem($Form->getItemData())->add();
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Grupo', false));
- $this->LogMessage->addDescription(__('Grupo creado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::GROUP_EDIT:
- Group::getItem($Form->getItemData())->update();
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Grupo', false));
- $this->LogMessage->addDescription(__('Grupo actualizado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::GROUP_DELETE:
- if (is_array($this->itemId)) {
- $GroupsData = Group::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Grupos eliminados', false));
- } else {
- $GroupsData = [Group::getItem()->getById($this->itemId)];
-
- Group::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Grupo eliminado', false));
- }
-
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Grupo', false));
-
- foreach ($GroupsData as $GroupData) {
- $this->LogMessage->addDetails(__('Nombre', false), $GroupData->getUsergroupName());
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre perfiles
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- */
- protected function profileAction()
- {
- $Form = new UserProfileForm($this->itemId);
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::PROFILE);
-
- switch ($this->actionId) {
- case ActionsInterface::PROFILE_CREATE:
- Profile::getItem($Form->getItemData())->add();
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Perfil', false));
- $this->LogMessage->addDescription(__('Perfil creado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::PROFILE_EDIT:
- Profile::getItem($Form->getItemData())->update();
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Perfil', false));
- $this->LogMessage->addDescription(__('Perfil actualizado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::PROFILE_DELETE:
- if (is_array($this->itemId)) {
- $ProfilesData = Profile::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Perfiles eliminados', false));
- } else {
- $ProfilesData = [Profile::getItem()->getById($this->itemId)];
-
- Profile::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Perfil eliminado', false));
- }
-
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Perfil', false));
-
- foreach ($ProfilesData as $ProfileData) {
- $this->LogMessage->addDetails(__('Nombre', false), $ProfileData->getUserprofileName());
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre clientes
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function customerAction()
- {
- $Form = new ClientForm($this->itemId);
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::CLIENT);
-
- switch ($this->actionId) {
- case ActionsInterface::CLIENT_CREATE:
- Customer::getItem($Form->getItemData())->add();
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Cliente', false));
- $this->LogMessage->addDescription(__('Cliente creado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CLIENT_EDIT:
- Customer::getItem($Form->getItemData())->update();
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Cliente', false));
- $this->LogMessage->addDescription(__('Cliente actualizado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CLIENT_DELETE:
- if (is_array($this->itemId)) {
- $CustomersData = Customer::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Clientes eliminados', false));
- } else {
- $CustomersData = [Customer::getItem()->getById($this->itemId)];
-
- Customer::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Cliente eliminado', false));
- }
-
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Cliente', false));
-
- foreach ($CustomersData as $CustomerData) {
- $this->LogMessage->addDetails(__('Nombre', false), $CustomerData->getCustomerName());
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre categorías
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function categoryAction()
- {
- $Form = new CategoryForm($this->itemId);
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::CATEGORY);
-
- switch ($this->actionId) {
- case ActionsInterface::CATEGORY_CREATE:
- Category::getItem($Form->getItemData())->add();
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Categoría', false));
- $this->LogMessage->addDescription(__('Categoría creada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CATEGORY_EDIT:
- Category::getItem($Form->getItemData())->update();
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Categoría', false));
- $this->LogMessage->addDescription(__('Categoría actualizada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CATEGORY_DELETE:
-
- if (is_array($this->itemId)) {
- $CategoriesData = Category::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Categorías eliminadas', false));
- } else {
- $CategoriesData = [Category::getItem()->getById($this->itemId)];
-
- Category::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Categoría eliminada', false));
- }
-
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Categoría', false));
-
- foreach ($CategoriesData as $CategoryData) {
- $this->LogMessage->addDetails(__('Nombre', false), $CategoryData->getCategoryName());
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre tokens API
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function tokenAction()
- {
- $Form = new AuthTokenForm($this->itemId);
-
- $refresh = Request::analyze('refreshtoken', false, false, true);
-
- switch ($this->actionId) {
- case ActionsInterface::AUTHTOKEN_CREATE:
- $Form->validate($this->actionId);
-
- if ($refresh === true) {
- ApiToken::getItem($Form->getItemData())->refreshToken()->add();
- } else {
- ApiToken::getItem($Form->getItemData())->add();
- }
-
- $this->LogMessage->setAction(__('Crear Autorización', false));
- $this->LogMessage->addDescription(__('Autorización creada', false));
- $this->LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($Form->getItemData()->getAuthtokenUserId()));
- break;
- case ActionsInterface::AUTHTOKEN_EDIT:
- $Form->validate($this->actionId);
-
- if ($refresh === true) {
- ApiToken::getItem($Form->getItemData())->refreshToken()->update();
- } else {
- ApiToken::getItem($Form->getItemData())->update();
- }
-
- $this->LogMessage->setAction(__('Actualizar Autorización', false));
- $this->LogMessage->addDescription(__('Autorización actualizada', false));
- $this->LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($Form->getItemData()->getAuthtokenUserId()));
- break;
- case ActionsInterface::AUTHTOKEN_DELETE:
- if (is_array($this->itemId)) {
- ApiToken::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Autorizaciones eliminadas', false));
- } else {
- ApiToken::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Autorización eliminada', false));
- }
-
- $this->LogMessage->setAction(__('Eliminar Autorización', false));
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre campos personalizados
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- */
- protected function customFieldAction()
- {
- $Form = new CustomFieldDefForm($this->itemId);
- $Form->validate($this->actionId);
-
- switch ($this->actionId) {
- case ActionsInterface::CUSTOMFIELD_CREATE:
- CustomFieldDef::getItem($Form->getItemData())->add();
-
- $this->LogMessage->setAction(__('Crear Campo', false));
- $this->LogMessage->addDescription(__('Campo creado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CUSTOMFIELD_EDIT:
- CustomFieldDef::getItem($Form->getItemData())->update();
-
- $this->LogMessage->setAction(__('Actualizar Campo', false));
- $this->LogMessage->addDescription(__('Campo actualizado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::CUSTOMFIELD_DELETE:
- if (is_array($this->itemId)) {
- CustomFieldDef::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Campos eliminados', false));
- } else {
- CustomFieldDef::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Campo eliminado', false));
- }
-
- $this->LogMessage->setAction(__('Eliminar Campo', false));
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre enlaces públicos
- *
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \PHPMailer\PHPMailer\Exception
- */
- protected function publicLinkAction()
- {
- $PublicLinkData = new PublicLinkData();
- $PublicLinkData->setItemId($this->itemId);
- $PublicLinkData->setTypeId(PublicLink::TYPE_ACCOUNT);
- $PublicLinkData->setNotify(Request::analyze('notify', false, false, true));
-
- switch ($this->actionId) {
- case ActionsInterface::PUBLICLINK_CREATE:
- $PublicLinkData->setItemId($this->itemId);
- PublicLink::getItem($PublicLinkData)->add();
-
- $this->LogMessage->setAction(__('Crear Enlace', false));
- $this->LogMessage->addDescription(__('Enlace creado', false));
- $this->LogMessage->addDetails(__('Tipo', false), $PublicLinkData->getTypeId());
- $this->LogMessage->addDetails(__('Cuenta', false), AccountUtil::getAccountNameById($PublicLinkData->getItemId()));
- $this->LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($PublicLinkData->getUserId()));
- break;
- case ActionsInterface::PUBLICLINK_REFRESH:
- $PublicLinkData = PublicLink::getItem()->getById($this->itemId);
- PublicLink::getItem($PublicLinkData)->refresh();
-
- $this->LogMessage->setAction(__('Actualizar Enlace', false));
- $this->LogMessage->addDescription(__('Enlace actualizado', false));
- $this->LogMessage->addDetails(__('Tipo', false), $PublicLinkData->getTypeId());
- $this->LogMessage->addDetails(__('Cuenta', false), AccountUtil::getAccountNameById($PublicLinkData->getItemId()));
- $this->LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($PublicLinkData->getUserId()));
- break;
- case ActionsInterface::PUBLICLINK_DELETE:
- if (is_array($this->itemId)) {
- PublicLink::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Enlaces eliminados', false));
- } else {
- $PublicLinkData = PublicLink::getItem()->getById($this->itemId);
-
- PublicLink::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Enlace eliminado', false));
- $this->LogMessage->addDetails(__('Tipo', false), $PublicLinkData->getTypeId());
- $this->LogMessage->addDetails(__('Cuenta', false), AccountUtil::getAccountNameById($PublicLinkData->getItemId()));
- $this->LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($PublicLinkData->getUserId()));
- }
-
- $this->LogMessage->setAction(__('Eliminar Enlace', false));
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre etiquetas
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- protected function tagAction()
- {
- $Form = new TagForm($this->itemId);
- $Form->validate($this->actionId);
-
- switch ($this->actionId) {
- case ActionsInterface::TAG_CREATE:
- Tag::getItem($Form->getItemData())->add();
-
- $this->LogMessage->setAction(__('Crear Etiqueta', false));
- $this->LogMessage->addDescription(__('Etiqueta creada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::TAG_EDIT:
- Tag::getItem($Form->getItemData())->update();
-
- $this->LogMessage->setAction(__('Actualizar Etiqueta', false));
- $this->LogMessage->addDescription(__('Etiqueta actualizada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
- break;
- case ActionsInterface::TAG_DELETE:
- if (is_array($this->itemId)) {
- $TagsData = Tag::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Etiquetas eliminadas', false));
- } else {
- $TagsData = [Tag::getItem()->getById($this->itemId)];
-
- Tag::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Etiqueta eliminada', false));
- }
-
- $this->LogMessage->setAction(__('Eliminar Etiqueta', false));
-
- foreach ($TagsData as $TagData) {
- $this->LogMessage->addDetails(__('Nombre', false), $TagData->getTagName());
- }
- break;
- }
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre archivos
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- */
- protected function fileAction()
- {
- if (is_array($this->itemId)) {
- $FilesData = File::getItem()->deleteBatch($this->itemId);
-
- $this->LogMessage->addDescription(__('Archivos eliminados', false));
- } else {
- $FilesData = [File::getItem()->getById($this->itemId)];
-
- File::getItem()->delete($this->itemId);
-
- $this->LogMessage->addDescription(__('Archivo eliminado', false));
- }
-
- $this->LogMessage->setAction(__('Eliminar Archivo', false));
-
- foreach ($FilesData as $FileData) {
- $this->LogMessage->addDetails(__('Cuenta', false), $FileData->getAccountName());
- $this->LogMessage->addDetails(__('Cliente', false), $FileData->getCustomerName());
- $this->LogMessage->addDetails(__('Archivo', false), $FileData->getAccfileName());
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre plugins
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- */
- protected function pluginAction()
- {
- $PluginData = new PluginData();
- $PluginData->setId($this->itemId);
-
- switch ($this->actionId) {
- case ActionsInterface::PLUGIN_ENABLE:
- $PluginData->setEnabled(1);
- Plugin::getItem($PluginData)->toggleEnabled();
-
- $this->LogMessage->setAction(__('Actualizar Plugin', false));
- $this->LogMessage->addDescription(__('Plugin habilitado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $PluginData->getName());
- break;
- case ActionsInterface::PLUGIN_DISABLE:
- $PluginData->setEnabled(0);
- Plugin::getItem($PluginData)->toggleEnabled();
-
- $this->LogMessage->setAction(__('Actualizar Plugin', false));
- $this->LogMessage->addDescription(__('Plugin deshabilitado', false));
- $this->LogMessage->addDetails(__('Nombre', false), $PluginData->getName());
- break;
- case ActionsInterface::PLUGIN_RESET:
- Plugin::getItem()->reset($this->itemId);
-
- $this->LogMessage->setAction(__('Actualizar Plugin', false));
- $this->LogMessage->addDescription(__('Plugin restablecido', false));
- $this->LogMessage->addDetails(__('Nombre', false), $PluginData->getName());
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre cuentas
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws phpmailerException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function accountAction()
- {
- $Form = new AccountForm($this->itemId);
- $Form->validate($this->actionId);
-
- $this->setCustomFieldData(ActionsInterface::ACCOUNT);
-
- $Account = new Account($Form->getItemData());
-
- switch ($this->actionId) {
- case ActionsInterface::ACCOUNT_CREATE:
- case ActionsInterface::ACCOUNT_COPY:
- $Form->getItemData()->setUserId(SessionFactory::getUserData()->getId());
-
- $Account->createAccount();
-
- $this->CustomFieldData->setId($Account->getAccountData()->getId());
-
- $this->addCustomFieldData();
-
- $this->LogMessage->setAction(__('Crear Cuenta', false));
- $this->LogMessage->addDescription(__('Cuenta creada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
-
- $this->JsonResponse->setData(['itemId' => $Account->getAccountData()->getId(), 'nextActionId' => ActionsInterface::ACCOUNT_EDIT]);
- break;
- case ActionsInterface::ACCOUNT_EDIT:
- $Account->updateAccount();
- $this->updateCustomFieldData();
-
- $this->LogMessage->setAction(__('Actualizar Cuenta', false));
- $this->LogMessage->addDescription(__('Cuenta actualizada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $Form->getItemData()->getName());
-
- $this->JsonResponse->setData(['itemId' => $this->itemId, 'nextActionId' => ActionsInterface::ACCOUNT_VIEW]);
- break;
- case ActionsInterface::ACCOUNT_EDIT_PASS:
- $Account->updateAccountPass();
-
- $this->LogMessage->setAction(__('Actualizar Cuenta', false));
- $this->LogMessage->addDescription(__('Clave actualizada', false));
- $this->LogMessage->addDetails(__('Nombre', false), AccountUtil::getAccountNameById($this->itemId));
-
- $this->JsonResponse->setData(['itemId' => $this->itemId, 'nextActionId' => ActionsInterface::ACCOUNT_VIEW]);
- break;
- case ActionsInterface::ACCOUNT_EDIT_RESTORE:
- $Account->restoreFromHistory(Request::analyze('accountHistoryId', 0));
-
- $this->LogMessage->setAction(__('Restaurar Cuenta', false));
- $this->LogMessage->addDescription(__('Cuenta restaurada', false));
- $this->LogMessage->addDetails(__('Nombre', false), AccountUtil::getAccountNameById($this->itemId));
-
- $this->JsonResponse->setData(['itemId' => $this->itemId, 'nextActionId' => ActionsInterface::ACCOUNT_VIEW]);
- break;
- case ActionsInterface::ACCOUNT_DELETE:
- case ActionsInterface::ACCOUNTMGR_DELETE:
- if (is_array($this->itemId)) {
- $accounts = AccountUtil::getAccountNameByIdBatch($this->itemId);
- $numAccounts = count($accounts);
- } else {
- $accounts = AccountUtil::getAccountNameById($this->itemId);
- $numAccounts = 1;
- }
-
- $Account->deleteAccount($this->itemId);
- $this->deleteCustomFieldData();
-
- $this->LogMessage->setAction(__('Eliminar Cuenta', false));
-
- if ($numAccounts > 1) {
- $this->LogMessage->addDescription(__('Cuentas eliminadas', false));
-
- foreach ($accounts as $account) {
- $this->LogMessage->addDetails(__('Nombre', false), $account->account_name);
- }
- } elseif ($numAccounts === 1) {
- $this->LogMessage->addDescription(__('Cuenta eliminada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $accounts);
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acción para eliminar una cuenta del historial
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function accountHistoryAction()
- {
- $Account = new AccountHistory();
-
- switch ($this->actionId) {
- case ActionsInterface::ACCOUNTMGR_RESTORE:
- AccountHistoryUtil::restoreFromHistory($this->itemId, Request::analyze('accountId', 0));
-
- $this->LogMessage->setAction(__('Restaurar Cuenta', false));
- $this->LogMessage->addDescription(__('Cuenta restaurada', false));
- $this->LogMessage->addDetails(__('Nombre', false), AccountUtil::getAccountNameById($this->itemId));
-
- $this->JsonResponse->setData(['itemId' => $this->itemId, 'nextActionId' => ActionsInterface::ACCOUNT_VIEW]);
- break;
- case ActionsInterface::ACCOUNTMGR_DELETE_HISTORY:
- if (is_array($this->itemId)) {
- $accounts = AccountHistoryUtil::getAccountNameByIdBatch($this->itemId);
- $numAccounts = count($accounts);
- } else {
- $accounts = AccountHistoryUtil::getAccountNameById($this->itemId);
- $numAccounts = 1;
- }
-
- $Account->deleteAccount($this->itemId);
-
- $this->LogMessage->setAction(__('Eliminar Cuenta (H)', false));
-
- if ($numAccounts > 1) {
- $this->LogMessage->addDescription(__('Cuentas eliminadas', false));
-
- foreach ($accounts as $account) {
- $this->LogMessage->addDetails(__('Nombre', false), $account->acchistory_name);
- }
- } elseif ($numAccounts === 1) {
- $this->LogMessage->addDescription(__('Cuenta eliminada', false));
- $this->LogMessage->addDetails(__('Nombre', false), $accounts->acchistory_name);
- }
- break;
- }
-
- Email::sendEmail($this->LogMessage);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones sobre cuentas favoritas
- *
- * @throws \SP\Core\Exceptions\ValidationException
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function favoriteAction()
- {
- $userId = SessionFactory::getUserData()->getId();
-
- switch ($this->actionId) {
- case ActionsInterface::ACCOUNT_FAVORITE_ADD:
- AccountFavorites::addFavorite($this->itemId, $userId);
-
- $this->JsonResponse->setDescription(__('Favorito añadido'));
- break;
- case ActionsInterface::ACCOUNT_FAVORITE_DELETE:
- AccountFavorites::deleteFavorite($this->itemId, $userId);
-
- $this->JsonResponse->setDescription(__('Favorito eliminado'));
- break;
- }
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Importar usuarios de LDAP
- *
- * @throws phpmailerException
- */
- protected function ldapImportAction()
- {
- $this->LogMessage->setAction(__('Importar usuarios de LDAP', false));
-
- $options = [
- 'loginAttribute' => Request::analyze('ldap_loginattribute'),
- 'nameAttribute' => Request::analyze('ldap_nameattribute'),
- 'isADS' => Util::boolval(Request::analyze('ldap_ads'))
- ];
-
- if (UserLdapSync::run($options)) {
- $this->LogMessage->addDescription(__('Importación de usuarios de LDAP realizada', false));
- $this->LogMessage->addDetails(__('Usuarios importados', false), sprintf('%d/%d', UserLdapSync::$syncedObjects, UserLdapSync::$totalObjects));
- $this->LogMessage->addDetails(__('Errores', false), UserLdapSync::$errorObjects);
-
- $this->JsonResponse->setStatus(0);
- } else {
- $this->LogMessage->addDescription(__('Error al importar usuarios de LDAP', false));
- }
-
- $this->JsonResponse->addMessage(__('Revise el registro de eventos para más detalles', false));
- }
-
- /**
- * Acciones sobre notificaciones
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\ValidationException
- */
- protected function noticeAction()
- {
- switch ($this->actionId) {
- case ActionsInterface::NOTIFICATION_CHECK:
- Notice::getItem()->setChecked($this->itemId);
-
- $this->JsonResponse->setDescription(__('Notificación leída'));
- break;
- case ActionsInterface::NOTIFICATION_CREATE:
- $Form = new NotificationForm($this->itemId);
- $Form->validate($this->actionId);
-
- Notice::getItem($Form->getItemData())->add();
-
- $this->JsonResponse->setDescription(__('Notificación creada'));
- break;
- case ActionsInterface::NOTIFICATION_EDIT:
- $Form = new NotificationForm($this->itemId);
- $Form->validate($this->actionId);
-
- Notice::getItem($Form->getItemData())->update();
-
- $this->JsonResponse->setDescription(__('Notificación actualizada'));
- break;
- case ActionsInterface::NOTIFICATION_DELETE:
- if (is_array($this->itemId)) {
- Notice::getItem()->deleteBatch($this->itemId);
-
- $this->JsonResponse->setDescription(__('Notificaciones eliminadas'));
- } else {
- Notice::getItem()->delete($this->itemId);
-
- $this->JsonResponse->setDescription(__('Notificación eliminada'));
- }
- break;
- }
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Acciones para peticiones sobre cuentas
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function requestAccountAction()
- {
- $description = Request::analyze('description');
-
- if (!$description) {
- $this->JsonResponse->setDescription(__('Es necesaria una descripción', false));
- return;
- }
-
- $account = AccountUtil::getAccountRequestData($this->itemId);
-
- if ($account->account_userId === $account->account_userEditId) {
- $users = [$account->account_userId];
- } else {
- $users = [$account->account_userId, $account->account_userEditId];
- }
-
- $requestUsername = SessionFactory::getUserData()->getName();
- $requestLogin = SessionFactory::getUserData()->getLogin();
-
- $this->LogMessage->setAction(__('Solicitud de Modificación de Cuenta', false));
- $this->LogMessage->addDetails(__('Solicitante', false), sprintf('%s (%s)', $requestUsername, $requestLogin));
- $this->LogMessage->addDetails(__('Cuenta', false), $account->account_name);
- $this->LogMessage->addDetails(__('Cliente', false), $account->customer_name);
- $this->LogMessage->addDetails(__('Descripción', false), $description);
-
- // Enviar por correo si está disponible
- if ($this->ConfigData->isMailRequestsEnabled()) {
- $recipients = [];
-
- foreach ($users as $user) {
- $recipients[] = UserUtil::getUserEmail($user);
- }
-
- $mailto = implode(',', $recipients);
-
- if (strlen($mailto) > 1
- && Email::sendEmail($this->LogMessage, $mailto)
- ) {
- $this->LogMessage->addDescription(__('Solicitud enviada por correo', false));
- } else {
- $this->LogMessage->addDescription(__('Solicitud no enviada por correo', false));
- }
- }
-
- // Crear notificaciones
- foreach ($users as $user) {
- $NoticeData = new NotificationData();
- $NoticeData->setUserId($user);
- $NoticeData->setComponent('Accounts');
- $NoticeData->setType(__('Solicitud'));
- $NoticeData->setDescription($this->LogMessage);
-
- Notice::getItem($NoticeData)->add();
- }
-
- $this->LogMessage->addDescription(__('Solicitud realizada', false));
- $this->JsonResponse->setStatus(0);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemControllerInterface.php b/lib/SP/Controller/ItemControllerInterface.php
deleted file mode 100644
index b2dda4e0..00000000
--- a/lib/SP/Controller/ItemControllerInterface.php
+++ /dev/null
@@ -1,38 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-/**
- * Interface ItemControllerInterface
- *
- * @package SP\Controller
- */
-interface ItemControllerInterface
-{
- /**
- * Realizar la acción solicitada en la la petición HTTP
- */
- public function doAction();
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemListController.php b/lib/SP/Controller/ItemListController.php
deleted file mode 100644
index 806d80cb..00000000
--- a/lib/SP/Controller/ItemListController.php
+++ /dev/null
@@ -1,407 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\AccountHistoryUtil;
-use SP\Account\AccountUtil;
-use SP\Controller\Grids\Items;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\ItemSearchData;
-use SP\Http\Request;
-use SP\Mgmt\ApiTokens\ApiTokenSearch;
-use SP\Mgmt\Categories\CategorySearch;
-use SP\Mgmt\Customers\CustomerSearch;
-use SP\Mgmt\CustomFields\CustomFieldDefSearch;
-use SP\Mgmt\Files\FileSearch;
-use SP\Mgmt\Files\FileUtil;
-use SP\Mgmt\Groups\GroupSearch;
-use SP\Mgmt\Plugins\PluginSearch;
-use SP\Mgmt\Profiles\ProfileSearch;
-use SP\Mgmt\PublicLinks\PublicLinkSearch;
-use SP\Mgmt\Tags\TagSearch;
-use SP\Mgmt\Users\UserSearch;
-use SP\Mvc\View\Template;
-
-/**
- * Clase encargada de de preparar la presentación de las vistas de gestión de accesos
- *
- * @package Controller
- */
-class ItemListController extends GridTabControllerBase implements ActionsInterface
-{
- const TYPE_ACCESSES = 1;
- const TYPE_ACCOUNTS = 2;
-
- /**
- * @var ItemSearchData
- */
- private $ItemSearchData;
-
- /**
- * Constructor
- *
- * @param $template \SP\Mvc\View\Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $ItemSearchData = new ItemSearchData();
- $ItemSearchData->setLimitCount($this->configData->getAccountCount());
- $this->ItemSearchData = $ItemSearchData;
- }
-
- /**
- * Obtener los datos para la vista de archivos de una cuenta
- */
- public function getAccountFiles()
- {
- $this->setAction(self::ACCOUNT_FILE);
-
- $this->view->addTemplate('files-list', 'account');
-
- $this->view->assign('accountId', Request::analyze('id', 0));
- $this->view->assign('deleteEnabled', Request::analyze('del', 0));
- $this->view->assign('files', FileUtil::getAccountFiles($this->view->accountId));
-
- if (!is_array($this->view->templates) || count($this->view->templates) === 0) {
- return;
- }
- }
-
- /**
- * Realizar las accione del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- try {
- $this->useTabs();
-
- if ($type === self::TYPE_ACCOUNTS) {
- $this->getCategories();
- $this->getCustomers();
- $this->getCustomFields();
- $this->getFiles();
- $this->getAccounts();
- $this->getAccountsHistory();
- $this->getTags();
- $this->getPluginsList();
-
- $this->eventDispatcher->notifyEvent('show.itemlist.accounts', $this);
- } elseif ($type === self::TYPE_ACCESSES) {
- $this->getUsersList();
- $this->getGroupsList();
- $this->getProfilesList();
- $this->getAPITokensList();
- $this->getPublicLinksList();
-
- $this->eventDispatcher->notifyEvent('show.itemlist.accesses', $this);
- }
- } catch (SPException $e) {
- $this->showError(self::ERR_EXCEPTION);
- }
- }
-
- /**
- * Obtener los datos para la pestaña de categorías
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getCategories()
- {
- $this->setAction(self::CATEGORY);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getCategoriesGrid();
- $Grid->getData()->setData(CategorySearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * @return Items
- */
- public function getGrids()
- {
- return $this->Grids;
- }
-
- /**
- * Obtener los datos para la pestaña de clientes
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getCustomers()
- {
- $this->setAction(self::CLIENT);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getCustomersGrid();
- $Grid->getData()->setData(CustomerSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de campos personalizados
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getCustomFields()
- {
- $this->setAction(self::CUSTOMFIELD);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getCustomFieldsGrid();
- $Grid->getData()->setData(CustomFieldDefSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de archivos
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getFiles()
- {
- if (!$this->configData->isFilesEnabled()) {
- return;
- }
-
- $this->setAction(self::FILE);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getFilesGrid();
- $Grid->getData()->setData(FileSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de cuentas
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getAccounts()
- {
- $this->setAction(self::ACCOUNTMGR);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getAccountsGrid();
- $Grid->getData()->setData(AccountUtil::getAccountsMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de cuentas en el histórico
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getAccountsHistory()
- {
- $this->setAction(self::ACCOUNTMGR_HISTORY);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getAccountsHistoryGrid();
- $Grid->getData()->setData(AccountHistoryUtil::getAccountsMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de etiquetas
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getTags()
- {
- $this->setAction(self::TAG);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getTagsGrid();
- $Grid->getData()->setData(TagSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de tokens de API
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getPluginsList()
- {
- $this->setAction(self::PLUGIN);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getPluginsGrid();
- $Grid->getData()->setData(PluginSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de usuarios
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getUsersList()
- {
- $this->setAction(self::USER);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getUsersGrid();
- $Grid->getData()->setData(UserSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de grupos
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getGroupsList()
- {
- $this->setAction(self::GROUP);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getGroupsGrid();
- $Grid->getData()->setData(GroupSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de perfiles
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getProfilesList()
- {
- $this->setAction(self::PROFILE);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getProfilesGrid();
- $Grid->getData()->setData(ProfileSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de tokens de API
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getAPITokensList()
- {
- $this->setAction(self::AUTHTOKEN);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getTokensGrid();
- $Grid->getData()->setData(ApiTokenSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * Obtener los datos para la pestaña de tokens de API
- *
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getPublicLinksList()
- {
- if (!$this->configData->isPublinksEnabled()) {
- return;
- }
-
- $this->setAction(self::PUBLICLINK);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getPublicLinksGrid();
- $Grid->getData()->setData(PublicLinkSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemSearchController.php b/lib/SP/Controller/ItemSearchController.php
deleted file mode 100644
index 5367054e..00000000
--- a/lib/SP/Controller/ItemSearchController.php
+++ /dev/null
@@ -1,515 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\AccountHistoryUtil;
-use SP\Account\AccountUtil;
-use SP\Controller\Grids\Items;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\SessionUtil;
-use SP\DataModel\ItemSearchData;
-use SP\Http\Request;
-use SP\Mgmt\ApiTokens\ApiTokenSearch;
-use SP\Mgmt\Categories\CategorySearch;
-use SP\Mgmt\Customers\CustomerSearch;
-use SP\Mgmt\CustomFields\CustomFieldDefSearch;
-use SP\Mgmt\Files\FileSearch;
-use SP\Mgmt\Groups\GroupSearch;
-use SP\Mgmt\Plugins\PluginSearch;
-use SP\Mgmt\Profiles\ProfileSearch;
-use SP\Mgmt\PublicLinks\PublicLinkSearch;
-use SP\Mgmt\Tags\TagSearch;
-use SP\Mgmt\Users\UserSearch;
-use SP\Mvc\View\Template;
-use SP\Util\Json;
-
-/**
- * Class AccItemsMgmtSearch para la gestión de búsquedas de items de accesos
- *
- * @package SP\Controller
- */
-class ItemSearchController extends GridItemsSearchController implements ActionsInterface, ItemControllerInterface
-{
- use RequestControllerTrait;
-
- /**
- * @var ItemSearchData
- */
- protected $ItemSearchData;
-
- /**
- * Constructor
- *
- * @param $template Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->grids = new Items();
- $this->grids->setQueryTimeStart(microtime());
- $this->ItemSearchData = new ItemSearchData();
-
- $this->init();
- $this->setItemSearchData();
- }
-
- /**
- * Establecer las propiedades de búsqueda
- */
- protected function setItemSearchData()
- {
- $this->ItemSearchData->setSeachString(Request::analyze('search'));
- $this->ItemSearchData->setLimitStart(Request::analyze('start', 0));
- $this->ItemSearchData->setLimitCount(Request::analyze('count', $this->configData->getAccountCount()));
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- $this->view->assign('isDemo', $this->configData->isDemoEnabled());
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->view->assign('index', $this->activeTab);
-
- try {
- switch ($this->actionId) {
- case ActionsInterface::USER_SEARCH:
- $this->getUsers();
- break;
- case ActionsInterface::GROUP_SEARCH:
- $this->getGroups();
- break;
- case ActionsInterface::PROFILE_SEARCH:
- $this->getProfiles();
- break;
- case ActionsInterface::AUTHTOKEN_SEARCH:
- $this->getTokens();
- break;
- case ActionsInterface::PUBLICLINK_SEARCH:
- $this->getPublicLinks();
- break;
- case ActionsInterface::CATEGORY_SEARCH:
- $this->getCategories();
- break;
- case ActionsInterface::CLIENT_SEARCH:
- $this->getCustomers();
- break;
- case ActionsInterface::CUSTOMFIELD_SEARCH:
- $this->getCustomFields();
- break;
- case ActionsInterface::FILE_SEARCH:
- $this->getFiles();
- break;
- case ActionsInterface::ACCOUNTMGR_SEARCH:
- $this->getAccounts();
- break;
- case ActionsInterface::ACCOUNTMGR_SEARCH_HISTORY:
- $this->getAccountsHistory();
- break;
- case ActionsInterface::TAG_SEARCH:
- $this->getTags();
- break;
- case ActionsInterface::PLUGIN_SEARCH:
- $this->getPlugins();
- break;
- default:
- $this->invalidAction();
- }
-
- $this->JsonResponse->setCsrf($this->view->sk);
- $this->JsonResponse->setData(['html' => $this->render()]);
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Obtener los usuarios de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getUsers()
- {
- $this->setAction(self::USER_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getUsersGrid();
- $Grid->getData()->setData(UserSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ACCESS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * @return Items
- */
- public function getGrids()
- {
- return $this->grids;
- }
-
- /**
- * Obtener los grupos de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getGroups()
- {
- $this->setAction(self::GROUP_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getGroupsGrid();
- $Grid->getData()->setData(GroupSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ACCESS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los perfiles de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getProfiles()
- {
- $this->setAction(self::PROFILE_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getProfilesGrid();
- $Grid->getData()->setData(ProfileSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ACCESS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los tokens API de una búsqueda
- *
- * @throws \InvalidArgumentException
- * @throws \SP\Core\Exceptions\InvalidArgumentException
- */
- public function getTokens()
- {
- $this->setAction(self::AUTHTOKEN_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getTokensGrid();
- $Grid->getData()->setData(ApiTokenSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ACCESS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los enlaces públicos de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getPublicLinks()
- {
- $this->setAction(self::PUBLICLINK_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getPublicLinksGrid();
- $Grid->getData()->setData(PublicLinkSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ACCESS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener las categorías de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getCategories()
- {
- $this->setAction(self::CATEGORY_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getCategoriesGrid();
- $Grid->getData()->setData(CategorySearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los clientes de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getCustomers()
- {
- $this->setAction(self::CLIENT_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getCustomersGrid();
- $Grid->getData()->setData(CustomerSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los campos personalizados de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getCustomFields()
- {
- $this->setAction(self::CUSTOMFIELD_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getCustomFieldsGrid();
- $Grid->getData()->setData(CustomFieldDefSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los archivos de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getFiles()
- {
- $this->setAction(self::FILE_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getFilesGrid();
- $Grid->getData()->setData(FileSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener las cuentas de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getAccounts()
- {
- $this->setAction(self::ACCOUNTMGR_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getAccountsGrid();
- $Grid->getData()->setData(AccountUtil::getAccountsMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener las cuentas de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getAccountsHistory()
- {
- $this->setAction(self::ACCOUNTMGR_SEARCH_HISTORY);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getAccountsHistoryGrid();
- $Grid->getData()->setData(AccountHistoryUtil::getAccountsMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener las etiquetas de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getTags()
- {
- $this->setAction(self::TAG_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getTagsGrid();
- $Grid->getData()->setData(TagSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los plugins de una búsqueda
- *
- * @throws \InvalidArgumentException
- */
- public function getPlugins()
- {
- $this->setAction(self::PLUGIN_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getPluginsGrid();
- $Grid->getData()->setData(PluginSearch::getItem()->getMgmtSearch($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::ITEMS_MANAGE);
-
- $this->JsonResponse->setStatus(0);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemShowController.php b/lib/SP/Controller/ItemShowController.php
deleted file mode 100644
index 5db90d2d..00000000
--- a/lib/SP/Controller/ItemShowController.php
+++ /dev/null
@@ -1,611 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\Account;
-use SP\Account\AccountAcl;
-use SP\Account\AccountHistory;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Crypt\Crypt;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Exceptions\ItemException;
-use SP\Core\Plugin\PluginUtil;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\DataModel\AccountExtData;
-use SP\DataModel\AuthTokenData;
-use SP\DataModel\CategoryData;
-use SP\DataModel\ClientData;
-use SP\DataModel\CustomFieldData;
-use SP\DataModel\CustomFieldDefinitionData;
-use SP\DataModel\ProfileData;
-use SP\DataModel\TagData;
-use SP\DataModel\UserData;
-use SP\DataModel\UserGroupData;
-use SP\Http\Request;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Mgmt\ApiTokens\ApiToken;
-use SP\Mgmt\ApiTokens\ApiTokensUtil;
-use SP\Mgmt\Categories\Category;
-use SP\Mgmt\Customers\Customer;
-use SP\Mgmt\CustomFields\CustomField;
-use SP\Mgmt\CustomFields\CustomFieldDef;
-use SP\Mgmt\CustomFields\CustomFieldTypes;
-use SP\Mgmt\Files\FileUtil;
-use SP\Mgmt\Groups\Group;
-use SP\Mgmt\Groups\GroupUsers;
-use SP\Mgmt\Plugins\Plugin;
-use SP\Mgmt\Profiles\Profile;
-use SP\Mgmt\Profiles\ProfileUtil;
-use SP\Mgmt\PublicLinks\PublicLink;
-use SP\Mgmt\Tags\Tag;
-use SP\Mgmt\Users\User;
-use SP\Mgmt\Users\UserPass;
-use SP\Mgmt\Users\UserUtil;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-use SP\Util\ImageUtil;
-use SP\Util\Json;
-
-/**
- * Class AccItemMgmt
- *
- * @package SP\Controller
- */
-class ItemShowController extends ControllerBase implements ActionsInterface, ItemControllerInterface
-{
- use RequestControllerTrait;
-
- /**
- * Máximo numero de acciones antes de agrupar
- */
- const MAX_NUM_ACTIONS = 3;
- /**
- * @var int
- */
- private $module = 0;
-
- /**
- * Constructor
- *
- * @param $template Template con instancia de plantilla
- * @throws \SP\Core\Exceptions\SPException
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->init();
-
- $this->view->assign('isDemo', $this->configData->isDemoEnabled());
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->view->assign('itemId', $this->itemId);
- $this->view->assign('activeTab', $this->activeTab);
- $this->view->assign('actionId', $this->actionId);
- $this->view->assign('isView', false);
- $this->view->assign('showViewCustomPass', true);
- $this->view->assign('readonly', '');
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- *
- * @param mixed $type Tipo de acción
- * @throws \SP\Core\Exceptions\SPException
- */
- public function doAction($type = null)
- {
- try {
- switch ($this->actionId) {
- case self::USER_VIEW:
- $this->view->assign('header', __('Ver Usuario'));
- $this->view->assign('isView', true);
- $this->getUser();
- break;
- case self::USER_EDIT:
- $this->view->assign('header', __('Editar Usuario'));
- $this->getUser();
- break;
- case self::USER_EDIT_PASS:
- $this->view->assign('header', __('Cambio de Clave'));
- $this->getUserPass();
- break;
- case self::USER_CREATE:
- $this->view->assign('header', __('Nuevo Usuario'));
- $this->getUser();
- break;
- case self::GROUP_VIEW:
- $this->view->assign('header', __('Ver Grupo'));
- $this->view->assign('isView', true);
- $this->getGroup();
- break;
- case self::GROUP_EDIT:
- $this->view->assign('header', __('Editar Grupo'));
- $this->getGroup();
- break;
- case self::GROUP_CREATE:
- $this->view->assign('header', __('Nuevo Grupo'));
- $this->getGroup();
- break;
- case self::PROFILE_VIEW:
- $this->view->assign('header', __('Ver Perfil'));
- $this->view->assign('isView', true);
- $this->getProfile();
- break;
- case self::PROFILE_EDIT:
- $this->view->assign('header', __('Editar Perfil'));
- $this->getProfile();
- break;
- case self::PROFILE_CREATE:
- $this->view->assign('header', __('Nuevo Perfil'));
- $this->getProfile();
- break;
- case self::CLIENT_VIEW:
- $this->view->assign('header', __('Ver Cliente'));
- $this->view->assign('isView', true);
- $this->getCustomer();
- break;
- case self::CLIENT_EDIT:
- $this->view->assign('header', __('Editar Cliente'));
- $this->getCustomer();
- break;
- case self::CLIENT_CREATE:
- $this->view->assign('header', __('Nuevo Cliente'));
- $this->getCustomer();
- break;
- case self::CATEGORY_VIEW:
- $this->view->assign('header', __('Ver Categoría'));
- $this->view->assign('isView', true);
- $this->getCategory();
- break;
- case self::CATEGORY_EDIT:
- $this->view->assign('header', __('Editar Categoría'));
- $this->getCategory();
- break;
- case self::CATEGORY_CREATE:
- $this->view->assign('header', __('Nueva Categoría'));
- $this->getCategory();
- break;
- case self::AUTHTOKEN_VIEW:
- $this->view->assign('header', __('Ver Autorización'));
- $this->view->assign('isView', true);
- $this->getToken();
- break;
- case self::AUTHTOKEN_CREATE:
- $this->view->assign('header', __('Nueva Autorización'));
- $this->getToken();
- break;
- case self::AUTHTOKEN_EDIT:
- $this->view->assign('header', __('Editar Autorización'));
- $this->getToken();
- break;
- case self::CUSTOMFIELD_CREATE:
- $this->view->assign('header', __('Nuevo Campo'));
- $this->getCustomField();
- break;
- case self::CUSTOMFIELD_EDIT:
- $this->view->assign('header', __('Editar Campo'));
- $this->getCustomField();
- break;
- case self::PUBLICLINK_VIEW:
- $this->view->assign('header', __('Ver Enlace Público'));
- $this->view->assign('isView', true);
- $this->getPublicLink();
- break;
- case self::TAG_CREATE:
- $this->view->assign('header', __('Nueva Etiqueta'));
- $this->getTag();
- break;
- case self::TAG_EDIT:
- $this->view->assign('header', __('Editar Etiqueta'));
- $this->getTag();
- break;
- case self::ACCOUNT_VIEW_PASS:
- $this->view->assign('header', __('Clave de Cuenta'));
- $this->getAccountPass();
- break;
- case self::PLUGIN_VIEW:
- $this->view->assign('header', __('Detalles de Plugin'));
- $this->view->assign('isView', true);
- $this->getPlugin();
- break;
- default:
- $this->invalidAction();
- }
-
- if (count($this->JsonResponse->getData()) === 0) {
- $this->JsonResponse->setData(['html' => $this->render()]);
- }
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- $this->JsonResponse->setCsrf($this->view->sk);
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Obtener los datos para la ficha de usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getUser()
- {
- $this->module = self::USER;
- $this->view->addTemplate('users');
-
- $this->view->assign('user', $this->itemId ? User::getItem()->getById($this->itemId) : new UserData());
- $this->view->assign('isDisabled', $this->view->actionId === self::USER_VIEW ? 'disabled' : '');
- $this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : '');
- $this->view->assign('isUseSSO', $this->configData->isAuthBasicAutoLoginEnabled());
- $this->view->assign('groups', Group::getItem()->getItemsForSelect());
- $this->view->assign('profiles', Profile::getItem()->getItemsForSelect());
-
- $this->getCustomFieldsForItem();
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener la lista de campos personalizados y sus valores
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- protected function getCustomFieldsForItem()
- {
- $this->view->assign('customFields', CustomField::getItem(new CustomFieldData($this->module))->getById($this->itemId));
- }
-
- /**
- * Inicializar la vista de cambio de clave de usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function getUserPass()
- {
- $this->module = self::USER;
- $this->setAction(self::USER_EDIT_PASS);
-
- // Comprobar si el usuario a modificar es distinto al de la sesión
- if ($this->itemId !== SessionFactory::getUserData()->getId() && !$this->checkAccess()) {
- return;
- }
-
- $this->view->assign('user', User::getItem()->getById($this->itemId));
- $this->view->addTemplate('userspass');
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de grupo
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getGroup()
- {
- $this->module = self::GROUP;
- $this->view->addTemplate('groups');
-
- $this->view->assign('group', $this->itemId ? Group::getItem()->getById($this->itemId) : new UserGroupData());
- $this->view->assign('users', User::getItem()->getItemsForSelect());
- $this->view->assign('groupUsers', GroupUsers::getItem()->getById($this->itemId));
-
- $this->getCustomFieldsForItem();
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de perfil
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getProfile()
- {
- $this->module = self::PROFILE;
- $this->view->addTemplate('profiles');
-
- $Profile = $this->itemId ? Profile::getItem()->getById($this->itemId) : new ProfileData();
-
- $this->view->assign('profile', $Profile);
- $this->view->assign('isDisabled', ($this->view->actionId === self::PROFILE_VIEW) ? 'disabled' : '');
- $this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : '');
-
- if ($this->view->isView === true) {
- $this->view->assign('usedBy', ProfileUtil::getProfileInUsersName($this->itemId));
- }
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de cliente
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getCustomer()
- {
- $this->module = self::CLIENT;
- $this->view->addTemplate('customers');
-
- $this->view->assign('customer', $this->itemId ? Customer::getItem()->getById($this->itemId) : new ClientData());
- $this->getCustomFieldsForItem();
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de categoría
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getCategory()
- {
- $this->module = self::CATEGORY;
- $this->view->addTemplate('categories');
-
- $this->view->assign('category', $this->itemId ? Category::getItem()->getById($this->itemId) : new CategoryData());
- $this->getCustomFieldsForItem();
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de tokens de API
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \phpmailer\phpmailerException
- */
- protected function getToken()
- {
- $this->module = self::AUTHTOKEN;
- $this->view->addTemplate('tokens');
-
- $ApiTokenData = $this->itemId ? ApiToken::getItem()->getById($this->itemId) : new AuthTokenData();
-
- $this->view->assign('users', User::getItem()->getItemsForSelect());
- $this->view->assign('actions', ApiTokensUtil::getTokenActions());
- $this->view->assign('authTokenData', $ApiTokenData);
- $this->view->assign('isDisabled', ($this->view->actionId === self::AUTHTOKEN_VIEW) ? 'disabled' : '');
- $this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : '');
-
- if ($this->view->isView === true) {
- $Log = Log::newLog(__('Autorizaciones', false));
- $LogMessage = $Log->getLogMessage();
- $LogMessage->addDescription(__('Token de autorización visualizado'));
- $LogMessage->addDetails(__('Usuario'), UserUtil::getUserLoginById($ApiTokenData->authtoken_userId));
- $Log->writeLog();
-
- Email::sendEmail($LogMessage);
- }
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de campo personalizado
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function getCustomField()
- {
- $this->module = self::CUSTOMFIELD;
- $this->view->addTemplate('customfields');
-
- $customField = $this->itemId ? CustomFieldDef::getItem()->getById($this->itemId) : new CustomFieldDefinitionData();
-
- $this->view->assign('field', $customField);
- $this->view->assign('types', CustomFieldTypes::getFieldsTypes());
- $this->view->assign('modules', CustomFieldTypes::getFieldsModules());
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de enlace público
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getPublicLink()
- {
- $this->module = self::PUBLICLINK;
- $this->view->addTemplate('publiclinks');
-
- $PublicLink = PublicLink::getItem();
-
- $this->view->assign('link', $PublicLink->getItemForList($PublicLink->getById($this->itemId)));
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la ficha de categoría
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getTag()
- {
- $this->module = self::TAG;
- $this->view->addTemplate('tags');
-
- $this->view->assign('tag', $this->itemId ? Tag::getItem()->getById($this->itemId) : new TagData());
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Mostrar la clave de una cuenta
- *
- * @throws ItemException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- */
- public function getAccountPass()
- {
- $this->setAction(self::ACCOUNT_VIEW_PASS);
-
- $isHistory = Request::analyze('isHistory', false);
- $isFull = Request::analyze('isFull', false);
-
- $AccountData = new AccountExtData();
-
- if (!$isHistory) {
- $AccountData->setId($this->itemId);
- $Account = new Account($AccountData);
- } else {
- $Account = new AccountHistory($AccountData);
- $Account->setId($this->itemId);
- }
-
- $Account->getAccountPassData();
-
- if ($isHistory && !$Account->checkAccountMPass()) {
- throw new ItemException(__('La clave maestra no coincide', false));
- }
-
- $AccountAcl = new AccountAcl(ActionsInterface::ACCOUNT_VIEW_PASS);
- $Acl = $AccountAcl->getAcl();
-
- if (!$Acl->isShowViewPass()) {
- throw new ItemException(__('No tiene permisos para acceder a esta cuenta', false));
- }
-
- if (!UserPass::checkUserUpdateMPass(SessionFactory::getUserData()->getId())) {
- throw new ItemException(__('Clave maestra actualizada') . '
' . __('Reinicie la sesión para cambiarla'));
- }
-
- $key = CryptSession::getSessionKey();
- $securedKey = Crypt::unlockSecuredKey($AccountData->getKey(), $key);
- $accountClearPass = Crypt::decrypt($AccountData->getPass(), $securedKey, $key);
-
- if (!$isHistory) {
- $Account->incrementDecryptCounter();
-
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Ver Clave', false));
- $LogMessage->addDetails(__('ID', false), $this->itemId);
- $LogMessage->addDetails(__('Cuenta', false), $AccountData->getClientName() . ' / ' . $AccountData->getName());
- $Log->writeLog();
- }
-
- $useImage = $this->configData->isAccountPassToImage();
-
- if (!$useImage) {
- $pass = $isFull ? htmlentities(trim($accountClearPass)) : trim($accountClearPass);
- } else {
- $pass = ImageUtil::convertText($accountClearPass);
- }
-
- $this->JsonResponse->setStatus(0);
-
- if ($isFull) {
- $this->view->addTemplate('viewpass', 'account');
-
- $this->view->assign('login', $AccountData->getLogin());
- $this->view->assign('pass', $pass);
- $this->view->assign('isImage', $useImage);
- $this->view->assign('isLinked', Request::analyze('isLinked', 0));
-
- return;
- }
-
- $data = [
- 'acclogin' => $AccountData->getLogin(),
- 'accpass' => $pass,
- 'useimage' => $useImage
- ];
-
- $this->JsonResponse->setData($data);
- }
-
- /**
- * Obtener los datos para la vista de plugins
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getPlugin()
- {
- $this->module = self::PLUGIN;
- $this->view->addTemplate('plugins');
-
- $Plugin = Plugin::getItem()->getById($this->itemId);
-
- $this->view->assign('isReadonly', $this->view->isView ? 'readonly' : '');
- $this->view->assign('plugin', $Plugin);
- $this->view->assign('pluginInfo', PluginUtil::getPluginInfo($Plugin->getName()));
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * Obtener los datos para la vista de archivos de una cuenta
- *
- * @throws \SP\Core\Exceptions\FileNotFoundException
- */
- protected function getAccountFiles()
- {
- $this->setAction(self::ACCOUNT_FILE);
-
- $this->view->assign('accountId', Request::analyze('id', 0));
- $this->view->assign('deleteEnabled', Request::analyze('del', 0));
- $this->view->assign('files', FileUtil::getAccountFiles($this->view->accountId));
-
- if (!is_array($this->view->templates) || count($this->view->templates) === 0) {
- return;
- }
-
- $this->view->addTemplate('files');
-
- $this->JsonResponse->setStatus(0);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/ItemsController.php b/lib/SP/Controller/ItemsController.php
deleted file mode 100644
index 55de3e5e..00000000
--- a/lib/SP/Controller/ItemsController.php
+++ /dev/null
@@ -1,167 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Account\AccountUtil;
-use SP\Core\ItemsTypeInterface;
-use SP\Core\SessionUtil;
-use SP\DataModel\DataModelInterface;
-use SP\Http\Request;
-use SP\Mgmt\Categories\Category;
-use SP\Mgmt\Customers\Customer;
-use SP\Util\Json;
-
-/**
- * Class ItemsController
- *
- * @package SP\Controller
- */
-class ItemsController implements ItemControllerInterface
-{
- use RequestControllerTrait;
-
- /**
- * ItemsController constructor.
- */
- public function __construct()
- {
- $this->init();
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- */
- public function doAction()
- {
- $itemType = Request::analyze('itemType', false);
-
- $this->JsonResponse->setStatus(0);
- $this->JsonResponse->setData($this->getItems($itemType));
- $this->JsonResponse->setCsrf(SessionUtil::getSessionKey());
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Devuelve los elementos solicitados
- *
- * @param $itemType int El tipo de elemento a devolver
- * @return array
- */
- protected function getItems($itemType)
- {
- switch ($itemType) {
- case ItemsTypeInterface::ITEM_CATEGORIES:
- return $this->getCategories();
- case ItemsTypeInterface::ITEM_CUSTOMERS:
- return $this->getCustomers();
- case ItemsTypeInterface::ITEM_CUSTOMERS_USER:
- return $this->getCustomersForUser();
- case ItemsTypeInterface::ITEM_ACCOUNTS_USER:
- return $this->getAccountsForUser();
- default:
- return [];
- }
- }
-
- /**
- * Devuelve las categorías disponibles
- *
- * @return array
- */
- protected function getCategories()
- {
- return $this->prepareItems(Category::getItem()->getAll());
- }
-
- /**
- * Preparar los elementos para devolverlos
- *
- * @param array $items
- * @return array
- */
- protected function prepareItems(array $items)
- {
- $outItems = [];
-
- /** @var DataModelInterface $item */
- foreach ($items as $item) {
- $obj = new \stdClass();
- $obj->id = $item->getId();
- $obj->name = $item->getName();
-
- $outItems[] = $obj;
- }
-
- return $outItems;
- }
-
- /**
- * Devuelve los clientes disponibles
- *
- * @return array
- */
- protected function getCustomers()
- {
- return $this->prepareItems(Customer::getItem()->getAll());
- }
-
- /**
- * Devolver los clientes visibles por el usuario
- *
- * @return array
- */
- protected function getCustomersForUser()
- {
- return Customer::getItem()->getItemsForSelectByUser();
- }
-
- /**
- * Devolver las cuentas visubles por el usuario
- *
- * @return array
- */
- protected function getAccountsForUser()
- {
- $outItems = [];
-
- foreach (AccountUtil::getAccountsForUser($this->itemId) as $account) {
- $obj = new \stdClass();
- $obj->id = $account->account_id;
- $obj->name = $account->customer_name . ' - ' . $account->account_name;
-
- $outItems[] = $obj;
- }
-
- return $outItems;
- }
-
- /**
- * Comprobaciones antes de realizar una acción
- */
- protected function preActionChecks()
- {
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/LoginController.php b/lib/SP/Controller/LoginController.php
deleted file mode 100644
index 18b81045..00000000
--- a/lib/SP/Controller/LoginController.php
+++ /dev/null
@@ -1,614 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use Defuse\Crypto\Exception\BadFormatException;
-use Defuse\Crypto\Exception\CryptoException;
-use SP\Auth\Auth;
-use SP\Auth\AuthResult;
-use SP\Auth\AuthUtil;
-use SP\Auth\Browser\BrowserAuthData;
-use SP\Auth\Database\DatabaseAuthData;
-use SP\Auth\Ldap\LdapAuthData;
-use SP\Config\Config;
-use SP\Core\CryptMasterPass;
-use SP\Core\DiFactory;
-use SP\Core\Exceptions\AuthException;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Init;
-use SP\Core\Language;
-use SP\Core\Messages\LogMessage;
-use SP\Core\SessionFactory;
-use SP\Core\SessionUtil;
-use SP\Core\UI\Theme;
-use SP\DataModel\TrackData;
-use SP\DataModel\UserLoginData;
-use SP\DataModel\UserPassRecoverData;
-use SP\DataModel\UserPreferencesData;
-use SP\Http\JsonResponse;
-use SP\Http\Request;
-use SP\Log\Log;
-use SP\Mgmt\Groups\Group;
-use SP\Mgmt\Profiles\Profile;
-use SP\Mgmt\Tracks\Track;
-use SP\Mgmt\Users\UserLdap;
-use SP\Mgmt\Users\UserPass;
-use SP\Mgmt\Users\UserPassRecover;
-use SP\Mgmt\Users\UserPreferences;
-use SP\Mgmt\Users\UserSSO;
-use SP\Mgmt\Users\UserUtil;
-use SP\Util\HttpUtil;
-use SP\Util\Json;
-use SP\Util\Util;
-
-/**
- * Class LoginController
- *
- * @package SP\Controller
- */
-class LoginController
-{
- use SP\Core\Dic\InjectableTrait;
-
- /**
- * Estados
- */
- const STATUS_INVALID_LOGIN = 1;
- const STATUS_INVALID_MASTER_PASS = 2;
- const STATUS_USER_DISABLED = 3;
- const STATUS_INTERNAL_ERROR = 4;
- const STATUS_NEED_OLD_PASS = 5;
- const STATUS_MAX_ATTEMPTS_EXCEEDED = 6;
- /**
- * Tiempo para contador de intentos
- */
- const TIME_TRACKING = 600;
- const TIME_TRACKING_MAX_ATTEMPTS = 5;
-
- /**
- * @var JsonResponse
- */
- protected $jsonResponse;
- /**
- * @var UserLoginData
- */
- protected $UserData;
- /**
- * @var LogMessage
- */
- protected $LogMessage;
- /**
- * @var $ConfigData
- */
- protected $ConfigData;
- /**
- * @var Config
- */
- protected $Config;
- /**
- * @var Theme
- */
- protected $Theme;
-
- /**
- * LoginController constructor.
- */
- public function __construct()
- {
- $this->injectDependencies();
-
- $this->UserData = new UserLoginData();
- $this->LogMessage->setAction(__('Inicio sesión', false));
- }
-
- /**
- * @param Config $config
- * @param SessionFactory $session
- * @param JsonResponse $jsonResponse
- * @param LogMessage $logMessage
- */
- public function inject(Config $config, SessionFactory $session, JsonResponse $jsonResponse, LogMessage $logMessage, Theme $theme)
- {
- $this->Config = $config;
- $this->ConfigData = $config->getConfigData();
- $this->jsonResponse = $jsonResponse;
- $this->LogMessage = $logMessage;
- $this->Theme = $theme;
- }
-
- /**
- * Ejecutar las acciones de login
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \InvalidArgumentException
- */
- public function doLogin()
- {
- $this->UserData->setLogin(Request::analyze('user'));
- $this->UserData->setLoginPass(Request::analyzeEncrypted('pass'));
-
- $Log = new Log($this->LogMessage);
-
- try {
- $this->checkTracking();
-
- $Auth = new Auth($this->UserData);
- $result = $Auth->doAuth();
-
- if ($result !== false) {
- // Ejecutar la acción asociada al tipo de autentificación
-
- /** @var AuthResult $AuthResult */
- foreach ($result as $AuthResult) {
- if ($this->{$AuthResult->getAuth()}($AuthResult->getData()) === true && $AuthResult->isAuthGranted() === true) {
- break;
- }
- }
- } else {
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, __('Login incorrecto', false), '', self::STATUS_INVALID_LOGIN);
- }
-
- $this->getUserData();
- $this->checkUser();
- $this->loadMasterPass();
- $this->setUserSession();
- $this->loadUserPreferences();
- $this->cleanUserData();
- } catch (SPException $e) {
- $Log->setLogLevel(Log::ERROR);
- $Log->writeLog();
-
- $this->jsonResponse->setDescription($e->getMessage());
- $this->jsonResponse->setStatus($e->getCode());
-
- Json::returnJson($this->jsonResponse);
- }
-
- $forward = Request::getRequestHeaders('X-Forwarded-For');
-
- if ($forward) {
- $this->LogMessage->addDetails('X-Forwarded-For', $this->ConfigData->isDemoEnabled() ? '***' : $forward);
- }
-
- $Log->writeLog();
-
- $data = ['url' => 'index.php' . Request::importUrlParamsToGet()];
- $this->jsonResponse->setStatus(0);
- $this->jsonResponse->setData($data);
- Json::returnJson($this->jsonResponse);
- }
-
- /**
- * Comprobar los intentos de login
- *
- * @throws \SP\Core\Exceptions\AuthException
- */
- private function checkTracking()
- {
- try {
- $TrackData = new TrackData();
- $TrackData->setSource('Login');
- $TrackData->setTrackIp(HttpUtil::getClientAddress());
-
- $attempts = count(Track::getItem($TrackData)->getTracksForClientFromTime(time() - self::TIME_TRACKING));
- } catch (SPException $e) {
- $this->LogMessage->addDescription($e->getMessage());
- $this->LogMessage->addDescription($e->getHint());
-
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
-
- if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) {
- $this->addTracking();
-
- sleep(0.3 * $attempts);
-
- $this->LogMessage->addDescription(sprintf(__('Intentos excedidos (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS));
-
- throw new AuthException(SPException::INFO, __('Intentos excedidos', false), '', self::STATUS_MAX_ATTEMPTS_EXCEEDED);
- }
- }
-
- /**
- * Añadir un seguimiento
- *
- * @throws \SP\Core\Exceptions\AuthException
- */
- private function addTracking()
- {
- try {
- $TrackData = new TrackData();
- $TrackData->setSource('Login');
- $TrackData->setTrackIp(HttpUtil::getClientAddress());
-
- Track::getItem($TrackData)->add();
- } catch (SPException $e) {
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
- }
-
- /**
- * Obtener los datos del usuario
- *
- * @throws SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\AuthException
- * @throws \InvalidArgumentException
- */
- protected function getUserData()
- {
- try {
- $this->UserData->setPreferences(UserPreferences::getItem()->getById($this->UserData->getId()));
- } catch (SPException $e) {
- $this->LogMessage->addDescription(__('Error al obtener los datos del usuario de la BBDD', false));
-
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
- }
-
- /**
- * Comprobar estado del usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function checkUser()
- {
- // Comprobar si el usuario está deshabilitado
- if ($this->UserData->isIsDisabled()) {
- $this->LogMessage->addDescription(__('Usuario deshabilitado', false));
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, __('Usuario deshabilitado', false), '', self::STATUS_USER_DISABLED);
- }
-
- if ($this->UserData->isIsChangePass()) {
- $hash = Util::generateRandomBytes(16);
-
- $UserPassRecoverData = new UserPassRecoverData();
- $UserPassRecoverData->setUserId($this->UserData->getId());
- $UserPassRecoverData->setHash($hash);
-
- UserPassRecover::getItem($UserPassRecoverData)->add();
-
- $data = ['url' => Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time() . '&f=1'];
- $this->jsonResponse->setData($data);
- $this->jsonResponse->setStatus(0);
- Json::returnJson($this->jsonResponse);
- }
-
- return false;
- }
-
- /**
- * Cargar la clave maestra o solicitarla
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\AuthException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function loadMasterPass()
- {
- $masterPass = Request::analyzeEncrypted('mpass');
- $oldPass = Request::analyzeEncrypted('oldpass');
-
- try {
- if ($masterPass) {
- if (CryptMasterPass::checkTempMasterPass($masterPass)) {
- $this->LogMessage->addDescription(__('Usando clave temporal', false));
-
- $masterPass = CryptMasterPass::getTempMasterPass($masterPass);
- }
-
- if (!UserPass::updateUserMPass($masterPass, $this->UserData)) {
- $this->LogMessage->addDescription(__('Clave maestra incorrecta', false));
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
- }
-
- $this->LogMessage->addDescription(__('Clave maestra actualizada', false));
- } else if ($oldPass) {
- if (!UserPass::updateMasterPassFromOldPass($oldPass, $this->UserData)) {
- $this->LogMessage->addDescription(__('Clave maestra incorrecta', false));
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
- }
-
- $this->LogMessage->addDescription(__('Clave maestra actualizada', false));
- } else {
- switch (UserPass::loadUserMPass($this->UserData)) {
- case UserPass::MPASS_CHECKOLD:
- throw new AuthException(SPException::INFO, __('Es necesaria su clave anterior', false), '', self::STATUS_NEED_OLD_PASS);
- break;
- case UserPass::MPASS_NOTSET:
- case UserPass::MPASS_CHANGED:
- case UserPass::MPASS_WRONG:
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, __('La clave maestra no ha sido guardada o es incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
- break;
- }
- }
- } catch (BadFormatException $e) {
- $this->LogMessage->addDescription(__('Clave maestra incorrecta', false));
-
- throw new AuthException(SPException::INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
- } catch (CryptoException $e) {
- $this->LogMessage->addDescription(__('Error interno', false));
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), $e->getMessage(), self::STATUS_INTERNAL_ERROR);
- }
- }
-
- /**
- * Cargar la sesión del usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \InvalidArgumentException
- * @throws \SP\Core\Exceptions\AuthException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- protected function setUserSession()
- {
- // Obtenemos la clave maestra del usuario
- if (UserPass::$gotMPass === true) {
- // Actualizar el último login del usuario
- UserUtil::setUserLastLogin($this->UserData->getId());
-
- // Cargar las variables de sesión del usuario
- SessionUtil::loadUserSession($this->UserData);
-
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
- $this->LogMessage->addDetails(__('Perfil', false), Profile::getItem()->getById($this->UserData->getUserProfileId())->getName());
- $this->LogMessage->addDetails(__('Grupo', false), Group::getItem()->getById($this->UserData->getUserGroupId())->getName());
- } else {
- $this->LogMessage->addDescription(__('Error al obtener la clave maestra del usuario', false));
-
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
- }
-
- /**
- * Cargar las preferencias del usuario y comprobar si usa 2FA
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- protected function loadUserPreferences()
- {
- if ($this->ConfigData->isDemoEnabled()) {
- SessionFactory::setUserPreferences(new UserPreferencesData());
- } else {
- SessionFactory::setUserPreferences($this->UserData->getPreferences());
- }
-
- Language::setLanguage(true);
- $this->Theme->initTheme(true);
-
- SessionFactory::setSessionType(SessionFactory::SESSION_INTERACTIVE);
- SessionFactory::setAuthCompleted(true);
-
- DiFactory::getEventDispatcher()->notifyEvent('login.preferences', $this);
- }
-
- /**
- * Limpiar datos de usuario
- */
- private function cleanUserData()
- {
- $this->UserData->setLogin(null);
- $this->UserData->setLoginPass(null);
- $this->UserData->setMPass(null);
- $this->UserData->setMKey(null);
- }
-
- /**
- * Comprobar si se ha forzado un cambio de clave
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- protected function checkPasswordChange()
- {
- // Comprobar si se ha forzado un cambio de clave
- if ($this->UserData->isIsChangePass()) {
- $hash = Util::generateRandomBytes();
-
- $UserPassRecoverData = new UserPassRecoverData();
- $UserPassRecoverData->setUserId($this->UserData->getId());
- $UserPassRecoverData->setHash($hash);
-
- UserPassRecover::getItem($UserPassRecoverData)->add();
-
- $data = ['url' => Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time() . '&f=1'];
- $this->jsonResponse->setData($data);
- $this->jsonResponse->setStatus(0);
- Json::returnJson($this->jsonResponse);
- }
-
- return false;
- }
-
- /**
- * Autentificación LDAP
- *
- * @param LdapAuthData $AuthData
- * @return bool
- * @throws \phpmailer\phpmailerException
- * @throws \SP\Core\Exceptions\SPException
- * @throws AuthException
- */
- protected function authLdap(LdapAuthData $AuthData)
- {
- if ($AuthData->getStatusCode() > 0) {
- $this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
-
- if ($AuthData->getStatusCode() === 49) {
- $this->LogMessage->addDescription(__('Login incorrecto', false));
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
- }
-
- if ($AuthData->getStatusCode() === 701) {
- $this->LogMessage->addDescription(__('Cuenta expirada', false));
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
- }
-
- if ($AuthData->getStatusCode() === 702) {
- $this->LogMessage->addDescription(__('El usuario no tiene grupos asociados', false));
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
- }
-
- if ($AuthData->isAuthGranted() === false) {
- return false;
- }
-
- $this->LogMessage->addDescription(__('Error interno', false));
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INTERNAL_ERROR);
- }
-
- $this->UserData->setName($AuthData->getName());
- $this->UserData->setEmail($AuthData->getEmail());
-
- $this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
- $this->LogMessage->addDetails(__('Servidor LDAP', false), $AuthData->getServer());
-
- try {
- $this->UserData->setLogin($this->UserData->getLogin());
-
- // Verificamos si el usuario existe en la BBDD
- if (UserLdap::checkLDAPUserInDB($this->UserData->getLogin())) {
- // Actualizamos el usuario de LDAP en MySQL
- UserLdap::getItem($this->UserData)->updateOnLogin();
- } else {
- // Creamos el usuario de LDAP en MySQL
- UserLdap::getItem($this->UserData)->add();
- }
- } catch (SPException $e) {
- $this->LogMessage->addDescription($e->getMessage());
-
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
-
- return true;
- }
-
- /**
- * Autentificación en BD
- *
- * @param DatabaseAuthData $AuthData
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- * @throws AuthException
- */
- protected function authDatabase(DatabaseAuthData $AuthData)
- {
- // Autentificamos con la BBDD
- if ($AuthData->getAuthenticated() === 0) {
- if ($AuthData->isAuthGranted() === false) {
- return false;
- }
-
- $this->LogMessage->addDescription(__('Login incorrecto', false));
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
- }
-
- if ($AuthData->getAuthenticated() === 1) {
- $this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
- }
-
- return true;
- }
-
- /**
- * Comprobar si el cliente ha enviado las variables de autentificación
- *
- * @param BrowserAuthData $AuthData
- * @return mixed
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws AuthException
- */
- protected function authBrowser(BrowserAuthData $AuthData)
- {
- // Comprobar si concide el login con la autentificación del servidor web
- if ($AuthData->getAuthenticated() === 0) {
- if ($AuthData->isAuthGranted() === false) {
- return false;
- }
-
- $this->LogMessage->addDescription(__('Login incorrecto', false));
- $this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
- $this->LogMessage->addDetails(__('Autentificación', false), sprintf('%s (%s)', AuthUtil::getServerAuthType(), $AuthData->getName()));
-
- $this->addTracking();
-
- throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
- }
-
- $this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
-
- if ($this->ConfigData->isAuthBasicAutoLoginEnabled()) {
- try {
- if (!UserSSO::getItem($this->UserData)->checkUserInDB($this->UserData->getLogin())) {
- UserSSO::getItem()->add();
- } else {
- UserSSO::getItem()->updateOnLogin();
- }
- } catch (SPException $e) {
- throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
- }
-
- $this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
- $this->LogMessage->addDetails(__('Autentificación', false), sprintf('%s (%s)', AuthUtil::getServerAuthType(), $AuthData->getName()));
-
- return true;
- }
-
- return null;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/NoticeShowController.php b/lib/SP/Controller/NoticeShowController.php
deleted file mode 100644
index e3ff08e4..00000000
--- a/lib/SP/Controller/NoticeShowController.php
+++ /dev/null
@@ -1,135 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\SessionUtil;
-use SP\DataModel\NotificationData;
-use SP\Mgmt\Notices\Notice;
-use SP\Mgmt\Users\User;
-use SP\Modules\Web\Controllers\ControllerBase;
-use SP\Mvc\View\Template;
-use SP\Util\Json;
-
-/**
- * Class NoticeShowController
- *
- * @package SP\Controller
- */
-class NoticeShowController extends ControllerBase implements ActionsInterface, ItemControllerInterface
-{
- use RequestControllerTrait;
-
- /**
- * Máximo numero de acciones antes de agrupar
- */
- const MAX_NUM_ACTIONS = 3;
- /**
- * @var int
- */
- private $module = 0;
-
- /**
- * Constructor
- *
- * @param $template Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->init();
-
- $this->view->assign('isDemo', $this->configData->isDemoEnabled());
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->view->assign('itemId', $this->itemId);
- $this->view->assign('activeTab', $this->activeTab);
- $this->view->assign('actionId', $this->actionId);
- $this->view->assign('isView', false);
- $this->view->assign('showViewPass', true);
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- *
- * @param mixed $type Tipo de acción
- * @throws \SP\Core\Exceptions\SPException
- */
- public function doAction($type = null)
- {
- try {
- switch ($this->actionId) {
- case self::NOTIFICATION_VIEW:
- $this->view->assign('header', __('Ver Notificación'));
- $this->view->assign('isView', true);
- $this->getNotice();
- break;
- case self::NOTIFICATION_CREATE:
- $this->view->assign('header', __('Nueva Notificación'));
- $this->getNotice();
- break;
- case self::NOTIFICATION_EDIT:
- $this->view->assign('header', __('Editar Notificación'));
- $this->getNotice();
- break;
- default:
- $this->invalidAction();
- }
-
- if (count($this->JsonResponse->getData()) === 0) {
- $this->JsonResponse->setData(['html' => $this->render()]);
- }
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- $this->JsonResponse->setCsrf($this->view->sk);
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Obtener los datos para la ficha de usuario
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- protected function getNotice()
- {
- $this->module = self::USER;
- $this->view->addTemplate('notices');
-
- $this->view->assign('notice', $this->itemId ? Notice::getItem()->getById($this->itemId) : new NotificationData());
- $this->view->assign('isDisabled', ($this->view->isDemo || $this->view->actionId === self::NOTIFICATION_VIEW) ? 'disabled' : '');
- $this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : '');
-
- if ($this->userData->isIsAdminApp()){
- $this->view->assign('users', User::getItem()->getItemsForSelect());
- }
-
- $this->JsonResponse->setStatus(0);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/NoticesController.php b/lib/SP/Controller/NoticesController.php
deleted file mode 100644
index fa31a2fb..00000000
--- a/lib/SP/Controller/NoticesController.php
+++ /dev/null
@@ -1,96 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Controller\Grids\Notices;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Exceptions\SPException;
-use SP\Mgmt\Notices\Notice;
-
-/**
- * Class NoticesController
- *
- * @package SP\Controller
- */
-class NoticesController extends GridTabControllerBase implements ActionsInterface
-{
- /**
- * Realizar las acciones del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- try {
- $this->useTabs();
- $this->getUserNotices();
-
- $this->eventDispatcher->notifyEvent('show.itemlist.notices', $this);
- } catch (SPException $e) {
- $this->showError(self::ERR_EXCEPTION);
- }
- }
-
- /**
- * Inicializar las plantillas para las pestañas
- */
- public function useTabs()
- {
- $this->Grids = new Notices();
- $this->view->addTemplate('datatabs-grid', 'grid');
-
- $this->view->assign('tabs', []);
- $this->view->assign('activeTab', 0);
- $this->view->assign('maxNumActions', self::MAX_NUM_ACTIONS);
- }
-
- /**
- * Obtener los datos para la pestaña de categorías
- *
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getUserNotices()
- {
- $this->setAction(self::NOTIFICATION);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $Grid = $this->getGrids()->getNoticesGrid();
- $Grid->getData()->setData(Notice::getItem()->getAllForUser());
- $Grid->updatePager();
-
- $this->view->append('tabs', $Grid);
- }
-
- /**
- * @return Notices
- */
- public function getGrids()
- {
- return $this->Grids;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/NoticesSearchController.php b/lib/SP/Controller/NoticesSearchController.php
deleted file mode 100644
index d7ba1872..00000000
--- a/lib/SP/Controller/NoticesSearchController.php
+++ /dev/null
@@ -1,145 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Controller\Grids\Notices;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\SessionUtil;
-use SP\DataModel\ItemSearchData;
-use SP\Http\Request;
-use SP\Mgmt\Notices\NoticeSearch;
-use SP\Mvc\View\Template;
-use SP\Util\Json;
-
-/**
- * Class NoticesSearchController para la gestión de búsquedas de items de accesos
- *
- * @package SP\Controller
- */
-class NoticesSearchController extends GridItemsSearchController implements ActionsInterface, ItemControllerInterface
-{
- use RequestControllerTrait;
-
- /**
- * @var ItemSearchData
- */
- protected $ItemSearchData;
-
- /**
- * Constructor
- *
- * @param $template \SP\Mvc\View\Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->grids = new Notices();
- $this->grids->setQueryTimeStart(microtime());
- $this->ItemSearchData = new ItemSearchData();
-
- $this->init();
- $this->setItemSearchData();
- }
-
- /**
- * Establecer las propiedades de búsqueda
- */
- protected function setItemSearchData()
- {
- $this->ItemSearchData->setSeachString(Request::analyze('search'));
- $this->ItemSearchData->setLimitStart(Request::analyze('start', 0));
- $this->ItemSearchData->setLimitCount(Request::analyze('count', $this->configData->getAccountCount()));
- }
-
- /**
- * Realizar la acción solicitada en la la petición HTTP
- *
- * @param mixed $type Tipo de acción
- * @throws \SP\Core\Exceptions\SPException
- */
- public function doAction($type = null)
- {
- $this->view->assign('isDemo', $this->configData->isDemoEnabled());
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->view->assign('index', $this->activeTab);
-
- try {
- switch ($this->actionId) {
- case ActionsInterface::NOTIFICATION_SEARCH:
- $this->getNoticesUser();
- break;
- default:
- $this->invalidAction();
- }
-
- $this->JsonResponse->setData(['html' => $this->render()]);
- } catch (\Exception $e) {
- $this->JsonResponse->setDescription($e->getMessage());
- }
-
- $this->JsonResponse->setCsrf($this->view->sk);
-
- Json::returnJson($this->JsonResponse);
- }
-
- /**
- * Obtener las notificaciones de una búsqueda
- *
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \InvalidArgumentException
- */
- protected function getNoticesUser()
- {
- $this->setAction(self::NOTIFICATION_SEARCH);
-
- if (!$this->checkAccess()) {
- return;
- }
-
- $this->view->addTemplate('datagrid-table', 'grid');
-
- $Grid = $this->getGrids()->getNoticesGrid();
- $Grid->getData()->setData(NoticeSearch::getItem()->getMgmtSearchUser($this->ItemSearchData));
- $Grid->updatePager();
-
- $this->updatePager($Grid->getPager(), $this->ItemSearchData);
-
- $this->view->assign('data', $Grid);
- $this->view->assign('actionId', self::NOTIFICATION);
-
- $this->JsonResponse->setStatus(0);
- }
-
- /**
- * @return Notices
- */
- public function getGrids()
- {
- return $this->grids;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/RequestControllerTrait.php b/lib/SP/Controller/RequestControllerTrait.php
deleted file mode 100644
index e91f5d80..00000000
--- a/lib/SP/Controller/RequestControllerTrait.php
+++ /dev/null
@@ -1,145 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Config\Config;
-use SP\Config\ConfigData;
-use SP\Core\Context\SessionContext;
-use SP\Core\Messages\LogMessage;
-use SP\Core\SessionUtil;
-use SP\Http\JsonResponse;
-use SP\Http\Request;
-use SP\Util\Checks;
-use SP\Util\Json;
-use SP\Util\Util;
-
-/**
- * Class RequestControllerTrait
- *
- * @package SP\Controller
- */
-trait RequestControllerTrait
-{
- use SP\Core\Dic\InjectableTrait;
-
- /**
- * @var int
- */
- protected $actionId;
- /**
- * @var int|array
- */
- protected $itemId;
- /**
- * @var int
- */
- protected $activeTab;
- /**
- * @var JsonResponse
- */
- protected $JsonResponse;
- /**
- * @var string
- */
- protected $sk;
- /**
- * @var LogMessage
- */
- protected $LogMessage;
- /** @var SessionContext */
- protected $session;
- /** @var Config */
- protected $Config;
- /** @var ConfigData */
- protected $ConfigData;
-
- /**
- * @param SessionContext $session
- * @param Config $config
- */
- final public function inject(SessionContext $session, Config $config)
- {
- $this->session = $session;
- $this->Config = $config;
- $this->ConfigData = $config->getConfigData();
- }
-
- /**
- * inicializar las propiedades
- *
- * @internal param array $checKItems Lista de elementos a analizar
- */
- protected function init()
- {
- $this->JsonResponse = new JsonResponse();
-
- $this->checkSession();
- $this->analyzeRequest();
- $this->preActionChecks();
- }
-
- /**
- * Comprobar si la sesión está activa
- */
- protected function checkSession()
- {
- if (!$this->session->isLoggedIn()) {
- if (Checks::isJson()) {
- $this->JsonResponse->setDescription(__('La sesión no se ha iniciado o ha caducado', false));
- $this->JsonResponse->setStatus(10);
- Json::returnJson($this->JsonResponse);
- } else {
- Util::logout();
- }
- }
- }
-
- /**
- * Analizar la petición HTTP y establecer las propiedades del elemento
- */
- protected function analyzeRequest()
- {
- $this->sk = Request::analyze('sk');
- }
-
- /**
- * Comprobaciones antes de realizar una acción
- */
- protected function preActionChecks()
- {
- if (!$this->sk || !SessionUtil::checkSessionKey($this->sk)) {
- $this->invalidAction();
- }
- }
-
- /**
- * Acción no disponible
- */
- protected function invalidAction()
- {
- $this->JsonResponse->setDescription(__('Acción Inválida', false));
- Json::returnJson($this->JsonResponse);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/TabControllerBase.php b/lib/SP/Controller/TabControllerBase.php
deleted file mode 100644
index e47742c9..00000000
--- a/lib/SP/Controller/TabControllerBase.php
+++ /dev/null
@@ -1,67 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-use SP\Modules\Web\Controllers\ControllerBase;
-
-
-/**
- * Class TabControllerBase
- *
- * @package SP\Controller
- */
-abstract class TabControllerBase extends ControllerBase implements TabsInterface
-{
- /**
- * Pestañas
- *
- * @var array
- */
- private $tabs = [];
-
- /**
- * Añadir una nueva pestaña
- *
- * @param string $title
- * @return int Índice de la última pestaña añadida
- */
- public function addTab($title)
- {
- $this->tabs[] = ['title' => $title];
-
- $this->view->assign('tabs', $this->tabs);
-
- return count($this->tabs) - 1;
- }
-
- /**
- * Devuelve las pestañas
- *
- * @return array
- */
- public function getTabs()
- {
- return $this->tabs;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/TabsInterface.php b/lib/SP/Controller/TabsInterface.php
deleted file mode 100644
index 24d74615..00000000
--- a/lib/SP/Controller/TabsInterface.php
+++ /dev/null
@@ -1,48 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-/**
- * Interface TabsInterface
- *
- * @package SP\Controller
- */
-interface TabsInterface
-{
- /**
- * Añadir una nueva pestaña
- *
- * @param string $title
- * @return int Índice actual de pestaña
- */
- public function addTab($title);
-
- /**
- * Devuelve las pestañas
- *
- * @return array
- */
- public function getTabs();
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/TaskController.php b/lib/SP/Controller/TaskController.php
deleted file mode 100644
index 316c668b..00000000
--- a/lib/SP/Controller/TaskController.php
+++ /dev/null
@@ -1,267 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-use SP\Core\Messages\TaskMessage;
-use SP\Http\Request;
-use SP\Services\Task\Task;
-use SP\Util\Util;
-
-/**
- * Class TaskController
- *
- * @package SP\Controller
- */
-class TaskController
-{
- /**
- * @var Task Instancia de la tarea
- */
- protected $Task;
- /**
- * @var int Tiempo de espera en cada intendo de inicialización
- */
- protected $startupWaitTime = 10;
- /**
- * @var int Intentos de inicialización
- */
- protected $startupWaitCount = 30;
- /**
- * @var string Archivo de bloqueo
- */
- protected $lockFile;
- /**
- * @var string Directorio de las tareas
- */
- protected $dir;
- /**
- * @var string ID de la tarea
- */
- protected $taskId;
- /**
- * @var string Archivo de la tarea
- */
- protected $taskFile;
-
- /**
- * TaskController constructor.
- */
- public function __construct()
- {
- $this->dir = Util::getTempDir();
- $this->taskId = Request::analyze('taskId');
- }
-
- /**
- * Realizar acción
- *
- * @return bool
- */
- public function doAction()
- {
- $source = Request::analyze('source');
-
- if ($this->dir === false || !$this->getLock($source)) {
- return false;
- }
-
- $this->taskFile = $this->dir . DIRECTORY_SEPARATOR . $this->taskId . '.task';
-
- $count = 0;
-
- while (!$this->checkTaskRegistered() || !$this->checkTaskFile()) {
- if ($count >= $this->startupWaitCount) {
- debugLog('Aborting ...');
-
- die(1);
- }
-
- debugLog('Waiting for task ...');
-
- $count++;
- sleep($this->startupWaitTime);
- }
-
- $this->readTaskStatus();
-
- die(0);
- }
-
- /**
- * Comprueba si una tarea ha sido registrada en la sesión
- *
- * @return bool
- */
- protected function checkTaskRegistered()
- {
- if (is_object($this->Task)) {
- debugLog('Task detected: ' . $this->Task->getTaskId());
-
- return true;
- }
-
- if (file_exists($this->taskFile)) {
- $task = file_get_contents($this->taskFile);
-
- if ($task !== false) {
- $this->Task = unserialize($task);
- }
-
- return is_object($this->Task);
- }
-
- return false;
- }
-
- /**
- * Comprobar si el archivo de salida de la tarea existe
- */
- protected function checkTaskFile()
- {
- return file_exists($this->Task->getFileOut());
- }
-
- /**
- * Leer el estado de una tarea y enviarlo
- */
- protected function readTaskStatus()
- {
- debugLog('Tracking task: ' . $this->Task->getTaskId());
-
- $id = 0;
- $failCount = 0;
- $file = $this->Task->getFileOut();
- $interval = $this->Task->getInterval();
-
- $Message = new TaskMessage();
- $Message->setTask($this->Task->getTaskId());
- $Message->setMessage(__('Esperando actualización de progreso ...'));
-
- while ($failCount <= 30 && file_exists($this->taskFile)) {
- $content = file_get_contents($file);
-
- if (!empty($content)) {
- $this->sendMessage($id, $content);
- $id++;
- } else {
- debugLog($Message->composeJson());
-
- $this->sendMessage($id, $Message->composeJson());
- $failCount++;
- }
-
- sleep($interval);
- }
- }
-
- /**
- * Enviar un mensaje
- *
- * @param $id
- * @param $message
- */
- protected function sendMessage($id, $message)
- {
- echo 'id: ', $id, PHP_EOL, 'data: ', $message, PHP_EOL, PHP_EOL;
-
- ob_flush();
- flush();
- }
-
- /**
- * Comprobar si hay una tarea a la espera
- *
- * @param $source
- * @return bool
- */
- protected function checkWait($source)
- {
- $this->lockFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $source . '.lock';
-
- if (file_exists($this->lockFile)) {
- $timeout = $this->startupWaitCount * $this->startupWaitTime;
-
- if (filemtime($this->lockFile) + $timeout < time()) {
- unlink($this->lockFile);
-
- return false;
- }
-
- return true;
- }
-
- touch($this->lockFile);
-
- return false;
- }
-
- /**
- * Eliminar bloqueo
- */
- protected function removeLock()
- {
- debugLog(__METHOD__);
-
- unlink($this->lockFile);
- }
-
- /**
- * Obtener un bloqueo para la ejecución de la tarea
- *
- * @param $source
- *
- * @return bool
- */
- private function getLock($source)
- {
- if ($source === '') {
- $source = 'task';
- }
-
- $this->lockFile = $this->dir . DIRECTORY_SEPARATOR . $source . '.lock';
-
- if (file_exists($this->lockFile)) {
- $timeout = $this->startupWaitCount * $this->startupWaitTime;
-
- if (filemtime($this->lockFile) + $timeout < time()) {
- unlink($this->lockFile);
-
- return $this->updateLock();
- }
-
- return false;
- } else {
- return $this->updateLock();
- }
- }
-
- /**
- * Actualizar el tiempo del archivo de bloqueo
- */
- protected function updateLock()
- {
- return file_put_contents($this->lockFile, time()) !== false;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Controller/UserPreferencesController.php b/lib/SP/Controller/UserPreferencesController.php
deleted file mode 100644
index 16ba3a2a..00000000
--- a/lib/SP/Controller/UserPreferencesController.php
+++ /dev/null
@@ -1,107 +0,0 @@
-.
- */
-
-namespace SP\Controller;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Language;
-use SP\Core\SessionUtil;
-use SP\DataModel\UserPreferencesData;
-use SP\Mgmt\Users\UserPreferences;
-use SP\Mvc\View\Template;
-
-/**
- * Class UsersPrefs encargada de mostrar las preferencias de los usuarios
- *
- * @package SP\Controller
- */
-class UserPreferencesController extends TabControllerBase implements ActionsInterface
-{
- /**
- * @var UserPreferencesData
- */
- private $userPrefs;
- /**
- * @var int
- */
- private $userId;
-
- /**
- * Constructor
- *
- * @param $template Template con instancia de plantilla
- */
- public function __construct(Template $template = null)
- {
- parent::__construct($template);
-
- $this->view->assign('tabs', []);
- $this->view->assign('sk', SessionUtil::getSessionKey(true));
- $this->userId = $this->userData->getId();
- $this->userPrefs = UserPreferences::getItem()->getById($this->userId);
- }
-
- /**
- * Obtener la pestaña de preferencias
- */
- public function getPreferencesTab()
- {
- $this->setAction(self::PREFERENCE_GENERAL);
-
- $this->view->addTemplate('preferences-site');
-
- $this->view->assign('userId', $this->userId);
- $this->view->assign('langsAvailable', Language::getAvailableLanguages());
- $this->view->assign('currentLang', $this->userPrefs->getLang());
- $this->view->assign('themesAvailable', $this->theme->getThemesAvailable());
- $this->view->assign('currentTheme', $this->userPrefs->getTheme() ?: $this->configData->getSiteTheme());
- $this->view->assign('chkAccountLink', $this->userPrefs->isAccountLink() ? 'checked="checked"' : '');
- $this->view->assign('resultsPerPage', $this->userPrefs->getResultsPerPage() ?: $this->configData->getAccountCount());
- $this->view->assign('chkSortViews', $this->userPrefs->isSortViews() ? 'checked="checked"' : '');
- $this->view->assign('chkTopNavbar', $this->userPrefs->isTopNavbar() ? 'checked="checked"' : '');
- $this->view->assign('chkOptionalActions', $this->userPrefs->isOptionalActions() ? 'checked="checked"' : '');
- $this->view->assign('chkResultsAsCards', $this->userPrefs->isResultsAsCards() ? 'checked="checked"' : '');
-
- $this->view->assign('tabIndex', $this->addTab(__('Preferencias')), 'preferences');
- $this->view->assign('actionId', $this->getAction(), 'preferences');
- }
-
- /**
- * Realizar las accione del controlador
- *
- * @param mixed $type Tipo de acción
- */
- public function doAction($type = null)
- {
- $this->view->addTemplate('tabs-start', 'common');
-
- $this->getPreferencesTab();
-
- $this->eventDispatcher->notifyEvent('user.preferences', $this);
-
- $this->view->addTemplate('tabs-end', 'common');
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Core/SessionFactory.php b/lib/SP/Core/SessionFactory.php
deleted file mode 100644
index 48e25988..00000000
--- a/lib/SP/Core/SessionFactory.php
+++ /dev/null
@@ -1,565 +0,0 @@
-.
- */
-
-namespace SP\Core;
-
-use SP\Core\Crypt\Vault;
-use SP\DataModel\UserData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Clase para manejar la variable de sesion
- * @deprecated
- */
-class SessionFactory
-{
- /**
- * Tipos de sesión
- */
- const SESSION_INTERACTIVE = 1;
- const SESSION_API = 2;
-
- /**
- * Establece los datos del usuario en la sesión.
- *
- * @param UserData $UserData
- */
- public static function setUserData(UserData $UserData = null)
- {
- self::setSessionKey('userData', $UserData);
- }
-
- /**
- * Establecer una variable de sesión
- *
- * @param string $key El nombre de la variable
- * @param mixed $value El valor de la variable
- */
- public static function setSessionKey($key, $value)
- {
- $_SESSION[$key] = $value;
- }
-
- /**
- * Establecer una variable de sesión para un plugin
- *
- * @param string $plugin Nombre del plugin
- * @param string $key El nombre de la variable
- * @param mixed $value El valor de la variable
- */
- public static function setPluginKey($plugin, $key, $value)
- {
- $_SESSION[$plugin][$key] = $value;
- }
-
- /**
- * Devuelve los datos del usuario en la sesión.
- *
- * @return UserData
- */
- public static function getUserData()
- {
- return self::getSessionKey('userData', new UserData());
- }
-
- /**
- * Devolver una variable de sesión
- *
- * @param string $key
- * @param mixed $default
- * @return mixed
- */
- public static function getSessionKey($key, $default = '')
- {
- if (isset($_SESSION[$key])) {
- return is_numeric($default) ? (int)$_SESSION[$key] : $_SESSION[$key];
- }
-
- return $default;
- }
-
- /**
- * Devolver una variable de sesión
- *
- * @param string $plugin
- * @param string $key
- * @param mixed $default
- * @return mixed
- */
- public static function getPluginKey($plugin, $key, $default = '')
- {
- if (isset($_SESSION[$plugin][$key])) {
- return is_numeric($default) ? (int)$_SESSION[$plugin][$key] : $_SESSION[$plugin][$key];
- }
-
- return $default;
- }
-
- /**
- * Establece si se ha comprobado si hay actualizaciones
- *
- * @param bool $bool
- */
- public static function setUpdated($bool = true)
- {
- self::setSessionKey('updated', $bool);
- }
-
- /**
- * Devuelve si se ha combrobado si hay actualizaciones
- *
- * @return bool
- */
- public static function getUpdated()
- {
- return self::getSessionKey('updated', false);
- }
-
- /**
- * Devuelve el timeout de la sesión
- *
- * @return int|null El valor en segundos
- */
- public static function getSessionTimeout()
- {
- return self::getSessionKey('sessionTimeout', null);
- }
-
- /**
- * Establecer el timeout de la sesión
- *
- * @param int $timeout El valor en segundos
- */
- public static function setSessionTimeout($timeout)
- {
- self::setSessionKey('sessionTimeout', $timeout);
- }
-
- /**
- * Devuelve si es necesario recargar la aplicación
- *
- * @return bool
- */
- public static function getReload()
- {
- return self::getSessionKey('reload', false);
- }
-
- /**
- * Establecer si es necesario recargar la aplicación
- *
- * @param bool $bool
- */
- public static function setReload($bool)
- {
- self::setSessionKey('reload', $bool);
- }
-
- /**
- * Devuelve la clave de seguridad para los formularios
- *
- * @return string|null
- */
- public static function getSecurityKey()
- {
- return self::getSessionKey('sk', null);
- }
-
- /**
- * Establece la clave de seguridad para los formularios
- *
- * @param string $sk La clave de seguridad
- */
- public static function setSecurityKey($sk)
- {
- self::setSessionKey('sk', $sk);
- }
-
- /**
- * Devuelve la hora en la que el SID de sesión fue creado
- *
- * @return int
- */
- public static function getSidStartTime()
- {
- return self::getSessionKey('sidStartTime', 0);
- }
-
- /**
- * Establece la hora de creación del SID
- *
- * @param $time int La marca de hora
- */
- public static function setSidStartTime($time)
- {
- self::setSessionKey('sidStartTime', $time);
- }
-
- /**
- * Devuelve la hora de inicio de actividad.
- *
- * @return int
- */
- public static function getStartActivity()
- {
- return self::getSessionKey('startActivity', 0);
- }
-
- /**
- * Establece la hora de inicio de actividad
- *
- * @param $time int La marca de hora
- */
- public static function setStartActivity($time)
- {
- self::setSessionKey('startActivity', $time);
- }
-
- /**
- * Devuelve la hora de la última actividad
- *
- * @return int
- */
- public static function getLastActivity()
- {
- return self::getSessionKey('lastActivity', 0);
- }
-
- /**
- * Establece la hora de la última actividad
- *
- * @param $time int La marca de hora
- */
- public static function setLastActivity($time)
- {
- self::setSessionKey('lastActivity', $time);
- }
-
- /**
- * Devuelve el id de la última cuenta vista
- *
- * @return int
- */
- public static function getLastAcountId()
- {
- return self::getSessionKey('lastAccountId', 0);
- }
-
- /**
- * Establece el id de la última cuenta vista
- *
- * @param $id int La marca de hora
- */
- public static function setLastAcountId($id)
- {
- self::setSessionKey('lastAccountId', $id);
- }
-
- /**
- * Devolver la clave pública
- *
- * @return mixed
- */
- public static function getPublicKey()
- {
- return self::getSessionKey('pubkey');
- }
-
- /**
- * Establecer la clave pública
- *
- * @param $key
- */
- public static function setPublicKey($key)
- {
- self::setSessionKey('pubkey', $key);
- }
-
- /**
- * Establecer el lenguaje de la sesión
- *
- * @param $locale
- */
- public static function setLocale($locale)
- {
- self::setSessionKey('locale', $locale);
- }
-
- /**
- * Devuelve el lenguaje de la sesión
- *
- * @return string
- */
- public static function getLocale()
- {
- return self::getSessionKey('locale');
- }
-
- /**
- * Devolver la clave maestra temporal
- *
- * @return string
- */
- public static function getTemporaryMasterPass()
- {
- return self::getSessionKey('tempmasterpass');
- }
-
- /**
- * Establece la clave maestra temporal
- *
- * @param string $password
- */
- public static function setTemporaryMasterPass($password)
- {
- self::setSessionKey('tempmasterpass', $password);
- }
-
- /**
- * Devolver el color asociado a una cuenta
- *
- * @return string
- */
- public static function getAccountColor()
- {
- return self::getSessionKey('accountcolor');
- }
-
- /**
- * Establece el color asociado a una cuenta
- *
- * @param array $color
- */
- public static function setAccountColor(array $color)
- {
- self::setSessionKey('accountcolor', $color);
- }
-
- /**
- * Devolver si hay una cookie de sesión para CURL
- *
- * @return string
- */
- public static function getCurlCookieSession()
- {
- return self::getSessionKey('curlcookiesession', false);
- }
-
- /**
- * Establecer si hay una cookie de sesión para CURL
- *
- * @param bool $session
- */
- public static function setCurlCookieSession($session)
- {
- self::setSessionKey('curlcookiesession', $session);
- }
-
- /**
- * Devolver si hay una sesión a la API de DokuWiki
- *
- * @return string
- */
- public static function getDokuWikiSession()
- {
- return self::getSessionKey('dokuwikisession', false);
- }
-
- /**
- * Establecer si hay una sesión a la API de DokuWiki
- *
- * @param bool $session
- */
- public static function setDokuWikiSession($session)
- {
- self::setSessionKey('dokuwikisession', $session);
- }
-
- /**
- * Devolver el tipo de sesion
- *
- * @return int
- */
- public static function getSessionType()
- {
- return self::getSessionKey('sessiontype', 0);
- }
-
- /**
- * Establecer el tipo de sesion
- *
- * @param int $type
- */
- public static function setSessionType($type)
- {
- self::setSessionKey('sessiontype', $type);
- }
-
- /**
- * Establecer los plugins cargados
- *
- * @param array $plugins
- */
- public static function setPluginsLoaded(array $plugins)
- {
- self::setSessionKey('plugins_loaded', $plugins);
- }
-
- /**
- * Devolver los plugins cargados
- */
- public static function getPluginsLoaded()
- {
- return self::getSessionKey('plugins_loaded', []);
- }
-
- /**
- * Establecer los plugins deshabilitados
- *
- * @param array $plugins
- */
- public static function setPluginsDisabled(array $plugins)
- {
- self::setSessionKey('plugins_disabled', $plugins);
- }
-
- /**
- * Devolver los plugins deshabilitados
- */
- public static function getPluginsDisabled()
- {
- return self::getSessionKey('plugins_disabled', []);
- }
-
- /**
- * @param $key
- */
- public static function unsetSessionKey($key)
- {
- unset($_SESSION[$key]);
- }
-
- /**
- * Establece si se ha actulizado la aplicación
- *
- * @param bool $bool
- */
- public static function setAppUpdated($bool = true)
- {
- self::setSessionKey('appupdated', $bool);
- }
-
- /**
- * Devuelve si se ha actulizado la aplicación
- *
- * @return bool
- */
- public static function getAppUpdated()
- {
- return self::getSessionKey('appupdated', false);
- }
-
- /**
- * Devuelve la clave maestra encriptada
- *
- * @return Vault
- */
- public static function getVault()
- {
- return self::getSessionKey('vault');
- }
-
- /**
- * Establecer la clave maestra encriptada
- *
- * @param Vault $vault
- */
- public static function setVault(Vault $vault)
- {
- self::setSessionKey('vault', $vault);
- }
-
- /**
- * Devuelve si es necesario comprobar la versión de la aplicación
- * para actualizar
- *
- * @return bool
- */
- public static function getUpgradeChecked()
- {
- return self::getSessionKey('upgradechecked', true);
- }
-
- /**
- * Establecer si es necesario comprobar la versión de la aplicación
- * para actualizar
- *
- * @param bool $upgradechecked
- */
- public static function setUpgradeChecked($upgradechecked = false)
- {
- self::setSessionKey('upgradechecked', $upgradechecked);
- }
-
- /**
- * Devuelve si se ha realizado un cierre de sesión
- *
- * @return bool
- */
- public static function getLoggedOut()
- {
- return self::getSessionKey('loggedout', false);
- }
-
- /**
- * Establecer si se ha realizado un cierre de sesión
- *
- * @param bool $loggedout
- */
- public static function setLoggedOut($loggedout = false)
- {
- self::setSessionKey('loggedout', $loggedout);
- }
-
- /**
- * Establecer la hora de carga de la configuración
- *
- * @param $time
- */
- public function setConfigTime($time)
- {
- self::setSessionKey('configTime', $time);
- }
-
- /**
- * Devolver la hora de carga de la configuración
- *
- * @return int
- */
- public function getConfigTime()
- {
- return self::getSessionKey('configTime');
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Log/Email.php b/lib/SP/Log/Email.php
deleted file mode 100644
index 310eb50e..00000000
--- a/lib/SP/Log/Email.php
+++ /dev/null
@@ -1,215 +0,0 @@
-.
- */
-
-namespace SP\Log;
-
-use PHPMailer\PHPMailer\Exception;
-use PHPMailer\PHPMailer\PHPMailer;
-use SP\Config\Config;
-use SP\Core\Init;
-use SP\Core\Messages\LogMessage;
-use SP\Core\Messages\NoticeMessage;
-use SP\Core\SessionFactory;
-use SP\Html\Html;
-use SP\Util\Checks;
-use SP\Util\HttpUtil;
-use SP\Util\Util;
-
-/**
- * Clase Email para la gestión de envío de correos de notificación
- *
- * @package SP
- */
-class Email
-{
- /**
- * Enviar un email utilizando la clase PHPMailer.
- *
- * @param LogMessage $LogMessage con el objeto del tipo Log
- * @param string $mailTo con el destinatario
- * @param bool $isEvent para indicar si es um
- * @return bool
- * @throws Exception
- */
- public static function sendEmail(LogMessage $LogMessage, $mailTo = '', $isEvent = true)
- {
- return false;
-
- // FIXME
- if (!Checks::mailIsEnabled()) {
- return false;
- }
-
- $Mail = self::getMailer($mailTo, $LogMessage->getAction(true));
-
- if ($isEvent === true) {
- $performer = SessionFactory::getUserData()->getLogin() ?: __('N/D');
- $body[] = sprintf('%s: %s', Html::strongText(__('Acción')), $LogMessage->getAction(true));
- $body[] = sprintf('%s: %s (%s)', Html::strongText(__('Realizado por')), $performer, HttpUtil::getClientAddress(true));
-
- $Mail->addCC(Config::getConfig()->getMailFrom());
- }
-
- $body[] = $LogMessage->getHtmlDescription(true);
- $body[] = $LogMessage->getHtmlDetails(true);
-
- $Mail->isHTML();
- $Mail->Body = implode(Log::NEWLINE_HTML, array_merge($body, Email::getEmailFooter()));
-
- $LogMessage = new LogMessage();
- $LogMessage->setAction(__('Enviar Email', false));
- $Log = new Log($LogMessage);
-
- try {
- $Mail->send();
- $LogMessage->addDescription(__('Correo enviado', false));
- $LogMessage->addDetails(__('Destinatario', false), $mailTo);
-
- if ($isEvent === true) {
- $LogMessage->addDetails(__('CC', false), Config::getConfig()->getMailFrom());
- }
-
- $Log->writeLog();
- return true;
- } catch (Exception $e) {
- $LogMessage->addDescription(__('Error al enviar correo', false));
- $LogMessage->addDetails(__('Error', false), $e->getMessage());
- $LogMessage->addDetails(__('Error', false), $Mail->ErrorInfo);
- $Log->writeLog();
- }
-
- return false;
- }
-
- /**
- * Inicializar la clase PHPMailer.
- *
- * @param string $mailTo con la dirección del destinatario
- * @param string $action con la acción realizada
- * @return false|PHPMailer
- */
- private static function getMailer($mailTo, $action)
- {
- $appName = Util::getAppInfo('appname');
- $mailFrom = Config::getConfig()->getMailFrom();
- $mailServer = Config::getConfig()->getMailServer();
- $mailPort = Config::getConfig()->getMailPort();
- $mailAuth = Config::getConfig()->isMailAuthenabled();
-
- if (empty($mailTo)) {
- $mailTo = $mailFrom;
- }
-
- $Mail = new PHPMailer();
-
- $Mail->SMTPAutoTLS = false;
- $Mail->isSMTP();
- $Mail->CharSet = 'utf-8';
- $Mail->Host = $mailServer;
- $Mail->Port = $mailPort;
-
- if ($mailAuth) {
- $Mail->SMTPAuth = $mailAuth;
- $Mail->Username = Config::getConfig()->getMailUser();
- $Mail->Password = Config::getConfig()->getMailPass();
- }
-
- $Mail->SMTPSecure = strtolower(Config::getConfig()->getMailSecurity());
- //$mail->SMTPDebug = 2;
- //$mail->Debugoutput = 'error_log';
-
- $Mail->setFrom($mailFrom, $appName);
- $Mail->addAddress($mailTo);
- $Mail->addReplyTo($mailFrom, $appName);
- $Mail->WordWrap = 100;
- $Mail->Subject = sprintf('%s (%s) - %s', $appName, __('Aviso'), $action);
-
- return $Mail;
- }
-
- /**
- * Devolver el pie del email con la firma de la aplicación
- *
- * @return array
- */
- protected static function getEmailFooter()
- {
- return [
- '',
- '--',
- sprintf('%s - %s', Util::getAppInfo('appname'), Util::getAppInfo('appdesc')),
- Html::anchorText(Init::$WEBURI)
- ];
- }
-
- /**
- * Enviar un correo a varios destinatarios.
- *
- * Se envía en copia oculta.
- *
- * @param NoticeMessage $Message
- * @param array $mailTo
- * @return bool
- */
- public static function sendEmailBatch(NoticeMessage $Message, array $mailTo)
- {
- if (!Checks::mailIsEnabled()) {
- return false;
- }
-
- $Mail = self::getMailer(Config::getConfig()->getMailFrom(), $Message->getTitle());
- $Mail->isHTML();
-
- foreach ($mailTo as $recipient) {
- $Mail->addBCC($recipient->user_email, $recipient->user_name);
- }
-
- if (empty($Message->getFooter())) {
- $Message->setFooter(self::getEmailFooter());
- }
-
- $Mail->Body = $Message->composeHtml();
- $Mail->AltBody = $Message->composeText();
-
- $LogMessage = new LogMessage();
- $LogMessage->setAction(__('Enviar Email', false));
- $LogMessage->addDetails(__('Destinatario', false), implode(';', array_keys($Mail->getAllRecipientAddresses())));
-
- $Log = new Log($LogMessage);
-
- try {
- $Mail->send();
- $LogMessage->addDescription(__('Correo enviado', false));
- $Log->writeLog();
- return true;
- } catch (phpmailerException $e) {
- $LogMessage->addDescription(__('Error al enviar correo', false));
- $LogMessage->addDetails(__('Error', false), $e->getMessage());
- $LogMessage->addDetails(__('Error', false), $Mail->ErrorInfo);
- $Log->writeLog();
- }
-
- return false;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ApiTokens/ApiToken.php b/lib/SP/Mgmt/ApiTokens/ApiToken.php
deleted file mode 100644
index f23a43a3..00000000
--- a/lib/SP/Mgmt/ApiTokens/ApiToken.php
+++ /dev/null
@@ -1,431 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\ApiTokens;
-
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Crypt\Hash;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Crypt\Vault;
-use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
-use SP\DataModel\AuthTokenData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\Util;
-
-/**
- * Class ApiToken
- *
- * @package SP\Mgmt\ApiTokens
- * @property AuthTokenData $itemData
- */
-class ApiToken extends ApiTokenBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * @return mixed
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('La autorización ya existe', false), SPException::WARNING);
- }
-
- $token = $this->getTokenByUserId($this->itemData->getAuthtokenUserId());
-
- $query = /** @lang SQL */
- 'INSERT INTO authTokens
- SET authtoken_userId = ?,
- actionId = ?,
- createdBy = ?,
- authtoken_token = ?,
- authtoken_vault = ?,
- hash = ?,
- startDate = UNIX_TIMESTAMP()';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAuthtokenUserId());
- $Data->addParam($this->itemData->getActionId());
- $Data->addParam(SessionFactory::getUserData()->getId());
- $Data->addParam($token);
-
- $action = $this->itemData->getActionId();
-
- if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE
- ) {
- $Data->addParam(serialize($this->getSecureData($token)));
- } else {
- $Data->addParam(null);
- }
-
- $Data->addParam(Hash::hashKey($this->itemData->getHash()));
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_id FROM authTokens
- WHERE authtoken_userId = ?
- AND actionId = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAuthtokenUserId());
- $Data->addParam($this->itemData->getActionId());
-
- DbWrapper::getResults($Data);
-
- return $Data->getQueryNumRows() === 1;
- }
-
- /**
- * Obtener el token de la API de un usuario
- *
- * @param $id
- * @return bool
- */
- private function getTokenByUserId($id)
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_token FROM authTokens WHERE authtoken_userId = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- $queryRes = DbWrapper::getResults($Data);
-
- return $Data->getQueryNumRows() === 1 ? $queryRes->authtoken_token : $this->generateToken();
- }
-
- /**
- * Generar un token de acceso
- *
- * @return string
- */
- private function generateToken()
- {
- return Util::generateRandomBytes(32);
- }
-
- /**
- * Generar la llave segura del token
- *
- * @param $token
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @return Vault
- */
- private function getSecureData($token)
- {
- $Vault = new Vault();
- $Vault->saveData(CryptSession::getSessionKey(), $this->itemData->getHash() . $token);
-
- return $Vault;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM authTokens WHERE authtoken_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Token no encontrado', false), SPException::INFO);
- } else {
- $Data->addParam(null);
- }
-
- return $this;
- }
-
- /**
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('La autorización ya existe', false), SPException::WARNING);
- }
-
- $token = $this->getTokenByUserId($this->itemData->getAuthtokenUserId());
- $this->getSecureData($token);
-
- $query = /** @lang SQL */
- 'UPDATE authTokens
- SET authtoken_userId = ?,
- actionId = ?,
- createdBy = ?,
- authtoken_token = ?,
- authtoken_vault = ?,
- hash = ?,
- startDate = UNIX_TIMESTAMP()
- WHERE authtoken_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAuthtokenUserId());
- $Data->addParam($this->itemData->getActionId());
- $Data->addParam(SessionFactory::getUserData()->getId());
- $Data->addParam($token);
-
- $action = $this->itemData->getActionId();
-
- if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE
- ) {
- $Data->addParam(serialize($this->getSecureData($token)));
- } else {
- $Data->addParam(null);
- }
-
- $Data->addParam(Hash::hashKey($this->itemData->getHash()));
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_id FROM authTokens
- WHERE authtoken_userId = ?
- AND actionId = ?
- AND authtoken_id <> ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAuthtokenUserId());
- $Data->addParam($this->itemData->getActionId());
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getResults($Data);
-
- return $Data->getQueryNumRows() === 1;
- }
-
- /**
- * Regenerar el hash de los tokens de un usuario
- *
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- public function refreshToken()
- {
- $token = $this->generateToken();
- $this->getSecureData($token);
-
- $query = /** @lang SQL */
- 'UPDATE authTokens
- SET authtoken_token = ?,
- hash = ?,
- authtoken_vault = ?,
- startDate = UNIX_TIMESTAMP()
- WHERE authtoken_userId = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($token);
- $Data->addParam(Hash::hashKey($this->itemData->getHash()));
-
- if ($this->itemData->getActionId() === ActionsInterface::ACCOUNT_VIEW_PASS) {
- $Data->addParam(serialize($this->getSecureData($token)));
- } else {
- $Data->addParam(null);
- }
-
- $Data->addParam($this->itemData->getAuthtokenUserId());
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return AuthTokenData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_id,
- authtoken_userId,
- actionId,
- createdBy,
- startDate,
- authtoken_token
- FROM authTokens
- WHERE authtoken_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * Eliminar elementos en lote
- *
- * @param array $ids
- * @return $this
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function deleteBatch(array $ids)
- {
- $query = /** @lang SQL */
- 'DELETE FROM authTokens WHERE authtoken_id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setParams($ids);
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-
- /**
- * Obtener el usuario a partir del token
- *
- * @param $token string El token de autorización
- * @return bool|mixed
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getUserIdForToken($token)
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_userId FROM authTokens WHERE authtoken_token = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($token);
-
- $queryRes = DbWrapper::getResults($Data);
-
- return $Data->getQueryNumRows() === 1 ? $queryRes->authtoken_userId : false;
- }
-
- /**
- * Devolver los datos de un token
- *
- * @param $actionId int El id de la accion
- * @param $token string El token de seguridad
- * @return false|AuthTokenData
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getTokenByToken($actionId, $token)
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_userId,
- authtoken_vault,
- hash
- FROM authTokens
- WHERE actionId = ?
- AND authtoken_token = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($actionId);
- $Data->addParam($token);
-
- $queryRes = DbWrapper::getResults($Data);
-
- return $Data->getQueryNumRows() === 1 ? $queryRes : false;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php b/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php
deleted file mode 100644
index 0ec8595d..00000000
--- a/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\ApiTokens;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\AuthTokenData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class ApiTokensBase
- *
- * @package SP\Mgmt\ApiTokens
- */
-abstract class ApiTokenBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(AuthTokenData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ApiTokens/ApiTokenSearch.php b/lib/SP/Mgmt/ApiTokens/ApiTokenSearch.php
deleted file mode 100644
index 7c2562cf..00000000
--- a/lib/SP/Mgmt/ApiTokens/ApiTokenSearch.php
+++ /dev/null
@@ -1,84 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\ApiTokens;
-
-use SP\Core\Acl\Acl;
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class ApiTokenSearch
- *
- * @package SP\Mgmt\ApiTokens
- */
-class ApiTokenSearch extends ApiTokenBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $query = /** @lang SQL */
- 'SELECT authtoken_id,
- authtoken_userId,
- actionId,
- authtoken_token,
- CONCAT(user_name, \' (\', user_login, \')\') AS user_login
- FROM authTokens
- LEFT JOIN usrData ON user_id = authtoken_userId ';
-
- $Data = new QueryData();
-
- if ($SearchData->getSeachString() !== '') {
- $search = '%' . $SearchData->getSeachString() . '%';
- $query .= ' WHERE user_login LIKE ?';
-
- $Data->addParam($search);
- }
-
- $query .= ' ORDER BY user_login';
- $query .= ' LIMIT ?, ?';
-
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- $Data->setQuery($query);
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- foreach ($queryRes as $token) {
- $token->authtoken_actionId = Acl::getActionInfo($token->authtoken_actionId);
- }
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ApiTokens/ApiTokensUtil.php b/lib/SP/Mgmt/ApiTokens/ApiTokensUtil.php
deleted file mode 100644
index c941a789..00000000
--- a/lib/SP/Mgmt/ApiTokens/ApiTokensUtil.php
+++ /dev/null
@@ -1,59 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\ApiTokens;
-
-use SP\Core\Acl\Acl;
-use SP\Core\Acl\ActionsInterface;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class ApiTokensUtil con utilidades para la gestión de tokens API
- *
- * @package SP\Api
- */
-class ApiTokensUtil
-{
- /**
- * Devuelver un array de acciones posibles para los tokens
- *
- * @return array
- */
- public static function getTokenActions()
- {
- $actions = [
- ActionsInterface::ACCOUNT_SEARCH => Acl::getActionInfo(ActionsInterface::ACCOUNT_SEARCH),
- ActionsInterface::ACCOUNT_VIEW => Acl::getActionInfo(ActionsInterface::ACCOUNT_VIEW),
- ActionsInterface::ACCOUNT_VIEW_PASS => Acl::getActionInfo(ActionsInterface::ACCOUNT_VIEW_PASS),
- ActionsInterface::ACCOUNT_DELETE => Acl::getActionInfo(ActionsInterface::ACCOUNT_DELETE),
- ActionsInterface::ACCOUNT_CREATE => Acl::getActionInfo(ActionsInterface::ACCOUNT_CREATE),
- ActionsInterface::BACKUP_CONFIG => Acl::getActionInfo(ActionsInterface::BACKUP_CONFIG),
- ActionsInterface::CATEGORY => Acl::getActionInfo(ActionsInterface::CATEGORY),
- ActionsInterface::CLIENT => Acl::getActionInfo(ActionsInterface::CLIENT)
- ];
-
- return $actions;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Categories/Category.php b/lib/SP/Mgmt/Categories/Category.php
deleted file mode 100644
index e85a10a7..00000000
--- a/lib/SP/Mgmt/Categories/Category.php
+++ /dev/null
@@ -1,255 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Categories;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\CategoryData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Esta clase es la encargada de realizar las operaciones sobre las categorías de sysPass.
- *
- * @property CategoryData $itemData
- */
-class Category extends CategoryBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Categoría duplicada', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO Category SET name = ?, description = ?, hash = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->setOnErrorMessage(__('Error al crear la categoría', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * Comprobar duplicados
- *
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM Category WHERE hash = ? OR name = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->addParam($this->itemData->getName());
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes !== false) {
- if ($Data->getQueryNumRows() === 0) {
- return false;
- } elseif ($Data->getQueryNumRows() === 1) {
- $this->itemData->setId($queryRes->category_id);
- }
- }
-
- return true;
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM Category WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar la categoría', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Categoría no encontrada', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT account_id FROM Account WHERE account_categoryId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @param $id int
- * @return CategoryData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id, name, description FROM Category WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setMapClassName($this->getDataModel());
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Nombre de categoría duplicado', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'UPDATE Category
- SET name = ?,
- description = ?,
- hash = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar la categoría', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM Category WHERE (hash = ? OR name = ?) AND id <> ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @return CategoryData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id, name, description, hash FROM Category ORDER BY name';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return CategoryData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT id, name, description FROM Category WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setParams($ids);
- $Data->setMapClassName($this->getDataModel());
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Categories/CategoryBase.php b/lib/SP/Mgmt/Categories/CategoryBase.php
deleted file mode 100644
index b6f5cf91..00000000
--- a/lib/SP/Mgmt/Categories/CategoryBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Categories;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\CategoryData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class CategoryBase
- *
- * @package SP\Mgmt\Categories
- */
-abstract class CategoryBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(CategoryData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Categories/CategorySearch.php b/lib/SP/Mgmt/Categories/CategorySearch.php
deleted file mode 100644
index 1b549e34..00000000
--- a/lib/SP/Mgmt/Categories/CategorySearch.php
+++ /dev/null
@@ -1,75 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Categories;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class CategorySearch
- *
- * @package SP\Mgmt\Categories
- */
-class CategorySearch extends CategoryBase implements ItemSearchInterface
-{
- /**
- * Obtiene el listado de categorías mediante una búsqueda
- *
- * @param ItemSearchData $SearchData
- * @return array con el id de categoria como clave y en nombre como valor
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('id, name, description');
- $Data->setFrom('categories');
- $Data->setOrder('name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('name LIKE ? OR description LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- /** @var array $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Customers/Customer.php b/lib/SP/Mgmt/Customers/Customer.php
deleted file mode 100644
index 27c6fd7d..00000000
--- a/lib/SP/Mgmt/Customers/Customer.php
+++ /dev/null
@@ -1,290 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Customers;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\AccountUtil;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\ClientData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Esta clase es la encargada de realizar las operaciones sobre los clientes de sysPass
- *
- * @property ClientData $itemData
- */
-class Customer extends CustomerBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Cliente duplicado', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO Client
- SET name = ?,
- description = ?,
- isGlobal = ?,
- hash = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->itemData->getIsGlobal());
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->setOnErrorMessage(__('Error al crear el cliente', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM Client WHERE hash = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes !== false) {
- if ($Data->getQueryNumRows() === 0) {
- return false;
- } elseif ($Data->getQueryNumRows() === 1) {
- $this->itemData->setId($queryRes->customer_id);
- }
- }
-
- return true;
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- if ($this->checkInUse($id)) {
- throw new SPException(__('No es posible eliminar', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'DELETE FROM Client WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar el cliente', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Cliente no encontrado', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT account_id FROM Account WHERE account_customerId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @param $id int
- * @return ClientData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id, name, description, isGlobal FROM Client WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Cliente duplicado', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'UPDATE Client
- SET name = ?,
- description = ?,
- isGlobal = ?,
- hash = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->itemData->getIsGlobal());
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el cliente', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM Client WHERE hash = ? AND id <> ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->makeItemHash($this->itemData->getName()));
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @return ClientData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id, name, description, isGlobal FROM Client ORDER BY name';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los clientes visibles por el usuario
- *
- * @return array
- */
- public function getItemsForSelectByUser()
- {
- $Data = new QueryData();
-
- // Acotar los resultados por usuario
- $queryWhere = AccountUtil::getAccountFilterUser($Data, $this->session);
-
- $query = /** @lang SQL */
- 'SELECT C.id as id, C.name as name
- FROM Account A
- RIGHT JOIN Client C ON C.id = A.clientId
- WHERE A.clientId IS NULL
- OR isGlobal = 1
- OR (' . implode(' AND ', $queryWhere) . ')
- GROUP BY id
- ORDER BY name';
-
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return ClientData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT id, name, description, isGlobal FROM Client WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
diff --git a/lib/SP/Mgmt/Customers/CustomerBase.php b/lib/SP/Mgmt/Customers/CustomerBase.php
deleted file mode 100644
index 4ce773b6..00000000
--- a/lib/SP/Mgmt/Customers/CustomerBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Customers;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\ClientData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class CustomerBase
- *
- * @package SP\Mgmt\Customers
- */
-abstract class CustomerBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(ClientData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Customers/CustomerSearch.php b/lib/SP/Mgmt/Customers/CustomerSearch.php
deleted file mode 100644
index 5173346d..00000000
--- a/lib/SP/Mgmt/Customers/CustomerSearch.php
+++ /dev/null
@@ -1,72 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Customers;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class CustomerSearch
- *
- * @package SP\Mgmt\Customers
- */
-class CustomerSearch extends CustomerBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('id, name, description');
- $Data->setFrom('customers');
- $Data->setOrder('name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('name LIKE ? OR description LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Files/File.php b/lib/SP/Mgmt/Files/File.php
deleted file mode 100644
index 8678641f..00000000
--- a/lib/SP/Mgmt/Files/File.php
+++ /dev/null
@@ -1,267 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Files;
-
-use SP\Account\AccountUtil;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\FileData;
-use SP\DataModel\FileExtData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\ImageUtil;
-
-defined('APP_ROOT') || die();
-
-/**
- * Esta clase es la encargada de realizar operaciones con archivos de las cuentas de sysPass
- *
- * @property FileData $itemData
- */
-class File extends FileBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \phpmailer\phpmailerException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- $query = /** @lang SQL */
- 'INSERT INTO accFiles
- SET accountId = ?,
- name = ?,
- type = ?,
- size = ?,
- content = ?,
- extension = ?,
- thumb = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAccfileAccountId());
- $Data->addParam($this->itemData->getAccfileName());
- $Data->addParam($this->itemData->getAccfileType());
- $Data->addParam($this->itemData->getAccfileSize());
- $Data->addParam($this->itemData->getAccfileContent());
- $Data->addParam($this->itemData->getAccfileExtension());
- $Data->setOnErrorMessage(__('No se pudo guardar el archivo', false));
-
- if (FileUtil::isImage($this->itemData)) {
- $thumbnail = ImageUtil::createThumbnail($this->itemData->getAccfileContent());
-
- if ($thumbnail !== false) {
- $Data->addParam($thumbnail);
- } else {
- $Data->addParam('no_thumb');
- }
- } else {
- $Data->addParam('no_thumb');
- }
-
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Subir Archivo', false));
- $LogMessage->addDetails(__('Cuenta', false), AccountUtil::getAccountNameById($this->itemData->getAccfileAccountId()));
- $LogMessage->addDetails(__('Archivo', false), $this->itemData->getAccfileName());
- $LogMessage->addDetails(__('Tipo', false), $this->itemData->getAccfileType());
- $LogMessage->addDetails(__('Tamaño', false), $this->itemData->getRoundSize() . 'KB');
-
- DbWrapper::getQuery($Data);
-
- $LogMessage->addDescription(__('Archivo subido', false));
- $Log->writeLog();
-
- Email::sendEmail($LogMessage);
-
- return true;
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- // Eliminamos el archivo de la BBDD
- $query = /** @lang SQL */
- 'DELETE FROM accFiles WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar el archivo', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Archivo no encontrado', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @param $id
- * @return FileExtData
- */
- public function getInfoById($id)
- {
- $query = /** @lang SQL */
- 'SELECT name,
- size,
- type,
- accountId,
- extension,
- account_name,
- name
- FROM accFiles
- LEFT JOIN Account ON account_id = accountId
- LEFT JOIN customers ON id = account_customerId
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName(FileExtData::class);
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return mixed
- */
- public function update()
- {
- // TODO: Implement update() method.
- }
-
- /**
- * @param $id int
- * @return FileExtData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT name,
- size,
- type,
- accountId,
- content,
- thumb,
- extension,
- account_name,
- name
- FROM accFiles
- LEFT JOIN Account ON account_id = accountId
- LEFT JOIN customers ON id = account_customerId
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName(FileExtData::class);
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return FileExtData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT name,
- size,
- type,
- accountId,
- content,
- thumb,
- extension,
- account_name,
- name
- FROM accFiles
- LEFT JOIN Account ON account_id = accountId
- LEFT JOIN customers ON id = account_customerId
- WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName(FileExtData::class);
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Files/FileBase.php b/lib/SP/Mgmt/Files/FileBase.php
deleted file mode 100644
index fa34709e..00000000
--- a/lib/SP/Mgmt/Files/FileBase.php
+++ /dev/null
@@ -1,51 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Files;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\FileData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class FileBase
- *
- * @package SP\Mgmt\Files
- */
-abstract class FileBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(FileData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Files/FileSearch.php b/lib/SP/Mgmt/Files/FileSearch.php
deleted file mode 100644
index bfbb3f45..00000000
--- a/lib/SP/Mgmt/Files/FileSearch.php
+++ /dev/null
@@ -1,74 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Files;
-
-use SP\DataModel\FileExtData;
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class FileSearch
- *
- * @package SP\Mgmt\Files
- */
-class FileSearch extends FileBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setMapClassName(FileExtData::class);
- $Data->setSelect('accfile_id, accfile_name, CONCAT(ROUND(accfile_size/1000, 2), "KB") AS accfile_size, accfile_thumb, accfile_type, account_name, name');
- $Data->setFrom('accFiles JOIN accounts ON account_id = accfile_accountId JOIN customers ON id = account_customerId');
- $Data->setOrder('accfile_name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('accfile_name LIKE ? OR accfile_type LIKE ? OR account_name LIKE ? OR name LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- $Data->addParam($search);
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Files/FileUtil.php b/lib/SP/Mgmt/Files/FileUtil.php
deleted file mode 100644
index cc94a401..00000000
--- a/lib/SP/Mgmt/Files/FileUtil.php
+++ /dev/null
@@ -1,115 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Files;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\FileData;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class FileUtil
- *
- * @package SP\Mgmt\Files
- */
-class FileUtil
-{
- /**
- * @var array
- */
- public static $imageExtensions = ['JPG', 'PNG', 'GIF'];
-
- /**
- * Obtener el listado de archivos de una cuenta.
- *
- * @param int $accountId Con el Id de la cuenta
- * @return FileData[]|array Con los archivos de la cuenta.
- */
- public static function getAccountFiles($accountId)
- {
- $query = 'SELECT id,
- name,
- size,
- thumb,
- type
- FROM accFiles
- WHERE accountId = ?';
-
- $Data = new QueryData();
- $Data->setMapClassName(FileData::class);
- $Data->setQuery($query);
- $Data->addParam($accountId);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Obtener el número de archivo de una cuenta.
- *
- * @param int $accountId con el Id de la cuenta
- * @return int con el número de archivos
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function countAccountFiles($accountId)
- {
- $query = 'SELECT id FROM accFiles WHERE accountId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($accountId);
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows();
- }
-
- /**
- * Elimina los archivos de una cuenta en la BBDD.
- *
- * @param int $accountId con el Id de la cuenta
- * @throws SPException
- */
- public static function deleteAccountFiles($accountId)
- {
- $query = 'DELETE FROM accFiles WHERE accountId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($accountId);
- $Data->setOnErrorMessage(__('Error al eliminar archivos asociados a la cuenta', false));
-
- DbWrapper::getQuery($Data);
- }
-
- /**
- * @param FileData $FileData
- * @return bool
- */
- public static function isImage(FileData $FileData)
- {
- return in_array(mb_strtoupper($FileData->getExtension()), self::$imageExtensions, true);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/Group.php b/lib/SP/Mgmt/Groups/Group.php
deleted file mode 100644
index 14f515a5..00000000
--- a/lib/SP/Mgmt/Groups/Group.php
+++ /dev/null
@@ -1,278 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserGroupData;
-use SP\DataModel\UserToUserGroupData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Esta clase es la encargada de realizar las operaciones sobre los grupos de usuarios.
- *
- * @property UserGroupData $itemData
- */
-class Group extends GroupBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Nombre de grupo duplicado', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO usrGroups SET usergroup_name = ?, usergroup_description = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->setOnErrorMessage(__('Error al crear el grupo', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- $GroupUsers = new UserToUserGroupData();
- $GroupUsers->setUserGroupId($this->itemData->getId());
- $GroupUsers->setUsers($this->itemData->getUsers());
-
- GroupUsers::getItem($GroupUsers)->add();
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT usergroup_name FROM usrGroups WHERE UPPER(usergroup_name) = ?';
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- if ($this->checkInUse($id)) {
- throw new SPException(__('Grupo en uso', false), SPException::WARNING);
- }
-
- $query = /** @lang SQL */
- 'DELETE FROM usrGroups WHERE usergroup_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar el grupo', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Grupo no encontrado', false), SPException::INFO);
- }
-
- GroupUsers::getItem()->delete($id);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_groupId as groupId
- FROM usrData WHERE user_groupId = ?
- UNION ALL
- SELECT userGroupId as groupId
- FROM UserToUserGroup WHERE userGroupId = ?
- UNION ALL
- SELECT userGroupId as groupId
- FROM AccountToUserGroup WHERE userGroupId = ?
- UNION ALL
- SELECT account_userGroupId as groupId
- FROM Account WHERE account_userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->addParam($id);
- $Data->addParam($id);
- $Data->addParam($id);
-
- DbWrapper::getQuery($Data);
-
- return ($Data->getQueryNumRows() > 1);
- }
-
- /**
- * @param $id int
- * @return UserGroupData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT usergroup_id, usergroup_name, usergroup_description FROM usrGroups WHERE usergroup_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \phpmailer\phpmailerException
- * @throws \SP\Core\Exceptions\InvalidClassException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Nombre de grupo duplicado', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'UPDATE usrGroups SET usergroup_name = ?, usergroup_description = ? WHERE usergroup_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el grupo', false));
-
- DbWrapper::getQuery($Data);
-
- $GroupUsers = new UserToUserGroupData();
- $GroupUsers->setUserGroupId($this->itemData->getId());
- $GroupUsers->setUsers($this->itemData->getUsers());
-
- GroupUsers::getItem($GroupUsers)->update();
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT usergroup_name FROM usrGroups WHERE UPPER(usergroup_name) = ? AND usergroup_id <> ?';
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @return UserGroupData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT usergroup_id,
- usergroup_name,
- usergroup_description
- FROM usrGroups
- ORDER BY usergroup_name';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return UserGroupData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT usergroup_id, usergroup_name, usergroup_description FROM usrGroups WHERE usergroup_id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
diff --git a/lib/SP/Mgmt/Groups/GroupAccounts.php b/lib/SP/Mgmt/Groups/GroupAccounts.php
deleted file mode 100644
index 452561e3..00000000
--- a/lib/SP/Mgmt/Groups/GroupAccounts.php
+++ /dev/null
@@ -1,193 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\AccountToUserGroupData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class GroupAccounts
- *
- * @package SP\Mgmt\Groups
- * @property AccountToUserGroupData $itemData
- */
-class GroupAccounts extends GroupAccountsBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- $this->delete($this->itemData->getAccountId());
- $this->add();
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM AccountToUserGroup WHERE accountId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar grupos asociados a la cuenta', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- if (!is_array($this->itemData->getGroups())
- || count($this->itemData->getGroups()) === 0
- ) {
- return $this;
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO AccountToUserGroup (accountId, userGroupId) VALUES ' . $this->getParamsFromArray($this->itemData->getGroups(), '(?,?)');
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- foreach ($this->itemData->getGroups() as $group) {
- $Data->addParam($this->itemData->getAccountId());
- $Data->addParam($group);
- }
-
- $Data->setOnErrorMessage(__('Error al actualizar los grupos secundarios', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return array
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId, accountId FROM AccountToUserGroup WHERE userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return bool
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId FROM AccountToUserGroup WHERE userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- DbWrapper::getResults($Data);
-
- return ($Data->getQueryNumRows() > 1);
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * @param $id int
- * @return AccountToUserGroupData[]
- */
- public function getByAccountId($id)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId, accountId FROM AccountToUserGroup WHERE accountId = ?';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupAccountsBase.php b/lib/SP/Mgmt/Groups/GroupAccountsBase.php
deleted file mode 100644
index 0ba65591..00000000
--- a/lib/SP/Mgmt/Groups/GroupAccountsBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\AccountToUserGroupData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class GroupAccountsBase
- *
- * @package SP\Mgmt\Groups
- */
-abstract class GroupAccountsBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(AccountToUserGroupData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupAccountsUtil.php b/lib/SP/Mgmt/Groups/GroupAccountsUtil.php
deleted file mode 100644
index 53765388..00000000
--- a/lib/SP/Mgmt/Groups/GroupAccountsUtil.php
+++ /dev/null
@@ -1,81 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\UserGroupData;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class GroupAccountsUtil
- *
- * @package SP\Mgmt\Groups
- */
-class GroupAccountsUtil
-{
- /**
- * Obtiene el listado con el nombre de los grupos de una cuenta.
- *
- * @param int $accountId con el Id de la cuenta
- * @return UserGroupData[]
- */
- public static function getGroupsInfoForAccount($accountId)
- {
- $query = /** @lang SQL */
- 'SELECT G.id, G.name
- FROM AccountToUserGroup AUG
- INNER JOIN UserGroup G ON AUG.userGroupId = G.id
- WHERE AUG.accountId = ?
- ORDER BY G.name';
-
- $Data = new QueryData();
- $Data->setMapClassName(UserGroupData::class);
- $Data->setQuery($query);
- $Data->addParam($accountId);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Obtiene el listado de grupos de una cuenta.
- *
- * @param int $accountId con el Id de la cuenta
- * @return array Con los ids de los grupos
- */
- public static function getGroupsForAccount($accountId)
- {
- $GroupAccountsData = GroupAccounts::getItem()->getByAccountId($accountId);
-
- $groups = [];
-
- foreach ($GroupAccountsData as $Group) {
- $groups[] = (int)$Group->getUserGroupId();
- }
-
- return $groups;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupBase.php b/lib/SP/Mgmt/Groups/GroupBase.php
deleted file mode 100644
index e370134a..00000000
--- a/lib/SP/Mgmt/Groups/GroupBase.php
+++ /dev/null
@@ -1,51 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\UserGroupData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class GroupBase
- *
- * @package SP\Mgmt\Groups
- */
-abstract class GroupBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserGroupData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupSearch.php b/lib/SP/Mgmt/Groups/GroupSearch.php
deleted file mode 100644
index 3649ffe9..00000000
--- a/lib/SP/Mgmt/Groups/GroupSearch.php
+++ /dev/null
@@ -1,73 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class GroupSearch
- *
- * @package SP\Mgmt\Groups
- */
-class GroupSearch extends GroupBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setSelect('usergroup_id, usergroup_name, usergroup_description');
- $Data->setFrom('usrGroups');
- $Data->setOrder('usergroup_name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('usergroup_name LIKE ? OR usergroup_description LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupUsers.php b/lib/SP/Mgmt/Groups/GroupUsers.php
deleted file mode 100644
index c5ec5dcc..00000000
--- a/lib/SP/Mgmt/Groups/GroupUsers.php
+++ /dev/null
@@ -1,220 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserToUserGroupData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class GroupUser
- *
- * @package SP\Mgmt\Groups
- * @property UserToUserGroupData $itemData
- */
-class GroupUsers extends GroupUsersBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- $this->delete($this->itemData->getUserGroupId());
- $this->add();
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM UserToUserGroup WHERE userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar los usuarios del grupo', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- if (!is_array($this->itemData->getUsers())
- || count($this->itemData->getUsers()) === 0
- ) {
- return $this;
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO UserToUserGroup (userId, userGroupId) VALUES ' . $this->getParamsFromArray($this->itemData->getUsers(), '(?,?)');
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- foreach ($this->itemData->getUsers() as $user) {
- $Data->addParam($user);
- $Data->addParam($this->itemData->getUserGroupId());
- }
-
- $Data->setOnErrorMessage(__('Error al asignar los usuarios al grupo', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return UserToUserGroupData[]
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId, userId FROM UserToUserGroup WHERE userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los usuarios que están asociados al grupo
- *
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- DbWrapper::getResults($Data);
-
- return ($Data->getQueryNumRows() > 1);
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-
- /**
- * Comprobar si un usuario está en el grupo
- *
- * @param $userId
- * @param $groupId
- * @return bool
- */
- public function checkUserInGroup($groupId, $userId)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = ? AND userId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($groupId);
- $Data->addParam($userId);
-
- DbWrapper::getResults($Data);
-
- return ($Data->getQueryNumRows() === 1);
- }
-
- /**
- * Devolver los grupos a los que pertenece el usuario
- *
- * @param $userId
- * @return array
- */
- public function getGroupsForUser($userId)
- {
- $query = /** @lang SQL */
- 'SELECT userGroupId AS groupId FROM UserToUserGroup WHERE userId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userId);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupUsersBase.php b/lib/SP/Mgmt/Groups/GroupUsersBase.php
deleted file mode 100644
index 5a50f9f7..00000000
--- a/lib/SP/Mgmt/Groups/GroupUsersBase.php
+++ /dev/null
@@ -1,51 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\UserToUserGroupData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class GroupUserBase
- *
- * @package SP\Mgmt\Groups
- */
-abstract class GroupUsersBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserToUserGroupData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Groups/GroupUtil.php b/lib/SP/Mgmt/Groups/GroupUtil.php
deleted file mode 100644
index e49402cc..00000000
--- a/lib/SP/Mgmt/Groups/GroupUtil.php
+++ /dev/null
@@ -1,57 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Groups;
-
-
-use SP\DataModel\UserGroupData;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class GroupsUtil
- *
- * @package SP\Mgmt\Groups
- */
-class GroupUtil
-{
- /**
- * Obtener el id de un grupo por a partir del nombre.
- *
- * @param int $name con el nombre del grupo
- * @return UserGroupData|false
- */
- public static function getGroupIdByName($name)
- {
- $query = /** @lang SQL */
- 'SELECT usergroup_id, usergroup_name FROM usrGroups WHERE usergroup_name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName(UserGroupData::class);
- $Data->setQuery($query);
- $Data->addParam($name);
-
- return DbWrapper::getResults($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemBaseInterface.php b/lib/SP/Mgmt/ItemBaseInterface.php
deleted file mode 100644
index c5995e68..00000000
--- a/lib/SP/Mgmt/ItemBaseInterface.php
+++ /dev/null
@@ -1,73 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-use SP\DataModel\DataModelInterface;
-
-/**
- * Interface ItemBaseInterface
- *
- * @package SP\Mgmt
- */
-interface ItemBaseInterface
-{
- /**
- * Devolver la instancia almacenada de la clase. Si no existe, se crea
- *
- * @param $itemData
- * @return static
- */
- public static function getItem($itemData = null);
-
- /**
- * Devolver una nueva instancia de la clase
- *
- * @param null $itemData
- * @return static
- */
- public static function getNewItem($itemData = null);
-
- /**
- * Devolver los datos del elemento
- *
- * @return mixed|DataModelInterface
- */
- public function getItemData();
-
- /**
- * Establecer los datos del elemento
- *
- * @param mixed|DataModelInterface $itemData
- * @return static
- */
- public function setItemData($itemData);
-
- /**
- * Obtener el nombre de la clase para el modelo de datos
- *
- * @return string
- */
- public function getDataModel();
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemBaseTrait.php b/lib/SP/Mgmt/ItemBaseTrait.php
deleted file mode 100644
index d5f5b408..00000000
--- a/lib/SP/Mgmt/ItemBaseTrait.php
+++ /dev/null
@@ -1,165 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-use SP\Config\Config;
-use SP\Core\Context\SessionContext;
-use SP\Core\DiFactory;
-use SP\Core\Exceptions\InvalidClassException;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\DataModelInterface;
-use SP\Storage\Database;
-
-/**
- * Class ItemBaseTrait
- *
- * @package SP\Mgmt
- */
-trait ItemBaseTrait
-{
- use SP\Core\Dic\InjectableTrait;
-
- /**
- * @var string
- */
- protected $dataModel;
- /**
- * @var mixed|DataModelInterface
- */
- protected $itemData;
- /** @var SessionContext */
- protected $session;
-
- /**
- * Constructor.
- *
- * @param null $itemData
- * @throws InvalidClassException
- */
- public function __construct($itemData = null)
- {
- $this->injectDependencies();
-
- $this->init();
-
- if (null !== $itemData) {
- $this->setItemData($itemData);
- } else {
- $this->itemData = new $this->dataModel();
- }
- }
-
- /**
- * Devolver la instancia almacenada de la clase. Si no existe, se crea
- *
- * @param $itemData
- * @return static
- */
- final public static function getItem($itemData = null)
- {
- return DiFactory::getItem(static::class, $itemData);
- }
-
- /**
- * Devolver una nueva instancia de la clase
- *
- * @param null $itemData
- * @return static
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- final public static function getNewItem($itemData = null)
- {
- return new static($itemData);
- }
-
- /**
- * Devolver los datos del elemento
- *
- * @return mixed|DataModelInterface
- */
- public function getItemData()
- {
- return is_object($this->itemData) ? $this->itemData : new $this->dataModel();
- }
-
- /**
- * @param $itemData
- * @return $this
- * @throws InvalidClassException
- */
- final public function setItemData($itemData)
- {
- if (null !== $this->dataModel && ($itemData instanceof $this->dataModel) === false) {
- throw new InvalidClassException(SPException::ERROR, $this->dataModel);
- }
-
- $this->itemData = $itemData;
-
- return $this;
- }
-
- /**
- * @return string
- */
- public function getDataModel()
- {
- return $this->dataModel;
- }
-
- /**
- * @param string $dataModel
- * @return static
- * @throws InvalidClassException
- */
- final protected function setDataModel($dataModel)
- {
- if (false === class_exists($dataModel)) {
- throw new InvalidClassException(SPException::ERROR, $dataModel);
- }
-
- $this->dataModel = $dataModel;
-
- return $this;
- }
-
- /**
- * @param Config $config
- * @param Database $db
- * @param SessionContext $session
- */
- public function inject(Config $config, Database $db, SessionContext $session)
- {
- $this->ConfigData = $config->getConfigData();
- $this->db = $db;
- $this->session = $session;
- }
-
- /**
- * Inicializar la clase
- *
- * @return void
- */
- abstract protected function init();
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemInterface.php b/lib/SP/Mgmt/ItemInterface.php
deleted file mode 100644
index 912f280d..00000000
--- a/lib/SP/Mgmt/ItemInterface.php
+++ /dev/null
@@ -1,111 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-defined('APP_ROOT') || die();
-
-/**
- * Interface Item para la implementación de clases de elementos
- *
- * @package SP\Mgmt
- */
-interface ItemInterface
-{
- /**
- * @param $itemData
- * @return static
- */
- public static function getItem($itemData = null);
-
- /**
- * @return mixed
- */
- public function add();
-
- /**
- * @param $id int|array
- * @return mixed
- */
- public function delete($id);
-
- /**
- * @return mixed
- */
- public function update();
-
- /**
- * @param $id int
- * @return mixed
- */
- public function getById($id);
-
- /**
- * @return mixed
- */
- public function getAll();
-
- /**
- * @param $itemData
- * @return mixed
- */
- public function setItemData($itemData);
-
- /**
- * @return mixed
- */
- public function getItemData();
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id);
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate();
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd();
-
- /**
- * Eliminar elementos en lote
- *
- * @param array $ids
- * @return $this
- */
- public function deleteBatch(array $ids);
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids);
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemSearchInterface.php b/lib/SP/Mgmt/ItemSearchInterface.php
deleted file mode 100644
index 07679e32..00000000
--- a/lib/SP/Mgmt/ItemSearchInterface.php
+++ /dev/null
@@ -1,43 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-use SP\DataModel\ItemSearchData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Interface ItemSearchInterface para la implementación de clases con búsqueda de elementos
- *
- * @package SP\Mgmt
- */
-interface ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData);
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemSelectInterface.php b/lib/SP/Mgmt/ItemSelectInterface.php
deleted file mode 100644
index 1fe7644c..00000000
--- a/lib/SP/Mgmt/ItemSelectInterface.php
+++ /dev/null
@@ -1,38 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-/**
- * Interface ItemSelectInterface
- *
- * @package SP\Mgmt
- */
-interface ItemSelectInterface
-{
- /**
- * @return array
- */
- public function getItemsForSelect();
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/ItemTrait.php b/lib/SP/Mgmt/ItemTrait.php
deleted file mode 100644
index c633c555..00000000
--- a/lib/SP/Mgmt/ItemTrait.php
+++ /dev/null
@@ -1,123 +0,0 @@
-.
- */
-
-namespace SP\Mgmt;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\DataModelInterface;
-use SP\Storage\DBUtil;
-
-/**
- * Class ItemTrait
- *
- * @package SP\Mgmt
- */
-trait ItemTrait
-{
- /**
- * Cache de elementos para select
- *
- * @var array
- */
- private static $itemsSelectCache;
-
- /**
- * Devolver los elementos para un campo select
- *
- * @param bool $useCache Usar la cache de elementos si está creada
- * @return array
- */
- public function getItemsForSelect($useCache = true)
- {
- // Usar cache si está creada
- if ($useCache === true && is_array(self::$itemsSelectCache)) {
- return self::$itemsSelectCache;
- }
-
- self::$itemsSelectCache = [];
-
- /** @var DataModelInterface $item */
- /** @var ItemInterface $this */
- foreach ($this->getAll() as $item) {
- $obj = new \stdClass();
- $obj->id = (int)$item->getId();
- $obj->name = $item->getName();
-
- self::$itemsSelectCache[] = $obj;
- }
-
- return self::$itemsSelectCache;
- }
-
- /**
- * Eliminar elementos en lotes
- *
- * @param $ids
- * @return array
- */
- public function deleteBatch(array $ids)
- {
- $items = $this->getByIdBatch($ids);
-
- /** @var DataModelInterface[] $items */
- foreach ($items as $key => $item) {
- try {
- $this->delete($item->getId());
- } catch (SPException $e) {
- unset($items[$key]);
- }
- }
-
- return $items;
- }
-
- /**
- * Crear un hash con el nombre del elemento.
- *
- * Esta función crear un hash para detectar nombres de elementos duplicados mediante
- * la eliminación de carácteres especiales y capitalización
- *
- * @param $name
- * @return string con el hash generado
- */
- protected function makeItemHash($name)
- {
- $charsSrc = ['.', ' ', '_', ', ', '-', ';', '\'', '"', ':', '(', ')', '|', '/'];
- $newValue = strtolower(str_replace($charsSrc, '', DBUtil::escape($name)));
-
- return md5($newValue);
- }
-
- /**
- * Devuelve una cadena con los parámetros para una consulta SQL desde un array
- *
- * @param array $items
- * @param string $string Cadena a utilizar para los parámetros
- * @return string
- */
- protected function getParamsFromArray(array $items, $string = '?')
- {
- return implode(',', array_fill(0, count($items), $string));
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Notices/Notice.php b/lib/SP/Mgmt/Notices/Notice.php
deleted file mode 100644
index 80cddf8e..00000000
--- a/lib/SP/Mgmt/Notices/Notice.php
+++ /dev/null
@@ -1,390 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Notices;
-
-use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
-use SP\DataModel\NotificationData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class Notice
- *
- * @package SP\Mgmt\Notices
- * @property NotificationData $itemData
- * @method NotificationData getItemData()
- */
-class Notice extends NoticeBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- $query = /** @lang SQL */
- 'INSERT INTO Notification
- SET type = ?,
- component = ?,
- description = ?,
- date = UNIX_TIMESTAMP(),
- checked = 0,
- userId = ?,
- sticky = ?,
- onlyAdmin = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getType());
- $Data->addParam($this->itemData->getComponent());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->itemData->getUserId());
- $Data->addParam($this->itemData->isSticky());
- $Data->addParam($this->itemData->isOnlyAdmin());
- $Data->setOnErrorMessage(__('Error al crear la notificación', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = 'DELETE FROM Notification WHERE id = ? AND BIN(sticky) = 0 LIMIT 1';
-
- if (SessionFactory::getUserData()->isAdminApp()) {
- $query = 'DELETE FROM Notification WHERE id = ? LIMIT 1';
- }
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar la notificación', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Notificación no encontrada', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE Notification
- SET type = ?,
- component = ?,
- description = ?,
- date = UNIX_TIMESTAMP(),
- checked = 0,
- userId = ?,
- sticky = ?,
- onlyAdmin = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getType());
- $Data->addParam($this->itemData->getComponent());
- $Data->addParam($this->itemData->getDescription());
- $Data->addParam($this->itemData->getUserId());
- $Data->addParam($this->itemData->isSticky());
- $Data->addParam($this->itemData->isOnlyAdmin());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al modificar la notificación', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return NotificationData
- * @throws SPException
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- type,
- component,
- description,
- FROM_UNIXTIME(date) AS notice_date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
- $Data->addParam($id);
-
- try {
- $queryRes = DbWrapper::getResults($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener la notificación', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @return NotificationData[]
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id
- notice_type,
- component,
- description,
- FROM_UNIXTIME(date) AS notice_date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
-
- try {
- $queryRes = DbWrapper::getResultsArray($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Marcar una notificación como leída
- *
- * @param $id
- * @return $this
- * @throws SPException
- */
- public function setChecked($id)
- {
- $query = /** @lang SQL */
- 'UPDATE Notification SET checked = 1 WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al modificar la notificación', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * Devolver las notificaciones de un usuario para una fecha y componente determinados
- *
- * @return mixed
- * @throws SPException
- */
- public function getByUserCurrentDate()
- {
- $query = /** @lang SQL */
- 'SELECT type,
- component,
- description,
- date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification
- WHERE component = ? AND
- (UNIX_TIMESTAMP() - date) <= 86400 AND
- userId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
- $Data->addParam($this->itemData->getComponent());
- $Data->addParam($this->itemData->getUserId());
-
- try {
- $queryRes = DbWrapper::getResultsArray($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @return NotificationData[]
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getAllForUser()
- {
- $query = /** @lang SQL */
- 'SELECT id,
- type,
- component,
- description,
- FROM_UNIXTIME(date) AS notice_date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification
- WHERE userId = ? OR (userId = NULL AND BIN(onlyAdmin) = 0) OR BIN(sticky) = 1
- ORDER BY date DESC ';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
- $Data->addParam(SessionFactory::getUserData()->getId());
-
- try {
- $queryRes = DbWrapper::getResultsArray($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @return NotificationData[]
- * @throws SPException
- */
- public function getAllActiveForUser()
- {
- $query = /** @lang SQL */
- 'SELECT id,
- type,
- component,
- description,
- FROM_UNIXTIME(date) AS notice_date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification
- WHERE (userId = ? OR BIN(sticky) = 1)
- AND BIN(onlyAdmin) = 0
- AND BIN(checked) = 0
- ORDER BY date DESC ';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
- $Data->addParam(SessionFactory::getUserData()->getId());
-
- try {
- $queryRes = DbWrapper::getResultsArray($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- type,
- component,
- description,
- FROM_UNIXTIME(date) AS notice_date,
- userId,
- BIN(checked) AS notice_checked,
- BIN(sticky) as notice_sticky,
- BIN(onlyAdmin) AS notice_onlyAdmin
- FROM Notification
- WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Notices/NoticeBase.php b/lib/SP/Mgmt/Notices/NoticeBase.php
deleted file mode 100644
index daacd336..00000000
--- a/lib/SP/Mgmt/Notices/NoticeBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Notices;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\NotificationData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class NoticeBase
- *
- * @package SP\Mgmt\Notices
- */
-abstract class NoticeBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(NotificationData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Notices/NoticeSearch.php b/lib/SP/Mgmt/Notices/NoticeSearch.php
deleted file mode 100644
index 828d08d4..00000000
--- a/lib/SP/Mgmt/Notices/NoticeSearch.php
+++ /dev/null
@@ -1,119 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Notices;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\SessionFactory;
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class NoticeSearch
- *
- * @package SP\Mgmt\Categories
- */
-class NoticeSearch extends NoticeBase implements ItemSearchInterface
-{
- /**
- * Obtiene el listado de categorías mediante una búsqueda
- *
- * @param ItemSearchData $SearchData
- * @return array con el id de categoria como clave y en nombre como valor
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('notice_id, notice_type, notice_component, notice_description, FROM_UNIXTIME(notice_date) AS notice_date, notice_checked, notice_userId, notice_sticky, notice_onlyAdmin');
- $Data->setFrom('notices');
- $Data->setOrder('notice_date DESC');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('(notice_type LIKE ? OR notice_component LIKE ? OR notice_description LIKE ?) AND notice_onlyAdmin = 0');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- /** @var array $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-
- /**
- * Obtiene el listado de categorías mediante una búsqueda
- *
- * @param ItemSearchData $SearchData
- * @return array con el id de categoria como clave y en nombre como valor
- */
- public function getMgmtSearchUser(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('notice_id, notice_type, notice_component, notice_description, FROM_UNIXTIME(notice_date) AS notice_date, BIN(notice_checked) AS notice_checked, notice_userId, BIN(notice_sticky) as notice_sticky, BIN(notice_onlyAdmin) AS notice_onlyAdmin');
- $Data->setFrom('notices');
- $Data->setOrder('notice_date DESC');
-
- $filterUser = '(notice_userId = ? OR (notice_userId = NULL AND BIN(notice_onlyAdmin) = 0) OR BIN(notice_sticky) = 1)';
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('(notice_type LIKE ? OR notice_component LIKE ? OR notice_description LIKE ?) AND ' . $filterUser);
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- $Data->addParam($search);
- $Data->addParam(SessionFactory::getUserData()->getId());
- } else {
- $Data->setWhere($filterUser);
- $Data->addParam(SessionFactory::getUserData()->getId());
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- /** @var array $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Plugins/Plugin.php b/lib/SP/Mgmt/Plugins/Plugin.php
deleted file mode 100644
index e0e27a38..00000000
--- a/lib/SP/Mgmt/Plugins/Plugin.php
+++ /dev/null
@@ -1,388 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Plugins;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\PluginData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class Plugin
- *
- * @package SP\Mgmt\Plugins
- * @property PluginData $itemData
- */
-class Plugin extends PluginBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * Añade un nuevo plugin
- *
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- $query = /** @lang SQL */
- 'INSERT INTO Plugin SET name = ?, data = ?, enabled = ?, available = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getData());
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getAvailable());
- $Data->setOnErrorMessage(__('Error al crear el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * Eliminar un plugin
- *
- * @param $name string
- * @return mixed
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($name)
- {
- $query = /** @lang SQL */
- 'DELETE FROM Plugin WHERE name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($name);
- $Data->setOnErrorMessage(__('Error al eliminar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Plugin no encontrado', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * Actualizar los datos de un plugin
- *
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET name = ?,
- data = ?,
- enabled = ?,
- available = ?
- WHERE name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getData());
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getAvailable());
- $Data->addParam($this->itemData->getName());
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Devuelve los datos de un plugin por su id
- *
- * @param $id int
- * @return bool|PluginData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- name,
- data,
- enabled,
- available
- FROM Plugin
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * Devolver todos los plugins
- *
- * @return PluginData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id,
- name,
- enabled,
- available
- FROM Plugin
- ORDER BY name';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Devuelve los datos de un plugin por su nombre
- *
- * @param $name int
- * @return mixed
- */
- public function getByName($name)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- name,
- data,
- enabled,
- available
- FROM Plugin
- WHERE name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($name);
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * Cambiar el estado del plugin
- *
- * @return $this
- * @throws SPException
- */
- public function toggleEnabled()
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET enabled = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Cambiar el estado del plugin
- *
- * @return $this
- * @throws SPException
- */
- public function toggleEnabledByName()
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET enabled = ?
- WHERE name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getName());
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Cambiar el estado del plugin
- *
- * @return $this
- * @throws SPException
- */
- public function toggleAvaliable()
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET available = ?, enabled = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAvailable());
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Cambiar el estado del plugin
- *
- * @return $this
- * @throws SPException
- */
- public function toggleAvaliableByName()
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET available = ?, enabled = ?
- WHERE name = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getAvailable());
- $Data->addParam($this->itemData->getEnabled());
- $Data->addParam($this->itemData->getName());
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Restablecer los datos de un plugin
- *
- * @param int $id Id del plugin
- * @return $this
- * @throws SPException
- */
- public function reset($id)
- {
- $query = /** @lang SQL */
- 'UPDATE Plugin
- SET data = NULL
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al actualizar el plugin', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return PluginData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT id,
- name,
- enabled,
- available
- FROM Plugin
- WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los plugins activados
- *
- * @return array
- */
- public function getEnabled()
- {
- $query = /** @lang SQL */
- 'SELECT name FROM Plugin WHERE enabled = 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Plugins/PluginBase.php b/lib/SP/Mgmt/Plugins/PluginBase.php
deleted file mode 100644
index 2c959f93..00000000
--- a/lib/SP/Mgmt/Plugins/PluginBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Plugins;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\PluginData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class CategoryBase
- *
- * @package SP\Mgmt\Categories
- */
-abstract class PluginBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(PluginData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Plugins/PluginSearch.php b/lib/SP/Mgmt/Plugins/PluginSearch.php
deleted file mode 100644
index f992a2ec..00000000
--- a/lib/SP/Mgmt/Plugins/PluginSearch.php
+++ /dev/null
@@ -1,72 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Plugins;
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class PluginSearch
- *
- * @package SP\Mgmt\Plugins
- */
-class PluginSearch extends PluginBase implements ItemSearchInterface
-{
- /**
- * Búsqueda de plugins
- *
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('plugin_id, plugin_name, plugin_enabled, plugin_available');
- $Data->setFrom('plugins');
- $Data->setOrder('plugin_name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('plugin_name LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- /** @var array $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Profiles/Profile.php b/lib/SP/Mgmt/Profiles/Profile.php
deleted file mode 100644
index 9be173c9..00000000
--- a/lib/SP/Mgmt/Profiles/Profile.php
+++ /dev/null
@@ -1,282 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Profiles;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\ProfileData;
-use SP\DataModel\UserProfileData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\Util;
-
-/**
- * Esta clase es la encargada de realizar las operaciones sobre los perfiles de usuarios.
- *
- * @property ProfileData $itemData
- */
-class Profile extends ProfileBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Nombre de perfil duplicado', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO UserProfile SET
- name = ?,
- profile = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam(serialize($this->itemData));
- $Data->setOnErrorMessage(__('Error al crear perfil', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::getLastId());
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT name
- FROM UserProfile
- WHERE UPPER(name) = ?';
-
- $Data = new QueryData();
- $Data->addParam($this->itemData->getName());
- $Data->setQuery($query);
-
- DbWrapper::getQuery($Data);
-
- return ($Data->getQueryNumRows() > 0);
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- if ($this->checkInUse($id)) {
- throw new SPException(__('Perfil en uso', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'DELETE FROM UserProfile WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar perfil', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Perfil no encontrado', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkInUse($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_profileId FROM usrData WHERE user_profileId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- DbWrapper::getQuery($Data);
-
- return ($Data->getQueryNumRows() > 0);
- }
-
- /**
- * @param $id int
- * @return ProfileData
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- name,
- profile
- FROM UserProfile
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- /**
- * @var UserProfileData $queryRes
- * @var ProfileData $Profile
- */
- $queryRes = DbWrapper::getResults($Data);
-
- $Profile = Util::unserialize($this->getDataModel(), $queryRes->getProfile());
- $Profile->setId($queryRes->getId());
- $Profile->setName($queryRes->getName());
-
- return $Profile;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Nombre de perfil duplicado', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'UPDATE UserProfile SET
- name = ?,
- profile = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam(serialize($this->itemData));
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al modificar perfil', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() > 0) {
- $this->updateSessionProfile();
- }
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT name
- FROM UserProfile
- WHERE UPPER(name) = ?
- AND id <> ?';
-
- $Data = new QueryData();
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getId());
- $Data->setQuery($query);
-
- DbWrapper::getQuery($Data);
-
- return ($Data->getQueryNumRows() > 0);
- }
-
- /**
- * Actualizar el perfil de la sesión
- */
- protected function updateSessionProfile()
- {
- if ($this->session->getUserProfile()->getId() === $this->itemData->getId()) {
- $this->session->setUserProfile($this->itemData);
- }
- }
-
- /**
- * @return ProfileData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id, name
- FROM UserProfile
- ORDER BY name';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return UserProfileData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT id,
- name
- FROM UserProfile
- WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
diff --git a/lib/SP/Mgmt/Profiles/ProfileBase.php b/lib/SP/Mgmt/Profiles/ProfileBase.php
deleted file mode 100644
index e7029e89..00000000
--- a/lib/SP/Mgmt/Profiles/ProfileBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Profiles;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\ProfileData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-defined('APP_ROOT') || die();
-
-/**
- * Clase ProfileBase para la definición de perfiles de acceso de usuarios
- *
- * @package SP
- */
-abstract class ProfileBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(ProfileData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Profiles/ProfileSearch.php b/lib/SP/Mgmt/Profiles/ProfileSearch.php
deleted file mode 100644
index 5311c666..00000000
--- a/lib/SP/Mgmt/Profiles/ProfileSearch.php
+++ /dev/null
@@ -1,71 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Profiles;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class ProfileSearch
- *
- * @package SP\Mgmt\Profiles
- */
-class ProfileSearch extends ProfileBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('userprofile_id, userprofile_name');
- $Data->setFrom('usrProfiles');
- $Data->setOrder('userprofile_name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('userprofile_name LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Profiles/ProfileUtil.php b/lib/SP/Mgmt/Profiles/ProfileUtil.php
deleted file mode 100644
index 8b4bde5a..00000000
--- a/lib/SP/Mgmt/Profiles/ProfileUtil.php
+++ /dev/null
@@ -1,173 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Profiles;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\ProfileData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class ProfileUtil
- *
- * @package SP\Mgmt\User
- */
-class ProfileUtil
-{
- /**
- * Migrar los perfiles con formato anterior a v1.2
- *
- * @return bool
- */
- public static function migrateProfiles()
- {
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Migrar Perfiles', false));
-
- $query = /** @lang SQL */
- 'SELECT id AS id,
- userprofile_name AS name,
- BIN(userProfile_pView) AS pView,
- BIN(userProfile_pViewPass) AS pViewPass,
- BIN(userProfile_pViewHistory) AS pViewHistory,
- BIN(userProfile_pEdit) AS pEdit,
- BIN(userProfile_pEditPass) AS pEditPass,
- BIN(userProfile_pAdd) AS pAdd,
- BIN(userProfile_pDelete) AS pDelete,
- BIN(userProfile_pFiles) AS pFiles,
- BIN(userProfile_pConfig) AS pConfig,
- BIN(userProfile_pConfigMasterPass) AS pConfigMasterPass,
- BIN(userProfile_pConfigBackup) AS pConfigBackup,
- BIN(userProfile_pAppMgmtCategories) AS pAppMgmtCategories,
- BIN(userProfile_pAppMgmtCustomers) AS pAppMgmtCustomers,
- BIN(userProfile_pUsers) AS pUsers,
- BIN(userProfile_pGroups) AS pGroups,
- BIN(userProfile_pProfiles) AS pProfiles,
- BIN(userProfile_pEventlog) AS pEventlog
- FROM usrProfiles';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- if (count($queryRes) === 0) {
- $LogMessage->addDescription(__('Error al obtener perfiles', false));
- $Log->setLogLevel(Log::ERROR);
- $Log->writeLog();
- return false;
- }
-
- foreach ($queryRes as $oldProfile) {
- $ProfileData = new ProfileData();
- $ProfileData->setId($oldProfile->id);
- $ProfileData->setName($oldProfile->name);
- $ProfileData->setAccAdd($oldProfile->pAdd);
- $ProfileData->setAccView($oldProfile->pView);
- $ProfileData->setAccViewPass($oldProfile->pViewPass);
- $ProfileData->setAccViewHistory($oldProfile->pViewHistory);
- $ProfileData->setAccEdit($oldProfile->pEdit);
- $ProfileData->setAccEditPass($oldProfile->pEditPass);
- $ProfileData->setAccDelete($oldProfile->pDelete);
- $ProfileData->setConfigGeneral($oldProfile->pConfig);
- $ProfileData->setConfigEncryption($oldProfile->pConfigMasterPass);
- $ProfileData->setConfigBackup($oldProfile->pConfigBackup);
- $ProfileData->setMgmCategories($oldProfile->pAppMgmtCategories);
- $ProfileData->setMgmCustomers($oldProfile->pAppMgmtCustomers);
- $ProfileData->setMgmUsers($oldProfile->pUsers);
- $ProfileData->setMgmGroups($oldProfile->pGroups);
- $ProfileData->setMgmProfiles($oldProfile->pProfiles);
- $ProfileData->setEvl($oldProfile->pEventlog);
-
- try {
- Profile::getItem($ProfileData)->add();
- } catch (SPException $e) {
- return false;
- }
- }
-
- $query = /** @lang SQL */
- 'ALTER TABLE UserProfile
- DROP COLUMN userProfile_pAppMgmtCustomers,
- DROP COLUMN userProfile_pAppMgmtCategories,
- DROP COLUMN userProfile_pAppMgmtMenu,
- DROP COLUMN userProfile_pUsersMenu,
- DROP COLUMN userProfile_pConfigMenu,
- DROP COLUMN userProfile_pFiles,
- DROP COLUMN userProfile_pViewHistory,
- DROP COLUMN userProfile_pEventlog,
- DROP COLUMN userProfile_pEditPass,
- DROP COLUMN userProfile_pViewPass,
- DROP COLUMN userProfile_pDelete,
- DROP COLUMN userProfile_pProfiles,
- DROP COLUMN userProfile_pGroups,
- DROP COLUMN userProfile_pUsers,
- DROP COLUMN userProfile_pConfigBackup,
- DROP COLUMN userProfile_pConfigMasterPass,
- DROP COLUMN userProfile_pConfig,
- DROP COLUMN userProfile_pAdd,
- DROP COLUMN userProfile_pEdit,
- DROP COLUMN userProfile_pView';
-
- $Data->setQuery($query);
-
- try {
- DbWrapper::getQuery($Data);
-
- $LogMessage->addDescription(__('Operación realizada correctamente', false));
- $Log->writeLog();
- Email::sendEmail($LogMessage);
- return true;
- } catch (SPException $e) {
- $LogMessage->addDescription(__('Fallo al realizar la operación', false));
- $Log->writeLog();
- Email::sendEmail($LogMessage);
- return false;
- }
- }
-
- /**
- * Obtener el nombre de los usuarios que usan un perfil.
- *
- * @param $id int El id del perfil
- * @return array
- */
- public static function getProfileInUsersName($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_login FROM usrData WHERE user_profileId = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/PublicLinks/PublicLink.php b/lib/SP/Mgmt/PublicLinks/PublicLink.php
deleted file mode 100644
index 702367d7..00000000
--- a/lib/SP/Mgmt/PublicLinks/PublicLink.php
+++ /dev/null
@@ -1,408 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\PublicLinks;
-
-use SP\Account\AccountUtil;
-use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
-use SP\DataModel\PublicLinkBaseData;
-use SP\DataModel\PublicLinkData;
-use SP\DataModel\PublicLinkListData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Mgmt\Users\UserUtil;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\HttpUtil;
-use SP\Util\Util;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class PublicLink para la creación de enlaces públicos
- *
- * @package SP
- * @property PublicLinkBaseData $itemData
- */
-class PublicLink extends PublicLinkBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * Tipos de enlaces
- */
- const TYPE_ACCOUNT = 1;
-
- /**
- * Incrementar el contador de visitas de un enlace
- *
- * @return bool
- * @throws \phpmailer\phpmailerException
- * @throws \SP\Core\Exceptions\SPException
- */
- public function addLinkView()
- {
- $this->itemData->addCountViews();
- $this->updateUseInfo(HttpUtil::getClientAddress(true));
-
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Ver Enlace Público', false));
- $LogMessage->addDescription(__('Enlace visualizado', false));
- $LogMessage->addDetails(__('Tipo', false), $this->itemData->getTypeId());
- $LogMessage->addDetails(__('Cuenta', false), AccountUtil::getAccountNameById($this->itemData->getItemId()));
- $LogMessage->addDetails(__('Usuario', false), UserUtil::getUserLoginById($this->itemData->getUserId()));
- $Log->writeLog();
-
- if ($this->itemData->isNotify()) {
- Email::sendEmail($LogMessage);
- }
-
- return $this->update();
- }
-
- /**
- * @return bool
- * @throws SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE PublicLink
- SET data = ?,
- hash = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(serialize($this->itemData));
- $Data->addParam($this->itemData->getLinkHash());
- $Data->addParam($this->itemData->getPublicLinkId());
- $Data->setOnErrorMessage(__('Error al actualizar enlace', false));
-
- DbWrapper::getQuery($Data);
-
- return true;
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Enlace ya creado', false), SPException::INFO);
- }
-
- $this->itemData->setDateAdd(time());
- $this->itemData->setUserId(SessionFactory::getUserData()->getId());
- $this->itemData->setMaxCountViews($this->ConfigData->getPublinksMaxViews());
- $this->calcDateExpire();
- $this->createLinkHash();
- $this->setLinkData();
-
- $query = /** @lang SQL */
- 'INSERT INTO PublicLink
- SET hash = ?,
- itemId = ?,
- data = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getPublicLinkHash());
- $Data->addParam($this->itemData->getPublicLinkItemId());
- $Data->addParam(serialize($this->itemData));
- $Data->setOnErrorMessage(__('Error al crear enlace', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM PublicLink WHERE itemId = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getPublicLinkItemId());
-
- DbWrapper::getResults($Data);
-
- return ($Data->getQueryNumRows() === 1);
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM PublicLink WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar enlace', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Enlace no encontrado', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws SPException
- */
- public function refresh()
- {
- $this->itemData->setMaxCountViews($this->itemData->getMaxCountViews() + $this->ConfigData->getPublinksMaxViews());
-
- $this->calcDateExpire();
- $this->createLinkHash(true);
- $this->setLinkData();
-
- $query = /** @lang SQL */
- 'UPDATE PublicLink
- SET data = ?,
- hash = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(serialize($this->itemData));
- $Data->addParam($this->itemData->getPublicLinkHash());
- $Data->addParam($this->itemData->getPublicLinkId());
- $Data->setOnErrorMessage(__('Error al renovar enlace', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return PublicLinkData
- * @throws SPException
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- hash,
- data
- FROM PublicLink WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($id);
-
- /** @var PublicLinkBaseData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error al obtener enlace', false), SPException::ERROR);
- }
-
- /** @var $PublicLink PublicLinkData */
- $PublicLink = Util::unserialize($this->getDataModel(), $queryRes->getPublicLinkLinkData());
- $PublicLink->setId($id);
-
- return $PublicLink;
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id, hash, data FROM PublicLink';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
- /** @var PublicLinkData[] $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $publicLinks = [];
-
- foreach ($queryRes as $PublicLinkListData) {
- /** @var PublicLinkData $PublicLinkData */
- $PublicLinkData = Util::unserialize($this->getDataModel(), $PublicLinkListData->getPublicLinkLinkData());
- $PublicLinkData->setId($PublicLinkListData->getId());
-
- $publicLinks[] = $this->getItemForList($PublicLinkData);
- }
-
- return $publicLinks;
- }
-
- /**
- * Devuelve los datos de un enlace para mostrarlo
- *
- * @param PublicLinkData $PublicLinkData
- * @return PublicLinkListData
- */
- public function getItemForList(PublicLinkData $PublicLinkData)
- {
- $PublicLinkListData = new PublicLinkListData();
- $PublicLinkListData->setId($PublicLinkData->getId());
- $PublicLinkListData->setHash($PublicLinkData->getPublicLinkLinkHash());
- $PublicLinkListData->setAccountName(AccountUtil::getAccountNameById($PublicLinkData->getItemId()));
- $PublicLinkListData->setUserLogin(UserUtil::getUserLoginById($PublicLinkData->getUserId()));
- $PublicLinkListData->setNotify($PublicLinkData->isNotify() ? __('ON') : __('OFF'));
- $PublicLinkListData->setDateAdd(date('Y-m-d H:i', $PublicLinkData->getDateAdd()));
- $PublicLinkListData->setDateExpire(date('Y-m-d H:i', $PublicLinkData->getDateExpire()));
- $PublicLinkListData->setCountViews($PublicLinkData->getCountViews() . '/' . $PublicLinkData->getMaxCountViews());
- $PublicLinkListData->setUseInfo($PublicLinkData->getUseInfo());
-
- return $PublicLinkListData;
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @param $hash int
- * @return bool|PublicLinkData
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getByHash($hash)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- hash,
- data
- FROM PublicLink WHERE hash = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($hash);
-
- /** @var PublicLinkBaseData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error al obtener enlace', false), SPException::ERROR);
- } elseif (is_array($queryRes)) {
- return false;
- }
-
- /**
- * @var $PublicLink PublicLinkData
- */
- $PublicLink = Util::unserialize($this->getDataModel(), $queryRes->getPublicLinkLinkData());
- $PublicLink->setId($queryRes->getPublicLinkId());
-
- return $PublicLink;
- }
-
- /**
- * Devolver el hash asociado a un elemento
- *
- * @param int $itemId
- * @return PublicLinkData
- * @throws SPException
- */
- public function getHashForItem($itemId)
- {
- $query = /** @lang SQL */
- 'SELECT id, hash FROM PublicLink WHERE itemId = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($itemId);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__u('Error al obtener enlace'), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- * @throws \SP\Core\Exceptions\SPException
- */
- public function getByIdBatch(array $ids)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- hash
- FROM PublicLink WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/PublicLinks/PublicLinkBase.php b/lib/SP/Mgmt/PublicLinks/PublicLinkBase.php
deleted file mode 100644
index 3230b2c6..00000000
--- a/lib/SP/Mgmt/PublicLinks/PublicLinkBase.php
+++ /dev/null
@@ -1,147 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\PublicLinks;
-
-defined('APP_ROOT') || die();
-
-use SP\Account\Account;
-use SP\Config\ConfigData;
-use SP\Core\Crypt\Crypt;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Exceptions\InvalidClassException;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountExtData;
-use SP\DataModel\PublicLinkBaseData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class PublicLinks para la gestión de enlaces públicos
- *
- * @package SP
- * @property PublicLinkBaseData $itemData
- */
-abstract class PublicLinkBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * @var ConfigData
- */
- protected $ConfigData;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(PublicLinkBaseData::class);
- }
-
- /**
- * Devolver la clave y el IV para el enlace
- *
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- final protected function createLinkPass()
- {
- $key = $this->ConfigData->getPasswordSalt() . $this->createLinkHash();
- $securedKey = Crypt::makeSecuredKey($key);
-
- $this->itemData->setPass(Crypt::encrypt(CryptSession::getSessionKey(), $securedKey, $key));
- $this->itemData->setPassIV($securedKey);
- }
-
- /**
- * Generar el hash para el enlace
- *
- * @param bool $refresh Si es necesario regenerar el hash
- * @return string
- */
- final protected function createLinkHash($refresh = false)
- {
- if ($refresh === true
- || $this->itemData->getLinkHash() === ''
- ) {
- $hash = hash('sha256', uniqid('sysPassPublicLink', true));
-
- $this->itemData->setPublicLinkHash($hash);
- $this->itemData->setLinkHash($hash);
- }
-
- return $this->itemData->getLinkHash();
- }
-
- /**
- * Obtener los datos de una cuenta y encriptarlos para el enlace
- *
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \SP\Core\Exceptions\SPException
- * @throws \Defuse\Crypto\Exception\BadFormatException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- */
- final protected function setLinkData()
- {
- // Obtener los datos de la cuenta
- $Account = new Account(new AccountExtData($this->itemData->getItemId()));
- $AccountData = $Account->getDataForLink();
-
- $key = CryptSession::getSessionKey();
- $securedKey = Crypt::unlockSecuredKey($AccountData->getKey(), $key);
- $AccountData->setPass(Crypt::decrypt($AccountData->getPass(), $securedKey, $key));
- $AccountData->setKey(null);
-
- // Encriptar los datos de la cuenta
- $linkKey = $this->ConfigData->getPasswordSalt() . $this->createLinkHash();
- $linkSecuredKey = Crypt::makeSecuredKey($linkKey);
-
- $this->itemData->setData(Crypt::encrypt(serialize($AccountData), $linkSecuredKey, $linkKey));
- $this->itemData->setPassIV($linkSecuredKey);
- }
-
- /**
- * Devolver el tiempo de caducidad del enlace
- */
- final protected function calcDateExpire()
- {
- $this->itemData->setDateExpire(time() + $this->ConfigData->getPublinksMaxTime());
- }
-
- /**
- * Actualizar la información de uso
- *
- * @param string $who Quién lo ha visto
- */
- final protected function updateUseInfo($who)
- {
- $this->itemData->addUseInfo(['who' => $who, 'time' => time()]);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/PublicLinks/PublicLinkSearch.php b/lib/SP/Mgmt/PublicLinks/PublicLinkSearch.php
deleted file mode 100644
index f5785f8d..00000000
--- a/lib/SP/Mgmt/PublicLinks/PublicLinkSearch.php
+++ /dev/null
@@ -1,88 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\PublicLinks;
-
-use SP\Account\AccountUtil;
-use SP\DataModel\ItemSearchData;
-use SP\DataModel\PublicLinkListData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Mgmt\Users\UserUtil;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\Util;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class PublicLinkUtil con utilidades para la gestión de enlaces
- *
- * @package SP
- */
-class PublicLinkSearch extends PublicLinkBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setMapClassName(PublicLinkListData::class);
- $Data->setSelect('publicLink_id, publicLink_hash, publicLink_linkData');
- $Data->setFrom('publicLinks');
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- /** @var PublicLinkListData[] $queryRes */
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $publicLinks = [];
- $publicLinks['count'] = $Data->getQueryNumRows();
-
- foreach ($queryRes as $PublicLinkListData) {
- $PublicLinkData = Util::unserialize($this->getDataModel(), $PublicLinkListData->getPublicLinkLinkData());
-
- $PublicLinkListData->setAccountName(AccountUtil::getAccountNameById($PublicLinkData->getItemId()));
- $PublicLinkListData->setUserLogin(UserUtil::getUserLoginById($PublicLinkData->getUserId()));
- $PublicLinkListData->setNotify($PublicLinkData->isNotify() ? __('ON') : __('OFF'));
- $PublicLinkListData->setDateAdd(date('Y-m-d H:i', $PublicLinkData->getDateAdd()));
- $PublicLinkListData->setDateExpire(date('Y-m-d H:i', $PublicLinkData->getDateExpire()));
- $PublicLinkListData->setCountViews($PublicLinkData->getCountViews() . '/' . $PublicLinkData->getMaxCountViews());
- $PublicLinkListData->setUseInfo($PublicLinkData->getUseInfo());
-
- if ($SearchData->getSeachString() === ''
- || stripos($PublicLinkListData->getAccountName(), $SearchData->getSeachString()) !== false
- || stripos($PublicLinkListData->getUserLogin(), $SearchData->getSeachString()) !== false
- ){
- $publicLinks[] = $PublicLinkListData;
- }
- }
-
- return $publicLinks;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Tags/Tag.php b/lib/SP/Mgmt/Tags/Tag.php
deleted file mode 100644
index 531ee47f..00000000
--- a/lib/SP/Mgmt/Tags/Tag.php
+++ /dev/null
@@ -1,233 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Tags;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\TagData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class Tags
- *
- * @package SP\Mgmt\Tags
- * @property TagData $itemData
- */
-class Tag extends TagBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Etiqueta duplicada', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO Tag SET tag_name = ?, tag_hash = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getHash());
- $Data->setOnErrorMessage(__('Error al crear etiqueta', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT id FROM tags WHERE hash = ?';
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getHash());
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes !== false) {
- if ($Data->getQueryNumRows() === 0) {
- return false;
- } elseif ($Data->getQueryNumRows() === 1) {
- $this->itemData->setId($queryRes->tag_id);
- }
- }
-
- return true;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM Tag WHERE tag_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar etiqueta', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Etiqueta no encontrada', false), SPException::INFO);
- }
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Etiqueta duplicada', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'UPDATE Tag SET tag_name = ?, tag_hash = ? WHERE tag_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getHash());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar etiqueta', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT hash FROM tags WHERE hash = ? AND tag_id <> ?';
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getHash());
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @param $id int
- * @return TagData
- * @throws SPException
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id, tag_name FROM tags WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setMapClassName($this->getDataModel());
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error al obtener etiqueta', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @return TagData[]
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id, tag_name, tag_hash FROM tags ORDER BY name';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->setMapClassName($this->getDataModel());
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return TagData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT id, tag_name FROM tags WHERE id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Tags/TagBase.php b/lib/SP/Mgmt/Tags/TagBase.php
deleted file mode 100644
index 84a488f0..00000000
--- a/lib/SP/Mgmt/Tags/TagBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Tags;
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\TagData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class TagBase
- *
- * @package SP\Mgmt\Tags
- */
-class TagBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(TagData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Tags/TagSearch.php b/lib/SP/Mgmt/Tags/TagSearch.php
deleted file mode 100644
index c3141a54..00000000
--- a/lib/SP/Mgmt/Tags/TagSearch.php
+++ /dev/null
@@ -1,71 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Tags;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class TagSearch
- *
- * @package SP\Mgmt\Tags
- */
-class TagSearch extends TagBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('tag_id, tag_name');
- $Data->setFrom('tags');
- $Data->setOrder('tag_name');
-
- if ($SearchData->getSeachString() !== '') {
- $Data->setWhere('tag_name LIKE ?');
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- }
-
- $Data->setLimit('?,?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Tracks/Track.php b/lib/SP/Mgmt/Tracks/Track.php
deleted file mode 100644
index 8a020fa7..00000000
--- a/lib/SP/Mgmt/Tracks/Track.php
+++ /dev/null
@@ -1,242 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Tracks;
-
-use SP\DataModel\TrackData;
-use SP\Mgmt\ItemInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class Track
- *
- * @package SP\Mgmt\Tracks
- * @property TrackData $itemData
- */
-class Track extends TrackBase implements ItemInterface
-{
- /**
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function add()
- {
- $query = /** @lang SQL */
- 'INSERT INTO Track SET
- userId = ?,
- source = ?,
- time = UNIX_TIMESTAMP(),
- ipv4 = ?,
- ipv6 = ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getUserId());
- $Data->addParam($this->itemData->getSource());
- $Data->addParam($this->itemData->getTrackIpv4Bin());
- $Data->addParam($this->itemData->getTrackIpv6Bin());
- $Data->setOnErrorMessage(__('Error al crear track', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * @param $id int|array
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function delete($id)
- {
- $query = /** @lang SQL */
- 'DELETE FROM Track WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al eliminar track', false));
-
- return DbWrapper::getQuery($Data);
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE Track SET
- track_userId = ?,
- source = ?,
- time = UNIX_TIMESTAMP(),
- ipv4 = ?,
- ipv6 = ?
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getUserId());
- $Data->addParam($this->itemData->getSource());
- $Data->addParam($this->itemData->getTrackIpv4Bin());
- $Data->addParam($this->itemData->getTrackIpv6Bin());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar track', false));
-
- return DbWrapper::getQuery($Data);
- }
-
- /**
- * @param $id int
- * @return mixed
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id,
- userId,
- source,
- time,
- ipv4,
- ipv6
- FROM Track
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al obtener track', false));
-
- return DbWrapper::getResults($Data);
- }
-
- /**
- * @return array
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT id,
- userId,
- source,
- time,
- ipv4,
- ipv6 FROM Track';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al obtener tracks', false));
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Eliminar elementos en lote
- *
- * @param array $ids
- * @return $this
- */
- public function deleteBatch(array $ids)
- {
- // TODO: Implement deleteBatch() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-
-
- /**
- * Devuelve los tracks de un cliente desde un tiempo y origen determinados
- *
- * @param $time
- * @return array
- */
- public function getTracksForClientFromTime($time)
- {
- $query = /** @lang SQL */
- 'SELECT id, userId
- FROM Track
- WHERE time >= ?
- AND (ipv4 = ? OR ipv6 = ?)
- AND source = ?';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($time);
- $Data->addParam($this->itemData->getTrackIpv4Bin());
- $Data->addParam($this->itemData->getTrackIpv6Bin());
- $Data->addParam($this->itemData->getSource());
- $Data->setOnErrorMessage(__('Error al obtener tracks', false));
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Tracks/TrackBase.php b/lib/SP/Mgmt/Tracks/TrackBase.php
deleted file mode 100644
index 272c874c..00000000
--- a/lib/SP/Mgmt/Tracks/TrackBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Tracks;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\TrackData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class TrackBase
- *
- * @package SP\Mgmt\Tracks
- */
-abstract class TrackBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(TrackData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/User.php b/lib/SP/Mgmt/Users/User.php
deleted file mode 100644
index 40727ed5..00000000
--- a/lib/SP/Mgmt/Users/User.php
+++ /dev/null
@@ -1,460 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Crypt\Hash;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserData;
-use SP\DataModel\UserLoginData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemSelectInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class User
- *
- * @package SP
- * @property UserData|UserLoginData $itemData
- */
-class User extends UserBase implements ItemInterface, ItemSelectInterface
-{
- use ItemTrait;
-
- /**
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'INSERT INTO usrData SET
- user_name = ?,
- user_login = ?,
- user_ssoLogin = ?,
- user_email = ?,
- user_notes = ?,
- user_groupId = ?,
- user_profileId = ?,
- user_mPass = \'\',
- user_mKey = \'\',
- user_isAdminApp = ?,
- user_isAdminAcc = ?,
- user_isDisabled = ?,
- user_isChangePass = ?,
- user_isLdap = 0,
- user_pass = ?,
- user_hashSalt = \'\'';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getSsoLogin());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getNotes());
- $Data->addParam($this->itemData->getUserGroupId());
- $Data->addParam($this->itemData->getUserProfileId());
- $Data->addParam($this->itemData->isAdminApp());
- $Data->addParam($this->itemData->isAdminAcc());
- $Data->addParam($this->itemData->isDisabled());
- $Data->addParam($this->itemData->isChangePass());
- $Data->addParam(Hash::hashKey($this->itemData->getPass()));
- $Data->setOnErrorMessage(__('Error al crear el usuario', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::getLastId());
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT user_login, user_email
- FROM usrData
- WHERE UPPER(user_login) = UPPER(?) OR UPPER(user_ssoLogin) = UPPER(?) OR UPPER(user_email) = UPPER(?)';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getSsoLogin());
- $Data->addParam($this->itemData->getEmail());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @param $id int
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function delete($id)
- {
- $query = 'DELETE FROM usrData WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
- $Data->setOnErrorMessage(__('Error al eliminar el usuario', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Usuario no encontrado', false), SPException::INFO);
- }
-
- $this->itemData->setId(DbWrapper::$lastId);
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function update()
- {
- if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
- }
-
- $query = /** @lang SQL */
- 'UPDATE usrData SET
- user_name = ?,
- user_login = ?,
- user_ssoLogin = ?,
- user_email = ?,
- user_notes = ?,
- user_groupId = ?,
- user_profileId = ?,
- user_isAdminApp = ?,
- user_isAdminAcc = ?,
- user_isDisabled = ?,
- user_isChangePass = ?,
- user_lastUpdate = NOW()
- WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getSsoLogin());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getNotes());
- $Data->addParam($this->itemData->getUserGroupId());
- $Data->addParam($this->itemData->getUserProfileId());
- $Data->addParam($this->itemData->isAdminApp());
- $Data->addParam($this->itemData->isAdminAcc());
- $Data->addParam($this->itemData->isDisabled());
- $Data->addParam($this->itemData->isChangePass());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el usuario', false));
-
- DbWrapper::getQuery($Data);
-
- if ($Data->getQueryNumRows() > 0) {
- $this->itemData->setId(DbWrapper::getLastId());
- }
-
- return $this;
- }
-
- /**
- * @return bool
- * @throws \SP\Core\Exceptions\SPException
- */
- public function checkDuplicatedOnUpdate()
- {
- $query = /** @lang SQL */
- 'SELECT user_login, user_email
- FROM usrData
- WHERE (UPPER(user_login) = UPPER(?) OR UPPER(user_ssoLogin) = UPPER(?) OR UPPER(user_email) = UPPER(?))
- AND user_id <> ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getSsoLogin());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getId());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @return UserData[]
- * @throws SPException
- */
- public function getAll()
- {
- $query = /** @lang SQL */
- 'SELECT user_id,
- user_name,
- user_groupId,
- user_login,
- user_ssoLogin,
- user_email,
- user_notes,
- user_count,
- user_profileId,
- user_preferences,
- BIN(user_isAdminApp) AS user_isAdminApp,
- BIN(user_isAdminAcc) AS user_isAdminAcc,
- BIN(user_isLdap) AS user_isLdap,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isChangePass) AS user_isChangePass
- FROM usrData';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
-
-
- try {
- $queryRes = DbWrapper::getResultsArray($Data);
- } catch (SPException $e) {
- throw new SPException(__('Error al obtener los usuarios', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function updatePass()
- {
- $query = /** @lang SQL */
- 'UPDATE usrData SET
- user_pass = ?,
- user_hashSalt = \'\',
- user_isChangePass = 0,
- user_isChangedPass = 1,
- user_lastUpdate = NOW()
- WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(Hash::hashKey($this->itemData->getPass()));
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al modificar la clave', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return UserData
- * @throws SPException
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_id,
- user_name,
- user_groupId,
- usergroup_name,
- user_login,
- user_ssoLogin,
- user_email,
- user_notes,
- user_count,
- user_profileId,
- user_count,
- user_lastLogin,
- user_lastUpdate,
- user_lastUpdateMPass,
- user_preferences,
- user_pass,
- user_hashSalt,
- user_mPass,
- user_mKey,
- BIN(user_isAdminApp) AS user_isAdminApp,
- BIN(user_isAdminAcc) AS user_isAdminAcc,
- BIN(user_isLdap) AS user_isLdap,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isChangePass) AS user_isChangePass,
- BIN(user_isChangedPass) AS user_isChangedPass,
- BIN(user_isMigrate) AS user_isMigrate
- FROM usrData
- JOIN usrGroups ON usergroup_id = user_groupId
- WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
-
- if (is_object($this->itemData)) {
- $Data->setMapClass($this->itemData);
- } else {
- $Data->setMapClassName($this->getDataModel());
- }
-
- $Data->setQuery($query);
- $Data->addParam($id);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error al obtener los datos del usuario', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * @param $login string
- * @return UserData
- * @throws SPException
- */
- public function getByLogin($login)
- {
- $query = /** @lang SQL */
- 'SELECT user_id,
- user_name,
- user_groupId,
- usergroup_name,
- user_login,
- user_ssoLogin,
- user_email,
- user_notes,
- user_count,
- user_profileId,
- user_count,
- user_lastLogin,
- user_lastUpdate,
- user_lastUpdateMPass,
- user_preferences,
- user_pass,
- user_hashSalt,
- user_mPass,
- user_mKey,
- BIN(user_isAdminApp) AS user_isAdminApp,
- BIN(user_isAdminAcc) AS user_isAdminAcc,
- BIN(user_isLdap) AS user_isLdap,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isChangePass) AS user_isChangePass,
- BIN(user_isChangedPass) AS user_isChangedPass,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isMigrate) AS user_isMigrate
- FROM usrData
- JOIN usrGroups ON usergroup_id = user_groupId
- WHERE user_login = ? OR user_ssoLogin = ? LIMIT 1';
-
- $Data = new QueryData();
-
- if (is_object($this->itemData)) {
- $Data->setMapClass($this->itemData);
- } else {
- $Data->setMapClassName($this->getDataModel());
- }
-
- $Data->setQuery($query);
- $Data->addParam($login);
- $Data->addParam($login);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error al obtener los datos del usuario', false), SPException::ERROR);
- }
-
- return $queryRes;
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return UserData[]
- */
- public function getByIdBatch(array $ids)
- {
- if (count($ids) === 0) {
- return [];
- }
-
- $query = /** @lang SQL */
- 'SELECT user_id,
- user_name,
- user_groupId,
- usergroup_name,
- user_login,
- user_ssoLogin,
- user_email,
- user_notes,
- user_count,
- user_profileId,
- user_count,
- user_lastLogin,
- user_lastUpdate,
- user_lastUpdateMPass,
- user_preferences,
- BIN(user_isAdminApp) AS user_isAdminApp,
- BIN(user_isAdminAcc) AS user_isAdminAcc,
- BIN(user_isLdap) AS user_isLdap,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isChangePass) AS user_isChangePass,
- BIN(user_isChangedPass) AS user_isChangedPass,
- BIN(user_isMigrate) AS user_isMigrate
- FROM usrData
- JOIN usrGroups ON usergroup_id = user_groupId
- WHERE user_id IN (' . $this->getParamsFromArray($ids) . ')';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->setParams($ids);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserBase.php b/lib/SP/Mgmt/Users/UserBase.php
deleted file mode 100644
index 599888f6..00000000
--- a/lib/SP/Mgmt/Users/UserBase.php
+++ /dev/null
@@ -1,59 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\Config\ConfigData;
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\UserData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class UserBase
- *
- * @package SP
- */
-abstract class UserBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * @var ConfigData
- */
- protected $ConfigData;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserLdap.php b/lib/SP/Mgmt/Users/UserLdap.php
deleted file mode 100644
index 0438786a..00000000
--- a/lib/SP/Mgmt/Users/UserLdap.php
+++ /dev/null
@@ -1,224 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use SP\Core\Crypt\Hash;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Messages\LogMessage;
-use SP\DataModel\UserLoginData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class UserLdap
- *
- * @package SP
- * @property UserLoginData $itemData
- */
-class UserLdap extends User
-{
- /**
- * Comprobar si los datos del usuario de LDAP están en la BBDD.
- *
- * @param $userLogin
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function checkLDAPUserInDB($userLogin)
- {
- $query = /** @lang SQL */
- 'SELECT user_login FROM usrData WHERE LOWER(user_login) = LOWER(?) LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userLogin);
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() === 1;
- }
-
- /**
- * @return mixed
- * @throws SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
- }
-
- $groupId = $this->ConfigData->getLdapDefaultGroup();
- $profileId = $this->ConfigData->getLdapDefaultProfile();
- $this->itemData->setIsDisabled(($groupId === 0 || $profileId === 0) ? 1 : 0);
-
- $query = /** @lang SQL */
- 'INSERT INTO usrData SET
- user_name = ?,
- user_login = ?,
- user_email = ?,
- user_notes = ?,
- user_groupId = ?,
- user_profileId = ?,
- user_mPass = \'\',
- user_mKey = \'\',
- user_isDisabled = ?,
- user_isLdap = 1,
- user_pass = ?,
- user_hashSalt = \'\'';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam(__('Usuario de LDAP'));
- $Data->addParam($groupId);
- $Data->addParam($profileId);
- $Data->addParam((int)$this->itemData->isIsDisabled());
- $Data->addParam(Hash::hashKey($this->itemData->getPass()));
- $Data->setOnErrorMessage(__('Error al guardar los datos de LDAP', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::getLastId());
-
- if (!$groupId || !$profileId) {
- $LogEmail = new LogMessage();
- $LogEmail->setAction(__('Activación Cuenta', false));
- $LogEmail->addDescription(__('Su cuenta está pendiente de activación.', false));
- $LogEmail->addDescription(__('En breve recibirá un email de confirmación.', false));
-
- Email::sendEmail($LogEmail, $this->itemData->getEmail(), false);
- }
-
- $Log = new Log();
- $Log->getLogMessage()
- ->setAction(__('Nuevo usuario de LDAP', false))
- ->addDescription(sprintf('%s (%s)', $this->itemData->getName(), $this->itemData->getLogin()));
- $Log->writeLog();
-
- Email::sendEmail($Log->getLogMessage());
-
- return $this;
- }
-
- /**
- * Comprobar duplicados por login e email en minúsculas
- *
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT user_login, user_email
- FROM usrData
- WHERE LOWER(user_login) = LOWER(?) OR (? <> \'\' AND LOWER(user_email) = LOWER(?))';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getEmail());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE usrData SET
- user_name = ?,
- user_email = ?,
- user_notes = ?,
- user_groupId = ?,
- user_profileId = ?,
- user_isAdminApp = ?,
- user_isAdminAcc = ?,
- user_isDisabled = ?,
- user_lastUpdate = NOW(),
- user_isLdap = 1
- WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getNotes());
- $Data->addParam($this->itemData->getUserGroupId());
- $Data->addParam($this->itemData->getUserProfileId());
- $Data->addParam($this->itemData->isIsAdminApp());
- $Data->addParam($this->itemData->isIsAdminAcc());
- $Data->addParam($this->itemData->isIsDisabled());
- $Data->addParam($this->itemData->getId());
- $Data->setOnErrorMessage(__('Error al actualizar el usuario', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function updateOnLogin()
- {
- $query = 'UPDATE usrData SET
- user_pass = ?,
- user_hashSalt = \'\',
- user_name = ?,
- user_email = ?,
- user_lastUpdate = NOW(),
- user_lastLogin = NOW(),
- user_isLdap = 1
- WHERE LOWER(user_login) = LOWER(?) LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(Hash::hashKey($this->itemData->getLoginPass()));
- $Data->addParam($this->itemData->getName());
- $Data->addParam($this->itemData->getEmail());
- $Data->addParam($this->itemData->getLogin());
- $Data->setOnErrorMessage(__('Error al actualizar la clave del usuario en la BBDD', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserLdapSync.php b/lib/SP/Mgmt/Users/UserLdapSync.php
deleted file mode 100644
index 34344330..00000000
--- a/lib/SP/Mgmt/Users/UserLdapSync.php
+++ /dev/null
@@ -1,134 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use SP\Auth\Ldap\LdapMsAds;
-use SP\Auth\Ldap\LdapStd;
-use SP\Bootstrap;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserData;
-use SP\Log\Log;
-use SP\Util\Util;
-
-/**
- * Class UserLdapSync
- *
- * @package SP\Mgmt\Users
- */
-class UserLdapSync
-{
- /**
- * @var int
- */
- public static $totalObjects = 0;
- /**
- * @var int
- */
- public static $syncedObjects = 0;
- /**
- * @var int
- */
- public static $errorObjects = 0;
-
- /**
- * Sincronizar usuarios de LDAP
- *
- * @param array $options
- * @return bool
- */
- public static function run(array &$options)
- {
- $ConfigData = Bootstrap::getContainer()['configData'];
-
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Sincronización LDAP', false));
-
- $Ldap = $ConfigData->isLdapAds() || $options['isADS'] ? new LdapMsAds() : new LdapStd();
-
- $ldapObjects = $Ldap->findObjects();
-
- if (!$ldapObjects) {
- return false;
- }
-
- self::$totalObjects = (int)$ldapObjects['count'];
-
- $LogMessage->addDetails(__('Objetos encontrados', false), self::$totalObjects);
-
- if (self::$totalObjects > 0) {
- $UserData = new UserData();
-
- foreach ($ldapObjects as $result) {
- if (is_array($result)) {
- $User = clone $UserData;
-
- foreach ($result as $attribute => $values) {
-
- $value = $values[0];
-
- switch (strtolower($attribute)) {
- case $options['nameAttribute']:
- $User->setName($value);
- break;
- case $options['loginAttribute']:
- $User->setLogin($value);
- break;
- case 'mail':
- $User->setEmail($value);
- break;
- }
- }
-
- if (!empty($User->getName())
- && !empty($User->getLogin())
- ) {
- $User->setPass(Util::generateRandomBytes());
-
- try {
- $LogMessage->addDetails(__('Usuario', false), sprintf('%s (%s)', $User->getName(), $User->getLogin()));
- UserLdap::getItem($User)->add();
-
- self::$syncedObjects++;
- } catch (SPException $e) {
- self::$errorObjects++;
- $LogMessage->addDescription($e->getMessage());
- }
- }
- }
- }
- } else {
- $LogMessage->addDescription(__('No se encontraron objetos para sincronizar', false));
- $Log->writeLog();
-
- return true;
- }
-
- $LogMessage->addDescription(__('Sincronización finalizada', false));
- $Log->writeLog();
-
- return true;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserMigrate.php b/lib/SP/Mgmt/Users/UserMigrate.php
deleted file mode 100644
index ab6e14b8..00000000
--- a/lib/SP/Mgmt/Users/UserMigrate.php
+++ /dev/null
@@ -1,176 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Crypt\Hash;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserLoginData;
-use SP\DataModel\UserToUserGroupData;
-use SP\Log\Log;
-use SP\Mgmt\Groups\GroupUsers;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class UserMigrate para la migración de usuarios
- *
- * @package SP
- */
-class UserMigrate
-{
- /**
- * Comprobar si un usuario está migrado desde phpPMS.
- *
- * @param string $userLogin con el login del usuario
- * @return bool
- */
- public static function checkUserIsMigrate($userLogin)
- {
- $query = /** @lang SQL */
- 'SELECT BIN(user_isMigrate) AS user_isMigrate FROM usrData WHERE user_login = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userLogin);
-
- $queryRes = DbWrapper::getResults($Data);
-
- return ($queryRes !== false && $Data->getQueryNumRows() === 1 && $queryRes->user_isMigrate == 1);
- }
-
- /**
- * Actualizar la clave de un usuario desde phpPMS.
- *
- * @param UserLoginData $userLoginData
- * @return bool
- * @throws SPException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public static function migrateUserPass(UserLoginData $userLoginData)
- {
- $userLoginResponse = $userLoginData->getUserLoginResponse();
-
- $passOk = ($userLoginResponse->getPass() === sha1($userLoginResponse->getHashSalt() . $userLoginData->getLoginPass())
- || $userLoginResponse->getPass() === md5($userLoginData->getLoginPass())
- || hash_equals($userLoginResponse->getPass(), crypt($userLoginData->getLoginPass(), $userLoginResponse->getHashSalt()))
- || Hash::checkHashKey($userLoginData->getLoginPass(), $userLoginResponse->getPass()));
-
- if ($passOk) {
- $query = /** @lang SQL */
- 'UPDATE User SET
- pass = ?,
- hashSalt = \'\',
- lastUpdate = NOW(),
- isMigrate = 0
- WHERE login = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(Hash::hashKey($userLoginData->getLoginPass()));
- $Data->addParam($userLoginResponse->getLogin());
- $Data->setOnErrorMessage(__u('Error al migrar cuenta de usuario'));
-
- DbWrapper::getQuery($Data);
-
-// $Log = new Log();
-// $Log->getLogMessage()
-// ->setAction(__FUNCTION__)
-// ->addDescription(__u('Usuario actualizado'))
-// ->addDetails(__u('Login'), $userLoginData->getLogin());
-// $Log->writeLog();
-
-// Email::sendEmail($Log->getLogMessage());
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Migrar el grupo de los usuarios a la nueva tabla
- *
- * @throws \SP\Core\Exceptions\SPException
- * @throws \SP\Core\Exceptions\InvalidClassException
- */
- public static function migrateUsersGroup()
- {
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__FUNCTION__);
-
- $query = /** @lang SQL */
- 'SELECT user_id, user_groupId FROM usrData';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- $LogMessage->addDescription(__('Error al obtener grupo de usuarios', false));
- $Log->setLogLevel(Log::ERROR);
- $Log->writeLog();
-
- throw new SPException($LogMessage->getDescription(), SPException::ERROR);
- }
-
- foreach ($queryRes as $user) {
- $GroupUsers = new UserToUserGroupData();
- $GroupUsers->setUserGroupId($user->user_groupId);
- $GroupUsers->addUser($user->user_id);
-
- try {
- GroupUsers::getItem($GroupUsers)->update();
- } catch (SPException $e) {
- $LogMessage->addDetails(__('Error al migrar grupo del usuario', false), $user->user_id);
- $Log->setLogLevel(Log::ERROR);
- }
- }
-
- $Log->writeLog();
-
- return true;
- }
-
- /**
- * Establecer el campo isMigrate de cada usuario
- *
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public static function setMigrateUsers()
- {
- $query = 'UPDATE usrData SET user_isMigrate = 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- return DbWrapper::getQuery($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPass.php b/lib/SP/Mgmt/Users/UserPass.php
deleted file mode 100644
index 09ac6262..00000000
--- a/lib/SP/Mgmt/Users/UserPass.php
+++ /dev/null
@@ -1,359 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
-use SP\Bootstrap;
-use SP\Config\ConfigData;
-use SP\Config\ConfigDB;
-use SP\Controller\LoginController;
-use SP\Core\Crypt\Crypt;
-use SP\Core\Crypt\Hash;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Exceptions\InvalidClassException;
-use SP\Core\Exceptions\QueryException;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Upgrade\User as UpgradeUser;
-use SP\DataModel\UserLoginData;
-use SP\DataModel\UserPassData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class UserPass para la gestión de las claves de un usuario
- *
- * @package SP
- * @property UserPassData $itemData
- */
-class UserPass extends UserBase
-{
- // La clave maestra incorrecta
- const MPASS_WRONG = 0;
- // La clave maestra correcta
- const MPASS_OK = 1;
- // La clave maestra no está guardada
- const MPASS_NOTSET = 2;
- // La clave maestra ha cambiado
- const MPASS_CHANGED = 3;
- // Comprobar la clave maestra con la clave del usuario anterior
- const MPASS_CHECKOLD = 4;
- /**
- * @var bool
- */
- public static $gotMPass = false;
- /**
- * @var string
- */
- private static $clearUserMPass = '';
-
- /**
- * Obtener el IV del usuario a partir del Id.
- *
- * @param int $id El id del usuario
- * @return string El hash
- */
- public static function getUserIVById($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_mKey FROM usrData WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- return false;
- }
-
- return $queryRes->user_mKey;
- }
-
- /**
- * Comprobar si el usuario tiene actualizada la clave maestra actual.
- *
- * @param int $userId ID de usuario
- * @return bool
- */
- public static function checkUserUpdateMPass($userId)
- {
- $configMPassTime = ConfigDB::getValue('lastupdatempass');
-
- if (empty($configMPassTime)) {
- return false;
- }
-
- $query = /** @lang SQL */
- 'SELECT lastUpdateMPass FROM User WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName(UserPassData::class);
- $Data->setQuery($query);
- $Data->addParam($userId);
-
- /** @var UserPassData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
-
- return ($queryRes !== false && $queryRes->getLastUpdateMPass() >= $configMPassTime);
- }
-
- /**
- * Actualizar la clave maestra con la clave anterior del usuario
- *
- * @param string $oldUserPass
- * @param UserLoginData $UserData $UserData
- * @return bool
- * @throws QueryException
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \PHPMailer\PHPMailer\Exception
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \Psr\Container\NotFoundExceptionInterface
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function updateMasterPassFromOldPass($oldUserPass, UserLoginData $UserData)
- {
- if (self::loadUserMPass($UserData, $oldUserPass) === UserPass::MPASS_OK) {
- return self::updateUserMPass(self::$clearUserMPass, $UserData);
- }
-
- return self::MPASS_WRONG;
- }
-
- /**
- * Comprueba la clave maestra del usuario.
- *
- * @param UserLoginData $userLoginData
- * @param string $key Clave de cifrado
- * @return bool
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \Psr\Container\NotFoundExceptionInterface
- */
- public static function loadUserMPass(UserLoginData $userLoginData, $key = null)
- {
- $userData = $userLoginData->getUserLoginResponse();
-
- $configHashMPass = ConfigDB::getValue('masterPwd');
-
- if (empty($configHashMPass)
- || empty($userData->getMPass())
- || empty($userData->getMKey())
- ) {
- return self::MPASS_NOTSET;
- }
-
- if ($userData->getLastUpdateMPass() < ConfigDB::getValue('lastupdatempass')) {
- return self::MPASS_CHANGED;
- }
-
- if ($userData->isIsMigrate() === 1) {
- return UpgradeUser::upgradeMasterKey($userLoginData) ? self::MPASS_OK : self::MPASS_WRONG;
- }
-
- if ($key === null && $userData->isIsChangedPass() === 1) {
- return self::MPASS_CHECKOLD;
- }
-
- try {
- $securedKey = Crypt::unlockSecuredKey($userData->getMKey(), self::getKey($userLoginData, $key));
- $userMPass = Crypt::decrypt($userData->getMPass(), $securedKey, self::getKey($userLoginData, $key));
-
- // Comprobamos el hash de la clave del usuario con la guardada
- if (Hash::checkHashKey($userMPass, $configHashMPass)) {
- self::$gotMPass = true;
- self::$clearUserMPass = $userMPass;
-
- CryptSession::saveSessionKey($userMPass);
-
- return self::MPASS_OK;
- }
- } catch (WrongKeyOrModifiedCiphertextException $e) {
- return self::MPASS_CHECKOLD;
- }
-
- return self::MPASS_WRONG;
- }
-
- /**
- * Obtener una clave de cifrado basada en la clave del usuario y un salt.
- *
- * @param UserLoginData $userLoginData
- * @param string $key Clave de cifrado
- * @return string con la clave de cifrado
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \Psr\Container\NotFoundExceptionInterface
- */
- private static function getKey(UserLoginData $userLoginData, $key = null)
- {
- $pass = $key === null ? $userLoginData->getLoginPass() : $key;
-
- /** @var ConfigData $ConfigData */
- $ConfigData = Bootstrap::getContainer()->get(ConfigData::class);
-
- return $pass . $userLoginData->getLoginUser() . $ConfigData->getPasswordSalt();
- }
-
- /**
- * Actualizar la clave maestra del usuario en la BBDD.
- *
- * @param string $userMPass con la clave maestra
- * @param UserLoginData $userLoginData $userLoginData
- * @return bool
- * @throws QueryException
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \PHPMailer\PHPMailer\Exception
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \Psr\Container\NotFoundExceptionInterface
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function updateUserMPass($userMPass, UserLoginData $userLoginData)
- {
- $userData = $userLoginData->getUserLoginResponse();
- $configHashMPass = ConfigDB::getValue('masterPwd');
-
- if ($configHashMPass === false) {
- return self::MPASS_NOTSET;
- }
-
- if (null === $configHashMPass) {
- $configHashMPass = Hash::hashKey($userMPass);
- ConfigDB::setValue('masterPwd', $configHashMPass);
- }
-
- if (Hash::checkHashKey($userMPass, $configHashMPass)
- || \SP\Core\Upgrade\Crypt::migrateHash($userMPass)
- ) {
- $securedKey = Crypt::makeSecuredKey(self::getKey($userLoginData));
- $cryptMPass = Crypt::encrypt($userMPass, $securedKey, self::getKey($userLoginData));
-
- if (!empty($cryptMPass)) {
- if (strlen($securedKey) > 1000 || strlen($cryptMPass) > 1000) {
- throw new QueryException(SPException::ERROR, __u('Error interno'), '', LoginController::STATUS_INTERNAL_ERROR);
- }
-
- $query = /** @lang SQL */
- 'UPDATE User SET
- mPass = ?,
- mKey = ?,
- lastUpdateMPass = UNIX_TIMESTAMP(),
- isMigrate = 0,
- isChangedPass = 0
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($cryptMPass);
- $Data->addParam($securedKey);
- $Data->addParam($userData->getId());
-
- self::$clearUserMPass = $userMPass;
- self::$gotMPass = true;
-
- CryptSession::saveSessionKey($userMPass);
-
- $userData->setMPass($cryptMPass);
- $userData->setMKey($securedKey);
-
- DbWrapper::getQuery($Data);
-
- return self::MPASS_OK;
- }
- }
-
- return self::MPASS_WRONG;
- }
-
- /**
- * @return string
- */
- public static function getClearUserMPass()
- {
- return self::$clearUserMPass;
- }
-
- /**
- * Modificar la clave de un usuario.
- *
- * @param $userId
- * @param $userPass
- * @return $this
- * @throws InvalidClassException
- * @throws QueryException
- * @throws SPException
- * @throws \PHPMailer\PHPMailer\Exception
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function updateUserPass($userId, $userPass)
- {
- $this->setItemData(User::getItem()->getById($userId));
-
- $query = /** @lang SQL */
- 'UPDATE User SET
- pass = ?,
- hashSalt = \'\',
- isChangePass = 0,
- mPass = \'\',
- mKey = \'\',
- lastUpdate = NOW()
- WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(Hash::hashKey($userPass));
- $Data->addParam($userId);
- $Data->setOnErrorMessage(__u('Error al modificar la clave'));
-
- DbWrapper::getQuery($Data);
-
- $Log = new Log();
- $Log->getLogMessage()
- ->setAction(__u('Modificar Clave Usuario'))
- ->addDetails(__u('Login'), $this->itemData->getLogin());
- $Log->writeLog();
-
- Email::sendEmail($Log->getLogMessage());
-
- return $this;
- }
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserPassData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPassRecover.php b/lib/SP/Mgmt/Users/UserPassRecover.php
deleted file mode 100644
index d722a42d..00000000
--- a/lib/SP/Mgmt/Users/UserPassRecover.php
+++ /dev/null
@@ -1,238 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserData;
-use SP\DataModel\UserPassRecoverData;
-use SP\Mgmt\ItemInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class UserPassRecover para la gestión de recuperaciones de claves de usuarios
- *
- * @package SP
- * @property UserPassRecoverData $itemData
- */
-class UserPassRecover extends UserPassRecoverBase implements ItemInterface
-{
- /**
- * Tiempo máximo para recuperar la clave
- */
- const MAX_PASS_RECOVER_TIME = 3600;
- /**
- * Número de intentos máximos para recuperar la clave
- */
- const MAX_PASS_RECOVER_LIMIT = 3;
- const USER_LOGIN_EXIST = 1;
- const USER_MAIL_EXIST = 2;
-
- /**
- * Comprobar el límite de recuperaciones de clave.
- *
- * @param UserData $UserData con el login del usuario
- * @return bool
- */
- public static function checkPassRecoverLimit(UserData $UserData)
- {
- $query = /** @lang SQL */
- 'SELECT userId
- FROM UserPassRecover
- WHERE userId = ?
- AND used = 0
- AND date >= ?';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($UserData->getId());
- $Data->addParam(time() - self::MAX_PASS_RECOVER_TIME);
-
- try {
- DbWrapper::getQuery($Data);
- } catch (SPException $e) {
- return false;
- }
-
- return $Data->getQueryNumRows() >= self::MAX_PASS_RECOVER_LIMIT;
- }
-
- /**
- * Comprobar el hash de recuperación de clave.
- *
- * @param $hash
- * @return $this
- * @throws SPException
- */
- public function getHashUserId($hash)
- {
- $query = /** @lang SQL */
- 'SELECT userId
- FROM UserPassRecover
- WHERE hash = ?
- AND used = 0
- AND date >= ?
- ORDER BY date DESC LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName($this->getDataModel());
- $Data->setQuery($query);
- $Data->addParam($hash);
- $Data->addParam(time() - self::MAX_PASS_RECOVER_TIME);
-
- /** @var UserPassRecoverData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- throw new SPException(__('Error en comprobación de hash', false), SPException::ERROR);
- } elseif ($Data->getQueryNumRows() === 0) {
- throw new SPException(__('Hash inválido o expirado', false), SPException::INFO);
- }
-
- $this->itemData = $queryRes;
-
- $this->update();
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE UserPassRecover SET used = 1 WHERE hash = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getHash());
- $Data->setOnErrorMessage(__('Error interno', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @return $this
- * @throws SPException
- */
- public function add()
- {
- $query = /** @lang SQL */
- 'INSERT INTO UserPassRecover SET
- userId = ?,
- hash = ?,
- date = UNIX_TIMESTAMP(),
- used = 0';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getUserId());
- $Data->addParam($this->itemData->getHash());
- $Data->setOnErrorMessage(__('Error al generar el hash de recuperación', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function delete($id)
- {
- // TODO: Implement delete() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function getById($id)
- {
- // TODO: Implement getById() method.
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Eliminar elementos en lote
- *
- * @param array $ids
- * @return $this
- */
- public function deleteBatch(array $ids)
- {
- // TODO: Implement deleteBatch() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPassRecoverBase.php b/lib/SP/Mgmt/Users/UserPassRecoverBase.php
deleted file mode 100644
index 56a878af..00000000
--- a/lib/SP/Mgmt/Users/UserPassRecoverBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\UserPassRecoverData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class UserPassRecoverBase
- *
- * @package SP\Mgmt\Users
- */
-abstract class UserPassRecoverBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserPassRecoverData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPreferences.php b/lib/SP/Mgmt/Users/UserPreferences.php
deleted file mode 100644
index f847c951..00000000
--- a/lib/SP/Mgmt/Users/UserPreferences.php
+++ /dev/null
@@ -1,158 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\UserData;
-use SP\DataModel\UserPreferencesData;
-use SP\Mgmt\ItemInterface;
-use SP\Mgmt\ItemTrait;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-use SP\Util\Util;
-
-/**
- * Class UsersPreferences para la gestion de las preferencias de usuarios
- *
- * @package SP
- * @property UserPreferencesData $itemData
- */
-class UserPreferences extends UserPreferencesBase implements ItemInterface
-{
- use ItemTrait;
-
- /**
- * @return mixed
- */
- public function add()
- {
- // TODO: Implement add() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function delete($id)
- {
- // TODO: Implement delete() method.
- }
-
- /**
- * @return $this
- * @throws \SP\Core\Exceptions\SPException
- */
- public function update()
- {
- $query = /** @lang SQL */
- 'UPDATE usrData
- SET user_preferences = ?
- WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(serialize($this->itemData));
- $Data->addParam($this->itemData->getUserId());
- $Data->setOnErrorMessage(__('Error al actualizar preferencias', false));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-
- /**
- * @param $id int
- * @return UserPreferencesData
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \Psr\Container\NotFoundExceptionInterface
- */
- public function getById($id)
- {
- $query = /** @lang SQL */
- 'SELECT id, preferences FROM User WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setMapClassName(UserData::class);
- $Data->setQuery($query);
- $Data->addParam($id);
-
- /** @var UserData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false
- || $queryRes->getPreferences() === null
- || $queryRes->getPreferences() === ''
- ) {
- return $this->getItemData();
- }
-
- return Util::unserialize($this->getDataModel(), $queryRes->getPreferences(), 'SP\UserPreferences');
- }
-
- /**
- * @return mixed
- */
- public function getAll()
- {
- // TODO: Implement getAll() method.
- }
-
- /**
- * @param $id int
- * @return mixed
- */
- public function checkInUse($id)
- {
- // TODO: Implement checkInUse() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnUpdate()
- {
- // TODO: Implement checkDuplicatedOnUpdate() method.
- }
-
- /**
- * @return bool
- */
- public function checkDuplicatedOnAdd()
- {
- // TODO: Implement checkDuplicatedOnAdd() method.
- }
-
- /**
- * Devolver los elementos con los ids especificados
- *
- * @param array $ids
- * @return mixed
- */
- public function getByIdBatch(array $ids)
- {
- // TODO: Implement getByIdBatch() method.
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPreferencesBase.php b/lib/SP/Mgmt/Users/UserPreferencesBase.php
deleted file mode 100644
index 8c4e420a..00000000
--- a/lib/SP/Mgmt/Users/UserPreferencesBase.php
+++ /dev/null
@@ -1,53 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\UserPreferencesData;
-use SP\Mgmt\ItemBaseInterface;
-use SP\Mgmt\ItemBaseTrait;
-
-/**
- * Class UserPreferencesBase
- *
- * @package SP\Mgmt\Users
- */
-abstract class UserPreferencesBase implements ItemBaseInterface
-{
- use ItemBaseTrait;
-
- /**
- * Inicializar la clase
- *
- * @return void
- * @throws InvalidClassException
- */
- protected function init()
- {
- $this->setDataModel(UserPreferencesData::class);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserPreferencesUtil.php b/lib/SP/Mgmt/Users/UserPreferencesUtil.php
deleted file mode 100644
index 59204bbb..00000000
--- a/lib/SP/Mgmt/Users/UserPreferencesUtil.php
+++ /dev/null
@@ -1,130 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use Plugins\Authenticator\AuthenticatorData;
-use Plugins\Authenticator\AuthenticatorPlugin;
-use SP\Bootstrap;
-use SP\Config\ConfigData;
-use SP\Core\Exceptions\SPException;
-use SP\Core\Plugin\PluginUtil;
-use SP\DataModel\PluginData;
-use SP\DataModel\UserData;
-use SP\DataModel\UserPreferencesData;
-use SP\Log\Log;
-use SP\Mgmt\Plugins\Plugin;
-use SP\Util\Util;
-
-/**
- * Class UserPreferencesUtil
- *
- * @package SP\Mgmt\Users
- */
-class UserPreferencesUtil
-{
- /**
- * Migrar las preferencias
- *
- * @return bool
- * @throws \Psr\Container\NotFoundExceptionInterface
- * @throws \Psr\Container\ContainerExceptionInterface
- * @throws \SP\Core\Exceptions\SPException
- */
- public static function migrate()
- {
- $Container = Bootstrap::getContainer();
- /** @var ConfigData $ConfigData */
- $ConfigData = $Container->get(ConfigData::class);
- /** @var Log $Log */
- $Log = $Container->get(Log::class);
-
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__FUNCTION__);
- $LogMessage->addDescription(__('Actualizando preferencias', false));
-
- foreach (User::getItem()->getAll() as $User) {
- try {
- $Preferences = $User->getPreferences();
-
- if (!empty($Preferences)) {
- $LogMessage->addDetails(__('Usuario', false), $User->getLogin());
-
- /** @var UserPreferencesData $Preferences */
- $Preferences = Util::unserialize(UserPreferencesData::class, $Preferences, 'SP\UserPreferences');
- $User->setPreferences($Preferences);
-
- // FIXME
- $Preferences->setTheme($ConfigData->getSiteTheme());
-
- if ($Preferences->isUse2Fa()) {
- self::migrateTwoFA($User);
-
- $Preferences->setUse2Fa(0);
- }
-
- $Preferences->setUserId($User->getId());
-
- UserPreferences::getItem($Preferences)->update();
- }
- } catch (SPException $e) {
- $LogMessage->addDescription($e->getMessage());
- $Log->setLogLevel(Log::ERROR);
- $Log->writeLog();
- }
- }
-
- $LogMessage->addDescription(__('Preferencias actualizadas', false));
- $Log->writeLog();
-
- return true;
- }
-
- /**
- * Migrar la función de 2FA a plugin Authenticator
- *
- * @param UserData $UserData
- * @throws \SP\Core\Exceptions\SPException
- */
- protected static function migrateTwoFA(UserData $UserData)
- {
- PluginUtil::loadPlugins();
-
- /** @var AuthenticatorData $AuthenticatorData */
- $AuthenticatorData = new AuthenticatorData();
- $AuthenticatorData->setUserId($UserData->getId());
- $AuthenticatorData->setIV(UserPass::getUserIVById($UserData->getId()));
- $AuthenticatorData->setTwofaEnabled(1);
- $AuthenticatorData->setDate(time());
-
- $data[$UserData->getId()] = $AuthenticatorData;
-
- $PluginData = new PluginData();
- $PluginData->setName(AuthenticatorPlugin::PLUGIN_NAME);
- $PluginData->setEnabled(1);
- $PluginData->setData(serialize($data));
-
- Plugin::getItem($PluginData)->update();
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserSSO.php b/lib/SP/Mgmt/Users/UserSSO.php
deleted file mode 100644
index 59041a89..00000000
--- a/lib/SP/Mgmt/Users/UserSSO.php
+++ /dev/null
@@ -1,174 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use SP\Core\Crypt\Hash;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserLoginData;
-use SP\Log\Email;
-use SP\Log\Log;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-defined('APP_ROOT') || die();
-
-/**
- * Class UserSSO
- *
- * @package SP\Mgmt\Users
- */
-class UserSSO extends User
-{
- /**
- * Comprobar si los datos del usuario de LDAP están en la BBDD.
- *
- * @param $userLogin
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkUserInDB($userLogin)
- {
- $query = /** @lang SQL */
- 'SELECT login FROM User WHERE LOWER(login) = LOWER(?) OR LOWER(ssoLogin) = LOWER(?) LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userLogin);
- $Data->addParam($userLogin);
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() === 1;
- }
-
- /**
- * @return mixed
- * @throws \SP\Core\Exceptions\SPException
- * @throws SPException
- */
- public function add()
- {
- if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(__u('Login/email de usuario duplicados'), SPException::INFO);
- }
-
- $groupId = $this->ConfigData->getSsoDefaultGroup();
- $profileId = $this->ConfigData->getSsoDefaultProfile();
-
- $this->itemData->setIsDisabled(($groupId === 0 || $profileId === 0) ? 1 : 0);
-
- $query = /** @lang SQL */
- 'INSERT INTO usrData SET
- user_name = ?,
- user_login = ?,
- user_ssoLogin = ?,
- user_notes = ?,
- user_groupId = ?,
- user_profileId = ?,
- user_mPass = \'\',
- user_mKey = \'\',
- user_isDisabled = ?,
- user_pass = ?,
- user_hashSalt = \'\'';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam(__('Usuario de SSO'));
- $Data->addParam($groupId);
- $Data->addParam($profileId);
- $Data->addParam((int)$this->itemData->isDisabled());
- $Data->addParam(Hash::hashKey($this->itemData->getLoginPass()));
- $Data->setOnErrorMessage(__('Error al guardar los datos de SSO', false));
-
- DbWrapper::getQuery($Data);
-
- $this->itemData->setId(DbWrapper::getLastId());
-
- $Log = new Log();
- $Log->getLogMessage()
- ->setAction(__('Nuevo usuario de SSO', false))
- ->addDescription(sprintf('%s (%s)', $this->itemData->getName(), $this->itemData->getLogin()));
- $Log->writeLog();
-
- Email::sendEmail($Log->getLogMessage());
-
- return $this;
- }
-
- /**
- * Comprobar duplicados por login e email en minúsculas
- *
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public function checkDuplicatedOnAdd()
- {
- $query = /** @lang SQL */
- 'SELECT user_login FROM usrData WHERE LOWER(user_login) = LOWER(?) OR LOWER(user_ssoLogin) = LOWER(?)';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($this->itemData->getLogin());
- $Data->addParam($this->itemData->getLogin());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() > 0;
- }
-
- /**
- * Actualizar al realizar login
- *
- * @param UserLoginData $itemData
- * @return $this
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function updateOnLogin(UserLoginData $itemData)
- {
- $query = 'UPDATE User SET
- pass = ?,
- hashSalt = \'\',
- lastUpdate = NOW(),
- lastLogin = NOW()
- WHERE LOWER(login) = LOWER(?) OR LOWER(ssoLogin) = LOWER(?) LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam(Hash::hashKey($itemData->getLoginPass()));
- $Data->addParam($itemData->getLoginUser());
- $Data->addParam($itemData->getLoginUser());
- $Data->setOnErrorMessage(__u('Error al actualizar la clave del usuario en la BBDD'));
-
- DbWrapper::getQuery($Data);
-
- return $this;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserSearch.php b/lib/SP/Mgmt/Users/UserSearch.php
deleted file mode 100644
index 51ee9397..00000000
--- a/lib/SP/Mgmt/Users/UserSearch.php
+++ /dev/null
@@ -1,86 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-use SP\Core\SessionFactory;
-use SP\DataModel\ItemSearchData;
-use SP\Mgmt\ItemSearchInterface;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class UserSearch
- *
- * @package SP\Mgmt\Users
- */
-class UserSearch extends UserBase implements ItemSearchInterface
-{
- /**
- * @param ItemSearchData $SearchData
- * @return mixed
- */
- public function getMgmtSearch(ItemSearchData $SearchData)
- {
- $Data = new QueryData();
- $Data->setSelect('user_id,
- user_name,
- user_login,
- userprofile_name,
- usergroup_name,
- BIN(user_isAdminApp) AS user_isAdminApp,
- BIN(user_isAdminAcc) AS user_isAdminAcc,
- BIN(user_isLdap) AS user_isLdap,
- BIN(user_isDisabled) AS user_isDisabled,
- BIN(user_isChangePass) AS user_isChangePass');
- $Data->setFrom('usrData LEFT JOIN usrProfiles ON user_profileId = userprofile_id LEFT JOIN usrGroups ON usrData.user_groupId = usergroup_id');
- $Data->setOrder('user_name');
-
- if ($SearchData->getSeachString() !== '') {
- if (SessionFactory::getUserData()->isAdminApp()) {
- $Data->setWhere('user_name LIKE ? OR user_login LIKE ?');
- } else {
- $Data->setWhere('user_name LIKE ? OR user_login LIKE ? AND user_isAdminApp = 0');
- }
-
- $search = '%' . $SearchData->getSeachString() . '%';
- $Data->addParam($search);
- $Data->addParam($search);
- } elseif (!SessionFactory::getUserData()->isAdminApp()) {
- $Data->setWhere('user_isAdminApp = 0');
- }
-
- $Data->setLimit('?, ?');
- $Data->addParam($SearchData->getLimitStart());
- $Data->addParam($SearchData->getLimitCount());
-
- DbWrapper::setFullRowCount();
-
- $queryRes = DbWrapper::getResultsArray($Data);
-
- $queryRes['count'] = $Data->getQueryNumRows();
-
- return $queryRes;
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Mgmt/Users/UserUtil.php b/lib/SP/Mgmt/Users/UserUtil.php
deleted file mode 100644
index 56bcc74e..00000000
--- a/lib/SP/Mgmt/Users/UserUtil.php
+++ /dev/null
@@ -1,196 +0,0 @@
-.
- */
-
-namespace SP\Mgmt\Users;
-
-defined('APP_ROOT') || die();
-
-use SP\DataModel\UserData;
-use SP\Storage\DbWrapper;
-use SP\Storage\QueryData;
-
-/**
- * Class UserUtil
- *
- * @package SP
- */
-class UserUtil
-{
- const USER_LOGIN_EXIST = 1;
- const USER_MAIL_EXIST = 2;
-
- /**
- * Comprobar si un usuario y email existen.
- *
- * @param UserData $UserData
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function checkUserMail(UserData $UserData)
- {
- $query = /** @lang SQL */
- 'SELECT user_id FROM usrData
- WHERE LOWER(user_login) = LOWER(?)
- AND LOWER(user_email) = LOWER(?) LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($UserData->getLogin());
- $Data->addParam($UserData->getEmail());
-
- DbWrapper::getQuery($Data);
-
- return $Data->getQueryNumRows() === 1;
- }
-
- /**
- * Obtener el email de un usuario.
- *
- * @param int $userId con el Id del usuario
- * @return string con el email del usuario
- */
- public static function getUserEmail($userId)
- {
- $query = /** @lang SQL */
- 'SELECT user_email FROM usrData WHERE user_id = ? AND user_email IS NOT NULL LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userId);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- return false;
- }
-
- return $queryRes->user_email;
- }
-
- /**
- * Actualiza el último inicio de sesión del usuario en la BBDD.
- *
- * @param $userId int El id del usuario
- * @return bool
- * @throws \SP\Core\Exceptions\QueryException
- * @throws \SP\Core\Exceptions\ConstraintException
- */
- public static function setUserLastLogin($userId)
- {
- $query = /** @lang SQL */
- 'UPDATE User SET lastLogin = NOW(), loginCount = loginCount + 1 WHERE id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($userId);
-
- return DbWrapper::getQuery($Data);
- }
-
-
- /**
- * Obtener el login de usuario a partir del Id.
- *
- * @param int $id con el id del usuario
- * @return string con el login del usuario
- */
- public static function getUserLoginById($id)
- {
- $query = /** @lang SQL */
- 'SELECT user_login FROM usrData WHERE user_id = ? LIMIT 1';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($id);
-
- $queryRes = DbWrapper::getResults($Data);
-
- if ($queryRes === false) {
- return false;
- }
-
- return $queryRes->user_login;
- }
-
- /**
- * Obtener el id y login de los usuarios disponibles
- *
- * @return UserData[]
- */
- public static function getUsersLogin()
- {
- $query = /** @lang SQL */
- 'SELECT user_id, user_login, user_name FROM usrData ORDER BY user_login';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Obtener el email de los usuarios de un grupo
- *
- * @param $groupId
- * @return array
- */
- public static function getUserGroupEmail($groupId)
- {
- $query = /** @lang SQL */
- 'SELECT user_id, user_login, user_name, user_email
- FROM usrData
- LEFT JOIN UserToUserGroup ON usertogroup_userId = user_id
- WHERE user_email IS NOT NULL
- AND user_groupId = ? OR usertogroup_groupId = ?
- AND user_isDisabled = 0
- ORDER BY user_login';
-
- $Data = new QueryData();
- $Data->setQuery($query);
- $Data->addParam($groupId);
- $Data->addParam($groupId);
-
- return DbWrapper::getResultsArray($Data);
- }
-
- /**
- * Obtener el email de los usuarios
- *
- * @return array
- */
- public static function getUsersEmail()
- {
- $query = /** @lang SQL */
- 'SELECT user_id, user_login, user_name, user_email
- FROM usrData
- WHERE user_email IS NOT NULL AND user_isDisabled = 0
- ORDER BY user_login';
-
- $Data = new QueryData();
- $Data->setQuery($query);
-
- return DbWrapper::getResultsArray($Data);
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Services/Api/ApiRequest.php b/lib/SP/Services/Api/ApiRequest.php
new file mode 100644
index 00000000..d65453b5
--- /dev/null
+++ b/lib/SP/Services/Api/ApiRequest.php
@@ -0,0 +1,97 @@
+.
+ */
+
+namespace SP\Services\Api;
+
+use SP\Core\DataCollection;
+use SP\Services\ServiceException;
+
+/**
+ * Class ApiRequest
+ *
+ * @package SP\Services\Api
+ */
+class ApiRequest extends DataCollection
+{
+ /**
+ * @var string
+ */
+ protected $method;
+ /**
+ * @var int
+ */
+ protected $id;
+
+ /**
+ * @return string
+ */
+ public function getMethod()
+ {
+ return $this->method;
+ }
+
+ /**
+ * @return int
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * Obtener los datos de la petición
+ *
+ * Comprueba que el JSON esté bien formado
+ *
+ * @throws ServiceException
+ */
+ public function getRequestData()
+ {
+ if (($request = file_get_contents('php://input')) === false
+ || ($data = json_decode($request, true)) === null
+ ) {
+ throw new ServiceException(
+ __u('Datos inválidos'),
+ ServiceException::ERROR,
+ null,
+ -32700
+ );
+ }
+
+ if (!isset($data['jsonrpc'], $data['method'], $data['params'], $data['id'], $data['params']['authToken'])) {
+ throw new ServiceException(
+ __u('Fomato incorrecto'),
+ ServiceException::ERROR,
+ null,
+ -32600
+ );
+ }
+
+ $this->method = preg_replace('#[^a-z/]+#i', '', $data['method']);
+ $this->id = filter_var($data['id'], FILTER_VALIDATE_INT);
+ $this->attributes = $data['params'];
+
+ return $this;
+ }
+}
\ No newline at end of file
diff --git a/lib/SP/Api/ApiResponse.php b/lib/SP/Services/Api/ApiResponse.php
similarity index 98%
rename from lib/SP/Api/ApiResponse.php
rename to lib/SP/Services/Api/ApiResponse.php
index 3e1c7779..e09de76f 100644
--- a/lib/SP/Api/ApiResponse.php
+++ b/lib/SP/Services/Api/ApiResponse.php
@@ -22,7 +22,7 @@
* along with sysPass. If not, see .
*/
-namespace SP\Api;
+namespace SP\Services\Api;
/**
* Class ApiResponse
diff --git a/lib/SP/Services/Api/ApiService.php b/lib/SP/Services/Api/ApiService.php
index 4b9451d5..ffbd9a23 100644
--- a/lib/SP/Services/Api/ApiService.php
+++ b/lib/SP/Services/Api/ApiService.php
@@ -29,7 +29,6 @@ use SP\Core\Acl\ActionsInterface;
use SP\Core\Crypt\Hash;
use SP\Core\Crypt\Vault;
use SP\DataModel\AuthTokenData;
-use SP\Html\Html;
use SP\Repositories\Track\TrackRequest;
use SP\Services\AuthToken\AuthTokenService;
use SP\Services\Service;
@@ -54,13 +53,9 @@ class ApiService extends Service
*/
protected $trackService;
/**
- * @var mixed
+ * @var ApiRequest
*/
- protected $requestData;
- /**
- * @var int
- */
- protected $requestId;
+ protected $apiRequest;
/**
* @var TrackRequest
*/
@@ -74,48 +69,6 @@ class ApiService extends Service
*/
protected $masterPass;
- /**
- * Obtener los datos de la petición
- *
- * Comprueba que el JSON esté bien formado
- *
- * @throws ServiceException
- */
- public static function getRequestData()
- {
- $request = file_get_contents('php://input');
- $data = json_decode(Html::sanitize($request));
-
- if (!is_object($data) || json_last_error() !== JSON_ERROR_NONE) {
- throw new ServiceException(
- __u('Datos inválidos'),
- ServiceException::ERROR,
- null,
- -32700
- );
- }
-
- if (!isset($data->jsonrpc, $data->method, $data->params, $data->id, $data->params->authToken)) {
- throw new ServiceException(
- __u('Formato incorrecto'),
- ServiceException::ERROR,
- null,
- -32600
- );
- }
-
- if (!isset($data->params->authToken)) {
- throw new ServiceException(
- __u('Formato incorrecto'),
- ServiceException::ERROR,
- null,
- -32602
- );
- }
-
- return $data;
- }
-
/**
* Sets up API
*
@@ -125,8 +78,6 @@ class ApiService extends Service
*/
public function setup($actionId)
{
- $this->requestId = (int)$this->requestData->id;
-
if ($this->trackService->checkTracking($this->trackRequest)) {
$this->addTracking();
@@ -173,27 +124,25 @@ class ApiService extends Service
* Devolver el valor de un parámetro
*
* @param string $param
- * @param bool $required Si es requerido
- * @param mixed $default Valor por defecto
+ * @param bool $required Si es requerido
+ * @param mixed $default Valor por defecto
* @return int|string
* @throws ServiceException
*/
public function getParam($param, $required = false, $default = null)
{
- if (null !== $this->requestData
- && isset($this->requestData->params->{$param})
+ if (null === $this->apiRequest
+ || ($required === true && !$this->apiRequest->exists($param))
) {
- return $this->requestData->params->{$param};
- } elseif ($required === true) {
throw new ServiceException(
__u('Parámetros incorrectos'),
ServiceException::ERROR,
- $this->getHelp($this->requestData->method),
+ $this->getHelp($this->apiRequest->getMethod()),
-32602
);
}
- return $default;
+ return $this->apiRequest->get($param, $default);
}
/**
@@ -362,6 +311,54 @@ class ApiService extends Service
}
}
+ /**
+ * @param string $param
+ * @param bool $required
+ * @param null $default
+ * @return int|string
+ * @throws ServiceException
+ */
+ public function getParamInt($param, $required = false, $default = null)
+ {
+ return filter_var($this->getParam($param, $required, $default), FILTER_VALIDATE_INT);
+ }
+
+ /**
+ * @param string $param
+ * @param bool $required
+ * @param null $default
+ * @return int|string
+ * @throws ServiceException
+ */
+ public function getParamString($param, $required = false, $default = null)
+ {
+ return filter_var($this->getParam($param, $required, $default), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
+ }
+
+ /**
+ * @param string $param
+ * @param bool $required
+ * @param null $default
+ * @return int|string
+ * @throws ServiceException
+ */
+ public function getParamEmail($param, $required = false, $default = null)
+ {
+ return filter_var($this->getParam($param, $required, $default), FILTER_SANITIZE_EMAIL);
+ }
+
+ /**
+ * @param string $param
+ * @param bool $required
+ * @param null $default
+ * @return int|string
+ * @throws ServiceException
+ */
+ public function getParamRaw($param, $required = false, $default = null)
+ {
+ return filter_var($this->getParam($param, $required, $default), FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
+ }
+
/**
* @return string
*/
@@ -371,11 +368,14 @@ class ApiService extends Service
}
/**
- * @param mixed $requestData
+ * @param ApiRequest $apiRequest
+ * @return ApiService
*/
- public function setRequestData($requestData)
+ public function setApiRequest(ApiRequest $apiRequest)
{
- $this->requestData = $requestData;
+ $this->apiRequest = $apiRequest;
+
+ return $this;
}
/**
@@ -383,7 +383,7 @@ class ApiService extends Service
*/
public function getRequestId()
{
- return $this->requestId;
+ return $this->apiRequest->getId();
}
/**
diff --git a/lib/SP/Api/JsonRpcResponse.php b/lib/SP/Services/Api/JsonRpcResponse.php
similarity index 95%
rename from lib/SP/Api/JsonRpcResponse.php
rename to lib/SP/Services/Api/JsonRpcResponse.php
index 95462502..4aa7fe4b 100644
--- a/lib/SP/Api/JsonRpcResponse.php
+++ b/lib/SP/Services/Api/JsonRpcResponse.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link https://syspass.org
+ * @author nuxsmin
+ * @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -22,7 +22,7 @@
* along with sysPass. If not, see .
*/
-namespace SP\Api;
+namespace SP\Services\Api;
use SP\Core\Exceptions\SPException;
use SP\Util\Json;
diff --git a/lib/SP/Util/Util.php b/lib/SP/Util/Util.php
index 8ebf2862..b7abf8eb 100644
--- a/lib/SP/Util/Util.php
+++ b/lib/SP/Util/Util.php
@@ -568,27 +568,6 @@ class Util
return ($in ? true : false);
}
- /**
- * Establecer variable de sesión para recargar la aplicación.
- */
- public static function reload()
- {
- if (SessionFactory::getReload() === false) {
- SessionFactory::setReload(true);
- }
- }
-
- /**
- * Comprobar si se necesita recargar la aplicación.
- */
- public static function checkReload()
- {
- if (SessionFactory::getReload() === true) {
- SessionFactory::setReload(false);
- exit('');
- }
- }
-
/**
* Recorrer un array y escapar los carácteres no válidos en Javascript.
*