* [ADD] Upgrade process. Work in progress.

This commit is contained in:
nuxsmin
2018-03-19 04:01:48 +01:00
parent f4ed93a621
commit 4e5ea8ae43
23 changed files with 1108 additions and 776 deletions

View File

@@ -25,13 +25,11 @@
namespace SP\Modules\Api;
use DI\Container;
use DI\DependencyException;
use Interop\Container\Exception\NotFoundException;
use SP\Core\Context\StatelessContext;
use SP\Core\Exceptions\InitializationException;
use SP\Core\Language;
use SP\Core\ModuleBase;
use SP\Services\Config\ConfigService;
use SP\Services\Upgrade\UpgradeAppService;
use SP\Services\Upgrade\UpgradeDatabaseService;
use SP\Services\Upgrade\UpgradeUtil;
@@ -77,6 +75,7 @@ class Init extends ModuleBase
* @throws \DI\NotFoundException
* @throws \SP\Core\Exceptions\SPException
* @throws NotFoundException
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
public function initialize($controller)
{
@@ -124,20 +123,17 @@ class Init extends ModuleBase
/**
* Comprobar si es necesario actualizar componentes
*
* @throws DependencyException
* @throws NotFoundException
* @throws \SP\Services\Config\ParameterNotFoundException
* @throws InitializationException
* @throws \DI\NotFoundException
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
private function checkUpgrade()
{
$configService = $this->container->get(ConfigService::class);
$dbVersion = UpgradeUtil::fixVersionNumber($configService->getByParam('version'));
if (UpgradeDatabaseService::needsUpgrade($dbVersion) ||
UpgradeAppService::needsUpgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion()))
if ($this->configData->getUpgradeKey()
|| (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) ||
UpgradeAppService::needsUpgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion())))
) {
$this->config->generateUpgradeKey();
throw new InitializationException(__u('Es necesario actualizar'));
}
}

View File

@@ -24,8 +24,14 @@
namespace SP\Modules\Web\Controllers;
use SP\Core\Exceptions\SPException;
use SP\Http\JsonResponse;
use SP\Http\Request;
use SP\Modules\Web\Controllers\Helpers\LayoutHelper;
use SP\Modules\Web\Controllers\Traits\JsonTrait;
use SP\Services\Upgrade\UpgradeAppService;
use SP\Services\Upgrade\UpgradeDatabaseService;
use SP\Services\Upgrade\UpgradeException;
use SP\Services\Upgrade\UpgradeUtil;
/**
* Class UpgradeController
@@ -34,22 +40,55 @@ use SP\Modules\Web\Controllers\Helpers\LayoutHelper;
*/
class UpgradeController extends ControllerBase
{
use JsonTrait;
/**
* indexAction
*/
public function indexAction()
{
$layoutHelper = $this->dic->get(LayoutHelper::class);
$layoutHelper->getErrorLayout('upgrade');
$errors[] = [
'type' => SPException::WARNING,
'description' => __('La aplicación necesita actualizarse'),
'hint' => __('Consulte con el administrador')
];
$this->view->assign('errors', $errors);
$layoutHelper->getPublicLayout('index', 'upgrade');
$this->view();
}
/**
* upgradeAction
*/
public function upgradeAction()
{
if (Request::analyzeBool('chkConfirm', false) === false) {
$this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('Es necesario confirmar la actualización'));
}
if (Request::analyzeString('key') !== $this->configData->getUpgradeKey()) {
$this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('Código de seguridad incorrecto'));
}
try {
$dbVersion = $this->configData->getDatabaseVersion();
$dbVersion = empty($dbVersion) ? '0.0' : $dbVersion;
if (UpgradeDatabaseService::needsUpgrade($dbVersion)) {
$this->dic->get(UpgradeDatabaseService::class)
->upgrade($dbVersion);
}
if (UpgradeAppService::needsUpgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion()))) {
$this->dic->get(UpgradeAppService::class)
->upgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion()));
}
$this->configData->setUpgradeKey(null);
$this->config->saveConfig($this->configData, false);
$this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Aplicación actualizada correctamente'), [__u('En 5 segundos será redirigido al login')]);
} catch (UpgradeException $e) {
processException($e);
$this->returnJsonResponseException($e);
}
}
}

View File

