* New customers management.

* Improved categories management by removing 'select'  by 'table' style layout.
* New permissions added for customers and categories management menu (needs DB update).
* Some methods have been refactored and made a bit of code cleanup
This commit is contained in:
nuxsmin
2014-02-05 01:21:44 +01:00
parent f5d9aa7a97
commit a5155636dd
30 changed files with 1150 additions and 822 deletions

View File

@@ -132,24 +132,22 @@ if ($frmSaveType == 1 || $frmSaveType == 4) {
}
$account = new SP_Account;
$customer = new SP_Customer;
switch ($frmSaveType) {
case 1:
$customer->customerId = $frmSelCustomer;
$customer->customerName = $frmNewCustomer;
SP_Customer::$customerName = $frmNewCustomer;
// Comprobar si se ha introducido un nuevo cliente
if ($frmNewCustomer) {
if (!$customer->chekDupCustomer()) {
if (!SP_Customer::checkDupCustomer()) {
SP_Common::printJSON(_('Cliente duplicado'));
}
if (!$customer->customerAdd()) {
if (!SP_Customer::addCustomer()) {
SP_Common::printJSON(_('Error al crear cliente'));
}
$account->accountCustomerId = $customer->customerLastId;
$account->accountCustomerId = SP_Customer::$customerLastId;
} else {
$account->accountCustomerId = $frmSelCustomer;
}
@@ -175,8 +173,7 @@ switch ($frmSaveType) {
SP_Common::printJSON(_('Error al crear la cuenta'), 0);
break;
case 2:
$customer->customerId = $frmSelCustomer;
$customer->customerName = $frmNewCustomer;
SP_Customer::$customerName = $frmNewCustomer;
$account->accountId = $frmAccountId;
$account->accountName = $frmName;
$account->accountCategoryId = $frmCategoryId;
@@ -191,15 +188,15 @@ switch ($frmSaveType) {
// Comprobar si se ha introducido un nuevo cliente
if ($frmNewCustomer) {
if (!$customer->chekDupCustomer()) {
if (!SP_Customer::checkDupCustomer()) {
SP_Common::printJSON(_('Cliente duplicado'));
}
if (!$customer->customerAdd()) {
if (!SP_Customer::addCustomer()) {
SP_Common::printJSON(_('Error al crear cliente'));
}
$account->accountCustomerId = $customer->customerLastId;
$account->accountCustomerId = SP_Customer::$customerLastId;
} else {
$account->accountCustomerId = $frmSelCustomer;
}

View File

@@ -66,6 +66,22 @@ switch ($itemType) {
$tplvars['header'] = _('Nuevo Perfil');
$template = 'profiles';
break;
case 7:
$tplvars['header'] = _('Editar Cliente');
$template = 'customers';
break;
case 8:
$tplvars['header'] = _('Nuevo Cliente');
$template = 'customers';
break;
case 9:
$tplvars['header'] = _('Editar Categoría');
$template = 'categories';
break;
case 10:
$tplvars['header'] = _('Nueva Categoría');
$template = 'categories';
break;
default :
break;
}

View File

@@ -44,9 +44,9 @@ $frmSaveType = SP_Common::parseParams('p', 'type', 0);
$frmAction = SP_Common::parseParams('p', 'action', 0);
$frmItemId = SP_Common::parseParams('p', 'id', 0);
$objUser = new SP_Users;
if ($frmSaveType == 1 || $frmSaveType == 2) {
$objUser = new SP_Users;
// Variables POST del formulario
$frmLdap = SP_Common::parseParams('p', 'ldap', 0);
$frmUsrName = SP_Common::parseParams('p', 'name');
@@ -121,8 +121,8 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Usuario creado'), 0);
}
}
SP_Common::printJSON(_('Error al crear el usuario'));
} elseif ($frmAction == 2) {
if ($objUser->updateUser()) {
@@ -134,17 +134,17 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Usuario actualizado'), 0);
}
SP_Common::printJSON(_('Error al actualizar el usuario'));
}
// Cambio de clave
// Cambio de clave
} elseif ($frmAction == 3) {
$userLogin = $objUser->getUserLoginById($frmItemId);
if ( SP_Config::getValue('demoenabled', 0) && $userLogin == 'demo'){
SP_Common::printJSON(_('Acción Inválida').'(DEMO)');
if (SP_Config::getValue('demoenabled', 0) && $userLogin == 'demo') {
SP_Common::printJSON(_('Acción Inválida') . '(DEMO)');
}
if (!$frmUsrPass || !$frmUsrPassV) {
SP_Common::printJSON(_('La clave no puede estar en blanco'), 2);
}
@@ -165,17 +165,17 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Clave actualizada'), 0);
}
SP_Common::printJSON(_('Error al modificar la clave'));
// Eliminar usuario
// Eliminar usuario
} elseif ($frmAction == 4) {
$userLogin = $objUser->getUserLoginById($frmItemId);
if ( SP_Config::getValue('demoenabled', 0) && $userLogin == 'demo' ){
SP_Common::printJSON(_('Acción Inválida').'(DEMO)');
if (SP_Config::getValue('demoenabled', 0) && $userLogin == 'demo') {
SP_Common::printJSON(_('Acción Inválida') . '(DEMO)');
}
$objUser->userId = $frmItemId;
if ($frmItemId == $_SESSION["uid"]) {
@@ -191,10 +191,10 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Usuario eliminado'), 0);
}
SP_Common::printJSON(_('Error al eliminar el usuario'));
}
}
SP_Common::printJSON(_('Acción Inválida'));
} elseif ($frmSaveType == 3 || $frmSaveType == 4) {
// Variables POST del formulario
@@ -210,7 +210,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Groups::$groupId = $frmItemId;
SP_Groups::$groupName = $frmGrpName;
SP_Groups::$groupDescription = $frmGrpDesc;
if (!SP_Groups::checkGroupExist()) {
SP_Common::printJSON(_('Nombre de grupo duplicado'), 2);
}
@@ -237,21 +237,29 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Grupo actualizado'), 0);
}
SP_Common::printJSON(_('Error al actualizar el grupo'));
}
// Eliminar grupo
// Eliminar grupo
} elseif ($frmAction == 4) {
SP_Groups::$groupId = $frmItemId;
$resGroupUse = SP_Groups::checkGroupInUse();
if ( $resGroupUse !== TRUE ) {
SP_Common::printJSON(_('No es posible eliminar:Grupo en uso por') . ' ' . $resGroupUse);
if ($resGroupUse['users'] > 0 || $resGroupUse['accounts'] > 0) {
if ($resGroupUse['users'] > 0) {
$uses[] = _('Usuarios') . " (" . $resGroupUse['users'] . ")";
}
if ($resGroupUse['accounts'] > 0) {
$uses[] = _('Cuentas') . " (" . $resGroupUse['accounts'] . ")";
}
SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Grupo en uso por:') . ';;' . implode(';;', $uses));
} else {
$groupName = SP_Groups::getGroupNameById($frmItemId);
if (SP_Groups::deleteGroup()) {
$message['action'] = _('Eliminar Grupo');
$message['text'][] = _('Nombre') . ': ' . $groupName;
@@ -261,7 +269,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Grupo eliminado'), 0);
}
SP_Common::printJSON(_('Error al eliminar el grupo'));
}
}
@@ -284,7 +292,8 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
$profileProp["pAccDel"] = SP_Common::parseParams('p', 'profile_accdel', 0, FALSE, 1);
$profileProp["pAccFiles"] = SP_Common::parseParams('p', 'profile_accfiles', 0, FALSE, 1);
$profileProp["pConfig"] = SP_Common::parseParams('p', 'profile_config', 0, FALSE, 1);
$profileProp["pConfigCat"] = SP_Common::parseParams('p', 'profile_configcat', 0, FALSE, 1);
$profileProp["pAppMgmtCat"] = SP_Common::parseParams('p', 'profile_categories', 0, FALSE, 1);
$profileProp["pAppMgmtCust"] = SP_Common::parseParams('p', 'profile_customers', 0, FALSE, 1);
$profileProp["pConfigMpw"] = SP_Common::parseParams('p', 'profile_configmpw', 0, FALSE, 1);
$profileProp["pConfigBack"] = SP_Common::parseParams('p', 'profile_configback', 0, FALSE, 1);
$profileProp["pUsers"] = SP_Common::parseParams('p', 'profile_users', 0, FALSE, 1);
@@ -314,7 +323,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Perfil creado'), 0);
}
SP_Common::printJSON(_('Error al crear el perfil'));
} else if ($frmAction == 2) {
if (SP_Profiles::updateProfile($profileProp)) {
@@ -326,19 +335,21 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Perfil actualizado'), 0);
}
SP_Common::printJSON(_('Error al actualizar el perfil'));
}
// Eliminar perfil
// Eliminar perfil
} elseif ($frmAction == 4) {
$resProfileUse = SP_Profiles::checkProfileInUse();
if (is_string($resProfileUse)) {
SP_Common::printJSON(_('No es posible eliminar: Perfil en uso por') . ' ' . $resProfileUse);
if ($resProfileUse['users'] > 0) {
$uses[] = _('Usuarios') . " (" . $resProfileUse['users'] . ")";
SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Perfil en uso por:') . ';;' . implode(';;', $uses));
} else {
$profileName = SP_Profiles::getProfileNameById($frmItemId);
if (SP_Profiles::deleteProfile()) {
$message['action'] = _('Eliminar Perfil');
$message['text'][] = _('Nombre') . ': ' . $profileName;
@@ -348,10 +359,110 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Common::printJSON(_('Perfil eliminado'), 0);
}
SP_Common::printJSON(_('Error al eliminar el perfil'));
}
}
SP_Common::printJSON(_('Acción Inválida'));
} elseif ($frmSaveType == 7 || $frmSaveType == 8) {
// Variables POST del formulario
$frmCustomerName = SP_Common::parseParams('p', 'name');
$frmCustomerDesc = SP_Common::parseParams('p', 'description');
// Nuevo cliente o editar
if ($frmAction == 1 OR $frmAction == 2) {
if (!$frmCustomerName) {
SP_Common::printJSON(_('Es necesario un nombre de cliente'), 2);
}
SP_Customer::$customerName = $frmCustomerName;
SP_Customer::$customerDescription = $frmCustomerDesc;
if (!SP_Customer::checkDupCustomer($frmItemId)) {
SP_Common::printJSON(_('Nombre de cliente duplicado'), 2);
}
if ($frmAction == 1) {
if (SP_Customer::addCustomer()) {
SP_Common::printJSON(_('Cliente creado'), 0);
} else {
SP_Common::printJSON(_('Error al crear el cliente'));
}
} else if ($frmAction == 2) {
if (SP_Customer::updateCustomer($frmItemId)) {
SP_Common::printJSON(_('Cliente actualizado'), 0);
}
SP_Common::printJSON(_('Error al actualizar el cliente'));
}
// Eliminar cliente
} elseif ($frmAction == 4) {
$resCustomerUse = SP_Customer::checkCustomerInUse($frmItemId);
if ($resCustomerUse['accounts'] > 0) {
$uses[] = _('Cuentas') . " (" . $resCustomerUse['accounts'] . ")";
SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Cliente en uso por:') . ';;' . implode(';;', $uses));
} else {
if (SP_Customer::delCustomer($frmItemId)) {
SP_Common::printJSON(_('Cliente eliminado'), 0);
}
SP_Common::printJSON(_('Error al eliminar el cliente'));
}
}
SP_Common::printJSON(_('Acción Inválida'));
} elseif ($frmSaveType == 9 || $frmSaveType == 10) {
// Variables POST del formulario
$frmCategoryName = SP_Common::parseParams('p', 'name');
$frmCategoryDesc = SP_Common::parseParams('p', 'description');
// Nueva categoría o editar
if ($frmAction == 1 OR $frmAction == 2) {
if (!$frmCategoryName) {
SP_Common::printJSON(_('Es necesario un nombre de categoría'), 2);
}
SP_Category::$categoryName = $frmCategoryName;
SP_Category::$categoryDescription = $frmCategoryDesc;
if (!SP_Category::checkDupCategory($frmItemId)) {
SP_Common::printJSON(_('Nombre de categoría duplicado'), 2);
}
if ($frmAction == 1) {
if (SP_Category::addCategory()) {
SP_Common::printJSON(_('Categpría creada'), 0);
} else {
SP_Common::printJSON(_('Error al crear la categoría'));
}
} else if ($frmAction == 2) {
if (SP_Category::updateCategory($frmItemId)) {
SP_Common::printJSON(_('Categoría actualizada'), 0);
}
SP_Common::printJSON(_('Error al actualizar la categoría'));
}
// Eliminar categoría
} elseif ($frmAction == 4) {
$resCategoryUse = SP_Category::checkCategoryInUse($frmItemId);
if ($resCategoryUse !== TRUE) {
SP_Common::printJSON(_('No es posible eliminar') . ';;' . _('Categoría en uso por:') . ';;' . $resCategoryUse);
} else {
if (SP_Category::delCategory($frmItemId)) {
SP_Common::printJSON(_('Categoría eliminada'), 0);
}
SP_Common::printJSON(_('Error al eliminar la categoría'));
}
}
SP_Common::printJSON(_('Acción Inválida'));
}

