From 2cbaed9965a3d5277e41be1b66cd13303709414a Mon Sep 17 00:00:00 2001
From: nuxsmin
Date: Thu, 8 Feb 2018 23:10:12 +0100
Subject: [PATCH] * [MOD] Improved CSS & JS resources handling. * [MOD]
Improved bootstrap workflow. Work in progress.
---
.gitignore | 1 +
.../config/strings.js.inc | 0
.../web/Controllers/AccountFileController.php | 18 +-
.../web/Controllers/BootstrapController.php | 17 +-
.../Helpers/Account/AccountHelper.php | 6 +-
.../web/Controllers/Helpers/LayoutHelper.php | 22 +-
.../web/Controllers/IndexController.php | 2 +
.../web/Controllers/MainController.php | 8 +-
.../web/Controllers/ResourceController.php | 129 ++++
.../web/Controllers/SimpleControllerBase.php | 56 +-
.../web/Controllers/Traits/ItemTrait.php | 4 +-
.../views/_partials/error-list.inc | 4 +-
lib/Base.php | 2 +-
lib/SP/Account/Account.php | 13 +-
lib/SP/Account/AccountCrypt.php | 5 +-
lib/SP/Account/AccountHistory.php | 4 +-
lib/SP/Account/AccountHistoryCrypt.php | 5 +-
lib/SP/Account/AccountUtil.php | 7 +-
lib/SP/Api/ApiBase.php | 14 +-
lib/SP/Api/ApiRequest.php | 14 +-
lib/SP/Api/ApiUtil.php | 2 +-
lib/SP/Api/SyspassApi.php | 12 +-
lib/SP/Bootstrap.php | 627 +++++++++---------
lib/SP/Config/Config.php | 2 +-
lib/SP/Config/ConfigUtil.php | 6 +-
lib/SP/Controller/LoginController.php | 42 +-
.../Core/Acl/AccountPermissionException.php | 2 +-
lib/SP/Core/Acl/Acl.php | 77 ++-
lib/SP/Core/Acl/UnauthorizedPageException.php | 2 +-
lib/SP/Core/Backup.php | 18 +-
lib/SP/Core/CryptPKI.php | 6 +-
lib/SP/Core/Dic/Injector.php | 1 +
lib/SP/Core/Events/EventDispatcherBase.php | 4 +-
.../Exceptions/InitializationException.php | 35 +
lib/SP/Core/Exceptions/SPException.php | 26 +-
lib/SP/Core/Init.php | 8 +-
lib/SP/Core/Installer.php | 71 +-
lib/SP/Core/Language.php | 6 +-
lib/SP/Core/OldCrypt.php | 9 +-
lib/SP/Core/Plugin/PluginUtil.php | 4 +-
lib/SP/Core/Session/Session.php | 20 +
lib/SP/Core/Traits/InjectableTrait.php | 1 +
lib/SP/Core/Upgrade/Crypt.php | 6 +-
lib/SP/Core/Upgrade/Upgrade.php | 117 ++--
lib/SP/Core/XmlExport.php | 28 +-
lib/SP/DataModel/TrackData.php | 2 +-
lib/SP/Html/DataGrid/DataGridBase.php | 2 +-
lib/SP/Html/Minify.php | 201 ++++--
lib/SP/Import/CsvImportBase.php | 4 +-
lib/SP/Import/FileImport.php | 20 +-
lib/SP/Import/Import.php | 8 +-
lib/SP/Import/SyspassImport.php | 8 +-
lib/SP/Import/XmlFileImport.php | 8 +-
lib/SP/Import/XmlImportTrait.php | 6 +-
lib/SP/Mgmt/ApiTokens/ApiToken.php | 6 +-
lib/SP/Mgmt/Categories/Category.php | 6 +-
lib/SP/Mgmt/CustomFields/CustomField.php | 4 +-
lib/SP/Mgmt/CustomFields/CustomFieldDef.php | 6 +-
lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php | 8 +-
lib/SP/Mgmt/Customers/Customer.php | 8 +-
lib/SP/Mgmt/Files/File.php | 2 +-
lib/SP/Mgmt/Groups/Group.php | 8 +-
lib/SP/Mgmt/ItemBaseTrait.php | 4 +-
lib/SP/Mgmt/Notices/Notice.php | 12 +-
lib/SP/Mgmt/Plugins/Plugin.php | 2 +-
lib/SP/Mgmt/Profiles/Profile.php | 10 +-
lib/SP/Mgmt/PublicLinks/PublicLink.php | 10 +-
lib/SP/Mgmt/Tags/Tag.php | 8 +-
lib/SP/Mgmt/Users/User.php | 12 +-
lib/SP/Mgmt/Users/UserLdap.php | 3 +-
lib/SP/Mgmt/Users/UserMigrate.php | 6 +-
lib/SP/Mgmt/Users/UserPass.php | 4 +-
lib/SP/Mgmt/Users/UserPassRecover.php | 4 +-
lib/SP/Mgmt/Users/UserSSO.php | 3 +-
lib/SP/Mvc/View/Template.php | 8 +-
lib/SP/Providers/Auth/Auth.php | 12 +-
lib/SP/Providers/Auth/Database/Database.php | 12 +-
lib/SP/Providers/Auth/Ldap/LdapBase.php | 14 +-
lib/SP/Providers/Auth/Ldap/LdapMsAds.php | 3 +-
lib/SP/Providers/Auth/Ldap/LdapStd.php | 3 +-
.../Account/AccountFileRepository.php | 4 +-
.../Account/AccountHistoryRepository.php | 3 +-
.../Account/AccountRepository.php | 8 +-
.../AuthToken/AuthTokenRepository.php | 4 +-
.../Category/CategoryRepository.php | 4 +-
.../Repositories/Client/ClientRepository.php | 5 +-
.../CustomField/CustomFieldDefRepository.php | 2 +-
.../CustomField/CustomFieldRepository.php | 4 +-
lib/SP/Repositories/NoSuchItemException.php | 38 ++
.../Repositories/Plugin/PluginRepository.php | 2 +-
.../PublicLink/PublicLinkRepository.php | 12 +-
lib/SP/Repositories/Tag/TagRepository.php | 4 +-
lib/SP/Repositories/User/UserRepository.php | 17 +-
.../UserGroup/UserGroupRepository.php | 8 +-
.../UserPassRecoverRepository.php | 4 +-
.../UserProfile/UserProfileRepository.php | 8 +-
lib/SP/Services/Account/AccountService.php | 6 +-
lib/SP/Services/Auth/LoginService.php | 53 +-
.../Services/AuthToken/AuthTokenService.php | 4 +-
lib/SP/Services/Category/CategoryService.php | 2 +-
lib/SP/Services/Client/ClientService.php | 2 +-
lib/SP/Services/Config/ConfigService.php | 2 +-
.../Services/PublicLink/PublicLinkService.php | 4 +-
lib/SP/Services/Tag/TagService.php | 2 +-
.../User/UpdatedMasterPassException.php | 2 +-
lib/SP/Services/User/UserPassService.php | 6 +-
lib/SP/Services/User/UserService.php | 1 +
.../Services/UserGroup/UserGroupService.php | 2 +-
.../UserProfile/UserProfileService.php | 2 +-
lib/SP/Storage/DBUtil.php | 5 +-
lib/SP/Storage/Database.php | 2 +-
lib/SP/Storage/DbWrapper.php | 11 +-
lib/SP/Storage/MySQLHandler.php | 6 +-
lib/SP/Util/Checks.php | 10 +-
lib/SP/Util/Connection.php | 6 +-
lib/SP/Util/ErrorUtil.php | 4 +-
lib/SP/Util/Json.php | 2 +-
lib/SP/Util/Util.php | 4 +-
lib/SP/Util/Wiki/DokuWikiApi.php | 7 +-
lib/SP/Util/Wiki/DokuWikiApiBase.php | 10 +-
public/css/css.php | 54 --
public/css/fonts.css | 8 +-
public/css/fonts.min.css | 2 +-
public/js/js.php | 72 --
schemas/dbstructure.sql | 2 +-
125 files changed, 1216 insertions(+), 1104 deletions(-)
rename public/js/strings.js.php => app/config/strings.js.inc (100%)
create mode 100644 app/modules/web/Controllers/ResourceController.php
create mode 100644 lib/SP/Core/Exceptions/InitializationException.php
create mode 100644 lib/SP/Repositories/NoSuchItemException.php
delete mode 100644 public/css/css.php
delete mode 100644 public/js/js.php
diff --git a/.gitignore b/.gitignore
index 49f253c6..52fa9d98 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,6 +49,7 @@ app/cache/*
app/backup/*
app/config/*
!app/config/actions.xml
+!app/config/*.inc
res/
tools/
app/temp/*
diff --git a/public/js/strings.js.php b/app/config/strings.js.inc
similarity index 100%
rename from public/js/strings.js.php
rename to app/config/strings.js.inc
diff --git a/app/modules/web/Controllers/AccountFileController.php b/app/modules/web/Controllers/AccountFileController.php
index 93408114..d2d17723 100644
--- a/app/modules/web/Controllers/AccountFileController.php
+++ b/app/modules/web/Controllers/AccountFileController.php
@@ -64,7 +64,7 @@ class AccountFileController extends ControllerBase implements CrudControllerInte
{
try {
if (null === ($fileData = $this->accountFileService->getById($id))) {
- throw new SPException(SPException::SP_INFO, __u('El archivo no existe'));
+ throw new SPException(__u('El archivo no existe'), SPException::INFO);
}
$this->view->addTemplate('file', 'itemshow');
@@ -104,7 +104,7 @@ class AccountFileController extends ControllerBase implements CrudControllerInte
{
try {
if (null === ($fileData = $this->accountFileService->getById($id))) {
- throw new SPException(SPException::SP_INFO, __u('El archivo no existe'));
+ throw new SPException(__u('El archivo no existe'), SPException::INFO);
}
// Enviamos el archivo al navegador
@@ -135,13 +135,13 @@ class AccountFileController extends ControllerBase implements CrudControllerInte
$file = $this->router->request()->files()->get('inFile');
if ($accountId === 0 || null === $file) {
- throw new SPException(SPException::SP_ERROR, __u('CONSULTA INVÁLIDA'));
+ throw new SPException(__u('CONSULTA INVÁLIDA'), SPException::ERROR);
}
$allowedExts = $this->configData->getFilesAllowedExts();
if (count($allowedExts) === 0) {
- throw new SPException(SPException::SP_ERROR, __u('No hay extensiones permitidas'));
+ throw new SPException(__u('No hay extensiones permitidas'), SPException::ERROR);
}
$fileData = new FileData();
@@ -155,27 +155,27 @@ class AccountFileController extends ControllerBase implements CrudControllerInte
$fileData->setExtension(mb_strtoupper(pathinfo($fileData->getName(), PATHINFO_EXTENSION)));
if (!in_array($fileData->getExtension(), $allowedExts, true)) {
- throw new SPException(SPException::SP_ERROR, __u('Tipo de archivo no soportado'), sprintf(__('Extensión: %s'), $fileData->getExtension()));
+ throw new SPException(__u('Tipo de archivo no soportado'), SPException::ERROR, sprintf(__('Extensión: %s'), $fileData->getExtension()));
}
} else {
- throw new SPException(SPException::SP_ERROR, __u('Archivo inválido'), sprintf(__u('Archivo: %s'), $fileData->getName()));
+ throw new SPException(__u('Archivo inválido'), SPException::ERROR, sprintf(__u('Archivo: %s'), $fileData->getName()));
}
if (!file_exists($file['tmp_name'])) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno al leer el archivo'), sprintf(__u('Máximo tamaño: %s'), Util::getMaxUpload()));
+ throw new SPException(__u('Error interno al leer el archivo'), SPException::ERROR, sprintf(__u('Máximo tamaño: %s'), Util::getMaxUpload()));
}
$allowedSize = $this->configData->getFilesAllowedSize();
if ($fileData->getSize() > ($allowedSize * 1000)) {
- throw new SPException(SPException::SP_ERROR, __u('Tamaño de archivo superado'), sprintf(__u('Máximo tamaño: %d KB'), $fileData->getRoundSize()));
+ throw new SPException(__u('Tamaño de archivo superado'), SPException::ERROR, sprintf(__u('Máximo tamaño: %d KB'), $fileData->getRoundSize()));
}
// Leemos el archivo a una variable
$fileData->setContent(file_get_contents($file['tmp_name']));
if ($fileData->getContent() === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno al leer el archivo'));
+ throw new SPException(__u('Error interno al leer el archivo'), SPException::ERROR);
}
$this->accountFileService->create($fileData);
diff --git a/app/modules/web/Controllers/BootstrapController.php b/app/modules/web/Controllers/BootstrapController.php
index 0a236577..be782042 100644
--- a/app/modules/web/Controllers/BootstrapController.php
+++ b/app/modules/web/Controllers/BootstrapController.php
@@ -24,11 +24,9 @@
namespace SP\Modules\Web\Controllers;
-use Exception;
use SP\Bootstrap;
use SP\Core\CryptPKI;
use SP\Core\Plugin\PluginUtil;
-use SP\Core\SessionFactory;
use SP\Http\Cookies;
use SP\Http\Response;
use SP\Providers\Auth\Browser\Browser;
@@ -42,16 +40,18 @@ class BootstrapController extends SimpleControllerBase
{
/**
* Returns environment data
+ *
+ * @throws \SP\Core\Exceptions\FileNotFoundException
+ * @throws \SP\Core\Exceptions\SPException
*/
public function getEnvironmentAction()
{
$configData = $this->config->getConfigData();
$data = [
- 'lang' => require PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'strings.js.php',
+ 'lang' => require CONFIG_PATH . DIRECTORY_SEPARATOR . 'strings.js.inc',
'locale' => $configData->getSiteLang(),
'app_root' => Bootstrap::$WEBURI,
- 'pk' => '',
'max_file_size' => $configData->getFilesAllowedSize(),
'check_updates' => $this->session->getAuthCompleted()
&& ($configData->isCheckUpdates() || $configData->isChecknotices())
@@ -61,15 +61,10 @@ class BootstrapController extends SimpleControllerBase
'cookies_enabled' => Cookies::checkCookies(),
'plugins' => PluginUtil::getEnabledPlugins(),
'loggedin' => $this->session->isLoggedIn(),
- 'authbasic_autologin' => Browser::getServerAuthUser() && $configData->isAuthBasicAutoLoginEnabled()
+ 'authbasic_autologin' => Browser::getServerAuthUser() && $configData->isAuthBasicAutoLoginEnabled(),
+ 'pk' => $this->session->getPublicKey() ?: (new CryptPKI())->getPublicKey()
];
- try {
- $CryptPKI = new CryptPKI();
- $data['pk'] = SessionFactory::getPublicKey() ?: $CryptPKI->getPublicKey();
- } catch (Exception $e) {
- }
-
Response::printJson($data, 0);
}
}
\ No newline at end of file
diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
index 1d56162e..427e9487 100644
--- a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
+++ b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
@@ -174,11 +174,11 @@ class AccountHelper extends HelperBase
public function checkActionAccess()
{
if (!$this->acl->checkUserAccess($this->actionId)) {
- throw new UnauthorizedPageException(SPException::SP_INFO);
+ throw new UnauthorizedPageException(SPException::INFO);
}
if (!UserPass::checkUserUpdateMPass($this->session->getUserData()->getId())) {
- throw new UpdatedMasterPassException(SPException::SP_INFO);
+ throw new UpdatedMasterPassException(SPException::INFO);
}
}
@@ -204,7 +204,7 @@ class AccountHelper extends HelperBase
$accountAcl = $this->accountAcl->getAcl($acccountAclDto);
if ($accountAcl === null || !$accountAcl->checkAccountAccess()) {
- throw new AccountPermissionException(SPException::SP_INFO);
+ throw new AccountPermissionException(SPException::INFO);
}
return $accountAcl;
diff --git a/app/modules/web/Controllers/Helpers/LayoutHelper.php b/app/modules/web/Controllers/Helpers/LayoutHelper.php
index 2349804d..3dcac9fd 100644
--- a/app/modules/web/Controllers/Helpers/LayoutHelper.php
+++ b/app/modules/web/Controllers/Helpers/LayoutHelper.php
@@ -137,9 +137,10 @@ class LayoutHelper extends HelperBase
{
$version = Util::getVersionStringNormalized();
+ $jsUri = Bootstrap::$WEBURI . '/index.php?r=resource/js';
$jsVersionHash = md5($version);
- $this->view->append('jsLinks', Bootstrap::$WEBROOT . '/public/js/js.php?v=' . $jsVersionHash);
- $this->view->append('jsLinks', Bootstrap::$WEBROOT . '/public/js/js.php?g=1&v=' . $jsVersionHash);
+ $this->view->append('jsLinks', $jsUri . '&v=' . $jsVersionHash);
+ $this->view->append('jsLinks', $jsUri . '&g=1&v=' . $jsVersionHash);
$themeInfo = $this->theme->getThemeInfo();
@@ -147,7 +148,7 @@ class LayoutHelper extends HelperBase
$themeJsBase = urlencode($this->theme->getThemePath() . DIRECTORY_SEPARATOR . 'js');
$themeJsFiles = urlencode(implode(',', $themeInfo['js']));
- $this->view->append('jsLinks', Bootstrap::$WEBROOT . '/public/js/js.php?f=' . $themeJsFiles . '&b=' . $themeJsBase . '&v=' . $jsVersionHash);
+ $this->view->append('jsLinks', $jsUri . '&f=' . $themeJsFiles . '&b=' . $themeJsBase . '&v=' . $jsVersionHash);
}
$userPreferences = $this->session->getUserData()->getPreferences();
@@ -158,15 +159,12 @@ class LayoutHelper extends HelperBase
$resultsAsCards = $this->configData->isResultsAsCards();
}
+ $cssUri = Bootstrap::$WEBURI . '/index.php?r=resource/css';
$cssVersionHash = md5($version . $resultsAsCards);
- $this->view->append('cssLinks', Bootstrap::$WEBROOT . '/public/css/css.php?v=' . $cssVersionHash);
+ $this->view->append('cssLinks', $cssUri . '&v=' . $cssVersionHash);
if (isset($themeInfo['css'])) {
- if ($resultsAsCards) {
- $themeInfo['css'][] = 'search-card.min.css';
- } else {
- $themeInfo['css'][] = 'search-grid.min.css';
- }
+ $themeInfo['css'][] = $resultsAsCards ? 'search-card.min.css' : 'search-grid.min.css';
if ($this->configData->isDokuwikiEnabled()) {
$themeInfo['css'][] = 'styles-wiki.min.css';
@@ -175,7 +173,7 @@ class LayoutHelper extends HelperBase
$themeCssBase = urlencode($this->theme->getThemePath() . DIRECTORY_SEPARATOR . 'css');
$themeCssFiles = urlencode(implode(',', $themeInfo['css']));
- $this->view->append('cssLinks', Bootstrap::$WEBROOT . '/public/css/css.php?f=' . $themeCssFiles . '&b=' . $themeCssBase . '&v=' . $jsVersionHash);
+ $this->view->append('cssLinks', $cssUri . '&f=' . $themeCssFiles . '&b=' . $themeCssBase . '&v=' . $jsVersionHash);
}
// Cargar los recursos de los plugins
@@ -185,11 +183,11 @@ class LayoutHelper extends HelperBase
$cssResources = $Plugin->getCssResources();
if (count($jsResources) > 0) {
- $this->view->append('jsLinks', Bootstrap::$WEBROOT . '/public/js/js.php?f=' . urlencode(implode(',', $jsResources)) . '&b=' . urlencode($base . DIRECTORY_SEPARATOR . 'js') . '&v=' . $jsVersionHash);
+ $this->view->append('jsLinks', $jsUri . '&f=' . urlencode(implode(',', $jsResources)) . '&b=' . urlencode($base . DIRECTORY_SEPARATOR . 'js') . '&v=' . $jsVersionHash);
}
if (count($cssResources) > 0) {
- $this->view->append('cssLinks', Bootstrap::$WEBROOT . '/public/css/css.php?f=' . urlencode(implode(',', $cssResources)) . '&b=' . urlencode($base . DIRECTORY_SEPARATOR . 'css') . '&v=' . $jsVersionHash);
+ $this->view->append('cssLinks', $cssUri . '&f=' . urlencode(implode(',', $cssResources)) . '&b=' . urlencode($base . DIRECTORY_SEPARATOR . 'css') . '&v=' . $jsVersionHash);
}
}
}
diff --git a/app/modules/web/Controllers/IndexController.php b/app/modules/web/Controllers/IndexController.php
index cfe8ed0f..69a7379a 100644
--- a/app/modules/web/Controllers/IndexController.php
+++ b/app/modules/web/Controllers/IndexController.php
@@ -38,6 +38,8 @@ class IndexController extends ControllerBase
{
/**
* Index action
+ *
+ * @throws \SP\Core\Dic\ContainerException
*/
public function indexAction()
{
diff --git a/app/modules/web/Controllers/MainController.php b/app/modules/web/Controllers/MainController.php
index 0c740a31..dd03b78e 100644
--- a/app/modules/web/Controllers/MainController.php
+++ b/app/modules/web/Controllers/MainController.php
@@ -387,7 +387,7 @@ class MainController extends ControllerBase implements ActionsInterface
if (!Checks::checkPhpVersion()) {
$errors[] = [
- 'type' => SPException::SP_CRITICAL,
+ 'type' => SPException::CRITICAL,
'description' => __('Versión de PHP requerida >= ') . ' 5.6.0 <= 7.0',
'hint' => __('Actualice la versión de PHP para que la aplicación funcione correctamente')
];
@@ -398,7 +398,7 @@ class MainController extends ControllerBase implements ActionsInterface
if (count($modules) > 0) {
foreach ($modules as $module) {
$error[] = [
- 'type' => SPException::SP_WARNING,
+ 'type' => SPException::WARNING,
'description' => sprintf('%s (%s)', __('Módulo no disponible'), $module),
'hint' => __('Sin este módulo la aplicación puede no funcionar correctamente.')
];
@@ -407,14 +407,14 @@ class MainController extends ControllerBase implements ActionsInterface
if (@file_exists(__FILE__ . "\0Nullbyte")) {
$errors[] = [
- 'type' => SPException::SP_WARNING,
+ 'type' => SPException::WARNING,
'description' => __('La version de PHP es vulnerable al ataque NULL Byte (CVE-2006-7243)'),
'hint' => __('Actualice la versión de PHP para usar sysPass de forma segura')];
}
if (!Checks::secureRNGIsAvailable()) {
$errors[] = [
- 'type' => SPException::SP_WARNING,
+ 'type' => SPException::WARNING,
'description' => __('No se encuentra el generador de números aleatorios.'),
'hint' => __('Sin esta función un atacante puede utilizar su cuenta al resetear la clave')];
}
diff --git a/app/modules/web/Controllers/ResourceController.php b/app/modules/web/Controllers/ResourceController.php
new file mode 100644
index 00000000..a4efc2c2
--- /dev/null
+++ b/app/modules/web/Controllers/ResourceController.php
@@ -0,0 +1,129 @@
+.
+ */
+
+namespace SP\Modules\Web\Controllers;
+
+use SP\Html\Minify;
+use SP\Http\Request;
+
+/**
+ * Class ResourceController
+ *
+ * @package SP\Modules\Web\Controllers
+ */
+class ResourceController extends SimpleControllerBase
+{
+ /**
+ * @var Minify
+ */
+ protected $minify;
+
+ /**
+ * @throws \Psr\Container\ContainerExceptionInterface
+ * @throws \Psr\Container\NotFoundExceptionInterface
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function cssAction()
+ {
+ $file = Request::analyze('f');
+ $base = Request::analyze('b');
+
+ $minify = new Minify();
+
+ if ($file && $base) {
+ $minify->setType(Minify::FILETYPE_CSS)
+ ->setBase(urldecode($base), true)
+ ->addFilesFromString(urldecode($file))
+ ->getMinified();
+ } else {
+ $minify->setType(Minify::FILETYPE_CSS)
+ ->setBase(PUBLIC_PATH . DIRECTORY_SEPARATOR . 'css')
+ ->addFiles(['reset.min.css',
+ 'jquery-ui.min.css',
+ 'jquery-ui.structure.min.css',
+ 'jquery.tagsinput.min.css',
+ 'fonts.min.css',
+ 'material-icons.min.css',
+ 'toastr.min.css',
+ 'magnific-popup.min.css'
+ ], false)
+ ->getMinified();
+ }
+ }
+
+ /**
+ * @throws \Psr\Container\ContainerExceptionInterface
+ * @throws \Psr\Container\NotFoundExceptionInterface
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function jsAction()
+ {
+ $file = Request::analyze('f');
+ $base = Request::analyze('b');
+
+ $minify = new Minify();
+
+ if ($file && $base) {
+ $minify->setType(Minify::FILETYPE_JS)
+ ->setBase(urldecode($base), true)
+ ->addFilesFromString(urldecode($file))
+ ->getMinified();
+ } else {
+ $minify->setType(Minify::FILETYPE_JS)
+ ->setBase(PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js');
+
+ $group = Request::analyze('g', 0);
+
+ if ($group === 0) {
+ $minify->addFiles([
+ 'jquery-3.2.0.min.js',
+ 'jquery-migrate-3.0.0.min.js',
+ 'jquery.fileDownload.min.js',
+ 'clipboard.min.js',
+ 'selectize.min.js',
+ 'selectize-plugins.min.js',
+ 'zxcvbn-async.min.js',
+ 'jsencrypt.min.js',
+ 'spark-md5.min.js',
+ 'moment.min.js',
+ 'moment-timezone.min.js',
+ 'toastr.min.js',
+ 'jquery.magnific-popup.min.js',
+ 'eventsource.min.js'], false);
+ } elseif ($group === 1) {
+ // FIXME: use MIN version
+ $minify->addFiles([
+ 'app.js',
+ 'app-triggers.js',
+ 'app-actions.js',
+ 'app-requests.js',
+ 'app-main.js'], false);
+ }
+
+ $minify->getMinified();
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/modules/web/Controllers/SimpleControllerBase.php b/app/modules/web/Controllers/SimpleControllerBase.php
index 379951ab..776586d8 100644
--- a/app/modules/web/Controllers/SimpleControllerBase.php
+++ b/app/modules/web/Controllers/SimpleControllerBase.php
@@ -24,13 +24,12 @@
namespace SP\Modules\Web\Controllers;
+use Klein\Klein;
use SP\Config\Config;
-use SP\Core\Acl\Acl;
use SP\Core\Events\EventDispatcher;
use SP\Core\Session\Session;
use SP\Core\Traits\InjectableTrait;
use SP\Core\UI\Theme;
-use SP\Storage\Database;
/**
* Class SimpleControllerBase
@@ -41,32 +40,53 @@ abstract class SimpleControllerBase
{
use InjectableTrait;
- /** @var int Módulo a usar */
+ /**
+ * @var int Módulo a usar
+ */
protected $action;
- /** @var string Nombre del controlador */
+ /**
+ * @var string Nombre del controlador
+ */
protected $controllerName;
- /** @var EventDispatcher */
+ /**
+ * @var EventDispatcher
+ */
protected $eventDispatcher;
- /** @var Config */
+ /**
+ * @var Config
+ */
protected $config;
- /** @var Session */
+ /**
+ * @var Session
+ */
protected $session;
- /** @var Database */
- protected $db;
- /** @var Theme */
+ /**
+ * @var Theme
+ */
protected $theme;
- /** @var \SP\Core\Acl\Acl */
- protected $acl;
+ /**
+ * @var string
+ */
+ protected $actionName;
+ /**
+ * @var Klein
+ */
+ protected $router;
/**
- * Constructor
+ * SimpleControllerBase constructor.
+ *
+ * @param $actionName
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
*/
- public function __construct()
+ public function __construct($actionName)
{
$this->injectDependencies();
$class = static::class;
$this->controllerName = substr($class, strrpos($class, '\\') + 1, -strlen('Controller'));
+ $this->actionName = $actionName;
if (method_exists($this, 'initialize')) {
$this->initialize();
@@ -76,18 +96,16 @@ abstract class SimpleControllerBase
/**
* @param Config $config
* @param Session $session
- * @param Database $db
* @param Theme $theme
* @param EventDispatcher $ev
- * @param Acl $acl
+ * @param Klein $router
*/
- public function inject(Config $config, Session $session, Database $db, Theme $theme, EventDispatcher $ev, Acl $acl)
+ public function inject(Config $config, Session $session, Theme $theme, EventDispatcher $ev, Klein $router)
{
$this->config = $config;
$this->session = $session;
- $this->db = $db;
$this->theme = $theme;
$this->eventDispatcher = $ev;
- $this->acl = $acl;
+ $this->router = $router;
}
}
\ No newline at end of file
diff --git a/app/modules/web/Controllers/Traits/ItemTrait.php b/app/modules/web/Controllers/Traits/ItemTrait.php
index 270105b4..8c04816e 100644
--- a/app/modules/web/Controllers/Traits/ItemTrait.php
+++ b/app/modules/web/Controllers/Traits/ItemTrait.php
@@ -101,7 +101,7 @@ trait ItemTrait
$customFieldService->create($customFieldData);
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno'));
+ throw new SPException(__u('Error interno'), SPException::ERROR);
}
}
}
@@ -144,7 +144,7 @@ trait ItemTrait
$customFieldService->update($customFieldData);
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno'));
+ throw new SPException(__u('Error interno'), SPException::ERROR);
}
}
}
diff --git a/app/modules/web/themes/material-blue/views/_partials/error-list.inc b/app/modules/web/themes/material-blue/views/_partials/error-list.inc
index 501979bf..7f350956 100644
--- a/app/modules/web/themes/material-blue/views/_partials/error-list.inc
+++ b/app/modules/web/themes/material-blue/views/_partials/error-list.inc
@@ -7,7 +7,7 @@
-
+
-
getIconCritical()->getIcon(); ?>
@@ -17,7 +17,7 @@
-
+
getIconWarning()->getIcon(); ?>
diff --git a/lib/Base.php b/lib/Base.php
index 30c1e1a9..680a3220 100644
--- a/lib/Base.php
+++ b/lib/Base.php
@@ -63,7 +63,7 @@ require __DIR__ . DIRECTORY_SEPARATOR . 'SplClassLoader.php';
initModule(APP_MODULE);
try {
- (new Bootstrap())->initialize();
+ (new Bootstrap())->run();
} catch (\Exception $e) {
debugLog($e->getMessage());
debugLog($e->getTraceAsString());
diff --git a/lib/SP/Account/Account.php b/lib/SP/Account/Account.php
index 37c0ead0..dc96ec78 100644
--- a/lib/SP/Account/Account.php
+++ b/lib/SP/Account/Account.php
@@ -29,7 +29,6 @@ use SP\Core\Crypt\Crypt;
use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\Core\SessionFactory;
use SP\DataModel\AccountData;
use SP\DataModel\AccountExtData;
use SP\DataModel\AccountToUserGroupData;
@@ -198,9 +197,9 @@ class Account extends AccountBase implements AccountInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __('No se pudieron obtener los datos de la cuenta', false));
+ throw new SPException(__('No se pudieron obtener los datos de la cuenta', false), SPException::CRITICAL);
} elseif (is_array($queryRes) && count($queryRes) === 0) {
- throw new SPException(SPException::SP_CRITICAL, __('La cuenta no existe', false));
+ throw new SPException(__('La cuenta no existe', false), SPException::CRITICAL);
}
// Obtener los usuarios y grupos secundarios y las etiquetas
@@ -318,10 +317,10 @@ class Account extends AccountBase implements AccountInterface
$this->accountData->setKey($securedKey);
if (strlen($securedKey) > 1000 || strlen($this->accountData->getPass()) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error interno', false));
+ throw new SPException(__('Error interno', false), SPException::ERROR);
}
}
@@ -505,11 +504,11 @@ class Account extends AccountBase implements AccountInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __('No se pudieron obtener los datos de la cuenta', false));
+ throw new SPException(__('No se pudieron obtener los datos de la cuenta', false), SPException::CRITICAL);
}
if (is_array($queryRes) && count($queryRes) === 0) {
- throw new SPException(SPException::SP_CRITICAL, __('La cuenta no existe', false));
+ throw new SPException(__('La cuenta no existe', false), SPException::CRITICAL);
}
return $this->accountData;
diff --git a/lib/SP/Account/AccountCrypt.php b/lib/SP/Account/AccountCrypt.php
index b09911b3..cc376bfb 100644
--- a/lib/SP/Account/AccountCrypt.php
+++ b/lib/SP/Account/AccountCrypt.php
@@ -32,7 +32,6 @@ use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
use SP\Core\OldCrypt;
use SP\Core\Session\Session;
-use SP\Core\SessionFactory;
use SP\Core\TaskFactory;
use SP\Core\Traits\InjectableTrait;
use SP\DataModel\AccountData;
@@ -174,7 +173,7 @@ class AccountCrypt
$AccountData->setKey($securedKey);
if (strlen($securedKey) > 1000 || strlen($AccountData->getPass()) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$Account = new Account($AccountData);
@@ -291,7 +290,7 @@ class AccountCrypt
$AccountData->setKey($newSecuredKey);
if (strlen($newSecuredKey) > 1000 || strlen($AccountData->getPass()) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$Account = new Account($AccountData);
diff --git a/lib/SP/Account/AccountHistory.php b/lib/SP/Account/AccountHistory.php
index c270e1a2..0face786 100644
--- a/lib/SP/Account/AccountHistory.php
+++ b/lib/SP/Account/AccountHistory.php
@@ -210,7 +210,7 @@ class AccountHistory extends AccountBase implements AccountInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __('No se pudieron obtener los datos de la cuenta', false), 0);
+ throw new SPException(__('No se pudieron obtener los datos de la cuenta', false), SPException::CRITICAL, 0);
}
return $queryRes->acchistory_accountId;
@@ -387,7 +387,7 @@ class AccountHistory extends AccountBase implements AccountInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __('No se pudieron obtener los datos de la cuenta', false));
+ throw new SPException(__('No se pudieron obtener los datos de la cuenta', false), SPException::CRITICAL);
}
$this->accountData = $queryRes;
diff --git a/lib/SP/Account/AccountHistoryCrypt.php b/lib/SP/Account/AccountHistoryCrypt.php
index 927585d6..e7d50075 100644
--- a/lib/SP/Account/AccountHistoryCrypt.php
+++ b/lib/SP/Account/AccountHistoryCrypt.php
@@ -39,7 +39,6 @@ use SP\Log\Email;
use SP\Log\Log;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
-use SP\Util\Checks;
use SP\Util\Util;
/**
@@ -185,7 +184,7 @@ class AccountHistoryCrypt
$AccountData->key = $securedKey;
if (strlen($securedKey) > 1000 || strlen($AccountData->pass) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$Account = new AccountHistory();
@@ -311,7 +310,7 @@ class AccountHistoryCrypt
$AccountData->key = $newSecuredKey;
if (strlen($newSecuredKey) > 1000 || strlen($AccountData->pass) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$Account = new AccountHistory();
diff --git a/lib/SP/Account/AccountUtil.php b/lib/SP/Account/AccountUtil.php
index e5971e49..e8413ff6 100644
--- a/lib/SP/Account/AccountUtil.php
+++ b/lib/SP/Account/AccountUtil.php
@@ -24,13 +24,8 @@
namespace SP\Account;
-use SP\Bootstrap;
-use SP\Config\Config;
-use SP\Config\ConfigData;
-use SP\Core\Dic\DicInterface;
use SP\Core\Exceptions\SPException;
use SP\Core\Session\Session;
-use SP\Core\SessionFactory;
use SP\DataModel\ItemSearchData;
use SP\Mvc\Model\QueryCondition;
use SP\Storage\DbWrapper;
@@ -134,7 +129,7 @@ class AccountUtil
try {
return DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_CRITICAL, __('No se pudieron obtener los datos de las cuentas', false));
+ throw new SPException(__('No se pudieron obtener los datos de las cuentas', false), SPException::CRITICAL);
}
}
diff --git a/lib/SP/Api/ApiBase.php b/lib/SP/Api/ApiBase.php
index 09183e83..8fc804ac 100644
--- a/lib/SP/Api/ApiBase.php
+++ b/lib/SP/Api/ApiBase.php
@@ -96,7 +96,7 @@ abstract class ApiBase implements ApiInterface
if ($this->ApiTokenData === false) {
ApiUtil::addTracking();
- throw new SPException(SPException::SP_CRITICAL, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
}
$this->data = $data;
@@ -156,7 +156,7 @@ abstract class ApiBase implements ApiInterface
) {
ApiUtil::addTracking();
- throw new SPException(SPException::SP_CRITICAL, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
}
}
@@ -172,7 +172,7 @@ abstract class ApiBase implements ApiInterface
protected function getParam($name, $required = false, $default = null)
{
if ($required === true && !isset($this->data->params->$name)) {
- throw new InvalidArgumentException(SPException::SP_WARNING, __('Parámetros incorrectos', false), $this->getHelp($this->data->method));
+ throw new InvalidArgumentException(SPException::WARNING, __('Parámetros incorrectos', false), $this->getHelp($this->data->method));
}
if (isset($this->data->params->$name)) {
@@ -197,10 +197,10 @@ abstract class ApiBase implements ApiInterface
if ($Vault && $pass = $Vault->getData($this->getParam('tokenPass') . $this->getParam('authToken'))) {
return $pass;
} else {
- throw new SPException(SPException::SP_ERROR, __('Error interno', false), __('Datos inválidos', false));
+ throw new SPException(__('Error interno', false), SPException::ERROR, __('Datos inválidos', false));
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error interno', false), $e->getMessage());
+ throw new SPException(__('Error interno', false), SPException::ERROR, $e->getMessage());
}
}
@@ -215,7 +215,7 @@ abstract class ApiBase implements ApiInterface
if ($this->actionId !== $action) {
ApiUtil::addTracking();
- throw new SPException(SPException::SP_CRITICAL, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
}
}
@@ -249,7 +249,7 @@ abstract class ApiBase implements ApiInterface
if ($this->auth === false) {
ApiUtil::addTracking();
- throw new SPException(SPException::SP_CRITICAL, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::CRITICAL);
}
}
}
\ No newline at end of file
diff --git a/lib/SP/Api/ApiRequest.php b/lib/SP/Api/ApiRequest.php
index a5eea6d5..4e39c988 100644
--- a/lib/SP/Api/ApiRequest.php
+++ b/lib/SP/Api/ApiRequest.php
@@ -157,7 +157,7 @@ class ApiRequest
$attempts = count(Track::getItem($TrackData)->getTracksForClientFromTime(time() - self::TIME_TRACKING));
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error interno', false), __FUNCTION__, -32601);
+ throw new SPException(__('Error interno', false), SPException::ERROR, __FUNCTION__, -32601);
}
if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) {
@@ -165,7 +165,7 @@ class ApiRequest
sleep(0.3 * $attempts);
- throw new SPException(SPException::SP_INFO, __('Intentos excedidos', false), '', -32601);
+ throw new SPException(__('Intentos excedidos', false), SPException::INFO, '', -32601);
}
}
@@ -187,7 +187,7 @@ class ApiRequest
$this->verb = $requestMethod;
break;
default:
- throw new SPException(SPException::SP_WARNING, __('Método inválido', false), '', -32600);
+ throw new SPException(__('Método inválido', false), SPException::WARNING, '', -32600);
}
}
@@ -204,11 +204,11 @@ class ApiRequest
$data = json_decode(Request::parse($request, '', true));
if (!is_object($data) || json_last_error() !== JSON_ERROR_NONE) {
- throw new SPException(SPException::SP_WARNING, __('Datos inválidos', false), '', -32700);
+ throw new SPException(__('Datos inválidos', false), SPException::WARNING, '', -32700);
}
if (!isset($data->jsonrpc, $data->method, $data->params, $data->id)) {
- throw new SPException(SPException::SP_WARNING, __('Formato incorrecto', false), '', -32600);
+ throw new SPException(__('Formato incorrecto', false), SPException::WARNING, '', -32600);
}
$this->data = $data;
@@ -222,7 +222,7 @@ class ApiRequest
private function checkBasicData()
{
if (!isset($this->data->params->authToken)) {
- throw new SPException(SPException::SP_WARNING, __('Parámetros incorrectos', false), '', -32602);
+ throw new SPException(__('Parámetros incorrectos', false), SPException::WARNING, '', -32602);
}
}
@@ -238,7 +238,7 @@ class ApiRequest
if (!$this->ApiReflection->hasMethod($this->data->method)) {
ApiUtil::addTracking();
- throw new SPException(SPException::SP_WARNING, __('Acción Inválida', false), '', -32601);
+ throw new SPException(__('Acción Inválida', false), SPException::WARNING, '', -32601);
}
}
diff --git a/lib/SP/Api/ApiUtil.php b/lib/SP/Api/ApiUtil.php
index 4e237c27..778d6b5e 100644
--- a/lib/SP/Api/ApiUtil.php
+++ b/lib/SP/Api/ApiUtil.php
@@ -52,7 +52,7 @@ class ApiUtil
Track::getItem($TrackData)->add();
} catch (SPException $e) {
- throw new SPException(SPException::SP_WARNING, __('Error interno', false), '', -32601);
+ throw new SPException(__('Error interno', false), SPException::WARNING, '', -32601);
}
}
}
\ No newline at end of file
diff --git a/lib/SP/Api/SyspassApi.php b/lib/SP/Api/SyspassApi.php
index 5a166908..945bb845 100644
--- a/lib/SP/Api/SyspassApi.php
+++ b/lib/SP/Api/SyspassApi.php
@@ -28,7 +28,6 @@ defined('APP_ROOT') || die();
use SP\Account\Account;
use SP\Account\AccountAcl;
-use SP\Services\Account\AccountSearchService;
use SP\Account\AccountUtil;
use SP\Core\Acl\ActionsInterface;
use SP\Core\Backup;
@@ -42,6 +41,7 @@ use SP\Mgmt\Categories\Category;
use SP\Mgmt\Categories\CategorySearch;
use SP\Mgmt\Customers\Customer;
use SP\Mgmt\Customers\CustomerSearch;
+use SP\Services\Account\AccountSearchService;
/**
* Class Api para la gestión de peticiones a la API de sysPass
@@ -73,7 +73,7 @@ class SyspassApi extends ApiBase
$Acl = $AccountAcl->getAcl();
if (!$Acl->isShowViewPass()) {
- throw new SPException(SPException::SP_WARNING, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::WARNING);
}
$Account->getAccountPassData();
@@ -145,7 +145,7 @@ class SyspassApi extends ApiBase
$Acl = $AccountAcl->getAcl();
if (!$Acl->isShowView()) {
- throw new SPException(SPException::SP_WARNING, __('Acceso no permitido', false));
+ throw new SPException(__('Acceso no permitido', false), SPException::WARNING);
}
$Account->incrementViewCounter();
@@ -216,7 +216,7 @@ class SyspassApi extends ApiBase
$AccountData = AccountUtil::getAccountNameById($accountId);
if ($AccountData === false) {
- throw new SPException(SPException::SP_ERROR, __('Cuenta no encontrada', false));
+ throw new SPException(__('Cuenta no encontrada', false), SPException::ERROR);
}
$Account = new Account();
@@ -306,7 +306,7 @@ class SyspassApi extends ApiBase
$CategoryData = Category::getItem()->getById($id);
if (!is_object($CategoryData)) {
- throw new SPException(SPException::SP_ERROR, __('Categoría no encontrada', false));
+ throw new SPException(__('Categoría no encontrada', false), SPException::ERROR);
}
Category::getItem()->delete($id);
@@ -395,7 +395,7 @@ class SyspassApi extends ApiBase
$CustomerData = Customer::getItem()->getById($id);
if (!is_object($CustomerData)) {
- throw new SPException(SPException::SP_ERROR, __('Cliente no encontrado', false));
+ throw new SPException(__('Cliente no encontrado', false), SPException::ERROR);
}
Customer::getItem()->delete($id);
diff --git a/lib/SP/Bootstrap.php b/lib/SP/Bootstrap.php
index 53c0903a..8d6d80b0 100644
--- a/lib/SP/Bootstrap.php
+++ b/lib/SP/Bootstrap.php
@@ -32,22 +32,20 @@ use Klein\Klein;
use PHPMailer\PHPMailer\Exception;
use RuntimeException;
use SP\Account\AccountAcl;
-use SP\Providers\Auth\Browser\Browser;
use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Config\ConfigUtil;
use SP\Core\Crypt\CryptSessionHandler;
use SP\Core\Crypt\SecureKeyCookie;
use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Dic\DicInterface;
use SP\Core\Exceptions\ConfigException;
+use SP\Core\Exceptions\InitializationException;
use SP\Core\Exceptions\SPException;
use SP\Core\Language;
use SP\Core\Plugin\PluginUtil;
use SP\Core\Session\Session;
use SP\Core\SessionFactory;
use SP\Core\SessionUtil;
-use SP\Mvc\View\Template;
use SP\Core\Traits\InjectableTrait;
use SP\Core\UI\Theme;
use SP\Core\Upgrade\Upgrade;
@@ -57,6 +55,8 @@ use SP\Log\Email;
use SP\Log\Log;
use SP\Mgmt\Profiles\Profile;
use SP\Modules\Web\Controllers\MainController;
+use SP\Mvc\View\Template;
+use SP\Providers\Auth\Browser\Browser;
use SP\Storage\DBUtil;
use SP\Util\Checks;
use SP\Util\HttpUtil;
@@ -143,222 +143,28 @@ class Bootstrap
* Bootstrap constructor.
*
* @throws Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
public function __construct()
{
$this->setupContainer();
$this->injectDependencies();
- }
-
- /**
- * @return ContainerInterface
- */
- public static function getContainer()
- {
- return self::$container;
- }
-
- /**
- * Comprobar si hay que ejecutar acciones de URL después de realizar login.
- *
- * @return bool
- */
- public function checkPostLoginActions()
- {
- $action = Request::analyze('a');
-
- if ($action === '') {
- return false;
- }
-
- $Controller = new MainController();
- $Controller->doAction('postlogin.' . $action);
-
- return false;
- }
-
- /**
- * @param Config $config
- * @param Upgrade $upgrade
- * @param Session $session
- * @param Theme $theme
- * @param Klein $router
- */
- public function inject(Config $config, Upgrade $upgrade, Session $session, Theme $theme, Klein $router)
- {
- $this->config = $config;
- $this->configData = $config->getConfigData();
- $this->upgrade = $upgrade;
- $this->session = $session;
- $this->theme = $theme;
- $this->router = $router;
- }
-
- /**
- * Comprueba que la aplicación esté instalada
- * Esta función comprueba si la aplicación está instalada. Si no lo está, redirige al instalador.
- */
- private function checkInstalled()
- {
- // Redirigir al instalador si no está instalada
- if (!$this->configData->isInstalled()) {
- if (self::$SUBURI !== '/index.php') {
- // FIXME
- $this->router->response()->redirect('index.php?r=install');
-
- $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
-
- $url = $protocol . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . self::$WEBROOT . '/index.php';
- header("Location: $url");
- exit();
- }
-
- if ($this->session->getAuthCompleted()) {
- session_destroy();
-
- $this->initialize();
- return;
- }
-
- // Comprobar si sysPass está instalada o en modo mantenimiento
- $Controller = new MainController();
- $Controller->getInstaller();
- $Controller->view();
- exit();
- }
- }
-
- /**
- * Inicializar la aplicación
- *
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \Psr\Container\ContainerExceptionInterface
- */
- public function initialize()
- {
- self::$checkPhpVersion = Checks::checkPhpVersion();
- self::$checkInitSourceInclude = $this->checkInitSourceInclude();
-
- if (date_default_timezone_get() === 'UTC') {
- date_default_timezone_set('UTC');
- }
$this->initRouter();
-
- // Inicializar autentificación
- $this->initAuth();
-
- // Inicializar logging
- $this->initLogging();
-
- // Cargar las extensiones
-// self::loadExtensions();
-
- // Establecer el lenguaje por defecto
- Language::setLocales('en_US');
-
- // Establecer las rutas de la aplicación
- $this->initPaths();
-
- if (!self::$checkPhpVersion && !self::$checkInitSourceInclude) {
- self::initError(
- __('Versión de PHP requerida >= ') . ' 5.6.0 <= 7.0',
- __('Actualice la versión de PHP para que la aplicación funcione correctamente'));
- }
-
- // Comprobar la configuración
- $this->initConfig();
-
- // Iniciar la sesión de PHP
- $this->initSession($this->configData->isEncryptSession());
-
- // Volver a cargar la configuración si se recarga la página
- if (!Request::checkReload()) {
- // Cargar la configuración
- $this->config->loadConfig();
-
- // Cargar el lenguaje
- Language::setLanguage();
- } else {
- // Cargar la configuración
- $this->config->loadConfig(true);
-
- // Restablecer el idioma y el tema visual
- Language::setLanguage(true);
- $this->theme->initTheme(true);
-
- if ($this->session->isLoggedIn()) {
- // Recargar los permisos del perfil de usuario
- $this->session->setUserProfile(Profile::getItem()->getById($this->session->getUserData()->getUserProfileId()));
- // Reset de los datos de ACL de cuentas
- AccountAcl::resetData();
- }
- }
-
- // Comprobar si es necesario cambiar a HTTPS
- HttpUtil::checkHttps();
-
- // Comprobar si es necesario inicialización
- if (self::$checkInitSourceInclude ||
- ((defined('IS_INSTALLER') || defined('IS_UPGRADE')) && Checks::isAjax())
- ) {
- return;
- }
-
- // Comprobar si está instalado
- $this->checkInstalled();
-
- // Comprobar si el modo mantenimiento está activado
- $this->checkMaintenanceMode();
-
- // Comprobar si la Base de datos existe
- if (!DBUtil::checkDatabaseExist()) {
- self::initError(__('Error en la verificación de la base de datos'));
- }
-
- // Comprobar si es necesario actualizar componentes
- $this->checkUpgrade();
-
- // Inicializar la sesión
- $this->initUserSession();
-
- // Cargar los plugins
- PluginUtil::loadPlugins();
-
- // Comprobar acciones en URL
- $this->checkPreLoginActions();
-
- if ($this->session->isLoggedIn() && $this->session->getAuthCompleted() === true) {
- $AuthBrowser = new Browser();
-
- // Comprobar si se ha identificado mediante el servidor web y el usuario coincide
- if ($AuthBrowser->checkServerAuthUser($this->session->getUserData()->getLogin()) === false
- && $AuthBrowser->checkServerAuthUser($this->session->getUserData()->getSsoLogin()) === false
- ) {
- $this->goLogout();
- }
- }
-
- $this->router->dispatch();
-
-
- // El usuario no está logado y no es una petición, redirigir al login
-// $this->goLogin();
}
/**
- * Comprobar el archivo que realiza el include necesita inicialización.
- *
- * @returns bool
+ * Setups DI container
*/
- private function checkInitSourceInclude()
+ private function setupContainer()
{
- self::$sourceScript = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_BASENAME);
- $skipInit = ['js.php', 'css.php', 'api.php', 'ajax_getEnvironment.php', 'ajax_task.php'];
+ $builder = new ContainerBuilder();
+ $builder->setDefinitionCache(new ArrayCache());
+ $builder->writeProxiesToFile(true, CACHE_PATH . DIRECTORY_SEPARATOR . 'proxies');
+ $builder->addDefinitions(BASE_PATH . DIRECTORY_SEPARATOR . 'Definitions.php');
- return in_array(self::$sourceScript, $skipInit, true);
+ self::$container = $builder->build();
}
/**
@@ -384,6 +190,8 @@ class Bootstrap
});
try {
+ $self->initialize();
+
/** @var \Klein\Request $request */
$route = filter_var($request->param('r', 'index/index'), FILTER_SANITIZE_STRING);
@@ -437,10 +245,135 @@ class Bootstrap
// );
}
+ /**
+ * Inicializar la aplicación
+ *
+ * @throws SPException
+ * @throws \Psr\Container\ContainerExceptionInterface
+ */
+ public function initialize()
+ {
+ self::$checkPhpVersion = Checks::checkPhpVersion();
+ self::$checkInitSourceInclude = $this->checkInitSourceInclude();
+
+ if (date_default_timezone_get() === 'UTC') {
+ date_default_timezone_set('UTC');
+ }
+
+ // Inicializar autentificación
+ $this->initAuthVariables();
+
+ // Inicializar logging
+ $this->initLogging();
+
+ // Cargar las extensiones
+// self::loadExtensions();
+
+ // Establecer el lenguaje por defecto
+ Language::setLocales('en_US');
+
+ // Establecer las rutas de la aplicación
+ $this->initPaths();
+
+ if (!self::$checkPhpVersion && !self::$checkInitSourceInclude) {
+ throw new InitializationException(
+ __u('Versión de PHP requerida >= ') . ' 5.6.0 <= 7.0',
+ SPException::ERROR,
+ __u('Actualice la versión de PHP para que la aplicación funcione correctamente')
+ );
+ }
+
+ // Comprobar la configuración
+ $this->initConfig();
+
+ // Iniciar la sesión de PHP
+ $this->initSession($this->configData->isEncryptSession());
+
+ // Volver a cargar la configuración si se recarga la página
+ if (!Request::checkReload()) {
+ // Cargar la configuración
+ $this->config->loadConfig();
+
+ // Cargar el lenguaje
+ Language::setLanguage();
+ } else {
+ // Cargar la configuración
+ $this->config->loadConfig(true);
+
+ // Restablecer el idioma y el tema visual
+ Language::setLanguage(true);
+ $this->theme->initTheme(true);
+
+ if ($this->session->isLoggedIn()) {
+ // Recargar los permisos del perfil de usuario
+ $this->session->setUserProfile(Profile::getItem()->getById($this->session->getUserData()->getUserProfileId()));
+ // Reset de los datos de ACL de cuentas
+ AccountAcl::resetData();
+ }
+ }
+
+ // Comprobar si es necesario cambiar a HTTPS
+ HttpUtil::checkHttps();
+
+ // Comprobar si es necesario inicialización
+ if ((defined('IS_INSTALLER') || defined('IS_UPGRADE')) && Checks::isAjax($this->router)) {
+ return;
+ }
+
+ // Comprobar si está instalado
+ $this->checkInstalled();
+
+ // Comprobar si el modo mantenimiento está activado
+ $this->checkMaintenanceMode();
+
+ // Comprobar si la Base de datos existe
+ DBUtil::checkDatabaseExist();
+
+ // Comprobar si es necesario actualizar componentes
+// $this->checkUpgrade();
+
+ // Inicializar la sesión
+ $this->initUserSession();
+
+ // Cargar los plugins
+ PluginUtil::loadPlugins();
+
+ // Comprobar acciones en URL
+// $this->checkPreLoginActions();
+
+ if ($this->session->isLoggedIn() && $this->session->getAuthCompleted() === true) {
+ $AuthBrowser = new Browser();
+
+ // Comprobar si se ha identificado mediante el servidor web y el usuario coincide
+ if ($AuthBrowser->checkServerAuthUser($this->session->getUserData()->getLogin()) === false
+ && $AuthBrowser->checkServerAuthUser($this->session->getUserData()->getSsoLogin()) === false
+ ) {
+ throw new InitializationException('Logout');
+// $this->goLogout();
+ }
+ }
+
+ // El usuario no está logado y no es una petición, redirigir al login
+// $this->goLogin();
+ }
+
+ /**
+ * Comprobar el archivo que realiza el include necesita inicialización.
+ *
+ * @returns bool
+ */
+ private function checkInitSourceInclude()
+ {
+ self::$sourceScript = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_BASENAME);
+ $skipInit = ['js.php', 'css.php', 'api.php', 'ajax_getEnvironment.php', 'ajax_task.php'];
+
+ return in_array(self::$sourceScript, $skipInit, true);
+ }
+
/**
* Establecer variables de autentificación
*/
- private function initAuth()
+ private function initAuthVariables()
{
// Copiar la cabecera http de autentificación para apache+php-fcgid
if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
@@ -496,10 +429,6 @@ class Bootstrap
*/
private function initPaths()
{
- // Calcular los directorios raíz
-// $dir = substr(__DIR__, 0, strpos(__DIR__, str_replace('\\', '/', __NAMESPACE__)) - 1);
-// self::$SERVERROOT = substr($dir, 0, strripos($dir, DIRECTORY_SEPARATOR));
-
self::$SERVERROOT = dirname(BASE_PATH);
self::$SUBURI = str_replace("\\", '/', substr(realpath($_SERVER['SCRIPT_FILENAME']), strlen(self::$SERVERROOT)));
@@ -517,9 +446,7 @@ class Bootstrap
}
}
- $pos = strpos($scriptName, self::$SUBURI);
-
- if ($pos === false) {
+ if (($pos = strpos($scriptName, self::$SUBURI)) === false) {
$pos = strpos($scriptName, '?');
}
@@ -532,53 +459,18 @@ class Bootstrap
self::$WEBURI = HttpUtil::getHttpHost() . self::$WEBROOT;
}
- /**
- * Devuelve un error utilizando la plantilla de error o en formato JSON
- *
- * @param string $message con la descripción del error
- * @param string $hint opcional, con una ayuda sobre el error
- * @param bool $headers
- */
- public static function initError($message, $hint = '', $headers = false)
- {
- debugLog(__FUNCTION__);
- debugLog(__($message));
- debugLog(__($hint));
-
- if (Checks::isJson()) {
- $JsonResponse = new JsonResponse();
- $JsonResponse->setDescription($message);
- $JsonResponse->addMessage($hint);
- Json::returnJson($JsonResponse);
- } elseif ($headers === true) {
- header('HTTP/1.1 503 Service Temporarily Unavailable');
- header('Status: 503 Service Temporarily Unavailable');
- header('Retry-After: 120');
- }
-
- SessionUtil::cleanSession();
-
- $Tpl = new Template();
- $Tpl->append('errors', ['type' => SPException::SP_CRITICAL, 'description' => __($message), 'hint' => __($hint)]);
-
- $Controller = new MainController($Tpl, 'error', !Checks::isAjax());
- $Controller->getError();
- }
-
/**
* Cargar la configuración
+ *
+ * @throws ConfigException
*/
private function initConfig()
{
// Comprobar si es una versión antigua
$this->checkConfigVersion();
- try {
- if (!self::$checkInitSourceInclude) {
- ConfigUtil::checkConfigDir();
- }
- } catch (ConfigException $e) {
- self::initError($e->getMessage(), $e->getHint());
+ if (!self::$checkInitSourceInclude) {
+ ConfigUtil::checkConfigDir();
}
}
@@ -590,7 +482,7 @@ class Bootstrap
$appVersion = Util::getVersionStringNormalized();
if (file_exists(OLD_CONFIG_FILE) && $this->upgrade->upgradeOldConfigFile($appVersion)) {
- $this->logConfigUpgrade($appVersion);
+// $this->logConfigUpgrade($appVersion);
self::$UPDATED = true;
@@ -604,34 +496,17 @@ class Bootstrap
&& $this->upgrade->needConfigUpgrade($configVersion)
&& $this->upgrade->upgradeConfig($configVersion)
) {
- $this->logConfigUpgrade($appVersion);
+// $this->logConfigUpgrade($appVersion);
self::$UPDATED = true;
}
}
- /**
- * Registrar la actualización de la configuración
- *
- * @param $version
- */
- private function logConfigUpgrade($version)
- {
- $Log = new Log();
- $LogMessage = $Log->getLogMessage();
- $LogMessage->setAction(__('Actualización', false));
- $LogMessage->addDescription(__('Actualización de versión realizada.', false));
- $LogMessage->addDetails(__('Versión', false), $version);
- $LogMessage->addDetails(__('Tipo', false), 'config');
- $Log->writeLog();
-
- Email::sendEmail($LogMessage);
- }
-
/**
* Iniciar la sesión PHP
*
* @param bool $encrypt Encriptar la sesión de PHP
+ * @throws InitializationException
*/
private function initSession($encrypt = false)
{
@@ -640,20 +515,56 @@ class Bootstrap
ini_set('session.save_handler', 'files');
if ($encrypt === true) {
- $Key = SecureKeyCookie::getKey();
+ $key = SecureKeyCookie::getKey();
- if ($Key !== false && self::$checkPhpVersion) {
- session_set_save_handler(new CryptSessionHandler($Key), true);
+ if ($key !== false && self::$checkPhpVersion) {
+ session_set_save_handler(new CryptSessionHandler($key), true);
}
}
// Si la sesión no puede ser iniciada, devolver un error 500
if (session_start() === false) {
- Log::writeNewLog(__('Sesión', false), __('La sesión no puede ser inicializada', false));
+ $this->router->response()->header('HTTP/1.1', '500 Internal Server Error');
- header('HTTP/1.1 500 Internal Server Error');
+ throw new InitializationException(__u('La sesión no puede ser inicializada'));
+ }
+ }
- self::initError(__('La sesión no puede ser inicializada'), __('Consulte con el administrador'));
+ /**
+ * Comprueba que la aplicación esté instalada
+ * Esta función comprueba si la aplicación está instalada. Si no lo está, redirige al instalador.
+ *
+ * @throws InitializationException
+ */
+ private function checkInstalled()
+ {
+ // Redirigir al instalador si no está instalada
+ if (!$this->configData->isInstalled()) {
+ throw new InitializationException('Not installed');
+
+// if (self::$SUBURI !== '/index.php') {
+// // FIXME
+// $this->router->response()->redirect('index.php?r=install');
+//
+// $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
+//
+// $url = $protocol . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . self::$WEBROOT . '/index.php';
+// header("Location: $url");
+// exit();
+// }
+//
+// if ($this->session->getAuthCompleted()) {
+// session_destroy();
+//
+// $this->initialize();
+// return;
+// }
+//
+// // Comprobar si sysPass está instalada o en modo mantenimiento
+// $Controller = new MainController();
+// $Controller->getInstaller();
+// $Controller->view();
+// exit();
}
}
@@ -664,6 +575,7 @@ class Bootstrap
*
* @param bool $check sólo comprobar si está activado el modo
* @return bool
+ * @throws InitializationException
*/
public function checkMaintenanceMode($check = false)
{
@@ -671,7 +583,7 @@ class Bootstrap
self::$LOCK = Util::getAppLock();
if ($check === true
- || Checks::isAjax()
+ || Checks::isAjax($this->router)
|| Request::analyze('nodbupgrade', 0) === 1
|| (Request::analyze('a') === 'upgrade' && Request::analyze('type') !== '')
|| (self::$LOCK > 0 && $this->session->isLoggedIn() && self::$LOCK === $this->session->getUserData()->getId())
@@ -679,23 +591,12 @@ class Bootstrap
return true;
}
- self::initError(__('Aplicación en mantenimiento'), __('En breve estará operativa'));
+ throw new InitializationException(__u('Aplicación en mantenimiento'), SPException::INFO, __u('En breve estará operativa'));
}
return false;
}
- /**
- * Comprobar si es necesario actualizar componentes
- *
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- */
- private function checkUpgrade()
- {
- return self::$SUBURI === '/index.php'
- && ($this->upgrade->checkDbVersion() || $this->upgrade->checkAppVersion());
- }
-
/**
* Inicializar la sesión de usuario
*
@@ -710,8 +611,8 @@ class Bootstrap
&& !$inMaintenance
&& (time() - $lastActivity) > $this->getSessionLifeTime()
) {
- if (isset($_COOKIE[session_name()])) {
- setcookie(session_name(), '', time() - 42000, '/');
+ if ($this->router->request()->cookies()->get(session_name()) !== null) {
+ $this->router->response()->cookie(session_name(), '', time() - 42000);
}
$this->wrLogoutInfo();
@@ -785,6 +686,98 @@ class Bootstrap
$Log->writeLog();
}
+ /**
+ * @return ContainerInterface
+ */
+ public static function getContainer()
+ {
+ return self::$container;
+ }
+
+ /**
+ * Devuelve un error utilizando la plantilla de error o en formato JSON
+ *
+ * @param string $message con la descripción del error
+ * @param string $hint opcional, con una ayuda sobre el error
+ * @param bool $headers
+ */
+ public static function initError($message, $hint = '', $headers = false)
+ {
+ debugLog(__FUNCTION__);
+ debugLog(__($message));
+ debugLog(__($hint));
+
+ if (Checks::isJson()) {
+ $JsonResponse = new JsonResponse();
+ $JsonResponse->setDescription($message);
+ $JsonResponse->addMessage($hint);
+ Json::returnJson($JsonResponse);
+ } elseif ($headers === true) {
+ header('HTTP/1.1 503 Service Temporarily Unavailable');
+ header('Status: 503 Service Temporarily Unavailable');
+ header('Retry-After: 120');
+ }
+
+ SessionUtil::cleanSession();
+
+ $Tpl = new Template();
+ $Tpl->append('errors', ['type' => SPException::CRITICAL, 'description' => __($message), 'hint' => __($hint)]);
+
+ $Controller = new MainController($Tpl, 'error', !Checks::isAjax());
+ $Controller->getError();
+ }
+
+ /**
+ * @param $module
+ * @throws InitializationException
+ */
+ public function run($module = APP_MODULE)
+ {
+ switch ($module) {
+ case 'web':
+ $this->router->dispatch();
+ break;
+ default;
+ throw new InitializationException('Unknown module');
+ }
+ }
+
+ /**
+ * Comprobar si hay que ejecutar acciones de URL después de realizar login.
+ *
+ * @return bool
+ */
+ public function checkPostLoginActions()
+ {
+ $action = Request::analyze('a');
+
+ if ($action === '') {
+ return false;
+ }
+
+ $Controller = new MainController();
+ $Controller->doAction('postlogin.' . $action);
+
+ return false;
+ }
+
+ /**
+ * @param Config $config
+ * @param Upgrade $upgrade
+ * @param Session $session
+ * @param Theme $theme
+ * @param Klein $router
+ */
+ public function inject(Config $config, Upgrade $upgrade, Session $session, Theme $theme, Klein $router)
+ {
+ $this->config = $config;
+ $this->configData = $config->getConfigData();
+ $this->upgrade = $upgrade;
+ $this->session = $session;
+ $this->theme = $theme;
+ $this->router = $router;
+ }
+
/**
* Comprobar si hay que ejecutar acciones de URL antes de presentar la pantalla de login.
*
@@ -805,18 +798,34 @@ class Bootstrap
}
/**
- * Deslogar el usuario actual y eliminar la información de sesión.
+ * Comprobar si es necesario actualizar componentes
+ *
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
- private function goLogout()
+ private function checkUpgrade()
{
- $this->wrLogoutInfo();
+ if (self::$SUBURI === '/index.php') {
+ $this->upgrade->checkDbVersion();
+ $this->upgrade->checkAppVersion();
+ }
+ }
- SessionUtil::cleanSession();
+ /**
+ * Registrar la actualización de la configuración
+ *
+ * @param $version
+ */
+ private function logConfigUpgrade($version)
+ {
+ $Log = new Log();
+ $LogMessage = $Log->getLogMessage();
+ $LogMessage->setAction(__('Actualización', false));
+ $LogMessage->addDescription(__('Actualización de versión realizada.', false));
+ $LogMessage->addDetails(__('Versión', false), $version);
+ $LogMessage->addDetails(__('Tipo', false), 'config');
+ $Log->writeLog();
- SessionFactory::setLoggedOut(true);
-
- $Controller = new MainController();
- $Controller->getLogout();
+ Email::sendEmail($LogMessage);
}
/**
@@ -830,15 +839,17 @@ class Bootstrap
}
/**
- * Setups DI container
+ * Deslogar el usuario actual y eliminar la información de sesión.
*/
- private function setupContainer()
+ private function goLogout()
{
- $builder = new ContainerBuilder();
- $builder->setDefinitionCache(new ArrayCache());
- $builder->writeProxiesToFile(true, CACHE_PATH . DIRECTORY_SEPARATOR . 'proxies');
- $builder->addDefinitions(BASE_PATH . DIRECTORY_SEPARATOR . 'Definitions.php');
+ $this->wrLogoutInfo();
- self::$container = $builder->build();
+ SessionUtil::cleanSession();
+
+ SessionFactory::setLoggedOut(true);
+
+ $Controller = new MainController();
+ $Controller->getLogout();
}
}
\ No newline at end of file
diff --git a/lib/SP/Config/Config.php b/lib/SP/Config/Config.php
index 10013c69..bc2f235a 100644
--- a/lib/SP/Config/Config.php
+++ b/lib/SP/Config/Config.php
@@ -105,7 +105,7 @@ class Config
} catch (\Exception $e) {
debugLog($e->getMessage());
- throw new ConfigException(ConfigException::SP_CRITICAL, $e->getMessage(), '', $e->getCode(), $e);
+ throw new ConfigException(ConfigException::CRITICAL, $e->getMessage(), '', $e->getCode(), $e);
}
return $this->configData;
diff --git a/lib/SP/Config/ConfigUtil.php b/lib/SP/Config/ConfigUtil.php
index 61efaabb..91a92f43 100644
--- a/lib/SP/Config/ConfigUtil.php
+++ b/lib/SP/Config/ConfigUtil.php
@@ -64,13 +64,13 @@ class ConfigUtil
if (!is_dir(CONFIG_PATH)) {
clearstatcache();
- throw new ConfigException(ConfigException::SP_CRITICAL, __('El directorio "/config" no existe', false));
+ throw new ConfigException(ConfigException::CRITICAL, __('El directorio "/config" no existe', false));
}
if (!is_writable(CONFIG_PATH)) {
clearstatcache();
- throw new ConfigException(ConfigException::SP_CRITICAL, __('No es posible escribir en el directorio "config"', false));
+ throw new ConfigException(ConfigException::CRITICAL, __('No es posible escribir en el directorio "config"', false));
}
$configPerms = decoct(fileperms(CONFIG_PATH) & 0777);
@@ -79,7 +79,7 @@ class ConfigUtil
clearstatcache();
throw new ConfigException(
- ConfigException::SP_ERROR,
+ ConfigException::ERROR,
__('Los permisos del directorio "/config" son incorrectos', false),
__('Actual:', false) . ' ' . $configPerms . ' - ' . __('Necesario: 750', false));
}
diff --git a/lib/SP/Controller/LoginController.php b/lib/SP/Controller/LoginController.php
index 4df9a57a..2226b9dc 100644
--- a/lib/SP/Controller/LoginController.php
+++ b/lib/SP/Controller/LoginController.php
@@ -173,7 +173,7 @@ class LoginController
} else {
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __('Login incorrecto', false), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException(SPException::INFO, __('Login incorrecto', false), '', self::STATUS_INVALID_LOGIN);
}
$this->getUserData();
@@ -223,7 +223,7 @@ class LoginController
$this->LogMessage->addDescription($e->getMessage());
$this->LogMessage->addDescription($e->getHint());
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) {
@@ -233,7 +233,7 @@ class LoginController
$this->LogMessage->addDescription(sprintf(__('Intentos excedidos (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS));
- throw new AuthException(SPException::SP_INFO, __('Intentos excedidos', false), '', self::STATUS_MAX_ATTEMPTS_EXCEEDED);
+ throw new AuthException(SPException::INFO, __('Intentos excedidos', false), '', self::STATUS_MAX_ATTEMPTS_EXCEEDED);
}
}
@@ -251,7 +251,7 @@ class LoginController
Track::getItem($TrackData)->add();
} catch (SPException $e) {
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
}
@@ -270,7 +270,7 @@ class LoginController
} catch (SPException $e) {
$this->LogMessage->addDescription(__('Error al obtener los datos del usuario de la BBDD', false));
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
}
@@ -288,7 +288,7 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __('Usuario deshabilitado', false), '', self::STATUS_USER_DISABLED);
+ throw new AuthException(SPException::INFO, __('Usuario deshabilitado', false), '', self::STATUS_USER_DISABLED);
}
if ($this->UserData->isIsChangePass()) {
@@ -335,7 +335,7 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
+ throw new AuthException(SPException::INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
}
$this->LogMessage->addDescription(__('Clave maestra actualizada', false));
@@ -345,32 +345,32 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
+ 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::SP_INFO, __('Es necesaria su clave anterior', false), '', self::STATUS_NEED_OLD_PASS);
+ 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::SP_INFO, __('La clave maestra no ha sido guardada o es incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
+ 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::SP_INFO, __('Clave maestra incorrecta', false), '', self::STATUS_INVALID_MASTER_PASS);
+ 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::SP_INFO, $this->LogMessage->getDescription(), $e->getMessage(), self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), $e->getMessage(), self::STATUS_INTERNAL_ERROR);
}
}
@@ -399,7 +399,7 @@ class LoginController
} else {
$this->LogMessage->addDescription(__('Error al obtener la clave maestra del usuario', false));
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
}
@@ -484,19 +484,19 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ 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::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
+ 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::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
+ throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
}
if ($AuthData->isAuthGranted() === false) {
@@ -505,7 +505,7 @@ class LoginController
$this->LogMessage->addDescription(__('Error interno', false));
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INTERNAL_ERROR);
}
$this->UserData->setName($AuthData->getName());
@@ -528,7 +528,7 @@ class LoginController
} catch (SPException $e) {
$this->LogMessage->addDescription($e->getMessage());
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
return true;
@@ -555,7 +555,7 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
}
if ($AuthData->getAuthenticated() === 1) {
@@ -588,7 +588,7 @@ class LoginController
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException(SPException::INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
}
$this->LogMessage->addDetails(__('Tipo', false), __FUNCTION__);
@@ -601,7 +601,7 @@ class LoginController
UserSSO::getItem()->updateOnLogin();
}
} catch (SPException $e) {
- throw new AuthException(SPException::SP_ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
+ throw new AuthException(SPException::ERROR, __('Error interno', false), '', self::STATUS_INTERNAL_ERROR);
}
$this->LogMessage->addDetails(__('Usuario', false), $this->UserData->getLogin());
diff --git a/lib/SP/Core/Acl/AccountPermissionException.php b/lib/SP/Core/Acl/AccountPermissionException.php
index a99cda06..bc533f5d 100644
--- a/lib/SP/Core/Acl/AccountPermissionException.php
+++ b/lib/SP/Core/Acl/AccountPermissionException.php
@@ -42,6 +42,6 @@ class AccountPermissionException extends SPException
*/
public function __construct($type, $code = 0, \Exception $previous = null)
{
- parent::__construct($type, __u('No tiene permisos para acceder a esta cuenta'), __u('Consulte con el administrador'), $code, $previous);
+ parent::__construct(__u('No tiene permisos para acceder a esta cuenta'), $type, __u('Consulte con el administrador'), $code, $previous);
}
}
\ No newline at end of file
diff --git a/lib/SP/Core/Acl/Acl.php b/lib/SP/Core/Acl/Acl.php
index f81314af..106cc540 100644
--- a/lib/SP/Core/Acl/Acl.php
+++ b/lib/SP/Core/Acl/Acl.php
@@ -26,7 +26,6 @@
namespace SP\Core\Acl;
use SP\Core\Session\Session;
-use SP\Log\Log;
defined('APP_ROOT') || die();
@@ -80,10 +79,10 @@ class Acl implements ActionsInterface
*/
public function checkUserAccess($action, $userId = 0)
{
- $curUserProfile = $this->session->getUserProfile();
+ $userProfile = $this->session->getUserProfile();
// Comprobamos si la cache de permisos está inicializada
- if (!is_object($curUserProfile)) {
+ if (!is_object($userProfile)) {
// error_log('ACL_CACHE_MISS');
return false;
}
@@ -96,95 +95,95 @@ class Acl implements ActionsInterface
switch ($action) {
case self::ACCOUNT_VIEW:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccView() || $curUserProfile->isAccEdit());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccView() || $userProfile->isAccEdit());
case self::ACCOUNT_VIEW_PASS:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccViewPass());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccViewPass());
case self::ACCOUNT_VIEW_HISTORY:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccViewHistory());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccViewHistory());
case self::ACCOUNT_EDIT:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccEdit());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccEdit());
case self::ACCOUNT_EDIT_PASS:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccEditPass());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccEditPass());
case self::ACCOUNT_CREATE:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccAdd());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccAdd());
case self::ACCOUNT_COPY:
- return ($userData->getIsAdminAcc() || ($curUserProfile->isAccAdd() && $curUserProfile->isAccView()));
+ return ($userData->getIsAdminAcc() || ($userProfile->isAccAdd() && $userProfile->isAccView()));
case self::ACCOUNT_DELETE:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccDelete());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccDelete());
case self::ACCOUNT_FILE:
- return ($userData->getIsAdminAcc() || $curUserProfile->isAccFiles());
+ return ($userData->getIsAdminAcc() || $userProfile->isAccFiles());
case self::ITEMS_MANAGE:
- return ($curUserProfile->isMgmCategories() || $curUserProfile->isMgmCustomers());
+ return ($userProfile->isMgmCategories() || $userProfile->isMgmCustomers());
case self::CONFIG:
- return ($curUserProfile->isConfigGeneral() || $curUserProfile->isConfigEncryption() || $curUserProfile->isConfigBackup() || $curUserProfile->isConfigImport());
+ return ($userProfile->isConfigGeneral() || $userProfile->isConfigEncryption() || $userProfile->isConfigBackup() || $userProfile->isConfigImport());
case self::CONFIG_GENERAL:
case self::PLUGIN:
case self::ACCOUNT_CONFIG:
- return $curUserProfile->isConfigGeneral();
+ return $userProfile->isConfigGeneral();
case self::IMPORT_CONFIG:
- return $curUserProfile->isConfigImport();
+ return $userProfile->isConfigImport();
case self::CATEGORY:
case self::CATEGORY_SEARCH:
- return $curUserProfile->isMgmCategories();
+ return $userProfile->isMgmCategories();
case self::CLIENT:
case self::CLIENT_SEARCH:
- return $curUserProfile->isMgmCustomers();
+ return $userProfile->isMgmCustomers();
case self::CUSTOMFIELD:
case self::CUSTOMFIELD_SEARCH:
- return $curUserProfile->isMgmCustomFields();
+ return $userProfile->isMgmCustomFields();
case self::PUBLICLINK:
case self::PUBLICLINK_SEARCH:
- return $curUserProfile->isMgmPublicLinks();
+ return $userProfile->isMgmPublicLinks();
case self::PUBLICLINK_CREATE:
- return ($curUserProfile->isMgmPublicLinks() || $curUserProfile->isAccPublicLinks());
+ return ($userProfile->isMgmPublicLinks() || $userProfile->isAccPublicLinks());
case self::ACCOUNTMGR:
case self::ACCOUNTMGR_SEARCH:
case self::ACCOUNTMGR_HISTORY:
case self::ACCOUNTMGR_SEARCH_HISTORY:
- return $curUserProfile->isMgmAccounts();
+ return $userProfile->isMgmAccounts();
case self::FILE:
case self::FILE_SEARCH:
- return $curUserProfile->isMgmFiles();
+ return $userProfile->isMgmFiles();
case self::TAG:
case self::TAG_SEARCH:
- return $curUserProfile->isMgmTags();
+ return $userProfile->isMgmTags();
case self::ENCRYPTION_CONFIG:
- return $curUserProfile->isConfigEncryption();
+ return $userProfile->isConfigEncryption();
case self::BACKUP_CONFIG:
- return $curUserProfile->isConfigBackup();
+ return $userProfile->isConfigBackup();
case self::ACCESS_MANAGE:
- return ($curUserProfile->isMgmUsers() || $curUserProfile->isMgmGroups() || $curUserProfile->isMgmProfiles());
+ return ($userProfile->isMgmUsers() || $userProfile->isMgmGroups() || $userProfile->isMgmProfiles());
case self::USER:
case self::USER_SEARCH:
case self::USER_CREATE:
case self::USER_EDIT:
- return $curUserProfile->isMgmUsers();
+ return $userProfile->isMgmUsers();
case self::USER_EDIT_PASS:
// Comprobar si el usuario es distinto al de la sesión
- return ($userId === $userData->getId() || $curUserProfile->isMgmUsers());
+ return ($userId === $userData->getId() || $userProfile->isMgmUsers());
case self::GROUP:
case self::GROUP_SEARCH:
- return $curUserProfile->isMgmGroups();
+ return $userProfile->isMgmGroups();
case self::PROFILE:
case self::PROFILE_SEARCH:
- return $curUserProfile->isMgmProfiles();
+ return $userProfile->isMgmProfiles();
case self::APITOKEN:
case self::APITOKEN_SEARCH:
- return $curUserProfile->isMgmApiTokens();
+ return $userProfile->isMgmApiTokens();
case self::EVENTLOG:
- return $curUserProfile->isEvl();
+ return $userProfile->isEvl();
case self::NOTICE:
case self::NOTICE_USER:
case self::NOTICE_USER_SEARCH:
return true;
}
- $Log = new Log();
- $Log->getLogMessage()
- ->setAction(__FUNCTION__)
- ->addDetails(__('Acceso denegado', false), self::getActionInfo($action, false));
- $Log->setLogLevel(Log::NOTICE);
- $Log->writeLog();
+// $Log = new Log();
+// $Log->getLogMessage()
+// ->setAction(__FUNCTION__)
+// ->addDetails(__('Acceso denegado', false), self::getActionInfo($action, false));
+// $Log->setLogLevel(Log::NOTICE);
+// $Log->writeLog();
return false;
}
diff --git a/lib/SP/Core/Acl/UnauthorizedPageException.php b/lib/SP/Core/Acl/UnauthorizedPageException.php
index 70182d15..65e701e9 100644
--- a/lib/SP/Core/Acl/UnauthorizedPageException.php
+++ b/lib/SP/Core/Acl/UnauthorizedPageException.php
@@ -42,7 +42,7 @@ class UnauthorizedPageException extends SPException
*/
public function __construct($type, $code = 0, \Exception $previous = null)
{
- parent::__construct($type, __u('No tiene permisos para acceder a esta página'), __u('Consulte con el administrador'), $code, $previous);
+ parent::__construct(__u('No tiene permisos para acceder a esta página'), $type, __u('Consulte con el administrador'), $code, $previous);
}
}
\ No newline at end of file
diff --git a/lib/SP/Core/Backup.php b/lib/SP/Core/Backup.php
index 54a56cfe..79a9bc2f 100644
--- a/lib/SP/Core/Backup.php
+++ b/lib/SP/Core/Backup.php
@@ -30,8 +30,8 @@ use SP\Core\Exceptions\SPException;
use SP\Core\Traits\InjectableTrait;
use SP\Log\Email;
use SP\Log\Log;
-use SP\Storage\DbWrapper;
use SP\Storage\DBUtil;
+use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
use SP\Util\Checks;
use SP\Util\Util;
@@ -118,14 +118,12 @@ class Backup
{
if (@mkdir(BACKUP_PATH, 0750) === false && is_dir(BACKUP_PATH) === false) {
throw new SPException(
- SPException::SP_ERROR,
- sprintf(__('No es posible crear el directorio de backups ("%s")'),BACKUP_PATH));
+ sprintf(__('No es posible crear el directorio de backups ("%s")'), BACKUP_PATH), SPException::ERROR);
}
if (!is_writable(BACKUP_PATH)) {
throw new SPException(
- SPException::SP_ERROR,
- __('Compruebe los permisos del directorio de backups', false));
+ __('Compruebe los permisos del directorio de backups', false), SPException::ERROR);
}
return true;
@@ -249,7 +247,7 @@ class Backup
fclose($handle);
} catch (\Exception $e) {
- throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
+ throw new SPException($e->getMessage(), SPException::CRITICAL);
}
return true;
@@ -267,14 +265,12 @@ class Backup
if (!class_exists(\PharData::class)) {
if (Checks::checkIsWindows()) {
throw new SPException(
- SPException::SP_ERROR,
- __('Esta operación sólo es posible en entornos Linux', false));
+ __('Esta operación sólo es posible en entornos Linux', false), SPException::ERROR);
}
if (!$this->backupAppLegacyLinux($backupFile)) {
throw new SPException(
- SPException::SP_ERROR,
- __('Error al realizar backup en modo compatibilidad', false));
+ __('Error al realizar backup en modo compatibilidad', false), SPException::ERROR);
}
return true;
@@ -293,7 +289,7 @@ class Backup
unlink($backupFile);
} catch (\Exception $e) {
- throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
+ throw new SPException($e->getMessage(), SPException::CRITICAL);
}
return file_exists($backupFile);
diff --git a/lib/SP/Core/CryptPKI.php b/lib/SP/Core/CryptPKI.php
index 78091029..e9ee7a8c 100644
--- a/lib/SP/Core/CryptPKI.php
+++ b/lib/SP/Core/CryptPKI.php
@@ -45,7 +45,7 @@ class CryptPKI
{
if (!file_exists($this->getPublicKeyFile()) || !file_exists($this->getPrivateKeyFile())) {
if (!$this->createKeys()) {
- throw new SPException(SPException::SP_CRITICAL, __('No es posible generar las claves RSA', false));
+ throw new SPException(__('No es posible generar las claves RSA', false), SPException::CRITICAL);
}
}
}
@@ -115,7 +115,7 @@ class CryptPKI
if (!file_exists($file)) {
Log::writeNewLog(__FUNCTION__, __('El archivo de clave no existe', false), Log::NOTICE);
- throw new FileNotFoundException(SPException::SP_ERROR, __('El archivo de clave no existe'));
+ throw new FileNotFoundException(SPException::ERROR, __('El archivo de clave no existe'));
}
return file_get_contents($file);
@@ -150,7 +150,7 @@ class CryptPKI
if (!file_exists($file)) {
Log::writeNewLog(__FUNCTION__, __('El archivo de clave no existe', false), Log::NOTICE);
- throw new FileNotFoundException(SPException::SP_ERROR, __('El archivo de clave no existe'));
+ throw new FileNotFoundException(SPException::ERROR, __('El archivo de clave no existe'));
}
return file_get_contents($file);
diff --git a/lib/SP/Core/Dic/Injector.php b/lib/SP/Core/Dic/Injector.php
index 901118ae..3bb8af6a 100644
--- a/lib/SP/Core/Dic/Injector.php
+++ b/lib/SP/Core/Dic/Injector.php
@@ -43,6 +43,7 @@ class Injector
* @param $context
* @return mixed
* @throws ContainerException
+ * @throws \ReflectionException
*/
public static function inject(ContainerInterface $container, $context)
{
diff --git a/lib/SP/Core/Events/EventDispatcherBase.php b/lib/SP/Core/Events/EventDispatcherBase.php
index 85545ed0..98e0024f 100644
--- a/lib/SP/Core/Events/EventDispatcherBase.php
+++ b/lib/SP/Core/Events/EventDispatcherBase.php
@@ -77,7 +77,7 @@ abstract class EventDispatcherBase implements EventDispatcherInterface
$observerClass = get_class($observer);
if (!array_key_exists($observerClass, $this->observers)) {
- throw new InvalidClassException(SPException::SP_ERROR, __('Observador no inicializado'));
+ throw new InvalidClassException(SPException::ERROR, __('Observador no inicializado'));
}
unset($this->observers[$observerClass]);
@@ -107,7 +107,7 @@ abstract class EventDispatcherBase implements EventDispatcherInterface
public function notifyEvent($event, $object)
{
if (!is_object($object)) {
- throw new InvalidArgumentException(SPException::SP_ERROR, __('Es necesario un objeto'));
+ throw new InvalidArgumentException(SPException::ERROR, __('Es necesario un objeto'));
}
foreach ($this->observers as $observer) {
diff --git a/lib/SP/Core/Exceptions/InitializationException.php b/lib/SP/Core/Exceptions/InitializationException.php
new file mode 100644
index 00000000..9b101f70
--- /dev/null
+++ b/lib/SP/Core/Exceptions/InitializationException.php
@@ -0,0 +1,35 @@
+.
+ */
+
+namespace SP\Core\Exceptions;
+
+/**
+ * Class InitializationException
+ *
+ * @package SP\Core\Exceptions
+ */
+class InitializationException extends SPException
+{
+
+}
\ No newline at end of file
diff --git a/lib/SP/Core/Exceptions/SPException.php b/lib/SP/Core/Exceptions/SPException.php
index b1a7fad4..3e94ede8 100644
--- a/lib/SP/Core/Exceptions/SPException.php
+++ b/lib/SP/Core/Exceptions/SPException.php
@@ -36,30 +36,30 @@ class SPException extends Exception
/**
* Constantes para tipos de excepción
*/
- const SP_OK = 0;
- const SP_CRITICAL = 1;
- const SP_WARNING = 2;
- const SP_ERROR = 3;
- const SP_INFO = 4;
+ const OK = 0;
+ const CRITICAL = 1;
+ const WARNING = 2;
+ const ERROR = 3;
+ const INFO = 4;
/**
* @var int Tipo de excepción
*/
- protected $type = 0;
+ protected $type;
/**
* @var string Ayuda de la excepción
*/
- protected $hint = '';
+ protected $hint;
/**
* SPException constructor.
*
- * @param string $type
* @param string $message
+ * @param int $type
* @param string $hint
* @param int $code
* @param Exception|null $previous
*/
- public function __construct($type, $message, $hint = '', $code = 0, \Exception $previous = null)
+ public function __construct($message, $type = self::ERROR, $hint = null, $code = 0, \Exception $previous = null)
{
$this->type = $type;
$this->hint = $hint;
@@ -74,10 +74,10 @@ class SPException extends Exception
public static function getExceptionTypeName($type)
{
$typeName = [
- self::SP_OK => 'ok',
- self::SP_CRITICAL => 'critical',
- self::SP_WARNING => 'warning',
- self::SP_ERROR => 'error'
+ self::OK => 'ok',
+ self::CRITICAL => 'critical',
+ self::WARNING => 'warning',
+ self::ERROR => 'error'
];
return $typeName[$type];
diff --git a/lib/SP/Core/Init.php b/lib/SP/Core/Init.php
index 68bbac6d..72f0e58e 100644
--- a/lib/SP/Core/Init.php
+++ b/lib/SP/Core/Init.php
@@ -26,21 +26,19 @@ namespace SP\Core;
use Defuse\Crypto\Exception\CryptoException;
use SP\Account\AccountAcl;
-use SP\Providers\Auth\Browser\Browser;
use SP\Config\Config;
-use SP\Modules\Web\Controllers\MainController;
use SP\Core\Crypt\CryptSessionHandler;
use SP\Core\Crypt\SecureKeyCookie;
use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Exceptions\SPException;
-use SP\Core\Plugin\PluginUtil;
use SP\Core\Upgrade\Upgrade;
use SP\Http\JsonResponse;
use SP\Http\Request;
use SP\Log\Email;
use SP\Log\Log;
use SP\Mgmt\Profiles\Profile;
-use SP\Mgmt\Users\UserUtil;
+use SP\Modules\Web\Controllers\MainController;
+use SP\Providers\Auth\Browser\Browser;
use SP\Storage\DBUtil;
use SP\Util\Checks;
use SP\Util\HttpUtil;
@@ -390,7 +388,7 @@ class Init
SessionUtil::cleanSession();
$Tpl = new Template();
- $Tpl->append('errors', ['type' => SPException::SP_CRITICAL, 'description' => __($message), 'hint' => __($hint)]);
+ $Tpl->append('errors', ['type' => SPException::CRITICAL, 'description' => __($message), 'hint' => __($hint)]);
$Controller = new MainController($Tpl, 'error', !Checks::isAjax());
$Controller->getError();
diff --git a/lib/SP/Core/Installer.php b/lib/SP/Core/Installer.php
index 5fa46f4d..9604a65e 100644
--- a/lib/SP/Core/Installer.php
+++ b/lib/SP/Core/Installer.php
@@ -34,9 +34,9 @@ use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\InvalidArgumentException;
use SP\Core\Exceptions\SPException;
use SP\Core\Traits\InjectableTrait;
-use SP\DataModel\UserGroupData;
use SP\DataModel\InstallData;
use SP\DataModel\ProfileData;
+use SP\DataModel\UserGroupData;
use SP\DataModel\UserLoginData;
use SP\Mgmt\Groups\Group;
use SP\Mgmt\Profiles\Profile;
@@ -147,63 +147,63 @@ class Installer
{
if (!$this->InstallData->getAdminLogin()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar nombre de usuario admin', false),
__('Usuario admin para acceso a la aplicación', false));
}
if (!$this->InstallData->getAdminPass()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar la clave de admin', false),
__('Clave del usuario admin de la aplicación', false));
}
if (!$this->InstallData->getMasterPassword()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar la clave maestra', false),
__('Clave maestra para encriptar las claves', false));
}
if (strlen($this->InstallData->getMasterPassword()) < 11) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Clave maestra muy corta', false),
__('La longitud de la clave maestra ha de ser mayor de 11 caracteres', false));
}
if (!$this->InstallData->getDbAdminUser()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar el usuario de la BBDD', false),
__('Usuario con permisos de administrador de la Base de Datos', false));
}
if (!$this->InstallData->getDbAdminPass()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar la clave de la BBDD'),
__('Clave del usuario administrador de la Base de Datos'));
}
if (!$this->InstallData->getDbName()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar el nombre de la BBDD', false),
__('Nombre para la BBDD de la aplicación pej. syspass', false));
}
if (substr_count($this->InstallData->getDbName(), '.') >= 1) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('El nombre de la BBDD no puede contener "."', false),
__('Elimine los puntos del nombre de la Base de Datos', false));
}
if (!$this->InstallData->getDbHost()) {
throw new InvalidArgumentException(
- SPException::SP_CRITICAL,
+ SPException::CRITICAL,
__('Indicar el servidor de la BBDD', false),
__('Servidor donde se instalará la Base de Datos', false));
}
@@ -227,9 +227,7 @@ class Installer
$this->DB = new PDO($dsn, $this->InstallData->getDbAdminUser(), $this->InstallData->getDbAdminPass());
$this->DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
- throw new SPException(SPException::SP_CRITICAL,
- __('No es posible conectar con la BD', false),
- __('Compruebe los datos de conexión') . '
' . $e->getMessage());
+ throw new SPException(__('No es posible conectar con la BD', false), SPException::CRITICAL, __('Compruebe los datos de conexión') . '
' . $e->getMessage());
}
}
@@ -262,9 +260,7 @@ class Installer
$this->createDBUser();
}
} catch (PDOException $e) {
- throw new SPException(SPException::SP_CRITICAL,
- sprintf(__('No es posible comprobar el usuario de sysPass') . ' (%s)', $this->InstallData->getAdminLogin()),
- __('Compruebe los permisos del usuario de conexión a la BD', false));
+ throw new SPException(sprintf(__('No es posible comprobar el usuario de sysPass') . ' (%s)', $this->InstallData->getAdminLogin()), SPException::CRITICAL, __('Compruebe los permisos del usuario de conexión a la BD', false));
}
// Guardar el nuevo usuario/clave de conexión a la BD
@@ -309,9 +305,7 @@ class Installer
$this->DB->exec('FLUSH PRIVILEGES');
} catch (PDOException $e) {
throw new SPException(
- SPException::SP_CRITICAL,
- sprintf(__('Error al crear el usuario de conexión a MySQL \'%s\'', false), $this->InstallData->getDbUser()),
- $e->getMessage());
+ sprintf(__('Error al crear el usuario de conexión a MySQL \'%s\'', false), $this->InstallData->getDbUser()), SPException::CRITICAL, $e->getMessage());
}
}
@@ -325,13 +319,9 @@ class Installer
$checkDatabase = $this->checkDatabaseExist();
if ($checkDatabase && !$this->InstallData->isHostingMode()) {
- throw new SPException(SPException::SP_CRITICAL,
- __('La BBDD ya existe', false),
- __('Indique una nueva Base de Datos o elimine la existente', false));
+ throw new SPException(__('La BBDD ya existe', false), SPException::CRITICAL, __('Indique una nueva Base de Datos o elimine la existente', false));
} elseif (!$checkDatabase && $this->InstallData->isHostingMode()) {
- throw new SPException(SPException::SP_CRITICAL,
- __('La BBDD no existe', false),
- __('Es necesario crearla y asignar los permisos necesarios', false));
+ throw new SPException(__('La BBDD no existe', false), SPException::CRITICAL, __('Es necesario crearla y asignar los permisos necesarios', false));
}
if (!$this->InstallData->isHostingMode()) {
@@ -340,9 +330,7 @@ class Installer
$this->DB->exec(/** @lang SQL */
'CREATE SCHEMA `' . $this->InstallData->getDbName() . '` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci');
} catch (PDOException $e) {
- throw new SPException(SPException::SP_CRITICAL,
- sprintf(__('Error al crear la BBDD') . ' (%s)', $e->getMessage()),
- __('Verifique los permisos del usuario de la Base de Datos', false));
+ throw new SPException(sprintf(__('Error al crear la BBDD') . ' (%s)', $e->getMessage()), SPException::CRITICAL, __('Verifique los permisos del usuario de la Base de Datos', false));
}
$query = /** @lang SQL */
@@ -360,9 +348,7 @@ class Installer
} catch (PDOException $e) {
$this->rollback();
- throw new SPException(SPException::SP_CRITICAL,
- sprintf(__('Error al establecer permisos de la BBDD (\'%s\')'), $e->getMessage()),
- __('Verifique los permisos del usuario de la Base de Datos', false));
+ throw new SPException(sprintf(__('Error al establecer permisos de la BBDD (\'%s\')'), $e->getMessage()), SPException::CRITICAL, __('Verifique los permisos del usuario de la Base de Datos', false));
}
}
}
@@ -416,18 +402,14 @@ class Installer
$fileName = SQL_PATH . DIRECTORY_SEPARATOR . 'dbstructure.sql';
if (!file_exists($fileName)) {
- throw new SPException(SPException::SP_CRITICAL,
- __('El archivo de estructura de la BBDD no existe', false),
- __('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.', false));
+ throw new SPException(__('El archivo de estructura de la BBDD no existe', false), SPException::CRITICAL, __('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.', false));
}
try {
// Usar la base de datos de sysPass
$this->DB->exec('USE `' . $this->InstallData->getDbName() . '`');
} catch (PDOException $e) {
- throw new SPException(SPException::SP_CRITICAL,
- sprintf(__('Error al seleccionar la BBDD') . ' \'%s\' (%s)', $this->InstallData->getDbName(), $e->getMessage()),
- __('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.', false));
+ throw new SPException(sprintf(__('Error al seleccionar la BBDD') . ' \'%s\' (%s)', $this->InstallData->getDbName(), $e->getMessage()), SPException::CRITICAL, __('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.', false));
}
// Leemos el archivo SQL para crear las tablas de la BBDD
@@ -443,9 +425,7 @@ class Installer
} catch (PDOException $e) {
$this->rollback();
- throw new SPException(SPException::SP_CRITICAL,
- sprintf(__('Error al crear la BBDD') . ' (%s)', $e->getMessage()),
- __('Error al crear la estructura de la Base de Datos.', false));
+ throw new SPException(sprintf(__('Error al crear la BBDD') . ' (%s)', $e->getMessage()), SPException::CRITICAL, __('Error al crear la estructura de la Base de Datos.', false));
}
}
}
@@ -462,9 +442,7 @@ class Installer
if (!DBUtil::checkDatabaseExist()) {
$this->rollback();
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al comprobar la base de datos', false),
- __('Intente de nuevo la instalación', false));
+ throw new SPException(__('Error al comprobar la base de datos', false), SPException::CRITICAL, __('Intente de nuevo la instalación', false));
}
}
@@ -508,14 +486,11 @@ class Installer
ConfigDB::writeConfig(true);
if (!UserPass::updateUserMPass($this->InstallData->getMasterPassword(), $UserData)) {
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al actualizar la clave maestra del usuario "admin"', false));
+ throw new SPException(__('Error al actualizar la clave maestra del usuario "admin"', false), SPException::CRITICAL);
}
} catch (\Exception $e) {
$this->rollback();
- throw new SPException(SPException::SP_CRITICAL,
- $e->getMessage(),
- __('Informe al desarrollador', false));
+ throw new SPException($e->getMessage(), SPException::CRITICAL, __('Informe al desarrollador', false));
}
}
diff --git a/lib/SP/Core/Language.php b/lib/SP/Core/Language.php
index 2c2cb584..52014843 100644
--- a/lib/SP/Core/Language.php
+++ b/lib/SP/Core/Language.php
@@ -100,10 +100,10 @@ class Language
$lang = SessionFactory::getLocale();
if (empty($lang) || $force === true) {
- $Language = new Language();
+ $language = new Language();
- self::$userLang = $Language->getUserLang();
- self::$globalLang = $Language->getGlobalLang();
+ self::$userLang = $language->getUserLang();
+ self::$globalLang = $language->getGlobalLang();
$lang = self::$userLang ?: self::$globalLang;
diff --git a/lib/SP/Core/OldCrypt.php b/lib/SP/Core/OldCrypt.php
index 24ed5d76..d2b5d9f6 100644
--- a/lib/SP/Core/OldCrypt.php
+++ b/lib/SP/Core/OldCrypt.php
@@ -25,7 +25,6 @@
namespace SP\Core;
use SP\Bootstrap;
-use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Core\Exceptions\SPException;
use SP\Util\Checks;
@@ -167,9 +166,7 @@ class OldCrypt
// Comprobar el módulo de encriptación
if (!OldCrypt::checkCryptModule()) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno', false),
- __('No se puede usar el módulo de encriptación', false)
+ __('Error interno', false), SPException::CRITICAL, __('No se puede usar el módulo de encriptación', false)
);
}
@@ -179,9 +176,7 @@ class OldCrypt
if (!empty($data) && ($encData['data'] === false || null === $encData['data'])) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno', false),
- __('Error al generar datos cifrados', false)
+ __('Error interno', false), SPException::CRITICAL, __('Error al generar datos cifrados', false)
);
}
diff --git a/lib/SP/Core/Plugin/PluginUtil.php b/lib/SP/Core/Plugin/PluginUtil.php
index 5a3a82e6..d0815dca 100644
--- a/lib/SP/Core/Plugin/PluginUtil.php
+++ b/lib/SP/Core/Plugin/PluginUtil.php
@@ -229,8 +229,8 @@ class PluginUtil
$PluginsLoader = new \SplClassLoader('Plugins', PLUGINS_PATH);
$PluginsLoader->register();
- foreach (PluginUtil::getPlugins() as $plugin) {
- $Plugin = PluginUtil::loadPlugin($plugin);
+ foreach (self::getPlugins() as $plugin) {
+ $Plugin = self::loadPlugin($plugin);
if ($Plugin !== false) {
DiFactory::getEventDispatcher()->attach($Plugin);
diff --git a/lib/SP/Core/Session/Session.php b/lib/SP/Core/Session/Session.php
index 88ea295e..b59f0b18 100644
--- a/lib/SP/Core/Session/Session.php
+++ b/lib/SP/Core/Session/Session.php
@@ -284,4 +284,24 @@ class Session
{
return $this->getSessionKey('config');
}
+
+ /**
+ * Devolver la clave pública
+ *
+ * @return mixed
+ */
+ public function getPublicKey()
+ {
+ return $this->getSessionKey('pubkey');
+ }
+
+ /**
+ * Establecer la clave pública
+ *
+ * @param $key
+ */
+ public function setPublicKey($key)
+ {
+ $this->setSessionKey('pubkey', $key);
+ }
}
\ No newline at end of file
diff --git a/lib/SP/Core/Traits/InjectableTrait.php b/lib/SP/Core/Traits/InjectableTrait.php
index 2231a237..d51275e7 100644
--- a/lib/SP/Core/Traits/InjectableTrait.php
+++ b/lib/SP/Core/Traits/InjectableTrait.php
@@ -38,6 +38,7 @@ trait InjectableTrait
* Injects dependencies through the DI container
*
* @throws \SP\Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
final protected function injectDependencies()
{
diff --git a/lib/SP/Core/Upgrade/Crypt.php b/lib/SP/Core/Upgrade/Crypt.php
index 127ca6cb..4e77b49b 100644
--- a/lib/SP/Core/Upgrade/Crypt.php
+++ b/lib/SP/Core/Upgrade/Crypt.php
@@ -55,11 +55,11 @@ class Crypt
AccountHistoryCrypt::$currentMPassHash = ConfigDB::getValue('masterPwd');
if (!DbWrapper::beginTransaction()) {
- throw new SPException(SPException::SP_ERROR, __('No es posible iniciar una transacción', false));
+ throw new SPException(__('No es posible iniciar una transacción', false), SPException::ERROR);
}
if (!self::migrateHash($masterPass)) {
- throw new SPException(SPException::SP_INFO, __('Clave maestra incorrecta', false));
+ throw new SPException(__('Clave maestra incorrecta', false), SPException::INFO);
}
self::migrateAccounts($masterPass);
@@ -67,7 +67,7 @@ class Crypt
UserMigrate::setMigrateUsers();
if (!DbWrapper::endTransaction()) {
- throw new SPException(SPException::SP_ERROR, __('No es posible finalizar una transacción', false));
+ throw new SPException(__('No es posible finalizar una transacción', false), SPException::ERROR);
}
debugLog('Total time: ' . getElapsedTime());
diff --git a/lib/SP/Core/Upgrade/Upgrade.php b/lib/SP/Core/Upgrade/Upgrade.php
index 395847d1..52413625 100644
--- a/lib/SP/Core/Upgrade/Upgrade.php
+++ b/lib/SP/Core/Upgrade/Upgrade.php
@@ -28,9 +28,7 @@ namespace SP\Core\Upgrade;
use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Config\ConfigDB;
-use SP\Controller\MainActionController;
use SP\Core\Exceptions\SPException;
-use SP\Core\Init;
use SP\Core\SessionFactory as CoreSession;
use SP\Core\TaskFactory;
use SP\Core\Traits\InjectableTrait;
@@ -71,18 +69,21 @@ class Upgrade
/**
* @var Config
*/
- protected $Config;
+ protected $config;
/**
* @var ConfigData
*/
- protected $ConfigData;
+ protected $configData;
/**
* @var Log
*/
- protected $Log;
+ protected $log;
/**
* Upgrade constructor.
+ *
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
*/
public function __construct()
{
@@ -103,15 +104,11 @@ class Upgrade
foreach (self::$dbUpgrade as $dbVersion) {
if (Util::checkVersion($version, $dbVersion)) {
if ($this->auxPreDbUpgrade($dbVersion) === false) {
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al aplicar la actualización auxiliar', false),
- __('Compruebe el registro de eventos para más detalles', false));
+ throw new SPException(__('Error al aplicar la actualización auxiliar', false), SPException::CRITICAL, __('Compruebe el registro de eventos para más detalles', false));
}
if ($this->upgradeDB($dbVersion) === false) {
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al aplicar la actualización de la Base de Datos', false),
- __('Compruebe el registro de eventos para más detalles', false));
+ throw new SPException(__('Error al aplicar la actualización de la Base de Datos', false), SPException::CRITICAL, __('Compruebe el registro de eventos para más detalles', false));
}
}
}
@@ -120,9 +117,7 @@ class Upgrade
if (Util::checkVersion($version, $appVersion)
&& $this->appUpgrades($appVersion) === false
) {
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al aplicar la actualización de la aplicación', false),
- __('Compruebe el registro de eventos para más detalles', false));
+ throw new SPException(__('Error al aplicar la actualización de la aplicación', false), SPException::CRITICAL, __('Compruebe el registro de eventos para más detalles', false));
}
}
@@ -130,9 +125,7 @@ class Upgrade
if (Util::checkVersion($version, $auxVersion)
&& $this->auxUpgrades($auxVersion) === false
) {
- throw new SPException(SPException::SP_CRITICAL,
- __('Error al aplicar la actualización auxiliar', false),
- __('Compruebe el registro de eventos para más detalles', false));
+ throw new SPException(__('Error al aplicar la actualización auxiliar', false), SPException::CRITICAL, __('Compruebe el registro de eventos para más detalles', false));
}
}
@@ -194,7 +187,7 @@ class Upgrade
*/
private function upgradeDB($version)
{
- $LogMessage = $this->Log->getLogMessage();
+ $LogMessage = $this->log->getLogMessage();
$LogMessage->setAction(__('Actualizar BBDD', false));
$LogMessage->addDetails(__('Versión', false), $version);
@@ -223,8 +216,8 @@ class Upgrade
} catch (SPException $e) {
$LogMessage->addDescription(__('Error al aplicar la actualización de la Base de Datos', false));
$LogMessage->addDetails('ERROR', sprintf('%s (%s)', $e->getMessage(), $e->getCode()));
- $this->Log->setLogLevel(Log::ERROR);
- $this->Log->writeLog();
+ $this->log->setLogLevel(Log::ERROR);
+ $this->log->writeLog();
Email::sendEmail($LogMessage);
return false;
@@ -236,7 +229,7 @@ class Upgrade
self::$currentDbVersion = $version;
$LogMessage->addDescription(__('Actualización de la Base de Datos realizada correctamente.', false));
- $this->Log->writeLog();
+ $this->log->writeLog();
Email::sendEmail($LogMessage);
@@ -289,7 +282,7 @@ class Upgrade
$UserData = User::getItem()->getByLogin(Request::analyze('userlogin'));
if (!is_object($UserData)) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener los datos del usuario', false));
+ throw new SPException(__('Error al obtener los datos del usuario', false), SPException::ERROR);
}
CoreSession::setUserData($UserData);
@@ -363,9 +356,9 @@ class Upgrade
case '200.17011202':
debugLog(__FUNCTION__ . ': ' . $version);
- $this->ConfigData->setSiteTheme('material-blue');
- $this->ConfigData->setConfigVersion($upgradeVersion);
- $this->Config->saveConfig(null, false);
+ $this->configData->setSiteTheme('material-blue');
+ $this->configData->setConfigVersion($upgradeVersion);
+ $this->config->saveConfig(null, false);
$count++;
break;
}
@@ -383,7 +376,7 @@ class Upgrade
*/
public function upgradeOldConfigFile($version)
{
- $LogMessage = $this->Log->getLogMessage();
+ $LogMessage = $this->log->getLogMessage();
$LogMessage->setAction(__('Actualizar Configuración', false));
// Include the file, save the data from $CONFIG
@@ -394,12 +387,12 @@ class Upgrade
$paramMapper = function ($mapFrom, $mapTo) use ($CONFIG, $LogMessage) {
if (isset($CONFIG[$mapFrom])) {
$LogMessage->addDetails(__('Parámetro', false), $mapFrom);
- $this->ConfigData->{$mapTo}($CONFIG[$mapFrom]);
+ $this->configData->{$mapTo}($CONFIG[$mapFrom]);
}
};
foreach (self::getConfigParams() as $mapTo => $mapFrom) {
- if (method_exists($this->ConfigData, $mapTo)) {
+ if (method_exists($this->configData, $mapTo)) {
if (is_array($mapFrom)) {
/** @var array $mapFrom */
foreach ($mapFrom as $param) {
@@ -418,22 +411,22 @@ class Upgrade
try {
- $this->ConfigData->setSiteTheme('material-blue');
- $this->ConfigData->setConfigVersion($version);
- $this->Config->saveConfig(null, false);
+ $this->configData->setSiteTheme('material-blue');
+ $this->configData->setConfigVersion($version);
+ $this->config->saveConfig(null, false);
rename(OLD_CONFIG_FILE, $oldFile);
$LogMessage->addDetails(__('Versión', false), $version);
- $this->Log->setLogLevel(Log::NOTICE);
- $this->Log->writeLog();
+ $this->log->setLogLevel(Log::NOTICE);
+ $this->log->writeLog();
return true;
} catch (\Exception $e) {
$LogMessage->addDescription(__('Error al actualizar la configuración', false));
$LogMessage->addDetails(__('Archivo', false), $oldFile);
- $this->Log->setLogLevel(Log::ERROR);
- $this->Log->writeLog();
+ $this->log->setLogLevel(Log::ERROR);
+ $this->log->writeLog();
}
// We are here...wrong
@@ -506,7 +499,8 @@ class Upgrade
/**
* Comrpueba y actualiza la versión de la BBDD.
*
- * @return int|false
+ * @return void
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
public function checkDbVersion()
{
@@ -516,18 +510,13 @@ class Upgrade
if (Util::checkVersion($databaseVersion, $appVersion)
&& Request::analyze('nodbupgrade', 0) === 0
&& Util::checkVersion($databaseVersion, self::$dbUpgrade)
+ && !$this->configData->isMaintenance()
) {
- if (!Init::checkMaintenanceMode(true)) {
- $this->setUpgradeKey('db');
- } else {
- $Controller = new MainActionController();
- $Controller->doAction($databaseVersion);
- }
+ $this->setUpgradeKey('db');
- return true;
+ // FIXME: send link for upgrading
+ throw new \RuntimeException('Needs upgrade');
}
-
- return false;
}
/**
@@ -538,42 +527,36 @@ class Upgrade
*/
private function setUpgradeKey($type)
{
- $upgradeKey = $this->ConfigData->getUpgradeKey();
+ $upgradeKey = $this->configData->getUpgradeKey();
if (empty($upgradeKey)) {
- $this->ConfigData->setUpgradeKey(Util::generateRandomBytes(32));
+ $this->configData->setUpgradeKey(Util::generateRandomBytes(32));
}
- $this->ConfigData->setMaintenance(true);
- $this->Config->saveConfig(null, false);
+ $this->configData->setMaintenance(true);
+ $this->config->saveConfig(null, false);
- Init::initError(
- __('La aplicación necesita actualizarse'),
- sprintf(__('Si es un administrador pulse en el enlace: %s'), '' . __('Actualizar') . ''));
+// Init::initError(
+// __('La aplicación necesita actualizarse'),
+// sprintf(__('Si es un administrador pulse en el enlace: %s'), '' . __('Actualizar') . ''));
}
/**
* Comrpueba y actualiza la versión de la aplicación.
*
- * @return int|false
+ * @return void
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
public function checkAppVersion()
{
- $appVersion = self::fixVersionNumber($this->ConfigData->getConfigVersion());
+ $appVersion = self::fixVersionNumber($this->configData->getConfigVersion());
- if (Util::checkVersion($appVersion, self::$appUpgrade)) {
- if (!Init::checkMaintenanceMode(true)) {
- $this->setUpgradeKey('app');
- } else {
- $Controller = new MainActionController();
- $Controller->doAction($appVersion);
- }
+ if (Util::checkVersion($appVersion, self::$appUpgrade) && !$this->configData->isMaintenance()) {
+ $this->setUpgradeKey('app');
- return true;
+ // FIXME: send link for upgrading
+ throw new \RuntimeException('Needs upgrade');
}
-
- return false;
}
/**
@@ -582,8 +565,8 @@ class Upgrade
*/
public function inject(Config $config, Log $log)
{
- $this->Config = $config;
- $this->ConfigData = $config->getConfigData();
- $this->Log = $log;
+ $this->config = $config;
+ $this->configData = $config->getConfigData();
+ $this->log = $log;
}
}
\ No newline at end of file
diff --git a/lib/SP/Core/XmlExport.php b/lib/SP/Core/XmlExport.php
index 04aaa496..4b156efb 100644
--- a/lib/SP/Core/XmlExport.php
+++ b/lib/SP/Core/XmlExport.php
@@ -212,13 +212,13 @@ class XmlExport
private function checkExportDir()
{
if (@mkdir($this->exportDir, 0750) === false && is_dir($this->exportDir) === false) {
- throw new SPException(SPException::SP_CRITICAL, sprintf(__('No es posible crear el directorio de backups ("%s")'), $this->exportDir));
+ throw new SPException(sprintf(__('No es posible crear el directorio de backups ("%s")'), $this->exportDir), SPException::CRITICAL);
}
clearstatcache(true, $this->exportDir);
if (!is_writable($this->exportDir)) {
- throw new SPException(SPException::SP_CRITICAL, __('Compruebe los permisos del directorio de backups', false));
+ throw new SPException(__('Compruebe los permisos del directorio de backups', false), SPException::CRITICAL);
}
return true;
@@ -235,7 +235,7 @@ class XmlExport
$root = $this->xml->createElement('Root');
$this->root = $this->xml->appendChild($root);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -264,7 +264,7 @@ class XmlExport
$this->root->appendChild($nodeMeta);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -303,7 +303,7 @@ class XmlExport
$this->appendNode($nodeCategories);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -364,9 +364,9 @@ class XmlExport
$this->root->appendChild($node);
}
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -403,7 +403,7 @@ class XmlExport
$this->appendNode($nodeCustomers);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -438,7 +438,7 @@ class XmlExport
$this->appendNode($nodeTags);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -496,7 +496,7 @@ class XmlExport
$this->appendNode($nodeAccounts);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -519,7 +519,7 @@ class XmlExport
$nodeMeta = $this->root->getElementsByTagName('Meta')->item(0);
$nodeMeta->appendChild($metaHash);
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -536,7 +536,7 @@ class XmlExport
$nodeXML = $this->xml->saveXML($this->root->getElementsByTagName($node)->item(0));
return $nodeXML;
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -553,10 +553,10 @@ class XmlExport
$this->xml->preserveWhiteSpace = false;
if (!$this->xml->save($this->exportFile)) {
- throw new SPException(SPException::SP_CRITICAL, __('Error al crear el archivo XML', false));
+ throw new SPException(__('Error al crear el archivo XML', false), SPException::CRITICAL);
}
} catch (\DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
diff --git a/lib/SP/DataModel/TrackData.php b/lib/SP/DataModel/TrackData.php
index a3ed66d8..e4329e47 100644
--- a/lib/SP/DataModel/TrackData.php
+++ b/lib/SP/DataModel/TrackData.php
@@ -154,7 +154,7 @@ class TrackData extends DataModelBase
} elseif ($ip === false) {
debugLog(sprintf('%s : %s', __('IP inválida', true), $track_ip));
- throw new InvalidArgumentException(SPException::SP_ERROR, __('IP inválida'), $track_ip);
+ throw new InvalidArgumentException(SPException::ERROR, __('IP inválida'), $track_ip);
}
}
diff --git a/lib/SP/Html/DataGrid/DataGridBase.php b/lib/SP/Html/DataGrid/DataGridBase.php
index b0d25590..d69eab16 100644
--- a/lib/SP/Html/DataGrid/DataGridBase.php
+++ b/lib/SP/Html/DataGrid/DataGridBase.php
@@ -285,7 +285,7 @@ abstract class DataGridBase implements DataGridInterface
$file = $this->theme->getViewsPath() . DIRECTORY_SEPARATOR . $template;
if (!is_readable($file)) {
- throw new FileNotFoundException(SPException::SP_ERROR, sprintf(__('No es posible obtener la plantilla "%s" : %s'), $template, $file));
+ throw new FileNotFoundException(SPException::ERROR, sprintf(__('No es posible obtener la plantilla "%s" : %s'), $template, $file));
}
return $file;
diff --git a/lib/SP/Html/Minify.php b/lib/SP/Html/Minify.php
index 93db2d85..67db37cf 100644
--- a/lib/SP/Html/Minify.php
+++ b/lib/SP/Html/Minify.php
@@ -24,8 +24,9 @@
namespace SP\Html;
-use CssMin;
+use Klein\Klein;
use SP\Core\Exceptions\SPException;
+use SP\Core\Traits\InjectableTrait;
use SP\Http\Request;
use SP\Util\Util;
@@ -38,11 +39,18 @@ defined('APP_ROOT') || die();
*/
class Minify
{
+ use InjectableTrait;
+
/**
* Constantes para tipos de archivos
*/
const FILETYPE_JS = 1;
const FILETYPE_CSS = 2;
+ const OFFSET = 3600 * 24 * 30;
+ /**
+ * @var Klein
+ */
+ protected $router;
/**
* Array con los archivos a procesar
@@ -63,6 +71,25 @@ class Minify
*/
private $base = '';
+ /**
+ * Minify constructor.
+ *
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function __construct()
+ {
+ $this->injectDependencies();
+ }
+
+ /**
+ * @param Klein $router
+ */
+ public function inject(Klein $router)
+ {
+ $this->router = $router;
+ }
+
/**
* @param string $path
* @param bool $checkPath
@@ -81,6 +108,8 @@ class Minify
* devuelve el código HTTP/304
*
* @param bool $disableMinify Deshabilitar minimizar
+ * @throws \Psr\Container\ContainerExceptionInterface
+ * @throws \Psr\Container\NotFoundExceptionInterface
*/
public function getMinified($disableMinify = false)
{
@@ -88,40 +117,13 @@ class Minify
return;
}
- $offset = 3600 * 24 * 30;
- $nextCheck = time() + $offset;
- $expire = 'Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', $nextCheck);
- $etag = $this->getEtag();
- $etagMatch = Request::getRequestHeaders('If-None-Match');
- $cacheControl = Request::getRequestHeaders('Cache-Control');
- $pragma = Request::getRequestHeaders('Pragma');
+ $this->setHeaders();
- header('Etag: ' . $etag);
- header("Cache-Control: public, max-age={$offset}, must-revalidate");
- header("Pragma: public; maxage={$offset}");
- header($expire);
+// if ($this->checkZlib() || !ob_start('ob_gzhandler')) {
+// ob_start();
+// }
- // Devolver código 304 si la versión es la misma y no se solicita refrescar
- if ($etag === $etagMatch
- && !($cacheControl === 'no-cache'
- || $cacheControl === 'max-age=0'
- || $pragma === 'no-cache')
- ) {
- header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
- exit();
- }
-
- if ($this->type === self::FILETYPE_JS) {
- header('Content-type: application/x-javascript; charset: UTF-8');
- } elseif ($this->type === self::FILETYPE_CSS) {
- header('Content-type: text/css; charset: UTF-8');
- }
-
- flush();
-
- if ($this->checkZlib() || !ob_start('ob_gzhandler')) {
- ob_start();
- }
+ $data = '';
foreach ($this->files as $file) {
$filePath = $file['base'] . DIRECTORY_SEPARATOR . $file['name'];
@@ -129,29 +131,57 @@ class Minify
// Obtener el recurso desde una URL
if ($file['type'] === 'url') {
try {
- $data = Util::getDataFromUrl($file['name']);
- echo '/* URL: ' . $file['name'] . ' */' . PHP_EOL;
- echo $data;
+ $data .= '/* URL: ' . $file['name'] . ' */' . PHP_EOL . Util::getDataFromUrl($file['name']);
} catch (SPException $e) {
- error_log($e->getMessage());
+ debugLog($e->getMessage());
}
} else {
if ($file['min'] === true && $disableMinify === false) {
- echo '/* MINIFIED FILE: ' . $file['name'] . ' */' . PHP_EOL;
+ $data .= '/* MINIFIED FILE: ' . $file['name'] . ' */' . PHP_EOL;
if ($this->type === self::FILETYPE_JS) {
- echo $this->jsCompress(file_get_contents($filePath));
+ $data .= $this->jsCompress(file_get_contents($filePath));
}
} else {
- echo '/* FILE: ' . $file['name'] . ' */' . PHP_EOL;
- echo file_get_contents($filePath);
+ $data .= '/* FILE: ' . $file['name'] . ' */' . PHP_EOL . file_get_contents($filePath);
}
}
-
- echo PHP_EOL;
}
- ob_end_flush();
+ $this->router->response()->body($data);
+ }
+
+ /**
+ * Sets HTTP headers
+ */
+ protected function setHeaders()
+ {
+ $response = $this->router->response();
+ $headers = $this->router->request()->headers();
+
+ $etag = $this->getEtag();
+
+ // Devolver código 304 si la versión es la misma y no se solicita refrescar
+ if ($etag === $headers->get('If-None-Match')
+ && !($headers->get('Cache-Control') === 'no-cache'
+ || $headers->get('Cache-Control') === 'max-age=0'
+ || $headers->get('Pragma') === 'no-cache')
+ ) {
+ $response->header($_SERVER['SERVER_PROTOCOL'], '304 Not Modified');
+ $response->send();
+ exit();
+ }
+
+ $response->header('Etag', $etag);
+ $response->header('Cache-Control', 'public, max-age={' . self::OFFSET . '}, must-revalidate');
+ $response->header('Pragma', 'public; maxage={' . self::OFFSET . '}');
+ $response->header('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + self::OFFSET));
+
+ if ($this->type === self::FILETYPE_JS) {
+ $response->header('Content-type', 'application/x-javascript; charset: UTF-8');
+ } elseif ($this->type === self::FILETYPE_CSS) {
+ $response->header('Content-type', 'text/css; charset: UTF-8');
+ }
}
/**
@@ -170,17 +200,6 @@ class Minify
return md5($md5Sum);
}
- /**
- * Comprobar si la salida comprimida en con zlib está activada.
- * No es compatible con ob_gzhandler()
- *
- * @return bool
- */
- private function checkZlib()
- {
- return Util::boolval(ini_get('zlib.output_compression'));
- }
-
/**
* Comprimir código javascript.
*
@@ -196,10 +215,28 @@ class Minify
'#^[\s\t]+#m',
'#\s*//\s.*$#m'
);
- $buffer = preg_replace($regexReplace, '', $buffer);
- // remove tabs, spaces, newlines, etc.
- $buffer = str_replace(array("\r\n", "\r", "\n", "\t"), '', $buffer);
- return $buffer;
+
+ return str_replace(array("\r\n", "\r", "\n", "\t"), '', preg_replace($regexReplace, '', $buffer));
+ }
+
+ /**
+ * @param $files
+ * @param bool $minify
+ * @return Minify
+ */
+ public function addFilesFromString($files, $minify = true)
+ {
+ if (strrpos($files, ',')) {
+ $files = explode(',', $files);
+
+ foreach ($files as $filename) {
+ $this->addFile($filename, $minify);
+ }
+ } else {
+ throw new \RuntimeException('Invalid string format');
+ }
+
+ return $this;
}
/**
@@ -247,6 +284,41 @@ class Minify
return !preg_match('/\.(min|pack)\./', $file);
}
+ /**
+ * @param array $files
+ * @param bool $minify
+ * @return Minify
+ */
+ public function addFiles(array $files, $minify = true)
+ {
+ foreach ($files as $filename) {
+ $this->processFile($filename, $minify);
+ }
+
+ return $this;
+ }
+
+ /**
+ * @param $file
+ * @param bool $minify
+ */
+ protected function processFile($file, $minify = true)
+ {
+ $filePath = $this->base . DIRECTORY_SEPARATOR . $file;
+
+ if (file_exists($filePath)) {
+ $this->files[] = array(
+ 'type' => 'file',
+ 'base' => $this->base,
+ 'name' => Request::getSecureAppFile($file, $this->base),
+ 'min' => $minify === true && $this->needsMinify($file),
+ 'md5' => md5_file($filePath)
+ );
+ } else {
+ debugLog('File not found: ' . $filePath);
+ }
+ }
+
/**
* Añadir un recurso desde URL
*
@@ -278,4 +350,15 @@ class Minify
return $this;
}
+
+ /**
+ * Comprobar si la salida comprimida en con zlib está activada.
+ * No es compatible con ob_gzhandler()
+ *
+ * @return bool
+ */
+ private function checkZlib()
+ {
+ return Util::boolval(ini_get('zlib.output_compression'));
+ }
}
\ No newline at end of file
diff --git a/lib/SP/Import/CsvImportBase.php b/lib/SP/Import/CsvImportBase.php
index 5c9f8d07..ecd01601 100644
--- a/lib/SP/Import/CsvImportBase.php
+++ b/lib/SP/Import/CsvImportBase.php
@@ -80,9 +80,7 @@ abstract class CsvImportBase extends ImportBase
// Comprobar el número de campos de la línea
if ($numfields !== $this->numFields) {
throw new SPException(
- SPException::SP_CRITICAL,
- sprintf(__('El número de campos es incorrecto (%d)', false), $numfields),
- sprintf(__('Compruebe el formato del archivo CSV en línea %s', false), $line)
+ sprintf(__('El número de campos es incorrecto (%d)', false), $numfields), SPException::CRITICAL, sprintf(__('Compruebe el formato del archivo CSV en línea %s', false), $line)
);
}
diff --git a/lib/SP/Import/FileImport.php b/lib/SP/Import/FileImport.php
index d5b2fdcb..70abf404 100644
--- a/lib/SP/Import/FileImport.php
+++ b/lib/SP/Import/FileImport.php
@@ -82,9 +82,7 @@ class FileImport
{
if (!is_array($fileData)) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Archivo no subido correctamente', false),
- __('Verifique los permisos del usuario del servidor web', false));
+ __('Archivo no subido correctamente', false), SPException::CRITICAL, __('Verifique los permisos del usuario del servidor web', false));
}
if ($fileData['name']) {
@@ -93,9 +91,7 @@ class FileImport
if ($fileExtension !== 'CSV' && $fileExtension !== 'XML') {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Tipo de archivo no soportado', false),
- __('Compruebe la extensión del archivo', false)
+ __('Tipo de archivo no soportado', false), SPException::CRITICAL, __('Compruebe la extensión del archivo', false)
);
}
}
@@ -109,9 +105,7 @@ class FileImport
Util::getMaxUpload();
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno al leer el archivo', false),
- __('Compruebe la configuración de PHP para subir archivos', false)
+ __('Error interno al leer el archivo', false), SPException::CRITICAL, __('Compruebe la configuración de PHP para subir archivos', false)
);
}
}
@@ -153,9 +147,7 @@ class FileImport
if ($this->fileContent === false) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno al leer el archivo', false),
- __('Compruebe los permisos del directorio temporal', false)
+ __('Error interno al leer el archivo', false), SPException::CRITICAL, __('Compruebe los permisos del directorio temporal', false)
);
}
}
@@ -181,9 +173,7 @@ class FileImport
if ($this->fileContent === false) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno al leer el archivo', false),
- __('Compruebe los permisos del directorio temporal', false)
+ __('Error interno al leer el archivo', false), SPException::CRITICAL, __('Compruebe los permisos del directorio temporal', false)
);
}
}
diff --git a/lib/SP/Import/Import.php b/lib/SP/Import/Import.php
index 12da0842..2ec53cb3 100644
--- a/lib/SP/Import/Import.php
+++ b/lib/SP/Import/Import.php
@@ -81,20 +81,18 @@ class Import
break;
default:
throw new SPException(
- SPException::SP_WARNING,
- sprintf(__('Tipo mime no soportado ("%s")'), $file->getFileType()),
- __('Compruebe el formato del archivo', false)
+ sprintf(__('Tipo mime no soportado ("%s")'), $file->getFileType()), SPException::WARNING, __('Compruebe el formato del archivo', false)
);
}
if (!DbWrapper::beginTransaction()) {
- throw new SPException(SPException::SP_ERROR, __('No es posible iniciar una transacción', false));
+ throw new SPException(__('No es posible iniciar una transacción', false), SPException::ERROR);
}
$Import->doImport();
if (!DbWrapper::endTransaction()) {
- throw new SPException(SPException::SP_ERROR, __('No es posible finalizar una transacción', false));
+ throw new SPException(__('No es posible finalizar una transacción', false), SPException::ERROR);
}
$LogMessage->addDetails(__('Cuentas importadas'), $Import->getCounter());
diff --git a/lib/SP/Import/SyspassImport.php b/lib/SP/Import/SyspassImport.php
index 7e977807..13289403 100644
--- a/lib/SP/Import/SyspassImport.php
+++ b/lib/SP/Import/SyspassImport.php
@@ -79,7 +79,7 @@ class SyspassImport extends ImportBase
if ($this->detectEncrypted()) {
if ($this->ImportParams->getImportPwd() === '') {
- throw new SPException(SPException::SP_ERROR, __('Clave de encriptación no indicada', false));
+ throw new SPException(__('Clave de encriptación no indicada', false), SPException::ERROR);
}
$this->processEncrypted();
@@ -92,7 +92,7 @@ class SyspassImport extends ImportBase
} catch (SPException $e) {
throw $e;
} catch (\Exception $e) {
- throw new SPException(SPException::SP_CRITICAL, $e->getMessage());
+ throw new SPException($e->getMessage(), SPException::CRITICAL);
}
}
@@ -126,7 +126,7 @@ class SyspassImport extends ImportBase
$hash = $this->xmlDOM->getElementsByTagName('Encrypted')->item(0)->getAttribute('hash');
if ($hash !== '' && !Hash::checkHashKey($this->ImportParams->getImportPwd(), $hash)) {
- throw new SPException(SPException::SP_ERROR, __('Clave de encriptación incorrecta', false));
+ throw new SPException(__('Clave de encriptación incorrecta', false), SPException::ERROR);
}
foreach ($this->xmlDOM->getElementsByTagName('Data') as $node) {
@@ -143,7 +143,7 @@ class SyspassImport extends ImportBase
$newXmlData = new \DOMDocument();
// $newXmlData->preserveWhiteSpace = true;
if (!$newXmlData->loadXML($xmlDecrypted)) {
- throw new SPException(SPException::SP_ERROR, __('Clave de encriptación incorrecta', false));
+ throw new SPException(__('Clave de encriptación incorrecta', false), SPException::ERROR);
}
$newNode = $this->xmlDOM->importNode($newXmlData->documentElement, TRUE);
diff --git a/lib/SP/Import/XmlFileImport.php b/lib/SP/Import/XmlFileImport.php
index 785c1c2b..4f61c834 100644
--- a/lib/SP/Import/XmlFileImport.php
+++ b/lib/SP/Import/XmlFileImport.php
@@ -81,9 +81,7 @@ class XmlFileImport
}
} else {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Archivo XML no soportado', false),
- __('No es posible detectar la aplicación que exportó los datos', false)
+ __('Archivo XML no soportado', false), SPException::CRITICAL, __('No es posible detectar la aplicación que exportó los datos', false)
);
}
@@ -102,9 +100,7 @@ class XmlFileImport
if ($this->xmlDOM->load($this->FileImport->getTmpFile()) === false) {
throw new SPException(
- SPException::SP_CRITICAL,
- __('Error interno', false),
- __('No es posible procesar el archivo XML', false)
+ __('Error interno', false), SPException::CRITICAL, __('No es posible procesar el archivo XML', false)
);
}
}
diff --git a/lib/SP/Import/XmlImportTrait.php b/lib/SP/Import/XmlImportTrait.php
index 703248fb..7ddecd91 100644
--- a/lib/SP/Import/XmlImportTrait.php
+++ b/lib/SP/Import/XmlImportTrait.php
@@ -64,16 +64,14 @@ trait XmlImportTrait
if ($ParentNode->length === 0) {
if ($required === true) {
throw new SPException(
- SPException::SP_WARNING,
- __('Formato de XML inválido', false),
- sprintf(__('El nodo "%s" no existe'), $nodeName));
+ __('Formato de XML inválido', false), SPException::WARNING, sprintf(__('El nodo "%s" no existe'), $nodeName));
}
return;
}
if (!is_callable([$this, $callback])) {
- throw new SPException(SPException::SP_WARNING, __('Método inválido', false));
+ throw new SPException(__('Método inválido', false), SPException::WARNING);
}
/** @var \DOMElement $nodes */
diff --git a/lib/SP/Mgmt/ApiTokens/ApiToken.php b/lib/SP/Mgmt/ApiTokens/ApiToken.php
index 77dfd3b1..07b3a987 100644
--- a/lib/SP/Mgmt/ApiTokens/ApiToken.php
+++ b/lib/SP/Mgmt/ApiTokens/ApiToken.php
@@ -57,7 +57,7 @@ class ApiToken extends ApiTokenBase implements ItemInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_WARNING, __('La autorización ya existe', false));
+ throw new SPException(__('La autorización ya existe', false), SPException::WARNING);
}
$token = $this->getTokenByUserId($this->itemData->getAuthtokenUserId());
@@ -181,7 +181,7 @@ class ApiToken extends ApiTokenBase implements ItemInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Token no encontrado', false));
+ throw new SPException(__('Token no encontrado', false), SPException::INFO);
} else {
$Data->addParam(null);
}
@@ -199,7 +199,7 @@ class ApiToken extends ApiTokenBase implements ItemInterface
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_WARNING, __('La autorización ya existe', false));
+ throw new SPException(__('La autorización ya existe', false), SPException::WARNING);
}
$token = $this->getTokenByUserId($this->itemData->getAuthtokenUserId());
diff --git a/lib/SP/Mgmt/Categories/Category.php b/lib/SP/Mgmt/Categories/Category.php
index 31c52937..c16bcc49 100644
--- a/lib/SP/Mgmt/Categories/Category.php
+++ b/lib/SP/Mgmt/Categories/Category.php
@@ -51,7 +51,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_WARNING, __('Categoría duplicada', false));
+ throw new SPException(__('Categoría duplicada', false), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -121,7 +121,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Categoría no encontrada', false));
+ throw new SPException(__('Categoría no encontrada', false), SPException::INFO);
}
return $this;
@@ -171,7 +171,7 @@ class Category extends CategoryBase implements ItemInterface, ItemSelectInterfac
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_WARNING, __('Nombre de categoría duplicado', false));
+ throw new SPException(__('Nombre de categoría duplicado', false), SPException::WARNING);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/CustomFields/CustomField.php b/lib/SP/Mgmt/CustomFields/CustomField.php
index e892dde7..31edcb87 100644
--- a/lib/SP/Mgmt/CustomFields/CustomField.php
+++ b/lib/SP/Mgmt/CustomFields/CustomField.php
@@ -68,7 +68,7 @@ class CustomField extends CustomFieldBase implements ItemInterface
$securedKey = Crypt::makeSecuredKey($sessionKey);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$query = /** @lang SQL */
@@ -135,7 +135,7 @@ class CustomField extends CustomFieldBase implements ItemInterface
$securedKey = Crypt::makeSecuredKey($sessionKey);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/CustomFields/CustomFieldDef.php b/lib/SP/Mgmt/CustomFields/CustomFieldDef.php
index b70d0797..e6533036 100644
--- a/lib/SP/Mgmt/CustomFields/CustomFieldDef.php
+++ b/lib/SP/Mgmt/CustomFields/CustomFieldDef.php
@@ -72,7 +72,7 @@ class CustomFieldDef extends CustomFieldBase implements ItemInterface
public function delete($id)
{
if ($this->deleteItemsDataForDefinition($id) === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al eliminar el campo personalizado', false));
+ throw new SPException(__('Error al eliminar el campo personalizado', false), SPException::ERROR);
}
$query = /** @lang SQL */
@@ -159,7 +159,7 @@ class CustomFieldDef extends CustomFieldBase implements ItemInterface
$CustomFieldDef = DbWrapper::getResults($Data);
if ($CustomFieldDef === false) {
- throw new SPException(SPException::SP_INFO, __('Campo personalizado no encontrado', false));
+ throw new SPException(__('Campo personalizado no encontrado', false), SPException::INFO);
}
/** @var CustomFieldDefinitionData $fieldDef */
@@ -212,7 +212,7 @@ class CustomFieldDef extends CustomFieldBase implements ItemInterface
$queryRes = DbWrapper::getResultsArray($Data);
if (count($queryRes) === 0) {
- throw new SPException(SPException::SP_INFO, __('No se encontraron campos personalizados', false));
+ throw new SPException(__('No se encontraron campos personalizados', false), SPException::INFO);
}
$fields = [];
diff --git a/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php b/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php
index 0f01e345..e13c2309 100644
--- a/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php
+++ b/lib/SP/Mgmt/CustomFields/CustomFieldsUtil.php
@@ -85,7 +85,7 @@ class CustomFieldsUtil
$securedKey = Crypt::makeSecuredKey($newMasterPassword);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$query = /** @lang SQL */
@@ -156,7 +156,7 @@ class CustomFieldsUtil
$fieldData = OldCrypt::getDecrypt($CustomField->getCustomfielddataData(), $CustomField->getCustomfielddataKey(), $currentMasterPass);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __('Error interno', false));
+ throw new QueryException(SPException::ERROR, __('Error interno', false));
}
$query = /** @lang SQL */
@@ -205,7 +205,7 @@ class CustomFieldsUtil
CustomField::getItem($CustomFieldData)->add();
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error interno'));
+ throw new SPException(__('Error interno'), SPException::ERROR);
}
}
@@ -226,7 +226,7 @@ class CustomFieldsUtil
CustomField::getItem($CustomFieldData)->update();
}
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error interno'));
+ throw new SPException(__('Error interno'), SPException::ERROR);
}
}
diff --git a/lib/SP/Mgmt/Customers/Customer.php b/lib/SP/Mgmt/Customers/Customer.php
index 8a3ecf30..9d0f4d71 100644
--- a/lib/SP/Mgmt/Customers/Customer.php
+++ b/lib/SP/Mgmt/Customers/Customer.php
@@ -52,7 +52,7 @@ class Customer extends CustomerBase implements ItemInterface, ItemSelectInterfac
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_WARNING, __('Cliente duplicado', false));
+ throw new SPException(__('Cliente duplicado', false), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -114,7 +114,7 @@ class Customer extends CustomerBase implements ItemInterface, ItemSelectInterfac
public function delete($id)
{
if ($this->checkInUse($id)) {
- throw new SPException(SPException::SP_WARNING, __('No es posible eliminar', false));
+ throw new SPException(__('No es posible eliminar', false), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -128,7 +128,7 @@ class Customer extends CustomerBase implements ItemInterface, ItemSelectInterfac
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Cliente no encontrado', false));
+ throw new SPException(__('Cliente no encontrado', false), SPException::INFO);
}
return $this;
@@ -178,7 +178,7 @@ class Customer extends CustomerBase implements ItemInterface, ItemSelectInterfac
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_WARNING, __('Cliente duplicado', false));
+ throw new SPException(__('Cliente duplicado', false), SPException::WARNING);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/Files/File.php b/lib/SP/Mgmt/Files/File.php
index 958dedb5..4a0a58ce 100644
--- a/lib/SP/Mgmt/Files/File.php
+++ b/lib/SP/Mgmt/Files/File.php
@@ -127,7 +127,7 @@ class File extends FileBase implements ItemInterface, ItemSelectInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Archivo no encontrado', false));
+ throw new SPException(__('Archivo no encontrado', false), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Mgmt/Groups/Group.php b/lib/SP/Mgmt/Groups/Group.php
index 3aa10b29..a7d405a3 100644
--- a/lib/SP/Mgmt/Groups/Group.php
+++ b/lib/SP/Mgmt/Groups/Group.php
@@ -55,7 +55,7 @@ class Group extends GroupBase implements ItemInterface, ItemSelectInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Nombre de grupo duplicado', false));
+ throw new SPException(__('Nombre de grupo duplicado', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -108,7 +108,7 @@ class Group extends GroupBase implements ItemInterface, ItemSelectInterface
public function delete($id)
{
if ($this->checkInUse($id)) {
- throw new SPException(SPException::SP_WARNING, __('Grupo en uso', false));
+ throw new SPException(__('Grupo en uso', false), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -122,7 +122,7 @@ class Group extends GroupBase implements ItemInterface, ItemSelectInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Grupo no encontrado', false));
+ throw new SPException(__('Grupo no encontrado', false), SPException::INFO);
}
GroupUsers::getItem()->delete($id);
@@ -191,7 +191,7 @@ class Group extends GroupBase implements ItemInterface, ItemSelectInterface
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_INFO, __('Nombre de grupo duplicado', false));
+ throw new SPException(__('Nombre de grupo duplicado', false), SPException::INFO);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/ItemBaseTrait.php b/lib/SP/Mgmt/ItemBaseTrait.php
index 49a40c63..5325eec3 100644
--- a/lib/SP/Mgmt/ItemBaseTrait.php
+++ b/lib/SP/Mgmt/ItemBaseTrait.php
@@ -113,7 +113,7 @@ trait ItemBaseTrait
final public function setItemData($itemData)
{
if (null !== $this->dataModel && ($itemData instanceof $this->dataModel) === false) {
- throw new InvalidClassException(SPException::SP_ERROR, $this->dataModel);
+ throw new InvalidClassException(SPException::ERROR, $this->dataModel);
}
$this->itemData = $itemData;
@@ -137,7 +137,7 @@ trait ItemBaseTrait
final protected function setDataModel($dataModel)
{
if (false === class_exists($dataModel)) {
- throw new InvalidClassException(SPException::SP_ERROR, $dataModel);
+ throw new InvalidClassException(SPException::ERROR, $dataModel);
}
$this->dataModel = $dataModel;
diff --git a/lib/SP/Mgmt/Notices/Notice.php b/lib/SP/Mgmt/Notices/Notice.php
index 19da923b..b96a3d2e 100644
--- a/lib/SP/Mgmt/Notices/Notice.php
+++ b/lib/SP/Mgmt/Notices/Notice.php
@@ -98,7 +98,7 @@ class Notice extends NoticeBase implements ItemInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Notificación no encontrada', false));
+ throw new SPException(__('Notificación no encontrada', false), SPException::INFO);
}
return $this;
@@ -166,7 +166,7 @@ class Notice extends NoticeBase implements ItemInterface
try {
$queryRes = DbWrapper::getResults($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener la notificación', false));
+ throw new SPException(__('Error al obtener la notificación', false), SPException::ERROR);
}
return $queryRes;
@@ -197,7 +197,7 @@ class Notice extends NoticeBase implements ItemInterface
try {
$queryRes = DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener las notificaciones', false));
+ throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
}
return $queryRes;
@@ -283,7 +283,7 @@ class Notice extends NoticeBase implements ItemInterface
try {
$queryRes = DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener las notificaciones', false));
+ throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
}
return $queryRes;
@@ -317,7 +317,7 @@ class Notice extends NoticeBase implements ItemInterface
try {
$queryRes = DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener las notificaciones', false));
+ throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
}
return $queryRes;
@@ -353,7 +353,7 @@ class Notice extends NoticeBase implements ItemInterface
try {
$queryRes = DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener las notificaciones', false));
+ throw new SPException(__('Error al obtener las notificaciones', false), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Mgmt/Plugins/Plugin.php b/lib/SP/Mgmt/Plugins/Plugin.php
index 7351095c..a839a72d 100644
--- a/lib/SP/Mgmt/Plugins/Plugin.php
+++ b/lib/SP/Mgmt/Plugins/Plugin.php
@@ -87,7 +87,7 @@ class Plugin extends PluginBase implements ItemInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Plugin no encontrado', false));
+ throw new SPException(__('Plugin no encontrado', false), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Mgmt/Profiles/Profile.php b/lib/SP/Mgmt/Profiles/Profile.php
index 5af04065..4d3824ea 100644
--- a/lib/SP/Mgmt/Profiles/Profile.php
+++ b/lib/SP/Mgmt/Profiles/Profile.php
@@ -28,8 +28,8 @@ namespace SP\Mgmt\Profiles;
defined('APP_ROOT') || die();
use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserProfileData;
use SP\DataModel\ProfileData;
+use SP\DataModel\UserProfileData;
use SP\Mgmt\ItemInterface;
use SP\Mgmt\ItemSelectInterface;
use SP\Mgmt\ItemTrait;
@@ -53,7 +53,7 @@ class Profile extends ProfileBase implements ItemInterface, ItemSelectInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Nombre de perfil duplicado', false));
+ throw new SPException(__('Nombre de perfil duplicado', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -102,7 +102,7 @@ class Profile extends ProfileBase implements ItemInterface, ItemSelectInterface
public function delete($id)
{
if ($this->checkInUse($id)) {
- throw new SPException(SPException::SP_INFO, __('Perfil en uso', false));
+ throw new SPException(__('Perfil en uso', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -116,7 +116,7 @@ class Profile extends ProfileBase implements ItemInterface, ItemSelectInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Perfil no encontrado', false));
+ throw new SPException(__('Perfil no encontrado', false), SPException::INFO);
}
return $this;
@@ -179,7 +179,7 @@ class Profile extends ProfileBase implements ItemInterface, ItemSelectInterface
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_INFO, __('Nombre de perfil duplicado', false));
+ throw new SPException(__('Nombre de perfil duplicado', false), SPException::INFO);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/PublicLinks/PublicLink.php b/lib/SP/Mgmt/PublicLinks/PublicLink.php
index 329b8953..315bb0bc 100644
--- a/lib/SP/Mgmt/PublicLinks/PublicLink.php
+++ b/lib/SP/Mgmt/PublicLinks/PublicLink.php
@@ -121,7 +121,7 @@ class PublicLink extends PublicLinkBase implements ItemInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Enlace ya creado', false));
+ throw new SPException(__('Enlace ya creado', false), SPException::INFO);
}
$this->itemData->setDateAdd(time());
@@ -184,7 +184,7 @@ class PublicLink extends PublicLinkBase implements ItemInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Enlace no encontrado', false));
+ throw new SPException(__('Enlace no encontrado', false), SPException::INFO);
}
return $this;
@@ -245,7 +245,7 @@ class PublicLink extends PublicLinkBase implements ItemInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener enlace', false));
+ throw new SPException(__('Error al obtener enlace', false), SPException::ERROR);
}
/** @var $PublicLink PublicLinkData */
@@ -344,7 +344,7 @@ class PublicLink extends PublicLinkBase implements ItemInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener enlace', false));
+ throw new SPException(__('Error al obtener enlace', false), SPException::ERROR);
} elseif (is_array($queryRes)) {
return false;
}
@@ -378,7 +378,7 @@ class PublicLink extends PublicLinkBase implements ItemInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener enlace'));
+ throw new SPException(__u('Error al obtener enlace'), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Mgmt/Tags/Tag.php b/lib/SP/Mgmt/Tags/Tag.php
index ce922204..ebd13215 100644
--- a/lib/SP/Mgmt/Tags/Tag.php
+++ b/lib/SP/Mgmt/Tags/Tag.php
@@ -51,7 +51,7 @@ class Tag extends TagBase implements ItemInterface, ItemSelectInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Etiqueta duplicada', false));
+ throw new SPException(__('Etiqueta duplicada', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -111,7 +111,7 @@ class Tag extends TagBase implements ItemInterface, ItemSelectInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Etiqueta no encontrada', false));
+ throw new SPException(__('Etiqueta no encontrada', false), SPException::INFO);
}
return $this;
@@ -124,7 +124,7 @@ class Tag extends TagBase implements ItemInterface, ItemSelectInterface
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_INFO, __('Etiqueta duplicada', false));
+ throw new SPException(__('Etiqueta duplicada', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -178,7 +178,7 @@ class Tag extends TagBase implements ItemInterface, ItemSelectInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener etiqueta', false));
+ throw new SPException(__('Error al obtener etiqueta', false), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Mgmt/Users/User.php b/lib/SP/Mgmt/Users/User.php
index 0f82719f..785ccf6b 100644
--- a/lib/SP/Mgmt/Users/User.php
+++ b/lib/SP/Mgmt/Users/User.php
@@ -53,7 +53,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Login/email de usuario duplicados', false));
+ throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -137,7 +137,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
DbWrapper::getQuery($Data);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Usuario no encontrado', false));
+ throw new SPException(__('Usuario no encontrado', false), SPException::INFO);
}
$this->itemData->setId(DbWrapper::$lastId);
@@ -152,7 +152,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
public function update()
{
if ($this->checkDuplicatedOnUpdate()) {
- throw new SPException(SPException::SP_INFO, __('Login/email de usuario duplicados', false));
+ throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
}
$query = /** @lang SQL */
@@ -252,7 +252,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
try {
$queryRes = DbWrapper::getResultsArray($Data);
} catch (SPException $e) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener los usuarios', false));
+ throw new SPException(__('Error al obtener los usuarios', false), SPException::ERROR);
}
return $queryRes;
@@ -345,7 +345,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener los datos del usuario', false));
+ throw new SPException(__('Error al obtener los datos del usuario', false), SPException::ERROR);
}
return $queryRes;
@@ -405,7 +405,7 @@ class User extends UserBase implements ItemInterface, ItemSelectInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error al obtener los datos del usuario', false));
+ throw new SPException(__('Error al obtener los datos del usuario', false), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Mgmt/Users/UserLdap.php b/lib/SP/Mgmt/Users/UserLdap.php
index ba9a7111..a171e6f9 100644
--- a/lib/SP/Mgmt/Users/UserLdap.php
+++ b/lib/SP/Mgmt/Users/UserLdap.php
@@ -24,7 +24,6 @@
namespace SP\Mgmt\Users;
-use SP\Config\Config;
use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\SPException;
use SP\Core\Messages\LogMessage;
@@ -73,7 +72,7 @@ class UserLdap extends User
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __('Login/email de usuario duplicados', false));
+ throw new SPException(__('Login/email de usuario duplicados', false), SPException::INFO);
}
$groupId = $this->ConfigData->getLdapDefaultGroup();
diff --git a/lib/SP/Mgmt/Users/UserMigrate.php b/lib/SP/Mgmt/Users/UserMigrate.php
index 666afa1f..f3c0102f 100644
--- a/lib/SP/Mgmt/Users/UserMigrate.php
+++ b/lib/SP/Mgmt/Users/UserMigrate.php
@@ -28,10 +28,8 @@ defined('APP_ROOT') || die();
use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserData;
-use SP\DataModel\UserToUserGroupData;
use SP\DataModel\UserLoginData;
-use SP\Log\Email;
+use SP\DataModel\UserToUserGroupData;
use SP\Log\Log;
use SP\Mgmt\Groups\GroupUsers;
use SP\Storage\DbWrapper;
@@ -139,7 +137,7 @@ class UserMigrate
$Log->setLogLevel(Log::ERROR);
$Log->writeLog();
- throw new SPException(SPException::SP_ERROR, $LogMessage->getDescription());
+ throw new SPException($LogMessage->getDescription(), SPException::ERROR);
}
foreach ($queryRes as $user) {
diff --git a/lib/SP/Mgmt/Users/UserPass.php b/lib/SP/Mgmt/Users/UserPass.php
index 81098e69..b71e893c 100644
--- a/lib/SP/Mgmt/Users/UserPass.php
+++ b/lib/SP/Mgmt/Users/UserPass.php
@@ -28,7 +28,6 @@ defined('APP_ROOT') || die();
use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
use SP\Bootstrap;
-use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Config\ConfigDB;
use SP\Controller\LoginController;
@@ -39,7 +38,6 @@ 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\UserData;
use SP\DataModel\UserLoginData;
use SP\DataModel\UserPassData;
use SP\Log\Email;
@@ -260,7 +258,7 @@ class UserPass extends UserBase
if (!empty($cryptMPass)) {
if (strlen($securedKey) > 1000 || strlen($cryptMPass) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __u('Error interno'), '', LoginController::STATUS_INTERNAL_ERROR);
+ throw new QueryException(SPException::ERROR, __u('Error interno'), '', LoginController::STATUS_INTERNAL_ERROR);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Mgmt/Users/UserPassRecover.php b/lib/SP/Mgmt/Users/UserPassRecover.php
index d5d0b4ff..2c0df93c 100644
--- a/lib/SP/Mgmt/Users/UserPassRecover.php
+++ b/lib/SP/Mgmt/Users/UserPassRecover.php
@@ -108,9 +108,9 @@ class UserPassRecover extends UserPassRecoverBase implements ItemInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __('Error en comprobación de hash', false));
+ throw new SPException(__('Error en comprobación de hash', false), SPException::ERROR);
} elseif ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __('Hash inválido o expirado', false));
+ throw new SPException(__('Hash inválido o expirado', false), SPException::INFO);
}
$this->itemData = $queryRes;
diff --git a/lib/SP/Mgmt/Users/UserSSO.php b/lib/SP/Mgmt/Users/UserSSO.php
index a05738f5..9046e572 100644
--- a/lib/SP/Mgmt/Users/UserSSO.php
+++ b/lib/SP/Mgmt/Users/UserSSO.php
@@ -24,7 +24,6 @@
namespace SP\Mgmt\Users;
-use SP\Config\Config;
use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\SPException;
use SP\DataModel\UserLoginData;
@@ -73,7 +72,7 @@ class UserSSO extends User
public function add()
{
if ($this->checkDuplicatedOnAdd()) {
- throw new SPException(SPException::SP_INFO, __u('Login/email de usuario duplicados'));
+ throw new SPException(__u('Login/email de usuario duplicados'), SPException::INFO);
}
$groupId = $this->ConfigData->getSsoDefaultGroup();
diff --git a/lib/SP/Mvc/View/Template.php b/lib/SP/Mvc/View/Template.php
index 19e942f2..673f009f 100644
--- a/lib/SP/Mvc/View/Template.php
+++ b/lib/SP/Mvc/View/Template.php
@@ -139,7 +139,7 @@ class Template
debugLog($msg);
- throw new FileNotFoundException(SPException::SP_ERROR, $msg);
+ throw new FileNotFoundException(SPException::ERROR, $msg);
}
return $templateFile;
@@ -255,7 +255,7 @@ class Template
if (!array_key_exists($name, $this->vars)) {
debugLog(sprintf(__('No es posible obtener la variable "%s"'), $name));
- throw new InvalidArgumentException(SPException::SP_ERROR, sprintf(__('No es posible obtener la variable "%s"'), $name));
+ throw new InvalidArgumentException(SPException::ERROR, sprintf(__('No es posible obtener la variable "%s"'), $name));
}
return $this->vars[$name];
@@ -300,7 +300,7 @@ class Template
if (!array_key_exists($name, $this->vars)) {
debugLog(sprintf(__('No es posible destruir la variable "%s"'), $name));
- throw new InvalidArgumentException(SPException::SP_ERROR, sprintf(__('No es posible destruir la variable "%s"'), $name));
+ throw new InvalidArgumentException(SPException::ERROR, sprintf(__('No es posible destruir la variable "%s"'), $name));
}
unset($this->vars[$name]);
@@ -317,7 +317,7 @@ class Template
public function render()
{
if (count($this->files) === 0) {
- throw new FileNotFoundException(SPException::SP_ERROR, __('La plantilla no contiene archivos'));
+ throw new FileNotFoundException(SPException::ERROR, __('La plantilla no contiene archivos'));
}
extract($this->vars, EXTR_SKIP);
diff --git a/lib/SP/Providers/Auth/Auth.php b/lib/SP/Providers/Auth/Auth.php
index b6ea4db7..1460f170 100644
--- a/lib/SP/Providers/Auth/Auth.php
+++ b/lib/SP/Providers/Auth/Auth.php
@@ -24,6 +24,9 @@
namespace SP\Providers\Auth;
+use SP\Config\ConfigData;
+use SP\Core\Exceptions\SPException;
+use SP\DataModel\UserLoginData;
use SP\Providers\Auth\Browser\Browser;
use SP\Providers\Auth\Browser\BrowserAuthData;
use SP\Providers\Auth\Database\Database;
@@ -31,9 +34,6 @@ use SP\Providers\Auth\Database\DatabaseAuthData;
use SP\Providers\Auth\Ldap\LdapAuthData;
use SP\Providers\Auth\Ldap\LdapMsAds;
use SP\Providers\Auth\Ldap\LdapStd;
-use SP\Config\ConfigData;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserLoginData;
defined('APP_ROOT') || die();
@@ -91,11 +91,11 @@ class Auth
protected function registerAuth($auth)
{
if (array_key_exists($auth, $this->auths)) {
- throw new SPException(SPException::SP_ERROR, __u('Método ya inicializado'), __FUNCTION__);
+ throw new SPException(__u('Método ya inicializado'), SPException::ERROR, __FUNCTION__);
}
if (!method_exists($this, $auth)) {
- throw new SPException(SPException::SP_ERROR, __u('Método no disponible'), __FUNCTION__);
+ throw new SPException(__u('Método no disponible'), SPException::ERROR, __FUNCTION__);
}
$this->auths[$auth] = $auth;
@@ -156,6 +156,8 @@ class Auth
* se ejecuta el proceso para actualizar la clave.
*
* @return DatabaseAuthData
+ * @throws \ReflectionException
+ * @throws \SP\Core\Dic\ContainerException
*/
public function authDatabase()
{
diff --git a/lib/SP/Providers/Auth/Database/Database.php b/lib/SP/Providers/Auth/Database/Database.php
index 477083d6..c90f3802 100644
--- a/lib/SP/Providers/Auth/Database/Database.php
+++ b/lib/SP/Providers/Auth/Database/Database.php
@@ -24,15 +24,10 @@
namespace SP\Providers\Auth\Database;
-use SP\Providers\Auth\AuthInterface;
use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\SPException;
-use SP\Core\Traits\InjectableTrait;
-use SP\DataModel\UserData;
use SP\DataModel\UserLoginData;
-use SP\Log\Log;
-use SP\Mgmt\Users\UserMigrate;
-use SP\Repositories\User\UserRepository;
+use SP\Providers\Auth\AuthInterface;
use SP\Services\User\UserPassService;
use SP\Services\User\UserService;
@@ -55,6 +50,8 @@ class Database implements AuthInterface
*
* @param UserLoginData $userLoginData Datos del usuario
* @return DatabaseAuthData
+ * @throws \SP\Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
public function authenticate(UserLoginData $userLoginData)
{
@@ -84,6 +81,8 @@ class Database implements AuthInterface
* se ejecuta el proceso para actualizar la clave.
*
* @return bool
+ * @throws \SP\Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
protected function authUser()
{
@@ -112,7 +111,6 @@ class Database implements AuthInterface
/**
* @return bool
- * @throws SPException
*/
protected function checkMigrateUser()
{
diff --git a/lib/SP/Providers/Auth/Ldap/LdapBase.php b/lib/SP/Providers/Auth/Ldap/LdapBase.php
index 8a894425..60356b8c 100644
--- a/lib/SP/Providers/Auth/Ldap/LdapBase.php
+++ b/lib/SP/Providers/Auth/Ldap/LdapBase.php
@@ -24,7 +24,6 @@
namespace SP\Providers\Auth\Ldap;
-use SP\Providers\Auth\AuthInterface;
use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Core\Exceptions\SPException;
@@ -32,6 +31,7 @@ use SP\Core\Messages\LogMessage;
use SP\Core\Traits\InjectableTrait;
use SP\DataModel\UserLoginData;
use SP\Log\Log;
+use SP\Providers\Auth\AuthInterface;
/**
* Class LdapBase
@@ -205,7 +205,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP ERROR', $this->ldapError());
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription(), $this->LogMessage->getDetails());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR, $this->LogMessage->getDetails());
}
@ldap_set_option($this->ldapHandler, LDAP_OPT_NETWORK_TIMEOUT, 10);
@@ -253,7 +253,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP DN', $dn);
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, __($this->LogMessage->getDescription()));
+ throw new SPException(__($this->LogMessage->getDescription()), SPException::ERROR);
}
return true;
@@ -276,7 +276,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP FILTER', $this->getGroupDnFilter());
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
return $searchResults;
@@ -597,7 +597,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP FILTER', $this->getUserDnFilter());
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
return $searchResults;
@@ -631,7 +631,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP FILTER', $filter);
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
return $searchResults[0]['dn'];
@@ -698,7 +698,7 @@ abstract class LdapBase implements LdapInterface, AuthInterface
$this->LogMessage->addDetails('LDAP FILTER', $this->getGroupDnFilter());
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
return $searchResults;
diff --git a/lib/SP/Providers/Auth/Ldap/LdapMsAds.php b/lib/SP/Providers/Auth/Ldap/LdapMsAds.php
index 9722aed0..6611e73d 100644
--- a/lib/SP/Providers/Auth/Ldap/LdapMsAds.php
+++ b/lib/SP/Providers/Auth/Ldap/LdapMsAds.php
@@ -24,7 +24,6 @@
namespace SP\Providers\Auth\Ldap;
-use SP\Config\Config;
use SP\Core\Exceptions\SPException;
use SP\Log\Log;
@@ -139,7 +138,7 @@ class LdapMsAds extends LdapBase
$this->LogMessage->addDetails('LDAP FILTER', $filter);
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
foreach ($searchResults as $entry) {
diff --git a/lib/SP/Providers/Auth/Ldap/LdapStd.php b/lib/SP/Providers/Auth/Ldap/LdapStd.php
index d3f2ecf6..271174e9 100644
--- a/lib/SP/Providers/Auth/Ldap/LdapStd.php
+++ b/lib/SP/Providers/Auth/Ldap/LdapStd.php
@@ -24,7 +24,6 @@
namespace SP\Providers\Auth\Ldap;
-use SP\Config\Config;
use SP\Core\Exceptions\SPException;
use SP\Log\Log;
@@ -113,7 +112,7 @@ class LdapStd extends LdapBase
$this->LogMessage->addDetails('LDAP FILTER', $filter);
$this->writeLog();
- throw new SPException(SPException::SP_ERROR, $this->LogMessage->getDescription());
+ throw new SPException($this->LogMessage->getDescription(), SPException::ERROR);
}
$this->LogMessage->addDescription(__('Usuario verificado en grupo', false));
diff --git a/lib/SP/Repositories/Account/AccountFileRepository.php b/lib/SP/Repositories/Account/AccountFileRepository.php
index 22d7b817..f9f80699 100644
--- a/lib/SP/Repositories/Account/AccountFileRepository.php
+++ b/lib/SP/Repositories/Account/AccountFileRepository.php
@@ -28,13 +28,11 @@ use SP\Core\Exceptions\SPException;
use SP\DataModel\FileData;
use SP\DataModel\FileExtData;
use SP\DataModel\ItemSearchData;
-use SP\Mgmt\Files\FileUtil;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
use SP\Repositories\RepositoryItemTrait;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
-use SP\Util\ImageUtil;
/**
* Class AccountFileRepository
@@ -291,7 +289,7 @@ class AccountFileRepository extends Repository implements RepositoryItemInterfac
DbWrapper::getQuery($Data, $this->db);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __u('Archivo no encontrado'));
+ throw new SPException(__u('Archivo no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Repositories/Account/AccountHistoryRepository.php b/lib/SP/Repositories/Account/AccountHistoryRepository.php
index 94c6cddf..d9cda59a 100644
--- a/lib/SP/Repositories/Account/AccountHistoryRepository.php
+++ b/lib/SP/Repositories/Account/AccountHistoryRepository.php
@@ -25,7 +25,6 @@
namespace SP\Repositories\Account;
use SP\Account\AccountUtil;
-use SP\Config\ConfigDB;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
use SP\DataModel\AccountHistoryData;
@@ -286,7 +285,7 @@ class AccountHistoryRepository extends Repository implements RepositoryItemInter
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __u('No se pudieron obtener los datos de la cuenta'));
+ throw new SPException(__u('No se pudieron obtener los datos de la cuenta'), SPException::CRITICAL);
}
return $queryRes;
diff --git a/lib/SP/Repositories/Account/AccountRepository.php b/lib/SP/Repositories/Account/AccountRepository.php
index 03aecb3c..d8f40e3a 100644
--- a/lib/SP/Repositories/Account/AccountRepository.php
+++ b/lib/SP/Repositories/Account/AccountRepository.php
@@ -353,11 +353,11 @@ class AccountRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_CRITICAL, __u('No se pudieron obtener los datos de la cuenta'));
+ throw new SPException(__u('No se pudieron obtener los datos de la cuenta'), SPException::CRITICAL);
}
if (is_array($queryRes) && count($queryRes) === 0) {
- throw new SPException(SPException::SP_CRITICAL, __u('La cuenta no existe'));
+ throw new SPException(__u('La cuenta no existe'), SPException::CRITICAL);
}
return $queryRes;
@@ -508,11 +508,11 @@ class AccountRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('No se pudieron obtener los datos de la cuenta'));
+ throw new SPException(__u('No se pudieron obtener los datos de la cuenta'), SPException::ERROR);
}
if (is_array($queryRes) && count($queryRes) === 0) {
- throw new SPException(SPException::SP_ERROR, __u('La cuenta no existe'));
+ throw new SPException(__u('La cuenta no existe'), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php
index e5f6d97d..cacb8d0d 100644
--- a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php
+++ b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php
@@ -204,7 +204,7 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('La autorización ya existe'));
+ throw new SPException(__u('La autorización ya existe'), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -287,7 +287,7 @@ class AuthTokenRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('La autorización ya existe'));
+ throw new SPException(__u('La autorización ya existe'), SPException::WARNING);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/Category/CategoryRepository.php b/lib/SP/Repositories/Category/CategoryRepository.php
index eccb5644..86c478af 100644
--- a/lib/SP/Repositories/Category/CategoryRepository.php
+++ b/lib/SP/Repositories/Category/CategoryRepository.php
@@ -55,7 +55,7 @@ class CategoryRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('Categoría duplicada'));
+ throw new SPException(__u('Categoría duplicada'), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -110,7 +110,7 @@ class CategoryRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('Nombre de categoría duplicado'));
+ throw new SPException(__u('Nombre de categoría duplicado'), SPException::WARNING);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/Client/ClientRepository.php b/lib/SP/Repositories/Client/ClientRepository.php
index 768ca076..b2b821d7 100644
--- a/lib/SP/Repositories/Client/ClientRepository.php
+++ b/lib/SP/Repositories/Client/ClientRepository.php
@@ -24,7 +24,6 @@
namespace SP\Repositories\Client;
-use SP\Account\AccountUtil;
use SP\Core\Exceptions\SPException;
use SP\DataModel\ClientData;
use SP\DataModel\ItemData;
@@ -55,7 +54,7 @@ class ClientRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('Cliente duplicado'));
+ throw new SPException(__u('Cliente duplicado'), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -112,7 +111,7 @@ class ClientRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_WARNING, __u('Cliente duplicado'));
+ throw new SPException(__u('Cliente duplicado'), SPException::WARNING);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php b/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php
index 37334ef1..56a8b1cc 100644
--- a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php
+++ b/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php
@@ -219,7 +219,7 @@ class CustomFieldDefRepository extends Repository implements RepositoryItemInter
public function delete($id)
{
if ($this->deleteItemsDataForDefinition($id) === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al eliminar el campo personalizado'));
+ throw new SPException(__u('Error al eliminar el campo personalizado'), SPException::ERROR);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/CustomField/CustomFieldRepository.php b/lib/SP/Repositories/CustomField/CustomFieldRepository.php
index 2e13e04b..24aeab13 100644
--- a/lib/SP/Repositories/CustomField/CustomFieldRepository.php
+++ b/lib/SP/Repositories/CustomField/CustomFieldRepository.php
@@ -114,7 +114,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac
$securedKey = Crypt::makeSecuredKey($sessionKey);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __u('Error interno'));
+ throw new QueryException(SPException::ERROR, __u('Error interno'));
}
$query = /** @lang SQL */
@@ -194,7 +194,7 @@ class CustomFieldRepository extends Repository implements RepositoryItemInterfac
$securedKey = Crypt::makeSecuredKey($sessionKey);
if (strlen($securedKey) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __u('Error interno'));
+ throw new QueryException(SPException::ERROR, __u('Error interno'));
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/NoSuchItemException.php b/lib/SP/Repositories/NoSuchItemException.php
new file mode 100644
index 00000000..b0c1f621
--- /dev/null
+++ b/lib/SP/Repositories/NoSuchItemException.php
@@ -0,0 +1,38 @@
+.
+ */
+
+namespace SP\Repositories;
+
+
+use SP\Core\Exceptions\SPException;
+
+/**
+ * Class NoSuchItemException
+ *
+ * @package SP\Repositories
+ */
+class NoSuchItemException extends SPException
+{
+
+}
\ No newline at end of file
diff --git a/lib/SP/Repositories/Plugin/PluginRepository.php b/lib/SP/Repositories/Plugin/PluginRepository.php
index d7dd9afa..aa22d9f7 100644
--- a/lib/SP/Repositories/Plugin/PluginRepository.php
+++ b/lib/SP/Repositories/Plugin/PluginRepository.php
@@ -207,7 +207,7 @@ class PluginRepository extends Repository implements RepositoryItemInterface
DbWrapper::getQuery($Data, $this->db);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __u('Plugin no encontrado'));
+ throw new SPException(__u('Plugin no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
index 5cf933a0..a24ab888 100644
--- a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
+++ b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
@@ -242,7 +242,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Enlace ya creado'));
+ throw new SPException(__u('Enlace ya creado'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -435,11 +435,11 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener enlace'));
+ throw new SPException(__u('Error al obtener enlace'), SPException::ERROR);
}
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_ERROR, __u('El enlace no existe'));
+ throw new SPException(__u('El enlace no existe'), SPException::ERROR);
}
return $queryRes;
@@ -484,11 +484,11 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener enlace'));
+ throw new SPException(__u('Error al obtener enlace'), SPException::ERROR);
}
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_ERROR, __u('El enlace no existe'));
+ throw new SPException(__u('El enlace no existe'), SPException::ERROR);
}
return $queryRes;
@@ -514,7 +514,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener enlace'));
+ throw new SPException(__u('Error al obtener enlace'), SPException::ERROR);
}
return $queryRes;
diff --git a/lib/SP/Repositories/Tag/TagRepository.php b/lib/SP/Repositories/Tag/TagRepository.php
index 65f34640..c5a60269 100644
--- a/lib/SP/Repositories/Tag/TagRepository.php
+++ b/lib/SP/Repositories/Tag/TagRepository.php
@@ -55,7 +55,7 @@ class TagRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Etiqueta duplicada'));
+ throw new SPException(__u('Etiqueta duplicada'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -105,7 +105,7 @@ class TagRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Etiqueta duplicada'));
+ throw new SPException(__u('Etiqueta duplicada'), SPException::INFO);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/User/UserRepository.php b/lib/SP/Repositories/User/UserRepository.php
index 72f50181..730cc468 100644
--- a/lib/SP/Repositories/User/UserRepository.php
+++ b/lib/SP/Repositories/User/UserRepository.php
@@ -25,12 +25,11 @@
namespace SP\Repositories\User;
use SP\Core\Acl\Acl;
-use SP\Core\Crypt\Hash;
use SP\Core\Exceptions\SPException;
use SP\DataModel\ItemSearchData;
use SP\DataModel\UserData;
-use SP\DataModel\UserLoginData;
use SP\Log\Log;
+use SP\Repositories\NoSuchItemException;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
use SP\Repositories\RepositoryItemTrait;
@@ -59,7 +58,7 @@ class UserRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Login/email de usuario duplicados'));
+ throw new SPException(__u('Login/email de usuario duplicados'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -187,7 +186,7 @@ class UserRepository extends Repository implements RepositoryItemInterface
DbWrapper::getQuery($Data, $this->db);
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __u('Usuario no encontrado'));
+ throw new SPException(__u('Usuario no encontrado'), SPException::INFO);
}
return $this;
@@ -240,7 +239,7 @@ class UserRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener los datos del usuario'));
+ throw new SPException(__u('Error al obtener los datos del usuario'), SPException::ERROR);
}
return $queryRes;
@@ -446,7 +445,7 @@ class UserRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Login/email de usuario duplicados'));
+ throw new SPException(__u('Login/email de usuario duplicados'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -564,7 +563,11 @@ class UserRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error al obtener los datos del usuario'));
+ throw new SPException(__u('Error al obtener los datos del usuario'), SPException::ERROR);
+ }
+
+ if ($Data->getQueryNumRows() === 0) {
+ throw new NoSuchItemException(__u('El usuario no existe'));
}
return $queryRes;
diff --git a/lib/SP/Repositories/UserGroup/UserGroupRepository.php b/lib/SP/Repositories/UserGroup/UserGroupRepository.php
index a954061d..745bad97 100644
--- a/lib/SP/Repositories/UserGroup/UserGroupRepository.php
+++ b/lib/SP/Repositories/UserGroup/UserGroupRepository.php
@@ -26,8 +26,8 @@ namespace SP\Repositories\UserGroup;
use SP\Core\Acl\Acl;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\UserGroupData;
use SP\DataModel\ItemSearchData;
+use SP\DataModel\UserGroupData;
use SP\Log\Log;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
@@ -54,7 +54,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
public function delete($id)
{
if ($this->checkInUse($id)) {
- throw new SPException(SPException::SP_WARNING, __u('Grupo en uso'));
+ throw new SPException(__u('Grupo en uso'), SPException::WARNING);
}
$query = /** @lang SQL */
@@ -272,7 +272,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Nombre de grupo duplicado'));
+ throw new SPException(__u('Nombre de grupo duplicado'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -322,7 +322,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Nombre de grupo duplicado'));
+ throw new SPException(__u('Nombre de grupo duplicado'), SPException::INFO);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Repositories/UserPassRecover/UserPassRecoverRepository.php b/lib/SP/Repositories/UserPassRecover/UserPassRecoverRepository.php
index 63267e7e..070eaade 100644
--- a/lib/SP/Repositories/UserPassRecover/UserPassRecoverRepository.php
+++ b/lib/SP/Repositories/UserPassRecover/UserPassRecoverRepository.php
@@ -119,11 +119,11 @@ class UserPassRecoverRepository extends Repository
$queryRes = DbWrapper::getResults($Data);
if ($queryRes === false) {
- throw new SPException(SPException::SP_ERROR, __u('Error en comprobación de hash'));
+ throw new SPException(__u('Error en comprobación de hash'), SPException::ERROR);
}
if ($Data->getQueryNumRows() === 0) {
- throw new SPException(SPException::SP_INFO, __u('Hash inválido o expirado'));
+ throw new SPException(__u('Hash inválido o expirado'), SPException::INFO);
}
return $queryRes;
diff --git a/lib/SP/Repositories/UserProfile/UserProfileRepository.php b/lib/SP/Repositories/UserProfile/UserProfileRepository.php
index 25edfdf0..e950897f 100644
--- a/lib/SP/Repositories/UserProfile/UserProfileRepository.php
+++ b/lib/SP/Repositories/UserProfile/UserProfileRepository.php
@@ -27,8 +27,8 @@ namespace SP\Repositories\UserProfile;
use SP\Core\Acl\Acl;
use SP\Core\Exceptions\SPException;
use SP\DataModel\ItemSearchData;
-use SP\DataModel\UserProfileData;
use SP\DataModel\ProfileData;
+use SP\DataModel\UserProfileData;
use SP\Log\Log;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
@@ -76,7 +76,7 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac
public function delete($id)
{
if ($this->checkInUse($id)) {
- throw new SPException(SPException::SP_INFO, __u('Perfil en uso'));
+ throw new SPException(__u('Perfil en uso'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -239,7 +239,7 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac
public function create($itemData)
{
if ($this->checkDuplicatedOnAdd($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Nombre de perfil duplicado'));
+ throw new SPException(__u('Nombre de perfil duplicado'), SPException::INFO);
}
$query = /** @lang SQL */
@@ -294,7 +294,7 @@ class UserProfileRepository extends Repository implements RepositoryItemInterfac
public function update($itemData)
{
if ($this->checkDuplicatedOnUpdate($itemData)) {
- throw new SPException(SPException::SP_INFO, __u('Nombre de perfil duplicado'));
+ throw new SPException(__u('Nombre de perfil duplicado'), SPException::INFO);
}
$query = /** @lang SQL */
diff --git a/lib/SP/Services/Account/AccountService.php b/lib/SP/Services/Account/AccountService.php
index 982ea2d5..7c7bea5c 100644
--- a/lib/SP/Services/Account/AccountService.php
+++ b/lib/SP/Services/Account/AccountService.php
@@ -31,6 +31,7 @@ use SP\Account\AccountUtil;
use SP\Core\Acl\Acl;
use SP\Core\Acl\ActionsInterface;
use SP\Core\Crypt\Crypt;
+use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
use SP\Core\Session\Session;
@@ -43,7 +44,6 @@ use SP\Repositories\Account\AccountRepository;
use SP\Repositories\Account\AccountToTagRepository;
use SP\Repositories\Account\AccountToUserGroupRepository;
use SP\Repositories\Account\AccountToUserRepository;
-use SP\Core\Crypt\Session as CryptSession;
use SP\Services\Config\ConfigService;
use SP\Services\ServiceItemTrait;
@@ -224,12 +224,12 @@ class AccountService implements AccountServiceInterface
$out['pass'] = Crypt::encrypt($pass, $out['key'], $masterPass);
if (strlen($pass) > 1000 || strlen($out['key']) > 1000) {
- throw new QueryException(SPException::SP_ERROR, __u('Error interno'));
+ throw new QueryException(SPException::ERROR, __u('Error interno'));
}
return $out;
} catch (CryptoException $e) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno'));
+ throw new SPException(__u('Error interno'), SPException::ERROR);
}
}
diff --git a/lib/SP/Services/Auth/LoginService.php b/lib/SP/Services/Auth/LoginService.php
index e4422569..ecf9f152 100644
--- a/lib/SP/Services/Auth/LoginService.php
+++ b/lib/SP/Services/Auth/LoginService.php
@@ -28,16 +28,9 @@ defined('APP_ROOT') || die();
use Defuse\Crypto\Exception\BadFormatException;
use Defuse\Crypto\Exception\CryptoException;
-use SP\Providers\Auth\Auth;
-use SP\Providers\Auth\AuthResult;
-use SP\Providers\Auth\AuthUtil;
-use SP\Providers\Auth\Browser\BrowserAuthData;
-use SP\Providers\Auth\Database\DatabaseAuthData;
-use SP\Providers\Auth\Ldap\LdapAuthData;
use SP\Bootstrap;
use SP\Config\Config;
use SP\Core\Events\EventDispatcher;
-use SP\Services\Auth\AuthException;
use SP\Core\Exceptions\SPException;
use SP\Core\Language;
use SP\Core\Messages\LogMessage;
@@ -52,6 +45,12 @@ use SP\Http\JsonResponse;
use SP\Http\Request;
use SP\Log\Log;
use SP\Mgmt\Tracks\Track;
+use SP\Providers\Auth\Auth;
+use SP\Providers\Auth\AuthResult;
+use SP\Providers\Auth\AuthUtil;
+use SP\Providers\Auth\Browser\BrowserAuthData;
+use SP\Providers\Auth\Database\DatabaseAuthData;
+use SP\Providers\Auth\Ldap\LdapAuthData;
use SP\Services\Service;
use SP\Services\User\UserLoginRequest;
use SP\Services\User\UserPassService;
@@ -131,6 +130,7 @@ class LoginService
* @param Theme $theme
* @param EventDispatcher $eventDispatcher
* @throws \SP\Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
public function __construct(Config $config, Session $session, Theme $theme, EventDispatcher $eventDispatcher)
{
@@ -182,7 +182,7 @@ class LoginService
} else {
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __u('Login incorrecto'), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException(__u('Login incorrecto'), SPException::INFO, null, self::STATUS_INVALID_LOGIN);
}
$this->checkUser();
@@ -233,7 +233,7 @@ class LoginService
$this->LogMessage->addDescription($e->getMessage());
$this->LogMessage->addDescription($e->getHint());
- throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException(__u('Error interno'), SPException::ERROR, null, Service::STATUS_INTERNAL_ERROR);
}
if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) {
@@ -243,7 +243,7 @@ class LoginService
$this->LogMessage->addDescription(sprintf(__('Intentos excedidos (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS));
- throw new AuthException(SPException::SP_INFO, __u('Intentos excedidos'), '', self::STATUS_MAX_ATTEMPTS_EXCEEDED);
+ throw new AuthException(__u('Intentos excedidos'), SPException::INFO, null, self::STATUS_MAX_ATTEMPTS_EXCEEDED);
}
}
@@ -261,7 +261,7 @@ class LoginService
Track::getItem($TrackData)->add();
} catch (SPException $e) {
- throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException(__u('Error interno'), SPException::ERROR, null, Service::STATUS_INTERNAL_ERROR);
}
}
@@ -283,7 +283,7 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __u('Usuario deshabilitado'), '', self::STATUS_USER_DISABLED);
+ throw new AuthException(__u('Usuario deshabilitado'), SPException::INFO, null, self::STATUS_USER_DISABLED);
}
// Comprobar si se ha forzado un cambio de clave
@@ -327,7 +327,7 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS);
+ throw new AuthException(__u('Clave maestra incorrecta'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS);
}
$this->LogMessage->addDescription(__u('Clave maestra actualizada'));
@@ -337,32 +337,32 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS);
+ throw new AuthException(__u('Clave maestra incorrecta'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS);
}
$this->LogMessage->addDescription(__u('Clave maestra actualizada'));
} else {
switch ($userPassService->loadUserMPass($this->userLoginData)->getStatus()) {
case UserPassService::MPASS_CHECKOLD:
- throw new AuthException(SPException::SP_INFO, __u('Es necesaria su clave anterior'), '', self::STATUS_NEED_OLD_PASS);
+ throw new AuthException(__u('Es necesaria su clave anterior'), SPException::INFO, null, self::STATUS_NEED_OLD_PASS);
break;
case UserPassService::MPASS_NOTSET:
case UserPassService::MPASS_CHANGED:
case UserPassService::MPASS_WRONG:
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, __u('La clave maestra no ha sido guardada o es incorrecta'), '', self::STATUS_INVALID_MASTER_PASS);
+ throw new AuthException(__u('La clave maestra no ha sido guardada o es incorrecta'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS);
break;
}
}
} catch (BadFormatException $e) {
$this->LogMessage->addDescription(__u('Clave maestra incorrecta'));
- throw new AuthException(SPException::SP_INFO, __u('Clave maestra incorrecta'), '', self::STATUS_INVALID_MASTER_PASS);
+ throw new AuthException(__u('Clave maestra incorrecta'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS);
} catch (CryptoException $e) {
$this->LogMessage->addDescription(__u('Error interno'));
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), $e->getMessage(), Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, $e->getMessage(), Service::STATUS_INTERNAL_ERROR);
}
}
@@ -370,6 +370,7 @@ class LoginService
* Cargar la sesión del usuario
*
* @throws \SP\Core\Exceptions\SPException
+ * @throws \SP\Core\Dic\ContainerException
*/
protected function setUserSession()
{
@@ -435,19 +436,19 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, self::STATUS_INVALID_LOGIN);
}
if ($AuthData->getStatusCode() === 701) {
$this->LogMessage->addDescription(__u('Cuenta expirada'));
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, self::STATUS_USER_DISABLED);
}
if ($AuthData->getStatusCode() === 702) {
$this->LogMessage->addDescription(__u('El usuario no tiene grupos asociados'));
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_USER_DISABLED);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, self::STATUS_USER_DISABLED);
}
if ($AuthData->isAuthGranted() === false) {
@@ -456,7 +457,7 @@ class LoginService
$this->LogMessage->addDescription(__u('Error interno'));
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, Service::STATUS_INTERNAL_ERROR);
}
$this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__);
@@ -482,7 +483,7 @@ class LoginService
} catch (SPException $e) {
$this->LogMessage->addDescription($e->getMessage());
- throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException(__u('Error interno'), SPException::ERROR, null, Service::STATUS_INTERNAL_ERROR);
}
return true;
@@ -509,7 +510,7 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, self::STATUS_INVALID_LOGIN);
}
if ($AuthData->getAuthenticated() === 1) {
@@ -541,7 +542,7 @@ class LoginService
$this->addTracking();
- throw new AuthException(SPException::SP_INFO, $this->LogMessage->getDescription(), '', self::STATUS_INVALID_LOGIN);
+ throw new AuthException($this->LogMessage->getDescription(), SPException::INFO, null, self::STATUS_INVALID_LOGIN);
}
$this->LogMessage->addDetails(__u('Tipo'), __FUNCTION__);
@@ -561,7 +562,7 @@ class LoginService
$this->userService->createOnLogin($userLoginRequest);
}
} catch (SPException $e) {
- throw new AuthException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR);
+ throw new AuthException(__u('Error interno'), SPException::ERROR, null, Service::STATUS_INTERNAL_ERROR);
}
$this->LogMessage->addDetails(__u('Usuario'), $this->userLoginData->getLoginUser());
diff --git a/lib/SP/Services/AuthToken/AuthTokenService.php b/lib/SP/Services/AuthToken/AuthTokenService.php
index 1fd79d94..3702dcba 100644
--- a/lib/SP/Services/AuthToken/AuthTokenService.php
+++ b/lib/SP/Services/AuthToken/AuthTokenService.php
@@ -26,6 +26,7 @@ namespace SP\Services\AuthToken;
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\Session\Session;
@@ -34,7 +35,6 @@ use SP\DataModel\AuthTokenData;
use SP\DataModel\ItemSearchData;
use SP\Repositories\AuthToken\AuthTokenRepository;
use SP\Services\ServiceItemTrait;
-use SP\Core\Crypt\Session as CryptSession;
use SP\Util\Util;
/**
@@ -104,7 +104,7 @@ class AuthTokenService
public function delete($id)
{
if ($this->authTokenRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Token no encontrado'));
+ throw new SPException(__u('Token no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/Category/CategoryService.php b/lib/SP/Services/Category/CategoryService.php
index eeec663a..1c756e28 100644
--- a/lib/SP/Services/Category/CategoryService.php
+++ b/lib/SP/Services/Category/CategoryService.php
@@ -86,7 +86,7 @@ class CategoryService
public function delete($id)
{
if ($this->categoryRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Categoría no encontrada'));
+ throw new SPException(__u('Categoría no encontrada'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/Client/ClientService.php b/lib/SP/Services/Client/ClientService.php
index b3125d3b..5981de6e 100644
--- a/lib/SP/Services/Client/ClientService.php
+++ b/lib/SP/Services/Client/ClientService.php
@@ -97,7 +97,7 @@ class ClientService
public function delete($id)
{
if ($this->clientRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Cliente no encontrado'));
+ throw new SPException(__u('Cliente no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/Config/ConfigService.php b/lib/SP/Services/Config/ConfigService.php
index fa3c9160..3ff4935e 100644
--- a/lib/SP/Services/Config/ConfigService.php
+++ b/lib/SP/Services/Config/ConfigService.php
@@ -75,7 +75,7 @@ class ConfigService
$query = $this->configRepository->getByParam($param);
if (empty($query)) {
- throw new ParameterNotFoundException(SPException::SP_ERROR, sprintf(__('Parámetro no encontrado (%s)'), $param));
+ throw new ParameterNotFoundException(SPException::ERROR, sprintf(__('Parámetro no encontrado (%s)'), $param));
}
return $query->value;
}
diff --git a/lib/SP/Services/PublicLink/PublicLinkService.php b/lib/SP/Services/PublicLink/PublicLinkService.php
index 4fc2c497..36973a12 100644
--- a/lib/SP/Services/PublicLink/PublicLinkService.php
+++ b/lib/SP/Services/PublicLink/PublicLinkService.php
@@ -27,6 +27,7 @@ namespace SP\Services\PublicLink;
use SP\Bootstrap;
use SP\Config\Config;
use SP\Core\Crypt\Crypt;
+use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Crypt\Vault;
use SP\Core\Exceptions\SPException;
use SP\Core\Session\Session;
@@ -37,7 +38,6 @@ use SP\Http\Request;
use SP\Repositories\Account\AccountRepository;
use SP\Repositories\PublicLink\PublicLinkRepository;
use SP\Services\ServiceItemTrait;
-use SP\Core\Crypt\Session as CryptSession;
use SP\Util\Checks;
use SP\Util\HttpUtil;
use SP\Util\Util;
@@ -217,7 +217,7 @@ class PublicLinkService
public function delete($id)
{
if ($this->publicLinkRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Enlace no encontrado'));
+ throw new SPException(__u('Enlace no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/Tag/TagService.php b/lib/SP/Services/Tag/TagService.php
index 1743ce1a..ebfc6367 100644
--- a/lib/SP/Services/Tag/TagService.php
+++ b/lib/SP/Services/Tag/TagService.php
@@ -90,7 +90,7 @@ class TagService
public function delete($id)
{
if ($this->tagRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Etiqueta no encontrada'));
+ throw new SPException(__u('Etiqueta no encontrada'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/User/UpdatedMasterPassException.php b/lib/SP/Services/User/UpdatedMasterPassException.php
index 036efd0f..086489c1 100644
--- a/lib/SP/Services/User/UpdatedMasterPassException.php
+++ b/lib/SP/Services/User/UpdatedMasterPassException.php
@@ -42,7 +42,7 @@ class UpdatedMasterPassException extends SPException
*/
public function __construct($type, $code = 0, \Exception $previous = null)
{
- parent::__construct($type, __u('Clave maestra actualizada'), __u('Reinicie la sesión para cambiarla'), $code, $previous);
+ parent::__construct(__u('Clave maestra actualizada'), $type, __u('Reinicie la sesión para cambiarla'), $code, $previous);
}
}
\ No newline at end of file
diff --git a/lib/SP/Services/User/UserPassService.php b/lib/SP/Services/User/UserPassService.php
index fea296ca..770131f2 100644
--- a/lib/SP/Services/User/UserPassService.php
+++ b/lib/SP/Services/User/UserPassService.php
@@ -29,12 +29,12 @@ use SP\Config\Config;
use SP\Config\ConfigData;
use SP\Core\Crypt\Crypt;
use SP\Core\Crypt\Hash;
+use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Exceptions\SPException;
use SP\Core\Traits\InjectableTrait;
+use SP\Core\Upgrade\Crypt as CryptUpgrade;
use SP\Core\Upgrade\User as UpgradeUser;
use SP\DataModel\UserLoginData;
-use SP\Core\Upgrade\Crypt as CryptUpgrade;
-use SP\Core\Crypt\Session as CryptSession;
use SP\Repositories\User\UserRepository;
use SP\Services\Config\ConfigService;
use SP\Services\Service;
@@ -222,7 +222,7 @@ class UserPassService
if (!empty($cryptMPass)) {
if (strlen($securedKey) > 1000 || strlen($cryptMPass) > 1000) {
- throw new SPException(SPException::SP_ERROR, __u('Error interno'), '', Service::STATUS_INTERNAL_ERROR);
+ throw new SPException(__u('Error interno'), SPException::ERROR, '', Service::STATUS_INTERNAL_ERROR);
}
$this->userRepository->updateMasterPassById($userData->getId(), $cryptMPass, $securedKey);
diff --git a/lib/SP/Services/User/UserService.php b/lib/SP/Services/User/UserService.php
index 3b061ecf..ea87290f 100644
--- a/lib/SP/Services/User/UserService.php
+++ b/lib/SP/Services/User/UserService.php
@@ -53,6 +53,7 @@ class UserService
* UserService constructor.
*
* @throws \SP\Core\Dic\ContainerException
+ * @throws \ReflectionException
*/
public function __construct()
{
diff --git a/lib/SP/Services/UserGroup/UserGroupService.php b/lib/SP/Services/UserGroup/UserGroupService.php
index 6b58c0f2..0dee73ee 100644
--- a/lib/SP/Services/UserGroup/UserGroupService.php
+++ b/lib/SP/Services/UserGroup/UserGroupService.php
@@ -91,7 +91,7 @@ class UserGroupService
public function delete($id)
{
if ($this->userGroupRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Grupo no encontrado'));
+ throw new SPException(__u('Grupo no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Services/UserProfile/UserProfileService.php b/lib/SP/Services/UserProfile/UserProfileService.php
index a51d2c6a..dd21ebba 100644
--- a/lib/SP/Services/UserProfile/UserProfileService.php
+++ b/lib/SP/Services/UserProfile/UserProfileService.php
@@ -91,7 +91,7 @@ class UserProfileService
public function delete($id)
{
if ($this->userProfileRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Perfil no encontrado'));
+ throw new SPException(__u('Perfil no encontrado'), SPException::INFO);
}
return $this;
diff --git a/lib/SP/Storage/DBUtil.php b/lib/SP/Storage/DBUtil.php
index 283bdca1..ffb849e9 100644
--- a/lib/SP/Storage/DBUtil.php
+++ b/lib/SP/Storage/DBUtil.php
@@ -25,6 +25,7 @@
namespace SP\Storage;
+use RuntimeException;
use SP\Bootstrap;
use SP\Config\ConfigData;
use SP\Core\DiFactory;
@@ -141,8 +142,8 @@ class DBUtil
} catch (\Exception $e) {
debugLog($e->getMessage());
debugLog($e->getCode());
- }
- return false;
+ throw new RuntimeException(__u('Error en la verificación de la base de datos'));
+ }
}
}
\ No newline at end of file
diff --git a/lib/SP/Storage/Database.php b/lib/SP/Storage/Database.php
index e5197457..98a76918 100644
--- a/lib/SP/Storage/Database.php
+++ b/lib/SP/Storage/Database.php
@@ -206,7 +206,7 @@ class Database implements DatabaseInterface
debugLog('Exception: ' . $e->getMessage());
debugLog(ob_get_clean());
- throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode(), 0, $e);
+ throw new SPException($e->getMessage(), SPException::CRITICAL, $e->getCode(), 0, $e);
}
}
diff --git a/lib/SP/Storage/DbWrapper.php b/lib/SP/Storage/DbWrapper.php
index 2745bb53..8acebfee 100644
--- a/lib/SP/Storage/DbWrapper.php
+++ b/lib/SP/Storage/DbWrapper.php
@@ -107,7 +107,7 @@ class DbWrapper
if (self::$fullRowCount === true) {
$db->getFullRowCount($queryData);
}
- } catch (SPException $e) {
+ } catch (\Exception $e) {
$queryData->setQueryStatus($e->getCode());
self::logDBException($queryData->getQuery(), $e, __FUNCTION__);
@@ -194,7 +194,6 @@ class DbWrapper
* @return bool
* @throws ConstraintException
* @throws QueryException
- * @throws \SP\Core\Dic\ContainerException
*/
public static function getQuery(QueryData $queryData, DatabaseInterface $db = null)
{
@@ -205,7 +204,7 @@ class DbWrapper
}
if ($queryData->getQuery() === '') {
- throw new QueryException(SPException::SP_ERROR, $errorMessage, __u('Consulta en blanco'));
+ throw new QueryException($errorMessage, SPException::ERROR, __u('Consulta en blanco'));
}
try {
@@ -218,17 +217,17 @@ class DbWrapper
$db->doQuery($queryData);
return true;
- } catch (SPException $e) {
+ } catch (\Exception $e) {
$queryData->setQueryStatus($e->getCode());
self::logDBException($queryData->getQuery(), $e, __FUNCTION__);
switch ($e->getCode()) {
case 23000:
- throw new ConstraintException(SPException::SP_ERROR, __u('Restricción de integridad'), $e->getMessage(), $e->getCode());
+ throw new ConstraintException(__u('Restricción de integridad'), SPException::ERROR, $e->getMessage(), $e->getCode());
}
- throw new QueryException(SPException::SP_ERROR, $errorMessage, $e->getMessage(), $e->getCode());
+ throw new QueryException($errorMessage, SPException::ERROR, $e->getMessage(), $e->getCode());
}
}
diff --git a/lib/SP/Storage/MySQLHandler.php b/lib/SP/Storage/MySQLHandler.php
index 5a4db06a..10fc30c4 100644
--- a/lib/SP/Storage/MySQLHandler.php
+++ b/lib/SP/Storage/MySQLHandler.php
@@ -137,9 +137,7 @@ class MySQLHandler implements DBStorageInterface
if ($isInstalled) {
Init::initError(__('No es posible conectar con la BD'), __('Compruebe los datos de conexión'));
} else {
- throw new SPException(SPException::SP_CRITICAL,
- __('No es posible conectar con la BD', false),
- __('Compruebe los datos de conexión', false));
+ throw new SPException(__('No es posible conectar con la BD', false), SPException::CRITICAL, __('Compruebe los datos de conexión', false));
}
}
@@ -164,7 +162,7 @@ class MySQLHandler implements DBStorageInterface
__('No es posible conectar con la BD'),
'Error ' . $e->getCode() . ': ' . $e->getMessage());
} else {
- throw new SPException(SPException::SP_CRITICAL, $e->getMessage(), $e->getCode());
+ throw new SPException($e->getMessage(), SPException::CRITICAL, $e->getCode());
}
}
}
diff --git a/lib/SP/Util/Checks.php b/lib/SP/Util/Checks.php
index dd28d239..d6d28ab4 100644
--- a/lib/SP/Util/Checks.php
+++ b/lib/SP/Util/Checks.php
@@ -24,6 +24,7 @@
namespace SP\Util;
+use Klein\Klein;
use SP\Http\Request;
/**
@@ -72,7 +73,7 @@ class Checks
*/
public static function checkPhpVersion()
{
- return version_compare(PHP_VERSION, '5.6.0', '>=') && version_compare(PHP_VERSION, '7.1.0') === -1;
+ return PHP_VERSION_ID >= 50600 && version_compare(PHP_VERSION, '7.1.0') === -1;
}
/**
@@ -156,12 +157,13 @@ class Checks
/**
* Comprobar si la petición es Ajax
*
+ * @param Klein $router
* @return bool
*/
- public static function isAjax()
+ public static function isAjax(Klein $router)
{
- return Request::getRequestHeaders('X-Requested-With') === 'XMLHttpRequest'
- || Request::analyze('isAjax', false, true);
+ return $router->request()->headers()->get('X-Requested-With') === 'XMLHttpRequest'
+ || (int)$router->request()->param('isAjax') === 1;
}
/**
diff --git a/lib/SP/Util/Connection.php b/lib/SP/Util/Connection.php
index 3564447b..761aaa95 100644
--- a/lib/SP/Util/Connection.php
+++ b/lib/SP/Util/Connection.php
@@ -92,7 +92,7 @@ class Connection implements ConnectionInterface
}
if ($this->socket === false) {
- throw new SPException(SPException::SP_WARNING, $this->getSocketError());
+ throw new SPException($this->getSocketError(), SPException::WARNING);
}
stream_set_timeout($this->socket, self::SOCKET_TIMEOUT);
@@ -119,14 +119,14 @@ class Connection implements ConnectionInterface
public function send($message)
{
if (!is_resource($this->socket)) {
- throw new SPException(SPException::SP_WARNING, __('Socket no inicializado', false));
+ throw new SPException(__('Socket no inicializado', false), SPException::WARNING);
}
$nBytes = @fwrite($this->socket, $message);
// $nBytes = @socket_sendto($this->_socket, $message, strlen($message), 0, $this->_host, $this->port);
if ($nBytes === false) {
- throw new SPException(SPException::SP_WARNING, __('Error al enviar datos', false), $this->getSocketError());
+ throw new SPException(__('Error al enviar datos', false), SPException::WARNING, $this->getSocketError());
}
return $nBytes;
diff --git a/lib/SP/Util/ErrorUtil.php b/lib/SP/Util/ErrorUtil.php
index 4bd13945..1d46ce28 100644
--- a/lib/SP/Util/ErrorUtil.php
+++ b/lib/SP/Util/ErrorUtil.php
@@ -71,7 +71,7 @@ class ErrorUtil
$view->append('errors',
[
- 'type' => SPException::SP_WARNING,
+ 'type' => SPException::WARNING,
'description' => $error['txt'],
'hint' => $error['hint']
]);
@@ -130,7 +130,7 @@ class ErrorUtil
$view->append('errors',
[
- 'type' => SPException::SP_WARNING,
+ 'type' => SPException::WARNING,
'description' => $error['txt'],
'hint' => $error['hint']
]);
diff --git a/lib/SP/Util/Json.php b/lib/SP/Util/Json.php
index 35c403b7..5def9f11 100644
--- a/lib/SP/Util/Json.php
+++ b/lib/SP/Util/Json.php
@@ -80,7 +80,7 @@ class Json
$json = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);
if ($json === false) {
- throw new SPException(SPException::SP_CRITICAL, __u('Error de codificación'), json_last_error_msg());
+ throw new SPException(__u('Error de codificación'), SPException::CRITICAL, json_last_error_msg());
}
return $json;
diff --git a/lib/SP/Util/Util.php b/lib/SP/Util/Util.php
index 116bdd18..4e64cd14 100644
--- a/lib/SP/Util/Util.php
+++ b/lib/SP/Util/Util.php
@@ -238,7 +238,7 @@ class Util
if (!Checks::curlIsAvailable()) {
$Log = LogUtil::extensionNotLoaded('CURL', __FUNCTION__);
- throw new SPException(SPException::SP_WARNING, $Log->getDescription());
+ throw new SPException($Log->getDescription(), SPException::WARNING);
}
$ch = curl_init($url);
@@ -303,7 +303,7 @@ class Util
$Log->setLogLevel(Log::ERROR);
$Log->writeLog();
- throw new SPException(SPException::SP_WARNING, $LogMessgae->getDescription());
+ throw new SPException($LogMessgae->getDescription(), SPException::WARNING);
}
return $data;
diff --git a/lib/SP/Util/Wiki/DokuWikiApi.php b/lib/SP/Util/Wiki/DokuWikiApi.php
index e5b3ab5d..de73595c 100644
--- a/lib/SP/Util/Wiki/DokuWikiApi.php
+++ b/lib/SP/Util/Wiki/DokuWikiApi.php
@@ -24,11 +24,8 @@
namespace SP\Util\Wiki;
-use SP\Config\Config;
-use SP\Config\ConfigData;
use SP\Core\Exceptions\SPException;
use SP\Core\SessionFactory;
-use SP\Core\Traits\InjectableTrait;
use SP\Log\Log;
use SP\Log\LogLevel;
@@ -69,7 +66,7 @@ class DokuWikiApi extends DokuWikiApiBase
SessionFactory::setDokuWikiSession($resLogin[0]);
if ($resLogin[0] === false) {
- throw new SPException(SPException::SP_WARNING, __('Fallo de autentificación', false));
+ throw new SPException(__('Fallo de autentificación', false), SPException::WARNING);
}
}
@@ -79,7 +76,7 @@ class DokuWikiApi extends DokuWikiApiBase
throw $e;
} catch (\InvalidArgumentException $e) {
Log::writeNewLog('DokuWiki API', $e->getMessage(), LogLevel::ERROR);
- throw new SPException(SPException::SP_WARNING, $e->getMessage());
+ throw new SPException($e->getMessage(), SPException::WARNING);
}
}
diff --git a/lib/SP/Util/Wiki/DokuWikiApiBase.php b/lib/SP/Util/Wiki/DokuWikiApiBase.php
index 584a4279..e71cacb0 100644
--- a/lib/SP/Util/Wiki/DokuWikiApiBase.php
+++ b/lib/SP/Util/Wiki/DokuWikiApiBase.php
@@ -135,7 +135,7 @@ abstract class DokuWikiApiBase
$this->params = $this->xml->createElement('params');
$this->root->appendChild($this->params);
} catch (DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -162,7 +162,7 @@ abstract class DokuWikiApiBase
$xmlParam->appendChild($xmlValue);
$this->params->appendChild($xmlParam);
} catch (DOMException $e) {
- throw new SPException(SPException::SP_WARNING, $e->getMessage(), __FUNCTION__);
+ throw new SPException($e->getMessage(), SPException::WARNING, __FUNCTION__);
}
}
@@ -193,9 +193,7 @@ abstract class DokuWikiApiBase
if (count($error) > 0) {
throw new SPException(
- SPException::SP_WARNING,
- __('Error al realizar la consulta', false),
- $error['faultString']
+ __('Error al realizar la consulta', false), SPException::WARNING, $error['faultString']
);
}
}
@@ -240,7 +238,7 @@ abstract class DokuWikiApiBase
$this->apiPassword = empty($pass) ? $this->ConfigData->getDokuwikiPass() : $pass;
if (empty($this->apiUrl)) {
- throw new SPException(SPException::SP_WARNING, __('URL de conexión no establecida', false));
+ throw new SPException(__('URL de conexión no establecida', false), SPException::WARNING);
}
}
}
\ No newline at end of file
diff --git a/public/css/css.php b/public/css/css.php
deleted file mode 100644
index 45a7966a..00000000
--- a/public/css/css.php
+++ /dev/null
@@ -1,54 +0,0 @@
-.
- */
-
-use SP\Html\Minify;
-use SP\Http\Request;
-
-define('APP_ROOT', dirname(dirname(__DIR__)));
-
-require_once APP_ROOT . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Base.php';
-
-$file = Request::analyze('f');
-$base = Request::analyze('b');
-
-if (!$file) {
- $Minify = new Minify();
- $Minify->setType(Minify::FILETYPE_CSS)
- ->setBase(__DIR__)
- ->addFile('reset.min.css')
- ->addFile('jquery-ui.min.css')
- ->addFile('jquery-ui.structure.min.css')
- ->addFile('jquery.tagsinput.min.css')
- ->addFile('fonts.min.css')
- ->addFile('material-icons.min.css')
- ->addFile('toastr.min.css')
- ->addFile('magnific-popup.min.css')
- ->getMinified();
-} elseif ($file && $base) {
- $Minify = new Minify();
- $Minify->setType(Minify::FILETYPE_CSS)
- ->setBase(urldecode($base), true)
- ->addFile(urldecode($file))
- ->getMinified();
-}
\ No newline at end of file
diff --git a/public/css/fonts.css b/public/css/fonts.css
index fbb48d2d..08303774 100644
--- a/public/css/fonts.css
+++ b/public/css/fonts.css
@@ -26,10 +26,10 @@
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
- src: url("fonts/MaterialIcons-Regular.eot"); /* For IE6-8 */
+ src: url("public/css/fonts/MaterialIcons-Regular.eot"); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
- url("fonts/MaterialIcons-Regular.woff2") format('woff2'),
- url("fonts/MaterialIcons-Regular.woff") format('woff'),
- url("fonts/MaterialIcons-Regular.ttf") format('truetype');
+ url("public/css/fonts/MaterialIcons-Regular.woff2") format('woff2'),
+ url("public/css/fonts/MaterialIcons-Regular.woff") format('woff'),
+ url("public/css/fonts/MaterialIcons-Regular.ttf") format('truetype');
}
\ No newline at end of file
diff --git a/public/css/fonts.min.css b/public/css/fonts.min.css
index bf83d485..6e3d36be 100644
--- a/public/css/fonts.min.css
+++ b/public/css/fonts.min.css
@@ -1 +1 @@
-@font-face{font-family:'Material Icons';font-style:normal;font-weight:400;src:url("fonts/MaterialIcons-Regular.eot");src:local('Material Icons'),local('MaterialIcons-Regular'),url("fonts/MaterialIcons-Regular.woff2") format('woff2'),url("fonts/MaterialIcons-Regular.woff") format('woff'),url("fonts/MaterialIcons-Regular.ttf") format('truetype')}
\ No newline at end of file
+@font-face{font-family:'Material Icons';font-style:normal;font-weight:400;src:url("public/css/fonts/MaterialIcons-Regular.eot");src:local('Material Icons'),local('MaterialIcons-Regular'),url("public/css/fonts/MaterialIcons-Regular.woff2") format('woff2'),url("public/css/fonts/MaterialIcons-Regular.woff") format('woff'),url("public/css/fonts/MaterialIcons-Regular.ttf") format('truetype')}
\ No newline at end of file
diff --git a/public/js/js.php b/public/js/js.php
deleted file mode 100644
index 83f7f332..00000000
--- a/public/js/js.php
+++ /dev/null
@@ -1,72 +0,0 @@
-.
- */
-
-use SP\Html\Minify;
-use SP\Http\Request;
-
-define('APP_ROOT', dirname(dirname(__DIR__)));
-
-require APP_ROOT . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Base.php';
-
-$file = Request::analyze('f');
-$base = Request::analyze('b');
-$group = Request::analyze('g', 0);
-
-if (!$file) {
- $Minify = new Minify();
- $Minify->setType(Minify::FILETYPE_JS);
- $Minify->setBase(__DIR__);
-
- if ($group === 0) {
- $Minify->addFile('jquery-3.2.0.min.js')
- ->addFile('jquery-migrate-3.0.0.min.js')
- ->addFile('jquery.fileDownload.min.js')
- ->addFile('clipboard.min.js')
- ->addFile('selectize.min.js')
- ->addFile('selectize-plugins.min.js')
- ->addFile('zxcvbn-async.min.js')
- ->addFile('jsencrypt.min.js')
- ->addFile('spark-md5.min.js')
- ->addFile('moment.min.js')
- ->addFile('moment-timezone.min.js')
- ->addFile('toastr.min.js')
- ->addFile('jquery.magnific-popup.min.js')
- ->addFile('eventsource.min.js');
- } elseif ($group === 1) {
- // FIXME: use MIN version
- $Minify->addFile('app.js', false)
- ->addFile('app-triggers.js', false)
- ->addFile('app-actions.js', false)
- ->addFile('app-requests.js', false)
- ->addFile('app-main.js', false);
- }
-
- $Minify->getMinified();
-} elseif ($file && $base) {
- $Minify = new Minify();
- $Minify->setType(Minify::FILETYPE_JS);
- $Minify->setBase(urldecode($base), true);
- $Minify->addFile(urldecode($file));
- $Minify->getMinified();
-}
\ No newline at end of file
diff --git a/schemas/dbstructure.sql b/schemas/dbstructure.sql
index 537b5c7c..29ebb7fd 100644
--- a/schemas/dbstructure.sql
+++ b/schemas/dbstructure.sql
@@ -511,7 +511,7 @@ CREATE TABLE `User` (
`isMigrate` tinyint(1) DEFAULT '0',
`isChangePass` tinyint(1) DEFAULT '0',
`isChangedPass` tinyint(1) DEFAULT '0',
- `user_preferences` blob,
+ `preferences` blob,
PRIMARY KEY (`id`),
UNIQUE KEY `IDX_login` (`login`,`ssoLogin`),
KEY `IDX_pass` (`pass`(767)),