@@ -26,8 +26,6 @@ namespace SP\Modules\Web;
use Defuse\Crypto\Exception\CryptoException;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use SP\Bootstrap;
use SP\Core\Context\ContextException;
use SP\Core\Context\ContextInterface;
@@ -40,7 +38,6 @@ use SP\Core\Language;
use SP\Core\ModuleBase;
use SP\Core\UI\Theme;
use SP\Http\Request;
use SP\Services\Config\ConfigService;
use SP\Services\Upgrade\UpgradeAppService;
use SP\Services\Upgrade\UpgradeDatabaseService;
use SP\Services\Upgrade\UpgradeUtil;
@@ -99,6 +96,7 @@ class Init extends ModuleBase
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
* @throws \SP\Core\Exceptions\SPException
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
public function initialize($controller)
{
@@ -163,6 +161,8 @@ class Init extends ModuleBase
// Checks if upgrade is needed
if ($this->checkUpgrade()) {
$this->config->generateUpgradeKey();
$this->router->response()
->redirect('index.php?r=upgrade/index')
->send();
@@ -229,18 +229,12 @@ class Init extends ModuleBase
/**
* Comprobar si es necesario actualizar componentes
*
* @throws DependencyException
* @throws NotFoundException
* @throws \SP\Services\Config\ParameterNotFoundException
*/
private function checkUpgrade()
{
$configService = $this->container->get(ConfigService::class);
$dbVersion = UpgradeUtil::fixVersionNumber($configService->getByParam('version'));
return UpgradeDatabaseService::needsUpgrade($dbVersion) ||
UpgradeAppService::needsUpgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion()));
return $this->configData->getUpgradeKey()
|| (UpgradeDatabaseService::needsUpgrade($this->configData->getDatabaseVersion()) ||
UpgradeAppService::needsUpgrade(UpgradeUtil::fixVersionNumber($this->configData->getConfigVersion())));
}
/**

View File

@@ -1,6 +1,7 @@
<?php
/**
* @var \SP\Mvc\View\Template $this
* @var \SP\Core\UI\ThemeIcons $icons
*/
?>
<div id="actions" class="installer" align="center">
@@ -11,6 +12,44 @@
<p class="hint">
<?php echo __('Consulte con el administrador'); ?>
</p>
<p class="hint">
<?php echo __('Para iniciar la actualización introduzca el código de seguridad'); ?>
</p>
</li>
</ul>
<form id="frmUpgrade" method="get" class="form-action" data-onsubmit="main/upgrade"
data-action-route="upgrade/upgrade">
<fieldset>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input id="key" name="key" type="text" required class="mdl-textfield__input mdl-color-text--indigo-400"
autocomplete="off" autofocus>
<label class="mdl-textfield__label"
for="key"><?php echo __('Código de Seguridad'); ?></label>
</div>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="chkConfirm">
<input type="checkbox" id="chkConfirm" class="mdl-checkbox__input" name="chkConfirm" required>
<span class="mdl-checkbox__label"><?php echo __('He realizado una copia de seguridad completa de sysPass'); ?></span>
</label>
</fieldset>
<div>
<ul class="errors">
<li class="msg-warning">
<i class="icon material-icons <?php echo $icons->getIconWarning()->getClass(); ?>"><?php echo $icons->getIconWarning()->getIcon(); ?></i>
<?php echo __('Por favor espere mientras el proceso se ejecuta'); ?>
</li>
</ul>
</div>
<div class="buttons">
<button id="btnChange" class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent"
type="submit">
<?php echo __('Actualizar'); ?>
<i class="material-icons"
title="<?php echo __('Iniciar Actualización'); ?>"><?php echo $icons->getIconPlay()->getIcon(); ?></i>
</button>
</div>
</form>
</div>

View File

@@ -32,6 +32,7 @@ use SP\Core\Exceptions\FileNotFoundException;
use SP\Services\Config\ConfigBackupService;
use SP\Storage\XmlFileStorageInterface;
use SP\Storage\XmlHandler;
use SP\Util\Util;
defined('APP_ROOT') || die();
@@ -65,8 +66,8 @@ class Config
* Config constructor.
*
* @param XmlFileStorageInterface $fileStorage
* @param ContextInterface $session
* @param Container $dic
* @param ContextInterface $session
* @param Container $dic
* @throws ConfigException
*/
public function __construct(XmlFileStorageInterface $fileStorage, ContextInterface $session, Container $dic)
@@ -125,15 +126,15 @@ class Config
* Guardar la configuración
*
* @param ConfigData $configData
* @param bool $backup
* @param bool $backup
* @return Config
*/
public function saveConfig(ConfigData $configData, $backup = true)
{
try {
if ($backup) {
$this->dic->get(ConfigBackupService::class)->backup();
$this->dic->get(ConfigBackupService::class)
->backup();
}
$configData->setConfigDate(time());
@@ -145,13 +146,15 @@ class Config
} catch (\Exception $e) {
processException($e);
}
return $this;
}
/**
* Cargar la configuración desde el archivo
*
* @param ContextInterface $context
* @param bool $reload
* @param bool $reload
* @return ConfigData
*/
public function loadConfig(ContextInterface $context, $reload = false)
@@ -189,4 +192,18 @@ class Config
{
return clone $this->configData;
}
/**
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
public function generateUpgradeKey()
{
if (empty($this->configData->getUpgradeKey())) {
debugLog('Generating upgrade key');
return $this->saveConfig($this->configData->setUpgradeKey(Util::generateRandomBytes(16)), false);
}
return $this;
}
}

View File

@@ -289,6 +289,10 @@ class ConfigData implements JsonSerializable
* @var string
*/
private $configVersion;
/**
* @var string
*/
private $databaseVersion;
/**
* @var bool
*/
@@ -1520,11 +1524,11 @@ class ConfigData implements JsonSerializable
*/
public function getConfigVersion()
{
return $this->configVersion;
return (string)$this->configVersion;
}
/**
* @param int $configVersion
* @param string $configVersion
* @return $this
*/
public function setConfigVersion($configVersion)
@@ -1989,4 +1993,23 @@ class ConfigData implements JsonSerializable
{
$this->mailEvents = $mailEvents;
}
/**
* @return string
*/
public function getDatabaseVersion()
{
return (string)$this->databaseVersion;
}
/**
* @param string $databaseVersion
* @return ConfigData
*/
public function setDatabaseVersion($databaseVersion)
{
$this->databaseVersion = $databaseVersion;
return $this;
}
}