View File

@@ -1,111 +0,0 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 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/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
SP_Util::checkReferer('POST');
if ( ! SP_Init::isLoggedIn() ) {
SP_Common::printJSON(_('La sesión no se ha iniciado o ha caducado'),10);
}
$sk = SP_Common::parseParams('p', 'sk', FALSE);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$intCategoryFunction = SP_Common::parseParams('p', 'categoryFunction', 0);
$categoryName = SP_Common::parseParams('p', 'categoryName');
$categoryNameNew = SP_Common::parseParams('p', 'categoryNameNew');
$categoryId = SP_Common::parseParams('p', 'categoryId', 0);
switch ($intCategoryFunction) {
case 1:
if ($categoryName == "") {
SP_Common::printJSON(_('Nombre de categoría necesario'));
} else {
// Comprobamos si la categoría existe
if (SP_Category::getCategoryIdByName($categoryName) === 0) {
if (SP_Category::categoryAdd($categoryName)) {
SP_Common::printJSON(_('Categoría añadida'), 0);
}
SP_Common::printJSON(_('Error al añadir la categoría'));
}
SP_Common::printJSON(_('Ya existe una categoría con ese nombre'));
}
break;
case 2:
if ($categoryNameNew == "" || !$categoryId) {
SP_Common::printJSON(_('Nombre de categoría necesario'));
} else {
// Comprobamos si la categoría existe
if (SP_Category::getCategoryIdByName($categoryNameNew) !== 0) {
SP_Common::printJSON(_('Ya existe una categoría con ese nombre'));
} else {
// Obtenemos el nombre de la categoría por el Id
$oldCategoryName = SP_Category::getCategoryNameById($categoryId);
if (SP_Category::editCategoryById($categoryId, $categoryNameNew)) {
$message['action'] = _('Modificar Categoría');
$message['text'][] = _('Nombre') . ': ' . $oldCategoryName.' > '.$categoryNameNew;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Categoría modificada'), 0);
}
SP_Common::printJSON(_('Error al modificar la categoría'));
}
}
break;
case 3:
if (!$categoryId) {
SP_Common::printJSON(_('Nombre de categoría necesario'));
} else {
// Comprobamos si la categoría está en uso por una cuenta
if (SP_Category::isCategoryInUse($categoryId)) {
SP_Common::printJSON(_('Categoría en uso, no es posible eliminar'));
} else {
// Obtenemos el nombre de la categoría por el Id
$oldCategoryName = SP_Category::getCategoryNameById($categoryId);
if (SP_Category::categoryDel($categoryId)) {
$message['action'] = _('Eliminar Categoría');
$message['text'][] = _('Nombre') . ': ' .$oldCategoryName.' ('. $categoryId.')';
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Categoría eliminada'));
}
SP_Common::printJSON(_('Error al eliminar la categoría'));
}
}
break;
default:
SP_Common::printJSON(_('Acción Inválida'));
}

View File

@@ -127,17 +127,18 @@ switch ($action) {
),
'tblRowSrcId' => 'user_id',
'frmId' => 'frm_tblusers',
'nextaction' => $action,
'actionId' => 1,
'newActionId' => 2,
'active' => $tplvars['active'] ++,
'actions' => array('view', 'edit', 'del', 'pass'));
'actions' => array('view' => 'appMgmtData', 'edit' => 'appMgmtData', 'del' => 'appMgmtSave', 'pass' => 'usrUpdPass'));
echo '<DIV ID="tabs-1">';
$startTime = microtime();
$users = SP_Users::getUsers();
if ($users) {
SP_Users::getUsrGrpTable($arrUsersTableProp, $users);
SP_Html::getQueryTable($arrUsersTableProp, $users);
SP_Html::printQueryInfoBar(count($users), $startTime);
}
echo '</DIV>';
@@ -152,10 +153,11 @@ switch ($action) {
'tblRowSrc' => array('usergroup_name', 'usergroup_description'),
'tblRowSrcId' => 'usergroup_id',
'frmId' => 'frm_tblgroups',
'nextaction' => $action,
'actionId' => 3,
'newActionId' => 4,
'active' => $tplvars['active'] ++,
'actions' => array('edit', 'del'));
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave'));
echo '<DIV ID="tabs-2">';
@@ -163,7 +165,7 @@ switch ($action) {
$groups = SP_Groups::getGroups();
if ($groups) {
SP_Users::getUsrGrpTable($arrGroupsTableProp, $groups);
SP_Html::getQueryTable($arrGroupsTableProp, $groups);
SP_Html::printQueryInfoBar(count($groups), $startTime);
}
@@ -179,10 +181,11 @@ switch ($action) {
'tblRowSrc' => array('userprofile_name'),
'tblRowSrcId' => 'userprofile_id',
'frmId' => 'frm_tblprofiles',
'nextaction' => $action,
'actionId' => 5,
'newActionId' => 6,
'active' => $tplvars['active'] ++,
'actions' => array('edit', 'del'));
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave'));
echo '<DIV ID="tabs-3">';
@@ -190,7 +193,7 @@ switch ($action) {
$profiles = SP_Profiles::getProfiles();
if ($profiles) {
SP_Users::getUsrGrpTable($arrProfilesTableProp, $profiles);
SP_Html::getQueryTable($arrProfilesTableProp, $profiles);
SP_Html::printQueryInfoBar(count($profiles), $startTime);
}
@@ -209,14 +212,93 @@ switch ($action) {
});
</script>';
break;
case "appmgmtmenu":
echo '<DIV ID="tabs">';
echo '<UL>';
echo ( SP_ACL::checkUserAccess("categories") ) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Categorías') . '">' . _('Categorías') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("customers") ) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Clientes') . '">' . _('Clientes') . '</A></LI>' : '';
echo '</UL>';
$tplvars['active'] = 0;
if (SP_ACL::checkUserAccess("categories")) {
$arrCategoriesTableProp = array(
'itemName' => _('Categoría'),
'tblId' => 'tblCategories',
'header' => '',
'tblHeaders' => array(_('Nombre'),_('Descripción')),
'tblRowSrc' => array('category_name','category_description'),
'tblRowSrcId' => 'category_id',
'frmId' => 'frm_tblcategories',
'nextaction' => $action,
'actionId' => 9,
'newActionId' => 10,
'active' => $tplvars['active'] ++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave')
);
echo '<DIV ID="tabs-1">';
$startTime = microtime();
$categories = SP_Category::getCategories();
if ($categories) {
SP_Html::getQueryTable($arrCategoriesTableProp, $categories);
SP_Html::printQueryInfoBar(count($categories), $startTime);
}
echo '</DIV>';
}
if (SP_ACL::checkUserAccess("customers")) {
$arrCustomersTableProp = array(
'itemName' => _('Cliente'),
'tblId' => 'tblCustomers',
'header' => '',
'tblHeaders' => array(_('Nombre'),_('Descripción')),
'tblRowSrc' => array('customer_name','customer_description'),
'tblRowSrcId' => 'customer_id',
'frmId' => 'frm_tblcustomers',
'nextaction' => $action,
'actionId' => 7,
'newActionId' => 8,
'active' => $tplvars['active'] ++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave')
);
echo '<DIV ID="tabs-2">';
$startTime = microtime();
$customers = SP_Customer::getCustomers();
if ($customers) {
SP_Html::getQueryTable($arrCustomersTableProp, $customers);
SP_Html::printQueryInfoBar(count($customers), $startTime);
}
echo '</DIV>';
}
echo '</DIV>';
echo '<script>
$("#tabs").tabs({
active: ' . $itemId . ',
create: function( event, ui ) {$("input:visible:first").focus();},
activate: function( event, ui ) {
setContentSize();
$("input:visible:first").focus();
}
});
</script>';
break;
case "configmenu":
echo '<DIV ID="tabs">';
echo '<UL>';
echo ( SP_ACL::checkUserAccess("config") ) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Configuración') . '">' . _('Configuración') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("categories") ) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Categorías') . '">' . _('Categorías') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("masterpass") ) ? '<LI><A HREF="#tabs-3" TITLE="' . _('Clave Maestra') . '">' . _('Clave Maestra') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("backup") ) ? '<LI><A HREF="#tabs-4" TITLE="' . _('Copia de Seguridad') . '">' . _('Copia de Seguridad') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("config") ) ? '<LI><A HREF="#tabs-5" TITLE="' . _('Importar cuentas desde fuentes externas') . '">' . _('Importar Cuentas') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("masterpass") ) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Clave Maestra') . '">' . _('Clave Maestra') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("backup") ) ? '<LI><A HREF="#tabs-3" TITLE="' . _('Copia de Seguridad') . '">' . _('Copia de Seguridad') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("config") ) ? '<LI><A HREF="#tabs-4" TITLE="' . _('Importar cuentas desde fuentes externas') . '">' . _('Importar Cuentas') . '</A></LI>' : '';
echo '</UL>';
$tplvars['active'] = 0;
@@ -229,18 +311,10 @@ switch ($action) {
echo '</DIV>';
}
if (SP_ACL::checkUserAccess("categories")) {
$tplvars['active'] ++;
echo '<DIV ID="tabs-2">';
SP_Html::getTemplate('categories', $tplvars);
echo '</DIV>';
}
if (SP_ACL::checkUserAccess("masterpass")) {
$tplvars['active'] ++;
echo '<DIV ID="tabs-3">';
echo '<DIV ID="tabs-2">';
SP_Html::getTemplate('masterpass', $tplvars);
echo '</DIV>';
}
@@ -248,7 +322,7 @@ switch ($action) {
if (SP_ACL::checkUserAccess("backup")) {
$tplvars['active'] ++;
echo '<DIV ID="tabs-4">';
echo '<DIV ID="tabs-3">';
SP_Html::getTemplate('backup', $tplvars);
echo '</DIV>';
}
@@ -256,7 +330,7 @@ switch ($action) {
if (SP_ACL::checkUserAccess("config")) {
$tplvars['active'] ++;
echo '<DIV ID="tabs-5">';
echo '<DIV ID="tabs-4">';
SP_Html::getTemplate('migrate', $tplvars);
echo '</DIV>';
}

BIN
imgs/appmgmt.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View File

@@ -71,12 +71,16 @@ class SP_ACL {
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pDelete );
case "accfiles":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pFiles );
case "appmgmtmenu":
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtMenu );
case "configmenu":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigMenu );
case "config":
return ( $blnUIsAdminApp || $profile->userProfile_pConfig );
case "categories":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigCategories );
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtCategories );
case "customers":
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtCustomers );
case "masterpass":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigMasterPass );
case "backup":

