Files
sysPass/inc/SP/Import/Migrate.class.php
2016-11-02 23:35:32 +01:00

970 lines
31 KiB
PHP

<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP\Import;
use SP\Config\Config;
use SP\DataModel\CustomerData;
use SP\Mgmt\Customers\Customer;
use SP\Log\Log;
use SP\Core\Session;
use SP\Core\Exceptions\SPException;
use SP\Storage\DB;
use SP\Storage\DBUtil;
use SP\Storage\QueryData;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar la migración de datos desde phpPMS.
*/
class Migrate
{
private static $DB; // Database connection
private static $customersByName;
private static $currentQuery;
private static $result = array();
private static $oldConfig = array();
/**
* Iniciar migración desde phpPMS.
*
* @param array $options datos de conexión
* @return array resultado del proceso
*/
public static function migrate($options)
{
if (!is_array($options)) {
$result['error'][]['description'] = _('Faltan parámetros');
return $result;
}
$dbname = $options['dbname'];
if (preg_match('/(.*):(\d{1,5})/', $options['dbhost'], $match)){
$dbhost = $match[1];
$dbport = $match[2];
} else {
$dbhost = $options['dbhost'];
$dbport = 3306;
}
$dbadmin = $options['dbuser'];
$dbpass = $options['dbpass'];
try {
self::checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbname, $dbport);
self::checkDatabaseExist($dbname);
self::checkSourceVersion();
self::cleanCurrentDB();
self::migrateCustomers();
self::migrateAccounts();
self::migrateAccountsGroups();
self::migrateAccountsHistory();
self::migrateAcountsFiles();
self::migrateAccountsCategories();
self::migrateUsers();
self::migrateUsersGroups();
self::migrateConfig();
} catch (SPException $e) {
self::$result['error'][] = array(
'type' => $e->getType(),
'description' => $e->getMessage(),
'hint' => $e->getHint()
);
return (self::$result);
}
self::$result['ok'][] = _('Importación finalizada');
self::$result['ok'][] = _('Revise el registro de eventos para más detalles');
return (self::$result);
}
/**
* Comprobar si la conexión con la BBDD de phpPMS es posible.
*
* @param string $dbhost host de conexión
* @param string $dbadmin usuario de conexión
* @param string $dbpass clave de conexión
* @param string $dbname nombre de la base de datos
* @param string $dbport puerto de conexión
* @throws \SP\Core\Exceptions\SPException
*/
private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbname, $dbport)
{
try {
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname . ';dbport=' . $dbport . ';charset=utf8';
self::$DB = new \PDO($dsn, $dbadmin, $dbpass);
} catch (\PDOException $e) {
throw new SPException(SPException::SP_CRITICAL
, _('No es posible conectar con la BD')
, _('Compruebe los datos de conexión') . '<br>' . $e->getMessage());
}
}
/**
* Comprobar si la BBDD existe.
*
* @param string $dbname nombre de la base de datos
* @return bool
*/
private static function checkDatabaseExist($dbname)
{
$query = 'SELECT COUNT(*) '
. 'FROM information_schema.tables '
. 'WHERE table_schema = \'' . $dbname . '\' '
. 'AND table_name = \'usrData\' LIMIT 1';
return (intval(self::$DB->query($query)->fetchColumn()) === 0);
}
/**
* Comprobar la versión de phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
*/
private static function checkSourceVersion()
{
if (!isset(self::$oldConfig['version'])) {
self::getSourceConfig();
}
if (self::$oldConfig['version'] != "0.973b") {
throw new SPException(SPException::SP_CRITICAL,
_('La versión no es compatible') . '(' . self::$oldConfig['version'] . ')',
_('Actualice a la última versión de phpPMS'));
}
}
/**
* Obtener la configuración desde desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
*/
private static function getSourceConfig()
{
$query = 'SELECT vacValue as value,vacParameter as parameter FROM config';
try {
self::parseSourceConfig(self::$DB->query($query));
} catch (\PDOException $e) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener la configuración'),
$e->getMessage());
}
}
/**
* Parsear los valores de configuración de phpPMS y adaptarlos a sysPass.
*
* @param array $config con los datos de configuración
* @return bool
*/
private static function parseSourceConfig($config)
{
if (!is_array($config)) {
return false;
}
if (strtolower($config['value']) == 'true' || strtolower($config['value']) == 'on') {
$value = 1;
} else {
$value = (is_numeric($config['value'])) ? (int)$config['value'] : trim($config['value']);
}
// Guardar la configuración anterior
self::$oldConfig[$config['parameter']] = $value;
}
/**
* Limpiar los datos de sysPass.
* Limpiar las tablas de la base de sysPass para la importación.
*
* @throws \SP\Core\Exceptions\SPException
*/
private static function cleanCurrentDB()
{
$tables = array('accounts', 'accHistory', 'accFiles', 'accGroups', 'categories', 'customers', 'usrGroups');
// Limpiar datos de las tablas
foreach ($tables as $table) {
$query = 'TRUNCATE TABLE ' . $table;
$Data = new QueryData();
$Data->setQuery($query);
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al vaciar tabla') . ' (' . $table . ')',
DB::$txtError);
}
}
$currentUserId = Session::getUserId();
// Limpiar datos de usuarios manteniendo el usuario actual
if (self::checkAdminAccount($currentUserId)) {
$query = 'DELETE FROM usrData WHERE user_id != :userid';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($currentUserId, 'userid');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al vaciar tabla') . ' (' . $table . ')',
DB::$txtError);
}
} else {
throw new SPException(SPException::SP_CRITICAL,
_('Usuario actual no es administrador de la aplicación'), 1);
}
}
/**
* Comprobar si el usuario actual es administrador de la aplicación.
*
* @param int $currentUserId con el Id del usuario de la sesión actual
* @return bool
*/
private static function checkAdminAccount($currentUserId)
{
$query = 'SELECT user_id FROM usrData WHERE user_id = :id AND user_isAdminApp = 1 LIMIT 1';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($currentUserId, 'id');
DB::getQuery($Data);
return ($Data->getQueryNumRows() === 0);
}
/**
* Migrar los clientes desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateCustomers()
{
$customers = self::getCustomers();
$totalRecords = count($customers);
$num = 0;
foreach ($customers as $customer) {
try {
Customer::getItem(new CustomerData(null, $customer))->add();
$num++;
} catch (SPException $e) {
if ($e->getType() === SPException::SP_WARNING){
continue;
}
throw new SPException(SPException::SP_CRITICAL,
_('No es posible crear el cliente'),
_('Contacte con el desarrollador'));
}
}
$Log = new Log(_('Importar Clientes'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Obtener los clientes desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array con los clientes
*/
private static function getCustomers()
{
$query = 'SELECT DISTINCT vacCliente FROM accounts';
try {
foreach (self::$DB->query($query) as $row) {
$customers[] = trim($row['vacCliente']);
}
return $customers;
} catch (\PDOException $e) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener los clientes'),
$e->getMessage());
}
}
/**
* Migrar las cuentas desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateAccounts()
{
$query = 'SELECT intAccountId,'
. 'intUGroupFId,'
. 'intUserFId,'
. 'intUEditFId,'
. 'vacCliente,vacName,'
. 'intCategoryFid,'
. 'vacLogin,'
. 'vacUrl,'
. 'vacPassword,'
. 'vacMd5Password,'
. 'vacInitialValue,'
. 'txtNotice,'
. 'intCountView,'
. 'intCountDecrypt,'
. 'datAdded,datChanged '
. 'FROM accounts ';
$totalRecords = 0;
$num = 0;
try {
foreach (self::$DB->query($query) as $row) {
if (self::insertAccounts($row)) {
$num++;
}
$totalRecords++;
}
} catch (\PDOException $e) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener cuentas'),
$e->getMessage());
}
$Log = new Log(_('Importar Cuentas'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar una cuenta en sysPass.
*
* @param array $account con los datos de la cuenta
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertAccounts($account)
{
// FIXME
if (!is_array(self::$customersByName)) {
$customers = Customer::getCustomers(NULL, true);
self::$customersByName = array_flip($customers);
}
$customer = trim($account['vacCliente']);
if (array_key_exists($customer, self::$customersByName)) {
$customerId = self::$customersByName[$customer];
} else {
self::$result['error'][] = _('Cliente no encontrado') . ": " . $account['vacCliente'];
return false;
}
$query = 'INSERT INTO accounts SET ' .
'account_id = :id,' .
'account_userGroupId = :userGroupId,' .
'account_userId = :userId,' .
'account_userEditId = :userEditId,' .
'account_customerId = :customerId,' .
'account_name = :name,' .
'account_categoryId = :categoryId,' .
'account_login = :login,' .
'account_url = :url,' .
'account_pass = :pass,' .
'account_IV = :iv,' .
'account_notes = :notes,' .
'account_countView = :countView,' .
'account_countDecrypt = :countDecrypt,' .
'account_dateAdd = :dateAdd,' .
'account_dateEdit = :dateEdit';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($account['intAccountId'], 'id');
$Data->addParam($account['intUGroupFId'], 'userGroupId');
$Data->addParam($account['intUserFId'], 'userId');
$Data->addParam($account['intUEditFId'], 'userEditId');
$Data->addParam($customerId, 'customerId');
$Data->addParam($account['vacName'], 'name');
$Data->addParam($account['intCategoryFid'], 'categoryId');
$Data->addParam($account['vacLogin'], 'login');
$Data->addParam($account['vacUrl'], 'url');
$Data->addParam($account['vacPassword'], 'pass');
$Data->addParam($account['vacInitialValue'], 'iv');
$Data->addParam($account['txtNotice'], 'notes');
$Data->addParam($account['intCountView'], 'countView');
$Data->addParam($account['intCountDecrypt'], 'countDecrypt');
$Data->addParam($account['datAdded'], 'dateAdd');
$Data->addParam($account['datChanged'], 'dateEdit');
if (DB::getQuery($Data) === false) {
self::$currentQuery = DBUtil::escape($query);
throw new SPException(SPException::SP_CRITICAL,
_('Error al migrar cuenta'),
DB::$txtError);
}
return true;
}
/**
* Migrar las grupos secundarios de las cuentas desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateAccountsGroups()
{
$query = 'SELECT intAccId,intUGroupId FROM acc_usergroups';
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertAccountsGroups($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener los grupos de cuentas'),
$e->getMessage());
}
$Log = new Log(_('Importar Grupos de Cuentas'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar los grupos secundarios de una cuenta en sysPass.
*
* @param array $accountGroup con los datos de los grupos secundarios
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertAccountsGroups($accountGroup)
{
$query = 'INSERT INTO accGroups SET ' .
'accgroup_accountId = :accountId,' .
'accgroup_groupId = :groudId';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($accountGroup['intAccId'], 'accountId');
$Data->addParam($accountGroup['intUGroupId'], 'groupId');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear grupos de cuentas'),
DB::$txtError);
}
return true;
}
/**
* Migrar el historail de las cuentas desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateAccountsHistory()
{
$query = 'SELECT intAccountId,'
. 'intUGroupFId,'
. 'intUserFId,'
. 'intUEditFId,'
. 'vacCliente,'
. 'vacName,'
. 'intCategoryFid,'
. 'vacLogin,'
. 'vacUrl,'
. 'vacPassword,'
. 'vacInitialValue,'
. 'txtNotice,'
. 'intCountView,'
. 'intCountDecrypt,'
. 'datAdded,'
. 'datChanged,'
. 'blnModificada,'
. 'blnEliminada '
. 'FROM acc_history';
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertAccountsHistory($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener el historico de cuentas'),
self::$DB->error);
}
$Log = new Log(_('Importar Histórico de Cuentas'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar el historial de una cuenta en sysPass.
*
* @param array $accountHistory con los datos del historial de la cuenta
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertAccountsHistory($accountHistory)
{
if (!is_array(self::$customersByName)) {
$customers = Customer::getCustomers(null, true);
self::$customersByName = array_flip($customers);
}
$customer = trim($accountHistory['vacCliente']);
if (array_key_exists($customer, self::$customersByName)) {
$customerId = self::$customersByName[$customer];
} else {
return false;
}
$query = 'INSERT INTO accHistory SET ' .
'acchistory_accountId = :id,' .
'acchistory_userGroupId = :userGroupId,' .
'acchistory_userId = :userId,' .
'acchistory_userEditId = :userEditId,' .
'acchistory_customerId = :customerId,' .
'acchistory_name = :name,' .
'acchistory_categoryId = :categoryId,' .
'acchistory_login = :login,' .
'acchistory_url = :url,' .
'acchistory_pass = :pass,' .
'acchistory_IV = :iv,' .
'acchistory_notes = :notes,' .
'acchistory_countView = :countView,' .
'acchistory_countDecrypt = :countDecrypt,' .
'acchistory_dateAdd = :dateAdd,' .
'acchistory_dateEdit = :dateEdit,' .
'acchistory_isModify = :isModify,' .
'acchistory_isDeleted = :isDeleted';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($accountHistory['intAccountId'], 'id');
$Data->addParam($accountHistory['intUGroupFId'], 'userGroupId');
$Data->addParam($accountHistory['intUserFId'], 'userId');
$Data->addParam($accountHistory['intUEditFId'], 'userEditId');
$Data->addParam($customerId, 'customerId');
$Data->addParam($accountHistory['vacName'], 'name');
$Data->addParam($accountHistory['intCategoryFid'], 'categoryId');
$Data->addParam($accountHistory['vacLogin'], 'login');
$Data->addParam($accountHistory['vacUrl'], 'url');
$Data->addParam($accountHistory['vacPassword'], 'pass');
$Data->addParam($accountHistory['vacInitialValue'], 'iv');
$Data->addParam($accountHistory['txtNotice'], 'notes');
$Data->addParam($accountHistory['intCountView'], 'countView');
$Data->addParam($accountHistory['intCountDecrypt'], 'countDecrypt');
$Data->addParam($accountHistory['datAdded'], 'dateAdd');
$Data->addParam($accountHistory['datChanged'], 'dateEdit');
$Data->addParam($accountHistory['blnModificada'], 'isModify');
$Data->addParam($accountHistory['blnEliminada'], 'isDeleted');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear historico de cuentas'),
DB::$txtError);
}
return true;
}
/**
* Migrar los archivos de de las cuentas desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateAcountsFiles()
{
$query = 'SELECT intAccountId,'
. 'vacName,'
. 'vacType,'
. 'intSize,'
. 'blobContent,'
. 'vacExtension '
. 'FROM files';
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertAccountsFiles($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener los archivos de cuentas'),
self::$DB->error);
}
$Log = new Log(_('Importar Archivos de Cuentas'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar los archivos de una cuenta en sysPass.
*
* @param array $accountFile con los datos del archivo
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertAccountsFiles($accountFile)
{
$query = 'INSERT INTO accFiles '
. 'SET accfile_accountId = :id,'
. 'accfile_name = :name,'
. 'accfile_type = :type,'
. 'accfile_size = :size,'
. 'accfile_content = :blobcontent,'
. 'accfile_extension = :extension';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($accountFile['intAccountId'], 'id');
$Data->addParam($accountFile['vacName'], 'name');
$Data->addParam($accountFile['vacType'], 'type');
$Data->addParam($accountFile['intSize'], 'size');
$Data->addParam($accountFile['blobContent'], 'blobcontent');
$Data->addParam($accountFile['vacExtension'], 'extension');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear archivos de cuentas'),
DB::$txtError);
}
return true;
}
/**
* Migrar las categorías de las cuentas desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateAccountsCategories()
{
$query = 'SELECT intCategoryId,vacCategoryName FROM categories';
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertAccountsCategories($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener las categorías de cuentas'),
self::$DB->error);
}
$Log = new Log(_('Importar Categorías de Cuentas'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar las categorías en sysPass.
*
* @param array $accountCategory con los datos de la categoría
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertAccountsCategories($accountCategory)
{
$query = 'INSERT INTO categories SET category_id = :id,category_name = :name';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($accountCategory['intCategoryId'], 'id');
$Data->addParam($accountCategory['vacCategoryName'], 'name');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear categorías de cuentas'),
DB::$txtError);
}
return true;
}
/**
* Migrar los usuarios desde desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateUsers()
{
$query = 'SELECT intUserId,'
. 'vacUName,'
. 'intUGroupFid,'
. 'vacULogin,'
. 'vacUPassword,'
. 'vacUEmail,'
. 'txtUNotes,'
. 'intUCount,'
. 'intUProfile,'
. 'datULastLogin,'
. 'blnIsAdminApp,'
. 'blnIsAdminAcc,'
. 'vacUserMPwd,'
. 'vacUserMIv,'
. 'datULastUpdate,'
. 'datUserLastUpdateMPass,'
. 'blnFromLdap,'
. 'blnDisabled '
. 'FROM users '
. 'WHERE intUserId <> ' . Session::getUserId();
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertUsers($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener los usuarios'),
self::$DB->error);
}
$Log = new Log(_('Importar Usuarios'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar los usuarios en sysPass.
*
* @param array $users con los datos del usuario
* @throws \SP\Core\Exceptions\SPException
* @return bool
*
* El usuario importado está deshabilitado
*/
private static function insertUsers($users)
{
$query = 'INSERT INTO usrData '
. 'SET user_id = :id,'
. 'user_name = :name,'
. 'user_groupId = :goupId,'
. 'user_login = :login,'
. 'user_pass = :pass,'
. 'user_mPass = :mpass,'
. 'user_mIV = :miv,'
. 'user_email = :email,'
. 'user_notes = :notes,'
. 'user_count = :count,'
. 'user_profileId = 0,'
. 'user_lastLogin = :lastLogin,'
. 'user_lastUpdate = :lastUpdate,'
. 'user_lastUpdateMPass = :lastUpdateMPass,'
. 'user_isAdminApp = :isAdminApp,'
. 'user_isAdminAcc = :isAdminAcc,'
. 'user_isLdap = :isLdap,'
. 'user_isDisabled = 1,'
. 'user_isMigrate = 1';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($users['intUserId'], 'id');
$Data->addParam($users['vacUName'], 'name');
$Data->addParam($users['intUGroupFid'], 'groupId');
$Data->addParam($users['vacULogin'], 'login');
$Data->addParam($users['vacUPassword'], 'pass');
$Data->addParam($users['vacUserMPwd'], 'mpass');
$Data->addParam($users['vacUserMIv'], 'miv');
$Data->addParam($users['vacUEmail'], 'email');
$Data->addParam($users['txtUNotes'], 'notes');
$Data->addParam($users['intUCount'], 'count');
$Data->addParam($users['datULastLogin'], 'lastLogin');
$Data->addParam($users['datULastUpdate'], 'lastUpdate');
$Data->addParam($users['datUserLastUpdateMPass'], 'lastUpdateMPass');
$Data->addParam($users['blnIsAdminApp'], 'isAdminApp');
$Data->addParam($users['blnIsAdminAcc'], 'isAdminAcc');
$Data->addParam($users['blnFromLdap'], 'isLdap');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear usuarios'),
DB::$txtError);
}
return true;
}
/**
* Migrar los grupos de usuarios desde desde phpPMS.
*
* @throws \SP\Core\Exceptions\SPException
* @return array resultado
*/
private static function migrateUsersGroups()
{
$query = 'SELECT intUGroupId,vacUGroupName,vacUGroupDesc FROM usergroups';
$totalRecords = 0;
$num = 0;
try {
foreach(self::$DB->query($query) as $row){
if (self::insertUsersGroups($row)) {
$num++;
}
$totalRecords++;
}
} catch(\PDOException $e){
throw new SPException(SPException::SP_CRITICAL,
_('Error al obtener los grupos de usuarios'),
self::$DB->error);
}
$Log = new Log(_('Importar Grupos de Usuarios'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalRecords);
$Log->writeLog();
}
/**
* Insertar los grupos de usuarios en sysPass.
*
* @param array $usersGroups con los datos del grupo
* @throws \SP\Core\Exceptions\SPException
* @return bool
*/
private static function insertUsersGroups($usersGroups)
{
$query = 'INSERT INTO usrGroups '
. 'SET usergroup_id = :id,'
. 'usergroup_name = :name,'
. 'usergroup_description = :description';
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($usersGroups['intUGroupId'], 'id');
$Data->addParam($usersGroups['vacUGroupName'], 'name');
$Data->addParam($usersGroups['vacUGroupDesc'], 'description');
if (DB::getQuery($Data) === false) {
throw new SPException(SPException::SP_CRITICAL,
_('Error al crear los grupos de usuarios'),
DB::$txtError);
}
return true;
}
/**
* Migrar la configuración desde phpPMS.
*
* @return array resultado
*/
private static function migrateConfig()
{
// Obtener la configuración actual
self::getSourceConfig();
$skip = array('version',
'installed',
'install',
'dbhost',
'dbname',
'dbuser',
'dbpass',
'siteroot',
'sitelang',
'sitename',
'siteshortname',
'md5_pass',
'password_show',
'lastupdatempass',
'passwordsalt');
$totalParams = count(self::$oldConfig);
$num = 0;
// Guardar la nueva configuración
foreach (self::$oldConfig as $key => $value) {
if (array_key_exists($key, $skip)) {
continue;
}
// FIXME
// Config::setValue($key, $value);
$num++;
}
$Log = new Log(_('Importar Configuración'));
$Log->addDescription('OK');
$Log->addDetails(_('Registros'), $num . '/' . $totalParams);
$Log->writeLog();
}
}