View File

@@ -1,132 +0,0 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*/
namespace SP\DataModel;
defined('APP_ROOT') || die();
/**
* Class PublicLinkBaseData
*
* @package SP\DataModel
*/
class PublicLinkBaseData extends DataModelBase implements DataModelInterface
{
/**
* @var int
*/
public $publicLink_id = 0;
/**
* @var int
*/
public $publicLink_itemId = 0;
/**
* @var string
*/
public $publicLink_hash = '';
/**
* @var PublicLinkData
*/
public $publicLink_linkData;
/**
* @return int
*/
public function getPublicLinkId()
{
return (int)$this->publicLink_id;
}
/**
* @param int $publicLink_id
*/
public function setPublicLinkId($publicLink_id)
{
$this->publicLink_id = (int)$publicLink_id;
}
/**
* @return string
*/
public function getPublicLinkHash()
{
return $this->publicLink_hash;
}
/**
* @param string $publicLink_hash
*/
public function setPublicLinkHash($publicLink_hash)
{
$this->publicLink_hash = $publicLink_hash;
}
/**
* @return PublicLinkData
*/
public function getPublicLinkLinkData()
{
return $this->publicLink_linkData;
}
/**
* @param PublicLinkData $publicLink_linkData
*/
public function setPublicLinkLinkData($publicLink_linkData)
{
$this->publicLink_linkData = $publicLink_linkData;
}
/**
* @return int
*/
public function getPublicLinkItemId()
{
return (int)$this->publicLink_itemId;
}
/**
* @param int $publicLink_itemId
*/
public function setPublicLinkItemId($publicLink_itemId)
{
$this->publicLink_itemId = (int)$publicLink_itemId;
}
/**
* @return int
*/
public function getId()
{
return $this->publicLink_id;
}
/**
* @return string
*/
public function getName()
{
return '';
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*/
namespace SP\DataModel;
/**
* Class PublickLinkOldData
*
* @package SP\DataModel
*/
class PublickLinkOldData
{
/**
* @var int
*/
protected $itemId = 0;
/**
* @var int
*/
protected $userId = 0;
/**
* @var string
*/
protected $linkHash = '';
/**
* @var int
*/
protected $typeId = 0;
/**
* @var bool
*/
protected $notify = false;
/**
* @var int
*/
protected $dateAdd = 0;
/**
* @var int
*/
protected $dateExpire = 0;
/**
* @var string
*/
protected $pass = '';
/**
* @var string
*/
protected $passIV = '';
/**
* @var int
*/
protected $countViews = 0;
/**
* @var int
*/
protected $maxCountViews = 0;
/**
* @var array
*/
protected $useInfo = [];
/**
* @var string
*/
protected $data;
/**
* @return int
*/
public function getItemId()
{
return $this->itemId;
}
/**
* @param int $itemId
*/
public function setItemId($itemId)
{
$this->itemId = $itemId;
}
/**
* @return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* @param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* @return string
*/
public function getLinkHash()
{
return $this->linkHash;
}
/**
* @param string $linkHash
*/
public function setLinkHash($linkHash)
{
$this->linkHash = $linkHash;
}
/**
* @return int
*/
public function getTypeId()
{
return $this->typeId;
}
/**
* @param int $typeId
*/
public function setTypeId($typeId)
{
$this->typeId = $typeId;
}
/**
* @return boolean
*/
public function isNotify()
{
return (bool)$this->notify;
}
/**
* @param boolean $notify
*/
public function setNotify($notify)
{
$this->notify = $notify;
}
/**
* @return int
*/
public function getDateAdd()
{
return $this->dateAdd;
}
/**
* @param int $dateAdd
*/
public function setDateAdd($dateAdd)
{
$this->dateAdd = $dateAdd;
}
/**
* @return int
*/
public function getDateExpire()
{
return $this->dateExpire;
}
/**
* @param int $dateExpire
*/
public function setDateExpire($dateExpire)
{
$this->dateExpire = $dateExpire;
}
/**
* @return string
*/
public function getPass()
{
return $this->pass;
}
/**
* @param string $pass
*/
public function setPass($pass)
{
$this->pass = $pass;
}
/**
* @return string
*/
public function getPassIV()
{
return $this->passIV;
}
/**
* @param string $passIV
*/
public function setPassIV($passIV)
{
$this->passIV = $passIV;
}
/**
* @return int
*/
public function getCountViews()
{
return $this->countViews;
}
/**
* @param int $countViews
*/
public function setCountViews($countViews)
{
$this->countViews = $countViews;
}
/**
* @return int
*/
public function addCountViews()
{
return $this->countViews++;
}
/**
* @return int
*/
public function getMaxCountViews()
{
return $this->maxCountViews;
}
/**
* @param int $maxCountViews
*/
public function setMaxCountViews($maxCountViews)
{
$this->maxCountViews = $maxCountViews;
}
/**
* @return array
*/
public function getUseInfo()
{
return $this->useInfo;
}
/**
* @param array $useInfo
*/
public function setUseInfo(array $useInfo)
{
$this->useInfo = $useInfo;
}
/**
* @param array $useInfo
*/
public function addUseInfo($useInfo)
{
$this->useInfo[] = $useInfo;
}
/**
* @return string
*/
public function getData()
{
return $this->data;
}
/**
* @param string $data
*/
public function setData($data)
{
$this->data = $data;
}
}

View File

@@ -2,8 +2,8 @@
/**
* sysPass
*
* @author nuxsmin
* @link https://syspass.org
* @author nuxsmin
* @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -245,7 +245,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
'INSERT INTO PublicLink
SET itemId = ?,
`hash` = ?,
data = ?,
`data` = ?,
userId = ?,
typeId = ?,
notify = ?,
@@ -337,20 +337,32 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
{
$query = /** @lang SQL */
'UPDATE PublicLink
SET `hash` = ?,
data = ?,
SET itemId = ?,
`hash` = ?,
`data` = ?,
userId = ?,
notify = ?,
dateAdd = ?,
dateExpire = ?,
maxCountViews = ?
countViews = ?,
maxCountViews = ?,
useInfo = ?,
typeId = ?
WHERE id = ? LIMIT 1';
$queryData = new QueryData();
$queryData->setQuery($query);
$queryData->addParam($itemData->getItemId());
$queryData->addParam($itemData->getHash());
$queryData->addParam($itemData->getData());
$queryData->addParam($itemData->getUserId());
$queryData->addParam((int)$itemData->isNotify());
$queryData->addParam($itemData->getDateAdd());
$queryData->addParam($itemData->getDateExpire());
$queryData->addParam($itemData->getCountViews());
$queryData->addParam($itemData->getMaxCountViews());
$queryData->addParam($itemData->getUseInfo());
$queryData->addParam($itemData->getTypeId());
$queryData->addParam($itemData->getId());
$queryData->setOnErrorMessage(__u('Error al actualizar enlace'));
@@ -371,7 +383,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$query = /** @lang SQL */
'UPDATE PublicLink
SET `hash` = ?,
data = ?,
`data` = ?,
dateExpire = ?,
countViews = 0,
maxCountViews = ?

View File

@@ -47,8 +47,11 @@ interface DatabaseSetupInterface
/**
* Crear el usuario para conectar con la base de datos.
* Esta función crea el usuario para conectar con la base de datos.
*
* @param string $user
* @param string $pass
*/
public function createDBUser();
public function createDBUser($user, $pass);
/**
* Crear la base de datos

View File

@@ -78,7 +78,6 @@ class Installer extends Service
/**
* @param InstallData $installData
* @return static
* @throws Dic\ContainerException
* @throws InvalidArgumentException
* @throws SPException
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
@@ -167,7 +166,6 @@ class Installer extends Service
/**
* Iniciar instalación.
*
* @throws Dic\ContainerException
* @throws SPException
* @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
* @throws \Psr\Container\ContainerExceptionInterface
@@ -185,9 +183,14 @@ class Installer extends Service
$this->saveMasterPassword();
$this->createAdminAccount();
$this->configService->create(new \SP\DataModel\ConfigData('version', Util::getVersionStringNormalized()));
$version = Util::getVersionStringNormalized();
$this->configService->create(new \SP\DataModel\ConfigData('version', $version));
$this->configData->setInstalled(true);
$this->configData->setDatabaseVersion($version);
$this->configData->setConfigVersion($version);
$this->config->saveConfig($this->configData, false);
}
@@ -270,7 +273,8 @@ class Installer extends Service
private function setupDBConnectionData()
{
// FIXME: ugly!!
$this->dic->get(DatabaseConnectionData::class)->refreshFromConfig($this->configData);
$this->dic->get(DatabaseConnectionData::class)
->refreshFromConfig($this->configData);
}
/**

View File

@@ -103,60 +103,63 @@ class MySQL implements DatabaseSetupInterface
*/
public function setupDbUser()
{
$this->installData->setDbPass(Util::randomPassword());
$this->installData->setDbUser(substr(uniqid('sp_'), 0, 16));
debugLog(__METHOD__);
$user = substr(uniqid('sp_'), 0, 16);
$pass = Util::randomPassword();
try {
// Comprobar si el usuario proporcionado existe
$sth = $this->dbs->getConnectionSimple()
->prepare('SELECT COUNT(*) FROM mysql.user WHERE `user` = ? AND `host` = ?');
$sth->execute([$this->installData->getDbUser(), $this->installData->getDbAuthHost()]);
$sth->execute([$user, $pass]);
// Si no existe el usuario, se intenta crear
if ((int)$sth->fetchColumn() === 0
// Se comprueba si el nuevo usuario es distinto del creado en otra instalación
&& $this->installData->getDbUser() !== $this->configData->getDbUser()
) {
$this->createDBUser();
if ((int)$sth->fetchColumn() === 0) {
$this->createDBUser($user, $pass);
}
} catch (PDOException $e) {
processException($e);
throw new SPException(
sprintf(__('No es posible comprobar el usuario de sysPass (%s)'), $this->installData->getAdminLogin()),
sprintf(__('No es posible comprobar el usuario de sysPass (%s)'), $user),
SPException::CRITICAL,
__u('Compruebe los permisos del usuario de conexión a la BD')
);
}
// Guardar el nuevo usuario/clave de conexión a la BD
$this->configData->setDbUser($this->installData->getDbUser());
$this->configData->setDbPass($this->installData->getDbPass());
$this->configData->setDbUser($user);
$this->configData->setDbPass($pass);
}
/**
* Crear el usuario para conectar con la base de datos.
* Esta función crea el usuario para conectar con la base de datos.
*
* @param string $user
* @param string $pass
* @throws SPException
*/
public function createDBUser()
public function createDBUser($user, $pass)
{
if ($this->installData->isHostingMode()) {
return;
}
debugLog('Creating DB user');
try {
$dbc = $this->dbs->getConnectionSimple();
$dbc->exec('CREATE USER `' . $this->installData->getDbUser() . '`@`' . $this->installData->getDbAuthHost() . '` IDENTIFIED BY \'' . $this->installData->getDbPass() . '\'');
$dbc->exec('CREATE USER `' . $this->installData->getDbUser() . '`@`' . $this->installData->getDbAuthHostDns() . '` IDENTIFIED BY \'' . $this->installData->getDbPass() . '\'');
$dbc->exec('CREATE USER `' . $user . '`@`' . $this->installData->getDbAuthHost() . '` IDENTIFIED BY \'' . $pass . '\'');
$dbc->exec('CREATE USER `' . $user . '`@`' . $this->installData->getDbAuthHostDns() . '` IDENTIFIED BY \'' . $pass . '\'');
$dbc->exec('FLUSH PRIVILEGES');
} catch (PDOException $e) {
processException($e);
throw new SPException(
sprintf(__u('Error al crear el usuario de conexión a MySQL \'%s\''), $this->installData->getDbUser()),
sprintf(__u('Error al crear el usuario de conexión a MySQL \'%s\''), $user),
SPException::CRITICAL, $e->getMessage()
);
}
@@ -291,9 +294,7 @@ class MySQL implements DatabaseSetupInterface
}
// Leemos el archivo SQL para crear las tablas de la BBDD
$handle = fopen($fileName, 'rb');
if ($handle) {
if ($handle = fopen($fileName, 'rb')) {
while (!feof($handle)) {
$buffer = stream_get_line($handle, 1000000, ";\n");

View File

@@ -325,6 +325,20 @@ class PublicLinkService extends Service
return $this->publicLinkRepository->getHashForItem($itemId);
}
/**
* Updates an item
*
* @param PublicLinkData $itemData
* @return mixed
* @throws SPException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
public function update(PublicLinkData $itemData)
{
return $this->publicLinkRepository->update($itemData);
}
/**
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface

View File

@@ -24,6 +24,8 @@
namespace SP\Services\Upgrade;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
use SP\Services\Service;
use SP\Util\Util;
@@ -51,17 +53,35 @@ class UpgradeAppService extends Service implements UpgradeInterface
*/
public function upgrade($version)
{
$this->eventDispatcher->notifyEvent('upgrade.app.start',
new Event($this, EventMessage::factory()
->addDescription(__u('Actualizar Aplicación')))
);
$configData = $this->config->getConfigData();
foreach (self::UPGRADES as $appVersion) {
if (Util::checkVersion($version, $appVersion)
&& $this->applyUpgrade($appVersion) === false
) {
throw new UpgradeException(
__u('Error al aplicar la actualización de la aplicación'),
UpgradeException::CRITICAL,
__u('Compruebe el registro de eventos para más detalles')
);
if (Util::checkVersion($version, $appVersion)) {
if ($this->applyUpgrade($appVersion) === false) {
throw new UpgradeException(
__u('Error al aplicar la actualización de la aplicación'),
UpgradeException::CRITICAL,
__u('Compruebe el registro de eventos para más detalles')
);
}
debugLog('APP Upgrade: '. $appVersion);
$configData->setConfigVersion($appVersion);
}
}
$this->config->saveConfig($configData, false);
$this->eventDispatcher->notifyEvent('upgrade.app.end',
new Event($this, EventMessage::factory()
->addDescription(__u('Actualizar Aplicación')))
);
}
/**
@@ -77,6 +97,8 @@ class UpgradeAppService extends Service implements UpgradeInterface
case '300.18010101':
$this->dic->get(UpgradeCustomFieldDefinition::class)
->upgrade_300_18010101();
$this->dic->get(UpgradePublicLink::class)
->upgrade_300_18010101();
return true;
}
} catch (\Exception $e) {

View File

@@ -32,7 +32,7 @@ use SP\Services\CustomField\CustomFieldDefService;
use SP\Services\CustomField\CustomFieldTypeService;
use SP\Services\Service;
use SP\Services\ServiceException;
use SP\Storage\DatabaseInterface;
use SP\Storage\Database;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
use SP\Util\Util;
@@ -45,7 +45,7 @@ use SP\Util\Util;
class UpgradeCustomFieldDefinition extends Service
{
/**
* @var DatabaseInterface
* @var Database
*/
private $db;
@@ -121,6 +121,6 @@ class UpgradeCustomFieldDefinition extends Service
protected function initialize()
{
$this->db = $this->dic->get(DatabaseInterface::class);
$this->db = $this->dic->get(Database::class);
}
}

View File

@@ -26,7 +26,6 @@ namespace SP\Services\Upgrade;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
use SP\Services\Config\ConfigService;
use SP\Services\Service;
use SP\Storage\Database;
use SP\Storage\DbWrapper;
@@ -58,7 +57,7 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
*/
public static function needsUpgrade($version)
{
return Util::checkVersion($version, self::UPGRADES);
return empty($version) || Util::checkVersion($version, self::UPGRADES);
}
/**
@@ -67,8 +66,6 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
* @param int $version con la versión de la BBDD actual
* @return bool
* @throws UpgradeException
* @throws \SP\Core\Exceptions\SPException
* @throws \SP\Services\Config\ParameterNotFoundException
*/
public function upgrade($version)
{
@@ -77,13 +74,10 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
->addDescription(__u('Actualizar BBDD')))
);
$configService = $this->dic->get(ConfigService::class);
$dbVersion = UpgradeUtil::fixVersionNumber($configService->getByParam('version'));
$configData = $this->config->getConfigData();
foreach (self::UPGRADES as $upgradeVersion) {
if (Util::checkVersion($version, $upgradeVersion)
&& Util::checkVersion($dbVersion, $version)
) {
if (Util::checkVersion($version, $upgradeVersion)) {
if ($this->applyPreUpgrade($upgradeVersion) === false) {
throw new UpgradeException(
__u('Error al aplicar la actualización auxiliar'),
@@ -100,7 +94,11 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
);
}
$configService->save('version', $version);
debugLog('DB Upgrade: ' . $upgradeVersion);
$configData->setDatabaseVersion($upgradeVersion);
$this->config->saveConfig($configData, false);
}
}
@@ -169,6 +167,7 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
DbWrapper::getQuery($queryData, $this->db);
} catch (\Exception $e) {
processException($e);
debugLog('SQL: ' . $query);
$this->eventDispatcher->notifyEvent('exception',
new Event($this, EventMessage::factory()
@@ -206,8 +205,8 @@ class UpgradeDatabaseService extends Service implements UpgradeInterface
while (!feof($handle)) {
$buffer = stream_get_line($handle, 1000000, ";\n");
if (strlen(trim($buffer)) > 0) {
$queries[] = str_replace("\n", '', $buffer);
if (strlen(trim($buffer)) > 0 && strpos($buffer, '--') !== 0) {
$queries[] = $buffer;
}
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*/
namespace SP\Services\Upgrade;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
use SP\DataModel\PublickLinkOldData;
use SP\DataModel\PublicLinkData;
use SP\Services\PublicLink\PublicLinkService;
use SP\Services\Service;
use SP\Services\ServiceException;
use SP\Storage\Database;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
use SP\Util\Util;
/**
* Class UpgradePublicLink
*
* @package SP\Services\Upgrade
*/
class UpgradePublicLink extends Service
{
/**
* @var Database
*/
private $db;
/**
* upgrade_300_18010101
*
* @throws \SP\Core\Exceptions\SPException
*/
public function upgrade_300_18010101()
{
$this->eventDispatcher->notifyEvent('upgrade.publicLink.start',
new Event($this, EventMessage::factory()
->addDescription(__u('Actualización de enlaces públicos'))
->addDescription(__FUNCTION__))
);
$queryData = new QueryData();
$queryData->setQuery('SELECT id, `data` FROM PublicLink');
try {
$publicLinkService = $this->dic->get(PublicLinkService::class);
if (!DbWrapper::beginTransaction($this->db)) {
throw new ServiceException(__u('No es posible iniciar una transacción'));
}
foreach (DbWrapper::getResultsArray($queryData, $this->db) as $item) {
/** @var PublickLinkOldData $data */
$data = Util::unserialize(PublickLinkOldData::class, $item->data, 'SP\DataModel\PublicLinkData');
$itemData = new PublicLinkData();
$itemData->setId($item->id);
$itemData->setItemId($data->getItemId());
$itemData->setHash($data->getLinkHash());
$itemData->setUserId($data->getUserId());
$itemData->setTypeId($data->getTypeId());
$itemData->setNotify($data->isNotify());
$itemData->setDateAdd($data->getDateAdd());
$itemData->setDateExpire($data->getDateExpire());
$itemData->setCountViews($data->getCountViews());
$itemData->setMaxCountViews($data->getMaxCountViews());
$itemData->setUseInfo($data->getUseInfo());
$itemData->setData($data->getData());
$publicLinkService->update($itemData);
$this->eventDispatcher->notifyEvent('upgrade.publicLink.process',
new Event($this, EventMessage::factory()
->addDescription(__u('Enlace actualizado'))
->addDetail(__u('Enlace'), $item->id))
);
}
if (!DbWrapper::endTransaction($this->db)) {
throw new ServiceException(__u('No es posible finalizar una transacción'));
}
} catch (\Exception $e) {
DbWrapper::rollbackTransaction($this->db);
processException($e);
$this->eventDispatcher->notifyEvent('exception', new Event($e));
}
$this->eventDispatcher->notifyEvent('upgrade.publicLink.end',
new Event($this, EventMessage::factory()
->addDescription(__u('Actualización de enlaces públicos'))
->addDescription(__FUNCTION__))
);
}
protected function initialize()
{
$this->db = $this->dic->get(Database::class);
}
}

View File

@@ -79,6 +79,8 @@ class DatabaseConnectionData
*/
public function refreshFromConfig(ConfigData $configData)
{
debugLog('Refresh DB connection data');
return $this->setDbHost($configData->getDbHost())
->setDbName($configData->getDbName())
->setDbUser($configData->getDbUser())

View File

@@ -2,8 +2,8 @@
/**
* sysPass
*
* @author nuxsmin
* @link https://syspass.org
* @author nuxsmin
* @link https://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -127,7 +127,7 @@ class XmlHandler implements XmlFileStorageInterface
$nodes[$node->nodeName] = $this->readChildNodes($node->childNodes);
}
} else {
$val = is_numeric($node->nodeValue) ? (int)$node->nodeValue : $node->nodeValue;
$val = is_numeric($node->nodeValue) && strpos($node->nodeValue, '.') === false ? (int)$node->nodeValue : $node->nodeValue;
if ($node->nodeName === 'item') {
$nodes[] = $val;
@@ -181,9 +181,9 @@ class XmlHandler implements XmlFileStorageInterface
/**
* Crear los nodos hijos recursivamente a partir de un array multidimensional
*
* @param mixed $items
* @param mixed $items
* @param DOMNode $Node
* @param null $type
* @param null $type
*/
protected function writeChildNodes($items, DOMNode $Node, $type = null)
{
@@ -212,7 +212,7 @@ class XmlHandler implements XmlFileStorageInterface
* Analizar el tipo de elementos
*
* @param mixed $items
* @param bool $serialize
* @param bool $serialize
* @return array
*/
protected function analyzeItems($items, $serialize = false)
@@ -246,8 +246,10 @@ class XmlHandler implements XmlFileStorageInterface
$property->setAccessible(true);
$value = $property->getValue($object);
if (is_numeric($value) || is_bool($value)) {
if (is_bool($value)) {
$items[$property->getName()] = (int)$value;
} elseif (is_numeric($value)) {
$items[$property->getName()] = strpos($value, '.') !== false ? (float)$value : (int)$value;
} else {
$items[$property->getName()] = $value;
}

View File

@@ -351,7 +351,7 @@ class Util
list($currentVersion, $build) = explode('.', $currentVersion, 2);
list($upgradeVersion, $upgradeBuild) = explode('.', $upgradeableVersion, 2);
$versionRes = (int)$currentVersion <= (int)$upgradeVersion;
$versionRes = (int)$currentVersion < (int)$upgradeVersion;
return (($versionRes && (int)$upgradeBuild === 0)
|| ($versionRes && (int)$build < (int)$upgradeBuild));
@@ -500,7 +500,7 @@ class Util
if (!is_object($serialized)) {
preg_match('/^O:\d+:"(?P<class>[^"]++)"/', $serialized, $matches);
if (class_exists($matches['class'])) {
if (class_exists($matches['class']) && $srcClass === null) {
return unserialize($serialized);
}

View File

@@ -665,7 +665,7 @@ sysPass.Actions = function (Common) {
}
const opts = Common.appRequests().getRequestOpts();
opts.url = ajaxUrl.entrypoint;
opts.url = ajaxUrl.entrypoint + "?r=" + $obj.data('action-route');
opts.method = "get";
opts.useFullLoading = !!taskId;
opts.data = $obj.serialize();
@@ -674,7 +674,7 @@ sysPass.Actions = function (Common) {
Common.msg.out(json);
if (json.status !== 0) {
$obj.find(":input[name=h]").val("");
$obj.find(":input[name=key]").val("");
} else {
if (taskRunner !== undefined) {
taskRunner.close();

View File

@@ -16,8 +16,8 @@ void 0!==a.data.itemId&&void 0!==a.data.nextAction&&h(b.appRequests().getRouteFo
update:function(a){e.info("items:update");var c=$("#"+a.data("item-dst"))[0].selectize;c.clearOptions();c.load(function(c){var d=b.appRequests().getRequestOpts();d.url=f.entrypoint;d.method="get";d.data={r:a.data("item-route"),sk:b.sk.get()};b.appRequests().getActionCall(d,function(a){c(a)})})}},u={logout:function(){b.redirect("index.php?r=login/logout")},login:function(a){e.info("main:login");var c=b.appRequests().getRequestOpts();c.url=f.entrypoint+"?r="+a.data("route");c.method="get";c.data=a.serialize();
b.appRequests().getActionCall(c,function(c){var d=$(".extra-hidden");switch(c.status){case 0:b.redirect(c.data.url);break;case 2:b.msg.out(c);a.find("input[type='text'],input[type='password']").val("");a.find("input:first").focus();0<d.length&&d.hide();$("#mpass").prop("disabled",!1).val("");$("#smpass").show();break;case 5:b.msg.out(c);a.find("input[type='text'],input[type='password']").val("");a.find("input:first").focus();0<d.length&&d.hide();$("#oldpass").prop("disabled",!1).val("");$("#soldpass").show();
break;default:b.msg.out(c),a.find("input[type='text'],input[type='password']").val(""),a.find("input:first").focus()}})},install:function(a){e.info("main:install");var c=b.appRequests().getRequestOpts();c.url=f.entrypoint+"?r="+a.data("route");c.data=a.serialize();b.appRequests().getActionCall(c,function(a){b.msg.out(a);0===a.status&&setTimeout(function(){b.redirect("index.php?r=login/index")},1E3)})},upgrade:function(a){e.info("main:upgrade");var c='<div id="alert"><p id="alert-text">'+b.config().LANG[59]+
"</p></div>";mdlDialog().show({text:c,negative:{title:b.config().LANG[44],onClick:function(a){a.preventDefault();b.msg.error(b.config().LANG[44])}},positive:{title:b.config().LANG[43],onClick:function(c){var d;(c=a.find("input[name='taskId']").val())&&(d=t(c));var e=b.appRequests().getRequestOpts();e.url=f.entrypoint;e.method="get";e.useFullLoading=!!c;e.data=a.serialize();b.appRequests().getActionCall(e,function(c){b.msg.out(c);0!==c.status?a.find(":input[name=h]").val(""):(void 0!==d&&d.close(),
setTimeout(function(){b.redirect("index.php")},5E3))})}}})},getUpdates:function(){e.info("main:getUpdates");var a=b.appRequests().getRequestOpts();a.url=f.entrypoint+"?r=status/checkRelease";a.method="get";a.timeout=1E4;a.useLoading=!1;a.data={isAjax:1};var c=$("#updates");b.appRequests().getActionCall(a,function(a){0===a.status?0<a.data.length?c.html('<a id="link-updates" href="'+a.data.url+'" target="_blank">'+a.data.title+'<div id="help-hasupdates" class="icon material-icons mdl-color-text--indigo-200">cloud_download</div></a><span for="link-updates" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large">'+
"</p></div>";mdlDialog().show({text:c,negative:{title:b.config().LANG[44],onClick:function(a){a.preventDefault();b.msg.error(b.config().LANG[44])}},positive:{title:b.config().LANG[43],onClick:function(c){var d;(c=a.find("input[name='taskId']").val())&&(d=t(c));var e=b.appRequests().getRequestOpts();e.url=f.entrypoint+"?r="+a.data("action-route");e.method="get";e.useFullLoading=!!c;e.data=a.serialize();b.appRequests().getActionCall(e,function(c){b.msg.out(c);0!==c.status?a.find(":input[name=key]").val(""):
(void 0!==d&&d.close(),setTimeout(function(){b.redirect("index.php")},5E3))})}}})},getUpdates:function(){e.info("main:getUpdates");var a=b.appRequests().getRequestOpts();a.url=f.entrypoint+"?r=status/checkRelease";a.method="get";a.timeout=1E4;a.useLoading=!1;a.data={isAjax:1};var c=$("#updates");b.appRequests().getActionCall(a,function(a){0===a.status?0<a.data.length?c.html('<a id="link-updates" href="'+a.data.url+'" target="_blank">'+a.data.title+'<div id="help-hasupdates" class="icon material-icons mdl-color-text--indigo-200">cloud_download</div></a><span for="link-updates" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large">'+
a.data.description+"</span>"):c.html('<div id="updates-info" class="icon material-icons mdl-color-text--teal-200">check_circle</div><span for="updates-info" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large">'+b.config().LANG[68]+"</span>"):c.html('<div id="updates-info" class="icon material-icons mdl-color-text--amber-200">warning</div><span for="updates-info" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large">'+b.config().LANG[69]+"</span>");void 0!==componentHandler&&componentHandler.upgradeDom()},
function(){c.html('<div id="updates-info" class="icon material-icons mdl-color-text--amber-200">warning</div><span for="updates-info" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large">'+b.config().LANG[69]+"</span>")})},getNotices:function(){e.info("main:getNotices");var a=b.appRequests().getRequestOpts();a.url=f.entrypoint+"?r=status/checkNotices";a.method="get";a.timeout=1E4;a.useLoading=!1;a.data={isAjax:1};var c=$("#notices");b.appRequests().getActionCall(a,function(a){0===a.status&&0<a.data.length&&
c.html('<a href="https://github.com/nuxsmin/sysPass/labels/Notices" target="_blank"><div id="notices-info" class="material-icons mdl-badge mdl-badge--overlap mdl-color-text--amber-200" data-badge="'+a.data.length+'">feedback</div></a><span for="notices-info" class="mdl-tooltip mdl-tooltip--top mdl-tooltip--large"><div class="notices-title">'+b.config().LANG[70]+"</div>"+a.data.map(function(a){return a.title}).join("<br>")+"</span>");void 0!==componentHandler&&componentHandler.upgradeDom()})}},k={state:{tab:{index:0,

File diff suppressed because it is too large Load Diff