View File

@@ -5,7 +5,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -23,27 +23,28 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones sobre las categorías de sysPass.
*/
class SP_Category {
public static $categoryName;
public static $categoryDescription;
public static $categoryLastId;
/**
* @brief Obtener el id de una categoría por el nombre
* @param string $categoryName con el nombre de la categoría
* @return bool|int si la consulta es errónea devuelve bool. Si no hay registros o se obtiene el id, devuelve int
*/
*/
public static function getCategoryIdByName($categoryName) {
$query = "SELECT category_id "
. "FROM categories "
. "WHERE category_name = '" . DB::escape($categoryName) . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ) {
if ($queryRes === FALSE) {
return FALSE;
}
@@ -58,19 +59,72 @@ class SP_Category {
* @brief Crear una nueva categoría en la BBDD
* @param string $categoryName con el nombre de la categoría
* @return bool
*/
public static function categoryAdd($categoryName) {
*/
public static function addCategory() {
$query = "INSERT INTO categories "
. "SET category_name = '" . DB::escape($categoryName) . "'";
. "SET category_name = '" . DB::escape(self::$categoryName) . "',"
. "category_description = '" . DB::escape(self::$categoryDescription) . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
self::$categoryLastId = DB::$lastId;
$message['action'] = _('Nueva Categoría');
$message['text'][] = _('Nombre') . ': ' . $categoryName;
$message['text'][] = _('Nombre') . ': ' . self::$categoryName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Comprobar si existe una categoría duplicada
* @param int $id con el Id de la categoría a consultar
* @return bool
*/
public static function checkDupCategory($id = NULL) {
if ($id === NULL) {
$query = "SELECT category_id "
. "FROM categories "
. "WHERE category_name = '" . DB::escape(self::$categoryName) . "'";
} else {
$query = "SELECT category_id "
. "FROM categories "
. "WHERE category_name = '" . DB::escape(self::$categoryName) . "' AND category_id <> " . $id;
}
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
}
return TRUE;
}
/**
* @brief Eliminar una categoría de la BBDD
* @param int $id con el id de la categoría
* @return bool
*/
public static function delCategory($id) {
$categoryName = self::getCategoryNameById($id);
$query = "DELETE FROM categories "
. "WHERE category_id = " . (int) $id . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
$message['action'] = _('Eliminar Categoría');
$message['text'][] = _('Nombre') . ': ' .$categoryName.' ('. $id.')';
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
@@ -78,95 +132,153 @@ class SP_Category {
return TRUE;
}
/**
* @brief Comprobar si una categoría está en uso por alguna cuenta
* @param int $categoryId con el id de la categoría
* @return bool
*/
public static function isCategoryInUse($categoryId) {
$query = "SELECT account_categoryId "
. "FROM accounts "
. "WHERE account_categoryId = " . (int) $categoryId;
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
return ( count(DB::$last_result) > 0 ) ? TRUE : FALSE;
}
/**
* @brief Eliminar una categoría de la BBDD
* @param int $categoryId con el id de la categoría
* @return bool
*/
public static function categoryDel($categoryId) {
$query = "DELETE FROM categories "
. "WHERE category_id = $categoryId LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
return TRUE;
}
/**
* @brief Actualizar una categoría en la BBDD con el id
* @param int $categoryId con el id de la categoría
* @param int $categoryNameNew con el nombre nuevo de la categoría
* @param int $id con el Id de la categoría a consultar
* @return bool
*/
public static function editCategoryById($categoryId, $categoryNameNew) {
public static function updateCategory($id) {
$categoryName = self::getCategoryNameById($id);
$query = "UPDATE categories "
. "SET category_name = '" . DB::escape($categoryNameNew) . "' "
. "WHERE category_id = " . (int) $categoryId . " LIMIT 1";
. "SET category_name = '" . DB::escape(self::$categoryName) . "',"
. "category_description = '" . DB::escape(self::$categoryDescription) . "' "
. "WHERE category_id = " . (int) $id . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
$message['action'] = _('Modificar Categoría');
$message['text'][] = _('Nombre') . ': ' . $categoryName.' > '.self::$categoryName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Obtiene el listado de categorías
* @param int $id con el Id de la categoría
* @param bool $retAssocArray para devolver un array asociativo
* @return array con en id de categorioa como clave y en nombre como valor
*/
public static function getCategories(){
*/
public static function getCategories($id = NULL, $retAssocArray = FALSE) {
$query = "SELECT category_id,"
. "category_name "
. "FROM categories "
. "ORDER BY category_name";
. "category_name,"
. "category_description "
. "FROM categories ";
if (!is_null($id)) {
$query .= "WHERE category_id = " . (int) $id . " LIMIT 1";
} else {
$query .= "ORDER BY category_name";
}
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ( $queryRes === FALSE ){
if ($queryRes === FALSE) {
return array();
}
$resCategories = array();
foreach ( $queryRes as $category ){
$resCategories[$category->category_id] = $category->category_name;
if ($retAssocArray) {
$resCategories = array();
foreach ($queryRes as $category) {
$resCategories[$category->category_id] = $category->category_name;
}
return $resCategories;
}
return $resCategories;
return $queryRes;
}
/**
* @brief Obtiene el nombre de la categoría a partir del Id
* @param int $id con el Id de la categoría a consultar
* @return string con el nombre de la categoría
*/
public static function getCategoryNameById($id) {
$query = "SELECT category_name "
. "FROM categories "
. "WHERE category_id = " . (int) $id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes->category_name;
}
/**
* @brief Obtener los datos de una categoría
* @param int $id con el Id de la categoría a consultar
* @return array con el nombre de la columna como clave y los datos como valor
*/
public static function getCategoryData($id = 0) {
$category = array('category_id' => 0,
'category_name' => '',
'category_description' => '',
'action' => 1);
if ($id > 0) {
$categories = self::getCategories($id);
if ($categories) {
foreach ($categories[0] as $name => $value) {
$category[$name] = $value;
}
$category['action'] = 2;
}
}
return $category;
}
/**
* @brief Obtiene el nombre de la categoría a partir del Id
* @return string con el nombre de la categoría
*/
public static function getCategoryNameById($id){
$query = "SELECT category_name "
. "FROM categories "
. "WHERE category_id = ".(int)$id;
* @brief Comprobar si una categoría está en uso
* @param int $id con el Id de la categoría a consultar
* @return bool
*
* Esta función comprueba si una categoría está en uso por cuentas.
*/
public static function checkCategoryInUse($id) {
$numAccounts = self::getCategoriesInAccounts($id);
$out = '';
if ($numAccounts) {
$out[] = _('Cuentas') . " (" . $numAccounts . ")";
}
if (is_array($out)) {
return implode('<br>', $out);
}
return TRUE;
}
/**
* @brief Obtener el número de cuentas que usan una categoría
* @param int $id con el Id de la categoría a consultar
* @return integer con el número total de cuentas
*/
private static function getCategoriesInAccounts($id) {
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_categoryId = " . (int) $id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ){
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes->category_name;
return $queryRes->uses;
}
}
}

View File

@@ -1,151 +1,280 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 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/>.
*
*/
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2014 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/>.
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones sobre los clientes de sysPass
*/
class SP_Customer{
class SP_Customer {
var $customerId;
var $customerName;
var $customerDescription;
var $customerLastId;
var $customerHash;
public static $customerName;
public static $customerDescription;
public static $customerLastId;
public static $customerHash;
/**
* @brief Obtener el listado de clientes
* @param int $customerId con el Id del cliente
* @param bool $retAssocArray para devolver un array asociativo
* @return array con el id de cliente como clave y el nombre como valor
*/
public static function getCustomers(){
*/
public static function getCustomers($customerId = NULL, $retAssocArray = FALSE) {
$query = "SELECT customer_id,"
. "customer_name "
. "FROM customers "
. "ORDER BY customer_name";
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ( $queryRes === FALSE ){
return FALSE;
}
$resCustomers = array();
foreach ( $queryRes as $customer ){
$resCustomers[$customer->customer_id] = $customer->customer_name;
. "customer_name, "
. "customer_description "
. "FROM customers ";
if (!is_null($customerId)) {
$query .= "WHERE customer_id = " . (int) $customerId . " LIMIT 1";
} else {
$query .= "ORDER BY customer_name";
}
return $resCustomers;
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ($queryRes === FALSE) {
return FALSE;
}
if ($retAssocArray) {
$resCustomers = array();
foreach ($queryRes as $customer) {
$resCustomers[$customer->customer_id] = $customer->customer_name;
}
return $resCustomers;
}
return $queryRes;
}
/**
* @brief Crear un nuevo cliente en la BBDD
* @return bool
*/
public function customerAdd(){
*/
public static function addCustomer() {
$query = "INSERT INTO customers "
. "SET customer_name = '".DB::escape($this->customerName)."',"
. "customer_hash = '".$this->mkCustomerHash()."'";
if ( DB::doQuery($query, __FUNCTION__) === FALSE ){
. "SET customer_name = '" . DB::escape(self::$customerName) . "',"
. "customer_hash = '" . self::mkCustomerHash() . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
$this->customerLastId = DB::$lastId;
self::$customerLastId = DB::$lastId;
$message['action'] = _('Nuevo Cliente');
$message['text'][] = _('Nombre').': '.$this->customerName;
$message['text'][] = _('Nombre') . ': ' . self::$customerName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Actualizar un cliente en la BBDD
* @return bool
*/
public static function updateCustomer($id) {
$query = "UPDATE customers "
. "SET customer_name = '" . DB::escape(self::$customerName) . "',"
. "customer_description = '" . DB::escape(self::$customerDescription) . "',"
. "customer_hash = '" . self::mkCustomerHash() . "' "
. "WHERE customer_id = " . (int) $id;
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
$message['action'] = _('Actualizar Cliente');
$message['text'][] = _('Nombre') . ': ' . self::$customerName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Eliminar un cliente de la BBDD
* @param int $id con el Id del cliente a eliminar
* @return bool
*/
public function customerDel(){
$query = "DELETE FROM customers"
. " WHERE customer_id = $this->customerId LIMIT 1";
if ( DB::doQuery($query, __FUNCTION__) === FALSE ){
*/
public static function delCustomer($id) {
$customerName = self::getCustomerById($id);
$query = "DELETE FROM customers "
. "WHERE customer_id = " . (int) $id . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
$message['action'] = _('Eliminar Cliente');
$message['text'][] = _('Nombre') . ': ' . $customerName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Crear un hash con el nombre del cliente
* @return string con el hash generado
*
* Esta función crear un hash para detectar clientes duplicados mediante
* la eliminación de carácteres especiales y capitalización
*/
private function mkCustomerHash(){
$charsSrc = array("."," ","_",",","-",";","'","\"",":","(",")","|","/");
$newValue = strtolower(str_replace($charsSrc, '', DB::escape($this->customerName)));
*/
private static function mkCustomerHash() {
$charsSrc = array(
".", " ", "_", ", ", "-", ";
", "'", "\"", ":", "(", ")", "|", "/");
$newValue = strtolower(str_replace($charsSrc, '', DB::escape(self::$customerName)));
$hashValue = md5($newValue);
return $hashValue;
return $hashValue;
}
/**
* @brief Comprobar si existe un cliente duplicado comprobando el hash
* @return bool
*/
public function chekDupCustomer(){
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '".$this->mkCustomerHash()."'";
if ( DB::doQuery($query, __FUNCTION__) === FALSE ){
return FALSE;
*/
public static function checkDupCustomer($id = NULL) {
if ($id === NULL) {
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '" . self::mkCustomerHash() . "'";
} else {
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '" . self::mkCustomerHash() . "' AND customer_id <> " . $id;
}
if ( count(DB::$last_result) >= 1 ){
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
}
return TRUE;
}
/**
* @brief Obtener el Id de un cliente por su nombre
* @return int con el Id del cliente
*/
public function getCustomerByName(){
*/
public static function getCustomerByName() {
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '".$this->mkCustomerHash()."' LIMIT 1";
. "WHERE customer_hash = '" . self::mkCustomerHash() . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ){
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes->customer_id;
}
/**
* @brief Obtener el Nombre de un cliente por su Id
* @param int $id con el Id del cliente
* @return string con el nombre del cliente
*/
public static function getCustomerById($id) {
$query = "SELECT customer_name "
. "FROM customers "
. "WHERE customer_id = " . (int) $id . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes->customer_name;
}
/**
* @brief Obtener los datos de un cliente
* @param int $id con el Id del cliente a consultar
* @return array con el nombre de la columna como clave y los datos como valor
*/
public static function getCustomerData($id = 0) {
$customer = array('customer_id' => 0,
'customer_name' => '',
'customer_description' => '',
'action' => 1);
if ($id > 0) {
$customers = self::getCustomers($id);
if ($customers) {
foreach ($customers[0] as $name => $value) {
$customer[$name] = $value;
}
$customer['action'] = 2;
}
}
return $customer;
}
/**
* @brief Comprobar si un cliente está en uso
* @param int $id con el Id del cliente a consultar
* @return bool
*
* Esta función comprueba si un cliente está en uso por cuentas.
*/
public static function checkCustomerInUse($id) {
$count['accounts'] = self::getCustomerInAccounts($id);
return $count;
}
/**
* @brief Obtener el número de cuentas que usan un cliente
* @param int $id con el Id del cliente a consultar
* @return integer con el número total de cuentas
*/
private static function getCustomerInAccounts($id) {
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_customerId = " . (int) $id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes->uses;
}
}

View File

@@ -1,76 +1,78 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 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/>.
*
*/
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 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/>.
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Esta clase es la encargada de realizar las operaciones con la BBDD de sysPass.
*/
class DB {
private static $_db;
static $last_result;
static $affected_rows;
static $lastId;
static $txtError;
static $numError;
static $num_rows;
function __construct(){ }
function __construct() {
}
/**
* @brief Realizar la conexión con la BBDD
* @return bool
*
* Esta función utiliza mysqli para conectar con la base de datos.
* Guarda el objeto creado en la variable $_db de la clase
*/
private static function connection(){
if ( self::$_db ){
*/
private static function connection() {
if (self::$_db) {
return true;
}
$dbhost = SP_Config::getValue("dbhost");
$dbuser = SP_Config::getValue("dbuser");
$dbpass = SP_Config::getValue("dbpass");
$dbname = SP_Config::getValue("dbname");
self::$_db = @new mysqli($dbhost,$dbuser,$dbpass,$dbname);
if ( self::$_db->connect_errno ){
if ( SP_Config::getValue("installed") ){
if ( self::$_db->connect_errno === 1049 ){
self::$_db = @new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (self::$_db->connect_errno) {
if (SP_Config::getValue("installed")) {
if (self::$_db->connect_errno === 1049) {
SP_Config::setValue('installed', '0');
}
SP_Init::initError(_('No es posible conectar con la BD'),'Error '.self::$_db->connect_errno . ': '.self::$_db->connect_error);
} else{
SP_Init::initError(_('No es posible conectar con la BD'), 'Error ' . self::$_db->connect_errno . ': ' . self::$_db->connect_error);
} else {
return false;
}
}
return true;
return true;
}
/**
@@ -79,9 +81,9 @@ class DB {
* @return string con la cadena escapada
*
* Esta función utiliza mysqli para escapar cadenas de texto.
*/
*/
public static function escape($str) {
if ( self::connection() ){
if (self::connection()) {
return self::$_db->real_escape_string(trim($str));
} else {
return $str;
@@ -93,104 +95,137 @@ class DB {
* @param string $query con la consulta a realizar
* @param string $querySource con el nombre de la función que realiza la consulta
* @return bool|int devuleve bool si hay un error. Devuelve int con el número de registros
*/
public static function doQuery($query,$querySource) {
if ( ! self::connection() ){
*/
public static function doQuery($query, $querySource) {
if (!self::connection()) {
return false;
}
$isSelect = preg_match("/^.*(select|show)\s/i",$query);
$isSelect = preg_match("/^.*(select|show)\s/i", $query);
// Limpiar valores de caché
self::$last_result = array();
$queryRes = self::$_db->query($query);
if ( ! $queryRes ) {
if (!$queryRes) {
self::$numError = self::$_db->errno;
self::$txtError = self::$_db->error;
$message['action'] = $querySource;
$message['text'][] = self::$_db->error.'('.self::$_db->errno.')';
$message['text'][] = "SQL: ".self::escape($query);
$message['text'][] = self::$_db->error . '(' . self::$_db->errno . ')';
$message['text'][] = "SQL: " . self::escape($query);
SP_Common::wrLogInfo($message);
return FALSE;
}
if ( $isSelect ) {
if ( $queryRes->num_rows == 1 ){
if ($isSelect) {
if ($queryRes->num_rows == 1) {
self::$last_result = @$queryRes->fetch_object();
} else {
$num_row = 0;
while ( $row = @$queryRes->fetch_object() ) {
while ($row = @$queryRes->fetch_object()) {
self::$last_result[$num_row] = $row;
$num_row++;
}
}
self::$num_rows = $queryRes->num_rows;
$queryRes->close();
}
self::$lastId = self::$_db->insert_id;
$numRows = self::$_db->affected_rows;
return $numRows;
}
/**
* @brief Obtener los resultados de una consulta
* @param string $query con la consulta a realizar
* @param string $querySource con el nombre de la función que realiza la consulta
* @return bool|array devuelve bool si hay un error. Devuelve array con el array de registros devueltos
*/
*/
public static function getResults($query, $querySource, $retArray = FALSE) {
if ( $query ){
self::doQuery($query,$querySource);
if ($query) {
self::doQuery($query, $querySource);
}
if ( self::$numError || self::$num_rows === 0) {
if (self::$numError || self::$num_rows === 0) {
return FALSE;
}
if ( is_null(self::$numError) && count(self::$last_result) === 0 ){
if (is_null(self::$numError) && count(self::$last_result) === 0) {
return TRUE;
}
if ( $retArray === TRUE && is_object(self::$last_result) ){
if ($retArray === TRUE && is_object(self::$last_result)) {
return array(self::$last_result);
}
return self::$last_result;
}
/**
* @brief Comprobar que la base de datos existe
* @return bool
*/
public static function checkDatabaseExist(){
if ( ! self::connection() ){
*/
public static function checkDatabaseExist() {
if (!self::connection()) {
return false;
}
$query='SELECT COUNT(*) '
$query = 'SELECT COUNT(*) '
. 'FROM information_schema.tables'
." WHERE table_schema='".SP_Config::getValue("dbname")."' "
. " WHERE table_schema='" . SP_Config::getValue("dbname") . "' "
. "AND table_name = 'usrData';";
$resquery = self::$_db->query($query);
if( $resquery ) {
if ($resquery) {
$row = $resquery->fetch_row();
}
if( ! $resquery || $row[0] == 0) {
if (!$resquery || $row[0] == 0) {
return false;
}
return true;
}
}
/**
* @brief Obtener los datos para generar un select
* @param string $tblName con el nombre de la tabla a cunsultar
* @param string $tblColId con el nombre de la columna a mostrar
* @param array $arrFilter con las columnas a filtrar
* @param array $arrOrder con el orden de las columnas
* @return array con los valores del select con el Id como clave y el nombre como valor
*/
public static function getValuesForSelect($tblName, $tblColId, $tblColName, $arrFilter = '', $arrOrder = '') {
if (!$tblName || !$tblColId || !$tblColName) {
return;
}
$strFilter = ( is_array($arrFilter) ) ? " WHERE " . implode(" OR ", $arrFilter) : "";
$strOrder = ( is_array($arrOrder) ) ? " ORDER BY " . implode(",", $arrOrder) : 'ORDER BY ' . $tblColName . ' ASC';
$query = "SELECT $tblColId, $tblColName FROM $tblName $strFilter $strOrder";
$queryRes = self::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
$arrValues = array();
foreach ($queryRes as $row) {
$arrValues[$row->$tblColId] = $row->$tblColName;
}
return $arrValues;
}
}

View File

@@ -26,7 +26,7 @@ CREATE TABLE `accFiles` (
`accfile_extension` varchar(10) NOT NULL,
PRIMARY KEY (`accfile_id`),
KEY `IDX_accountId` (`accfile_accountId`)
) ENGINE=MyISAM AUTO_INCREMENT=61 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=62 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -42,7 +42,7 @@ CREATE TABLE `accGroups` (
`accgroup_groupId` int(10) unsigned NOT NULL,
PRIMARY KEY (`accgroup_id`),
KEY `IDX_accountId` (`accgroup_accountId`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
) ENGINE=MyISAM AUTO_INCREMENT=69 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -77,7 +77,7 @@ CREATE TABLE `accHistory` (
`accHistory_otherGroupEdit` varchar(45) DEFAULT NULL,
PRIMARY KEY (`acchistory_id`),
KEY `IDX_accountId` (`acchistory_accountId`)
) ENGINE=MyISAM AUTO_INCREMENT=264 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=285 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -127,7 +127,7 @@ CREATE TABLE `accounts` (
KEY `IDX_userId` (`account_userGroupId`,`account_userId`),
KEY `IDX_customerId` (`account_customerId`),
FULLTEXT KEY `IDX_searchTxt` (`account_name`,`account_login`,`account_url`,`account_notes`)
) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=44 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -140,8 +140,9 @@ DROP TABLE IF EXISTS `categories`;
CREATE TABLE `categories` (
`category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`category_name` varchar(50) NOT NULL,
`category_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf16;
) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf16;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -172,7 +173,7 @@ CREATE TABLE `customers` (
`customer_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`customer_id`),
KEY `IDX_name` (`customer_name`,`customer_hash`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -190,7 +191,7 @@ CREATE TABLE `log` (
`log_action` varchar(50) NOT NULL,
`log_description` text NOT NULL,
PRIMARY KEY (`log_id`)
) ENGINE=MyISAM AUTO_INCREMENT=79 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=640 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -225,7 +226,7 @@ CREATE TABLE `usrData` (
PRIMARY KEY (`user_id`),
UNIQUE KEY `IDX_login` (`user_login`),
KEY `IDX_pass` (`user_pass`)
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -240,7 +241,7 @@ CREATE TABLE `usrGroups` (
`usergroup_name` varchar(50) NOT NULL,
`usergroup_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`usergroup_id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -257,7 +258,6 @@ CREATE TABLE `usrProfiles` (
`userProfile_pEdit` bit(1) DEFAULT b'0',
`userProfile_pAdd` bit(1) DEFAULT b'0',
`userProfile_pConfig` bit(1) DEFAULT b'0',
`userProfile_pConfigCategories` bit(1) DEFAULT b'0',
`userProfile_pConfigMasterPass` bit(1) DEFAULT b'0',
`userProfile_pConfigBackup` bit(1) DEFAULT b'0',
`userProfile_pUsers` bit(1) DEFAULT b'0',
@@ -271,8 +271,11 @@ CREATE TABLE `usrProfiles` (
`userProfile_pFiles` bit(1) DEFAULT b'0',
`userProfile_pConfigMenu` bit(1) DEFAULT b'0',
`userProfile_pUsersMenu` bit(1) DEFAULT b'0',
`userProfile_pAppMgmt` bit(1) DEFAULT b'0',
`userProfile_pAppMgmtCategories` bit(1) DEFAULT b'0',
`userProfile_pAppMgmtCustomers` bit(1) DEFAULT b'0',
PRIMARY KEY (`userprofile_id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
@@ -282,5 +285,4 @@ CREATE TABLE `usrProfiles` (
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

View File

@@ -179,35 +179,19 @@ class SP_Groups {
self::$queryLastId = DB::$lastId;
return TRUE;
// return TRUE;
}
/**
* @brief Comprobar si un grupo está en uso
* @return bool
* @return array con el número de usuarios/cuentas que usan el grupo
*
* Esta función comprueba si un grupo está en uso por usuarios o cuentas.
*/
public static function checkGroupInUse() {
$numUsers = self::getGroupInUsers();
$numAccounts = self::getGroupInAccounts() + self::getGroupInAccountsSec();
$out = '';
if ($numUsers) {
$out[] = _('Usuarios') . " (" . $numUsers . ")";
}
if ($numAccounts) {
$out[] = _('Cuentas') . " (" . $numAccounts . ")";
}
if (is_array($out)) {
return implode('<br>', $out);
}
return TRUE;
$count['users'] = self::getGroupInUsers();
$count['accounts'] = self::getGroupInAccounts() + self::getGroupInAccountsSec();
return $count;
}
/**
@@ -233,7 +217,7 @@ class SP_Groups {
* @return integer con el número total de cuentas
*/
private static function getGroupInAccounts() {
$query = "SELECT COUNT(*) as uses"
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_userGroupId = " . (int) self::$groupId;

View File

@@ -5,7 +5,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -91,7 +91,7 @@ class SP_Html {
*/
public static function render($page = "main", $err = NULL) {
$data['showlogo'] = 1;
// UTF8 Headers
header("Content-Type: text/html; charset=UTF-8");
@@ -110,7 +110,7 @@ class SP_Html {
foreach (self::$htmlPage as $html) {
if (is_array($html) && array_key_exists('include', $html)) {
self::getTemplate($html['include'],$data);
self::getTemplate($html['include'], $data);
} else {
echo $html . PHP_EOL;
}
@@ -146,9 +146,9 @@ class SP_Html {
self::$htmlPage[] = '<div id="wrap">';
self::$htmlPage[] = '<noscript><div id="nojs">' . _('Javascript es necesario para el correcto funcionamiento') . '</div></noscript>';
self::$htmlPage[] = '<div id="container" class="' . $page . '">';
self::$htmlPage[] = array('include' => $page);
self::$htmlPage[] = '</div> <!-- Close container -->';
self::makeFooter($page);
self::$htmlPage[] = '</div> <!-- Close wrap -->';
@@ -254,7 +254,7 @@ class SP_Html {
* @return string con los datos limpiados
*/
public static function sanitize(&$data) {
if (!$data){
if (!$data) {
return FALSE;
}
@@ -326,7 +326,7 @@ class SP_Html {
$versionParameter = md5(implode(SP_Util::getVersion()));
$js_files = self::getJs();
foreach ($js_files as $js) {
self::$htmlPage[] = '<script type="text/javascript" src="' . SP_Init::$WEBROOT . "/" . $js["src"] . '?v=' . $versionParameter . $js["params"] . '"></script>';
}
@@ -351,10 +351,10 @@ class SP_Html {
array("src" => "js/jquery.tagsinput.js", "params" => ""),
array("src" => "js/functions.php", "params" => "&l=" . SP_Init::$LANG . "&r=" . urlencode(base64_encode(SP_Init::$WEBROOT)))
);
return $jsProp;
}
/**
* @brief Devuelve información sobre la aplicación
* @return array con las propiedades de la aplicación
@@ -444,19 +444,19 @@ class SP_Html {
exit();
}
private static function minifier($files){
if ( !is_array($files) ){
private static function minifier($files) {
if (!is_array($files)) {
return FALSE;
}
foreach ($files as $file){
foreach ($files as $file) {
//$output_min .= file_get_contents($file['src']);
include_once SP_Init::$SERVERROOT.'/'.$file['src'];
include_once SP_Init::$SERVERROOT . '/' . $file['src'];
}
//return $output_min;
}
/**
* @brief Convertir un color RGB a HEX
* @param array $rgb con color en RGB
@@ -465,11 +465,105 @@ class SP_Html {
* From: http://bavotasan.com/2011/convert-hex-color-to-rgb-using-php/
*/
public static function rgb2hex($rgb) {
$hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);
$hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);
return $hex; // returns the hex value including the number sign (#)
}
}
return $hex; // returns the hex value including the number sign (#)
}
/**
* @brief Devolver una tabla con el resultado de una consulta y acciones
* @param array $arrTableProp con las propiedades de la tabla
* @return none
*/
public static function getQueryTable($arrTableProp, $queryItems) {
$sk = SP_Common::getSessionKey(TRUE);
echo '<div class="action fullWidth">';
echo '<ul>';
echo '<LI><img src="imgs/add.png" title="' . _('Nuevo') . ' ' . $arrTableProp['itemName'] . '" class="inputImg" OnClick="' . $arrTableProp["actions"]['edit'] . '(0,' . $arrTableProp["newActionId"] . ',\'' . $sk . '\',' . $arrTableProp["active"] . ',0,\'' . $arrTableProp["nextaction"] . '\');" /></LI>';
echo '</ul>';
echo '</div>';
if ($arrTableProp["header"]) {
echo '<div id="title" class="midroundup titleNormal">' . $arrTableProp["header"] . '</div>';
}
echo '<form name="' . $arrTableProp["frmId"] . '" id="' . $arrTableProp["frmId"] . '" OnSubmit="return false;" >';
echo '<div id="' . $arrTableProp["tblId"] . '" class="data-header" >';
echo '<ul class="round header-grey">';
$cellWidth = floor(65 / count($arrTableProp["tblHeaders"]));
foreach ($arrTableProp["tblHeaders"] as $header) {
if (is_array($header)) {
echo '<li class="' . $header['class'] . '" style="width: ' . $cellWidth . '%;">' . $header['name'] . '</li>';
} else {
echo '<li style="width: ' . $cellWidth . '%;">' . $header . '</li>';
}
}
echo '</ul>';
echo '</div>';
echo '<div class="data-rows">';
foreach ($queryItems as $item) {
$intId = $item->$arrTableProp["tblRowSrcId"];
$action_check = array();
$numActions = count($arrTableProp["actions"]);
$classActionsOptional = ( $numActions > 2 ) ? 'actions-optional' : '';
echo '<ul>';
foreach ($arrTableProp["tblRowSrc"] as $rowSrc) {
// If row is an array handle images in it
if (is_array($rowSrc)) {
echo '<li class="cell-nodata" style="width: ' . $cellWidth . '%;">';
foreach ($rowSrc as $rowName => $imgProp) {
if ($item->$rowName) {
echo '<img src="imgs/' . $imgProp['img_file'] . '" title="' . $imgProp['img_title'] . '" />';
$action_check[$rowName] = 1;
}
}
echo '</li>';
} else {
echo '<li class="cell-data" style="width: ' . $cellWidth . '%;">';
echo ( $item->$rowSrc ) ? $item->$rowSrc : '&nbsp;'; // Fix height
echo '</li>';
}
}
echo '<li class="cell-actions round" style="width: ' . ($numActions * 5 + 2) . '%;">';
//echo '<li class="cell-actions round" style="width: 175px;">';
foreach ($arrTableProp["actions"] as $action => $function) {
switch ($action) {
case "view":
echo '<img src="imgs/view.png" title="' . _('Ver Detalles') . '" class="inputImg" Onclick="return ' . $arrTableProp["actions"]['view'] . '(' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrTableProp["active"] . ',1,\'' . $arrTableProp["nextaction"] . '\');" />';
break;
case "edit":
echo '<img src="imgs/edit.png" title="' . _('Editar') . ' ' . $arrTableProp['itemName'] . '" class="inputImg" Onclick="return ' . $arrTableProp["actions"]['edit'] . '(' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrTableProp["active"] . ',0,\'' . $arrTableProp["nextaction"] . '\');" />';
break;
case "del":
echo '<img src="imgs/delete.png" title="' . _('Eliminar') . ' ' . $arrTableProp['itemName'] . '" class="inputImg ' . $classActionsOptional . '" Onclick="return ' . $arrTableProp["actions"]['del'] . '(' . $arrTableProp["active"] . ', 1,' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\',\'' . $arrTableProp["nextaction"] . '\');" />';
break;
case "pass":
if (isset($action_check['user_isLdap'])) {
break;
}
echo '<img src="imgs/key.png" title="' . _('Cambiar clave') . '" class="inputImg ' . $classActionsOptional . '" Onclick="return ' . $arrTableProp["actions"]['pass'] . '(' . $intId . ');" />';
break;
}
}
echo ($numActions > 2 ) ? '<img src="imgs/action.png" title="' . _('Más Acciones') . '" OnClick="showOptional(this)" />' : '';
echo '</li>';
echo '</ul>';
}
echo '</div></form>';
}
}

View File

@@ -136,7 +136,6 @@ class SP_Import {
$groupId = SP_Common::parseParams('s', 'ugroup', 0);
$account = new SP_Account;
$customer = new SP_Customer;
foreach (self::$fileContent as $data) {
$fields = explode(';', $data);
@@ -147,17 +146,17 @@ class SP_Import {
list($accountName, $customerName, $categoryName, $url, $username, $password, $notes) = $fields;
$customer->customerName = $customerName;
if ( ! $customer->chekDupCustomer() ){
$customerId = $customer->getCustomerByName();
SP_Customer::$customerName = $customerName;
if ( !SP_Customer::checkDupCustomer() ){
$customerId = SP_Customer::getCustomerByName();
} else{
$customer->customerAdd();
$customerId = $customer->customerLastId;
SP_Customer::addCustomer();
$customerId = SP_Customer::$customerLastId;
}
$categoryId = SP_Category::getCategoryIdByName($categoryName);
if ( $categoryId == 0 ){
SP_Category::categoryAdd($categoryName);
SP_Category::addCategory($categoryName);
$categoryId = SP_Category::$categoryLastId;
}

View File

@@ -458,7 +458,7 @@ class SP_Init {
$update = FALSE;
$configVersion = (int) str_replace('.', '', SP_Config::getValue('version'));
$databaseVersion = (int) str_replace('.', '', SP_Config::getConfigValue('version'));
$appVersion = (int) implode(SP_Util::getVersion());
$appVersion = (int) implode(SP_Util::getVersion(TRUE));
if ( $databaseVersion < $appVersion && SP_Common::parseParams('g', 'nodbupgrade', 0) === 0){
if ( SP_Upgrade::needUpgrade($appVersion) && ! self::checkMaintenanceMode(TRUE) ){

View File

@@ -246,20 +246,19 @@ class SP_Migrate {
*/
private static function migrateCustomers() {
$customers = self::getCustomers();
$objCustomer = new SP_Customer;
$totalRecords = count($customers);
$num = 0;
foreach ($customers as $customer) {
$objCustomer->customerName = $customer;
SP_Customer::$customerName = $customer;
if (!$objCustomer->chekDupCustomer()) {
if (!SP_Customer::checkDupCustomer()) {
$num++;
continue;
}
if (!$objCustomer->customerAdd()) {
if (!SP_Customer::addCustomer()) {
throw new MigrateException('critical',
_('No es posible crear el cliente'),
_('Contacte con el desarrollador'));
@@ -330,7 +329,7 @@ class SP_Migrate {
*/
private static function insertAccounts($account) {
if (!is_array(self::$customersByName)) {
$customers = SP_Customer::getCustomers();
$customers = SP_Customer::getCustomers(NULL,TRUE);
self::$customersByName = array_flip($customers);
}
@@ -481,7 +480,7 @@ class SP_Migrate {
*/
private static function insertAccountsHistory($accountHistory) {
if (!is_array(self::$customersByName)) {
$customers = SP_Customer::getCustomers();
$customers = SP_Customer::getCustomers(NULL,TRUE);
self::$customersByName = array_flip($customers);
}

View File

@@ -53,9 +53,10 @@ class SP_Profiles {
'userProfile_pDelete' => 0,
'userProfile_pFiles' => 0,
'userProfile_pConfig' => 0,
'userProfile_pConfigCategories' => 0,
'userProfile_pConfigMasterPass' => 0,
'userProfile_pConfigBackup' => 0,
'userProfile_pAppMgmtCategories' => 0,
'userProfile_pAppMgmtCustomers' => 0,
'userProfile_pUsers' => 0,
'userProfile_pGroups' => 0,
'userProfile_pProfiles' => 0,
@@ -99,9 +100,10 @@ class SP_Profiles {
. 'userProfile_pDelete,'
. 'userProfile_pFiles,'
. 'userProfile_pConfig,'
. 'userProfile_pConfigCategories,'
. 'userProfile_pConfigMasterPass,'
. 'userProfile_pConfigBackup,'
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. 'userProfile_pUsers,'
. 'userProfile_pGroups,'
. 'userProfile_pProfiles,'
@@ -160,7 +162,8 @@ class SP_Profiles {
*/
public static function addProfile($profileProp = '') {
$enableConfig = (int) ( $profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$enableusers = (int) ( $profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
$enableAppMgmt = (int) ( $profileProp["pAppMgmt"] || $profileProp["pAppMgmtCat"] || $profileProp["pAppMgmtCust"]);
$enableUsers = (int) ( $profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
$query = "INSERT INTO usrProfiles SET "
. "userprofile_name = '" . DB::escape(self::$profileName) . "',"
@@ -174,10 +177,12 @@ class SP_Profiles {
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigCategories = " . $profileProp["pConfigCat"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "userProfile_pUsersMenu = " . $enableusers . ","
. "userProfile_pAppMgmtMenu = " . $enableAppMgmt . ","
. "userProfile_pAppMgmtCategories = " . $profileProp["pAppMgmtCat"] . ","
. "userProfile_pAppMgmtCustomers = " . $profileProp["pAppMgmtCust"] . ","
. "userProfile_pUsersMenu = " . $enableUsers . ","
. "userProfile_pUsers = " . $profileProp["pUsers"] . ","
. "userProfile_pGroups = " . $profileProp["pGroups"] . ","
. "userProfile_pProfiles = " . $profileProp["pProfiles"] . ","
@@ -198,7 +203,8 @@ class SP_Profiles {
*/
public static function updateProfile($profileProp = '') {
$enableConfig = (int) ( $profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$enableusers = (int) ( $profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
$enableAppMgmt = (int) ( $profileProp["pAppMgmt"] || $profileProp["pAppMgmtCat"] || $profileProp["pAppMgmtCust"]);
$enableUsers = (int) ( $profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
$query = "UPDATE usrProfiles SET "
. "userprofile_name = '" . DB::escape(self::$profileName) . "',"
@@ -212,10 +218,12 @@ class SP_Profiles {
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigCategories = " . $profileProp["pConfigCat"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "userProfile_pUsersMenu = " . $enableusers . ","
. "userProfile_pAppMgmtMenu = " . $enableAppMgmt . ","
. "userProfile_pAppMgmtCategories = " . $profileProp["pAppMgmtCat"] . ","
. "userProfile_pAppMgmtCustomers = " . $profileProp["pAppMgmtCust"] . ","
. "userProfile_pUsersMenu = " . $enableUsers . ","
. "userProfile_pUsers = " . $profileProp["pUsers"] . ","
. "userProfile_pGroups = " . $profileProp["pGroups"] . ","
. "userProfile_pProfiles = " . $profileProp["pProfiles"] . ","
@@ -253,20 +261,8 @@ class SP_Profiles {
* @return mixed string con el número de usuarios, o bool si no está en uso
*/
public static function checkProfileInUse() {
$numUsers = self::getProfileInUsers();
$out = '';
if ($numUsers) {
$out[] = _('Usuarios') . " (" . $numUsers . ")";
}
if (is_array($out)) {
return implode('<br>', $out);
}
return TRUE;
$count['users'] = self::getProfileInUsers();
return $count;
}
/**
@@ -330,9 +326,10 @@ class SP_Profiles {
. "userProfile_pFiles,"
. "userProfile_pConfigMenu,"
. "userProfile_pConfig,"
. "userProfile_pConfigCategories,"
. "userProfile_pConfigMasterPass,"
. "userProfile_pConfigBackup,"
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. "userProfile_pUsersMenu,"
. "userProfile_pUsers,"
. "userProfile_pGroups,"

View File

@@ -181,7 +181,7 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
<td class="valField">
<?php
if ( $showform ){
SP_Html::printSelect(SP_Customer::getCustomers(), $customersSelProp);
SP_Html::printSelect(DB::getValuesForSelect('customers', 'customer_id', 'customer_name'), $customersSelProp);
?>
<br><br>
<input type="text" name="customer_new" maxlength="50" placeholder="<?php echo _('Buscar en desplegable o introducir'); ?>" />
@@ -197,7 +197,7 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
<td class="valField">
<?php
if ( $showform ){
SP_Html::printSelect(SP_Category::getCategories(), $categoriesSelProp);
SP_Html::printSelect(DB::getValuesForSelect('categories', 'category_id', 'category_name'), $categoriesSelProp);
} else{
echo $accountData->category_name;
}
@@ -267,7 +267,9 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
<?php
if ( $action != 'accnew' ){
foreach (SP_Users::getUsersIdName() as $otherUserName => $otherUserId) {
$users = array_flip(DB::getValuesForSelect('usrData', 'user_id', 'user_name'));
foreach ( $users as $otherUserName => $otherUserId) {
$userSelected = '';
if ($otherUserId != $accountData->account_userGroupId && $otherUserId != $userId) {
@@ -292,7 +294,9 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
<select id="selGroups" name="othergroups[]" multiple="multiple">
<?php
if ( $action != 'accnew' ){
foreach (SP_Groups::getGroups(NULL, TRUE) as $groupName => $groupId) {
$groups = array_flip(DB::getValuesForSelect('usrGroups', 'usergroup_id', 'usergroup_name'));
foreach ($groups as $groupName => $groupId) {
$uGroupSelected = '';
if ($groupId != $accountData->account_userGroupId && $groupId != $userGroupId) {
@@ -394,7 +398,7 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
</tr>
<tr>
<td class="descField"><?php echo _('Creador'); ?></td>
<td class="valField"><?php echo $accountData->user_name; ?></td>
<td class="valField"><?php echo ($accountData->user_name) ? $accountData->user_name : _('N/D'); ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Grupo Principal'); ?></td>
@@ -450,7 +454,7 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
</tr>
<tr>
<td class="descField"><?php echo _('Editor'); ?></td>
<td class="valField"><?php echo $accountData->user_editName; ?></td>
<td class="valField"><?php echo ($accountData->user_editName) ? $accountData->user_editName : _('N/D'); ?></td>
</tr>
<?php endif; ?>
</table>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -25,89 +25,42 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$action = $data['action'];
$category = SP_Category::getCategoryData($data['itemid']);
$activeTab = $data['active'];
SP_ACL::checkUserAccess($action) || SP_Html::showCommonError('unavailable');
$categoriesSelProp1 = array ( "name" => "categoryId",
"id" => "sel-edit_categories",
"class" => "",
"size" => 1,
"label" => "",
"selected" => "",
"default" => "",
"js" => "",
"attribs" => "");
$categoriesSelProp2 = array ( "name" => "categoryId",
"id" => "sel-del_categories",
"class" => "",
"size" => 1,
"label" => "",
"selected" => "",
"default" => "",
"js" => "",
"attribs" => "");
$skey = SP_Common::getSessionKey(TRUE);
?>
<table class="data tblConfig round">
<tr>
<td class="descField">
<?php echo _('Nueva categoría'); ?>
</td>
<td class="valField">
<form OnSubmit="return configMgmt('addcat');" method="post" name="frmAddCategory" id="frmAddCategory">
<input type="text" name="categoryName" maxlength="50">
<input type="image" src="imgs/add.png" title="<?php echo _('Nueva categoría'); ?>" class="inputImg" id="btnAdd" />
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="categoryFunction" value="1">
<input type="hidden" name="sk" value="<?php echo $skey; ?>">
</form>
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Modificar categoría'); ?>
</td>
<td class="valField">
<form OnSubmit="return configMgmt('editcat');" method="post" name="frmEditCategory" id="frmEditCategory">
<?php SP_Html::printSelect(SP_Category::getCategories(), $categoriesSelProp1); ?>
<br>
<br>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="text" name="categoryNameNew" maxlength="50" >
<input type="hidden" name="categoryFunction" value="2">
<input type="hidden" name="sk" value="<?php echo $skey; ?>">
<input type="image" src="imgs/save.png" title="<?php echo _('Guardar'); ?>" class="inputImg" id="btnGuardar" />
</form>
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Borrar categoría'); ?>
</td>
<td class="valField">
<form OnSubmit="return configMgmt('delcat');" method="post" name="frmDelCategory" id="frmDelCategory">
<?php SP_Html::printSelect(SP_Category::getCategories(), $categoriesSelProp2); ?>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="categoryFunction" value="3">
<input type="hidden" name="sk" value="<?php echo $skey; ?>">
<input type="image" src="imgs/delete.png" title="<?php echo _('Borrar categoría'); ?>" class="inputImg" />
</form>
</td>
</tr>
</table>
<script>
$("#sel-edit_categories").chosen({
placeholder_text_single: "<?php echo _('Seleccionar Categoría'); ?>",
disable_search_threshold: 10,
no_results_text: "<?php echo _('Sin resultados'); ?>"});
$("#sel-del_categories").chosen({
placeholder_text_single: "<?php echo _('Seleccionar Categoría'); ?>",
disable_search_threshold: 10,
no_results_text: "<?php echo _('Sin resultados'); ?>"});
</script>
<div id="fancyContainer" align="center">
<h2 class="midround"><?php echo $data['header']; ?></H2>
<form method="post" name="frmCategories" id="frmCategories">
<table class="fancydata">
<tbody>
<tr>
<td class="descField"><?php echo _('Nombre'); ?></td>
<td class="valField">
<input type="text" id="grpname" name="name" title="<?php echo _('Nombre de la categoría'); ?>" value="<?php echo $category["category_name"] ?>" />
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Descripción'); ?></td>
<td class="valField"><input type="text" id="grpdesc" name="description" title="<?php echo _('Descripción de la categoría'); ?>" value="<?php echo $category["category_description"]; ?>" />
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="id" value="<?php echo $category["category_id"]; ?>" />
<input type="hidden" name="action" value="<?php echo $category["action"] ?>" />
<input type="hidden" name="nextaction" value="<?php echo $data["nextaction"] ?>" />
<input type="hidden" name="type" value="<?php echo $data['itemtype']; ?>" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE) ?>">
<input type="hidden" name="is_ajax" value="1">
</form>
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">
<ul>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmCategories');" /></li>
</ul>
</div>
</div>

66
inc/tpl/customers.php Normal file
View File

@@ -0,0 +1,66 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 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/>.
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$customer = SP_Customer::getCustomerData($data['itemid']);
$activeTab = $data['active'];
?>
<div id="fancyContainer" align="center">
<h2 class="midround"><?php echo $data['header']; ?></H2>
<form method="post" name="frmCustomers" id="frmCustomers">
<table class="fancydata">
<tbody>
<tr>
<td class="descField"><?php echo _('Nombre'); ?></td>
<td class="valField">
<input type="text" id="grpname" name="name" title="<?php echo _('Nombre del cliente'); ?>" value="<?php echo $customer["customer_name"] ?>" />
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Descripción'); ?></td>
<td class="valField"><input type="text" id="grpdesc" name="description" title="<?php echo _('Descripción del cliente'); ?>" value="<?php echo $customer["customer_description"]; ?>" />
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="id" value="<?php echo $customer["customer_id"]; ?>" />
<input type="hidden" name="action" value="<?php echo $customer["action"] ?>" />
<input type="hidden" name="nextaction" value="<?php echo $data["nextaction"] ?>" />
<input type="hidden" name="type" value="<?php echo $data['itemtype']; ?>" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE) ?>">
<input type="hidden" name="is_ajax" value="1">
</form>
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">
<ul>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmCustomers');" /></li>
</ul>
</div>
</div>

View File

@@ -59,7 +59,7 @@ $activeTab = $data['active'];
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">
<ul>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="usersMgmt('frmGroups');" /></li>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmGroups');" /></li>
</ul>
</div>
</div>

View File

@@ -52,6 +52,7 @@ $chpass = ( ! isset($_SESSION['uisldap']) || $_SESSION['uisldap'] == 0 ) ? '<img
array('name' => 'accsearch', 'title' => _('Buscar'), 'img' => 'search.png', 'checkaccess' => 0),
array('name' => 'accnew', 'title' => _('Nueva Cuenta'), 'img' => 'add.png', 'checkaccess' => 1),
array('name' => 'usersmenu', 'title' => _('Gestión de Usuarios'), 'img' => 'users.png', 'checkaccess' => 1),
array('name' => 'appmgmtmenu', 'title' => _('Gestión de Clientes y Categorías'), 'img' => 'appmgmt.png', 'checkaccess' => 0),
array('name' => 'configmenu', 'title' => _('Configuración'), 'img' => 'config.png', 'checkaccess' => 1),
array('name' => 'eventlog', 'title' => _('Registro de Eventos'), 'img' => 'log.png', 'checkaccess' => 1)
);

View File

@@ -72,11 +72,9 @@ $activeTab = $data['active'];
<div id="btnProfilesConfig" class="btn-checks round5">
<label for="profile_config" title="<?php echo _('Configuración general'); ?>"><?php echo _('General'); ?></label>
<input type="checkbox" id="profile_config" name="profile_config" <?php echo $profile['userProfile_pConfig']; ?> />
<label for="profile_configcat" title="<?php echo _('Gestión de categorías'); ?>"><?php echo _('Categorías'); ?></label>
<input type="checkbox" id="profile_configcat" name="profile_configcat" <?php echo $profile['userProfile_pConfigCategories']; ?> />
<br>
<label for="profile_configmpw" title="<?php echo _('Cambiar clave maestra'); ?>"><?php echo _('Clave Maestra'); ?></label>
<input type="checkbox" id="profile_configmpw" name="profile_configmpw" <?php echo $profile['userProfile_pConfigMasterPass']; ?> />
<br>
<label for="profile_configback" title="<?php echo _('Realizar copia de seguridad'); ?>"><?php echo _('Backup'); ?></label>
<input type="checkbox" id="profile_configback" name="profile_configback" <?php echo $profile['userProfile_pConfigBackup']; ?> />
</div>
@@ -93,6 +91,11 @@ $activeTab = $data['active'];
<br>
<label for="profile_profiles" title="<?php echo _('Gestión de perfiles'); ?>"><?php echo _('Perfiles'); ?></label>
<input type="checkbox" id="profile_profiles" name="profile_profiles" <?php echo $profile['userProfile_pProfiles']; ?> />
<label for="profile_categories" title="<?php echo _('Gestión de categorías'); ?>"><?php echo _('Categorías'); ?></label>
<input type="checkbox" id="profile_categories" name="profile_categories" <?php echo $profile['userProfile_pAppMgmtCategories']; ?> />
<br>
<label for="profile_customers" title="<?php echo _('Gestión de clientes'); ?>"><?php echo _('Clientes'); ?></label>
<input type="checkbox" id="profile_customers" name="profile_customers" <?php echo $profile['userProfile_pAppMgmtCustomers']; ?> />
</div>
</td>
</tr>
@@ -126,7 +129,7 @@ $activeTab = $data['active'];
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">
<ul>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="usersMgmt('frmProfiles');" /></li>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmProfiles');" /></li>
</ul>
</div>
</div>

View File

@@ -68,8 +68,8 @@ $searchOrder = SP_Common::parseParams('s', 'accountSearchOrder', 0);
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="is_ajax" value="1">
<?php
SP_Html::printSelect(SP_Customer::getCustomers(), $customersSelProp);
SP_Html::printSelect(SP_Category::getCategories(), $categoriesSelProp);
SP_Html::printSelect(DB::getValuesForSelect('customers', 'customer_id', 'customer_name'), $customersSelProp);
SP_Html::printSelect(DB::getValuesForSelect('categories', 'category_id', 'category_name'), $categoriesSelProp);
?>
<br>
</td>

View File

@@ -96,14 +96,14 @@ $ro = ( $user['checks']['user_isLdap'] ) ? "READONLY" : "";
<tr>
<td class="descField"><?php echo _('Perfil'); ?></td>
<td class="valField">
<?php SP_Html::printSelect(SP_Users::getValuesForSelect('usrProfiles', 'userprofile_id', 'userprofile_name'), $profilesSelProp); ?>
<?php SP_Html::printSelect(DB::getValuesForSelect('usrProfiles', 'userprofile_id', 'userprofile_name'), $profilesSelProp); ?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Grupo'); ?></td>
<td class="valField">
<?php SP_Html::printSelect(SP_Users::getValuesForSelect('usrGroups', 'usergroup_id', 'usergroup_name'), $groupsSelProp); ?>
<?php SP_Html::printSelect(DB::getValuesForSelect('usrGroups', 'usergroup_id', 'usergroup_name'), $groupsSelProp); ?>
</td>
</tr>
@@ -203,7 +203,7 @@ $ro = ( $user['checks']['user_isLdap'] ) ? "READONLY" : "";
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">
<ul>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="usersMgmt('frmUsers');" /></li>
<li><img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmUsers');" /></li>
</ul>
</div>
<?php endif; ?>

View File

@@ -30,7 +30,7 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
*/
class SP_Upgrade {
private static $result = array();
private static $upgrade = array(110);
private static $upgrade = array(110,1121);
/**
* @brief Inicia el proceso de actualización de la BBDD
@@ -75,6 +75,10 @@ class SP_Upgrade {
$queries[] = "ALTER TABLE `accHistory` ADD COLUMN `accHistory_otherUserEdit` BIT NULL AFTER `acchistory_mPassHash`, ADD COLUMN `accHistory_otherGroupEdit` VARCHAR(45) NULL AFTER `accHistory_otherUserEdit`;";
$queries[] = "ALTER TABLE `accFiles` CHANGE COLUMN `accfile_type` `accfile_type` VARCHAR(100) NOT NULL ;";
break;
case 1121:
$queries[] = "ALTER TABLE `categories` ADD COLUMN `category_description` VARCHAR(255) NULL AFTER `category_name`;";
$queries[] = "ALTER TABLE `usrProfiles` ADD COLUMN `userProfile_pAppMgmtMenu` BIT(1) NULL DEFAULT b'0' AFTER `userProfile_pUsersMenu`,CHANGE COLUMN `userProfile_pConfigCategories` `userProfile_pAppMgmtCategories` BIT(1) NULL DEFAULT b'0' AFTER `userProfile_pAppMgmtMenu`,ADD COLUMN `userProfile_pAppMgmtCustomers` BIT(1) NULL DEFAULT b'0' AFTER `userProfile_pAppMgmtCategories`;";
break;
default :
self::$result['text'][] = _('No es necesario actualizar la Base de Datos.');
return TRUE;

View File

@@ -172,136 +172,6 @@ class SP_Users {
return $queryRes;
}
/**
* @brief Obtener los datos para generar un select
* @param string $tblName con el nombre de la tabla a cunsultar
* @param string $tblColId con el nombre de la columna a mostrar
* @param array $arrFilter con las columnas a filtrar
* @return array con los valores del select con el Id como clave y el nombre como valor
*/
public static function getValuesForSelect($tblName, $tblColId, $tblColName, $arrFilter = "") {
if (!$tblName || !$tblColId || !$tblColName) {
return;
}
$strFilter = ( is_array($arrFilter) ) ? " WHERE " . implode(" OR ", $arrFilter) : "";
$query = "SELECT $tblColId, $tblColName FROM $tblName $strFilter";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
$arrValues = array();
foreach ($queryRes as $row) {
$arrValues[$row->$tblColId] = $row->$tblColName;
}
return $arrValues;
}
/**
* @brief Devolver la tabla de usuarios, grupos o perfiles
* @param array $arrUsersTableProp con las propiedades de la tabla
* @return none
*/
public static function getUsrGrpTable($arrUsersTableProp, $queryItems = NULL) {
$sk = SP_Common::getSessionKey(TRUE);
echo '<div class="action fullWidth">';
echo '<ul>';
echo '<LI><img src="imgs/add.png" title="' . _('Nuevo') . ' ' . $arrUsersTableProp['itemName'] . '" class="inputImg" OnClick="usersData(0,' . $arrUsersTableProp["newActionId"] . ',\'' . $sk . '\',' . $arrUsersTableProp["active"] . ');" /></LI>';
echo '</ul>';
echo '</div>';
if ($arrUsersTableProp["header"]) {
echo '<div id="title" class="midroundup titleNormal">' . $arrUsersTableProp["header"] . '</div>';
}
echo '<form name="' . $arrUsersTableProp["frmId"] . '" id="' . $arrUsersTableProp["frmId"] . '" OnSubmit="return false;" >';
echo '<div id="' . $arrUsersTableProp["tblId"] . '" class="data-header" >';
echo '<ul class="round header-grey">';
$cellWidth = floor(65 / count($arrUsersTableProp["tblHeaders"]));
foreach ($arrUsersTableProp["tblHeaders"] as $header) {
if (is_array($header)) {
echo '<li class="' . $header['class'] . '" style="width: ' . $cellWidth . '%;">' . $header['name'] . '</li>';
} else {
echo '<li style="width: ' . $cellWidth . '%;">' . $header . '</li>';
}
}
echo '</ul>';
echo '</div>';
echo '<div class="data-rows">';
if (!is_null($queryItems)){
$items = $queryItems;
} else{
$items = self::$queryRes;
}
foreach ( $items as $item) {
$intId = $item->$arrUsersTableProp["tblRowSrcId"];
$action_check = array();
$numActions = count($arrUsersTableProp["actions"]);
$classActionsOptional = ( $numActions > 2 ) ? 'actions-optional' : '';
$lnkView = '<img src="imgs/view.png" title="' . _('Ver Detalles') . '" class="inputImg" Onclick="return usersData(' . $intId . ',' . $arrUsersTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrUsersTableProp["active"] . ',1);" />';
$lnkEdit = '<img src="imgs/edit.png" title="' . _('Editar') . ' ' . $arrUsersTableProp['itemName'] . '" class="inputImg" Onclick="return usersData(' . $intId . ',' . $arrUsersTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrUsersTableProp["active"] . ');" />';
$lnkDel = '<img src="imgs/delete.png" title="' . _('Eliminar') . ' ' . $arrUsersTableProp['itemName'] . '" class="inputImg '.$classActionsOptional.'" Onclick="return usersMgmt(' . $arrUsersTableProp["active"] . ', 1,' . $intId . ',' . $arrUsersTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrUsersTableProp["active"] . ');" />';
$lnkPass = '<img src="imgs/key.png" title="' . _('Cambiar clave') . '" class="inputImg '.$classActionsOptional.'" Onclick="return usrUpdPass(' . $intId . ');" />';
echo '<ul>';
foreach ($arrUsersTableProp["tblRowSrc"] as $rowSrc) {
// If row is an array handle images in it
if (is_array($rowSrc)) {
echo '<li class="cell-nodata" style="width: ' . $cellWidth . '%;">';
foreach ($rowSrc as $rowName => $imgProp) {
if ($item->$rowName) {
echo '<img src="imgs/' . $imgProp['img_file'] . '" title="' . $imgProp['img_title'] . '" />';
$action_check[$rowName] = 1;
}
}
echo '</li>';
} else {
echo '<li class="cell-data" style="width: ' . $cellWidth . '%;">';
echo ( $item->$rowSrc ) ? $item->$rowSrc : '&nbsp;'; // Fix height
echo '</li>';
}
}
echo '<li class="cell-actions round" style="width: ' . ($numActions * 5 + 2) . '%;">';
//echo '<li class="cell-actions round" style="width: 175px;">';
foreach ($arrUsersTableProp["actions"] as $action) {
switch ($action) {
case "view":
echo $lnkView;
break;
case "edit":
echo $lnkEdit;
break;
case "del":
echo $lnkDel;
break;
case "pass":
echo (!isset($action_check['user_isLdap']) ) ? $lnkPass : '';
break;
}
}
echo ($numActions > 2 ) ? '<img src="imgs/action.png" title="'._('Más Acciones').'" OnClick="showOptional(this)" />' : '';
echo '</li>';
echo '</ul>';
}
echo '</div></form>';
}
/**
* @brief Obtener los datos de un usuario
* @param int $id con el Id del usuario a consultar
@@ -965,25 +835,4 @@ class SP_Users {
return TRUE;
}
/**
* @brief Obtiene el listado de usuarios
* @return array con los registros con nombre de usuario como clave e id de usuario como valor
*/
public static function getUsersIdName(){
$query = "SELECT user_id,"
. "user_name "
. "FROM usrData";
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ( $queryRes === FALSE ){
return FALSE;
}
foreach ( $queryRes as $users ){
$arrUsers[$users->user_name] = $users->user_id;
}
return $arrUsers;
}
}

View File

@@ -168,8 +168,15 @@ class SP_Util {
* @brief Devuelve la versión de sysPass
* @return array con el número de versión
*/
public static function getVersion() {
return array(1, 1, 02);
public static function getVersion($retBuild = FALSE) {
$build = 1;
$version = array(1, 1, 2);
if ( $retBuild ){
array_push($version, $build);
}
return $version;
}
/**

View File

@@ -654,58 +654,8 @@ function importFile(sk){
});
}
// Función para mostrar los registros de usuarios y grupos
function usersData(id, type, sk, active, view){
var data = {'id' : id, 'type' : type, 'sk' : sk, 'active' : active, 'view' : view, 'is_ajax' : 1};
var url = APP_ROOT + '/ajax/ajax_usersMgmt.php';
$.fancybox.showLoading();
$.ajax({
type: 'POST',
dataType: 'html',
url: url,
data: data,
success: function(response){
$.fancybox(response,{
padding: [0,10,10,10],
afterClose: function(){doAction('usersmenu','',active);}
});
},
error:function(jqXHR, textStatus, errorThrown){
var txt = LANG[1] + '<p>' + errorThrown + textStatus + '</p>';
resMsg("error", txt);
},
complete: function(){$.fancybox.hideLoading();}
});
}
// Función para editar los registros de usuarios y grupos
function usersMgmt(frmId, isDel, id, type, sk){
var data;
var url = '/ajax/ajax_usersSave.php';
if ( isDel === 1 ){
var data = {'id' : id, 'type' : type, 'action' : 4, 'sk' : sk };
var atext = '<div id="alert"><p id="alert-text">' + LANG[12] + '</p></div>';
var active = frmId;
alertify.confirm(atext, function (e) {
if (e) {
usersAjax(data, url);
doAction('usersmenu','',active)
}
});
} else {
data = $("#" + frmId).serialize();
//type = parseInt($('input:[name=type]').val());
usersAjax(data, url);
}
}
// Función para realizar la petición ajax de gestión de usuarios
function usersAjax(data, url){
// Función para realizar la petición ajax
function sendAjax(data, url){
$.fancybox.showLoading();
$.ajax({
@@ -772,6 +722,55 @@ function usrUpdPass(id,usrlogin){
});
}
// Función para mostrar los datos de un registro
function appMgmtData(id, type, sk, active, view, nextaction){
var data = {'id' : id, 'type' : type, 'sk' : sk, 'active' : active, 'view' : view, 'is_ajax' : 1};
var url = APP_ROOT + '/ajax/ajax_appMgmtData.php';
$.fancybox.showLoading();
$.ajax({
type: 'POST',
dataType: 'html',
url: url,
data: data,
success: function(response){
$.fancybox(response,{
padding: [0,10,10,10],
afterClose: function(){doAction(nextaction,'',active);}
});
},
error:function(jqXHR, textStatus, errorThrown){
var txt = LANG[1] + '<p>' + errorThrown + textStatus + '</p>';
resMsg("error", txt);
},
complete: function(){$.fancybox.hideLoading();}
});
}
// Función para editar los datos de un registro
function appMgmtSave(frmId, isDel, id, type, sk, nextaction){
var data;
var url = '/ajax/ajax_appMgmtSave.php';
if ( isDel === 1 ){
var data = {'id' : id, 'type' : type, 'action' : 4, 'sk' : sk };
var atext = '<div id="alert"><p id="alert-text">' + LANG[12] + '</p></div>';
var active = frmId;
alertify.confirm(atext, function (e) {
if (e) {
sendAjax(data, url);
doAction(nextaction,'',active)
}
});
} else {
data = $("#" + frmId).serialize();
sendAjax(data, url);
}
}
// Función para verificar si existen actualizaciones
function checkUpds(){
$.ajax({