- Closes #26. Enable users password reset by email and forced by an admin.

- Improved email handling by using phpmailer class. All emails are sent in HTML format and security and authentication are available.
- Improved javascript code by code refactoring.
- Client IP address is logged in event log.
- Translation fixes.
- Minor bugfixes.
- Needs database upgrade (read wiki if unsure).
This commit is contained in:
nuxsmin
2014-02-24 01:51:23 +01:00
parent b4f937e01b
commit 0f172ed1d8
72 changed files with 11589 additions and 5205 deletions

5
.gitignore vendored
View File

@@ -1,5 +0,0 @@
/config/config.php
/nbproject/
/res/
/backup/
/patches/

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,8 +23,9 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +33,7 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
@@ -52,8 +53,8 @@ $frmOtherGroups = SP_Common::parseParams('p', 'othergroups');
$frmOtherUsers = SP_Common::parseParams('p', 'otherusers');
$frmNotes = SP_Common::parseParams('p', 'notice');
$frmUrl = SP_Common::parseParams('p', 'url');
$frmGroupEditEnabled = SP_Common::parseParams('p', 'geditenabled', 0, FALSE, 1);
$frmUserEditEnabled = SP_Common::parseParams('p', 'ueditenabled', 0, FALSE, 1);
$frmGroupEditEnabled = SP_Common::parseParams('p', 'geditenabled', 0, false, 1);
$frmUserEditEnabled = SP_Common::parseParams('p', 'ueditenabled', 0, false, 1);
$frmChangesHash = SP_Common::parseParams('p', 'hash');
// Datos del Usuario
@@ -108,7 +109,7 @@ if ($frmSaveType == 1) {
SP_Common::printJSON(_('Las claves no coinciden'));
}
} else {
$SP_Common::printJSON(_('Acción Inválida'));
SP_Common::printJSON(_('Acción Inválida'));
}
if ($frmSaveType == 1 || $frmSaveType == 4) {
@@ -124,7 +125,7 @@ if ($frmSaveType == 1 || $frmSaveType == 4) {
//$accountURL = $crypt->mkEncrypt($frmUrl, $crypt->getSessionMasterPass());
//$accountNotes = $crypt->mkEncrypt($frmNotes, $crypt->getSessionMasterPass());
if ($accountPass === FALSE || is_null($accountPass)) {
if ($accountPass === false || is_null($accountPass)) {
SP_Common::printJSON(_('Error al generar datos cifrados'));
}
@@ -217,7 +218,7 @@ switch ($frmSaveType) {
// Eliminar cuenta
if ($account->deleteAccount()) {
SP_Common::printJSON(_('Cuenta eliminada'), 0);
SP_Common::printJSON(_('Cuenta eliminada'), 0, "doAction('accsearch');");
}
SP_Common::printJSON(_('Error al eliminar la cuenta'));
break;

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,10 +32,10 @@ if (!SP_Init::isLoggedIn()) {
SP_Util::logout();
}
if ( SP_Common::parseParams('p', 'id', FALSE, TRUE) && SP_Common::parseParams('p', 'type', FALSE, TRUE) ) {
if ( SP_Common::parseParams('p', 'id', false, true) && SP_Common::parseParams('p', 'type', false, true) ) {
$tplvars['itemid'] = SP_Common::parseParams('p', 'id', 0);
$itemType = $tplvars['itemtype'] = SP_Common::parseParams('p', 'type', 0);
$tplvars['active'] = SP_Common::parseParams('p', 'active', 0);
$tplvars['activeTab'] = SP_Common::parseParams('p', 'active', 0);
$tplvars['view'] = SP_Common::parseParams('p', 'view', 0);
} else {
return;
@@ -44,42 +44,52 @@ if ( SP_Common::parseParams('p', 'id', FALSE, TRUE) && SP_Common::parseParams('p
switch ($itemType) {
case 1:
$tplvars['header'] = _('Editar Usuario');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'users';
break;
case 2:
$tplvars['header'] = _('Nuevo Usuario');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'users';
break;
case 3:
$tplvars['header'] = _('Editar Grupo');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'groups';
break;
case 4:
$tplvars['header'] = _('Nuevo Grupo');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'groups';
break;
case 5:
$tplvars['header'] = _('Editar Perfil');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'profiles';
break;
case 6:
$tplvars['header'] = _('Nuevo Perfil');
$tplvars['onCloseAction'] = 'usersmenu';
$template = 'profiles';
break;
case 7:
$tplvars['header'] = _('Editar Cliente');
$tplvars['onCloseAction'] = 'appmgmtmenu';
$template = 'customers';
break;
case 8:
$tplvars['header'] = _('Nuevo Cliente');
$tplvars['onCloseAction'] = 'appmgmtmenu';
$template = 'customers';
break;
case 9:
$tplvars['header'] = _('Editar Categoría');
$tplvars['onCloseAction'] = 'appmgmtmenu';
$template = 'categories';
break;
case 10:
$tplvars['header'] = _('Nueva Categoría');
$tplvars['onCloseAction'] = 'appmgmtmenu';
$template = 'categories';
break;
default :

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,8 +23,9 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -33,7 +34,7 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
@@ -43,6 +44,10 @@ if (!$sk || !SP_Common::checkSessionKey($sk)) {
$frmSaveType = SP_Common::parseParams('p', 'type', 0);
$frmAction = SP_Common::parseParams('p', 'action', 0);
$frmItemId = SP_Common::parseParams('p', 'id', 0);
$frmOnCloseAction = SP_Common::parseParams('p', 'onCloseAction');
$frmActiveTab = SP_Common::parseParams('p', 'activeTab', 0);
$doActionOnClose = "doAction('$frmOnCloseAction','',$frmActiveTab);";
if ($frmSaveType == 1 || $frmSaveType == 2) {
$objUser = new SP_Users;
@@ -57,9 +62,10 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
$frmUsrNotes = SP_Common::parseParams('p', 'notes');
$frmUsrPass = SP_Common::parseParams('p', 'pass');
$frmUsrPassV = SP_Common::parseParams('p', 'passv');
$frmAdminApp = SP_Common::parseParams('p', 'adminapp', 0, FALSE, 1);
$frmAdminAcc = SP_Common::parseParams('p', 'adminacc', 0, FALSE, 1);
$frmDisabled = SP_Common::parseParams('p', 'disabled', 0, FALSE, 1);
$frmAdminApp = SP_Common::parseParams('p', 'adminapp', 0, false, 1);
$frmAdminAcc = SP_Common::parseParams('p', 'adminacc', 0, false, 1);
$frmDisabled = SP_Common::parseParams('p', 'disabled', 0, false, 1);
$frmChangePass = SP_Common::parseParams('p', 'changepass', 0, false, 1);
// Nuevo usuario o editar
if ($frmAction == 1 OR $frmAction == 2) {
@@ -93,6 +99,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
$objUser->userIsAdminApp = $frmAdminApp;
$objUser->userIsAdminAcc = $frmAdminAcc;
$objUser->userIsDisabled = $frmDisabled;
$objUser->userChangePass = $frmChangePass;
$objUser->userPass = $frmUsrPass;
switch ($objUser->checkUserExist()) {
@@ -114,35 +121,21 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
}
if ($objUser->addUser()) {
$message['action'] = _('Nuevo Usuario');
$message['text'][] = _('Nombre') . ': ' . $frmUsrName . ' (' . $frmUsrLogin . ')';
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Usuario creado'), 0);
SP_Common::printJSON(_('Usuario creado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al crear el usuario'));
} elseif ($frmAction == 2) {
if ($objUser->updateUser()) {
$message['action'] = _('Modificar Usuario');
$message['text'][] = _('Nombre') . ': ' . $frmUsrName . ' (' . $frmUsrLogin . ')';
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Usuario actualizado'), 0);
SP_Common::printJSON(_('Usuario actualizado'), 0, $doActionOnClose);
}
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)');
SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
}
if (!$frmUsrPass || !$frmUsrPassV) {
@@ -157,23 +150,14 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
$objUser->userPass = $frmUsrPass;
if ($objUser->updateUserPass()) {
$message['action'] = _('Modificar Clave Usuario');
$message['text'][] = _('Login') . ': ' . $userLogin;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
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)');
SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
}
$objUser->userId = $frmItemId;
@@ -183,13 +167,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
}
if ($objUser->deleteUser()) {
$message['action'] = _('Eliminar Usuario');
$message['text'][] = _('Login') . ': ' . $userLogin;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Usuario eliminado'), 0);
SP_Common::printJSON(_('Usuario eliminado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al eliminar el usuario'));
@@ -217,31 +195,19 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
if ($frmAction == 1) {
if (SP_Groups::addGroup()) {
$message['action'] = _('Nuevo Grupo');
$message['text'][] = _('Nombre') . ': ' . $frmGrpName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Grupo creado'), 0);
SP_Common::printJSON(_('Grupo creado'), 0, $doActionOnClose);
} else {
SP_Common::printJSON(_('Error al crear el grupo'));
}
} else if ($frmAction == 2) {
if (SP_Groups::updateGroup()) {
$message['action'] = _('Modificar Grupo');
$message['text'][] = _('Nombre') . ': ' . $frmGrpName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Grupo actualizado'), 0);
SP_Common::printJSON(_('Grupo actualizado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al actualizar el grupo'));
}
// Eliminar grupo
// Eliminar grupo
} elseif ($frmAction == 4) {
SP_Groups::$groupId = $frmItemId;
@@ -261,13 +227,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
$groupName = SP_Groups::getGroupNameById($frmItemId);
if (SP_Groups::deleteGroup()) {
$message['action'] = _('Eliminar Grupo');
$message['text'][] = _('Nombre') . ': ' . $groupName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Grupo eliminado'), 0);
SP_Common::printJSON(_('Grupo eliminado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al eliminar el grupo'));
@@ -283,23 +243,23 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
SP_Profiles::$profileId = $frmItemId;
// Profile properties Array
$profileProp["pAccView"] = SP_Common::parseParams('p', 'profile_accview', 0, FALSE, 1);
$profileProp["pAccViewPass"] = SP_Common::parseParams('p', 'profile_accviewpass', 0, FALSE, 1);
$profileProp["pAccViewHistory"] = SP_Common::parseParams('p', 'profile_accviewhistory', 0, FALSE, 1);
$profileProp["pAccEdit"] = SP_Common::parseParams('p', 'profile_accedit', 0, FALSE, 1);
$profileProp["pAccEditPass"] = SP_Common::parseParams('p', 'profile_acceditpass', 0, FALSE, 1);
$profileProp["pAccAdd"] = SP_Common::parseParams('p', 'profile_accadd', 0, FALSE, 1);
$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["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);
$profileProp["pGroups"] = SP_Common::parseParams('p', 'profile_groups', 0, FALSE, 1);
$profileProp["pProfiles"] = SP_Common::parseParams('p', 'profile_profiles', 0, FALSE, 1);
$profileProp["pEventlog"] = SP_Common::parseParams('p', 'profile_eventlog', 0, FALSE, 1);
$profileProp["pAccView"] = SP_Common::parseParams('p', 'profile_accview', 0, false, 1);
$profileProp["pAccViewPass"] = SP_Common::parseParams('p', 'profile_accviewpass', 0, false, 1);
$profileProp["pAccViewHistory"] = SP_Common::parseParams('p', 'profile_accviewhistory', 0, false, 1);
$profileProp["pAccEdit"] = SP_Common::parseParams('p', 'profile_accedit', 0, false, 1);
$profileProp["pAccEditPass"] = SP_Common::parseParams('p', 'profile_acceditpass', 0, false, 1);
$profileProp["pAccAdd"] = SP_Common::parseParams('p', 'profile_accadd', 0, false, 1);
$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["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);
$profileProp["pGroups"] = SP_Common::parseParams('p', 'profile_groups', 0, false, 1);
$profileProp["pProfiles"] = SP_Common::parseParams('p', 'profile_profiles', 0, false, 1);
$profileProp["pEventlog"] = SP_Common::parseParams('p', 'profile_eventlog', 0, false, 1);
// Nuevo perfil o editar
if ($frmAction == 1 OR $frmAction == 2) {
@@ -315,31 +275,19 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
if ($frmAction == 1) {
if (SP_Profiles::addProfile($profileProp)) {
$message['action'] = _('Nuevo Perfil');
$message['text'][] = _('Nombre') . ': ' . $frmProfileName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Perfil creado'), 0);
SP_Common::printJSON(_('Perfil creado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al crear el perfil'));
} else if ($frmAction == 2) {
if (SP_Profiles::updateProfile($profileProp)) {
$message['action'] = _('Modificar Perfil');
$message['text'][] = _('Nombre') . ': ' . $frmProfileName;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Perfil actualizado'), 0);
SP_Common::printJSON(_('Perfil actualizado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al actualizar el perfil'));
}
// Eliminar perfil
// Eliminar perfil
} elseif ($frmAction == 4) {
$resProfileUse = SP_Profiles::checkProfileInUse();
@@ -352,12 +300,12 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
if (SP_Profiles::deleteProfile()) {
$message['action'] = _('Eliminar Perfil');
$message['text'][] = _('Nombre') . ': ' . $profileName;
$message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . $profileName;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Perfil eliminado'), 0);
SP_Common::printJSON(_('Perfil eliminado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al eliminar el perfil'));
@@ -385,19 +333,19 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
if ($frmAction == 1) {
if (SP_Customer::addCustomer()) {
SP_Common::printJSON(_('Cliente creado'), 0);
SP_Common::printJSON(_('Cliente creado'), 0, $doActionOnClose);
} 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(_('Cliente actualizado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al actualizar el cliente'));
}
// Eliminar cliente
// Eliminar cliente
} elseif ($frmAction == 4) {
$resCustomerUse = SP_Customer::checkCustomerInUse($frmItemId);
@@ -408,7 +356,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
} else {
if (SP_Customer::delCustomer($frmItemId)) {
SP_Common::printJSON(_('Cliente eliminado'), 0);
SP_Common::printJSON(_('Cliente eliminado'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al eliminar el cliente'));
@@ -436,28 +384,28 @@ if ($frmSaveType == 1 || $frmSaveType == 2) {
if ($frmAction == 1) {
if (SP_Category::addCategory()) {
SP_Common::printJSON(_('Categpría creada'), 0);
SP_Common::printJSON(_('Categpría creada'), 0, $doActionOnClose);
} 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(_('Categoría actualizada'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al actualizar la categoría'));
}
// Eliminar categoría
// Eliminar categoría
} elseif ($frmAction == 4) {
$resCategoryUse = SP_Category::checkCategoryInUse($frmItemId);
if ($resCategoryUse !== TRUE) {
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(_('Categoría eliminada'), 0, $doActionOnClose);
}
SP_Common::printJSON(_('Error al eliminar la categoría'));

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +32,7 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
@@ -44,12 +44,11 @@ if ( $doBackup ){
$arrOut = SP_Config::makeBackup();
$message['action'] = _('Realizar Backup');
$message['text'] = '';
SP_Common::sendEmail($message);
if ( array_key_exists('error', $arrOut) ){
SP_Common::printJSON(_('Error al realizar el backup').'<br><br>'.$arrOut['error']);
SP_Common::printJSON(_('Error al realizar el backup').';;'.$arrOut['error']);
}
SP_Common::printJSON(_('Proceso de backup finalizado'),0);

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +32,7 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
@@ -46,7 +46,7 @@ $frmLdapBindPass = SP_Common::parseParams('p', 'ldapbindpass');
$resCheckLdap = SP_LDAP::checkLDAPConn($frmLdapServer,$frmLdapBindUser,$frmLdapBindPass,$frmLdapBase,$frmLdapGroup);
if ( $resCheckLdap === FALSE ){
if ( $resCheckLdap === false ){
SP_Common::printJSON(_('Error de conexión a LDAP').';;'._('Revise el registro de eventos para más detalles'));
} else{
SP_Common::printJSON(_('Conexión a LDAP correcta').';;'._('Objetos encontrados').': '.$resCheckLdap,0);

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,11 +24,11 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('GET');
$checkVersion = SP_Common::parseParams('s', 'UPDATED', FALSE, TRUE);
$checkVersion = SP_Common::parseParams('s', 'UPDATED', false, true);
// Una vez por sesión
if ( ! $checkVersion ){
@@ -39,8 +39,8 @@ session_write_close();
if ( is_array($checkVersion) ){
echo '<a href="'.$checkVersion['url'].'" target="_blank" title="'._('Descargar nueva versión').'"><img src="imgs/update.png" />&nbsp;'.$checkVersion['version'].'</a>';
} elseif ( $checkVersion == TRUE ){
} elseif ( $checkVersion == true ){
echo '<img src="imgs/ok.png" title="'._('Actualizado').'"/>';
} elseif ( $checkVersion == FALSE ){
} elseif ( $checkVersion == false ){
echo '!';
}

View File

@@ -5,7 +5,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -23,8 +23,9 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,44 +33,53 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
}
// Variables POST del formulario
$frmAction = SP_Common::parseParams('p', 'action');
$frmOnCloseAction = SP_Common::parseParams('p', 'onCloseAction');
$frmActiveTab = SP_Common::parseParams('p', 'activeTab', 0);
$doActionOnClose = "doAction('$frmOnCloseAction','',$frmActiveTab);";
if ($frmAction == "config") {
$frmSiteLang = SP_Common::parseParams('p', 'sitelang');
$frmSessionTimeout = SP_Common::parseParams('p', 'session_timeout', 300);
$frmLog = SP_Common::parseParams('p', 'logenabled', 0, FALSE, 1);
$frmDebug = SP_Common::parseParams('p', 'debug', 0, FALSE, 1);
$frmMaintenance = SP_Common::parseParams('p', 'maintenance', 0, FALSE, 1);
$frmCheckUpdates = SP_Common::parseParams('p', 'updates', 0, FALSE, 1);
$frmFiles = SP_Common::parseParams('p', 'filesenabled', 0, FALSE, 1);
$frmGlobalSearch = SP_Common::parseParams('p', 'globalsearch', 0, FALSE, 1);
$frmAccountLink = SP_Common::parseParams('p', 'account_link', 0, FALSE, 1);
$frmLog = SP_Common::parseParams('p', 'logenabled', 0, false, 1);
$frmDebug = SP_Common::parseParams('p', 'debug', 0, false, 1);
$frmMaintenance = SP_Common::parseParams('p', 'maintenance', 0, false, 1);
$frmCheckUpdates = SP_Common::parseParams('p', 'updates', 0, false, 1);
$frmFiles = SP_Common::parseParams('p', 'filesenabled', 0, false, 1);
$frmGlobalSearch = SP_Common::parseParams('p', 'globalsearch', 0, false, 1);
$frmAccountLink = SP_Common::parseParams('p', 'account_link', 0, false, 1);
$frmAccountCount = SP_Common::parseParams('p', 'account_count', 10);
$frmAllowedSize = SP_Common::parseParams('p', 'allowed_size', 1024);
$frmAllowedExts = SP_Common::parseParams('p', 'allowed_exts');
$frmWiki = SP_Common::parseParams('p', 'wikienabled', 0, FALSE, 1);
$frmWiki = SP_Common::parseParams('p', 'wikienabled', 0, false, 1);
$frmWikiSearchUrl = SP_Common::parseParams('p', 'wikisearchurl');
$frmWikiPageUrl = SP_Common::parseParams('p', 'wikipageurl');
$frmWikiFilter = SP_Common::parseParams('p', 'wikifilter');
$frmLdap = SP_Common::parseParams('p', 'ldapenabled', 0, FALSE, 1);
$frmLdap = SP_Common::parseParams('p', 'ldapenabled', 0, false, 1);
$frmLdapServer = SP_Common::parseParams('p', 'ldapserver');
$frmLdapBase = SP_Common::parseParams('p', 'ldapbase');
$frmLdapGroup = SP_Common::parseParams('p', 'ldapgroup');
$frmLdapBindUser = SP_Common::parseParams('p', 'ldapbinduser');
$frmLdapBindPass = SP_Common::parseParams('p', 'ldapbindpass');
$frmMail = SP_Common::parseParams('p', 'mailenabled', 0, FALSE, 1);
$frmMail = SP_Common::parseParams('p', 'mailenabled', 0, false, 1);
$frmMailServer = SP_Common::parseParams('p', 'mailserver');
$frmMailPort = SP_Common::parseParams('p', 'mailport',25);
$frmMailUser = SP_Common::parseParams('p', 'mailuser');
$frmMailPass = SP_Common::parseParams('p', 'mailpass');
$frmMailSecurity = SP_Common::parseParams('p', 'mailsecurity');
$frmMailFrom = SP_Common::parseParams('p', 'mailfrom');
$frmMailRequests = SP_Common::parseParams('p', 'mailrequestsenabled', 0, FALSE, 1);
$frmMailRequests = SP_Common::parseParams('p', 'mailrequestsenabled', 0, false, 1);
if ($frmAccountCount == "all") {
$intAccountCount = 99;
@@ -107,6 +117,10 @@ if ($frmAction == "config") {
SP_Config::setValue("mailenabled", 1);
SP_Config::setValue("mailrequestsenabled", $frmMailRequests);
SP_Config::setValue("mailserver", $frmMailServer);
SP_Config::setValue("mailport", $frmMailPort);
SP_Config::setValue("mailuser", $frmMailUser);
SP_Config::setValue("mailpass", $frmMailPass);
SP_Config::setValue("mailsecurity", $frmMailSecurity);
SP_Config::setValue("mailfrom", $frmMailFrom);
} else {
SP_Config::setValue("mailenabled", 0);
@@ -131,21 +145,20 @@ if ($frmAction == "config") {
SP_Config::setValue("allowed_size", $frmAllowedSize);
$message['action'] = _('Modificar Configuración');
$message['text'][] = '';
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Configuración actualizada'), 0);
SP_Common::printJSON(_('Configuración actualizada'), 0, $doActionOnClose);
} elseif ($frmAction == "crypt") {
$currentMasterPass = SP_Common::parseParams('p', 'curMasterPwd');
$newMasterPass = SP_Common::parseParams('p', 'newMasterPwd');
$newMasterPassR = SP_Common::parseParams('p', 'newMasterPwdR');
$confirmPassChange = SP_Common::parseParams('p', 'confirmPassChange', 0, FALSE, 1);
$noAccountPassChange = SP_Common::parseParams('p', 'chkNoAccountChange', 0, FALSE, 1);
$confirmPassChange = SP_Common::parseParams('p', 'confirmPassChange', 0, false, 1);
$noAccountPassChange = SP_Common::parseParams('p', 'chkNoAccountChange', 0, false, 1);
if (!SP_Users::checkUserUpdateMPass()) {
SP_Common::printJSON(_('Clave maestra actualizada') . '<br>' . _('Reinicie la sesión para cambiarla'));
SP_Common::printJSON(_('Clave maestra actualizada') . ';;' . _('Reinicie la sesión para cambiarla'));
}
if ($newMasterPass == "" && $currentMasterPass == "") {
@@ -181,7 +194,7 @@ if ($frmAction == "config") {
}
if (SP_Config::getValue('demoenabled', 0)) {
SP_Common::printJSON(_('DEMO'));
SP_Common::printJSON(_('Ey, esto es una DEMO!!'));
}
SP_Config::$arrConfigValue["masterPwd"] = $hashMPass;
@@ -189,7 +202,6 @@ if ($frmAction == "config") {
if (SP_Config::writeConfig()) {
$message['action'] = _('Actualizar Clave Maestra');
$message['text'] = '';
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Clave maestra cambiada'), 0);

View File

@@ -5,7 +5,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -23,12 +23,13 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
if (!SP_Common::parseParams('p', 'login', FALSE)) {
if (!SP_Common::parseParams('p', 'login', false)) {
return;
}
@@ -57,7 +58,7 @@ if ($resLdap == 1) {
// Creamos el usuario de LDAP en MySQL
if (!$objUser->newUserLDAP()) {
$message['text'][] = _('Error al guardar los datos de LDAP');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Error interno'));
}
@@ -65,7 +66,7 @@ if ($resLdap == 1) {
// Actualizamos la clave del usuario en MySQL
if (!$objUser->updateLDAPUserInDB()) {
$message['text'][] = _('Error al actualizar la clave del usuario en la BBDD');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Error interno'));
}
@@ -74,8 +75,7 @@ if ($resLdap == 1) {
$message['action'] = _('Inicio sesión (LDAP)');
$message['text'][] = _('Login incorrecto');
$message['text'][] = _('Usuario') . ": " . $userLogin;
$message['text'][] = _('IP') . ": " . $_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Usuario/Clave incorrectos'));
} else { // Autentificamos por MySQL (ha fallado LDAP)
@@ -85,19 +85,17 @@ if ($resLdap == 1) {
if (!SP_Auth::authUserMySQL($userLogin,$userPass)) {
$message['text'][] = _('Login incorrecto');
$message['text'][] = _('Usuario') . ": " . $userLogin;
$message['text'][] = _('IP') . ": " . $_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Usuario/Clave incorrectos'));
}
}
// Comprobar si el usuario está deshabilitado
if (SP_Auth::checkUserIsDisabled($userLogin)) {
if (SP_Users::checkUserIsDisabled($userLogin)) {
$message['text'][] = _('Usuario deshabilitado');
$message['text'][] = _('Usuario') . ": " . $userLogin;
$message['text'][] = _('IP') . ": " . $_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Usuario deshabilitado'));
}
@@ -105,7 +103,7 @@ if (SP_Auth::checkUserIsDisabled($userLogin)) {
// Obtenemos los datos del usuario
if (!$objUser->getUserInfo()) {
$message['text'][] = _('Error al obtener los datos del usuario de la BBDD');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Error interno'));
}
@@ -116,22 +114,32 @@ if (!$masterPass && (!$objUser->checkUserMPass() || !SP_Users::checkUserUpdateMP
} elseif ($masterPass) {
if (!$objUser->updateUserMPass($masterPass)) {
$message['text'][] = _('Clave maestra incorrecta');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Clave maestra incorrecta'), 4);
}
}
// Comprobar si se ha forzado un cambio de clave
if ($objUser->userChangePass){
$hash = SP_Util::generate_random_bytes();
if (SP_Users::addPassRecover($userLogin, $hash)){
$url = SP_Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time();
SP_Common::printJSON($url, 0);
}
}
// Obtenemos la clave maestra del usuario
if ($objUser->getUserMPass()) {
// Establecemos las variables de sesión
$objUser->setUserSession();
$message['text'][] = _('Usuario') . ": " . $_SESSION['uname'];
$message['text'][] = _('Perfil') . ": " . $_SESSION['uprofile'];
$message['text'][] = _('Grupo') . ": " . $_SESSION['ugroup'];
$message['text'][] = _('IP') . ": " . $_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
$message['text'][] = _('Usuario') . ": " . $userLogin;
$message['text'][] = _('Perfil') . ": " . SP_Profiles::getProfileNameById($objUser->userProfileId);
$message['text'][] = _('Grupo') . ": " . SP_Groups::getGroupNameById($objUser->userGroupId);
SP_Log::wrLogInfo($message);
// Comprobar si existen parámetros adicionales en URL via GET
foreach ($_POST as $param => $value){
@@ -143,4 +151,4 @@ if ($objUser->getUserMPass()) {
$urlParams = isset($params) ? '?'.implode('&', $params) : '';
SP_Common::printJSON('index.php'.$urlParams, 0);
}
}

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -36,11 +36,11 @@ SP_ACL::checkUserAccess('eventlog') || SP_Html::showCommonError('unavailable');
$start = SP_Common::parseParams('p', 'start', 0);
$clear = SP_Common::parseParams('p', 'clear', 0);
$sk = SP_Common::parseParams('p', 'sk', FALSE);
$sk = SP_Common::parseParams('p', 'sk', false);
if ( $clear && $sk && SP_Common::checkSessionKey($sk) ){
if ( SP_Log::clearEvents() ){
SP_Common::printJSON(_('Registro de eventos vaciado'), 0);
SP_Common::printJSON(_('Registro de eventos vaciado'), 0, "doAction('eventlog');scrollUp();");
} else{
SP_Common::printJSON(_('Error al vaciar el registro de eventos'));
}

View File

@@ -5,7 +5,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,7 @@
// TODO: comprobar permisos para eliminar archivos
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -34,7 +34,7 @@ if (!SP_Init::isLoggedIn()) {
SP_Util::logout();
}
$sk = SP_Common::parseParams('p', 'sk', FALSE);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
die(_('CONSULTA INVÁLIDA'));
@@ -98,7 +98,7 @@ if ($action == 'upload') {
$message['action'] = _('Subir Archivo');
$message['text'][] = _('Error interno al leer el archivo');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
exit(_('Error interno al leer el archivo'));
}
@@ -119,7 +119,7 @@ if ($action == 'download' || $action == 'view') {
exit(_('No es un ID de archivo válido'));
}
$isView = ( $action == 'view' ) ? TRUE : FALSE;
$isView = ( $action == 'view' ) ? true : false;
$file = SP_Files::fileDownload($fileId);
@@ -140,7 +140,7 @@ if ($action == 'download' || $action == 'view') {
$message['text'][] = _('Tamaño') . ": " . round($fileSize / 1024, 2) . " KB";
if (!$isView) {
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
// Enviamos el archivo al navegador
header('Set-Cookie: fileDownload=true; path=/');
@@ -155,14 +155,14 @@ if ($action == 'download' || $action == 'view') {
} else {
$extsOkImg = array("JPG", "GIF", "PNG");
if (in_array(strtoupper($fileExt), $extsOkImg)) {
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
$imgData = chunk_split(base64_encode($fileData));
exit('<img src="data:' . $fileType . ';base64, ' . $imgData . '" border="0" />');
// } elseif ( strtoupper($fileExt) == "PDF" ){
// echo '<object data="data:application/pdf;base64, '.base64_encode($fileData).'" type="application/pdf"></object>';
} elseif (strtoupper($fileExt) == "TXT") {
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
exit('<div id="fancyView" class="backGrey"><pre>' . $fileData . '</pre></div>');
} else {

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -24,7 +24,7 @@
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +32,7 @@ if (!SP_Init::isLoggedIn()) {
SP_Util::logout();
}
if (SP_Common::parseParams('p', 'action', '', TRUE)) {
if (SP_Common::parseParams('p', 'action', '', true)) {
$action = $tplvars['action'] = SP_Common::parseParams('p', 'action');
$itemId = $tplvars['id'] = SP_Common::parseParams('p', 'id', 0);
$tplvars['lastaction'] = SP_Common::parseParams('p', 'lastAction', 'accsearch');
@@ -95,12 +95,12 @@ switch ($action) {
case "usersmenu":
echo '<DIV ID="tabs">';
echo '<UL>';
echo ( SP_ACL::checkUserAccess("users") ) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Gestión de Usuarios') . '">' . _('Gestión de Usuarios') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("groups") ) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Gestión de Grupos') . '">' . _('Gestión de Grupos') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("profiles") ) ? '<LI><A HREF="#tabs-3" TITLE="' . _('Gestión de Perfiles') . '">' . _('Gestión de Perfiles') . '</A></LI>' : '';
echo (SP_ACL::checkUserAccess("users")) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Gestión de Usuarios') . '">' . _('Gestión de Usuarios') . '</A></LI>' : '';
echo (SP_ACL::checkUserAccess("groups")) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Gestión de Grupos') . '">' . _('Gestión de Grupos') . '</A></LI>' : '';
echo (SP_ACL::checkUserAccess("profiles")) ? '<LI><A HREF="#tabs-3" TITLE="' . _('Gestión de Perfiles') . '">' . _('Gestión de Perfiles') . '</A></LI>' : '';
echo '</UL>';
$tplvars['active'] = 0;
$activeTab = 0;
if (SP_ACL::checkUserAccess("users")) {
$arrUsersTableProp = array(
@@ -127,10 +127,10 @@ switch ($action) {
),
'tblRowSrcId' => 'user_id',
'frmId' => 'frm_tblusers',
'nextaction' => $action,
'onCloseAction' => $action,
'actionId' => 1,
'newActionId' => 2,
'active' => $tplvars['active'] ++,
'activeTab' => $activeTab++,
'actions' => array('view' => 'appMgmtData', 'edit' => 'appMgmtData', 'del' => 'appMgmtSave', 'pass' => 'usrUpdPass'));
echo '<DIV ID="tabs-1">';
@@ -153,10 +153,10 @@ switch ($action) {
'tblRowSrc' => array('usergroup_name', 'usergroup_description'),
'tblRowSrcId' => 'usergroup_id',
'frmId' => 'frm_tblgroups',
'nextaction' => $action,
'onCloseAction' => $action,
'actionId' => 3,
'newActionId' => 4,
'active' => $tplvars['active'] ++,
'activeTab' => $activeTab++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave'));
echo '<DIV ID="tabs-2">';
@@ -181,10 +181,10 @@ switch ($action) {
'tblRowSrc' => array('userprofile_name'),
'tblRowSrcId' => 'userprofile_id',
'frmId' => 'frm_tblprofiles',
'nextaction' => $action,
'onCloseAction' => $action,
'actionId' => 5,
'newActionId' => 6,
'active' => $tplvars['active'] ++,
'activeTab' => $activeTab++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave'));
echo '<DIV ID="tabs-3">';
@@ -215,70 +215,70 @@ switch ($action) {
case "appmgmtmenu":
echo '<DIV ID="tabs">';
echo '<UL>';
echo ( SP_ACL::checkUserAccess("categories") ) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Gestión de Categorías') . '">' . _('Gestión de Categorías') . '</A></LI>' : '';
echo ( SP_ACL::checkUserAccess("customers") ) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Gestión de Clientes') . '">' . _('Gestión de Clientes') . '</A></LI>' : '';
echo (SP_ACL::checkUserAccess("categories")) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Gestión de Categorías') . '">' . _('Gestión de Categorías') . '</A></LI>' : '';
echo (SP_ACL::checkUserAccess("customers")) ? '<LI><A HREF="#tabs-2" TITLE="' . _('Gestión de Clientes') . '">' . _('Gestión de Clientes') . '</A></LI>' : '';
echo '</UL>';
$tplvars['active'] = 0;
$activeTab = 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'),
'tblHeaders' => array(_('Nombre'), _('Descripción')),
'tblRowSrc' => array('category_name', 'category_description'),
'tblRowSrcId' => 'category_id',
'frmId' => 'frm_tblcategories',
'nextaction' => $action,
'onCloseAction' => $action,
'actionId' => 9,
'newActionId' => 10,
'active' => $tplvars['active'] ++,
'activeTab' => $activeTab++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave')
);
);
echo '<DIV ID="tabs-1">';
$startTime = microtime();
$categories = SP_Category::getCategories();
if ($categories !== FALSE) {
if ($categories !== false) {
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'),
'tblHeaders' => array(_('Nombre'), _('Descripción')),
'tblRowSrc' => array('customer_name', 'customer_description'),
'tblRowSrcId' => 'customer_id',
'frmId' => 'frm_tblcustomers',
'nextaction' => $action,
'onCloseAction' => $action,
'actionId' => 7,
'newActionId' => 8,
'active' => $tplvars['active'] ++,
'activeTab' => $activeTab++,
'actions' => array('edit' => 'appMgmtData', 'del' => 'appMgmtSave')
);
);
echo '<DIV ID="tabs-2">';
$startTime = microtime();
$customers = SP_Customer::getCustomers();
if ($customers !== FALSE) {
if ($customers !== false) {
SP_Html::getQueryTable($arrCustomersTableProp, $customers);
SP_Html::printQueryInfoBar(count($customers), $startTime);
}
echo '</DIV>';
}
echo '</DIV>';
echo '<script>
@@ -295,24 +295,23 @@ switch ($action) {
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("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 (SP_ACL::checkUserAccess("config")) ? '<LI><A HREF="#tabs-1" TITLE="' . _('Configuración') . '">' . _('Configuración') . '</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;
$tplvars['activeTab'] = 0;
$tplvars['onCloseAction'] = $action;
if (SP_ACL::checkUserAccess("config")) {
$tplvars['active'] ++;
echo '<DIV ID="tabs-1">';
SP_Html::getTemplate('config', $tplvars);
echo '</DIV>';
}
if (SP_ACL::checkUserAccess("masterpass")) {
$tplvars['active'] ++;
$tplvars['activeTab']++;
echo '<DIV ID="tabs-2">';
SP_Html::getTemplate('masterpass', $tplvars);
@@ -320,7 +319,7 @@ switch ($action) {
}
if (SP_ACL::checkUserAccess("backup")) {
$tplvars['active'] ++;
$tplvars['activeTab']++;
echo '<DIV ID="tabs-3">';
SP_Html::getTemplate('backup', $tplvars);
@@ -328,7 +327,7 @@ switch ($action) {
}
if (SP_ACL::checkUserAccess("config")) {
$tplvars['active'] ++;
$tplvars['activeTab']++;
echo '<DIV ID="tabs-4">';
SP_Html::getTemplate('migrate', $tplvars);
@@ -367,10 +366,10 @@ if (isset($_SESSION["uisadminapp"]) && SP_Config::getValue('debug')) {
$debugTxt[] = "<li>RENDER -> " . $time . " sec</li>";
$debugTxt[] = "<li>MEM -> Init: " . ($memInit / 1000) . " KB - End: " . ($memEnd / 1000) . " KB - Total: " . (($memEnd - $memInit) / 1000) . " KB</li>";
$debugTxt[] = "<li>SESSION:";
$debugTxt[] = "<pre>" . print_r($_SESSION, TRUE) . "</pre";
$debugTxt[] = "<pre>" . print_r($_SESSION, true) . "</pre";
$debugTxt[] = "</li>";
$debugTxt[] = "<li>CONFIG:<pre>";
$debugTxt[] = "<pre>" . print_r(SP_Config::getKeys(TRUE), TRUE) . "</pre>";
$debugTxt[] = "<pre>" . print_r(SP_Config::getKeys(true), true) . "</pre>";
$debugTxt[] = "</li>";
//$debugTxt[] = '<li>'.$crypt->getSessionMasterPass().'</li>';
$debugTxt[] = "</div>";
@@ -383,6 +382,6 @@ if (isset($_SESSION["uisadminapp"]) && SP_Config::getValue('debug')) {
// Se comprueba si hay actualizaciones.
// Es necesario que se haga al final de obtener el contenido ya que la
// consulta ajax detiene al resto si se ejecuta antes
if ($_SESSION['uisadminapp'] && SP_Config::getValue('checkupdates') === 1 && !SP_Common::parseParams('s', 'UPDATED', FALSE, TRUE)) {
if ($_SESSION['uisadminapp'] && SP_Config::getValue('checkupdates') === 1 && !SP_Common::parseParams('s', 'UPDATED', false, true)) {
echo '<script>checkUpds();</script>';
}

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('GET');
@@ -34,10 +34,10 @@ if ( ! SP_Init::isLoggedIn() ) {
if ( SP_Config::getValue('filesenabled') == 0 ){
echo _('Gestión de archivos deshabilitada');
return FALSE;
return false;
}
$sk = SP_Common::parseParams('g', 'sk', FALSE);
$sk = SP_Common::parseParams('g', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printXML(_('CONSULTA INVÁLIDA'));

View File

@@ -1 +1 @@
<?php
<?php

View File

@@ -1 +1 @@
<?php
<?php

86
ajax/ajax_passReset.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-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/>.
*
*/
define('APP_ROOT', '..');
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
}
$userLogin = SP_Common::parseParams('p', 'login');
$userEmail = SP_Common::parseParams('p', 'email');
$userPass = SP_Common::parseParams('p', 'pass');
$userPassV = SP_Common::parseParams('p', 'passv');
$hash = SP_Common::parseParams('p', 'hash');
$time = SP_Common::parseParams('p', 'time');
$message['action'] = _('Recuperación de Clave');
if ($userLogin && $userEmail) {
if (SP_Auth::mailPassRecover($userLogin, $userEmail)) {
$message['text'][] = SP_Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
SP_Common::sendEmail($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Solicitud enviada') . ';;' . _('En breve recibirá un correo para completar la solicitud.'), 0, 'goLogin();');
} else {
$message['text'][] = 'ERROR';
$message['text'][] = SP_Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')';
SP_Common::sendEmail($message);
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('No se ha podido realizar la solicitud. Consulte con el administrador.'));
}
}
if ($userPass && $userPassV && $userPass === $userPassV) {
$userId = SP_Users::checkHashPassRecover($hash);
if ($userId) {
$user = new SP_Users();
$user->userId = $userId;
$user->userPass = $userPass;
if ($user->updateUserPass() && SP_Users::updateHashPassRecover($hash)) {
$message['action'] = _('Modificar Clave Usuario');
$message['text'][] = SP_Html::strongText(_('Login') . ': ') . $user->getUserLoginById($userId);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
SP_Common::printJSON(_('Clave actualizada'), 0, 'goLogin();');
}
}
SP_Common::printJSON(_('Error al modificar la clave'));
} else {
SP_Common::printJSON(_('La clave es incorrecta o no coincide'));
}

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +32,7 @@ if (!SP_Init::isLoggedIn()) {
SP_Util::logout();
}
$sk = SP_Common::parseParams('p', 'sk', FALSE);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
die('<div class="error round">'._('CONSULTA INVÁLIDA').'</div>');
@@ -47,7 +47,7 @@ $wikiEnabled = SP_Config::getValue('wikienabled');
$wikiSearchUrl = SP_Config::getValue('wikisearchurl');
$wikiFilter = explode(',',SP_Config::getValue('wikifilter'));
$wikiPageUrl = SP_Config::getValue('wikipageurl');
$requestEnabled = SP_Config::getValue('mailrequestsenabled', FALSE);
$requestEnabled = SP_Config::getValue('mailrequestsenabled', false);
$sortKey = SP_Common::parseParams('p', 'skey', 0);
$sortOrder = SP_Common::parseParams('p', 'sorder', 0);
@@ -55,13 +55,13 @@ $customerId = SP_Common::parseParams('p', 'customer', 0);
$categoryId = SP_Common::parseParams('p', 'category', 0);
$searchTxt = SP_Common::parseParams('p', 'search', '');
$limitStart = SP_Common::parseParams('p', 'start', 0);
$globalSearch = SP_Common::parseParams('p', 'gsearch', 0, FALSE, 1);
$globalSearch = SP_Common::parseParams('p', 'gsearch', 0, false, 1);
$userGroupId = SP_Common::parseParams('s', 'ugroup', 0);
$userProfileId = SP_Common::parseParams('s', 'uprofile', 0);
$userId = SP_Common::parseParams('s', 'uid', 0);
$filterOn = ( $sortKey > 1 || $customerId || $categoryId || $searchTxt ) ? TRUE : FALSE;
$filterOn = ( $sortKey > 1 || $customerId || $categoryId || $searchTxt ) ? true : false;
$objAccount = new SP_Account;
$arrSearchFilter = array("txtSearch" => $searchTxt,
@@ -224,7 +224,7 @@ foreach ( $resQuery as $account ){
echo '<div class="account-info">';
echo '<img src="imgs/btn_group.png" title="'.$secondaryAccesses.'" />';
echo ( $strAccNotes ) ? '<img src="imgs/notes.png" title="'._('Notas').': <br><br>'. nl2br(wordwrap(htmlspecialchars($strAccNotes),50,'<br>',TRUE)).'" />' : '';
echo ( $strAccNotes ) ? '<img src="imgs/notes.png" title="'._('Notas').': <br><br>'. nl2br(wordwrap(htmlspecialchars($strAccNotes),50,'<br>',true)).'" />' : '';
if ( $filesEnabled == 1 ){
$intNumFiles = SP_Files::countFiles($account->account_id);

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -24,7 +24,7 @@
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -32,7 +32,7 @@ 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);
$sk = SP_Common::parseParams('p', 'sk', false);
if (!$sk || !SP_Common::checkSessionKey($sk)) {
SP_Common::printJSON(_('CONSULTA INVÁLIDA'));
@@ -56,17 +56,19 @@ $requestUsername = SP_Common::parseParams('s', 'uname');
$requestLogin = SP_Common::parseParams('s', 'ulogin');
$message['action'] = _('Solicitud de Modificación de Cuenta');
$message['text'][] = _('Solicitante') . ': ' . $requestUsername . ' (' . $requestLogin . ')';
$message['text'][] = _('Cuenta') . ': ' . $accountRequestData->account_name;
$message['text'][] = _('Cliente') . ': ' . $accountRequestData->customer_name;
$message['text'][] = _('Descripción') . ': ' . $frmDescription;
$message['text'][] = SP_Html::strongText(_('Solicitante') . ': ') . $requestUsername . ' (' . $requestLogin . ')';
$message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $accountRequestData->account_name;
$message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $accountRequestData->customer_name;
$message['text'][] = SP_Html::strongText(_('Descripción') . ': ') . $frmDescription;
$mailto = implode(',', $recipients);
if ($mailto
&& SP_Config::getValue('mailrequestsenabled', FALSE)
&& SP_Common::sendEmail($message, $mailto)) {
SP_Common::printJSON(_('Solicitud enviada'), 0);
if ($mailto
&& SP_Config::getValue('mailrequestsenabled', false)
&& SP_Common::sendEmail($message, $mailto)
) {
SP_Log::wrLogInfo($message);
SP_Common::printJSON(_('Solicitud enviada'), 0, "doAction('accsearch');");
}
SP_Common::printJSON(_('Error al enviar la solicitud'));

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '..');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('GET');
@@ -32,7 +32,7 @@ if ( ! SP_Init::isLoggedIn() ){
SP_Util::logout();
}
$userId = SP_Common::parseParams('g', 'usrid', FALSE);
$userId = SP_Common::parseParams('g', 'usrid', false);
if ( ! $userId ) {
return;
@@ -79,7 +79,7 @@ SP_ACL::checkUserAccess("acceditpass",$userId) || die ($strError);
<div class="action-in-box">
<ul>
<li>
<img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="usersMgmt('frmUpdUsrPass')" alt="<?php echo _('Guardar'); ?>"/>
<img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" OnClick="appMgmtSave('frmUpdUsrPass')" alt="<?php echo _('Guardar'); ?>"/>
</li>
</ul>
</div>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -22,8 +22,9 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
define('APP_ROOT', '..');
include_once (APP_ROOT . "/inc/init.php");
require_once APP_ROOT.DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'init.php';
SP_Util::checkReferer('POST');
@@ -31,7 +32,7 @@ if (!SP_Init::isLoggedIn()) {
return;
}
$accountId = SP_Common::parseParams('p', 'accountid', FALSE);
$accountId = SP_Common::parseParams('p', 'accountid', false);
$fullTxt = SP_Common::parseParams('p', 'full', 0);
$isHistory = SP_Common::parseParams('p', 'isHistory', 0);
@@ -84,7 +85,7 @@ $message['text'][] = _('ID') . ': ' . $accountId;
$message['text'][] = _('Cuenta') . ': ' . $accountData->customer_name . " / " . $accountData->account_name;
$message['text'][] = _('IP') . ': ' . $_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
if ($fullTxt) {
?>

44
config/config.php.sample Normal file
View File

@@ -0,0 +1,44 @@
<?php
// This file is generated automatically on installation process
// Please, modify with caution, it could break the application
$CONFIG = array (
'account_count' => 12,
'account_link' => 1,
'allowed_exts' => 'BAK,CSV,DOC,DOCX,JPG,ODS,ODT,PDF,PNG,TXT,VSD,XLS,XSL',
'allowed_size' => 1280,
'checkupdates' => 1,
'dbhost' => 'localhost',
'dbname' => 'syspass',
'dbpass' => 'your_secret_db_pass',
'dbuser' => 'sp_admin',
'debug' => 0,
'demoenabled' => 0,
'filesenabled' => 1,
'globalsearch' => 1,
'installed' => 0,
'ldapbase' => 'dc=cygnux,dc=org',
'ldapbindpass' => 'your_secret_ldap_pass',
'ldapbinduser' => 'cn=Proxy User,ou=Users,dc=cygnux,dc=org',
'ldapenabled' => 1,
'ldapgroup' => 'GRP_SYSPASS',
'ldapserver' => 'ldap://localhost',
'ldapuserattr' => '',
'logenabled' => 0,
'mailenabled' => 0,
'mailfrom' => 'demo@syspass.org',
'mailpass' => 'your_secret_mail_pass',
'mailport' => 25,
'mailrequestsenabled' => 0,
'mailsecurity' => 'TLS',
'mailserver' => 'mail.syspass.org',
'mailuser' => 'demo@syspass.org',
'maintenance' => 0,
'passwordsalt' => '87a77bb997f834d7859e726907233a',
'session_timeout' => 600,
'sitelang' => 'en_US',
'version' => 1123,
'wikienabled' => 0,
'wikifilter' => 'vm-',
'wikipageurl' => 'http://wiki.syspass.org/doku.php/demo:',
'wikisearchurl' => 'http://wiki.syspass.org/wiki/doku.php/start?do=search&id=',
);

View File

@@ -874,6 +874,9 @@ A:focus {text-decoration: none; color: #FF0000;}
#boxLogin #boxData input:active,
#boxLogin #boxData input:focus{border: 1px solid #5897fb;}
#boxLogin #boxActions {float: left; width: 100%; padding: .5em; text-align: right;}
#boxLogin #boxActions a{color: #c9c9c9;}
#boxLogout{
width: 250px;
margin: 0 auto;
@@ -905,15 +908,15 @@ fieldset.warning {
fieldset.warning legend { color:#b94a48 !important; }
fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
/*Install Page*/
#install, #error{
/*Actions and Errors Page*/
#actions{
width: 100%;
margin: auto;
margin-bottom: 50px;
line-height: 2em;
}
#install #logo, #error #logo{
#actions #logo{
width: 100%;
margin-bottom: 30px;
font-size: 18px;
@@ -926,14 +929,14 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
-moz-box-shadow: 0px 8px 6px -6px #a9a9a9;
}
#install #logo #pageDesc{
#actions #logo #pageDesc{
position: relative;
top: 30px;
left: -100px;
text-shadow: 3px 3px #fff;
}
#install ul.errors, #error ul.errors{
#actions ul.errors{
max-width: 40%;
margin: 0 auto;
list-style: none;
@@ -941,32 +944,32 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
text-align: left;
}
#install ul.errors>li, #error ul.errors>li{
#actions ul.errors>li{
margin: 1.5em auto;
border-radius:5px;
padding: 0.5em;
}
#install ul.errors>li.err_critical, #error ul.errors>li.err_critical{
#actions ul.errors>li.err_critical{
color:#b94a48;
background:#fed7d7;
border:1px solid #f00;
}
#install ul.errors>li.err_warning, #error ul.errors>li.err_warning{
#actions ul.errors>li.err_warning{
color: orange;
background: #FFF2D9;
border: #ffe5b3 1px solid;
}
#install ul.errors>li.err_ok, #error ul.errors>li.err_ok{
#actions ul.errors>li.err_ok{
color: green;
background: #ecfde4;
border: #dbfdcb 1px solid;
font-weight: bold;
}
#install ul.errors>li>p.hint, #error ul.errors>li>p.hint{
#actions ul.errors>li>p.hint{
background-image:url('../imgs/info.png');
background-repeat:no-repeat;
color:#777777;
@@ -975,7 +978,7 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
font-size: 12px;
}
#install form fieldset legend{
#actions form fieldset legend{
width:100%;
margin-top: 1em;
text-align:center;
@@ -985,9 +988,9 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
font-size: 14px;
}
#install input[type="text"],
#install input[type="password"],
#install input[type="email"] {
#actions input[type="text"],
#actions input[type="password"],
#actions input[type="email"]{
margin-top: 0.5em;
border: 1px solid #a9a9a9;
font-size: 14px;
@@ -996,11 +999,13 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
box-shadow: 0 1px 0 rgba(255,255,255,.15), 0 1px 1px rgba(0,0,0,.25) inset;
}
#install form input[type="checkbox"]+label { position:relative; margin:0; font-size:1em; text-shadow:#fff 0 1px 0; }
#actions form input[type="checkbox"]+label { position:relative; margin:0; font-size:1em; text-shadow:#fff 0 1px 0; }
#install .button{
#actions .button{
display: inline-block;
width: 150px;
margin: 15px;
padding: 5px;
text-align: center;
border: 1px solid #d9d9d9;
background-color: #777;
@@ -1011,4 +1016,4 @@ fieldset.warning a { color:#b94a48 !important; font-weight:bold; }
box-shadow: 3px 3px 3px -3px #a9a9a9;
-webkit-box-shadow: 8px 8px 6px -6px #a9a9a9;
-moz-box-shadow: 8px 8px 6px -6px #a9a9a9;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,13 +23,15 @@
* 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 calcular las access lists de acceso a usuarios.
*/
class SP_ACL {
class SP_ACL
{
static $accountCacheUserGroupsId;
/**
@@ -37,15 +39,16 @@ class SP_ACL {
* @param string $strAction con el nombre de la acción
* @param int $userId opcional, con el Id del usuario
* @return bool
*
*
* Esta función comprueba los permisos del usuario para realizar una acción.
* Si los permisos ya han sido obtenidos desde la BBDD, se utiliza el objeto creado
* en la variable de sesión.
*/
public static function checkUserAccess($strAction, $userId = 0) {
public static function checkUserAccess($strAction, $userId = 0)
{
// Comprobamos si la cache de permisos está inicializada
if (!isset($_SESSION["usrprofile"]) || !is_object($_SESSION["usrprofile"])) {
return FALSE;
return false;
}
$blnUIsAdminApp = $_SESSION["uisadminapp"];
@@ -54,121 +57,122 @@ class SP_ACL {
switch ($strAction) {
case "accview":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pView );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pView);
case "accviewpass":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pViewPass );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pViewPass);
case "accviewhistory":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pViewHistory );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pViewHistory);
case "accedit":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pEdit );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pEdit);
case "acceditpass":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pEditPass || $userId == $_SESSION["uid"] );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pEditPass || $userId == $_SESSION["uid"]);
case "accnew":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pAdd );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pAdd);
case "acccopy":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || ($profile->userProfile_pAdd && $profile->userProfile_pView) );
return ($blnUIsAdminApp || $blnUIsAdminAcc || ($profile->userProfile_pAdd && $profile->userProfile_pView));
case "accdelete":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pDelete );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pDelete);
case "accfiles":
return ( $blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pFiles );
return ($blnUIsAdminApp || $blnUIsAdminAcc || $profile->userProfile_pFiles);
case "appmgmtmenu":
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtMenu );
return ($blnUIsAdminApp || $profile->userProfile_pAppMgmtMenu);
case "configmenu":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigMenu );
return ($blnUIsAdminApp || $profile->userProfile_pConfigMenu);
case "config":
return ( $blnUIsAdminApp || $profile->userProfile_pConfig );
return ($blnUIsAdminApp || $profile->userProfile_pConfig);
case "categories":
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtCategories );
return ($blnUIsAdminApp || $profile->userProfile_pAppMgmtCategories);
case "customers":
return ( $blnUIsAdminApp || $profile->userProfile_pAppMgmtCustomers );
return ($blnUIsAdminApp || $profile->userProfile_pAppMgmtCustomers);
case "masterpass":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigMasterPass );
return ($blnUIsAdminApp || $profile->userProfile_pConfigMasterPass);
case "backup":
return ( $blnUIsAdminApp || $profile->userProfile_pConfigBackup );
return ($blnUIsAdminApp || $profile->userProfile_pConfigBackup);
case "usersmenu":
return ( $blnUIsAdminApp || $profile->userProfile_pUsersMenu );
return ($blnUIsAdminApp || $profile->userProfile_pUsersMenu);
case "users":
return ( $blnUIsAdminApp || $profile->userProfile_pUsers );
return ($blnUIsAdminApp || $profile->userProfile_pUsers);
case "groups":
return ( $blnUIsAdminApp || $profile->userProfile_pGroups );
return ($blnUIsAdminApp || $profile->userProfile_pGroups);
case "profiles":
return ( $blnUIsAdminApp || $profile->userProfile_pProfiles );
return ($blnUIsAdminApp || $profile->userProfile_pProfiles);
case "eventlog":
return ( $blnUIsAdminApp || $profile->userProfile_pEventlog );
return ($blnUIsAdminApp || $profile->userProfile_pEventlog);
}
$message['action'][] = __FUNCTION__;
$message['text'][] = _('Denegado acceso a') . " '" . $strAction . "'";
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
return FALSE;
return false;
}
/**
* @brief Comprueba los permisos de acceso a una cuenta
* @param string $action con la acción realizada
* @param array $accountData con los datos de la cuenta a verificar
* @return bool
*/
public static function checkAccountAccess($action, $accountData){
*/
public static function checkAccountAccess($action, $accountData)
{
$userGroupId = $_SESSION["ugroup"];
$userId = $_SESSION["uid"];
$userIsAdminApp = $_SESSION["uisadminapp"];
$userIsAdminAcc = $_SESSION["uisadminacc"];
switch ($action){
switch ($action) {
case "accview":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "accviewpass":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "accviewhistory":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "accedit":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "accdelete":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "acceditpass":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| (in_array($userId, $accountData['users_id']) && $accountData['otheruser_edit'])
|| (in_array($userGroupId, $accountData['groups_id']) && $accountData['othergroup_edit'])
|| $userIsAdminApp
|| $userIsAdminAcc);
case "acccopy":
return ( $userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc );
return ($userId == $accountData['user_id']
|| $userGroupId == $accountData['group_id']
|| in_array($userId, $accountData['users_id'])
|| in_array($userGroupId, $accountData['groups_id'])
|| $userIsAdminApp
|| $userIsAdminAcc);
}
return FALSE;
return false;
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,13 +23,14 @@
* 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 la autentificación de usuarios de sysPass.
*/
class SP_Auth {
class SP_Auth
{
static $userName;
static $userEmail;
@@ -39,12 +40,13 @@ class SP_Auth {
* @param string $userPass con la clave del usuario
* @return bool
*/
public static function authUserLDAP($userLogin, $userPass) {
if (!SP_Util::ldapIsAvailable() || !SP_Config::getValue('ldapenabled', FALSE) || !SP_LDAP::checkLDAPParams()) {
return FALSE;
public static function authUserLDAP($userLogin, $userPass)
{
if (!SP_Util::ldapIsAvailable() || !SP_Config::getValue('ldapenabled', false) || !SP_LDAP::checkLDAPParams()) {
return false;
}
$ldapAccess = FALSE;
$ldapAccess = false;
$message['action'] = __FUNCTION__;
// Conectamos al servidor realizamos la conexión con el usuario proxy
@@ -53,7 +55,7 @@ class SP_Auth {
SP_LDAP::ldapBind();
SP_LDAP::getUserDN($userLogin);
} catch (Exception $e) {
return FALSE;
return false;
}
$userDN = SP_LDAP::$ldapSearchData[0]['dn'];
@@ -77,7 +79,7 @@ class SP_Auth {
// Comprobamos si la cuenta está bloqueada o expirada
if (isset($attribs['expire']) && $attribs['expire'] > 0) {
return FALSE;
return false;
}
// Comprobamos que el usuario está en el grupo indicado buscando en los atributos del usuario
@@ -90,101 +92,110 @@ class SP_Auth {
// Comprobamos que el usuario está en el grupo indicado
if (self::checkLDAPGroup($group)) {
$ldapAccess = TRUE;
$ldapAccess = true;
break;
}
}
} else {
$ldapAccess = self::checkLDAPGroup($attribs['group']);
}
// Comprobamos que el usuario está en el grupo indicado buscando en los atributos del grupo
// Comprobamos que el usuario está en el grupo indicado buscando en los atributos del grupo
} else {
$ldapAccess = SP_LDAP::searchUserInGroup($userDN);
}
if ($ldapAccess == FALSE) {
if ($ldapAccess == false) {
$message['text'][] = _('El usuario no tiene grupos asociados');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
}
self::$userName = $attribs['name'];
self::$userEmail = $attribs['mail'];
return $ldapAccess;
}
/**
* @brief Autentificación de usuarios con MySQL
* @param string $userLogin con el login del usuario
* @param string $userPass con la clave del usuario
* @return bool
*
* Esta función comprueba la clave del usuario. Si el usuario necesita ser migrado desde phpPMS,
* se ejecuta el proceso para actualizar la clave.
*/
public static function authUserMySQL($userLogin, $userPass) {
if (SP_Users::checkUserIsMigrate($userLogin)) {
if (!SP_Users::migrateUser($userLogin, $userPass)) {
return FALSE;
}
}
$query = "SELECT user_login,"
. "user_pass "
. "FROM usrData "
. "WHERE user_login = '" . DB::escape($userLogin) . "' "
. "AND user_isMigrate = 0 "
. "AND user_pass = SHA1(CONCAT(user_hashSalt,'" . DB::escape($userPass) . "')) LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
if (count(DB::$last_result) == 0) {
return FALSE;
}
return TRUE;
}
/**
* @brief Comprobar si un usuario está deshabilitado
* @param string $userLogin con el login del usuario
* @return bool
*/
public static function checkUserIsDisabled($userLogin) {
$query = "SELECT user_isDisabled "
. "FROM usrData "
. "WHERE user_login = '" . DB::escape($userLogin) . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
}
if ($queryRes->user_isDisabled == 0) {
return FALSE;
}
return TRUE;
}
/**
* @brief Comprobar si el grupo de LDAP está habilitado
* @param string $group con el nombre del grupo
* @return bool
*/
private static function checkLDAPGroup($group) {
private static function checkLDAPGroup($group)
{
$ldapgroup = SP_Config::getValue('ldapgroup');
$groupName = array();
preg_match('/^cn=([\w\s-]+),.*/i', $group, $groupName);
if ($groupName[1] == $ldapgroup || $group == $ldapgroup) {
return TRUE;
return true;
}
return FALSE;
return false;
}
/**
* @brief Autentificación de usuarios con MySQL
* @param string $userLogin con el login del usuario
* @param string $userPass con la clave del usuario
* @return bool
*
* Esta función comprueba la clave del usuario. Si el usuario necesita ser migrado desde phpPMS,
* se ejecuta el proceso para actualizar la clave.
*/
public static function authUserMySQL($userLogin, $userPass)
{
if (SP_Users::checkUserIsMigrate($userLogin)) {
if (!SP_Users::migrateUser($userLogin, $userPass)) {
return false;
}
}
$query = "SELECT user_login,"
. "user_pass "
. "FROM usrData "
. "WHERE user_login = '" . DB::escape($userLogin) . "' "
. "AND user_isMigrate = 0 "
. "AND user_pass = SHA1(CONCAT(user_hashSalt,'" . DB::escape($userPass) . "')) LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
if (count(DB::$last_result) == 0) {
return false;
}
return true;
}
/**
* @brief Proceso para la recuperación de clave
* @param string $login con el login del usuario
* @param string $email con el email del usuario
* @return bool
*/
public static function mailPassRecover($login, $email)
{
if (SP_Users::checkUserMail($login, $email)
&& !SP_Users::checkUserIsDisabled($login)
&& !SP_Users::checkUserIsLDAP($login)
&& !SP_Users::checkPassRecoverLimit($login)
) {
$hash = SP_Util::generate_random_bytes();
$message['action'] = _('Recuperación de Clave');
$message['text'][] = SP_Html::strongText(_('Se ha solicitado la recuperación de su clave de usuario.'));
$message['text'][] = '';
$message['text'][] = _('Para completar el proceso es necesario que acceda a la siguiente URL:');
$message['text'][] = '';
$message['text'][] = SP_Html::anchorText(SP_Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time());
$message['text'][] = '';
$message['text'][] = _('Si no ha solicitado esta acción, ignore este mensaje.');
return (SP_Common::sendEmail($message, $email, false) && SP_Users::addPassRecover($login, $hash));
} else {
return false;
}
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,12 +23,14 @@
* 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 {
class SP_Category
{
public static $categoryName;
public static $categoryDescription;
public static $categoryLastId;
@@ -36,20 +38,21 @@ class SP_Category {
/**
* @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
* @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) {
public static function getCategoryIdByName($categoryName)
{
$query = "SELECT category_id "
. "FROM categories "
. "WHERE category_name = '" . DB::escape($categoryName) . "' LIMIT 1";
. "FROM categories "
. "WHERE category_name = '" . DB::escape($categoryName) . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
if (DB::$num_rows == 0) {
return FALSE;
return false;
} else {
return $queryRes->category_id;
}
@@ -57,55 +60,56 @@ 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 addCategory() {
public static function addCategory()
{
$query = "INSERT INTO categories "
. "SET category_name = '" . DB::escape(self::$categoryName) . "',"
. "category_description = '" . DB::escape(self::$categoryDescription) . "'";
. "SET category_name = '" . DB::escape(self::$categoryName) . "',"
. "category_description = '" . DB::escape(self::$categoryDescription) . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$categoryLastId = DB::$lastId;
$message['action'] = _('Nueva Categoría');
$message['text'][] = _('Nombre') . ': ' . self::$categoryName;
$message['text'][] = SP_Html::strongText(_('Categoría') . ': ') . self::$categoryName;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
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) {
public static function checkDupCategory($id = NULL)
{
if ($id === NULL) {
$query = "SELECT category_id "
. "FROM categories "
. "WHERE category_name = '" . DB::escape(self::$categoryName) . "'";
. "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;
. "FROM categories "
. "WHERE category_name = '" . DB::escape(self::$categoryName) . "' AND category_id <> " . $id;
}
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
return false;
}
return TRUE;
return true;
}
/**
@@ -113,86 +117,24 @@ class SP_Category {
* @param int $id con el id de la categoría
* @return bool
*/
public static function delCategory($id) {
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;
$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.')';
$message['text'][] = SP_Html::strongText(_('Categoría') . ': ') . $categoryName . ' (' . $id . ')';
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
/**
* @brief Actualizar una categoría en la BBDD con el id
* @param int $id con el Id de la categoría a consultar
* @return bool
*/
public static function updateCategory($id) {
$categoryName = self::getCategoryNameById($id);
$query = "UPDATE categories "
. "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_Log::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($id = NULL, $retAssocArray = FALSE) {
$query = "SELECT category_id,"
. "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) {
return array();
}
if ($retAssocArray) {
$resCategories = array();
foreach ($queryRes as $category) {
$resCategories[$category->category_id] = $category->category_name;
}
return $resCategories;
}
return $queryRes;
return true;
}
/**
@@ -200,25 +142,54 @@ class SP_Category {
* @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) {
public static function getCategoryNameById($id)
{
$query = "SELECT category_name "
. "FROM categories "
. "WHERE category_id = " . (int) $id;
. "FROM categories "
. "WHERE category_id = " . (int)$id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->category_name;
}
/**
* @brief Actualizar una categoría en la BBDD con el id
* @param int $id con el Id de la categoría a consultar
* @return bool
*/
public static function updateCategory($id)
{
$categoryName = self::getCategoryNameById($id);
$query = "UPDATE categories "
. "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'][] = SP_Html::strongText(_('Categoría') . ': ') . $categoryName . ' > ' . self::$categoryName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @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) {
public static function getCategoryData($id = 0)
{
$category = array('category_id' => 0,
'category_name' => '',
'category_description' => '',
@@ -237,15 +208,54 @@ class SP_Category {
return $category;
}
/**
* @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($id = NULL, $retAssocArray = false)
{
$query = "SELECT category_id,"
. "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) {
return array();
}
if ($retAssocArray) {
$resCategories = array();
foreach ($queryRes as $category) {
$resCategories[$category->category_id] = $category->category_name;
}
return $resCategories;
}
return $queryRes;
}
/**
* @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) {
public static function checkCategoryInUse($id)
{
$numAccounts = self::getCategoriesInAccounts($id);
@@ -259,7 +269,7 @@ class SP_Category {
return implode('<br>', $out);
}
return TRUE;
return true;
}
/**
@@ -267,15 +277,16 @@ class SP_Category {
* @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) {
private static function getCategoriesInAccounts($id)
{
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_categoryId = " . (int) $id;
. "FROM accounts "
. "WHERE account_categoryId = " . (int)$id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;

View File

@@ -1,11 +1,11 @@
<?php
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -28,93 +28,118 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
/**
* Esta clase es encargada de ejecutar acciones comunes para las funciones
*/
class SP_Common {
/**
* @brief Crear un nuevo registro en el registro de eventos
* @param array $message con el nombre de la accióm y el texto del mensaje
* @return bool
*/
public static function wrLogInfo($message) {
if (SP_Config::getValue('logenabled', 0) === 0 || !is_array($message)) {
return FALSE;
}
$login = ( isset($_SESSION["ulogin"]) ) ? $_SESSION["ulogin"] : "-";
$userId = ( isset($_SESSION['uid']) ) ? $_SESSION['uid'] : 0;
$action = utf8_encode($message['action']);
$description = utf8_encode(implode(';;', $message['text']));
$query = "INSERT INTO log SET
log_date = UNIX_TIMESTAMP(),
log_login = '" . DB::escape($login) . "',
log_userId = " . $userId . ",
log_action = '" . DB::escape($action) . "',
log_description = '" . DB::escape($description) . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
}
}
class SP_Common
{
/**
* @brief Enviar un email
* @param array $message con el nombre de la accióm y el texto del mensaje
* @param string $mailTo con el destinatario
* @param bool $isEvent para indicar si es um
* @return bool
* @todo Autentificación
* @todo Permitir HTML
*/
public static function sendEmail($message, $mailTo = "") {
*/
public static function sendEmail($message, $mailTo = '', $isEvent = true)
{
if (SP_Config::getValue('mailenabled', 0) === 0) {
return FALSE;
return false;
}
if (!is_array($message)) {
return FALSE;
return false;
}
$info = SP_Html::getAppInfo();
$replyTo = SP_Config::getValue('mailfrom');
$strFrom = SP_Config::getValue('mailfrom');
$mailSubject = _('Aviso') . ' ' . $info['appname'] . ' - ' . $message['action'];
$mail = self::getEmailObject($mailTo, $message['action']);
// Para enviar un correo HTML mail, la cabecera Content-type debe fijarse
$headers[] = 'MIME-Version: 1.0';
// HTML Version
//$strHead .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers[] = 'Content-Type: text/plain;charset=utf-8';
if (!is_object($mail)) {
return false;
}
// Cabeceras adicionales
//$strHead .= "To: $strDestinatario \r\n";
$headers[] = "From: " . $info['appname'] . " <$strFrom>";
$headers[] = "Reply-To: $replyTo";
$headers[] = "Cc: $strFrom";
$mail->isHTML();
$newline = '<br>';
$mailbody = _('Acción') . ": " . $message['action'] . "\r\n";
$mailbody .= _('Realizado por') . ": " . $_SESSION["ulogin"] . "\r\n";
$mailbody .= (is_array($message['text'])) ? implode("\r\n",$message['text']) : '';
if ($isEvent === true) {
$performer = (isset($_SESSION["ulogin"])) ? $_SESSION["ulogin"] : _('N/D');
$body[] = SP_Html::strongText(_('Acción') . ": ") . $message['action'];
$body[] = SP_Html::strongText(_('Realizado por') . ": ") . $performer . ' (' . $_SERVER['REMOTE_ADDR'] . ')';
$mail->addCC(SP_Config::getValue('mailfrom'));
}
$body[] = (is_array($message['text'])) ? implode($newline, $message['text']) : '';
$body[] = '';
$body[] = '--';
$body[] = SP_Html::getAppInfo('appname') . ' - ' . SP_Html::getAppInfo('appdesc');
$body[] = SP_Html::anchorText(SP_Init::$WEBURI);
$mail->Body = implode($newline, $body);
$sendMail = $mail->send();
$mailHeader = implode("\r\n", $headers);
$log['action'] = _('Enviar Email');
$sendMail = mail($mailTo, $mailSubject, $mailbody, $mailHeader);
// Enviar correo
if ( $sendMail ){
$log['text'][]= _('Correo enviado');
} else{
if ($sendMail) {
$log['text'][] = _('Correo enviado');
} else {
$log['text'][] = _('Error al enviar correo');
$log['text'][] = 'ERROR: ' . $mail->ErrorInfo;
}
$log['text'][] = _('Destinatario').": $mailTo";
$log['text'][] = _('CC').": $strFrom";
$log['text'][] = '';
$log['text'][] = _('Destinatario') . ": $mailTo";
$log['text'][] = ($isEvent === true) ? _('CC') . ": " . SP_Config::getValue('mailfrom') : '';
self::wrLogInfo($log);
return $sendMail;
$log['action'] = _('Enviar Email');
SP_Log::wrLogInfo($log);
return $sendMail;
}
/**
* @brief Inicializar la clase PHPMailer
* @param string $mailTo con la dirección del destinatario
* @param string $action con la acción realizada
* @return object
*/
public static function getEmailObject($mailTo, $action)
{
$appName = SP_Html::getAppInfo('appname');
$mailFrom = SP_Config::getValue('mailfrom');
$mailServer = SP_Config::getValue('mailserver');
$mailPort = SP_Config::getValue('mailport', 25);
$mailUser = SP_Config::getValue('mailuser');
$mailPass = SP_Config::getValue('mailpass');
if (!$mailServer) {
return false;
}
if (empty($mailTo)) {
$mailTo = $mailFrom;
}
$phpmailerPath = EXTENSIONS_DIR . DIRECTORY_SEPARATOR . 'phpmailer';
require_once $phpmailerPath . DIRECTORY_SEPARATOR . 'class.phpmailer.php';
require_once $phpmailerPath . DIRECTORY_SEPARATOR . 'class.smtp.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->CharSet = 'utf-8';
$mail->SMTPAuth = true;
$mail->Host = $mailServer;
$mail->Port = $mailPort;
$mail->Username = $mailUser;
$mail->Password = $mailPass;
$mail->SMTPSecure = strtolower(SP_Config::getValue('mailsecurity'));
//$mail->SMTPDebug = 2;
//$mail->Debugoutput = 'error_log';
$mail->setFrom($mailFrom, $appName);
$mail->addAddress($mailTo);
$mail->addReplyTo($mailFrom, $appName);
$mail->WordWrap = 100;
$mail->Subject = $appName . ' (' . _('Aviso') . ') - ' . $action;
return $mail;
}
/**
@@ -123,9 +148,10 @@ class SP_Common {
* @param int $status devuelve el estado
* @return string documento XML
*/
public static function printXML($description, $status = 1) {
public static function printXML($description, $status = 1)
{
if (!is_string($description)) {
return FALSE;
return false;
}
$arrStrFrom = array("&", "<", ">", "\"", "\'");
@@ -135,7 +161,7 @@ class SP_Common {
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<root>\n<status>" . $status . "</status>\n <description>" . $cleanDescription . "</description>\n</root>";
header("Content-Type: application/xml");
exit($xml);
}
@@ -144,31 +170,34 @@ class SP_Common {
* @brief Devuelve una respuesta en formato JSON con el estado y el mensaje
* @param string $description mensaje a devolver
* @param int $status devuelve el estado
* @param string $action con la accion a realizar
* @return string respuesta JSON
*/
public static function printJSON($description, $status = 1) {
public static function printJSON($description, $status = 1, $action = '')
{
if (!is_string($description)) {
return FALSE;
return false;
}
$arrStrFrom = array("&", "<", ">", "\"", "\'");
$arrStrTo = array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;");
$arrStrFrom = array("\\", '"', "'");
$arrStrTo = array("\\", '\"', "\'");
$cleanDescription = str_replace($arrStrFrom, $arrStrTo, $description);
$json = array('status' => $status, 'description' => $cleanDescription);
$json = array('status' => $status, 'description' => $cleanDescription, 'action' => $action);
header('Content-type: application/json');
exit(json_encode($json));
}
/**
* @brief Devuelve un icono de ayuda con el mensaje
* @param int $type tipo de mensaje
* @param int $id id del mensaje
* @return string con la etiqueta html <img>
*/
public static function printHelpButton($type, $id) {
public static function printHelpButton($type, $id)
{
$msgHelp[0] = _('Indicar el usuario de conexión a la base de datos de phpPMS');
$msgHelp[1] = _('Indicar el nombre de la base de datos de phpPMS');
$msgHelp[2] = _('Indicar el servidor de la base de datos de phpPMS');
@@ -203,13 +232,14 @@ class SP_Common {
* @brief Devuelve un hash para verificación de formularios
* @param bool $new si es necesrio regenerar el hash
* @return string con el hash de verificación
*
*
* Esta función genera un hash que permite verificar la autenticidad de un formulario
*/
public static function getSessionKey($new = FALSE) {
public static function getSessionKey($new = false)
{
$hash = sha1(time());
if (!isset($_SESSION["sk"]) || $new === TRUE) {
if (!isset($_SESSION["sk"]) || $new === true) {
$_SESSION["sk"] = $hash;
return $hash;
}
@@ -220,14 +250,15 @@ class SP_Common {
/**
* @brief Comprobar el hash de verificación de formularios
* @param string $key con el hash a comprobar
* @return boo|string si no es correcto el hash devuelve bool. Si lo es, devuelve el hash actual.
* @return bool|string si no es correcto el hash devuelve bool. Si lo es, devuelve el hash actual.
*/
public static function checkSessionKey($key) {
if (!isset($_SESSION["sk"]) || $_SESSION["sk"] == "" || !$key){
return FALSE;
public static function checkSessionKey($key)
{
if (!isset($_SESSION["sk"]) || $_SESSION["sk"] == "" || !$key) {
return false;
}
return ( $_SESSION["sk"] == $key );
return ($_SESSION["sk"] == $key);
}
/**
@@ -237,51 +268,52 @@ class SP_Common {
* @param mixed $default opcional, valor por defecto a devolver
* @param bool $onlyCHeck opcional, comprobar si el parámetro está presente
* @param mixed $force opcional, valor devuelto si el parámeto está definido
* @return boo|string si está presente el parámeto en la petición devuelve bool. Si lo está, devuelve el valor.
* @return bool|string si está presente el parámeto en la petición devuelve bool. Si lo está, devuelve el valor.
*/
public static function parseParams($method, $param, $default = '', $onlyCHeck = FALSE, $force = FALSE){
public static function parseParams($method, $param, $default = '', $onlyCHeck = false, $force = false)
{
$out = '';
switch ($method){
switch ($method) {
case 'g':
if ( !isset($_GET[$param]) ){
if (!isset($_GET[$param])) {
return $default;
}
$out = $_GET[$param];
break;
case 'p':
if ( !isset($_POST[$param]) ){
if (!isset($_POST[$param])) {
return $default;
}
$out = $_POST[$param];
break;
case 's':
if ( !isset($_SESSION[$param]) ){
if (!isset($_SESSION[$param])) {
return $default;
}
$out = $_SESSION[$param];
break;
default :
return FALSE;
return false;
}
if ( $onlyCHeck ){
return TRUE;
if ($onlyCHeck) {
return true;
}
if ($force){
if ($force) {
return $force;
}
if (is_numeric($out) && is_numeric($default)){
if (is_numeric($out) && is_numeric($default)) {
return (int)$out;
}
if (is_string($out)){
return ( $method != 's' ) ? SP_Html::sanitize($out) : $out;
if (is_string($out)) {
return ($method != 's') ? SP_Html::sanitize($out) : $out;
}
if (is_array($out)){
if (is_array($out)) {
return $out;
}
}

View File

@@ -1,27 +1,27 @@
<?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-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'));
@@ -40,14 +40,14 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
* Esta clase es responsable de leer y escribir la configuración del archivo config.php
* y en la base de datos
*/
class SP_Config{
class SP_Config
{
// Array asociativo clave => valor
private static $cache = array();
// La caché está llena??
private static $init = false;
// Configuracion actual en array
static $arrConfigValue;
private static $cache = array(); // Configuracion actual en array
private static $init = false; // La caché está llena??
/**
* @brief Obtiene un valor desde la configuración en la BBDD
* @param string $param con el parámetro de configuración
@@ -55,39 +55,41 @@ class SP_Config{
*
* Obtener el valor de un parámetro almacenado en la BBDD
*/
public static function getConfigValue($param){
public static function getConfigValue($param)
{
$query = "SELECT config_value "
. "FROM config "
. "WHERE config_parameter = '$param'";
. "FROM config "
. "WHERE config_parameter = '$param'";
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->config_value;
}
/**
* @brief Obtener array con la configuración
*
* Obtener un array con la configuración almacenada en la BBDD
*/
public static function getConfig(){
public static function getConfig()
{
$query = "SELECT config_parameter,"
. "config_value "
. "FROM config";
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
. "config_value "
. "FROM config";
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
foreach ( $queryRes as $config ){
foreach ($queryRes as $config) {
$strKey = $config->config_parameter;
$strValue = $config->config_value;
self::$arrConfigValue[$strKey] = $strValue;
}
}
@@ -98,34 +100,35 @@ class SP_Config{
*
* Guardar la configuración en la BBDD
*/
public static function writeConfig($mkInsert = FALSE){
public static function writeConfig($mkInsert = false)
{
foreach (self::$arrConfigValue as $key => $value) {
$key = DB::escape($key);
$value = DB::escape($value);
if ( $mkInsert ){
if ($mkInsert) {
$query = "INSERT INTO config "
. "VALUES ('$key','$value') "
. "ON DUPLICATE KEY UPDATE config_value = '$value' ";
. "VALUES ('$key','$value') "
. "ON DUPLICATE KEY UPDATE config_value = '$value' ";
} else {
$query = "UPDATE config SET "
. "config_value = '$value' "
. "WHERE config_parameter = '$key'";
. "config_value = '$value' "
. "WHERE config_parameter = '$key'";
}
if ( DB::doQuery($query, __FUNCTION__) === FALSE ){
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
}
$message['action'] = _('Configuración');
$message['text'][] = _('Modificar configuración');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
return true;
}
/**
* @brief Guardar un parámetro de configuración
@@ -133,14 +136,15 @@ class SP_Config{
* @param string $value con el calor a guardar
* @return bool
*/
public static function setConfigValue($param, $value) {
public static function setConfigValue($param, $value)
{
$query = "INSERT INTO config "
. "SET config_parameter = '" . DB::escape($param) . "',"
. "config_value = '" . DB::escape($value) . "'"
. "ON DUPLICATE KEY UPDATE config_value = '" . DB::escape($value) . "' ";
. "SET config_parameter = '" . DB::escape($param) . "',"
. "config_value = '" . DB::escape($value) . "'"
. "ON DUPLICATE KEY UPDATE config_value = '" . DB::escape($value) . "' ";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
$message['action'] = _('Configuración');
@@ -148,10 +152,10 @@ class SP_Config{
$message['text'][] = _('Parámetro') . ': ' . $param;
$message['text'][] = _('Valor') . ': ' . $value;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
return true;
}
/**
@@ -161,36 +165,37 @@ class SP_Config{
*
* Cargar la configuración desde la BBDD y guardarla en una variable global $CFG
*/
public static function getDBConfig($force = FALSE){
public static function getDBConfig($force = false)
{
global $CFG;
if ( isset ($CFG) && ! $force ){
return TRUE;
if (isset ($CFG) && !$force) {
return true;
}
$query = "SELECT config_parameter,"
. "config_value "
. "FROM config";
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
. "config_value "
. "FROM config";
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
foreach ( $queryRes as $config ){
foreach ($queryRes as $config) {
$cfgParam = $config->config_parameter;
$cfgValue = $config->config_value;
if ( strstr($cfgValue, "||") ){
$cfgValue = explode ("||",$cfgValue);
if (strstr($cfgValue, "||")) {
$cfgValue = explode("||", $cfgValue);
}
$CFG["$cfgParam"] = $cfgValue;
}
return TRUE;
}
return true;
}
/**
* @brief Realizar backup de la BBDD y aplicación
* @return array resultado
@@ -198,82 +203,65 @@ class SP_Config{
* Realizar un backup completo de la BBDD y de la aplicación.
* Sólo es posible en entornos Linux
*/
public static function makeBackup(){
if ( SP_Util::runningOnWindows() ){
public static function makeBackup()
{
if (SP_Util::runningOnWindows()) {
$arrOut['error'] = _('Esta operación sólo es posible en entornos Linux');
return $arrOut;
}
$arrOut = array();
$error = 0;
$siteName = SP_Html::getAppInfo('appname');
$backupDir = SP_Init::$SERVERROOT;
$bakDstDir = $backupDir.'/backup';
$bakFile = $backupDir.'/backup/'.$siteName.'.tgz';
$bakFileDB = $backupDir.'/backup/'.$siteName.'_db.sql';
if ( ! is_dir($bakDstDir) ){
if ( ! @mkdir($bakDstDir, 0550) ){
$arrOut['error'] = _('No es posible crear el directorio de backups').' ('.$bakDstDir.')';
$bakDstDir = $backupDir . '/backup';
$bakFile = $backupDir . '/backup/' . $siteName . '.tgz';
$bakFileDB = $backupDir . '/backup/' . $siteName . '_db.sql';
if (!is_dir($bakDstDir)) {
if (!@mkdir($bakDstDir, 0550)) {
$arrOut['error'] = _('No es posible crear el directorio de backups') . ' (' . $bakDstDir . ')';
$message['action'] = _('Copia BBDD');
$message['text'][] = _('No es posible crear el directorio de backups');
$message['text'][] = "IP: ".$_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
$error = 1;
}
}
if ( ! is_writable($bakDstDir) ){
if (!is_writable($bakDstDir)) {
$arrOut['error'] = _('Compruebe los permisos del directorio de backups');
$error = 1;
}
if ( $error == 0 ){
if ($error == 0) {
$message['action'] = _('Copia BBDD');
$message['text'][] = "IP: ".$_SERVER['REMOTE_ADDR'];
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
$dbhost = SP_Config::getValue("dbhost");
$dbuser = SP_Config::getValue("dbuser");
$dbpass = SP_Config::getValue("dbpass");
$dbname = SP_Config::getValue("dbname");
// Backup de la BBDD
$command = 'mysqldump -h '.$dbhost.' -u '.$dbuser.' -p'.$dbpass.' -r "'.$bakFileDB.'" '.$dbname.' 2>&1';
$command = 'mysqldump -h ' . $dbhost . ' -u ' . $dbuser . ' -p' . $dbpass . ' -r "' . $bakFileDB . '" ' . $dbname . ' 2>&1';
exec($command, $resOut, $resBakDB);
// Backup de la Aplicación
$command = 'tar czf '.$bakFile.' '.$backupDir.' --exclude "'.$bakDstDir.'" 2>&1';
$command = 'tar czf ' . $bakFile . ' ' . $backupDir . ' --exclude "' . $bakDstDir . '" 2>&1';
exec($command, $resOut, $resBakApp);
if ( $resBakApp != 0 || $resBakDB != 0 ){
if ($resBakApp != 0 || $resBakDB != 0) {
$arrOut['error'] = implode('<br>', $resOut);
}
}
return $arrOut;
}
/**
* @brief Lista todas las claves de configuración
* @return array con nombres de claves
*
* Esta función devuelve todas las claves guardadas en config.php.
*/
public static function getKeys($full = FALSE){
self::readData();
if ( $full ){
return self::$cache;
}
return array_keys( self::$cache );
return $arrOut;
}
/**
@@ -285,75 +273,35 @@ class SP_Config{
* Esta función obtiene un valor desde config.php. Si no existe,
* $default será defuelto.
*/
public static function getValue( $key, $default = null ) {
public static function getValue($key, $default = null)
{
self::readData();
if( array_key_exists( $key, self::$cache )) return self::$cache[$key];
if (array_key_exists($key, self::$cache)) return self::$cache[$key];
return $default;
}
/**
* @brief Establece un valor
* @param string $key clave
* @param string $value valor
* @return bool
*
* Esta función establece el valor y reescribe config.php. Si el archivo
* no se puede escribir, devolverá false.
*/
public static function setValue( $key, $value ) {
self::readData();
// Add change
self::$cache[$key] = $value;
// Write changes
self::writeData();
return true;
}
/**
* @brief Elimina una clave de la configuración
* @param string $key clave
* @return bool
*
* Esta función elimina una clave de config.php. Si no tiene permiso
* de escritura en config.php, devolverá false.
*/
public static function deleteKey( $key ) {
self::readData();
if( array_key_exists( $key, self::$cache )) {
// Delete key from cache
unset( self::$cache[$key] );
// Write changes
self::writeData();
}
return true;
}
/**
* @brief Carga el archivo de configuración
* @return bool
*
* Lee el archivo de configuración y lo guarda en caché
*/
private static function readData() {
if( self::$init ) {
private static function readData()
{
if (self::$init) {
return true;
}
if( !file_exists( SP_Init::$SERVERROOT."/config/config.php" )){
if (!file_exists(SP_Init::$SERVERROOT . "/config/config.php")) {
return false;
}
// Include the file, save the data from $CONFIG
include SP_Init::$SERVERROOT."/config/config.php";
if( isset($CONFIG) && is_array($CONFIG) ) {
include SP_Init::$SERVERROOT . "/config/config.php";
if (isset($CONFIG) && is_array($CONFIG)) {
self::$cache = $CONFIG;
}
@@ -363,48 +311,96 @@ class SP_Config{
return true;
}
/**
* @brief Lista todas las claves de configuración
* @param bool $full obtener todas las claves y sus valores
* @return array con nombres de claves
*
* Esta función devuelve todas las claves guardadas en config.php.
*/
public static function getKeys($full = false)
{
self::readData();
if ($full) {
return self::$cache;
}
return array_keys(self::$cache);
}
/**
* @brief Elimina una clave de la configuración
* @param string $key clave
* @return bool
*
* Esta función elimina una clave de config.php. Si no tiene permiso
* de escritura en config.php, devolverá false.
*/
public static function deleteKey($key)
{
self::readData();
if (array_key_exists($key, self::$cache)) {
// Delete key from cache
unset(self::$cache[$key]);
// Write changes
self::writeData();
}
return true;
}
/**
* @brief Escribe en archivo de configuración
* @return bool
*/
public static function writeData() {
$content = "<?php\n\$CONFIG = ";
$content .= trim(var_export(self::$cache, true),',');
public static function writeData()
{
ksort(self::$cache);
$content = "<?php\n";
$content .= "// Generated on " . time() . "\n";
$content .= "// This file is generated automatically on installation process\n// Please, modify with caution, it could break the application\n";
$content .= "\$CONFIG = ";
$content .= trim(var_export(self::$cache, true), ',');
$content .= ";\n";
$filename = SP_Init::$SERVERROOT."/config/config.php";
// Write the file
$result=@file_put_contents( $filename, $content );
if( ! $result ) {
$errors[] = array(
'type' => 'critical',
'description' => _('No es posible escribir el archivo de configuración'),
'hint' => 'Compruebe los permisos del directorio "config"');
$filename = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
SP_Html::render('error',$errors);
// Write the file
$result = @file_put_contents($filename, $content);
if (!$result) {
$errors[] = array(
'type' => 'critical',
'description' => _('No es posible escribir el archivo de configuración'),
'hint' => _('Compruebe los permisos del directorio "config"'));
SP_Html::render('error', $errors);
exit();
}
// Prevent others not to read the config
@chmod($filename, 0640);
return TRUE;
return true;
}
/**
* @brief Establece los valores de configuración por defecto en config.php
* @return none
*/
public static function setDefaultValues(){
*/
public static function setDefaultValues()
{
self::setValue('logenabled', 1);
self::setValue('debug', 0);
self::setValue('ldapenabled', 0);
self::setValue('mailenabled', 0);
self::setValue('wikienabled', 0);
self::setValue('demoenabled', 0);
self::setValue('allowed_exts', 'PDF,JPG,GIF,PNG,ODT,ODS,DOC,DOCX,XLS,XSL,VSD,TXT,CSV,BAK');
self::setValue('allowed_size', 1024);
self::setValue('wikisearchurl', '');
@@ -420,6 +416,27 @@ class SP_Config{
self::setValue('sitelang', 'es_ES');
self::setValue('session_timeout', '300');
self::setValue('account_link', 1);
self::setValue('account_count', 10);
self::setValue('account_count', 12);
}
/**
* @brief Establece un valor
* @param string $key clave
* @param string $value valor
* @return bool
*
* Esta función establece el valor y reescribe config.php. Si el archivo
* no se puede escribir, devolverá false.
*/
public static function setValue($key, $value)
{
self::readData();
// Add change
self::$cache[$key] = $value;
// Write changes
self::writeData();
return true;
}
}

View File

@@ -1,44 +1,167 @@
<?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-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 el encriptad/desencriptado de claves
*/
class SP_Crypt {
class SP_Crypt
{
public $strInitialVector;
/**
* @brief Comprobar si el módulo de encriptación está disponible
* @return bool
*/
public static function checkCryptModule()
{
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
if ($resEncDes == false) {
return false;
} else {
return true;
}
}
/**
* @brief Generar un hash de una clave utilizando un salt
* @param string $pwd con la clave a 'hashear'
* @return string con el hash de la clave
*/
public static function mkHashPassword($pwd)
{
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); // Obtenemos 256 bits aleatorios en hexadecimal
$hash = hash("sha256", $salt . $pwd); // Añadimos el salt a la clave y rehacemos el hash
$hashPwd = $salt . $hash;
return $hashPwd;
}
/**
* @brief Comprobar el hash de una clave
* @param string $pwd con la clave a comprobar
* @param string $correctHash con el hash a comprobar
* @return bool
*/
public static function checkHashPass($pwd, $correctHash)
{
// Obtenemos el salt de la clave
$salt = substr($correctHash, 0, 64);
// Obtenemos el hash SHA256
$validHash = substr($correctHash, 64, 64);
// Re-hash de la clave a comprobar
$testHash = hash("sha256", $salt . $pwd);
// Si los hashes son idénticos, la clave es válida
if ($testHash === $validHash) {
return true;
}
return false;
}
/**
* @brief Crear un salt
* @return string con el salt creado
*/
public static function makeHashSalt()
{
do {
$cryptIV = self::createIV();
$blnCheckIv = self::checkIV($cryptIV);
} while ($blnCheckIv == false);
return $cryptIV;
}
/**
* @brief Generar una clave encriptada
* @param string $pwd con la clave a encriptar
* @param string $masterPwd con la clave maestra
* @return bool
*
* Esta función llama a los métodos privados para encriptar datos.
*/
public function mkEncrypt($pwd, $masterPwd = "")
{
$masterPwd = (!$masterPwd) ? $this->getSessionMasterPass() : $masterPwd;
do {
do {
$cryptIV = SP_Crypt::createIV();
$blnCheckIv = SP_Crypt::checkIV($cryptIV);
} while ($blnCheckIv == false);
$this->strInitialVector = $cryptIV;
$cryptValue = $this->encrypt($pwd, $masterPwd, $cryptIV);
$blnCheckEncrypted = $this->checkEncryptedPass($cryptValue);
} while ($blnCheckEncrypted == false);
return $cryptValue;
}
/**
* @brief Desencriptar la clave maestra de la sesión
* @return string con la clave maestra
*/
public function getSessionMasterPass()
{
return $this->decrypt($_SESSION["mPass"], $_SESSION['mPassPwd'], $_SESSION['mPassIV']);
}
/**
* @brief Desencriptar datos con la clave maestra
* @param string $strEncrypted con los datos a desencriptar
* @param string $strPassword con la clave maestra
* @param string $cryptIV con el IV
* @return string con los datos desencriptados
*/
public function decrypt($strEncrypted, $strPassword, $cryptIV)
{
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
mcrypt_generic_init($resEncDes, $strPassword, $cryptIV);
$strDecrypted = trim(mdecrypt_generic($resEncDes, $strEncrypted));
mcrypt_generic_deinit($resEncDes);
mcrypt_module_close($resEncDes);
return $strDecrypted;
}
/**
* @brief Crear el vector de inicialización
* @return string con el IV
*/
private static function createIV() {
*/
private static function createIV()
{
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
if ( SP_Util::runningOnWindows() && (! defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) ){
if (SP_Util::runningOnWindows() && (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300)) {
$cryptIV = mcrypt_create_iv(mcrypt_enc_get_iv_size($resEncDes), MCRYPT_RAND);
} else {
$cryptIV = mcrypt_create_iv(mcrypt_enc_get_iv_size($resEncDes), MCRYPT_DEV_URANDOM);
@@ -52,14 +175,15 @@ class SP_Crypt {
* @brief Comprobar si el vector de inicialización tiene la longitud correcta
* @param string $cryptIV con el IV
* @return bool
*/
private static function checkIV($cryptIV){
*/
private static function checkIV($cryptIV)
{
$strEscapeInitialVector = DB::escape($cryptIV);
if (strlen($strEscapeInitialVector) != 32 ) {
return FALSE;
if (strlen($strEscapeInitialVector) != 32) {
return false;
} else {
return TRUE;
return true;
}
}
@@ -69,8 +193,9 @@ class SP_Crypt {
* @param string $strPassword con la clave maestra
* @param string $cryptIV con el IV
* @return string con los datos encriptados
*/
private function encrypt($strValue, $strPassword, $cryptIV){
*/
private function encrypt($strValue, $strPassword, $cryptIV)
{
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
mcrypt_generic_init($resEncDes, $strPassword, $cryptIV);
$strEncrypted = mcrypt_generic($resEncDes, $strValue);
@@ -79,162 +204,47 @@ class SP_Crypt {
return $strEncrypted;
}
/**
* @brief Desencriptar datos con la clave maestra
* @param string $strEncrypted con los datos a desencriptar
* @param string $strPassword con la clave maestra
* @param string $cryptIV con el IV
* @return string con los datos desencriptados
*/
public function decrypt($strEncrypted, $strPassword, $cryptIV){
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
mcrypt_generic_init($resEncDes, $strPassword, $cryptIV);
$strDecrypted = trim(mdecrypt_generic($resEncDes, $strEncrypted));
mcrypt_generic_deinit($resEncDes);
mcrypt_module_close($resEncDes);
return $strDecrypted;
}
/**
* @brief Comprobar si el módulo de encriptación está disponible
* @param string $strEncrypted con los datos a desencriptar
* @param string $strPassword con la clave maestra
* @param string $cryptIV con el IV
* @return string con los datos desencriptados
*/
public static function checkCryptModule(){
$resEncDes = mcrypt_module_open('rijndael-256', '', 'cbc', '');
if ($resEncDes == FALSE ) {
return FALSE;
} else {
return TRUE;
}
}
/**
* @brief Comprobar datos encriptados
* @param string $strEncryptedPass con los datos encriptados
* @return bool
*
* Esta función comprueba la longitud de los datos encriptados despues de
*
* Esta función comprueba la longitud de los datos encriptados despues de
* escaparlos con mysqli
*/
private function checkEncryptedPass($strEncryptedPass){
*/
private function checkEncryptedPass($strEncryptedPass)
{
$strEscapedEncryptedPass = DB::escape($strEncryptedPass);
if (strlen($strEscapedEncryptedPass) != strlen($strEncryptedPass) ) {
return FALSE;
if (strlen($strEscapedEncryptedPass) != strlen($strEncryptedPass)) {
return false;
} else {
return TRUE;
return true;
}
}
/**
* @brief Generar una clave encriptada
* @param string $pwd con la clave a encriptar
* @param string $masterPwd con la clave maestra
* @return bool
*
* Esta función llama a los métodos privados para encriptar datos.
*/
public function mkEncrypt($pwd,$masterPwd = ""){
$masterPwd = ( ! $masterPwd ) ? $this->getSessionMasterPass() : $masterPwd;
do {
do {
$cryptIV = SP_Crypt::createIV();
$blnCheckIv = SP_Crypt::checkIV($cryptIV);
} while ($blnCheckIv == FALSE);
$this->strInitialVector = $cryptIV;
$cryptValue = $this->encrypt($pwd, $masterPwd, $cryptIV);
$blnCheckEncrypted = $this->checkEncryptedPass($cryptValue);
} while ($blnCheckEncrypted == FALSE );
return $cryptValue;
}
/**
* @brief Generar la clave maestra encriptada con la clave del usuario
* @param string $customPwd con la clave a encriptar
* @param string $masterPwd con la clave maestra
* @return string con la clave encriptada
*
*
* Esta función llama a los métodos privados para encriptar datos.
*/
public function mkCustomMPassEncrypt($customPwd,$masterPwd){
*/
public function mkCustomMPassEncrypt($customPwd, $masterPwd)
{
do {
do {
$cryptIV = SP_Crypt::createIV();
$blnCheckIv = SP_Crypt::CheckIV($cryptIV);
} while ($blnCheckIv == FALSE);
} while ($blnCheckIv == false);
$cryptValue = $this->encrypt($masterPwd, $customPwd, $cryptIV);
$blnCheckEncrypted = $this->checkEncryptedPass($cryptValue);
} while ($blnCheckEncrypted == FALSE );
} while ($blnCheckEncrypted == false);
$dataCrypt = array($cryptValue, $cryptIV);
return $dataCrypt;
}
/**
* @brief Generar un hash de una clave utilizando un salt
* @param string $pwd con la clave a 'hashear'
* @return string con el hash de la clave
*/
public static function mkHashPassword($pwd){
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); // Obtenemos 256 bits aleatorios en hexadecimal
$hash = hash("sha256", $salt.$pwd); // Añadimos el salt a la clave y rehacemos el hash
$hashPwd = $salt.$hash;
return $hashPwd;
}
/**
* @brief Comprobar el hash de una clave
* @param string $pwd con la clave a comprobar
* @param string $correctHash con el hash a comprobar
* @return bool
*/
public static function checkHashPass($pwd, $correctHash){
// Obtenemos el salt de la clave
$salt = substr($correctHash, 0, 64);
// Obtenemos el hash SHA256
$validHash = substr($correctHash, 64, 64);
// Re-hash de la clave a comprobar
$testHash = hash("sha256", $salt . $pwd);
// Si los hashes son idénticos, la clave es válida
if ( $testHash === $validHash ){
return TRUE;
}
return FALSE;
}
/**
* @brief Crear un salt
* @return string con el salt creado
*/
public static function makeHashSalt(){
do {
$cryptIV = self::createIV();
$blnCheckIv = self::checkIV($cryptIV);
} while ($blnCheckIv == FALSE);
return $cryptIV;
}
/**
* @brief Desencriptar la clave maestra de la sesión
* @return string con la clave maestra
*/
public function getSessionMasterPass(){
return $this->decrypt($_SESSION["mPass"], $_SESSION['mPassPwd'], $_SESSION['mPassIV']);
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,135 +23,54 @@
* 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
{
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($customerId = NULL, $retAssocArray = FALSE) {
$query = "SELECT customer_id,"
. "customer_name, "
. "customer_description "
. "FROM customers ";
if (!is_null($customerId)) {
$query .= "WHERE customer_id = " . (int) $customerId . " LIMIT 1";
} else {
$query .= "ORDER BY customer_name";
}
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ($queryRes === FALSE) {
return array();
}
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 static function addCustomer() {
public static function addCustomer()
{
$query = "INSERT INTO customers "
. "SET customer_name = '" . DB::escape(self::$customerName) . "',"
. "customer_hash = '" . self::mkCustomerHash() . "'";
. "SET customer_name = '" . DB::escape(self::$customerName) . "',"
. "customer_hash = '" . self::mkCustomerHash() . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$customerLastId = DB::$lastId;
$message['action'] = _('Nuevo Cliente');
$message['text'][] = _('Nombre') . ': ' . self::$customerName;
$message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . self::$customerName;
SP_Common::wrLogInfo($message);
SP_Log::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 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;
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 static function mkCustomerHash() {
private static function mkCustomerHash()
{
$charsSrc = array(
".", " ", "_", ", ", "-", ";
", "'", "\"", ":", "(", ")", "|", "/");
@@ -162,46 +81,56 @@ class SP_Customer {
}
/**
* @brief Comprobar si existe un cliente duplicado comprobando el hash
* @brief Actualizar un cliente en la BBDD
* @param int $id con el Id del cliente
* @return bool
*/
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 (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
public static function updateCustomer($id)
{
$customerName = self::getCustomerById($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;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
}
$message['action'] = _('Actualizar Cliente');
$message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $customerName . ' > ' . self::$customerName;
return TRUE;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Obtener el Id de un cliente por su nombre
* @return int con el Id del cliente
* @brief Eliminar un cliente de la BBDD
* @param int $id con el Id del cliente a eliminar
* @return bool
*/
public static function getCustomerByName() {
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '" . self::mkCustomerHash() . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
public static function delCustomer($id)
{
$customerName = self::getCustomerById($id);
if ($queryRes === FALSE) {
return FALSE;
$query = "DELETE FROM customers "
. "WHERE customer_id = " . (int)$id . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
return $queryRes->customer_id;
$message['action'] = _('Eliminar Cliente');
$message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $customerName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
@@ -209,25 +138,73 @@ class SP_Customer {
* @param int $id con el Id del cliente
* @return string con el nombre del cliente
*/
public static function getCustomerById($id) {
public static function getCustomerById($id)
{
$query = "SELECT customer_name "
. "FROM customers "
. "WHERE customer_id = " . (int) $id . " LIMIT 1";
. "FROM customers "
. "WHERE customer_id = " . (int)$id . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->customer_name;
}
/**
* @brief Comprobar si existe un cliente duplicado comprobando el hash
* @param int $id opcional con el Id del cliente
* @return bool
*/
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 (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 static function getCustomerByName()
{
$query = "SELECT customer_id "
. "FROM customers "
. "WHERE customer_hash = '" . self::mkCustomerHash() . "' LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === false) {
return false;
}
return $queryRes->customer_id;
}
/**
* @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) {
public static function getCustomerData($id = 0)
{
$customer = array('customer_id' => 0,
'customer_name' => '',
'customer_description' => '',
@@ -247,14 +224,53 @@ class SP_Customer {
return $customer;
}
/**
* @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($customerId = NULL, $retAssocArray = false)
{
$query = "SELECT customer_id,"
. "customer_name, "
. "customer_description "
. "FROM customers ";
if (!is_null($customerId)) {
$query .= "WHERE customer_id = " . (int)$customerId . " LIMIT 1";
} else {
$query .= "ORDER BY customer_name";
}
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === false) {
return array();
}
if ($retAssocArray) {
$resCustomers = array();
foreach ($queryRes as $customer) {
$resCustomers[$customer->customer_id] = $customer->customer_name;
}
return $resCustomers;
}
return $queryRes;
}
/**
* @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) {
public static function checkCustomerInUse($id)
{
$count['accounts'] = self::getCustomerInAccounts($id);
return $count;
}
@@ -264,15 +280,16 @@ class SP_Customer {
* @param int $id con el Id del cliente a consultar
* @return integer con el número total de cuentas
*/
private static function getCustomerInAccounts($id) {
private static function getCustomerInAccounts($id)
{
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_customerId = " . (int) $id;
. "FROM accounts "
. "WHERE account_customerId = " . (int)$id;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,33 +23,59 @@
* 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;
class DB
{
static $last_result;
static $affected_rows;
static $lastId;
static $txtError;
static $numError;
static $num_rows;
private static $_db;
function __construct() {
/**
* @brief Comprobar que la base de datos existe
* @return bool
*/
public static function checkDatabaseExist()
{
if (!self::connection()) {
return false;
}
$query = 'SELECT COUNT(*) '
. 'FROM information_schema.tables'
. " WHERE table_schema='" . SP_Config::getValue("dbname") . "' "
. "AND table_name = 'usrData';";
$resquery = self::$_db->query($query);
if ($resquery) {
$row = $resquery->fetch_row();
}
if (!$resquery || $row[0] == 0) {
return false;
}
return true;
}
/**
* @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() {
private static function connection()
{
if (self::$_db) {
return true;
}
@@ -76,18 +102,65 @@ class DB {
}
/**
* @brief Escapar una cadena de texto
* @param string $str con la cadena a escapar
* @return string con la cadena escapada
*
* Esta función utiliza mysqli para escapar cadenas de texto.
* @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 del tipo Id a mostrar
* @param string $tblColName con el nombre de la columna del tipo Name 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 escape($str) {
if (self::connection()) {
return self::$_db->real_escape_string(trim($str));
} else {
return $str;
public static function getValuesForSelect($tblName, $tblColId, $tblColName, $arrFilter = NULL, $arrOrder = NULL)
{
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__, true);
if ($queryRes === false) {
return false;
}
$arrValues = array();
foreach ($queryRes as $row) {
$arrValues[$row->$tblColId] = $row->$tblColName;
}
return $arrValues;
}
/**
* @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
* @param bool $retArray devolver un array si la consulta tiene esultados
* @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 (self::$numError || self::$num_rows === 0) {
return false;
}
if (is_null(self::$numError) && count(self::$last_result) === 0) {
return true;
}
if ($retArray === true && is_object(self::$last_result)) {
return array(self::$last_result);
}
return self::$last_result;
}
/**
@@ -96,7 +169,8 @@ class DB {
* @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) {
public static function doQuery($query, $querySource)
{
if (!self::connection()) {
return false;
}
@@ -116,8 +190,8 @@ class DB {
$message['text'][] = self::$_db->error . '(' . self::$_db->errno . ')';
$message['text'][] = "SQL: " . self::escape($query);
SP_Common::wrLogInfo($message);
return FALSE;
SP_Log::wrLogInfo($message);
return false;
}
if ($isSelect) {
@@ -144,88 +218,18 @@ class DB {
}
/**
* @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
* @brief Escapar una cadena de texto
* @param string $str con la cadena a escapar
* @return string con la cadena escapada
*
* Esta función utiliza mysqli para escapar cadenas de texto.
*/
public static function getResults($query, $querySource, $retArray = FALSE) {
if ($query) {
self::doQuery($query, $querySource);
public static function escape($str)
{
if (self::connection()) {
return self::$_db->real_escape_string(trim($str));
} else {
return $str;
}
if (self::$numError || self::$num_rows === 0) {
return FALSE;
}
if (is_null(self::$numError) && count(self::$last_result) === 0) {
return TRUE;
}
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()) {
return false;
}
$query = 'SELECT COUNT(*) '
. 'FROM information_schema.tables'
. " WHERE table_schema='" . SP_Config::getValue("dbname") . "' "
. "AND table_name = 'usrData';";
$resquery = self::$_db->query($query);
if ($resquery) {
$row = $resquery->fetch_row();
}
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__, TRUE);
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=62 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 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=69 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!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=285 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -93,7 +93,7 @@ CREATE TABLE `accUsers` (
`accuser_userId` int(10) unsigned NOT NULL,
PRIMARY KEY (`accuser_id`),
KEY `idx_account` (`accuser_accountId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
) ENGINE=InnoDB AUTO_INCREMENT=0 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=44 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -142,7 +142,7 @@ CREATE TABLE `categories` (
`category_name` varchar(50) NOT NULL,
`category_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -173,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=8 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -188,10 +188,11 @@ CREATE TABLE `log` (
`log_date` int(10) unsigned NOT NULL,
`log_login` varchar(25) NOT NULL,
`log_userId` tinyint(3) unsigned NOT NULL,
`log_ipAddress` varchar(45) NOT NULL,
`log_action` varchar(50) NOT NULL,
`log_description` text NOT NULL,
PRIMARY KEY (`log_id`)
) ENGINE=MyISAM AUTO_INCREMENT=640 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -206,11 +207,11 @@ CREATE TABLE `usrData` (
`user_name` varchar(80) NOT NULL,
`user_groupId` tinyint(3) unsigned NOT NULL,
`user_secGroupId` tinyint(3) unsigned DEFAULT NULL,
`user_login` varchar(30) NOT NULL,
`user_login` varchar(50) NOT NULL,
`user_pass` varbinary(40) NOT NULL,
`user_mPass` varbinary(32) NOT NULL,
`user_mIV` varbinary(32) NOT NULL,
`user_email` varchar(50) DEFAULT NULL,
`user_email` varchar(80) DEFAULT NULL,
`user_notes` text,
`user_count` int(10) unsigned NOT NULL DEFAULT '0',
`user_profileId` tinyint(4) NOT NULL,
@@ -223,10 +224,11 @@ CREATE TABLE `usrData` (
`user_isDisabled` bit(1) NOT NULL DEFAULT b'0',
`user_hashSalt` varbinary(40) NOT NULL,
`user_isMigrate` bit(1) DEFAULT b'0',
`user_isChangePass` bit(1) DEFAULT b'0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `IDX_login` (`user_login`),
KEY `IDX_pass` (`user_pass`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -241,7 +243,25 @@ CREATE TABLE `usrGroups` (
`usergroup_name` varchar(50) NOT NULL,
`usergroup_description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`usergroup_id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `usrPassRecover`
--
DROP TABLE IF EXISTS `usrPassRecover`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usrPassRecover` (
`userpassr_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userpassr_userId` smallint(5) unsigned NOT NULL,
`userpassr_hash` varbinary(40) NOT NULL,
`userpassr_date` int(10) unsigned NOT NULL,
`userpassr_used` bit(1) NOT NULL,
PRIMARY KEY (`userpassr_id`),
KEY `IDX_userId` (`userpassr_userId`,`userpassr_date`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
@@ -275,7 +295,7 @@ CREATE TABLE `usrProfiles` (
`userProfile_pAppMgmtCategories` bit(1) DEFAULT b'0',
`userProfile_pAppMgmtCustomers` bit(1) DEFAULT b'0',
PRIMARY KEY (`userprofile_id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

504
inc/ext/phpmailer/LICENSE Normal file
View File

@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,958 @@
<?php
/**
* PHPMailer RFC821 SMTP email transport class.
* Version 5.2.7
* PHP version 5.0.0
* @category PHP
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/
* @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @copyright 2013 Marcus Bointon
* @copyright 2004 - 2008 Andy Prevost
* @copyright 2010 - 2012 Jim Jagielski
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
/**
* PHPMailer RFC821 SMTP email transport class.
*
* Implements RFC 821 SMTP commands
* and provides some utility methods for sending mail to an SMTP server.
*
* PHP Version 5.0.0
*
* @category PHP
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/blob/master/class.smtp.php
* @author Chris Ryan <unknown@example.com>
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class SMTP
{
/**
* The PHPMailer SMTP Version number.
*/
const VERSION = '5.2.7';
/**
* SMTP line break constant.
*/
const CRLF = "\r\n";
/**
* The SMTP port to use if one is not specified.
*/
const DEFAULT_SMTP_PORT = 25;
/**
* The PHPMailer SMTP Version number.
* @type string
* @deprecated This should be a constant
* @see SMTP::VERSION
*/
public $Version = '5.2.7';
/**
* SMTP server port number.
* @type int
* @deprecated This is only ever ued as default value, so should be a constant
* @see SMTP::DEFAULT_SMTP_PORT
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending
* @type string
* @deprecated Use the class constant instead
* @see SMTP::CRLF
*/
public $CRLF = "\r\n";
/**
* Debug output level.
* Options:
* 0: no output
* 1: commands
* 2: data and commands
* 3: as 2 plus connection status
* 4: low level data output
* @type int
*/
public $do_debug = 0;
/**
* The function/method to use for debugging output.
* Options: 'echo', 'html' or 'error_log'
* @type string
*/
public $Debugoutput = 'echo';
/**
* Whether to use VERP.
* @type bool
*/
public $do_verp = false;
/**
* The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @type int
*/
public $Timeout = 300;
/**
* The SMTP timelimit value for reads, in seconds.
* @type int
*/
public $Timelimit = 30;
/**
* The socket for the server connection.
* @type resource
*/
protected $smtp_conn;
/**
* Error message, if any, for the last call.
* @type string
*/
protected $error = '';
/**
* The reply the server sent to us for HELO.
* @type string
*/
protected $helo_rply = '';
/**
* The most recent reply received from the server.
* @type string
*/
protected $last_reply = '';
/**
* Constructor.
* @access public
*/
public function __construct()
{
$this->smtp_conn = 0;
$this->error = null;
$this->helo_rply = null;
$this->do_debug = 0;
}
/**
* Output debugging info via a user-selected method.
* @param string $str Debug string to output
* @return void
*/
protected function edebug($str)
{
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
)
. "<br>\n";
break;
case 'echo':
default:
echo gmdate('Y-m-d H:i:s')."\t".trim($str)."\n";
}
}
/**
* Connect to an SMTP server.
* @param string $host SMTP server IP or host name
* @param int $port The port number to connect to
* @param int $timeout How long to wait for the connection to open
* @param array $options An array of options for stream_context_create()
* @access public
* @return bool
*/
public function connect($host, $port = null, $timeout = 30, $options = array())
{
// Clear errors to avoid confusion
$this->error = null;
// Make sure we are __not__ connected
if ($this->connected()) {
// Already connected, generate error
$this->error = array('error' => 'Already connected to a server');
return false;
}
if (empty($port)) {
$port = self::DEFAULT_SMTP_PORT;
}
// Connect to the SMTP server
if ($this->do_debug >= 3) {
$this->edebug('Connection: opening');
}
$errno = 0;
$errstr = '';
$socket_context = stream_context_create($options);
//Suppress errors; connection failures are handled at a higher level
$this->smtp_conn = @stream_socket_client(
$host . ":" . $port,
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$socket_context
);
// Verify we connected properly
if (empty($this->smtp_conn)) {
$this->error = array(
'error' => 'Failed to connect to server',
'errno' => $errno,
'errstr' => $errstr
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP ERROR: ' . $this->error['error']
. ": $errstr ($errno)"
);
}
return false;
}
if ($this->do_debug >= 3) {
$this->edebug('Connection: opened');
}
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if (substr(PHP_OS, 0, 3) != 'WIN') {
$max = ini_get('max_execution_time');
if ($max != 0 && $timeout > $max) { // Don't bother if unlimited
@set_time_limit($timeout);
}
stream_set_timeout($this->smtp_conn, $timeout, 0);
}
// Get any announcement
$announce = $this->get_lines();
if ($this->do_debug >= 2) {
$this->edebug('SERVER -> CLIENT: ' . $announce);
}
return true;
}
/**
* Initiate a TLS (encrypted) session.
* @access public
* @return bool
*/
public function startTLS()
{
if (!$this->sendCommand("STARTTLS", "STARTTLS", 220)) {
return false;
}
// Begin encrypted connection
if (!stream_socket_enable_crypto(
$this->smtp_conn,
true,
STREAM_CRYPTO_METHOD_TLS_CLIENT
)
) {
return false;
}
return true;
}
/**
* Perform SMTP authentication.
* Must be run after hello().
* @see hello()
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5)
* @param string $realm The auth realm for NTLM
* @param string $workstation The auth workstation for NTLM
* @access public
* @return bool True if successfully authenticated.
*/
public function authenticate(
$username,
$password,
$authtype = 'LOGIN',
$realm = '',
$workstation = ''
) {
if (empty($authtype)) {
$authtype = 'LOGIN';
}
switch ($authtype) {
case 'PLAIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
// Send encoded username and password
if (!$this->sendCommand(
'User & Password',
base64_encode("\0" . $username . "\0" . $password),
235
)
) {
return false;
}
break;
case 'LOGIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
if (!$this->sendCommand("Username", base64_encode($username), 334)) {
return false;
}
if (!$this->sendCommand("Password", base64_encode($password), 235)) {
return false;
}
break;
case 'NTLM':
/*
* ntlm_sasl_client.php
* Bundled with Permission
*
* How to telnet in windows:
* http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
* PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
*/
require_once 'extras/ntlm_sasl_client.php';
$temp = new stdClass();
$ntlm_client = new ntlm_sasl_client_class;
//Check that functions are available
if (!$ntlm_client->Initialize($temp)) {
$this->error = array('error' => $temp->error);
if ($this->do_debug >= 1) {
$this->edebug(
'You need to enable some modules in your php.ini file: '
. $this->error['error']
);
}
return false;
}
//msg1
$msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand(
'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1),
334
)
) {
return false;
}
//Though 0 based, there is a white space after the 3 digit number
//msg2
$challenge = substr($this->last_reply, 3);
$challenge = base64_decode($challenge);
$ntlm_res = $ntlm_client->NTLMResponse(
substr($challenge, 24, 8),
$password
);
//msg3
$msg3 = $ntlm_client->TypeMsg3(
$ntlm_res,
$username,
$realm,
$workstation
);
// send encoded username
return $this->sendCommand('Username', base64_encode($msg3), 235);
break;
case 'CRAM-MD5':
// Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
// Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
// Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
break;
}
return true;
}
/**
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available
* @param string $data The data to hash
* @param string $key The key to hash with
* @access protected
* @return string
*/
protected function hmac($data, $key)
{
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
// The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// Hacked by Lance Rushing
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack('H*', md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}
/**
* Check connection state.
* @access public
* @return bool True if connected.
*/
public function connected()
{
if (!empty($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
// the socket is valid but we are not connected
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP NOTICE: EOF caught while checking if connected'
);
}
$this->close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
* @see quit()
* @access public
* @return void
*/
public function close()
{
$this->error = null; // so there is no confusion
$this->helo_rply = null;
if (!empty($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
if ($this->do_debug >= 3) {
$this->edebug('Connection: closed');
}
$this->smtp_conn = 0;
}
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by and additional <CRLF>.
* Implements rfc 821: DATA <CRLF>
* @param string $msg_data Message data to send
* @access public
* @return bool
*/
public function data($msg_data)
{
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
/* The server is ready to accept data!
* according to rfc821 we should not send more than 1000
* including the CRLF
* characters on a single line so we will break the data up
* into lines by \r and/or \n then if needed we will break
* each of those into smaller lines to fit within the limit.
* in addition we will be looking for lines that start with
* a period '.' and append and additional period '.' to that
* line. NOTE: this does not count towards limit.
*/
// Normalize the line breaks before exploding
$msg_data = str_replace("\r\n", "\n", $msg_data);
$msg_data = str_replace("\r", "\n", $msg_data);
$lines = explode("\n", $msg_data);
/* We need to find a good way to determine if headers are
* in the msg_data or if it is a straight msg body
* currently I am assuming rfc822 definitions of msg headers
* and if the first field of the first line (':' separated)
* does not contain a space then it _should_ be a header
* and we can process all lines before a blank "" line as
* headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false;
if (!empty($field) && !strstr($field, ' ')) {
$in_headers = true;
}
//RFC 2822 section 2.1.1 limit
$max_line_length = 998;
foreach ($lines as $line) {
$lines_out = null;
if ($line == '' && $in_headers) {
$in_headers = false;
}
// ok we need to break this line up into several smaller lines
while (strlen($line) > $max_line_length) {
$pos = strrpos(substr($line, 0, $max_line_length), ' ');
// Patch to fix DOS attack
if (!$pos) {
$pos = $max_line_length - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
} else {
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos + 1);
}
/* If processing headers add a LWSP-char to the front of new line
* rfc822 on long msg headers
*/
if ($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
// send the lines to the server
while (list(, $line_out) = @each($lines_out)) {
if (strlen($line_out) > 0) {
if (substr($line_out, 0, 1) == '.') {
$line_out = '.' . $line_out;
}
}
$this->client_send($line_out . self::CRLF);
}
}
// Message data has been sent, complete the command
return $this->sendCommand('DATA END', '.', 250);
}
/**
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements from RFC 821: HELO <SP> <domain> <CRLF>
* and RFC 2821 EHLO.
* @param string $host The host name or IP to connect to
* @access public
* @return bool
*/
public function hello($host = '')
{
// Try extended hello first (RFC 2821)
if (!$this->sendHello('EHLO', $host)) {
if (!$this->sendHello('HELO', $host)) {
return false;
}
}
return true;
}
/**
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string
* @param string $host The hostname to say we are
* @access protected
* @return bool
*/
protected function sendHello($hello, $host)
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
return $noerror;
}
/**
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
* @param string $from Source address of this message
* @access public
* @return bool
*/
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
250
);
}
/**
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from rfc 821: QUIT <CRLF>
* @param bool $close_on_error Should the connection close if an error occurs?
* @access public
* @return bool
*/
public function quit($close_on_error = true)
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$e = $this->error; //Save any error
if ($noerror or $close_on_error) {
$this->close();
$this->error = $e; //Restore any error from the quit command
}
return $noerror;
}
/**
* Send an SMTP RCPT command.
* Sets the TO argument to $to.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
* @param string $to The address the message is being sent to
* @access public
* @return bool
*/
public function recipient($to)
{
return $this->sendCommand(
'RCPT TO ',
'RCPT TO:<' . $to . '>',
array(250, 251)
);
}
/**
* Send an SMTP RSET command.
* Abort any transaction that is currently in progress.
* Implements rfc 821: RSET <CRLF>
* @access public
* @return bool True on success.
*/
public function reset()
{
return $this->sendCommand('RSET', 'RSET', 250);
}
/**
* Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server
* @param string $commandstring The actual command to send
* @param int|array $expect One or more expected integer success codes
* @access protected
* @return bool True on success.
*/
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->error = array(
"error" => "Called $command without being connected"
);
return false;
}
$this->client_send($commandstring . self::CRLF);
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
if ($this->do_debug >= 2) {
$this->edebug('SERVER -> CLIENT: ' . $reply);
}
if (!in_array($code, (array)$expect)) {
$this->last_reply = null;
$this->error = array(
"error" => "$command command failed",
"smtp_code" => $code,
"detail" => substr($reply, 4)
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP ERROR: ' . $this->error['error'] . ': ' . $reply
);
}
return false;
}
$this->last_reply = $reply;
$this->error = null;
return true;
}
/**
* Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from.
* Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
* @param string $from The address the message is from
* @access public
* @return bool
*/
public function sendAndMail($from)
{
return $this->sendCommand("SAML", "SAML FROM:$from", 250);
}
/**
* Send an SMTP VRFY command.
* @param string $name The name to verify
* @access public
* @return bool
*/
public function verify($name)
{
return $this->sendCommand("VRFY", "VRFY $name", array(250, 251));
}
/**
* Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything
* @access public
* @return bool
*/
public function noop()
{
return $this->sendCommand("NOOP", "NOOP", 250);
}
/**
* Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support.
* This method is here to make the RFC821 Definition
* complete for this class and __may__ be implemented in future
* Implements from rfc 821: TURN <CRLF>
* @access public
* @return bool
*/
public function turn()
{
$this->error = array(
'error' => 'The SMTP TURN command is not implemented'
);
if ($this->do_debug >= 1) {
$this->edebug('SMTP NOTICE: ' . $this->error['error']);
}
return false;
}
/**
* Send raw data to the server.
* @param string $data The data to send
* @access public
* @return int|bool The number of bytes sent to the server or false on error
*/
public function client_send($data)
{
if ($this->do_debug >= 1) {
$this->edebug("CLIENT -> SERVER: $data");
}
return fwrite($this->smtp_conn, $data);
}
/**
* Get the latest error.
* @access public
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* Get the last reply from the server.
* @access public
* @return string
*/
public function getLastReply()
{
return $this->last_reply;
}
/**
* Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access protected
* @return string
*/
protected function get_lines()
{
$data = '';
$endtime = 0;
// If the connection is bad, give up now
if (!is_resource($this->smtp_conn)) {
return $data;
}
stream_set_timeout($this->smtp_conn, $this->Timeout);
if ($this->Timelimit > 0) {
$endtime = time() + $this->Timelimit;
}
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
$str = @fgets($this->smtp_conn, 515);
if ($this->do_debug >= 4) {
$this->edebug("SMTP -> get_lines(): \$data was \"$data\"");
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"");
}
$data .= $str;
if ($this->do_debug >= 4) {
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"");
}
// if 4th character is a space, we are done reading, break the loop
if (substr($str, 3, 1) == ' ') {
break;
}
// Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
if ($this->do_debug >= 4) {
$this->edebug(
'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)'
);
}
break;
}
// Now check if reads took too long
if ($endtime) {
if (time() > $endtime) {
if ($this->do_debug >= 4) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached ('
. $this->Timelimit . ' sec)'
);
}
break;
}
}
}
return $data;
}
/**
* Enable or disable VERP address generation.
* @param bool $enabled
*/
public function setVerp($enabled = false)
{
$this->do_verp = $enabled;
}
/**
* Get VERP address generation mode.
* @return bool
*/
public function getVerp()
{
return $this->do_verp;
}
/**
* Set debug output method.
* @param string $method The function/method to use for debugging output.
*/
public function setDebugOutput($method = 'echo')
{
$this->Debugoutput = $method;
}
/**
* Get debug output method.
* @return string
*/
public function getDebugOutput()
{
return $this->Debugoutput;
}
/**
* Set debug output level.
* @param int $level
*/
public function setDebugLevel($level = 0)
{
$this->do_debug = $level;
}
/**
* Get debug output level.
* @return int
*/
public function getDebugLevel()
{
return $this->do_debug;
}
/**
* Set SMTP timeout.
* @param int $timeout
*/
public function setTimeout($timeout = 0)
{
$this->Timeout = $timeout;
}
/**
* Get SMTP timeout.
* @return int
*/
public function getTimeout()
{
return $this->Timeout;
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -29,83 +29,60 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
/**
* Esta clase es la encargada de realizar operaciones con archivos de las cuentas de sysPass
*/
class SP_Files {
class SP_Files
{
/**
* @brief Guardar un archivo en la BBDD
* @param int $accountId
* @param array $fileData con los datos y el contenido del archivo
* @return bool
*/
public static function fileUpload($accountId, $fileData = array()) {
*/
public static function fileUpload($accountId, $fileData = array())
{
$query = "INSERT INTO accFiles "
. "SET accfile_accountId = " . (int) $accountId . ","
. "accfile_name = '" . $fileData['name'] . "',"
. "accfile_type = '".$fileData['type']."',"
. "accfile_size = '".$fileData['size']."',"
. "accfile_content = '".$fileData['content']."',"
. "accfile_extension = '" . DB::escape($fileData['extension']) . "'";
. "SET accfile_accountId = " . (int)$accountId . ","
. "accfile_name = '" . $fileData['name'] . "',"
. "accfile_type = '" . $fileData['type'] . "',"
. "accfile_size = '" . $fileData['size'] . "',"
. "accfile_content = '" . $fileData['content'] . "',"
. "accfile_extension = '" . DB::escape($fileData['extension']) . "'";
if (DB::doQuery($query, __FUNCTION__) !== FALSE) {
if (DB::doQuery($query, __FUNCTION__) !== false) {
$message['action'] = _('Subir Archivo');
$message['text'][] = _('Cuenta') . ": " . $accountId;
$message['text'][] = _('Archivo') . ": " . $fileData['name'];
$message['text'][] = _('Tipo') . ": " . $fileData['type'];
$message['text'][] = _('Tamaño') . ": " . round($fileData['size'] / 1024, 2) . " KB";
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
return true;
}
return FALSE;
return false;
}
/**
* @brief Obtener un archivo desde la BBDD
* @param int $fileId con el Id del archivo
* @param bool $view si el es para ver el archivo
* @return object con los datos del archivo
*
*
* Función para obtener un archivo y pasarlo al navegador como descarga o imagen en línea
*/
public static function fileDownload($fileId) {
*/
public static function fileDownload($fileId)
{
// Obtenemos el archivo de la BBDD
$query = "SELECT * FROM accFiles "
. "WHERE accfile_id = " . (int) $fileId . " LIMIT 1";
. "WHERE accfile_id = " . (int)$fileId . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
if ( DB::$num_rows == 0) {
return FALSE;
}
return $queryRes;
}
/**
* @brief Obtener información de un archivo almacenado en la BBDD
* @param int $fileId con el Id del archivo
* @return object con el resultado de la consulta
*/
public static function getFileInfo($fileId) {
$query = "SELECT accfile_name,"
. "accfile_size,"
. "accfile_type "
. "FROM accFiles "
. "WHERE accfile_id = " . (int) $fileId . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ( $queryRes === FALSE ) {
return FALSE;
}
if ( DB::$num_rows === 0) {
echo _('El archivo no existe');
return FALSE;
if (DB::$num_rows == 0) {
return false;
}
return $queryRes;
@@ -115,59 +92,86 @@ class SP_Files {
* @brief Eliminar un archivo de la BBDD
* @param int $fileId con el Id del archivo
* @return bool
*/
public static function fileDelete($fileId) {
*/
public static function fileDelete($fileId)
{
$fileInfo = self::getFileInfo($fileId);
// Eliminamos el archivo de la BBDD
$query = "DELETE FROM accFiles "
. "WHERE accfile_id = " . (int) $fileId . " LIMIT 1";
. "WHERE accfile_id = " . (int)$fileId . " LIMIT 1";
$queryRes = DB::doQuery($query, __FUNCTION__);
if ($queryRes !== FALSE) {
if ($queryRes !== false) {
$message['action'] = _('Eliminar Archivo');
$message['text'][] = _('ID') . ": " . $fileId;
$message['text'][] = _('Archivo') . ": " . $fileInfo->accfile_name;
$message['text'][] = _('Tipo') . ": " . $fileInfo->accfile_type;
$message['text'][] = _('Tamaño') . ": " . round($fileInfo->accfile_size / 1024, 2) . " KB";
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return TRUE;
}
return FALSE;
return true;
}
return false;
}
/**
* @brief Obtener información de un archivo almacenado en la BBDD
* @param int $fileId con el Id del archivo
* @return object con el resultado de la consulta
*/
public static function getFileInfo($fileId)
{
$query = "SELECT accfile_name,"
. "accfile_size,"
. "accfile_type "
. "FROM accFiles "
. "WHERE accfile_id = " . (int)$fileId . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === false) {
return false;
}
if (DB::$num_rows === 0) {
echo _('El archivo no existe');
return false;
}
return $queryRes;
}
/**
* @brief Obtener el listado de archivos de una cuenta
* @param int $accountId con el Id de la cuenta
* @param bool $blnDelete para mostrar o no el botón de eliminar
* @return array con los archivos de la cuenta.
*/
public static function getFileList($accountId) {
*/
public static function getFileList($accountId)
{
$query = "SELECT accfile_id,"
. "accfile_name,"
. "accfile_size "
. "FROM accFiles "
. "WHERE accfile_accountId = " . (int) $accountId;
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
. "accfile_name,"
. "accfile_size "
. "FROM accFiles "
. "WHERE accfile_accountId = " . (int)$accountId;
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
$files = array();
$fileNum = 0;
foreach ($queryRes as $file) {
$files[$fileNum]['id'] = $file->accfile_id;
$files[$fileNum]['name'] = $file->accfile_name;
$files[$fileNum]['size'] = round($file->accfile_size / 1000, 2);
$fileNum++;
}
return $files;
}
@@ -175,33 +179,36 @@ class SP_Files {
* @brief Obtener el número de archivo de una cuenta
* @param int $accountId con el Id de la cuenta
* @return int con el número de archivos
*/
public static function countFiles($accountId) {
*/
public static function countFiles($accountId)
{
// Obtenemos los archivos de la BBDD para dicha cuenta
$query = "SELECT accfile_id "
. "FROM accFiles "
. "WHERE accfile_accountId = " . (int) $accountId;
. "FROM accFiles "
. "WHERE accfile_accountId = " . (int)$accountId;
if (DB::doQuery($query, __FUNCTION__) === FALSE){
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
return count(DB::$last_result);
}
/**
* @brief Elimina los archivos de una cuenta en la BBDD
* @param int $accountId con el Id de la cuenta
* @return bool
*/
public static function deleteAccountFiles($accountId) {
*/
public static function deleteAccountFiles($accountId)
{
$query = "DELETE FROM accFiles "
. "WHERE accfile_accountId = " . (int) $accountId;
. "WHERE accfile_accountId = " . (int)$accountId;
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
return TRUE;
return true;
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,13 +23,14 @@
* 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 grupos de usuarios.
*/
class SP_Groups {
class SP_Groups
{
static $queryRes;
static $groupId;
static $groupName;
@@ -41,7 +42,8 @@ class SP_Groups {
* @param int $id con el Id del grupo a consultar
* @return array con el nombre de la columna como clave y los datos como valor
*/
public static function getGroupData($id = 0) {
public static function getGroupData($id = 0)
{
$group = array('usergroup_id' => 0,
'usergroup_name' => '',
'usergroup_description' => '',
@@ -67,33 +69,34 @@ class SP_Groups {
* @param bool $returnArray opcional, si se debe de devolver un array asociativo
* @return array con la lista de grupos
*/
public static function getGroups($groupId = NULL, $returnArray = FALSE) {
public static function getGroups($groupId = NULL, $returnArray = false)
{
$query = "SELECT usergroup_id,"
. "usergroup_name,"
. "usergroup_description "
. "FROM usrGroups ";
. "usergroup_name,"
. "usergroup_description "
. "FROM usrGroups ";
if (!is_null($groupId)) {
$query .= "WHERE usergroup_id = " . (int) $groupId . " LIMIT 1";
$query .= "WHERE usergroup_id = " . (int)$groupId . " LIMIT 1";
} else {
$query .= "ORDER BY usergroup_name";
}
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
if ( $returnArray === TRUE ){
if ($returnArray === true) {
foreach ($queryRes as $group) {
$groups[$group->usergroup_name] = $group->usergroup_id;
}
return $groups;
}
return $queryRes;
}
@@ -101,93 +104,120 @@ class SP_Groups {
* @brief Comprobar si un grupo existe en la BBDD
* @return bool
*/
public static function checkGroupExist() {
$groupId = (int) self::$groupId;
public static function checkGroupExist()
{
$groupId = (int)self::$groupId;
$groupName = strtoupper(self::$groupName);
if ($groupId) {
$query = "SELECT usergroup_name
FROM usrGroups
WHERE UPPER(usergroup_name) = '" . DB::escape($groupName) . "'
AND usergroup_id != " . (int) $groupId;
AND usergroup_id != " . (int)$groupId;
} else {
$query = "SELECT usergroup_name
FROM usrGroups
WHERE UPPER(usergroup_name) = '" . DB::escape($groupName) . "'";
}
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
return false;
}
return TRUE;
return true;
}
/**
* @brief Añadir un nuevo grupo
* @return bool
*/
public static function addGroup() {
public static function addGroup()
{
$query = "INSERT INTO usrGroups SET
usergroup_name = '" . DB::escape(self::$groupName) . "',
usergroup_description = '" . DB::escape(self::$groupDescription) . "'";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
return TRUE;
$message['action'] = _('Nuevo Grupo');
$message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . self::$groupName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Modificar un grupo
* @return bool
*/
public static function updateGroup() {
public static function updateGroup()
{
$groupName = self::getGroupNameById(self::$groupId);
$query = "UPDATE usrGroups SET
usergroup_name = '" . DB::escape(self::$groupName) . "',
usergroup_description = '" . DB::escape(self::$groupDescription) . "'
WHERE usergroup_id = " . (int) self::$groupId;
WHERE usergroup_id = " . (int)self::$groupId;
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
return TRUE;
$message['action'] = _('Modificar Grupo');
$message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . $groupName . ' > ' . self::$groupName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Eliminar un grupo
* @return bool
*/
public static function deleteGroup() {
$query = "DELETE FROM usrGroups "
. "WHERE usergroup_id = " . (int) self::$groupId . " LIMIT 1";
public static function deleteGroup()
{
$groupName = self::getGroupNameById(self::$groupId);
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
$query = "DELETE FROM usrGroups "
. "WHERE usergroup_id = " . (int)self::$groupId . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
// return TRUE;
$message['action'] = _('Eliminar Grupo');
$message['text'][] = SP_Html::strongText(_('Grupo') . ': ') . $groupName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Comprobar si un grupo está en uso
* @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() {
public static function checkGroupInUse()
{
$count['users'] = self::getGroupInUsers();
$count['accounts'] = self::getGroupInAccounts() + self::getGroupInAccountsSec();
return $count;
@@ -197,15 +227,16 @@ class SP_Groups {
* @brief Obtener el número de usuarios que usan un grupo
* @return int con el número total de cuentas
*/
private static function getGroupInUsers() {
private static function getGroupInUsers()
{
$query = "SELECT COUNT(*) as uses "
. "FROM usrData "
. "WHERE user_groupId = " . (int) self::$groupId;
. "FROM usrData "
. "WHERE user_groupId = " . (int)self::$groupId;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;
@@ -215,15 +246,16 @@ class SP_Groups {
* @brief Obtener el número de cuentas que usan un grupo como primario
* @return integer con el número total de cuentas
*/
private static function getGroupInAccounts() {
private static function getGroupInAccounts()
{
$query = "SELECT COUNT(*) as uses "
. "FROM accounts "
. "WHERE account_userGroupId = " . (int) self::$groupId;
. "FROM accounts "
. "WHERE account_userGroupId = " . (int)self::$groupId;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;
@@ -233,15 +265,16 @@ class SP_Groups {
* @brief Obtener el número de cuentas que usan un grupo como secundario
* @return integer con el número total de cuentas
*/
private static function getGroupInAccountsSec() {
private static function getGroupInAccountsSec()
{
$query = "SELECT COUNT(*) as uses "
. "FROM accGroups "
. "WHERE accgroup_groupId = " . (int) self::$groupId;
. "FROM accGroups "
. "WHERE accgroup_groupId = " . (int)self::$groupId;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;
@@ -249,55 +282,41 @@ class SP_Groups {
/**
* @brief Obtener el nombre de un grupo por a partir del Id
* @param int $id con el Id del grupo
* @return string con el nombre del grupo
*/
public static function getGroupNameById($id) {
public static function getGroupNameById($id)
{
$query = "SELECT usergroup_name "
. "FROM usrGroups "
. "WHERE usergroup_id = " . (int) $id . " LIMIT 1";
. "FROM usrGroups "
. "WHERE usergroup_id = " . (int)$id . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->usergroup_name;
}
/**
* @brief Obtiene el listado de grupos de una cuenta
* @return array con el Id de grupo
*/
public static function getGroupsForAccount($accountId) {
$query = "SELECT accgroup_groupId "
. "FROM accGroups "
. "WHERE accgroup_accountId = " . (int) $accountId;
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ($queryRes === FALSE) {
return FALSE;
}
return $queryRes;
}
/**
* @brief Obtiene el listado con el nombre de los grupos de una cuenta
* @param int $accountId con el Id de la cuenta
* @return array con los nombres de los grupos ordenados
*/
public static function getGroupsNameForAccount($accountId) {
public static function getGroupsNameForAccount($accountId)
{
$query = "SELECT usergroup_id,"
. "usergroup_name "
. "FROM accGroups "
. "JOIN usrGroups ON accgroup_groupId = usergroup_id "
. "WHERE accgroup_accountId = " . (int) $accountId;
. "usergroup_name "
. "FROM accGroups "
. "JOIN usrGroups ON accgroup_groupId = usergroup_id "
. "WHERE accgroup_accountId = " . (int)$accountId;
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $groups) {
@@ -312,15 +331,16 @@ class SP_Groups {
/**
* @brief Actualizar la asociación de grupos con cuentas
* @param int $accountId con el Id de la cuenta
* @param array $newGroups con los grupos de la cuenta
* @param array $groupsId con los grupos de la cuenta
* @return bool
*/
public static function updateGroupsForAccount($accountId, $groupsId) {
public static function updateGroupsForAccount($accountId, $groupsId)
{
if (self::deleteGroupsForAccount($accountId, $groupsId)) {
return self::addGroupsForAccount($accountId, $groupsId);
}
return FALSE;
return false;
}
/**
@@ -329,24 +349,25 @@ class SP_Groups {
* @param array $groupsId opcional con los grupos de la cuenta
* @return bool
*/
public static function deleteGroupsForAccount($accountId, $groupsId = NULL) {
public static function deleteGroupsForAccount($accountId, $groupsId = NULL)
{
$queryExcluded = '';
// Excluimos los grupos actuales
if (is_array($groupsId)) {
$queryExcluded = ' AND accgroup_groupId NOT IN ('. implode(',', $groupsId).')';
$queryExcluded = ' AND accgroup_groupId NOT IN (' . implode(',', $groupsId) . ')';
}
$query = 'DELETE FROM accGroups '
. 'WHERE accgroup_accountId = ' . (int) $accountId . $queryExcluded;
. 'WHERE accgroup_accountId = ' . (int)$accountId . $queryExcluded;
error_log($query);
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
//error_log($query);
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
return TRUE;
return true;
}
/**
@@ -355,39 +376,60 @@ class SP_Groups {
* @param array $groupsId con los grupos de la cuenta
* @return bool
*/
public static function addGroupsForAccount($accountId, $groupsId) {
public static function addGroupsForAccount($accountId, $groupsId)
{
$values = '';
// Obtenemos los grupos actuales
$currentGroups = self::getGroupsForAccount($accountId);
if (is_array($currentGroups) ){
foreach ( $currentGroups as $group ){
if (is_array($currentGroups)) {
foreach ($currentGroups as $group) {
$groupsExcluded[] = $group->accgroup_groupId;
}
}
foreach ($groupsId as $groupId) {
// Excluimos los grupos actuales
if ( is_array($groupsExcluded) && in_array($groupId, $groupsExcluded)){
if (is_array($groupsExcluded) && in_array($groupId, $groupsExcluded)) {
continue;
}
$values[] = '(' . $accountId . ',' . $groupId . ')';
}
if ( ! is_array($values) ){
return TRUE;
if (!is_array($values)) {
return true;
}
$query = 'INSERT INTO accGroups (accgroup_accountId, accgroup_groupId) '
. 'VALUES ' . implode(',', $values);
. 'VALUES ' . implode(',', $values);
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
return TRUE;
return true;
}
/**
* @brief Obtiene el listado de grupos de una cuenta
* @param int $accountId con el Id de la cuenta
* @return array con el Id de grupo
*/
public static function getGroupsForAccount($accountId)
{
$query = "SELECT accgroup_groupId "
. "FROM accGroups "
. "WHERE accgroup_accountId = " . (int)$accountId;
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === false) {
return false;
}
return $queryRes;
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,15 +23,16 @@
* 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 mostrar el HTML
*/
class SP_Html {
private static $htmlPage = array();
class SP_Html
{
public static $htmlBodyOpts = "";
private static $htmlPage = array();
/**
* @brief Crear un elemento del tipo SELECT
@@ -42,14 +43,15 @@ class SP_Html {
*
* Esta función genera un elemento SELECT con las propiedades y valores pasados.
*/
public static function printSelect($arrValues, $arrSelectProp, $useValue = TRUE) {
public static function printSelect($arrValues, $arrSelectProp, $useValue = true)
{
if (!is_array($arrSelectProp)) {
return;
}
$strAttrs = ( is_array($arrSelectProp["attribs"]) ) ? implode(" ", $arrSelectProp["attribs"]) : "";
$strClass = ( $arrSelectProp["class"] ) ? 'class="' . $arrSelectProp["class"] . '"' : "";
$strAttrs = (is_array($arrSelectProp["attribs"])) ? implode(" ", $arrSelectProp["attribs"]) : "";
$strClass = ($arrSelectProp["class"]) ? 'class="' . $arrSelectProp["class"] . '"' : "";
if (!is_array($arrValues)) {
echo '<label for=' . $arrSelectProp["id"] . '">' . $arrSelectProp["label"] . '</label>';
@@ -66,14 +68,14 @@ class SP_Html {
echo '<select name="' . $arrSelectProp["name"] . '" id="' . $arrSelectProp["id"] . '" ' . $strClass . ' size="' . $arrSelectProp["size"] . '" ' . $arrSelectProp["js"] . ' ' . $strAttrs . ' >';
echo '<option value="0">' . $arrSelectProp["default"] . '</option>';
$selectedId = ( isset($arrSelectProp["selected"]) ) ? $arrSelectProp["selected"] : "";
$selectedId = (isset($arrSelectProp["selected"])) ? $arrSelectProp["selected"] : "";
foreach ($arrValues as $valueId => $valueName) {
if ($useValue) {
$selected = ( $valueId == $selectedId ) ? "SELECTED" : "";
$selected = ($valueId == $selectedId) ? "SELECTED" : "";
echo '<option value="' . $valueId . '" ' . $selected . '>' . $valueName . '</option>';
} else {
$selected = ( $valueName == $selectedId ) ? "SELECTED" : "";
$selected = ($valueName == $selectedId) ? "SELECTED" : "";
echo '<option ' . $selected . '>' . $valueName . '</option>';
}
}
@@ -89,7 +91,8 @@ class SP_Html {
*
* Esta función es la encargada de devolver el código HTML al navegador.
*/
public static function render($page = "main", $err = NULL) {
public static function render($page = "main", $err = NULL)
{
$data['showlogo'] = 1;
// UTF8 Headers
@@ -123,7 +126,8 @@ class SP_Html {
*
* Esta función crea la cabecera de una página HTML
*/
private static function makeHeader() {
private static function makeHeader()
{
$info = self::getAppInfo();
self::$htmlPage[] = '<head>';
@@ -135,13 +139,103 @@ class SP_Html {
self::$htmlPage[] = '</head>';
}
/**
* @brief Devuelve información sobre la aplicación
* @param string $index con la key a devolver
* @return array con las propiedades de la aplicación
*/
public static function getAppInfo($index = NULL)
{
$appinfo = array(
'appname' => 'sysPass',
'appdesc' => 'Sysadmin Password Manager',
'appwebsite' => 'http://www.syspass.org',
'appblog' => 'http://www.cygnux.org',
'appdoc' => 'http://wiki.syspass.org',
'appupdates' => 'http://sourceforge.net/api/file/index/project-id/775555/mtime/desc/limit/20/rss',
'apphelp' => 'help.syspass.org',
'appchangelog' => '');
if (!is_null($index) && array_key_exists($index, $appinfo)) {
return $appinfo[$index];
}
return $appinfo;
}
/**
* @brief Establece los enlaces CSS de la página HTML
* @return none
*/
public static function setCss()
{
$versionParameter = '?v=' . md5(implode(SP_Util::getVersion()));
$cssProp = array(
array("href" => "css/reset.css", "media" => ""),
array("href" => "css/smoothness/jquery-ui.css", "media" => "screen"),
array("href" => "css/jquery.powertip.css", "media" => "screen"),
array("href" => "css/jquery.powertip-yellow.min.css", "media" => "screen"),
array("href" => "css/chosen.css", "media" => "screen"),
array("href" => "css/alertify.core.css", "media" => "screen"),
array("href" => "css/alertify.default.css", "media" => "screen"),
array("href" => "css/jquery.tagsinput.css", "media" => "screen"),
array("href" => "js/fancybox/jquery.fancybox.css", "media" => "screen"),
array("href" => "css/styles.css", "media" => ""));
foreach ($cssProp as $css) {
self::$htmlPage[] = '<link rel="stylesheet" href="' . SP_Init::$WEBROOT . "/" . $css["href"] . $versionParameter . '" media="' . $css["media"] . '" />';
}
}
/**
* @brief Establece los enlaces JAVASCRIPT de la página HTML
* @return none
*/
public static function setJs()
{
$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>';
}
}
/**
* @brief Devuelve un array con los archivos JS a incluir
* @return array con los archivos js y parámetros
*/
public static function getJs()
{
$jsProp = array(
array("src" => "js/jquery.js", "params" => ""),
array("src" => "js/jquery.placeholder.js", "params" => ""),
array("src" => "js/jquery-ui.js", "params" => ""),
array("src" => "js/fancybox/jquery.fancybox.pack.js", "params" => ""),
array("src" => "js/jquery.powertip.min.js", "params" => ""),
array("src" => "js/chosen.jquery.min.js", "params" => ""),
array("src" => "js/alertify.js", "params" => ""),
array("src" => "js/jquery.fileDownload.js", "params" => ""),
array("src" => "js/jquery.filedrop.js", "params" => ""),
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 Crear el body en HTML
* @param string $page con la página a cargar
* @return none
*
* Esta función crea el cuerpo de una página HTML
*/
private static function makeBody($page) {
private static function makeBody($page)
{
self::$htmlPage[] = '<body ' . self::$htmlBodyOpts . '>';
self::$htmlPage[] = '<div id="wrap">';
self::$htmlPage[] = '<noscript><div id="nojs">' . _('Javascript es necesario para el correcto funcionamiento') . '</div></noscript>';
@@ -162,7 +256,8 @@ class SP_Html {
*
* Esta función crea el pie de página en HTML
*/
public static function makeFooter($page = "main") {
public static function makeFooter($page = "main")
{
$info = self::getAppInfo();
self::$htmlPage[] = '<div id="footer">';
@@ -176,6 +271,23 @@ class SP_Html {
self::$htmlPage[] = '<script>$(\'input[type="text"], select, textarea\').placeholder().mouseenter(function(){ $(this).focus(); });</script>';
}
/**
* @brief Cargar un archivo de plantilla
* @param string $template con el nombre de la plantilla
* @param array $tplvars con los datos a pasar a la plantilla
* @return none
*/
public static function getTemplate($template, $tplvars = array())
{
$tpl = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR . $template . '.php';
if (file_exists($tpl)) {
$data = $tplvars;
include_once $tpl;
//self::$htmlPage[] = array('include' => $tpl);
}
}
/**
* @brief Crea la barra de navegación para búsqueda de cuentas
* @param int $intSortKey con el número de campo del filro
@@ -186,17 +298,18 @@ class SP_Html {
* @param bool $filterOn opcional con el estado del filtrado
* @return none
*/
public static function printQuerySearchNavBar($intSortKey, $intCur, $intTotal, $intLimit, $intTime, $filterOn = FALSE) {
public static function printQuerySearchNavBar($intSortKey, $intCur, $intTotal, $intLimit, $intTime, $filterOn = false)
{
$firstPage = ceil(($intCur + 1) / $intLimit);
$lastPage = ceil($intTotal / $intLimit);
$globalOn = SP_Common::parseParams('p', 'gsearch', 0, FALSE, 1);
$globalOn = SP_Common::parseParams('p', 'gsearch', 0, false, 1);
echo '<div id="pageNav" class="round shadow">';
echo '<div id="pageNavLeft">';
echo $intTotal . ' @ ' . abs($intTime) . ' s ';
echo ( $filterOn ) ? '<span class="filterOn round">' . _('Filtro ON') . '</span>' : '';
echo ($filterOn) ? '<span class="filterOn round">' . _('Filtro ON') . '</span>' : '';
echo '&nbsp;';
echo ( $globalOn ) ? '<span class="globalOn round">' . _('Global ON') . '</span>' : '';
echo ($globalOn) ? '<span class="globalOn round">' . _('Global ON') . '</span>' : '';
echo '</div>';
echo '<div id="pageNavRight">';
@@ -208,7 +321,7 @@ class SP_Html {
echo "&nbsp; $firstPage / $lastPage &nbsp;";
if ($intCur < $intTotal && $firstPage != $lastPage) {
$intLimitLast = ( ($intTotal % $intLimit) == 0 ) ? $intTotal - $intLimit : floor($intTotal / $intLimit) * $intLimit;
$intLimitLast = (($intTotal % $intLimit) == 0) ? $intTotal - $intLimit : floor($intTotal / $intLimit) * $intLimit;
echo '<img src="imgs/arrow_right.png" onClick="searchSort(' . $intSortKey . ',' . ($intCur + $intLimit) . ',1);" title="' . _('Página siguiente') . '" />';
echo '<img src="imgs/arrow_last.png" onClick="searchSort(' . $intSortKey . ',' . $intLimitLast . ',1);" title="' . _('Última página') . '" />';
}
@@ -223,7 +336,8 @@ class SP_Html {
* @param int $intTime con el tiempo de carga de los resultados
* @return none
*/
public static function printQueryLogNavBar($intCur, $intTotal, $intTime = 0) {
public static function printQueryLogNavBar($intCur, $intTotal, $intTime = 0)
{
$intLimit = 50;
$firstPage = ceil(($intCur + 1) / $intLimit);
$lastPage = ceil($intTotal / $intLimit);
@@ -240,7 +354,7 @@ class SP_Html {
echo "&nbsp; $firstPage / $lastPage &nbsp;";
if ($intCur < $intTotal && $firstPage != $lastPage) {
$intLimitLast = ( ($intTotal % $intLimit) == 0 ) ? $intTotal - $intLimit : floor($intTotal / $intLimit) * $intLimit;
$intLimitLast = (($intTotal % $intLimit) == 0) ? $intTotal - $intLimit : floor($intTotal / $intLimit) * $intLimit;
echo '<img src="imgs/arrow_right.png" onClick="navLog(' . ($intCur + $intLimit) . ',' . $intCur . ');" title="' . _('Página siguiente') . '" />';
echo '<img src="imgs/arrow_last.png" onClick="navLog(' . $intLimitLast . ',' . $intCur . ');" title="' . _('Última página') . '" />';
}
@@ -253,9 +367,10 @@ class SP_Html {
* @param string $data con los datos a limpiar
* @return string con los datos limpiados
*/
public static function sanitize(&$data) {
public static function sanitize(&$data)
{
if (!$data) {
return FALSE;
return false;
}
if (is_array($data)) {
@@ -294,96 +409,14 @@ class SP_Html {
return $data;
}
/**
* @brief Establece los enlaces CSS de la página HTML
* @return none
*/
public static function setCss() {
$versionParameter = '?v=' . md5(implode(SP_Util::getVersion()));
$cssProp = array(
array("href" => "css/reset.css", "media" => ""),
array("href" => "css/smoothness/jquery-ui.css", "media" => "screen"),
array("href" => "css/jquery.powertip.css", "media" => "screen"),
array("href" => "css/jquery.powertip-yellow.min.css", "media" => "screen"),
array("href" => "css/chosen.css", "media" => "screen"),
array("href" => "css/alertify.core.css", "media" => "screen"),
array("href" => "css/alertify.default.css", "media" => "screen"),
array("href" => "css/jquery.tagsinput.css", "media" => "screen"),
array("href" => "js/fancybox/jquery.fancybox.css", "media" => "screen"),
array("href" => "css/styles.css", "media" => ""));
foreach ($cssProp as $css) {
self::$htmlPage[] = '<link rel="stylesheet" href="' . SP_Init::$WEBROOT . "/" . $css["href"] . $versionParameter . '" media="' . $css["media"] . '" />';
}
}
/**
* @brief Establece los enlaces JAVASCRIPT de la página HTML
* @return none
*/
public static function setJs() {
$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>';
}
}
/**
* @brief Devuelve un array con los archivos JS a incluir
* @return array con los archivos js y parámetros
*/
public static function getJs() {
$jsProp = array(
array("src" => "js/jquery.js", "params" => ""),
array("src" => "js/jquery.placeholder.js", "params" => ""),
array("src" => "js/jquery-ui.js", "params" => ""),
array("src" => "js/fancybox/jquery.fancybox.pack.js", "params" => ""),
array("src" => "js/jquery.powertip.min.js", "params" => ""),
array("src" => "js/chosen.jquery.min.js", "params" => ""),
array("src" => "js/alertify.min.js", "params" => ""),
array("src" => "js/jquery.fileDownload.js", "params" => ""),
array("src" => "js/jquery.filedrop.js", "params" => ""),
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
*/
public static function getAppInfo($index = NULL) {
$appinfo = array(
'appname' => 'sysPass',
'appdesc' => 'Sysadmin Password Manager',
'appwebsite' => 'http://www.syspass.org',
'appblog' => 'http://www.cygnux.org',
'appdoc' => 'http://wiki.syspass.org',
'appupdates' => 'http://sourceforge.net/api/file/index/project-id/775555/mtime/desc/limit/20/rss',
'apphelp' => 'help.syspass.org',
'appchangelog' => '');
if (!is_null($index) && array_key_exists($index, $appinfo)) {
return $appinfo[$index];
}
return $appinfo;
}
/**
* @brief Muestra una barra de información con los registros y tiempo de la consulta
* @param int $intTotal con el total de registros devueltos
* @param int $startTime con el tiempo de inicio de la consulta
* @return none
*/
public static function printQueryInfoBar($intTotal, $startTime) {
public static function printQueryInfoBar($intTotal, $startTime)
{
$endTime = microtime();
$totalTime = round($endTime - $startTime, 5);
@@ -394,9 +427,12 @@ class SP_Html {
/**
* @brief Truncar un texto a una determinada longitud
* @param string $str con la cadena a truncar
* @param int $len con la longitud máxima de la cadena
* @return string con el texto truncado
*/
public static function truncate($str, $len) {
public static function truncate($str, $len)
{
$tail = max(0, $len - 10);
$truncate = substr($str, 0, $tail);
$truncate .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len - $tail))));
@@ -404,30 +440,15 @@ class SP_Html {
return $truncate;
}
/**
* @brief Cargar un archivo de plantilla
* @param string $template con el nombre de la plantilla
* @param array $tplvars con los datos a pasar a la plantilla
* @return none
*/
public static function getTemplate($template, $tplvars = array()) {
$tpl = dirname(__FILE__) . '/tpl/' . $template . '.php';
if (file_exists($tpl)) {
$data = $tplvars;
include_once $tpl;
//self::$htmlPage[] = array('include' => $tpl);
}
}
/**
* @brief Devolver errores comunes
* @param string $code con el código de error a mostrar
* @return none
*
*
* Esta función muestra la página de error con el error indicado.
*/
public static function showCommonError($code) {
public static function showCommonError($code)
{
$commonErrors = array(
'unavailable' => array('txt' => _('Opción no disponible'), 'hint' => _('Consulte con el administrador')),
'noaccpermission' => array('txt' => _('No tiene permisos para acceder a esta cuenta'), 'hint' => _('Consulte con el administrador')),
@@ -444,27 +465,15 @@ class SP_Html {
exit();
}
private static function minifier($files) {
if (!is_array($files)) {
return FALSE;
}
foreach ($files as $file) {
//$output_min .= file_get_contents($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
* @return string
*
*
* From: http://bavotasan.com/2011/convert-hex-color-to-rgb-using-php/
*/
public static function rgb2hex($rgb) {
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);
@@ -476,14 +485,16 @@ class SP_Html {
/**
* @brief Devolver una tabla con el resultado de una consulta y acciones
* @param array $arrTableProp con las propiedades de la tabla
* @param array $queryItems con los resultados de la consulta
* @return none
*/
public static function getQueryTable($arrTableProp, $queryItems) {
$sk = SP_Common::getSessionKey(TRUE);
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 '<LI><img src="imgs/add.png" title="' . _('Nuevo') . ' ' . $arrTableProp['itemName'] . '" class="inputImg" OnClick="' . $arrTableProp["actions"]['edit'] . '(0,' . $arrTableProp["newActionId"] . ',\'' . $sk . '\',' . $arrTableProp["activeTab"] . ',0);" /></LI>';
echo '</ul>';
echo '</div>';
@@ -514,7 +525,7 @@ class SP_Html {
$intId = $item->$arrTableProp["tblRowSrcId"];
$action_check = array();
$numActions = count($arrTableProp["actions"]);
$classActionsOptional = ( $numActions > 2 ) ? 'actions-optional' : '';
$classActionsOptional = ($numActions > 2) ? 'actions-optional' : '';
echo '<ul>';
@@ -531,7 +542,7 @@ class SP_Html {
echo '</li>';
} else {
echo '<li class="cell-data" style="width: ' . $cellWidth . '%;">';
echo ( $item->$rowSrc ) ? $item->$rowSrc : '&nbsp;'; // Fix height
echo ($item->$rowSrc) ? $item->$rowSrc : '&nbsp;'; // Fix height
echo '</li>';
}
}
@@ -541,13 +552,13 @@ class SP_Html {
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"] . '\');" />';
echo '<img src="imgs/view.png" title="' . _('Ver Detalles') . '" class="inputImg" Onclick="return ' . $arrTableProp["actions"]['view'] . '(' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrTableProp["activeTab"] . ',1);" />';
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"] . '\');" />';
echo '<img src="imgs/edit.png" title="' . _('Editar') . ' ' . $arrTableProp['itemName'] . '" class="inputImg" Onclick="return ' . $arrTableProp["actions"]['edit'] . '(' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\', ' . $arrTableProp["activeTab"] . ',0);" />';
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"] . '\');" />';
echo '<img src="imgs/delete.png" title="' . _('Eliminar') . ' ' . $arrTableProp['itemName'] . '" class="inputImg ' . $classActionsOptional . '" Onclick="return ' . $arrTableProp["actions"]['del'] . '(' . $arrTableProp["activeTab"] . ',1,' . $intId . ',' . $arrTableProp["actionId"] . ',\'' . $sk . '\', \'' . $arrTableProp["onCloseAction"] . '\');" />';
break;
case "pass":
if (isset($action_check['user_isLdap'])) {
@@ -558,7 +569,7 @@ class SP_Html {
break;
}
}
echo ($numActions > 2 ) ? '<img src="imgs/action.png" title="' . _('Más Acciones') . '" OnClick="showOptional(this)" />' : '';
echo ($numActions > 2) ? '<img src="imgs/action.png" title="' . _('Más Acciones') . '" OnClick="showOptional(this)" />' : '';
echo '</li>';
echo '</ul>';
}
@@ -566,4 +577,45 @@ class SP_Html {
echo '</div></form>';
}
/**
* @brief Devolver una cadena con el tag HTML strong
* @param string $text con la cadena de texto
* @return string
*/
public static function strongText($text)
{
return ('<strong>' . $text . '</strong>');
}
/**
* @brief Devolver un link HTML
* @param string $text con la cadena de texto
* @param string $link con el destino del enlace
* @param string $title con el título del enlace
* @param string $attribs con atributos del enlace
* @return string
*/
public static function anchorText($text, $link = '', $title = '', $attribs = '')
{
$alink = (!empty($link)) ? $link : $text;
$atitle = (!empty($title)) ? $title : '';
$anchor = '<a href="' . $alink . '" title="' . $atitle . '" ' . $attribs . '>' . $text . '</a>';
return $anchor;
}
private static function minifier($files)
{
if (!is_array($files)) {
return false;
}
foreach ($files as $file) {
//$output_min .= file_get_contents($file['src']);
include_once SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR . $file['src'];
}
//return $output_min;
}
}

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,31 +23,36 @@
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Extender la clase Exception para mostrar ayuda en los mensajes
*/
class ImportException extends Exception {
class ImportException extends Exception
{
private $type;
private $hint;
public function __construct($type, $message, $hint, $code = 0, Exception $previous = null) {
public function __construct($type, $message, $hint, $code = 0, Exception $previous = null)
{
$this->type = $type;
$this->hint = $hint;
parent::__construct($message, $code, $previous);
}
public function __toString() {
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
}
public function getHint() {
public function getHint()
{
return $this->hint;
}
public function getType() {
public function getType()
{
return $this->type;
}
@@ -56,8 +61,8 @@ class ImportException extends Exception {
/**
* Esta clase es la encargada de importar cuentas.
*/
class SP_Import {
class SP_Import
{
private static $result = array();
private static $fileContent;
@@ -66,7 +71,8 @@ class SP_Import {
* @param array $fileData con los datos del archivo
* @return array resultado del proceso
*/
public static function doImport(&$fileData) {
public static function doImport(&$fileData)
{
try {
self::readDataFromFile($fileData);
self::parseData();
@@ -74,23 +80,25 @@ class SP_Import {
$message['action'] = _('Importar Cuentas');
$message['text'][] = $e->getMessage();
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
self::$result['error'][] = array('type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint());
return(self::$result);
return (self::$result);
}
self::$result['ok'][] = _('Importación finalizada');
self::$result['ok'][] = _('Revise el registro de eventos para más detalles');
return(self::$result);
return (self::$result);
}
/**
* @brief Leer los datos del archivo
* @param array $fileData con los datos del archivo
* @throws ImportException
* @return bool
*/
private static function readDataFromFile(&$fileData) {
private static function readDataFromFile(&$fileData)
{
if (!is_array($fileData)) {
throw new ImportException('critical', _('Archivo no subido correctamente'), _('Verifique los permisos del usuario del servidor web'));
@@ -123,14 +131,16 @@ class SP_Import {
throw new ImportException('critical', _('Error interno al leer el archivo'), _('Compruebe los permisos del directorio temporal'));
}
return TRUE;
return true;
}
/**
* @brief Leer los datos importados y formatearlos
* @throws ImportException
* @return bool
*/
private static function parseData() {
private static function parseData()
{
// Datos del Usuario
$userId = SP_Common::parseParams('s', 'uid', 0);
$groupId = SP_Common::parseParams('s', 'ugroup', 0);
@@ -145,24 +155,24 @@ class SP_Import {
}
list($accountName, $customerName, $categoryName, $url, $username, $password, $notes) = $fields;
SP_Customer::$customerName = $customerName;
if ( !SP_Customer::checkDupCustomer() ){
if (!SP_Customer::checkDupCustomer()) {
$customerId = SP_Customer::getCustomerByName();
} else{
} else {
SP_Customer::addCustomer();
$customerId = SP_Customer::$customerLastId;
}
$categoryId = SP_Category::getCategoryIdByName($categoryName);
if ( $categoryId == 0 ){
if ($categoryId == 0) {
SP_Category::$categoryName = $categoryName;
SP_Category::addCategory($categoryName);
$categoryId = SP_Category::$categoryLastId;
}
$pass = self::encryptPass($password);
$account->accountName = $accountName;
$account->accountCustomerId = $customerId;
$account->accountCategoryId = $categoryId;
@@ -173,24 +183,29 @@ class SP_Import {
$account->accountNotes = $notes;
$account->accountUserId = $userId;
$account->accountUserGroupId = $groupId;
if ( ! $account->createAccount() ){
if (!$account->createAccount()) {
$message['action'] = _('Importar Cuentas');
$message['text'][] = _('Error importando cuenta');
$message['text'][] = $data;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
}
}
return true;
}
/**
* @brief Encriptar la clave de una cuenta
* @param string $password con la clave de la cuenta
* @throws ImportException
* @return array con la clave y el IV
*/
private static function encryptPass($password){
*/
private static function encryptPass($password)
{
$crypt = new SP_Crypt;
// Comprobar el módulo de encriptación
if (!SP_Crypt::checkCryptModule()) {
throw new ImportException('critical', _('Error interno'), _('No se puede usar el módulo de encriptación'));
@@ -199,12 +214,12 @@ class SP_Import {
// Encriptar clave
$data['pass'] = $crypt->mkEncrypt($password);
if ($data['pass'] === FALSE || is_null($data['pass'])) {
if ($data['pass'] === false || is_null($data['pass'])) {
throw new ImportException('critical', _('Error interno'), _('Error al generar datos cifrados'));
}
$data['IV'] = $crypt->strInitialVector;
return $data;
}

View File

@@ -1,79 +1,97 @@
<?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-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'));
define ('EXTENSIONS_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ext');
class SP_Init {
// Associative array for autoloading. classname => filename
public static $CLASSPATH = array();
// The installation path on the server (e.g. /srv/www/syspass)
public static $SERVERROOT = '';
// The current request path relative to the sysPass root (e.g. files/index.php)
private static $SUBURI = '';
// The sysPass root path for http requests (e.g. syspass/)
public static $WEBROOT = '';
class SP_Init
{
public static $CLASSPATH = array(); // Associative array for autoloading. classname => filename
public static $SERVERROOT = ''; // The installation path on the server (e.g. /srv/www/syspass)
public static $WEBROOT = ''; // The current request path relative to the sysPass root (e.g. files/index.php)
public static $WEBURI = ''; // The sysPass root path for http requests (e.g. syspass/)
public static $LANG = '';
public static $UPDATED = FALSE;
public static $UPDATED = false;
private static $SUBURI = '';
/**
* SPL autoload
*/
public static function autoload($classname){
* SPL autoload
*/
public static function sysPassAutoload($classname)
{
$class = str_replace("sp_", '', strtolower($classname));
$classfile = dirname(__FILE__)."/$class.class.php";
$classfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . $class . ".class.php";
//error_log('Cargando clase: '.$classfile);
if (file_exists($classfile)) {
include_once ($classfile);
if (is_readable($classfile)) {
require $classfile;
} else {
error_log('Class Autoloader Error: ' . $classfile);
}
}
/**
* @brief Inicialiar la aplicación
* @brief Inicializar la aplicación
* @return none
*
* Esta función inicializa las variables de la aplicación y muestra la página
*
* Esta función inicializa las variables de la aplicación y muestra la página
* según el estado en el que se encuentre.
*/
public static function init(){
// Registro del cargador de clases
spl_autoload_register(array('SP_Init','autoload'));
public static function init()
{
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
// Registro del cargador de clases (PHP >= 5.1.2)
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register(array('SP_Init', 'sysPassAutoload'), true, true);
} else {
spl_autoload_register(array('SP_Init', 'sysPassAutoload'));
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* @param string $classname The name of the class to load
*/
function __autoload($classname)
{
SP_Init::sysPassAutoload($classname);
}
}
error_reporting(E_ALL | E_STRICT);
if (defined('DEBUG') && DEBUG) {
ini_set('display_errors', 1);
}
date_default_timezone_set('UTC');
// Intentar desactivar magic quotes.
if (get_magic_quotes_gpc()==1) {
if (get_magic_quotes_gpc() == 1) {
ini_set('magic_quotes_runtime', 0);
}
// Copiar la cabecera http de autentificación para apache+php-fcgid
if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
@@ -81,7 +99,8 @@ class SP_Init {
// Establecer las cabeceras de autentificación para apache+php-cgi
if (isset($_SERVER['HTTP_AUTHORIZATION'])
&& preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
&& preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)
) {
list($name, $password) = explode(':', base64_decode($matches[1]), 2);
$_SERVER['PHP_AUTH_USER'] = strip_tags($name);
$_SERVER['PHP_AUTH_PW'] = strip_tags($password);
@@ -89,116 +108,122 @@ class SP_Init {
// Establecer las cabeceras de autentificación para que apache+php-cgi funcione si la variable es renombrada por apache
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])
&& preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
&& preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)
) {
list($name, $password) = explode(':', base64_decode($matches[1]), 2);
$_SERVER['PHP_AUTH_USER'] = strip_tags($name);
$_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
self::setPaths();
// Establecer el modo debug si una sesión de xdebug está activa
if ( !defined('DEBUG') || !DEBUG ) {
if (!defined('DEBUG') || !DEBUG) {
if (isset($_COOKIE['XDEBUG_SESSION'])) {
define('DEBUG', true);
}
}
// Cargar el lenguaje
self::selectLang();
// Comprobar la configuración
self::checkConfig();
// Comprobar si está instalado
self::checkInstalled();
// Comprobar si la Base de datos existe
if ( ! db::checkDatabaseExist() ){
if (!db::checkDatabaseExist()) {
self::initError(_('Error en la verificación de la base de datos'));
}
// Comprobar si el modo mantenimiento está activado
self::checkMaintenanceMode();
// Comprobar la versión y actualizarla
self::checkVersion();
// Inicializar la sesión
self::initSession();
// Comprobar acciones en URL
self::checkRequestActions();
// Intentar establecer el tiempo de vida de la sesión en PHP
$sessionLifeTime = self::getSessionLifeTime();
@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
if ( ! SP_Config::getValue("installed", false) ) {
if (!SP_Config::getValue("installed", false)) {
$_SESSION['user_id'] = '';
}
if ( isset($_SERVER['PHP_AUTH_USER']) && isset($_SESSION['user_id'])
&& $_SERVER['PHP_AUTH_USER'] != $_SESSION['user_id']) {
self::logout();
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SESSION['user_id'])
&& $_SERVER['PHP_AUTH_USER'] != $_SESSION['user_id']
) {
self::logout();
}
// Manejar la redirección para usuarios logeados
if ( isset($_REQUEST['redirect_url']) && self::isLoggedIn() ) {
if (isset($_REQUEST['redirect_url']) && self::isLoggedIn()) {
$location = 'index.php';
// Denegar la regirección si la URL contiene una @
// Esto previene redirecciones como ?redirect_url=:user@domain.com
if (strpos($location, '@') === FALSE) {
header('Location: ' . $location);
return;
if (strpos($location, '@') === false) {
header('Location: ' . $location);
return;
}
}
// El usuario está logado
if ( self::isLoggedIn() ) {
if (self::isLoggedIn()) {
if (isset($_GET["logout"]) && $_GET["logout"]) {
self::logout();
if (count($_GET) > 1){
foreach ($_GET as $param => $value){
if ($param == 'logout'){
if (count($_GET) > 1) {
foreach ($_GET as $param => $value) {
if ($param == 'logout') {
continue;
}
$params[] = $param.'='.$value;
$params[] = $param . '=' . $value;
}
header("Location: ".self::$WEBROOT.'/index.php?'.implode('&', $params));
header("Location: " . self::$WEBROOT . '/index.php?' . implode('&', $params));
} else {
header("Location: ".self::$WEBROOT.'/');
header("Location: " . self::$WEBROOT . '/');
}
}
}
return;
} else {
// Si la petición es ajax, no hacer nada
if ( (isset($_POST['is_ajax']) || isset($_GET['is_ajax']) )
&& ($_POST['is_ajax'] || $_GET['is_ajax']) ){
if ((isset($_POST['isAjax']) || isset($_GET['isAjax']))
&& ($_POST['isAjax'] || $_GET['isAjax'])
) {
return;
}
SP_Html::render('login');
exit();
}
}
/**
* @brief Establecer las rutas de la aplicación
* @return none
*
*
* Esta función establece las rutasdel sistema de archivos y web de la aplicación.
* La variables de clase definidas son $SERVERROOT, $WEBROOT y $SUBURI
*/
private static function setPaths(){
private static function setPaths()
{
// Calcular los directorios raíz
self::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
self::$SERVERROOT = str_replace("\\", DIRECTORY_SEPARATOR, substr(__DIR__, 0, -4));
// Establecer la ruta include correcta
set_include_path(self::$SERVERROOT.'/inc'.PATH_SEPARATOR.
self::$SERVERROOT.'/config'.PATH_SEPARATOR.
get_include_path() . PATH_SEPARATOR.self::$SERVERROOT);
self::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(self::$SERVERROOT)));
set_include_path(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'inc' . PATH_SEPARATOR .
self::$SERVERROOT . DIRECTORY_SEPARATOR . 'config' . PATH_SEPARATOR .
get_include_path() . PATH_SEPARATOR . self::$SERVERROOT);
self::$SUBURI = str_replace("\\", '/', substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(self::$SERVERROOT)));
$scriptName = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
if (substr($scriptName, -1) == '/') {
$scriptName .= 'index.php';
@@ -212,49 +237,102 @@ class SP_Init {
}
//self::$WEBROOT = substr($scriptName, 0, strlen($scriptName) - strlen(self::$SUBURI) + 1);
self::$WEBROOT = substr($scriptName, 0, strpos($scriptName,self::$SUBURI));
self::$WEBROOT = substr($scriptName, 0, strpos($scriptName, self::$SUBURI));
if (self::$WEBROOT != '' and self::$WEBROOT[0] !== '/') {
self::$WEBROOT = '/'.self::$WEBROOT;
}
self::$WEBROOT = '/' . self::$WEBROOT;
}
self::$WEBURI = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
self::$WEBURI .= $_SERVER['HTTP_HOST'] . self::$WEBROOT;
}
/**
* @brief Establece el lenguaje de la aplicación
* @returns none
*
* Esta función establece el lenguaje según esté definidi en la configuración o en el navegador.
*/
private static function selectLang()
{
$browserLang = str_replace("-", "_", substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5));
$configLang = SP_Config::getValue('sitelang');
// Establecer a en_US si no existe la traducción o no es español
if (!file_exists(self::$SERVERROOT . '/inc/locales/' . $browserLang)
&& !preg_match('/^es_.*/i', $browserLang)
&& !$configLang
) {
self::$LANG = 'en_US';
} else {
self::$LANG = ($configLang) ? $configLang : $browserLang;
}
self::$LANG = self::$LANG . ".utf8";
putenv("LANG=" . self::$LANG);
setlocale(LC_MESSAGES, self::$LANG);
setlocale(LC_ALL, self::$LANG);
bindtextdomain("messages", self::$SERVERROOT . "/inc/locales");
textdomain("messages");
bind_textdomain_codeset("messages", 'UTF-8');
}
/**
* @brief Comprobar el archivo de configuración.
* @return none
*
*
* Esta función comprueba que el archivo de configuración exista y los permisos sean correctos.
*/
private static function checkConfig() {
if ( !is_dir(self::$SERVERROOT.'/config') ){
private static function checkConfig()
{
if (!is_dir(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'config')) {
self::initError(_('El directorio "/config" no existe'));
}
if ( !is_writable(self::$SERVERROOT.'/config') ) {
}
if (!is_writable(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'config')) {
self::initError(_('No es posible escribir en el directorio "config"'));
}
//$configPerms = substr(sprintf('%o', fileperms(self::$SERVERROOT.'/config')), -4);
$configPerms = decoct(fileperms(self::$SERVERROOT.'/config') & 0777);
if ( ! SP_Util::runningOnWindows() && $configPerms != "750" ){
self::initError(_('Los permisos del directorio "/config" son incorrectos'),$configPerms);
$configPerms = decoct(fileperms(self::$SERVERROOT . DIRECTORY_SEPARATOR . 'config') & 0777);
if (!SP_Util::runningOnWindows() && $configPerms != "750") {
self::initError(_('Los permisos del directorio "/config" son incorrectos'), $configPerms);
}
}
/**
* @brief Devuelve un eror utilizando la plantilla de rror
* @param string $str con la descripción del error
* @param string $hint opcional, con una ayuda sobre el error
* @returns none
*/
public static function initError($str, $hint = '')
{
$errors[] = array(
'type' => 'critical',
'description' => $str,
'hint' => $hint);
SP_Html::render('error', $errors);
exit();
}
/**
* @brief Comprueba que la aplicación esté instalada
* @return none
*
*
* Esta función comprueba si la aplicación está instalada. Si no lo está, redirige al instalador.
*/
private static function checkInstalled() {
private static function checkInstalled()
{
// Redirigir al instalador si no está instalada
if (!SP_Config::getValue('installed', false) && self::$SUBURI != '/index.php') {
$url = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].self::$WEBROOT.'/index.php';
$url = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . self::$WEBROOT . '/index.php';
header("Location: $url");
exit();
} elseif ( !SP_Config::getValue('installed', false) && self::$SUBURI == '/index.php') {
} elseif (!SP_Config::getValue('installed', false) && self::$SUBURI == '/index.php') {
// Comprobar si sysPass está instalada o en modo mantenimiento
if (!SP_Config::getValue('installed', false)) {
SP_Html::render('install');
@@ -267,54 +345,100 @@ class SP_Init {
* @brief Comprobar si el modo mantenimeinto está activado
* @param bool $check sólo comprobar si está activado el modo
* @return bool
*
*
* Esta función comprueba si el modo mantenimiento está activado.
* Devuelve un error 503 y un reintento de 120s al cliente.
*/
public static function checkMaintenanceMode($check = FALSE) {
if ( SP_Config::getValue('maintenance', false) ) {
if ( $check === TRUE
|| $_REQUEST['is_ajax'] == 1
public static function checkMaintenanceMode($check = false)
{
if (SP_Config::getValue('maintenance', false)) {
if ($check === true
|| $_REQUEST['isAjax'] == 1
|| $_REQUEST['upgrade'] == 1
|| $_REQUEST['nodbupgrade'] == 1 ){
return TRUE;
|| $_REQUEST['nodbupgrade'] == 1
) {
return true;
}
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 120');
self::initError(_('Aplicación en mantenimiento'),_('En breve estará operativa'));
self::initError(_('Aplicación en mantenimiento'), _('En breve estará operativa'));
}
return FALSE;
return false;
}
/**
* @brief Comrpueba y actualiza la versión de la aplicación
* @returns none
*/
private static function checkVersion()
{
if (substr(self::$SUBURI, -9) != 'index.php' || SP_Common::parseParams('g', 'logout', 0) === 1) {
return;
}
$update = false;
$configVersion = (int)str_replace('.', '', SP_Config::getValue('version'));
$databaseVersion = (int)str_replace('.', '', SP_Config::getConfigValue('version'));
$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)) {
self::initError(_('La aplicación necesita actualizarse'), _('Contacte con el administrador'));
}
if (SP_Upgrade::doUpgrade($databaseVersion)) {
SP_Config::setConfigValue('version', $appVersion);
$update = true;
}
}
if ($configVersion < $appVersion) {
SP_Config::setValue('version', $appVersion);
$update = true;
}
if ($update === true) {
$message['action'] = _('Actualización');
$message['text'][] = _('Actualización de versión realizada.');
$message['text'][] = _('Versión') . ': ' . $appVersion;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
self::$UPDATED = true;
}
}
/**
* @brief Inicialiar la sesión de usuario
* @return none
*/
private static function initSession() {
*/
private static function initSession()
{
// Evita que javascript acceda a las cookis de sesion de PHP
ini_set('session.cookie_httponly', '1;');
// Si la sesión no puede ser iniciada, devolver un error 500
if ( session_start() === false){
SP_Common::wrLogInfo(_('Sesion'), _('La sesión no puede ser inicializada'));
if (session_start() === false) {
SP_Log::wrLogInfo(_('Sesion'), _('La sesión no puede ser inicializada'));
header('HTTP/1.1 500 Internal Server Error');
$errors[] = array(
'type' => 'critical',
'description' => _('La sesión no puede ser inicializada'),
'hint' => _('Contacte con el administrador'));
SP_Html::render('error',$errors);
exit();
'type' => 'critical',
'description' => _('La sesión no puede ser inicializada'),
'hint' => _('Contacte con el administrador'));
SP_Html::render('error', $errors);
exit();
}
$sessionLifeTime = self::getSessionLifeTime();
// Regenerar el Id de sesión periódicamente para evitar fijación
if (!isset($_SESSION['SID_CREATED'])) {
$_SESSION['SID_CREATED'] = time();
@@ -332,162 +456,102 @@ class SP_Init {
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 42000, '/');
}
self::wrLogoutInfo();
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = time();
}
/**
* @brief Obtener el timeout de sesión desde la configuración
* @returns int con el tiempo en segundos
*/
private static function getSessionLifeTime()
{
return SP_Config::getValue('session_timeout', 60 * 60 * 24);
}
/**
* @brief Escribir la información de logout en el registro de eventos
* @return none
*/
private static function wrLogoutInfo()
{
$inactiveTime = round(((time() - $_SESSION['LAST_ACTIVITY']) / 60), 2);
$totalTime = round(((time() - $_SESSION['START_ACTIVITY']) / 60), 2);
$message['action'] = _('Finalizar sesión');
$message['text'][] = _('Usuario') . ": " . $_SESSION['ulogin'];
$message['text'][] = _('Tiempo inactivo') . ": " . $inactiveTime . " min.";
$message['text'][] = _('Tiempo total') . ": " . $totalTime . " min.";
SP_Log::wrLogInfo($message);
}
/**
* @brief Comprobar si hay que ejecutar acciones de URL
* @return bool
*/
public static function checkRequestActions()
{
if (!isset($_REQUEST['a'])) {
return;
}
$action = $_REQUEST['a'];
switch ($action) {
case 'passreset':
SP_Html::render('passreset');
break;
default:
return false;
}
exit();
}
/**
* @brief Deslogar el usuario actual y eliminar la información de sesión
* @return none
*/
private static function logout() {
self::wrLogoutInfo();
session_unset();
session_destroy();
}
/**
* @brief Escribir la información de logout en el registro de eventos
* @return none
*/
private static function wrLogoutInfo() {
$inactiveTime = round(((time() - $_SESSION['LAST_ACTIVITY']) / 60),2);
$totalTime = round(((time() - $_SESSION['START_ACTIVITY']) / 60),2);
$message['action'] = _('Finalizar sesión');
$message['text'][] = _('Usuario').": ".$_SESSION['uname'];
$message['text'][] = _('IP').": ".$_SERVER['REMOTE_ADDR'];
$message['text'][] = _('Tiempo inactivo').": ".$inactiveTime." min.";
$message['text'][] = _('Tiempo total').": ".$totalTime." min.";
private static function logout()
{
self::wrLogoutInfo();
SP_Common::wrLogInfo($message);
session_unset();
session_destroy();
}
/**
* @brief Comprobar si el usuario está logado
* @returns bool
*/
public static function isLoggedIn() {
if( isset($_SESSION['ulogin']) AND $_SESSION['ulogin']) {
public static function isLoggedIn()
{
if (isset($_SESSION['ulogin']) AND $_SESSION['ulogin']) {
// TODO: refrescar variables de sesión.
return true;
}
return false;
}
/**
* @brief Obtener el timeout de sesión desde la configuración
* @returns int con el tiempo en segundos
*/
private static function getSessionLifeTime() {
return SP_Config::getValue('session_timeout', 60 * 60 * 24);
}
/**
* @brief Devuelve el tiempo actual en coma flotante
* @returns float con el tiempo actual
*
*
* Esta función se utiliza para calcular el tiempo de renderizado con coma flotante
*/
public static function microtime_float(){
public static function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* @brief Devuelve un eror utilizando la plantilla de rror
* @param string $str con la descripción del error
* @param string $hint opcional, con una ayuda sobre el error
* @returns none
*/
public static function initError($str, $hint = ''){
$errors[] = array(
'type' => 'critical',
'description' => $str,
'hint' => $hint);
SP_Html::render('error',$errors);
exit();
}
/**
* @brief Establece el lenguaje de la aplicación
* @returns none
*
* Esta función establece el lenguaje según esté definidi en la configuración o en el navegador.
*/
private static function selectLang(){
$browserLang = str_replace("-","_",substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5));
$configLang = SP_Config::getValue('sitelang');
// Establecer a en_US si no existe la traducción o no es español
if ( ! file_exists( self::$SERVERROOT.'/inc/locales/'.$browserLang)
&& ! preg_match('/^es_.*/i',$browserLang)
&& ! $configLang ){
self::$LANG = 'en_US';
} else{
self::$LANG = ( $configLang ) ? $configLang : $browserLang;
}
self::$LANG = self::$LANG.".utf8";
putenv("LANG=".self::$LANG);
setlocale(LC_MESSAGES, self::$LANG);
setlocale(LC_ALL, self::$LANG);
bindtextdomain("messages", self::$SERVERROOT."/inc/locales");
textdomain("messages");
bind_textdomain_codeset("messages", 'UTF-8');
}
/**
* @brief Comrpueba y actualiza la versión de la aplicación
* @returns none
*/
private static function checkVersion(){
if (substr(self::$SUBURI, -9) != 'index.php' || SP_Common::parseParams('g', 'logout', 0) === 1 ) {
return;
}
$update = FALSE;
$configVersion = (int) str_replace('.', '', SP_Config::getValue('version'));
$databaseVersion = (int) str_replace('.', '', SP_Config::getConfigValue('version'));
$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) ){
self::initError(_('La aplicación necesita actualizarse'), _('Contacte con el administrador'));
}
if ( SP_Upgrade::doUpgrade($databaseVersion) ){
SP_Config::setConfigValue('version', $appVersion);
$update = TRUE;
}
}
if ( $configVersion < $appVersion ){
SP_Config::setValue('version', $appVersion);
$update = TRUE;
}
if ( $update === TRUE ){
$message['action'] = _('Actualización');
$message['text'][] = _('Actualización de versión realizada.');
$message['text'][] = _('Versión') . ': ' . $appVersion;
SP_Common::wrLogInfo($message);
SP_Common::sendEmail($message);
self::$UPDATED = TRUE;
}
}
}
// Empezar a calcular el tiempo y memoria utilizados

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -29,26 +29,30 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
/**
* Extender la clase Exception para mostrar ayuda en los mensajes
*/
class InstallerException extends Exception {
class InstallerException extends Exception
{
private $type;
private $hint;
public function __construct($type, $message, $hint, $code = 0, Exception $previous = null) {
public function __construct($type, $message, $hint, $code = 0, Exception $previous = null)
{
$this->type = $type;
$this->hint = $hint;
parent::__construct($message, $code, $previous);
}
public function __toString() {
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
}
public function getHint() {
public function getHint()
{
return $this->hint;
}
public function getType() {
public function getType()
{
return $this->type;
}
@@ -57,8 +61,8 @@ class InstallerException extends Exception {
/**
* Esta clase es la encargada de instalar sysPass.
*/
class SP_Installer {
class SP_Installer
{
private static $dbuser;
private static $dbname;
private static $dbhost;
@@ -72,8 +76,9 @@ class SP_Installer {
* @brief Iniciar instalación
* @param array $options datos de instalación
* @return array resultado del proceso
*/
public static function install($options) {
*/
public static function install($options)
{
$error = array();
if (empty($options['adminlogin'])) {
@@ -144,13 +149,13 @@ class SP_Installer {
//generate a random salt that is used to salt the local user passwords
$salt = SP_Util::generate_random_bytes(30);
SP_Config::setValue('passwordsalt', $salt);
SP_Config::setValue('version', implode(SP_Util::getVersion(TRUE)));
SP_Config::setValue('version', implode(SP_Util::getVersion(true)));
$dbadmin = $options['dbuser'];
$dbpass = $options['dbpass'];
$dbhost = $options['dbhost'];
self::$isHostingMode = ( isset($options['hostingmode']) ) ? 1: 0;
self::$isHostingMode = (isset($options['hostingmode'])) ? 1 : 0;
// Save DB connection info
SP_Config::setValue('dbhost', $dbhost);
@@ -165,14 +170,14 @@ class SP_Installer {
self::createAdminAccount();
} catch (InstallerException $e) {
$error[] = array('type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint());
return($error);
return ($error);
}
SP_Config::setConfigValue('version', implode(SP_Util::getVersion(TRUE)));
SP_Config::setConfigValue('version', implode(SP_Util::getVersion(true)));
SP_Config::setValue('installed', 1);
}
return($error);
return ($error);
}
/**
@@ -180,39 +185,43 @@ class SP_Installer {
* @param string $dbhost host de conexión
* @param string $dbadmin usuario de conexión
* @param string $dbpass clave de conexión
* @throws InstallerException
* @return none
*
* Comprobar si la conexión con la base de datos para sysPass es posible con
* los datos facilitados.
*/
private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass) {
private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass)
{
self::$dbc = new mysqli($dbhost, $dbadmin, $dbpass);
if (self::$dbc->connect_errno) {
throw new InstallerException('critical'
, _('El usuario/clave de MySQL no es correcto')
, _('Verifique el usuario de conexión con la Base de Datos'));
, _('El usuario/clave de MySQL no es correcto')
, _('Verifique el usuario de conexión con la Base de Datos'));
}
}
/**
* @brief Configurar la base de datos
* @throws InstallerException
* @return none
*
* Esta función crea la base de datos y el usuario necesario para sysPass.
*/
private static function setupMySQLDatabase() {
private static function setupMySQLDatabase()
{
$oldUser = SP_Config::getValue('dbuser', false);
//this should be enough to check for admin rights in mysql
$query = "SELECT user "
. "FROM mysql.user "
. "WHERE user='" . self::$username . "' and host='" . self::$dbhost . "';";
. "FROM mysql.user "
. "WHERE user='" . self::$username . "' and host='" . self::$dbhost . "';";
// Hash DB connection password
$dbpassword = ( ! self::$isHostingMode ) ? md5(time() . self::$password) : self::$password;
self::$dbuser = ( ! self::$isHostingMode ) ? substr('sp_' . self::$username, 0, 16) : self::$username;
$dbpassword = (!self::$isHostingMode) ? md5(time() . self::$password) : self::$password;
self::$dbuser = (!self::$isHostingMode) ? substr('sp_' . self::$username, 0, 16) : self::$username;
if (!self::$dbc->query($query)) {
if (self::$dbuser != $oldUser) {
@@ -234,22 +243,79 @@ class SP_Installer {
self::createDBStructure();
} else {
throw new InstallerException('critical'
, _('La BBDD ya existe')
, _('Indique una nueva Base de Datos o elimine la existente'));
, _('La BBDD ya existe')
, _('Indique una nueva Base de Datos o elimine la existente'));
}
// self::$dbc->close();
}
/**
* @brief Crear el usuario para conectar con la base de datos.
* @param string $dbpassword clave del usuario de sysPass
* @throws InstallerException
* @return none
*
* Esta función crea el usuario para conectar con la base de datos.
* Si se marca en modo hosting, no se crea el usuario.
*/
private static function createDBUser($dbpassword)
{
if (self::$isHostingMode) {
return;
}
$query = "CREATE USER '" . self::$dbuser . "'@'localhost' IDENTIFIED BY '" . $dbpassword . "'";
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('El usuario de MySQL ya existe') . " (" . self::$dbuser . ")"
, _('Indique un nuevo usuario o elimine el existente'));
}
}
/**
* @brief Crear la base de datos
* @param string $dbpassword clave del usuario de sysPass
* @throws InstallerException
* @return none
*
* Esta función crea la base de datos y asigna los permisos para el usuario de sysPass.
* Si se marca el modo hosting, no se establecen los permisos.
*/
private static function createMySQLDatabase($dbpassword)
{
$query = "CREATE DATABASE IF NOT EXISTS `" . self::$dbname . "`";
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('Error al crear la BBDD') . " (" . self::$dbc->error . ")"
, _('Verifique los permisos del usuario de la Base de Datos'));
}
if (!self::$isHostingMode) {
$query = "GRANT ALL PRIVILEGES ON `" . self::$dbname . "`.* TO '" . self::$dbuser . "'@'" . self::$dbhost . "' IDENTIFIED BY '$dbpassword';";
self::$dbc->query($query);
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('Error al establecer permisos de la BBDD') . " (" . self::$dbc->error . ")"
, _('Verifique los permisos del usuario de la Base de Datos'));
}
}
}
/**
* @brief Comprobar si la base de datos indicada existe
* @return bool
*/
private static function checkDatabaseExist() {
private static function checkDatabaseExist()
{
$query = "SELECT COUNT(*) "
. "FROM information_schema.tables "
. "WHERE table_schema = '" . self::$dbname . "' "
. "AND table_name = 'usrData';";
. "FROM information_schema.tables "
. "WHERE table_schema = '" . self::$dbname . "' "
. "AND table_name = 'usrData';";
$resquery = self::$dbc->query($query);
@@ -264,78 +330,28 @@ class SP_Installer {
return true;
}
/**
* @brief Crear la base de datos
* @param string $dbpassword clave del usuario de sysPass
* @return none
*
* Esta función crea la base de datos y asigna los permisos para el usuario de sysPass.
* Si se marca el modo hosting, no se establecen los permisos.
*/
private static function createMySQLDatabase($dbpassword) {
$query = "CREATE DATABASE IF NOT EXISTS `" . self::$dbname . "`";
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('Error al crear la BBDD') . " (" . self::$dbc->error . ")"
, _('Verifique los permisos del usuario de la Base de Datos'));
}
if ( ! self::$isHostingMode ){
$query = "GRANT ALL PRIVILEGES ON `" . self::$dbname . "`.* TO '" . self::$dbuser . "'@'" . self::$dbhost . "' IDENTIFIED BY '$dbpassword';";
self::$dbc->query($query);
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('Error al establecer permisos de la BBDD') . " (" . self::$dbc->error . ")"
, _('Verifique los permisos del usuario de la Base de Datos'));
}
}
}
/**
* @brief Crear el usuario para conectar con la base de datos.
* @param string $dbpassword clave del usuario de sysPass
* @return none
*
* Esta función crea el usuario para conectar con la base de datos.
* Si se marca en modo hosting, no se crea el usuario.
*/
private static function createDBUser($dbpassword) {
if ( self::$isHostingMode ){
return;
}
$query = "CREATE USER '" . self::$dbuser . "'@'localhost' IDENTIFIED BY '" . $dbpassword . "'";
if (!self::$dbc->query($query)) {
throw new InstallerException('critical'
, _('El usuario de MySQL ya existe') . " (" . self::$dbuser . ")"
, _('Indique un nuevo usuario o elimine el existente'));
}
}
/**
* @brief Crear la estructura de la base de datos
* @throws InstallerException
* @return none
*
* Esta función crea la estructura de la base de datos a partir del archivo dbsctructure.sql.
*/
private static function createDBStructure() {
private static function createDBStructure()
{
$fileName = dirname(__FILE__) . '/dbstructure.sql';
if (!file_exists($fileName)) {
throw new InstallerException('critical'
, _('El archivo de estructura de la BBDD no existe')
, _('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.'));
, _('El archivo de estructura de la BBDD no existe')
, _('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.'));
}
// Usar la base de datos de sysPass
if (!self::$dbc->select_db(self::$dbname)) {
throw new InstallerException('critical'
, _('Error al seleccionar la BBDD') . " '" . self::$dbname . "' (" . self::$dbc->error . ")"
, _('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.'));
, _('Error al seleccionar la BBDD') . " '" . self::$dbname . "' (" . self::$dbc->error . ")"
, _('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.'));
}
// Leemos el archivo SQL para crear las tablas de la BBDD
@@ -349,8 +365,8 @@ class SP_Installer {
// drop database on error
self::$dbc->query("DROP DATABASE " . self::$dbname . ";");
throw new InstallerException('critical'
, _('Error al crear la BBDD')
, _('Error al crear la estructura de la Base de Datos.'));
, _('Error al crear la BBDD')
, _('Error al crear la estructura de la Base de Datos.'));
}
}
}
@@ -359,11 +375,13 @@ class SP_Installer {
/**
* @brief Crear el usuario admin de sysPass.
* @throws InstallerException
* @return none
*
* Esta función crea el grupo, perfil y usuario 'admin' para utilizar sysPass.
*/
private static function createAdminAccount() {
private static function createAdminAccount()
{
$user = new SP_Users;
// Datos del grupo
@@ -374,30 +392,30 @@ class SP_Installer {
self::rollback();
throw new InstallerException("critical"
, _('Error al crear el grupo "admin"')
, _('Informe al desarrollador'));
, _('Error al crear el grupo "admin"')
, _('Informe al desarrollador'));
}
// Establecer el id de grupo del usuario al recién creado
$user->userGroupId = SP_Groups::$queryLastId;
$profileProp = array("pAccView" => 1
, "pAccViewPass" => 1
, "pAccViewHistory" => 1
, "pAccEdit" => 1
, "pAccEditPass" => 1
, "pAccAdd" => 1
, "pAccDel" => 1
, "pAccFiles" => 1
, "pConfig" => 1
, "pConfigMpw" => 1
, "pConfigBack" => 1
, "pAppMgmtCat" => 1
, "pAppMgmtCust" => 1
, "pUsers" => 1
, "pGroups" => 1
, "pProfiles" => 1
, "pEventlog" => 1);
$profileProp = array("pAccView" => 1,
"pAccViewPass" => 1,
"pAccViewHistory" => 1,
"pAccEdit" => 1,
"pAccEditPass" => 1,
"pAccAdd" => 1,
"pAccDel" => 1,
"pAccFiles" => 1,
"pConfig" => 1,
"pConfigMpw" => 1,
"pConfigBack" => 1,
"pAppMgmtCat" => 1,
"pAppMgmtCust" => 1,
"pUsers" => 1,
"pGroups" => 1,
"pProfiles" => 1,
"pEventlog" => 1);
SP_Profiles::$profileName = 'Admin';
@@ -406,13 +424,13 @@ class SP_Installer {
self::rollback();
throw new InstallerException("critical"
, _('Error al crear el perfil "admin"')
, _('Informe al desarrollador'));
, _('Error al crear el perfil "admin"')
, _('Informe al desarrollador'));
}
// Establecer el id de perfil del usuario al recién creado
$user->userProfileId = SP_Profiles::$queryLastId;
// Datos del usuario
$user->userLogin = self::$username;
$user->userPass = self::$password;
@@ -424,23 +442,23 @@ class SP_Installer {
self::rollback();
throw new InstallerException('critical'
, _('Error al crear el usuario "admin"')
, _('Informe al desarrollador'));
, _('Error al crear el usuario "admin"')
, _('Informe al desarrollador'));
}
// Guardar el hash de la clave maestra
SP_Config::$arrConfigValue["masterPwd"] = SP_Crypt::mkHashPassword(self::$masterPassword);
SP_Config::$arrConfigValue["lastupdatempass"] = time();
SP_Config::writeConfig(TRUE);
SP_Config::writeConfig(true);
$user->userId = $user->queryLastId; // Needed for update user's master password
if (!$user->updateUserMPass(self::$masterPassword, FALSE)) {
if (!$user->updateUserMPass(self::$masterPassword, false)) {
self::rollback();
throw new InstallerException('critical'
, _('Error al actualizar la clave maestra del usuario "admin"')
, _('Informe al desarrollador'));
, _('Error al actualizar la clave maestra del usuario "admin"')
, _('Informe al desarrollador'));
}
}
@@ -450,7 +468,8 @@ class SP_Installer {
*
* Esta función elimina la base de datos y el usuario de sysPass
*/
private static function rollback() {
private static function rollback()
{
self::$dbc->query("DROP DATABASE IF EXISTS " . self::$dbname . ";");
self::$dbc->query("DROP USER '" . self::$dbuser . "'@'" . self::$dbhost . "';");
self::$dbc->query("DROP USER '" . self::$dbuser . "'@'%';");

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,26 +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 la autentificación de usuarios de sysPass.
*/
class SP_LDAP {
class SP_LDAP
{
public static $ldapSearchData;
private static $ldapConn;
private static $ldapServer;
private static $searchBase;
private static $bindDN;
private static $bindPass;
private static $ldapGroup;
public static $ldapSearchData;
/**
* @brief Obtener el recurso de conexión a LDAP
* @return resource
*/
public static function getConn() {
public static function getConn()
{
if (is_resource(self::$ldapConn)) {
return self::$ldapConn;
}
@@ -57,7 +59,8 @@ class SP_LDAP {
* @param string $ldapGroup con el grupo con los usuarios de acceso
* @return bool
*/
public static function checkLDAPConn($ldapServer, $bindDN, $bindPass, $searchBase, $ldapGroup) {
public static function checkLDAPConn($ldapServer, $bindDN, $bindPass, $searchBase, $ldapGroup)
{
self::$ldapServer = $ldapServer;
self::$bindDN = $bindDN;
self::$bindPass = $bindPass;
@@ -69,17 +72,156 @@ class SP_LDAP {
self::ldapBind();
$numObjects = self::searchBase();
} catch (Exception $e) {
return FALSE;
return false;
}
return $numObjects;
}
/**
* @brief Realizar la conexión al servidor de LDAP
* @throws Exception
* @return bool
*/
public static function ldapConnect()
{
$message['action'] = __FUNCTION__;
// Conexión al servidor LDAP
if (!self::$ldapConn = @ldap_connect(self::$ldapServer)) {
$message['text'][] = _('No es posible conectar con el servidor de LDAP') . " '" . self::$ldapServer . "'";
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
SP_Log::wrLogInfo($message);
throw new Exception(_('No es posible conectar con el servidor de LDAP'));
}
@ldap_set_option(self::$ldapConn, LDAP_OPT_NETWORK_TIMEOUT, 10); // Set timeout
@ldap_set_option(self::$ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); // Set LDAP version
return true;
}
/**
* @brief Realizar la autentificación con el servidor de LDAP
* @param string $userDN con el DN del usuario
* @param string $userPass con la clave del usuario
* @throws Exception
* @return bool
*/
public static function ldapBind($userDN = '', $userPass = '')
{
$message['action'] = __FUNCTION__;
$dn = ($userDN) ? $userDN : self::$bindDN;
$pass = ($userPass) ? $userPass : self::$bindPass;
if (!@ldap_bind(self::$ldapConn, $dn, $pass)) {
$message['text'][] = _('Error al conectar (BIND)');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP DN: ' . $dn;
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al conectar (BIND)'));
}
return true;
}
/**
* @brief Realizar una búsqueda de objetos en la ruta indicada
* @throws Exception
* @return int con el número de resultados
*/
private static function searchBase()
{
$message['action'] = __FUNCTION__;
$groupDN = self::searchGroupDN();
$filter = '(&(|(memberOf=' . $groupDN . ')(groupMembership=' . $groupDN . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))';
$filterAttr = array("dn");
$searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr);
if (!$searchRes) {
$message['text'][] = _('Error al buscar objetos en DN base');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar objetos en DN base'));
}
return @ldap_count_entries(self::$ldapConn, $searchRes);
}
/**
* @brief Obtener el RDN del grupo
* @throws Exception
* @return string con el RDN del grupo
*/
private static function searchGroupDN()
{
$message['action'] = __FUNCTION__;
$groupName = array();
if (preg_match('/^cn=([\w\s-]+),.*/i', self::$ldapGroup, $groupName)) {
$filter = '(cn=' . $groupName[1] . ')';
} else {
$filter = '(cn=' . self::$ldapGroup . ')';
}
$filterAttr = array("dn", "cn");
$searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr);
if (!$searchRes) {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
if (@ldap_count_entries(self::$ldapConn, $searchRes) === 1) {
$ldapSearchData = @ldap_get_entries(self::$ldapConn, $searchRes);
if (!$ldapSearchData) {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
$message['text'][] = _('RDN de grupo encontrado');
$message['text'][] = 'RDN: ' . $ldapSearchData[0]["dn"];
SP_Log::wrLogInfo($message);
return $ldapSearchData[0]["dn"];
} else {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
}
/**
* @brief Comprobar si los parámetros necesario de LDAP están establecidos
* @return bool
*/
public static function checkLDAPParams() {
public static function checkLDAPParams()
{
self::$searchBase = SP_Config::getValue('ldapbase');
self::$ldapServer = SP_Config::getValue('ldapserver');
self::$bindDN = SP_Config::getValue('ldapbinduser');
@@ -90,69 +232,22 @@ class SP_LDAP {
$message['action'] = __FUNCTION__;
$message['text'][] = _('Los parámetros de LDAP no están configurados');
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
return FALSE;
return false;
}
return TRUE;
}
/**
* @brief Realizar la conexión al servidor de LDAP
* @param string $server con la dirección del servidor
* @return bool
*/
public static function ldapConnect() {
$message['action'] = __FUNCTION__;
// Conexión al servidor LDAP
if (!self::$ldapConn = @ldap_connect(self::$ldapServer)) {
$message['text'][] = _('No es posible conectar con el servidor de LDAP') . " '" . self::$ldapServer . "'";
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
SP_Common::wrLogInfo($message);
throw new Exception(_('No es posible conectar con el servidor de LDAP'));
}
@ldap_set_option(self::$ldapConn, LDAP_OPT_NETWORK_TIMEOUT, 10); // Set timeout
@ldap_set_option(self::$ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); // Set LDAP version
return TRUE;
}
/**
* @brief Realizar la autentificación con el servidor de LDAP
* @param string $dn con el DN del usuario
* @param string $pass con la clave del usuario
* @return bool
*/
public static function ldapBind($userDN = '', $userPass = '') {
$message['action'] = __FUNCTION__;
$dn = ( $userDN ) ? $userDN : self::$bindDN;
$pass = ( $userPass ) ? $userPass : self::$bindPass;
if (!@ldap_bind(self::$ldapConn, $dn, $pass)) {
$message['text'][] = _('Error al conectar (BIND)');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP DN: ' . $dn;
SP_Common::wrLogInfo($message);
throw new Exception(_('Error al conectar (BIND)'));
}
return TRUE;
return true;
}
/**
* @brief Obtener el RDN del usuario que realiza el login
* @param string $userLogin con el login del usuario
* @throws Exception
* @return none
*/
public static function getUserDN($userLogin) {
public static function getUserDN($userLogin)
{
$message['action'] = __FUNCTION__;
$filter = '(&(|(samaccountname=' . $userLogin . ')(cn=' . $userLogin . ')(uid=' . $userLogin . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))';
@@ -165,7 +260,7 @@ class SP_LDAP {
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar el DN del usuario'));
}
@@ -177,7 +272,7 @@ class SP_LDAP {
$message['text'][] = _('Error al localizar el usuario en LDAP');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al localizar el usuario en LDAP'));
}
@@ -185,7 +280,7 @@ class SP_LDAP {
$message['text'][] = _('Error al buscar el DN del usuario');
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar el DN del usuario'));
}
@@ -195,7 +290,8 @@ class SP_LDAP {
* @brief Realizar la desconexión del servidor de LDAP
* @return none
*/
public static function unbind() {
public static function unbind()
{
@ldap_unbind(self::$ldapConn);
}
@@ -204,7 +300,8 @@ class SP_LDAP {
* @param array $attribs con los atributos a obtener
* @return array con los atributos disponibles y sus valores
*/
public static function getLDAPAttr($attribs) {
public static function getLDAPAttr($attribs)
{
$res = array();
foreach (self::$ldapSearchData as $entryValue) {
@@ -228,100 +325,20 @@ class SP_LDAP {
return $res;
}
/**
* @brief Realizar una búsqueda de objetos en la ruta indicada
* @return int con el número de resultados
*/
private static function searchBase() {
$message['action'] = __FUNCTION__;
$groupDN = self::searchGroupDN();
$filter = '(&(|(memberOf=' . $groupDN . ')(groupMembership=' . $groupDN . '))(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject)))';
$filterAttr = array("dn");
$searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr);
if (!$searchRes) {
$message['text'][] = _('Error al buscar objetos en DN base');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
throw new Exception(_('Error al buscar objetos en DN base'));
}
return @ldap_count_entries(self::$ldapConn, $searchRes);
}
/**
* @brief Obtener el RDN del grupo
* @return string con el RDN del grupo
*/
private static function searchGroupDN() {
$message['action'] = __FUNCTION__;
$groupName = array();
if (preg_match('/^cn=([\w\s-]+),.*/i', self::$ldapGroup, $groupName)) {
$filter = '(cn=' . $groupName[1] . ')';
} else {
$filter = '(cn=' . self::$ldapGroup . ')';
}
$filterAttr = array("dn","cn");
$searchRes = @ldap_search(self::$ldapConn, self::$searchBase, $filter, $filterAttr);
if (!$searchRes) {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
if (@ldap_count_entries(self::$ldapConn, $searchRes) === 1) {
$ldapSearchData = @ldap_get_entries(self::$ldapConn, $searchRes);
if (!$ldapSearchData) {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
SP_Common::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
$message['text'][] = _('RDN de grupo encontrado');
$message['text'][] = 'RDN: ' . $ldapSearchData[0]["dn"];
SP_Common::wrLogInfo($message);
return $ldapSearchData[0]["dn"];
} else {
$message['text'][] = _('Error al buscar RDN de grupo');
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
throw new Exception(_('Error al buscar RDN de grupo'));
}
}
/**
* @brief Bustar al usuario en un grupo
* @param string $userDN con el RDN del usuario
* @throws Exception
* @return bool
*/
public static function searchUserInGroup($userDN) {
public static function searchUserInGroup($userDN)
{
$message['action'] = __FUNCTION__;
self::$ldapGroup = SP_Config::getValue('ldapgroup');
if (!$groupDN = self::searchGroupDN()) {
return FALSE;
return false;
}
$filter = '(&(cn=' . $groupDN . ')(|(member=' . $userDN . ')(uniqueMember=' . $userDN . '))(|(objectClass=groupOfNames)(objectClass=groupOfUniqueNames)))';
@@ -334,7 +351,7 @@ class SP_LDAP {
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
throw new Exception(_('Error al buscar el grupo de usuarios'));
}
@@ -344,12 +361,11 @@ class SP_LDAP {
$message['text'][] = 'LDAP ERROR: ' . ldap_error(self::$ldapConn) . '(' . ldap_errno(self::$ldapConn) . ')';
$message['text'][] = 'LDAP FILTER: ' . $filter;
SP_Common::wrLogInfo($message);
SP_Log::wrLogInfo($message);
throw new Exception(_('No se encontró el grupo con ese nombre'));
}
return TRUE;
return true;
}
}

View File

@@ -1,80 +1,116 @@
<?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-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 manejar el registro de eventos
*/
class SP_Log {
class SP_Log
{
static $numRows;
/**
* @brief Obtener los eventos guardados
* @param int $start con el número de registro desde el que empezar
* @return array con el resultado de la consulta
*/
public static function getEvents($start){
$query = 'SELECT SQL_CALC_FOUND_ROWS log_id,'
. 'FROM_UNIXTIME(log_date) as date,'
. 'log_action,log_login,'
. 'log_description '
. 'FROM log '
. 'ORDER BY log_id DESC '
. 'LIMIT '.$start.', 50';
*/
public static function getEvents($start)
{
$query = 'SELECT SQL_CALC_FOUND_ROWS ' .
'log_id,' .
'FROM_UNIXTIME(log_date) as date,' .
'log_action,' .
'log_login,' .
'log_ipAddress,' .
'log_description ' .
'FROM log ' .
'ORDER BY log_id DESC ' .
'LIMIT ' . $start . ', 50';
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ( $queryRes === FALSE ){
return FALSE;
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === false) {
return false;
}
$numRows = DB::getResults("SELECT FOUND_ROWS() as numRows", __FUNCTION__);
self::$numRows = $numRows->numRows;
return $queryRes;
}
/**
* @brief Limpiar el registro de eventos
* @return bool con el resultado
*/
public static function clearEvents(){
*/
public static function clearEvents()
{
$query = 'TRUNCATE TABLE log';
$queryRes = DB::doQuery($query, __FUNCTION__);
if ( $queryRes === FALSE ){
return FALSE;
if ($queryRes === false) {
return false;
}
$message['action'] = _('Vaciar Eventos');
$message['text'][] = _('Vaciar registro de eventos.');
SP_Common::wrLogInfo($message);
return TRUE;
self::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Crear un nuevo registro en el registro de eventos
* @param array $message con el nombre de la accióm y el texto del mensaje
* @return bool
*/
public static function wrLogInfo($message)
{
if (SP_Config::getValue('logenabled', 0) === 0 || !is_array($message)) {
return false;
}
$login = (isset($_SESSION["ulogin"])) ? $_SESSION["ulogin"] : "-";
$userId = (isset($_SESSION['uid'])) ? $_SESSION['uid'] : 0;
$action = strip_tags(utf8_encode($message['action']));
$description = strip_tags(utf8_encode(implode(';;', $message['text'])));
$query = "INSERT INTO log SET " .
"log_date = UNIX_TIMESTAMP()," .
"log_login = '" . DB::escape($login) . "'," .
"log_userId = " . $userId . "," .
"log_ipAddress = '" . DB::escape($_SERVER['REMOTE_ADDR']) . "'," .
"log_action = '" . DB::escape($action) . "'," .
"log_description = '" . DB::escape($description) . "'";
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,13 +23,14 @@
* 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 perfiles de usuarios.
*/
class SP_Profiles {
class SP_Profiles
{
static $profileId;
static $profileName;
static $queryLastId;
@@ -39,7 +40,8 @@ class SP_Profiles {
* @param int $id con el Id del perfil a consultar
* @return array con el nombre de la columna como clave y los datos como valor
*/
public static function getProfileData($id = 0) {
public static function getProfileData($id = 0)
{
$profile = array('userprofile_id' => 0,
'userprofile_name' => '',
@@ -68,7 +70,7 @@ class SP_Profiles {
if ($usersProfiles) {
foreach ($usersProfiles[0] as $name => $value) {
if (preg_match('/^.*_p[A-Z].*$/', $name)) {
$profile[$name] = ( (int) $value === 1 ) ? "CHECKED" : "";
$profile[$name] = ((int)$value === 1) ? "CHECKED" : "";
} else {
$profile[$name] = $value;
}
@@ -86,266 +88,290 @@ class SP_Profiles {
* @param int $profileId opcional, con el Id del perfil a consultar
* @return array con la lista de perfiles
*/
public static function getProfiles($profileId = NULL) {
public static function getProfiles($profileId = NULL)
{
if (!is_null($profileId)) {
$query = 'SELECT userprofile_id,'
. 'userprofile_name,'
. 'userProfile_pView,'
. 'userProfile_pViewPass,'
. 'userProfile_pViewHistory,'
. 'userProfile_pEdit,'
. 'userProfile_pEditPass,'
. 'userProfile_pAdd,'
. 'userProfile_pDelete,'
. 'userProfile_pFiles,'
. 'userProfile_pConfig,'
. 'userProfile_pConfigMasterPass,'
. 'userProfile_pConfigBackup,'
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. 'userProfile_pUsers,'
. 'userProfile_pGroups,'
. 'userProfile_pProfiles,'
. 'userProfile_pEventlog '
. 'FROM usrProfiles '
. 'WHERE userprofile_id = ' . (int) $profileId . ' LIMIT 1';
. 'userprofile_name,'
. 'userProfile_pView,'
. 'userProfile_pViewPass,'
. 'userProfile_pViewHistory,'
. 'userProfile_pEdit,'
. 'userProfile_pEditPass,'
. 'userProfile_pAdd,'
. 'userProfile_pDelete,'
. 'userProfile_pFiles,'
. 'userProfile_pConfig,'
. 'userProfile_pConfigMasterPass,'
. 'userProfile_pConfigBackup,'
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. 'userProfile_pUsers,'
. 'userProfile_pGroups,'
. 'userProfile_pProfiles,'
. 'userProfile_pEventlog '
. 'FROM usrProfiles '
. 'WHERE userprofile_id = ' . (int)$profileId . ' LIMIT 1';
} else {
$query = 'SELECT userprofile_id,'
. 'userprofile_name '
. 'FROM usrProfiles '
. 'ORDER BY userprofile_name';
. 'userprofile_name '
. 'FROM usrProfiles '
. 'ORDER BY userprofile_name';
}
$queryRes = DB::getResults($query, __FUNCTION__, TRUE);
if ($queryRes === FALSE) {
return FALSE;
$queryRes = DB::getResults($query, __FUNCTION__, true);
if ($queryRes === false) {
return false;
}
return $queryRes;
}
/**
* @brief Comprobar si un perfil existe
* @return bool
*/
public static function checkProfileExist() {
$profileId = (int) strtoupper(self::$profileId);
public static function checkProfileExist()
{
$profileId = (int)strtoupper(self::$profileId);
$profileName = strtoupper(self::$profileName);
if ($profileId) {
$query = "SELECT userprofile_name "
. "FROM usrProfiles "
. "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "' "
. "AND userprofile_id != " . $profileId;
. "FROM usrProfiles "
. "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "' "
. "AND userprofile_id != " . $profileId;
} else {
$query = "SELECT userprofile_name "
. "FROM usrProfiles "
. "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "'";
. "FROM usrProfiles "
. "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "'";
}
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
if (count(DB::$last_result) >= 1) {
return FALSE;
return false;
}
return TRUE;
return true;
}
/**
* @brief Añadir un nuevo perfil
* @param array $profileProp con las propiedades del perfil
* @return bool
*/
public static function addProfile($profileProp = '') {
$enableConfig = (int) ( $profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$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) . "',"
. "userProfile_pView = " . $profileProp["pAccView"] . ","
. "userProfile_pViewPass = " . $profileProp["pAccViewPass"] . ","
. "userProfile_pViewHistory = " . $profileProp["pAccViewHistory"] . ","
. "userProfile_pEdit = " . $profileProp["pAccEdit"] . ","
. "userProfile_pEditPass = " . $profileProp["pAccEditPass"] . ","
. "userProfile_pAdd = " . $profileProp["pAccAdd"] . ","
. "userProfile_pDelete = " . $profileProp["pAccDel"] . ","
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "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"] . ","
. "userProfile_pEventlog = " . $profileProp["pEventlog"];
public static function addProfile($profileProp = NULL)
{
$enableConfig = (int)($profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$enableAppMgmt = (int)($profileProp["pAppMgmt"] || $profileProp["pAppMgmtCat"] || $profileProp["pAppMgmtCust"]);
$enableUsers = (int)($profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
$query = "INSERT INTO usrProfiles SET "
. "userprofile_name = '" . DB::escape(self::$profileName) . "',"
. "userProfile_pView = " . $profileProp["pAccView"] . ","
. "userProfile_pViewPass = " . $profileProp["pAccViewPass"] . ","
. "userProfile_pViewHistory = " . $profileProp["pAccViewHistory"] . ","
. "userProfile_pEdit = " . $profileProp["pAccEdit"] . ","
. "userProfile_pEditPass = " . $profileProp["pAccEditPass"] . ","
. "userProfile_pAdd = " . $profileProp["pAccAdd"] . ","
. "userProfile_pDelete = " . $profileProp["pAccDel"] . ","
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "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"] . ","
. "userProfile_pEventlog = " . $profileProp["pEventlog"];
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
return TRUE;
$message['action'] = _('Nuevo Perfil');
$message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . self::$profileName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Modificar un perfil
* @param array $profileProp con las propiedades del perfil
* @return bool
*/
public static function updateProfile($profileProp = '') {
$enableConfig = (int) ( $profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$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) . "',"
. "userProfile_pView = " . $profileProp["pAccView"] . ","
. "userProfile_pViewPass = " . $profileProp["pAccViewPass"] . ","
. "userProfile_pViewHistory = " . $profileProp["pAccViewHistory"] . ","
. "userProfile_pEdit = " . $profileProp["pAccEdit"] . ","
. "userProfile_pEditPass = " . $profileProp["pAccEditPass"] . ","
. "userProfile_pAdd = " . $profileProp["pAccAdd"] . ","
. "userProfile_pDelete = " . $profileProp["pAccDel"] . ","
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "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"] . ","
. "userProfile_pEventlog = " . $profileProp["pEventlog"] . " "
. "WHERE userprofile_id = " . (int) self::$profileId . " LIMIT 1";
public static function updateProfile($profileProp = NULL)
{
$enableConfig = (int)($profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]);
$enableAppMgmt = (int)($profileProp["pAppMgmt"] || $profileProp["pAppMgmtCat"] || $profileProp["pAppMgmtCust"]);
$enableUsers = (int)($profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]);
$profileName = self::getProfileNameById(self::$profileId);
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
$query = "UPDATE usrProfiles SET "
. "userprofile_name = '" . DB::escape(self::$profileName) . "',"
. "userProfile_pView = " . $profileProp["pAccView"] . ","
. "userProfile_pViewPass = " . $profileProp["pAccViewPass"] . ","
. "userProfile_pViewHistory = " . $profileProp["pAccViewHistory"] . ","
. "userProfile_pEdit = " . $profileProp["pAccEdit"] . ","
. "userProfile_pEditPass = " . $profileProp["pAccEditPass"] . ","
. "userProfile_pAdd = " . $profileProp["pAccAdd"] . ","
. "userProfile_pDelete = " . $profileProp["pAccDel"] . ","
. "userProfile_pFiles = " . $profileProp["pAccFiles"] . ","
. "userProfile_pConfigMenu = " . $enableConfig . ","
. "userProfile_pConfig = " . $profileProp["pConfig"] . ","
. "userProfile_pConfigMasterPass = " . $profileProp["pConfigMpw"] . ","
. "userProfile_pConfigBackup = " . $profileProp["pConfigBack"] . ","
. "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"] . ","
. "userProfile_pEventlog = " . $profileProp["pEventlog"] . " "
. "WHERE userprofile_id = " . (int)self::$profileId . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
return TRUE;
$message['action'] = _('Modificar Perfil');
$message['text'][] = SP_Html::strongText(_('Perfil') . ': ') . $profileName . ' > ' . self::$profileName;
SP_Log::wrLogInfo($message);
SP_Common::sendEmail($message);
return true;
}
/**
* @brief Eliminar un perfil
* @return bool
*/
public static function deleteProfile() {
public static function deleteProfile()
{
$query = "DELETE FROM usrProfiles "
. "WHERE userprofile_id = " . (int) self::$profileId . " LIMIT 1";
. "WHERE userprofile_id = " . (int)self::$profileId . " LIMIT 1";
if (DB::doQuery($query, __FUNCTION__) === FALSE) {
return FALSE;
if (DB::doQuery($query, __FUNCTION__) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
return TRUE;
return true;
}
/**
* @brief Comprobar si un perfil está en uso
* @return mixed string con el número de usuarios, o bool si no está en uso
*/
public static function checkProfileInUse() {
public static function checkProfileInUse()
{
$count['users'] = self::getProfileInUsers();
return $count;
}
/**
* @brief Obtener el número de usuarios que usan un perfil
* @return int con el número total de cuentas
*/
private static function getProfileInUsers() {
private static function getProfileInUsers()
{
$query = "SELECT COUNT(*) as uses "
. "FROM usrData "
. "WHERE user_profileId = " . (int) self::$profileId;
. "FROM usrData "
. "WHERE user_profileId = " . (int)self::$profileId;
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->uses;
}
/**
* @brief Obtener el nombre de un perfil por a partir del Id
* @param int $id con el Id del perfil
* @return string con el nombre del perfil
*/
public static function getProfileNameById($id) {
public static function getProfileNameById($id)
{
$query = "SELECT userprofile_name "
. "FROM usrProfiles "
. "WHERE userprofile_id = " . (int)$id . " LIMIT 1";
. "FROM usrProfiles "
. "WHERE userprofile_id = " . (int)$id . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes->userprofile_name;
}
/**
* @brief Obtener el perfil de un usuario
* @param int $userId opcional con el Id del usuario
* @return object con los permisos del perfil del usuario
*
* Si el usuario no es indicado, se obtiene el perfil del suuario de la sesión actual
*/
public static function getProfileForUser($userId = 0) {
/**
* @brief Obtener el perfil de un usuario
* @param int $userId opcional con el Id del usuario
* @return object con los permisos del perfil del usuario
*
* Si el usuario no es indicado, se obtiene el perfil del suuario de la sesión actual
*/
public static function getProfileForUser($userId = 0)
{
$userId = SP_Common::parseParams('s', 'uid', 0);
if ( ! $userId ){
return FALSE;
if (!$userId) {
return false;
}
$query = "SELECT user_profileId,"
. "userProfile_pView,"
. "userProfile_pViewPass,"
. "userProfile_pViewHistory,"
. "userProfile_pEdit,"
. "userProfile_pEditPass,"
. "userProfile_pAdd,"
. "userProfile_pDelete,"
. "userProfile_pFiles,"
. "userProfile_pConfigMenu,"
. "userProfile_pConfig,"
. "userProfile_pConfigMasterPass,"
. "userProfile_pConfigBackup,"
. "userProfile_pAppMgmtMenu,"
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. "userProfile_pUsersMenu,"
. "userProfile_pUsers,"
. "userProfile_pGroups,"
. "userProfile_pProfiles,"
. "userProfile_pEventlog "
. "FROM usrData "
. "JOIN usrProfiles ON userProfile_Id = user_profileId "
. "WHERE user_id = " . $userId . " LIMIT 1";
. "userProfile_pView,"
. "userProfile_pViewPass,"
. "userProfile_pViewHistory,"
. "userProfile_pEdit,"
. "userProfile_pEditPass,"
. "userProfile_pAdd,"
. "userProfile_pDelete,"
. "userProfile_pFiles,"
. "userProfile_pConfigMenu,"
. "userProfile_pConfig,"
. "userProfile_pConfigMasterPass,"
. "userProfile_pConfigBackup,"
. "userProfile_pAppMgmtMenu,"
. 'userProfile_pAppMgmtCategories,'
. 'userProfile_pAppMgmtCustomers,'
. "userProfile_pUsersMenu,"
. "userProfile_pUsers,"
. "userProfile_pGroups,"
. "userProfile_pProfiles,"
. "userProfile_pEventlog "
. "FROM usrData "
. "JOIN usrProfiles ON userProfile_Id = user_profileId "
. "WHERE user_id = " . $userId . " LIMIT 1";
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === FALSE) {
return FALSE;
if ($queryRes === false) {
return false;
}
return $queryRes;
}
}

View File

@@ -1,11 +1,11 @@
<?php
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -53,7 +53,7 @@ switch ($action) {
$title = array('class' => 'titleGreen', 'name' => _('Copiar Cuenta'));
$showform = true;
$nextaction = 'acccopy';
$accountUsers = $account->getUsersAccount();
$accountGroups = $account->getGroupsAccount();
$accountData = $account->getAccount();
@@ -63,7 +63,7 @@ switch ($action) {
$title = array('class' => 'titleOrange', 'name' => _('Editar Cuenta'));
$showform = true;
$nextaction = 'accedit';
$accountUsers = $account->getUsersAccount();
$accountGroups = $account->getGroupsAccount();
$accountData = $account->getAccount();
@@ -72,14 +72,14 @@ switch ($action) {
$savetype = 0;
$title = array('class' => 'titleRed', 'name' => _('Eliminar Cuenta'));
$showform = false;
$accountData = $account->getAccount();
break;
case "accview":
$savetype = 0;
$title = array('class' => 'titleNormal', 'name' => _('Detalles de Cuenta'));
$showform = false;
$_SESSION["accParentId"] = $data['id'];
$account->incrementViewCounter();
$accountUsers = $account->getUsersAccount();
@@ -90,8 +90,8 @@ switch ($action) {
$savetype = 0;
$title = array('class' => 'titleNormal', 'name' => _('Detalles de Cuenta'));
$showform = false;
$account->accountIsHistory = TRUE;
$account->accountIsHistory = true;
$accountGroups = $account->getGroupsAccount();
$accountData = $account->getAccountHistory();
break;
@@ -99,10 +99,10 @@ switch ($action) {
return;
}
if ( $data['id'] > 0) {
if ($data['id'] > 0) {
// Comprobar permisos de acceso
SP_ACL::checkAccountAccess($action, $account->getAccountDataForACL()) || SP_Html::showCommonError('noaccpermission');
$changesHash = $account->calcChangesHash();
$chkUserEdit = ($accountData->account_otherUserEdit) ? 'checked' : '';
$chkGroupEdit = ($accountData->account_otherGroupEdit) ? 'checked' : '';
@@ -128,388 +128,406 @@ $categoriesSelProp = array("name" => "categoryId",
"js" => "",
"attribs" => "");
$isModified = ( $accountData->account_dateEdit && $accountData->account_dateEdit <> '0000-00-00 00:00:00');
$showHistory = (($action == 'accview' || $action == 'accviewhistory' ) && SP_ACL::checkUserAccess("accviewhistory") && ($isModified || $action == 'accviewhistory'));
$isModified = ($accountData->account_dateEdit && $accountData->account_dateEdit <> '0000-00-00 00:00:00');
$showHistory = (($action == 'accview' || $action == 'accviewhistory') && SP_ACL::checkUserAccess("accviewhistory") && ($isModified || $action == 'accviewhistory'));
$showDetails = ($action == 'accview' || $action == 'accviewhistory' || $action == 'accdelete');
$showPass = ($action == "accnew" || $action == 'acccopy');
$showFiles = (($action == "accedit" || $action == "accview" || $action == "accviewhistory")
&& (SP_Config::getValue('filesenabled') == 1 && SP_ACL::checkUserAccess("accfiles")));
$showViewPass = (($action == "accview" || $action == "accviewhistory")
&& (SP_ACL::checkAccountAccess("accviewpass",$account->getAccountDataForACL()) && SP_ACL::checkUserAccess("accviewpass")));
$showSave = ($action == "accedit" || $action == "accnew" || $action == "acccopy");
&& (SP_Config::getValue('filesenabled') == 1 && SP_ACL::checkUserAccess("accfiles")));
$showViewPass = (($action == "accview" || $action == "accviewhistory")
&& (SP_ACL::checkAccountAccess("accviewpass", $account->getAccountDataForACL()) && SP_ACL::checkUserAccess("accviewpass")));
$showSave = ($action == "accedit" || $action == "accnew" || $action == "acccopy");
$showEdit = ($action == "accview"
&& SP_ACL::checkAccountAccess("accedit",$account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("accedit")
&& ! $account->accountIsHistory);
$showEditPass = ($action == "accedit"
&& SP_ACL::checkAccountAccess("acceditpass",$account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("acceditpass")
&& ! $account->accountIsHistory);
$showDelete = ($action == "accdelete"
&& SP_ACL::checkAccountAccess("accdelete", $account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("accdelete"));
$filesDelete = ( $action == 'accedit' ) ? 1 : 0;
$skey = SP_Common::getSessionKey(TRUE);
&& SP_ACL::checkAccountAccess("accedit", $account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("accedit")
&& !$account->accountIsHistory);
$showEditPass = ($action == "accedit"
&& SP_ACL::checkAccountAccess("acceditpass", $account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("acceditpass")
&& !$account->accountIsHistory);
$showDelete = ($action == "accdelete"
&& SP_ACL::checkAccountAccess("accdelete", $account->getAccountDataForACL())
&& SP_ACL::checkUserAccess("accdelete"));
$filesDelete = ($action == 'accedit') ? 1 : 0;
$skey = SP_Common::getSessionKey(true);
$maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
?>
<div id="title" class="midroundup <?php echo $title['class']; ?>"><?php echo $title['name']; ?></div>
<?php if ( $showform ): ?>
<form METHOD="post" name="frmaccount" id="frmAccount">
<?php if ($showform): ?>
<form METHOD="post" name="frmaccount" id="frmAccount">
<?php endif; ?>
<?php if ( $account->accountIsHistory ): ?>
<table class="data round tblIcon">
<?php if ($account->accountIsHistory): ?>
<table class="data round tblIcon">
<?php else: ?>
<table class="data round">
<table class="data round">
<?php endif; ?>
<tr>
<td class="descField"><?php echo _('Nombre'); ?></td>
<td class="valField">
<?php
if ( $showform ){
?>
<input name="name" type="text" placeholder="<?php echo _('Nombre de cuenta'); ?>" required maxlength="50" value="<?php echo ( $action != 'accnew' ) ? $accountData->account_name : ''; ?>">
<?php
} else{
echo $accountData->account_name;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Cliente'); ?></td>
<td class="valField">
<?php
if ( $showform ){
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'); ?>" />
<?php
} else{
echo $accountData->customer_name;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Categoría'); ?></td>
<td class="valField">
<?php
if ( $showform ){
SP_Html::printSelect(DB::getValuesForSelect('categories', 'category_id', 'category_name'), $categoriesSelProp);
} else{
echo $accountData->category_name;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('URL / IP'); ?></td>
<td class="valField">
<?php
if ( $showform ){
?>
<input name="url" type="text" placeholder="<?php echo _('URL o IP de acceso'); ?>" maxlength="255" value="<?php echo ( $action != 'accnew' ) ? $accountData->account_url : ''; ?>">
<?php
} else{
echo $accountData->account_url;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Usuario'); ?></td>
<td class="valField">
<?php
if ( $showform ){
?>
<input name="login" type="text" placeholder="<?php echo _('Usuario de acceso'); ?>" maxlength="50" value="<?php echo ( $action != 'accnew' ) ? $accountData->account_login : ''; ?>">
<?php
} else{
echo $accountData->account_login;
}
?>
</td>
</tr>
<?php if ( $showPass ): ?>
<tr>
<td class="descField"><?php echo _('Clave'); ?></td>
<td class="descField"><?php echo _('Nombre'); ?></td>
<td class="valField">
<input name="password" type="password" id="txtPass" maxlength="255" OnKeyUp="checkPassLevel(this.value)">
<img src="imgs/user-pass.png" title="<?php echo _('La clave generada se mostrará aquí'); ?>" class="inputImg" id="viewPass" />
&nbsp;&nbsp;
<img src="imgs/genpass.png" title="<?php echo _('Generar clave aleatoria'); ?>" class="inputImg" OnClick="password(11, true, true);" />
<?php
if ($showform) {
?>
<input name="name" type="text" placeholder="<?php echo _('Nombre de cuenta'); ?>" required
maxlength="50"
value="<?php echo ($action != 'accnew') ? $accountData->account_name : ''; ?>">
<?php
} else {
echo $accountData->account_name;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Clave (repetir)'); ?></td>
<td class="descField"><?php echo _('Cliente'); ?></td>
<td class="valField">
<input name="password2" type="password" maxlength="255">
<span id="passLevel" title="<?php echo _('Nivel de fortaleza de la clave'); ?>" ></span>
<?php
if ($showform) {
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'); ?>"/>
<?php
} else {
echo $accountData->customer_name;
}
?>
</td>
</tr>
<?php endif; ?>
<tr>
<td class="descField"><?php echo _('Notas'); ?></td>
<td class="valField">
<textarea name="notice" cols="30" rows="5" placeholder="<?php echo _('Notas sobre la cuenta'); ?>" maxlength="1000" <?php echo ( ! $showform ) ? 'READONLY' : ''; ?> ><?php echo ( $action != 'accnew' ) ? $accountData->account_notes : ''; ?></textarea>
</td>
</tr>
<?php if ( $showform ): ?>
<tr>
<td class="descField"><?php echo _('Permisos'); ?></td>
<td class="valField">
<div class="account-permissions">
<fieldset class="round5">
<legend><?php echo _('Usuarios'); ?></legend>
<select id="selUsers" name="otherusers[]" multiple="multiple">
<?php
if ( $action != 'accnew' ){
$users = array_flip(DB::getValuesForSelect('usrData', 'user_id', 'user_name'));
foreach ( $users as $otherUserName => $otherUserId) {
$userSelected = '';
if ($otherUserId != $accountData->account_userGroupId) {
if ( isset($accountUsers) && is_array($accountUsers)){
$userSelected = ( in_array($otherUserId, $accountUsers)) ? "selected" : "";
}
echo "<option value='" . $otherUserId . "' $userSelected>" . $otherUserName . "</option>";
}
}
}
<tr>
<td class="descField"><?php echo _('Categoría'); ?></td>
<td class="valField">
<?php
if ($showform) {
SP_Html::printSelect(DB::getValuesForSelect('categories', 'category_id', 'category_name'), $categoriesSelProp);
} else {
echo $accountData->category_name;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('URL / IP'); ?></td>
<td class="valField">
<?php
if ($showform) {
?>
</select>
<br><br>
<span><?php echo _('Hablitar edición'); ?></span>
<label for="ueditenabled"><?php echo ($chkUserEdit) ? _('SI') : _('NO'); ?></label>
<input type="checkbox" name="ueditenabled" id="ueditenabled" class="checkbox" <?php echo $chkUserEdit; ?> />
</fieldset>
</div>
<div class="account-permissions">
<fieldset class="round5">
<legend><?php echo _('Grupos'); ?></legend>
<select id="selGroups" name="othergroups[]" multiple="multiple">
<?php
if ( $action != 'accnew' ){
$groups = array_flip(DB::getValuesForSelect('usrGroups', 'usergroup_id', 'usergroup_name'));
foreach ($groups as $groupName => $groupId) {
$uGroupSelected = '';
if ($groupId != $accountData->account_userGroupId) {
if ( isset($accountGroups) && is_array($accountGroups)){
$uGroupSelected = ( in_array($groupId, $accountGroups)) ? "selected" : "";
}
echo "<option value='" . $groupId . "' $uGroupSelected>" . $groupName . "</option>";
}
}
}
<input name="url" type="text" placeholder="<?php echo _('URL o IP de acceso'); ?>"
maxlength="255"
value="<?php echo ($action != 'accnew') ? $accountData->account_url : ''; ?>">
<?php
} else {
echo $accountData->account_url;
}
?>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Usuario'); ?></td>
<td class="valField">
<?php
if ($showform) {
?>
</select>
<br><br>
<span><?php echo _('Hablitar edición'); ?></span>
<label for="geditenabled"><?php echo ($chkGroupEdit) ? _('SI') : _('NO'); ?></label>
<input type="checkbox" name="geditenabled" id="geditenabled" class="checkbox" <?php echo $chkGroupEdit; ?> />
</fieldset>
</div>
</td>
</tr>
<?php endif; ?>
<?php if ( $showform ): ?>
<input type="hidden" name="hash" value="<?php echo $changesHash; ?>">
<input type="hidden" name="next" value="<?php echo $nextaction; ?>">
<input type="hidden" name="savetyp" value="<?php echo $savetype; ?>">
<input type="hidden" name="accountid" value="<?php echo $account->accountId; ?>" />
<input type="hidden" name="sk" value="<?php echo $skey; ?>">
<input type="hidden" name="is_ajax" value="1">
<input name="login" type="text" placeholder="<?php echo _('Usuario de acceso'); ?>"
maxlength="50"
value="<?php echo ($action != 'accnew') ? $accountData->account_login : ''; ?>">
<?php
} else {
echo $accountData->account_login;
}
?>
</td>
</tr>
<?php if ($showPass): ?>
<tr>
<td class="descField"><?php echo _('Clave'); ?></td>
<td class="valField">
<input name="password" type="password" id="txtPass" maxlength="255"
OnKeyUp="checkPassLevel(this.value)">
<img src="imgs/user-pass.png" title="<?php echo _('La clave generada se mostrará aquí'); ?>"
class="inputImg" id="viewPass"/>
&nbsp;&nbsp;
<img src="imgs/genpass.png" title="<?php echo _('Generar clave aleatoria'); ?>" class="inputImg"
OnClick="password(11, true, true);"/>
</td>
</tr>
<tr>
<td class="descField"><?php echo _('Clave (repetir)'); ?></td>
<td class="valField">
<input name="password2" type="password" maxlength="255">
<span id="passLevel" title="<?php echo _('Nivel de fortaleza de la clave'); ?>"></span>
</td>
</tr>
<?php endif; ?>
<tr>
<td class="descField"><?php echo _('Notas'); ?></td>
<td class="valField">
<textarea name="notice" cols="30" rows="5" placeholder="<?php echo _('Notas sobre la cuenta'); ?>"
maxlength="1000" <?php echo (!$showform) ? 'READONLY' : ''; ?> ><?php echo ($action != 'accnew') ? $accountData->account_notes : ''; ?></textarea>
</td>
</tr>
<?php if ($showform): ?>
<tr>
<td class="descField"><?php echo _('Permisos'); ?></td>
<td class="valField">
<div class="account-permissions">
<fieldset class="round5">
<legend><?php echo _('Usuarios'); ?></legend>
<select id="selUsers" name="otherusers[]" multiple="multiple">
<?php
$users = array_flip(DB::getValuesForSelect('usrData', 'user_id', 'user_name'));
foreach ($users as $otherUserName => $otherUserId) {
$userSelected = '';
if ($otherUserId != $accountData->account_userGroupId) {
if (isset($accountUsers) && is_array($accountUsers)) {
$userSelected = (in_array($otherUserId, $accountUsers)) ? "selected" : "";
}
echo "<option value='" . $otherUserId . "' $userSelected>" . $otherUserName . "</option>";
}
}
?>
</select>
<br><br>
<span><?php echo _('Hablitar edición'); ?></span>
<label for="ueditenabled"><?php echo ($chkUserEdit) ? _('SI') : _('NO'); ?></label>
<input type="checkbox" name="ueditenabled" id="ueditenabled"
class="checkbox" <?php echo $chkUserEdit; ?> />
</fieldset>
</div>
<div class="account-permissions">
<fieldset class="round5">
<legend><?php echo _('Grupos'); ?></legend>
<select id="selGroups" name="othergroups[]" multiple="multiple">
<?php
$groups = array_flip(DB::getValuesForSelect('usrGroups', 'usergroup_id', 'usergroup_name'));
foreach ($groups as $groupName => $groupId) {
$uGroupSelected = '';
if ($groupId != $accountData->account_userGroupId) {
if (isset($accountGroups) && is_array($accountGroups)) {
$uGroupSelected = (in_array($groupId, $accountGroups)) ? "selected" : "";
}
echo "<option value='" . $groupId . "' $uGroupSelected>" . $groupName . "</option>";
}
}
?>
</select>
<br><br>
<span><?php echo _('Hablitar edición'); ?></span>
<label for="geditenabled"><?php echo ($chkGroupEdit) ? _('SI') : _('NO'); ?></label>
<input type="checkbox" name="geditenabled" id="geditenabled"
class="checkbox" <?php echo $chkGroupEdit; ?> />
</fieldset>
</div>
</td>
</tr>
<?php endif; ?>
<?php if ($showform): ?>
<input type="hidden" name="hash" value="<?php echo $changesHash; ?>">
<input type="hidden" name="next" value="<?php echo $nextaction; ?>">
<input type="hidden" name="savetyp" value="<?php echo $savetype; ?>">
<input type="hidden" name="accountid" value="<?php echo $account->accountId; ?>"/>
<input type="hidden" name="sk" value="<?php echo $skey; ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<?php endif; ?>
<?php endif; ?>
<!--Files boxes-->
<?php if ( $showFiles ): ?>
<tr>
<td class="descField"><?php echo _('Archivos'); ?></td>
<td class="valField">
<div id="downFiles"></div>
<?php if ( $account->accountIsHistory ): ?>
<script>getFiles(<?php echo $account->accountParentId; ?>, <?php echo $filesDelete; ?>, '<?php echo $skey; ?>');</script>
<?php else: ?>
<script>getFiles(<?php echo $account->accountId; ?>, <?php echo $filesDelete; ?>, '<?php echo $skey; ?>'); </script>
<?php if ( $action == "accedit" ): ?>
<form method="post" enctypr="multipart/form-data" name="upload_form" id="fileUpload">
<input type="file" id="inFile" name="inFile" />
</form>
<div id="dropzone" class="round" data-files-ext="<?php echo SP_Config::getValue('allowed_exts'); ?>" title="<?php echo _('Soltar archivos aquí (max. 5) o click para seleccionar').'<br><br>'._('Tamaño máximo de archivo').' '.$maxFileSize.' MB'; ?>">
<img src="imgs/upload.png" alt="upload" class="opacity50"/>
</div>
<script> dropFile(<?php echo $account->accountId; ?>, '<?php echo $skey; ?>', <?php echo $maxFileSize; ?>); </script>
<?php endif; ?>
<?php endif; ?>
</td>
</tr>
<?php endif; ?>
<?php if ($showFiles): ?>
<tr>
<td class="descField"><?php echo _('Archivos'); ?></td>
<td class="valField">
<div id="downFiles"></div>
<?php if ($account->accountIsHistory): ?>
<script>getFiles(<?php echo $account->accountParentId; ?>, <?php echo $filesDelete; ?>, '<?php echo $skey; ?>');</script>
<?php else: ?>
<script>getFiles(<?php echo $account->accountId; ?>, <?php echo $filesDelete; ?>, '<?php echo $skey; ?>'); </script>
<?php if ($action == "accedit"): ?>
<form method="post" enctypr="multipart/form-data" name="upload_form" id="fileUpload">
<input type="file" id="inFile" name="inFile"/>
</form>
<div id="dropzone" class="round" data-files-ext="<?php echo SP_Config::getValue('allowed_exts'); ?>"
title="<?php echo _('Soltar archivos aquí (max. 5) o click para seleccionar') . '<br><br>' . _('Tamaño máximo de archivo') . ' ' . $maxFileSize . ' MB'; ?>">
<img src="imgs/upload.png" alt="upload" class="opacity50"/>
</div>
<script> dropFile(<?php echo $account->accountId; ?>, '<?php echo $skey; ?>', <?php echo $maxFileSize; ?>); </script>
<?php endif; ?>
<?php endif; ?>
</td>
</tr>
<?php endif; ?>
<?php if ( $showHistory ): ?>
<tr>
<td class="descField"><?php echo _('Historial'); ?></td>
<td class="valField">
<?php
$arrSelectProp = array ( "name" => "historyId",
"id" => "sel-history",
"class" => "",
"size" => 1,
"label" => "",
"selected" => ( $account->accountIsHistory ) ? $account->accountId : "",
"default" => "",
"js" => "OnChange=\"if ( $('#sel-history').val() > 0 ) doAction('accviewhistory','accview', $('#sel-history').val());\"",
"attribs" => '');
<?php if ($showHistory): ?>
<tr>
<td class="descField"><?php echo _('Historial'); ?></td>
<td class="valField">
<?php
$arrSelectProp = array("name" => "historyId",
"id" => "sel-history",
"class" => "",
"size" => 1,
"label" => "",
"selected" => ($account->accountIsHistory) ? $account->accountId : "",
"default" => "",
"js" => "OnChange=\"if ( $('#sel-history').val() > 0 ) doAction('accviewhistory','accview', $('#sel-history').val());\"",
"attribs" => '');
SP_Html::printSelect($account->getAccountHistoryList(), $arrSelectProp);
?>
<script>$("#sel-history").chosen({disable_search : true, placeholder_text_single: "<?php echo _('Seleccionar fecha'); ?>"});</script>
</td>
SP_Html::printSelect($account->getAccountHistoryList(), $arrSelectProp);
?>
<script>$("#sel-history").chosen({disable_search: true, placeholder_text_single: "<?php echo _('Seleccionar fecha'); ?>"});</script>
</td>
</tr>
<?php endif; ?>
<?php if ($action == "accedit"): ?>
<tr>
<td class="descField"><?php echo _('Última Modificación'); ?></td>
<?php if ($accountData->user_editName): ?>
<td class="valField"><?php echo $accountData->account_dateEdit; ?> <?php echo _('por'); ?> <?php echo $accountData->user_editName; ?></td>
<?php endif; ?>
</tr>
<?php endif; ?>
</table>
<!--More info about account details-->
<?php if ($showDetails): ?>
<table class="data round extra-info">
<tr>
<td class="descField"><?php echo _('Visitas'); ?></td>
<td class="valField"><?php echo $accountData->account_countView . "(" . $accountData->account_countDecrypt . ")"; ?></td>
</tr>
<?php endif; ?>
<?php if ( $action == "accedit"): ?>
<tr>
<td class="descField"><?php echo _('Fecha Alta'); ?></td>
<td class="valField"><?php echo $accountData->account_dateAdd ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Creador'); ?></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>
<td class="valField"><?php echo $accountData->usergroup_name; ?></td>
</tr>
<?php if (count($accountUsers) > 0): ?>
<tr>
<td class="descField"><?php echo _('Última Modificación'); ?></td>
<?php if ($accountData->user_editName): ?>
<td class="valField"><?php echo $accountData->account_dateEdit; ?> <?php echo _('por'); ?> <?php echo $accountData->user_editName; ?></td>
<?php endif; ?>
<td class="descField"><?php echo _('Usuarios Secundarios'); ?></td>
<td class="valField">
<?php
$users = SP_Users::getUsersNameForAccount($account->accountId);
foreach ($users as $userId => $userName) {
if ($userId != $accountData->account_userId) {
if (in_array($userId, $accountUsers)) {
$accUsers[] = $userName;
}
}
}
$usersEdit = ($accountData->account_otherUserEdit) ? '(+)' : '';
echo $usersEdit . ' ' . implode(" | ", $accUsers);
?>
</td>
</tr>
<?php endif; ?>
<?php if (count($accountGroups) > 0): ?>
<tr>
<td class="descField"><?php echo _('Grupos Secundarios'); ?></td>
<td class="valField">
<?php
$groups = SP_Groups::getGroupsNameForAccount($accountData->account_id);
foreach ($groups as $groupId => $groupName) {
if ($groupId != $accountData->account_userGroupId) {
if (in_array($groupId, $accountGroups)) {
$accGroups[] = $groupName;
}
}
}
$groupsEdit = ($accountData->account_otherGroupEdit) ? '(+)' : '';
echo $groupsEdit . ' ' . implode(" | ", $accGroups);
?>
</td>
</tr>
<?php endif; ?>
<?php if ($isModified): ?>
<tr>
<td class="descField"><?php echo _('Fecha Edición'); ?></td>
<td class="valField"><?php echo $accountData->account_dateEdit; ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Editor'); ?></td>
<td class="valField"><?php echo ($accountData->user_editName) ? $accountData->user_editName : _('N/D'); ?></td>
</tr>
<?php endif; ?>
</table>
<!--More info about account details-->
<?php if ( $showDetails ): ?>
<table class="data round extra-info">
<tr>
<td class="descField"><?php echo _('Visitas'); ?></td>
<td class="valField"><?php echo $accountData->account_countView."(".$accountData->account_countDecrypt.")"; ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Fecha Alta'); ?></td>
<td class="valField"><?php echo $accountData->account_dateAdd ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Creador'); ?></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>
<td class="valField"><?php echo $accountData->usergroup_name; ?></td>
</tr>
<?php if ( count($accountUsers) > 0 ): ?>
<tr>
<td class="descField"><?php echo _('Usuarios Secundarios'); ?></td>
<td class="valField">
<?php
$users = SP_Users::getUsersNameForAccount($account->accountId);
foreach ( $users as $userId => $userName ){
if ( $userId != $accountData->account_userId ){
if ( in_array($userId, $accountUsers)){
$accUsers[] = $userName;
}
}
}
$usersEdit = ($accountData->account_otherUserEdit) ? '(+)' : '';
echo $usersEdit.' '.implode(" | ",$accUsers);
?>
</td>
</tr>
<?php endif; ?>
<?php if ( count($accountGroups) > 0 ): ?>
<tr>
<td class="descField"><?php echo _('Grupos Secundarios'); ?></td>
<td class="valField">
<?php
$groups = SP_Groups::getGroupsNameForAccount($accountData->account_id);
foreach ( $groups as $groupId => $groupName ){
if ( $groupId != $accountData->account_userGroupId ){
if ( in_array($groupId, $accountGroups)){
$accGroups[] = $groupName;
}
}
}
$groupsEdit = ($accountData->account_otherGroupEdit) ? '(+)' : '';
echo $groupsEdit.' '.implode(" | ",$accGroups);
?>
</td>
</tr>
<?php endif; ?>
<?php if ( $isModified ): ?>
<tr>
<td class="descField"><?php echo _('Fecha Edición'); ?></td>
<td class="valField"><?php echo $accountData->account_dateEdit; ?></td>
</tr>
<tr>
<td class="descField"><?php echo _('Editor'); ?></td>
<td class="valField"><?php echo ($accountData->user_editName) ? $accountData->user_editName : _('N/D'); ?></td>
</tr>
<?php endif; ?>
</table>
<?php endif; ?>
<?php endif; ?>
<div class="action">
<ul>
<li>
<?php if ( $account->accountIsHistory ): ?>
<img SRC="imgs/back.png" title="<?php echo _('Ver Actual'); ?>" class="inputImg" id="btnBack" OnClick="doAction('accview','accsearch',<?php echo $account->accountParentId; ?>)" />
<?php if ($account->accountIsHistory): ?>
<img SRC="imgs/back.png" title="<?php echo _('Ver Actual'); ?>" class="inputImg" id="btnBack"
OnClick="doAction('accview','accsearch',<?php echo $account->accountParentId; ?>)"/>
<?php else: ?>
<img src="imgs/back.png" title="<?php echo _('Atrás'); ?>" class="inputImg" id="btnBack" OnClick="doAction('<?php echo $account->lastAction; ?>', '<?php echo $action; ?>',<?php echo $account->accountId; ?>)" />
<img src="imgs/back.png" title="<?php echo _('Atrás'); ?>" class="inputImg" id="btnBack"
OnClick="doAction('<?php echo $account->lastAction; ?>', '<?php echo $action; ?>',<?php echo $account->accountId; ?>)"/>
<?php endif; ?>
</li>
<?php if ( $showViewPass ): ?>
<?php if ($showViewPass): ?>
<li>
<img src="imgs/user-pass.png" title="<?php echo _('Ver clave'); ?>" onClick="viewPass(<?php echo $account->accountId; ?>,1,<?php echo $account->accountIsHistory; ?>)" class="inputImg" />
<img src="imgs/user-pass.png" title="<?php echo _('Ver clave'); ?>"
onClick="viewPass(<?php echo $account->accountId; ?>,1,<?php echo $account->accountIsHistory; ?>)"
class="inputImg"/>
</li>
<?php endif; ?>
<?php if ( $showSave ): ?>
<?php if ($showSave): ?>
<li>
<img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" id="btnSave" OnClick="saveAccount('frmAccount');" />
<img src="imgs/check.png" title="<?php echo _('Guardar'); ?>" class="inputImg" id="btnSave"
OnClick="saveAccount('frmAccount');"/>
</li>
<?php endif; ?>
<?php if ( $showEditPass ): ?>
<?php if ($showEditPass): ?>
<li>
<img src="imgs/key.png" title="<?php echo _('Modificar Clave de Cuenta'); ?>" class="inputImg" OnClick="doAction('acceditpass', '<?php echo $action; ?>',<?php echo $account->accountId; ?>)"/>
<img src="imgs/key.png" title="<?php echo _('Modificar Clave de Cuenta'); ?>" class="inputImg"
OnClick="doAction('acceditpass', '<?php echo $action; ?>',<?php echo $account->accountId; ?>)"/>
</li>
<?php endif; ?>
<?php if ( $showEdit ): ?>
<?php if ($showEdit): ?>
<li>
<img src="imgs/edit.png" title="<?php echo _('Modificar Cuenta'); ?>" class="inputImg" OnClick="doAction('accedit','accview',<?php echo $account->accountId; ?>)" />
<img src="imgs/edit.png" title="<?php echo _('Modificar Cuenta'); ?>" class="inputImg"
OnClick="doAction('accedit','accview',<?php echo $account->accountId; ?>)"/>
</li>
<?php elseif ( ! $showEdit && $action == 'accview' && SP_Config::getValue('mailrequestsenabled', FALSE) ): ?>
<?php elseif (!$showEdit && $action == 'accview' && SP_Config::getValue('mailrequestsenabled', false)): ?>
<li>
<img src="imgs/request.png" title="<?php echo _('Solicitar Modificación'); ?>" class="inputImg" OnClick="doAction('accrequest','accview',<?php echo $account->accountId; ?>)" />
<img src="imgs/request.png" title="<?php echo _('Solicitar Modificación'); ?>" class="inputImg"
OnClick="doAction('accrequest','accview',<?php echo $account->accountId; ?>)"/>
</li>
<?php endif; ?>
<?php if ( $showDelete ): ?>
<?php if ($showDelete): ?>
<li>
<img src="imgs/delete.png" title="<?php echo _('Eliminar Cuenta'); ?>" class="inputImg" OnClick="delAccount(<?php echo $account->accountId; ?>,3,'<?php echo $skey; ?>');" />
<img src="imgs/delete.png" title="<?php echo _('Eliminar Cuenta'); ?>" class="inputImg"
OnClick="delAccount(<?php echo $account->accountId; ?>,3,'<?php echo $skey; ?>');"/>
</li>
<?php endif; ?>
</ul>
</div>
<?php if ( $showform ): ?>
<?php if ($showform): ?>
<script>
$("#selCustomer").chosen({
placeholder_text_single: "<?php echo _('Seleccionar Cliente'); ?>",
placeholder_text_single: "<?php echo _('Seleccionar Cliente'); ?>",
disable_search_threshold: 10,
no_results_text: "<?php echo _('Sin resultados'); ?>"
});
@@ -519,21 +537,21 @@ $maxFileSize = round(SP_Config::getValue('allowed_size') / 1024, 1);
no_results_text: "<?php echo _('Sin resultados'); ?>"
});
$("#selGroups").chosen({
placeholder_text_multiple: "<?php echo _('Seleccionar grupos secundarios'); ?>",
placeholder_text_multiple: "<?php echo _('Seleccionar grupos secundarios'); ?>"
});
$("#selUsers").chosen({
placeholder_text_multiple: "<?php echo _('Seleccionar usuarios'); ?>",
placeholder_text_multiple: "<?php echo _('Seleccionar usuarios'); ?>"
});
$('input:text:visible:first').focus();
$('.checkbox').button();
$('.ui-button').click(function(){
$('.ui-button').click(function () {
// El cambio de clase se produce durante el evento de click
// Si tiene la clase significa que el estado anterior era ON y ahora es OFF
if ( $(this).hasClass('ui-state-active') ){
if ($(this).hasClass('ui-state-active')) {
$(this).children().html('<?php echo _('NO'); ?>');
} else{
} else {
$(this).children().html('<?php echo _('SI'); ?>');
}
});
</script>
<?php endif; ?>
<?php endif; ?>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,7 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$action = $data['action'];
$activeTab = $data['active'];
$activeTab = $data['activeTab'];
SP_ACL::checkUserAccess($action) || SP_Html::showCommonError('unavailable');
@@ -66,10 +66,11 @@ $lastBackupTime = ( file_exists($backupFile['absolute']) ) ? _('Último backup')
</table>
<form method="post" name="frmBackup" id="frmBackup">
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="backup" value="1" />
<input type="hidden" name="isAjax" value="1" />
<input type="hidden" name="action" value="backup" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
</form>
<div class="action">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2014 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$category = SP_Category::getCategoryData($data['itemid']);
$activeTab = $data['active'];
$onCloseAction = $data['onCloseAction'];
$activeTab = $data['activeTab'];
?>
<div id="fancyContainer" align="center">
@@ -49,13 +50,13 @@ $activeTab = $data['active'];
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<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">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true) ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,14 +26,16 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$action = $data['action'];
$activeTab = $data['active'];
$activeTab = $data['activeTab'];
$onCloseAction = $data['onCloseAction'];
SP_ACL::checkUserAccess($action) || SP_Html::showCommonError('unavailable');
$arrLangAvailable = array('es_ES','en_US');
$isDemoMode = SP_Config::getValue('demoenabled',0);
$arrLangAvailable = array('Español' => 'es_ES','English' => 'en_US');
$arrAccountCount = array(6,9,12,15,21,27,30,51,99);
$mailSecurity = array('SSL','TLS');
$isDemoMode = SP_Config::getValue('demoenabled',0);
$txtDisabled = ( $isDemoMode ) ? "DISABLED" : "";
$chkLog = ( SP_Config::getValue('logenabled') ) ? 'checked="checked"' : '';
@@ -63,9 +65,9 @@ $allowedExts = SP_Config::getValue('allowed_exts');
<td class="valField">
<select name="sitelang" id="sel-sitelang" size="1">
<?php
foreach ( $arrLangAvailable as $langOption ){
$selected = ( SP_Config::getValue('sitelang') == $langOption ) ? "SELECTED" : "";
echo "<option $selected>$langOption</option>";
foreach ( $arrLangAvailable as $langName => $langValue ){
$selected = ( SP_Config::getValue('sitelang') == $langValue ) ? "SELECTED" : "";
echo "<option value='$langValue' $selected>$langName</option>";
}
?>
</select>
@@ -330,7 +332,47 @@ $allowedExts = SP_Config::getValue('allowed_exts');
<?php echo _('Servidor'); ?>
</td>
<td class="valField">
<input type="text" name="mailserver" size="20" value="<?php echo SP_Config::getValue('mailserver'); ?>" maxlength="128" />
<input type="text" name="mailserver" size="20" value="<?php echo SP_Config::getValue('mailserver','localhost'); ?>" maxlength="128" />
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Puerto'); ?>
</td>
<td class="valField">
<input type="text" name="mailport" size="20" value="<?php echo SP_Config::getValue('mailport',25); ?>" maxlength="5" />
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Usuario'); ?>
</td>
<td class="valField">
<input type="text" name="mailuser" size="20" value="<?php echo SP_Config::getValue('mailuser'); ?>" maxlength="50" />
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Clave'); ?>
</td>
<td class="valField">
<input type="password" name="mailpass" size="20" value="<?php echo SP_Config::getValue('mailpass'); ?>" maxlength="50" />
</td>
</tr>
<tr>
<td class="descField">
<?php echo _('Seguridad'); ?>
</td>
<td class="valField">
<select name="mailsecurity" id="sel-mailsecurity" size="1">
<option></option>
<?php
foreach ( $mailSecurity as $security ){
$selected = ( SP_Config::getValue('mailsecurity') == $security ) ? "SELECTED" : "";
echo "<option $selected>$security</option>";
}
?>
</select>
</td>
</tr>
<tr>
@@ -357,10 +399,11 @@ $allowedExts = SP_Config::getValue('allowed_exts');
<input type="hidden" name="filesenabled" value="1" />
<input type="hidden" name="wikienabled" value="1" />
<?php endif; ?>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="action" value="config" />
<input type="hidden" name="is_ajax" value="1" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="isAjax" value="1" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
</form>
<div class="action">
@@ -372,11 +415,9 @@ $allowedExts = SP_Config::getValue('allowed_exts');
</div>
<script>
$("#sel-sitelang").chosen({disable_search : true});
$("#sel-account_link").chosen({disable_search : true});
$("#sel-account_count").chosen({disable_search : true});
$('#frmConfig .checkbox').button();
$('#frmConfig .ui-button').click(function(){
$("#sel-sitelang,#sel-account_link,#sel-account_count,#sel-mailsecurity").chosen({disable_search : true});
$('#frmConfig').find('.checkbox').button();
$('#frmConfig').find('.ui-button').click(function(){
// El cambio de clase se produce durante el evento de click
// Si tiene la clase significa que el estado anterior era ON y ahora es OFF
if ( $(this).hasClass('ui-state-active') ){

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$customer = SP_Customer::getCustomerData($data['itemid']);
$activeTab = $data['active'];
$onCloseAction = $data['onCloseAction'];
$activeTab = $data['activeTab'];
?>
<div id="fancyContainer" align="center">
@@ -49,13 +50,13 @@ $activeTab = $data['active'];
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<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">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true) ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -68,8 +68,8 @@ $accountData= $account->getAccount();
</table>
<input type="hidden" name="savetyp" value="4" />
<input type="hidden" name="accountid" value="<?php echo $account->accountId; ?>" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="is_ajax" value="1">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<div class="action">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -25,7 +25,7 @@
?>
<div id="error" align="center">
<div id="actions" align="center">
<?php if ( isset($data['showlogo']) ): ?>
<div id="logo">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -61,6 +61,9 @@ $numRows = SP_Log::$numRows;
<th>
<?php echo _('Usuario'); ?>
</th>
<th>
<?php echo _('IP'); ?>
</th>
<th class="cell-description">
<?php echo _('Descripción'); ?>
</th>
@@ -86,6 +89,9 @@ $numRows = SP_Log::$numRows;
<td class="cell">
<?php echo strtoupper($log->log_login); ?>
</td>
<td class="cell">
<?php echo $log->log_ipAddress; ?>
</td>
<td class="cell-description">
<?php
$descriptions = explode(';;', $description);
@@ -97,7 +103,7 @@ $numRows = SP_Log::$numRows;
}
if (strlen($text) >= 150) {
echo wordwrap($text, 150, '<br>', TRUE);
echo wordwrap($text, 150, '<br>', true);
} else {
echo $text . '<br>';
}

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$group = SP_Groups::getGroupData($data['itemid']);
$activeTab = $data['active'];
$onCloseAction = $data['onCloseAction'];
$activeTab = $data['activeTab'];
?>
<div id="fancyContainer" align="center">
@@ -49,12 +50,13 @@ $activeTab = $data['active'];
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="id" value="<?php echo $group["usergroup_id"]; ?>" />
<input type="hidden" name="action" value="<?php echo $group["action"] ?>" />
<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">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true) ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<div id="resCheck"><span id="resFancyAccion"></span></div>
<div class="action-in-box">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -32,13 +32,13 @@ if (isset($_POST['install']) AND $_POST['install'] == 'true') {
if (count($resInstall) == 0) {
$resInstall[] = array('type' => 'ok',
'description' => _('Instalación finalizada'),
'hint' => 'Pulse <a href="index.php" title="Acceder"> aquí</a> para acceder');
'hint' => _('Pulse <a href="index.php" title="Acceder">aquí</a> para acceder'));
$isCompleted = 1;
}
}
?>
<div id="install" align="center">
<div id="actions" align="center">
<div id="logo">
<img src="imgs/logo_full.png" alt="sysPass logo"/>
<span ID="pageDesc"><?php echo _('Instalación ') . ' ' . SP_Util::getVersionString(); ?></span>

View File

@@ -42,7 +42,7 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
<?php endif; ?>
<input type="image" id="btnLogin" src="imgs/login.png" title="<?php echo _('Acceder') ?>"/>
<input type="hidden" name="login" value="1" />
<input type="hidden" name="is_ajax" value="1" />
<input type="hidden" name="isAjax" value="1" />
<?php if ( count($_GET) > 0 ): ?>
<?php foreach( $_GET as $param => $value ): ?>
<input type="hidden" name="g_<?php echo $param; ?>" value="<?php echo $value; ?>" />
@@ -50,13 +50,16 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
<?php endif; ?>
</form>
</div><!-- Close boxData -->
<div id="boxActions">
<a href="index.php?a=passreset"><?php echo _('¿Olvidó su clave?'); ?></a>
</div>
</div><!-- Close boxLogin -->
<?php if( SP_Common::parseParams('g', 'logout', FALSE, TRUE) ): ?>
<?php if( SP_Common::parseParams('g', 'logout', false, true) ): ?>
<div id="boxLogout" class="round5"><?php echo _('Sesión finalizada'); ?></div>
<script>$('#boxLogout').fadeOut(1500, function(){ location.href = 'index.php';});</script>
<?php endif; ?>
<?php if( SP_Init::$UPDATED === TRUE ): ?>
<?php if( SP_Init::$UPDATED === true ): ?>
<div id="boxUpdated" class="round5"><?php echo _('Aplicación actualizada correctamente'); ?></div>
<?php endif; ?>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -29,8 +29,8 @@ $startTime = microtime();
$adminApp = ( isset($_SESSION["uisadminapp"]) && $_SESSION["uisadminapp"] == 1 ) ? "<span title=\""._('Admin Aplicación')."\">(A+)</span>" : "";
$userId = ( isset($_SESSION["uid"]) ) ? $_SESSION["uid"] : 0;
$userLogin = ( isset($_SESSION["ulogin"]) ) ? $_SESSION["ulogin"] : '';
$userName = ( isset($_SESSION["uname"]) ) ? $_SESSION["uname"] : $userLogin;
$userLogin = ( isset($_SESSION["ulogin"]) && ! empty($_SESSION["ulogin"])) ? strtoupper($_SESSION["ulogin"]) : '';
$userName = ( isset($_SESSION["uname"]) && ! empty($_SESSION["uname"])) ? $_SESSION["uname"] : strtoupper($userLogin);
$userGroup = ( isset($_SESSION["ugroupn"]) ) ? $_SESSION["ugroupn"] : '';
$strUser = "$userName ($userGroup) " . $adminApp;

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$action = $data['action'];
$activeTab = $data['active'];
$activeTab = $data['activeTab'];
$onCloseAction = $data['onCloseAction'];
SP_ACL::checkUserAccess($action) || SP_Html::showCommonError('unavailable');
@@ -99,9 +100,11 @@ $lastUpdateMPass = SP_Config::getConfigValue("lastupdatempass");
</td>
</tr>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="action" value="crypt" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="isAjax" value="1" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
</form>
<div class="action">
<ul>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -23,10 +23,10 @@
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$activeTab = $data['active'];
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$activeTab = $data['activeTab'];
$onCloseAction = $data['onCloseAction'];
?>
<div id="title" class="midroundup titleNormal">
@@ -84,9 +84,11 @@ $activeTab = $data['active'];
</tr>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="action" value="migrate" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="isAjax" value="1" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
</form>
<div class="action">
@@ -130,5 +132,5 @@ $activeTab = $data['active'];
$(this).children().html('<?php echo _('SI'); ?>');
}
});
importFile('<?php echo SP_Common::getSessionKey(TRUE); ?>');
importFile('<?php echo SP_Common::getSessionKey(true); ?>');
</script>

79
inc/tpl/passreset.php Normal file
View File

@@ -0,0 +1,79 @@
<?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/>.
*
*/
$action = SP_Common::parseParams('g', 'a');
$hash = SP_Common::parseParams('g', 'h');
$time = SP_Common::parseParams('g', 't');
$passReset = ( $action === 'passreset' && $hash && $time );
?>
<div id="actions" align="center">
<?php if ( isset($data['showlogo']) ): ?>
<div id="logo">
<img src="<?php echo SP_Init::$WEBROOT; ?>/imgs/logo_full.png" alt="sysPass logo"/>
</div>
<?php endif; ?>
<form id="passreset" action="" method="post" onsubmit="sendAjax($(this).serialize(),'/ajax/ajax_passReset.php'); return false;">
<fieldset id="resetdata">
<legend><?php echo _('Solicitud de Cambio de Clave'); ?></legend>
<?php if ( ! $passReset ): ?>
<p>
<input type="text" name="login" id="login" title="<?php echo _('Login del Usuario'); ?>" placeholder="<?php echo _('Usuario'); ?> " value="<?php echo SP_Util::init_var('login'); ?>" autocomplete="off" autofocus required />
<img class="svg" src="<?php //p(image_path('', 'actions/user.svg')); ?>" alt="" />
</p>
<p>
<input type="text" name="email" id="email" title="<?php echo _('Email del Usuario'); ?>" placeholder="<?php echo _('Email'); ?> " value="<?php echo SP_Util::init_var('email'); ?>" autocomplete="off" autofocus required />
<img class="svg" src="<?php //p(image_path('', 'actions/user.svg')); ?>" alt="" />
</p>
<?php else: ?>
<p>
<input type="password" name="pass" id="pass" title="<?php echo _('Nueva Clave'); ?>" placeholder="<?php echo _('Clave'); ?>" value="<?php echo SP_Util::init_var('pass'); ?>" required/>
<img class="svg" id="adminpass-icon" src="<?php //print_unescaped(image_path('', 'actions/password.svg')); ?>" alt="" />
</p>
<p>
<input type="password" name="passv" id="passv" title="<?php echo _('Nueva Clave (Verificar)'); ?>" placeholder="<?php echo _('Clave (Verificar)'); ?>" value="<?php echo SP_Util::init_var('passv'); ?>" required/>
<img class="svg" id="adminpass-icon" src="<?php //print_unescaped(image_path('', 'actions/password.svg')); ?>" alt="" />
</p>
<input type="hidden" name="time" value="<?php echo $time; ?>">
<input type="hidden" name="hash" value="<?php echo $hash; ?>">
<?php endif; ?>
<input type="hidden" name="isAjax" value="1">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
</fieldset>
<div class="buttons">
<?php echo SP_Html::anchorText(_('Volver'),'index.php',_('Volver a iniciar sesión'),'class="button round5"'); ?>
<?php if ( ! $passReset ): ?>
<input type="submit" class="button round5" value="<?php echo _('Solicitar'); ?>" title="<?php echo _('Solicitar cambio de clave'); ?>" />
<?php else: ?>
<input type="submit" class="button round5" value="<?php echo _('Cambiar'); ?>" title="<?php echo _('Cambiar Clave'); ?>" />
<?php endif; ?>
</div>
</form>
</div>

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -26,7 +26,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$profile = SP_Profiles::getProfileData($data['itemid']);
$activeTab = $data['active'];
$onCloseAction = $data['onCloseAction'];
$activeTab = $data['activeTab'];
?>
<div id="fancyContainer" align="center">
@@ -111,12 +112,13 @@ $activeTab = $data['active'];
</tbody>
</table>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="id" value="<?php echo $profile['userprofile_id']; ?>" />
<input type="hidden" name="action" value="<?php echo $profile["action"] ?>" />
<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">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true) ?>">
<input type="hidden" name="isAjax" value="1">
<script>
$(function() {
$('#btnProfilesAcc').buttonset();

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -58,8 +58,8 @@ $accountData = $account->getAccount();
</tr>
</table>
<input type="hidden" name="accountid" value="<?php echo $account->accountId; ?>" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="is_ajax" value="1">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
<input type="hidden" name="isAjax" value="1">
</form>
<div class="action">

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -65,8 +65,8 @@ $searchOrder = SP_Common::parseParams('s', 'accountSearchOrder', 0);
<input type="hidden" name="start" value="<?php echo $searchStart; ?>">
<input type="hidden" name="skey" value="<?php echo $searchKey; ?>" />
<input type="hidden" name="sorder" value="<?php echo $searchOrder; ?>" />
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(TRUE); ?>">
<input type="hidden" name="is_ajax" value="1">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true); ?>">
<input type="hidden" name="isAjax" value="1">
<?php
SP_Html::printSelect(DB::getValuesForSelect('customers', 'customer_id', 'customer_name'), $customersSelProp);
SP_Html::printSelect(DB::getValuesForSelect('categories', 'category_id', 'category_name'), $categoriesSelProp);
@@ -88,7 +88,7 @@ $searchOrder = SP_Common::parseParams('s', 'accountSearchOrder', 0);
accSearch(0);
}});
<?php if ( $globalSearch ): ?>
$('#tblTools .checkbox').button();
$('#tblTools').find('.checkbox').button();
$('#gsearch').click(function(){
if ( $(this).next('label').hasClass('ui-state-active') ){
$(this).next('label').children('span').html('OFF');

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -25,7 +25,8 @@
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
$activeTab = $data['active'];
$activeTab = $data['activeTab'];
$onCloseAction = $data['onCloseAction'];
$isView = $data['view'];
$user = SP_Users::getUserData($data['itemid']);
@@ -160,8 +161,11 @@ $ro = ( $user['checks']['user_isLdap'] ) ? "READONLY" : "";
<label for="usradminacc" title="<?php echo _('Administrador de cuentas') ?>"><?php echo _('Admin. Cuentas') ?></label>
<input type="checkbox" id="usradminacc" name="adminacc" <?php echo $user['checks']['user_isAdminAcc'] . ' ' . $isDisabled; ?> />
<?php endif; ?>
<br>
<label for="usrdisabled" title="<?php echo _('Deshabilitado'); ?>"><?php echo _('Deshabilitado'); ?></label>
<input type="checkbox" id="usrdisabled" name="disabled" <?php echo $user['checks']['user_isDisabled'] . ' ' . $isDisabled; ?>/>
<label for="usrchangepass" title="<?php echo _('Forzar cambio de clave'); ?>"><?php echo _('Cambio Clave'); ?></label>
<input type="checkbox" id="usrchangepass" name="changepass" <?php echo $user['checks']['user_isChangePass'] . ' ' . $isDisabled; ?>/>
</div>
</td>
</tr>
@@ -189,13 +193,14 @@ $ro = ( $user['checks']['user_isLdap'] ) ? "READONLY" : "";
</tbody>
</table>
<?php if ( ! $isView ): ?>
<input type="hidden" name="active" value="<?php echo $activeTab ?>" />
<input type="hidden" name="activeTab" value="<?php echo $activeTab ?>" />
<input type="hidden" name="onCloseAction" value="<?php echo $onCloseAction ?>" />
<input type="hidden" name="ldap" value="<?php echo $user['user_isLdap']; ?>" />
<input type="hidden" name="id" value="<?php echo $user['user_id']; ?>" />
<input type="hidden" name="action" value="<?php echo $user['action']; ?>" />
<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">
<input type="hidden" name="sk" value="<?php echo SP_Common::getSessionKey(true) ?>">
<input type="hidden" name="isAjax" value="1">
<?php endif; ?>
</form>

View File

@@ -2,11 +2,11 @@
/**
* sysPass
*
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
*
* @copyright 2012-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
@@ -23,43 +23,36 @@
* 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 actualización de la aplicación.
*/
class SP_Upgrade {
private static $result = array();
private static $upgrade = array(110, 1121, 1122);
class SP_Upgrade
{
private static $upgrade = array(110, 1121, 1122, 1123);
/**
* @brief Inicia el proceso de actualización de la BBDD
* @param int $version con la versión de la BBDD actual
* @returns bool
*/
public static function doUpgrade($version) {
public static function doUpgrade($version)
{
foreach (self::$upgrade as $upgradeVersion) {
if ($version < $upgradeVersion) {
error_log($upgradeVersion);
if (self::upgradeTo($upgradeVersion) === FALSE) {
if (self::upgradeTo($upgradeVersion) === false) {
SP_Init::initError(
_('Error al aplicar la actualización de la Base de Datos'),
_('Compruebe el registro de eventos para más detalles') . '. <a href="index.php?nodbupgrade=1">' . _('Acceder') . '</a>');
_('Error al aplicar la actualización de la Base de Datos'),
_('Compruebe el registro de eventos para más detalles') . '. <a href="index.php?nodbupgrade=1">' . _('Acceder') . '</a>');
}
}
}
return TRUE;
}
/**
* @brief Comprueba si es necesario actualizar la BBDD
* @returns bool
*/
public static function needUpgrade($version) {
return ( in_array($version, self::$upgrade) );
return true;
}
/**
@@ -67,41 +60,57 @@ class SP_Upgrade {
* @param int $version con la versión a actualizar
* @returns bool
*/
private static function upgradeTo($version) {
private static function upgradeTo($version)
{
$result['action'] = _('Actualizar BBDD');
switch ($version) {
case 110:
$queries[] = "ALTER TABLE `accFiles` CHANGE COLUMN `accfile_name` `accfile_name` VARCHAR(100) NOT NULL";
$queries[] = "ALTER TABLE `accounts` ADD COLUMN `account_otherGroupEdit` BIT(1) NULL DEFAULT 0 AFTER `account_dateEdit`, ADD COLUMN `account_otherUserEdit` BIT(1) NULL DEFAULT 0 AFTER `account_otherGroupEdit`;";
$queries[] = "CREATE TABLE `accUsers` (`accuser_id` INT NOT NULL AUTO_INCREMENT,`accuser_accountId` INT(10) UNSIGNED NOT NULL,`accuser_userId` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`accuser_id`), INDEX `idx_account` (`accuser_accountId` ASC));";
$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 ;";
$queries[] = 'ALTER TABLE `accFiles` CHANGE COLUMN `accfile_name` `accfile_name` VARCHAR(100) NOT NULL';
$queries[] = 'ALTER TABLE `accounts` ADD COLUMN `account_otherGroupEdit` BIT(1) NULL DEFAULT 0 AFTER `account_dateEdit`, ADD COLUMN `account_otherUserEdit` BIT(1) NULL DEFAULT 0 AFTER `account_otherGroupEdit`;';
$queries[] = 'CREATE TABLE `accUsers` (`accuser_id` INT NOT NULL AUTO_INCREMENT,`accuser_accountId` INT(10) UNSIGNED NOT NULL,`accuser_userId` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`accuser_id`), INDEX `idx_account` (`accuser_accountId` ASC));';
$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`;";
$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;
case 1122:
$queries[] = "ALTER TABLE `usrData` CHANGE COLUMN `user_login` `user_login` VARCHAR(50) NOT NULL ,CHANGE COLUMN `user_email` `user_email` VARCHAR(80) NULL DEFAULT NULL ;";
$queries[] = 'ALTER TABLE `usrData` CHANGE COLUMN `user_login` `user_login` VARCHAR(50) NOT NULL ,CHANGE COLUMN `user_email` `user_email` VARCHAR(80) NULL DEFAULT NULL ;';
break;
case 1123:
$queries[] = 'CREATE TABLE `usrPassRecover` (`userpassr_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `userpassr_userId` SMALLINT UNSIGNED NOT NULL,`userpassr_hash` VARBINARY(40) NOT NULL,`userpassr_date` INT UNSIGNED NOT NULL,`userpassr_used` BIT(1) NOT NULL DEFAULT b\'0\', PRIMARY KEY (`userpassr_id`),INDEX `IDX_userId` (`userpassr_userId` ASC, `userpassr_date` ASC)) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;';
$queries[] = 'ALTER TABLE `log` ADD COLUMN `log_ipAddress` VARCHAR(45) NOT NULL AFTER `log_userId`;';
$queries[] = 'ALTER TABLE `usrData` ADD COLUMN `user_isChangePass` BIT(1) NULL DEFAULT b\'0\' AFTER `user_isMigrate`;';
break;
default :
$result['text'][] = _('No es necesario actualizar la Base de Datos.');
return TRUE;
return true;
}
foreach ($queries as $query) {
if (DB::doQuery($query, __FUNCTION__) === FALSE && DB::$numError != 1060 && DB::$numError != 1050) {
if (DB::doQuery($query, __FUNCTION__) === false && DB::$numError != 1060 && DB::$numError != 1050) {
$result['text'][] = _('Error al aplicar la actualización de la Base de Datos.') . ' (v' . $version . ')';
$result['text'][] = 'ERROR: '.DB::$txtError.' ('.DB::$numError.')';
SP_Common::wrLogInfo($result);
return FALSE;
$result['text'][] = 'ERROR: ' . DB::$txtError . ' (' . DB::$numError . ')';
SP_Log::wrLogInfo($result);
return false;
}
}
$result['text'][] = _('Actualización de la Base de Datos realizada correctamente.') . ' (v' . $version . ')';
SP_Common::wrLogInfo($result);
return TRUE;
SP_Log::wrLogInfo($result);
return true;
}
/**
* @brief Comprueba si es necesario actualizar la BBDD
* @param int $version con el número de versión actual
* @returns bool
*/
public static function needUpgrade($version)
{
return (in_array($version, self::$upgrade));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,75 +1,79 @@
<?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-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'));
/**
* Clase con utilizades para la aplicación
*/
class SP_Util {
class SP_Util
{
/**
* @brief Comprobar si la función de números aleatorios está disponible
* @return bool
*/
public static function secureRNG_available() {
public static function secureRNG_available()
{
// Check openssl_random_pseudo_bytes
if(function_exists('openssl_random_pseudo_bytes')) {
openssl_random_pseudo_bytes(1, $strong);
if($strong == true) {
return true;
}
if (function_exists('openssl_random_pseudo_bytes')) {
openssl_random_pseudo_bytes(1, $strong);
if ($strong == true) {
return true;
}
}
// Check /dev/urandom
$fp = @file_get_contents('/dev/urandom', false, null, 0, 1);
if ($fp !== false) {
return true;
return true;
}
return false;
}
/**
* @brief Comprobar si sysPass se ejecuta en W$indows
* @return bool
*/
public static function runningOnWindows() {
public static function runningOnWindows()
{
return (substr(PHP_OS, 0, 3) === "WIN");
}
/**
* @brief Generar una cadena aleatoria usuando criptografía
* @param int $length opcional, con la longitud de la cadena
* @return string
*/
public static function generate_random_bytes($length = 30) {
public static function generate_random_bytes($length = 30)
{
// Try to use openssl_random_pseudo_bytes
if(function_exists('openssl_random_pseudo_bytes')) {
if (function_exists('openssl_random_pseudo_bytes')) {
$pseudo_byte = bin2hex(openssl_random_pseudo_bytes($length, $strong));
if($strong == true) {
if ($strong == true) {
return substr($pseudo_byte, 0, $length); // Truncate it to match the length
}
}
@@ -84,75 +88,80 @@ class SP_Util {
// Fallback to mt_rand()
$characters = '0123456789';
$characters .= 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters)-1;
$charactersLength = strlen($characters) - 1;
$pseudo_byte = "";
// Select some random characters
for ($i = 0; $i < $length; $i++) {
$pseudo_byte .= $characters[mt_rand(0, $charactersLength)];
}
return $pseudo_byte;
}
/**
* @brief Comprobar la versión de PHP
* @return bool
*/
public static function checkPhpVersion(){
preg_match("/(^\d\.\d)\..*/",PHP_VERSION, $version);
public static function checkPhpVersion()
{
preg_match("/(^\d\.\d)\..*/", PHP_VERSION, $version);
if ( $version[1] >= 5.1 ){
$this->printMsg(_('Versión PHP')." '".$version[0]."'");
return TRUE;
if ($version[1] >= 5.1) {
self::printMsg(_('Versión PHP') . " '" . $version[0] . "'");
return true;
} else {
$this->printMsg(_('Versión PHP')." '".$version[0]."'", 1);
return FALSE;
}
self::printMsg(_('Versión PHP') . " '" . $version[0] . "'", 1);
return false;
}
}
/**
* @brief Comprobar los módulos necesarios
* @return array con los módulos no disponibles
*/
public static function checkModules(){
public static function checkModules()
{
$modsAvail = get_loaded_extensions();
$modsNeed = array("mysql","ldap","mcrypt","curl","SimpleXML");
$modsNeed = array("mysql", "ldap", "mcrypt", "curl", "SimpleXML");
$modsErr = array();
foreach($modsNeed as $module){
if ( ! in_array($module, $modsAvail) ){
foreach ($modsNeed as $module) {
if (!in_array($module, $modsAvail)) {
$error = array(
'type' => 'warning',
'description' => _('Módulo no disponible')." ($module)",
'hint' => _('Sin este módulo la aplicación puede no funcionar correctamente.')
);
'type' => 'warning',
'description' => _('Módulo no disponible') . " ($module)",
'hint' => _('Sin este módulo la aplicación puede no funcionar correctamente.')
);
$modsErr[] = $error;
}
}
return $modsErr;
}
/**
* @brief Devuelve el valor de la variable enviada por un formulario
* @param string $s con el nombre de la variable
* @param string $d con el valor por defecto
* @return string con el valor de la variable
*/
public static function init_var($s, $d="") {
public static function init_var($s, $d = "")
{
$r = $d;
if(isset($_REQUEST[$s]) && !empty($_REQUEST[$s])) {
if (isset($_REQUEST[$s]) && !empty($_REQUEST[$s])) {
$r = SP_Html::sanitize($_REQUEST[$s]);
}
return $r;
}
/**
* @brief Comprobar si el módulo de LDAP está instalado
* @return bool
*/
public static function ldapIsAvailable(){
public static function ldapIsAvailable()
{
return in_array("ldap", get_loaded_extensions());
}
@@ -160,101 +169,109 @@ class SP_Util {
* @brief Comprobar si el módulo CURL está instalado
* @return bool
*/
public static function curlIsAvailable(){
return ( function_exists(curl_init) );
public static function curlIsAvailable()
{
return (function_exists(curl_init));
}
/**
* @brief Devuelve la versión de sysPass
* @return array con el número de versión
*/
public static function getVersion($retBuild = FALSE) {
$build = 2;
$version = array(1, 1, 2);
if ( $retBuild ){
array_push($version, $build);
}
return $version;
}
/**
* @brief Devuelve la versión de sysPass
* @return string con la versión
*/
public static function getVersionString() {
public static function getVersionString()
{
return '1.1b';
}
/**
* @brief Comprobar si hay actualizaciones de sysPass disponibles desde internet (sourceforge.net)
* @return array|bool
*
*
* Esta función comprueba el feed RSS de sourceforge.net y lo parsea para verificar si la aplicación está actualizada
*/
public static function checkUpdates(){
*/
public static function checkUpdates()
{
//if ( ! self::curlIsAvailable() || ! SP_Config::getValue('checkupdates') ){
if ( ! SP_Config::getValue('checkupdates') ){
return FALSE;
if (!SP_Config::getValue('checkupdates')) {
return false;
}
// $ch = curl_init("http://sourceforge.net/api/file/index/project-id/775555/mtime/desc/limit/1/rss");
//
//
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HEADER, 0);
//
// if ( ! $data = curl_exec($ch) ) return FALSE;
//
//
// if ( ! $data = curl_exec($ch) ) return false;
//
// curl_close($ch);
$feedUrl = 'https://sourceforge.net/api/file/index/project-id/1257402/mtime/desc/limit/20/rss';
$feed = file_get_contents($feedUrl);
if ( $feed ){
$feed = file_get_contents($feedUrl);
if ($feed) {
$xmlUpd = new SimpleXMLElement($feed, LIBXML_NOCDATA);
} else{
return FALSE;
} else {
return false;
}
if ( $xmlUpd->channel->item->title ){
if ($xmlUpd->channel->item->title) {
$pubVer = '';
foreach ( $xmlUpd->channel->item as $item ){
foreach ($xmlUpd->channel->item as $item) {
$url = (string)$item->link;
$title = (string)$item->title;
$description = (string)$item->description;
if ( preg_match("/.*\/sysPass_(\d)\.(\d{1,})\.(\d{1,})(\-[a-z0-9]+)?\.(tar\.gz|zip)$/", $title, $pubVer) ){
if (preg_match("/.*\/sysPass_(\d)\.(\d{1,})\.(\d{1,})(\-[a-z0-9]+)?\.(tar\.gz|zip)$/", $title, $pubVer)) {
break;
}
}
if ( is_array($pubVer) && SP_Init::isLoggedIn() ){
$appVersion = implode('',self::getVersion());
$pubVersion = $pubVer[1].$pubVer[2].$pubVer[3];
if ( $pubVersion > $appVersion ){
$version = $pubVer[1].'.'.$pubVer[2].'.'.$pubVer[3];
return array('version' => $version,'url' => $url);
if (is_array($pubVer) && SP_Init::isLoggedIn()) {
$appVersion = implode('', self::getVersion());
$pubVersion = $pubVer[1] . $pubVer[2] . $pubVer[3];
if ($pubVersion > $appVersion) {
$version = $pubVer[1] . '.' . $pubVer[2] . '.' . $pubVer[3];
return array('version' => $version, 'url' => $url);
} else {
return TRUE;
return true;
}
} else{
return FALSE;
} else {
return false;
}
}
}
/**
* @brief Devuelve la versión de sysPass
* @param bool $retBuild devolver el número de compilación
* @return array con el número de versión
*/
public static function getVersion($retBuild = false)
{
$build = 3;
$version = array(1, 1, 2);
if ($retBuild) {
array_push($version, $build);
}
return $version;
}
/**
* @brief Comprobar el método utilizado para enviar un formulario
* @param string $method con el método utilizado.
* @return none
*/
public static function checkReferer($method){
if ( $_SERVER['REQUEST_METHOD'] !== $method
|| ! isset($_SERVER['HTTP_REFERER'])
|| ! preg_match('#'.SP_Init::$WEBROOT.'/.*$#', $_SERVER['HTTP_REFERER'])){
*/
public static function checkReferer($method)
{
if ($_SERVER['REQUEST_METHOD'] !== $method
|| !isset($_SERVER['HTTP_REFERER'])
|| !preg_match('#' . SP_Init::$WEBROOT . '/.*$#', $_SERVER['HTTP_REFERER'])
) {
SP_Init::initError(_('No es posible acceder directamente a este archivo'));
exit();
}
@@ -263,24 +280,26 @@ class SP_Util {
/**
* @brief Realiza el proceso de logout
* @return none
*/
public static function logout(){
*/
public static function logout()
{
exit('<script>doLogout();</script>');
}
/**
* @brief Obtener el tamaño máximo de subida de PHP
* @return none
*/
public static function getMaxUpload() {
$max_upload = (int) (ini_get('upload_max_filesize'));
$max_post = (int) (ini_get('post_max_size'));
$memory_limit = (int) (ini_get('memory_limit'));
*/
public static function getMaxUpload()
{
$max_upload = (int)(ini_get('upload_max_filesize'));
$max_post = (int)(ini_get('post_max_size'));
$memory_limit = (int)(ini_get('memory_limit'));
$upload_mb = min($max_upload, $max_post, $memory_limit);
$message['action'] = __FUNCTION__;
$message['text'][] = "Max. PHP upload: " . $upload_mb . "MB";
SP_Common::wrLogInfo($message);
}
SP_Log::wrLogInfo($message);
}
}

View File

@@ -4,7 +4,7 @@
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012 Rubén Domínguez nuxsmin@syspass.org
* @copyright 2012-2014 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
@@ -24,7 +24,7 @@
*/
define('APP_ROOT', '.');
include_once (APP_ROOT."/inc/init.php");
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'init.php';
SP_Html::$htmlBodyOpts = 'OnLoad="doAction(\'accsearch\')"';
SP_Html::render("main");

648
js/alertify.js Normal file
View File

@@ -0,0 +1,648 @@
/**
* alertify
* An unobtrusive customizable JavaScript notification system
*
* @author Fabien Doiron <fabien.doiron@gmail.com>
* @copyright Fabien Doiron 2013
* @license MIT <http://opensource.org/licenses/mit-license.php>
* @link http://fabien-d.github.com/alertify.js/
* @module alertify
* @version 0.3.11
*/
(function (global, undefined) {
"use strict";
var document = global.document,
Alertify;
Alertify = function () {
var _alertify = {},
dialogs = {},
isopen = false,
keys = { ENTER: 13, ESC: 27, SPACE: 32 },
queue = [],
$, btnCancel, btnOK, btnReset, btnResetBack, btnFocus, elCallee, elCover, elDialog, elLog, form, input, getTransitionEvent;
/**
* Markup pieces
* @type {Object}
*/
dialogs = {
buttons : {
holder : "<nav class=\"alertify-buttons\">{{buttons}}</nav>",
submit : "<button type=\"submit\" class=\"alertify-button alertify-button-ok\" id=\"alertify-ok\">{{ok}}</button>",
ok : "<button class=\"alertify-button alertify-button-ok\" id=\"alertify-ok\">{{ok}}</button>",
cancel : "<button class=\"alertify-button alertify-button-cancel\" id=\"alertify-cancel\">{{cancel}}</button>"
},
input : "<div class=\"alertify-text-wrapper\"><input type=\"text\" class=\"alertify-text\" id=\"alertify-text\"></div>",
message : "<p class=\"alertify-message\">{{message}}</p>",
log : "<article class=\"alertify-log{{class}}\">{{message}}</article>"
};
/**
* Return the proper transitionend event
* @return {String} Transition type string
*/
getTransitionEvent = function () {
var t,
type,
supported = false,
el = document.createElement("fakeelement"),
transitions = {
"WebkitTransition" : "webkitTransitionEnd",
"MozTransition" : "transitionend",
"OTransition" : "otransitionend",
"transition" : "transitionend"
};
for (t in transitions) {
if (el.style[t] !== undefined) {
type = transitions[t];
supported = true;
break;
}
}
return {
type : type,
supported : supported
};
};
/**
* Shorthand for document.getElementById()
*
* @param {String} id A specific element ID
* @return {Object} HTML element
*/
$ = function (id) {
return document.getElementById(id);
};
/**
* Alertify private object
* @type {Object}
*/
_alertify = {
/**
* Labels object
* @type {Object}
*/
labels : {
ok : "OK",
cancel : "Cancel"
},
/**
* Delay number
* @type {Number}
*/
delay : 5000,
/**
* Whether buttons are reversed (default is secondary/primary)
* @type {Boolean}
*/
buttonReverse : false,
/**
* Which button should be focused by default
* @type {String} "ok" (default), "cancel", or "none"
*/
buttonFocus : "ok",
/**
* Set the transition event on load
* @type {[type]}
*/
transition : undefined,
/**
* Set the action after closing the alert
* @type {String}
*/
beforeCloseAction : undefined,
/**
* Set the proper button click events
*
* @param {Function} fn [Optional] Callback function
*
* @return {undefined}
*/
addListeners : function (fn) {
var hasOK = (typeof btnOK !== "undefined"),
hasCancel = (typeof btnCancel !== "undefined"),
hasInput = (typeof input !== "undefined"),
val = "",
self = this,
ok, cancel, common, key, reset;
// ok event handler
ok = function (event) {
if (typeof event.preventDefault !== "undefined") event.preventDefault();
common(event);
if (typeof input !== "undefined") val = input.value;
if (typeof fn === "function") {
if (typeof input !== "undefined") {
fn(true, val);
}
else fn(true);
}
return false;
};
// cancel event handler
cancel = function (event) {
if (typeof event.preventDefault !== "undefined") event.preventDefault();
common(event);
if (typeof fn === "function") fn(false);
return false;
};
// common event handler (keyup, ok and cancel)
common = function (event) {
self.hide();
self.unbind(document.body, "keyup", key);
self.unbind(btnReset, "focus", reset);
if (hasOK) self.unbind(btnOK, "click", ok);
if (hasCancel) self.unbind(btnCancel, "click", cancel);
};
// keyup handler
key = function (event) {
var keyCode = event.keyCode;
if ((keyCode === keys.SPACE && !hasInput) || (hasInput && keyCode === keys.ENTER)) ok(event);
if (keyCode === keys.ESC && hasCancel) cancel(event);
};
// reset focus to first item in the dialog
reset = function (event) {
if (hasInput) input.focus();
else if (!hasCancel || self.buttonReverse) btnOK.focus();
else btnCancel.focus();
};
// handle reset focus link
// this ensures that the keyboard focus does not
// ever leave the dialog box until an action has
// been taken
this.bind(btnReset, "focus", reset);
this.bind(btnResetBack, "focus", reset);
// handle OK click
if (hasOK) this.bind(btnOK, "click", ok);
// handle Cancel click
if (hasCancel) this.bind(btnCancel, "click", cancel);
// listen for keys, Cancel => ESC
this.bind(document.body, "keyup", key);
if (!this.transition.supported) {
this.setFocus();
}
},
/**
* Bind events to elements
*
* @param {Object} el HTML Object
* @param {Event} event Event to attach to element
* @param {Function} fn Callback function
*
* @return {undefined}
*/
bind : function (el, event, fn) {
if (typeof el.addEventListener === "function") {
el.addEventListener(event, fn, false);
} else if (el.attachEvent) {
el.attachEvent("on" + event, fn);
}
},
/**
* Use alertify as the global error handler (using window.onerror)
*
* @return {boolean} success
*/
handleErrors : function () {
if (typeof global.onerror !== "undefined") {
var self = this;
global.onerror = function (msg, url, line) {
self.error("[" + msg + " on line " + line + " of " + url + "]", 0);
};
return true;
} else {
return false;
}
},
/**
* Append button HTML strings
*
* @param {String} secondary The secondary button HTML string
* @param {String} primary The primary button HTML string
*
* @return {String} The appended button HTML strings
*/
appendButtons : function (secondary, primary) {
return this.buttonReverse ? primary + secondary : secondary + primary;
},
/**
* Build the proper message box
*
* @param {Object} item Current object in the queue
*
* @return {String} An HTML string of the message box
*/
build : function (item) {
var html = "",
type = item.type,
message = item.message,
css = item.cssClass || "";
html += "<div class=\"alertify-dialog\">";
html += "<a id=\"alertify-resetFocusBack\" class=\"alertify-resetFocus\" href=\"#\">Reset Focus</a>";
if (_alertify.buttonFocus === "none") html += "<a href=\"#\" id=\"alertify-noneFocus\" class=\"alertify-hidden\"></a>";
// doens't require an actual form
if (type === "prompt") html += "<div id=\"alertify-form\">";
html += "<article class=\"alertify-inner\">";
html += dialogs.message.replace("{{message}}", message);
if (type === "prompt") html += dialogs.input;
html += dialogs.buttons.holder;
html += "</article>";
if (type === "prompt") html += "</div>";
html += "<a id=\"alertify-resetFocus\" class=\"alertify-resetFocus\" href=\"#\">Reset Focus</a>";
html += "</div>";
switch (type) {
case "confirm":
html = html.replace("{{buttons}}", this.appendButtons(dialogs.buttons.cancel, dialogs.buttons.ok));
html = html.replace("{{ok}}", this.labels.ok).replace("{{cancel}}", this.labels.cancel);
break;
case "prompt":
html = html.replace("{{buttons}}", this.appendButtons(dialogs.buttons.cancel, dialogs.buttons.submit));
html = html.replace("{{ok}}", this.labels.ok).replace("{{cancel}}", this.labels.cancel);
break;
case "alert":
html = html.replace("{{buttons}}", dialogs.buttons.ok);
html = html.replace("{{ok}}", this.labels.ok);
break;
default:
break;
}
elDialog.className = "alertify alertify-" + type + " " + css;
elCover.className = "alertify-cover";
return html;
},
/**
* Close the log messages
*
* @param {Object} elem HTML Element of log message to close
* @param {Number} wait [optional] Time (in ms) to wait before automatically hiding the message, if 0 never hide
*
* @return {undefined}
*/
close : function (elem, wait) {
// Unary Plus: +"2" === 2
var timer = (wait && !isNaN(wait)) ? +wait : this.delay,
self = this,
hideElement, transitionDone;
var action = this.beforeCloseAction;
// set click event on log messages
this.bind(elem, "click", function () {
hideElement(elem);
});
// Hide the dialog box after transition
// This ensure it doens't block any element from being clicked
transitionDone = function (event) {
event.stopPropagation();
// unbind event so function only gets called once
self.unbind(this, self.transition.type, transitionDone);
// remove log message
elLog.removeChild(this);
if (!elLog.hasChildNodes()) elLog.className += " alertify-logs-hidden";
};
// this sets the hide class to transition out
// or removes the child if css transitions aren't supported
hideElement = function (el) {
// ensure element exists
if (typeof el !== "undefined" && el.parentNode === elLog) {
// whether CSS transition exists
if (self.transition.supported) {
self.bind(el, self.transition.type, transitionDone);
el.className += " alertify-log-hide";
} else {
elLog.removeChild(el);
if (!elLog.hasChildNodes()) elLog.className += " alertify-logs-hidden";
}
}
};
// Execute an action before closing alert
eval(action);
// never close (until click) if wait is set to 0
if (wait === 0) return;
// set timeout to auto close the log message
setTimeout(function () { hideElement(elem);}, timer);
},
/**
* Create a dialog box
*
* @param {String} message The message passed from the callee
* @param {String} type Type of dialog to create
* @param {Function} fn [Optional] Callback function
* @param {String} placeholder [Optional] Default value for prompt input field
* @param {String} cssClass [Optional] Class(es) to append to dialog box
*
* @return {Object}
*/
dialog : function (message, type, fn, placeholder, cssClass) {
// set the current active element
// this allows the keyboard focus to be resetted
// after the dialog box is closed
elCallee = document.activeElement;
// check to ensure the alertify dialog element
// has been successfully created
var check = function () {
if ((elLog && elLog.scrollTop !== null) && (elCover && elCover.scrollTop !== null)) return;
else check();
};
// error catching
if (typeof message !== "string") throw new Error("message must be a string");
if (typeof type !== "string") throw new Error("type must be a string");
if (typeof fn !== "undefined" && typeof fn !== "function") throw new Error("fn must be a function");
// initialize alertify if it hasn't already been done
this.init();
check();
queue.push({ type: type, message: message, callback: fn, placeholder: placeholder, cssClass: cssClass });
if (!isopen) this.setup();
return this;
},
/**
* Extend the log method to create custom methods
*
* @param {String} type Custom method name
*
* @return {Function}
*/
extend : function (type) {
if (typeof type !== "string") throw new Error("extend method must have exactly one paramter");
return function (message, wait) {
this.log(message, type, wait);
return this;
};
},
/**
* Hide the dialog and rest to defaults
*
* @return {undefined}
*/
hide : function () {
var transitionDone,
self = this;
// remove reference from queue
queue.splice(0,1);
// if items remaining in the queue
if (queue.length > 0) this.setup(true);
else {
isopen = false;
// Hide the dialog box after transition
// This ensure it doens't block any element from being clicked
transitionDone = function (event) {
event.stopPropagation();
// unbind event so function only gets called once
self.unbind(elDialog, self.transition.type, transitionDone);
};
// whether CSS transition exists
if (this.transition.supported) {
this.bind(elDialog, this.transition.type, transitionDone);
elDialog.className = "alertify alertify-hide alertify-hidden";
} else {
elDialog.className = "alertify alertify-hide alertify-hidden alertify-isHidden";
}
elCover.className = "alertify-cover alertify-cover-hidden";
// set focus to the last element or body
// after the dialog is closed
elCallee.focus();
}
},
/**
* Initialize Alertify
* Create the 2 main elements
*
* @return {undefined}
*/
init : function () {
// ensure legacy browsers support html5 tags
document.createElement("nav");
document.createElement("article");
document.createElement("section");
// cover
if ($("alertify-cover") == null) {
elCover = document.createElement("div");
elCover.setAttribute("id", "alertify-cover");
elCover.className = "alertify-cover alertify-cover-hidden";
document.body.appendChild(elCover);
}
// main element
if ($("alertify") == null) {
isopen = false;
queue = [];
elDialog = document.createElement("section");
elDialog.setAttribute("id", "alertify");
elDialog.className = "alertify alertify-hidden";
document.body.appendChild(elDialog);
}
// log element
if ($("alertify-logs") == null) {
elLog = document.createElement("section");
elLog.setAttribute("id", "alertify-logs");
elLog.className = "alertify-logs alertify-logs-hidden";
document.body.appendChild(elLog);
}
// set tabindex attribute on body element
// this allows script to give it focus
// after the dialog is closed
document.body.setAttribute("tabindex", "0");
// set transition type
this.transition = getTransitionEvent();
},
/**
* Show a new log message box
*
* @param {String} message The message passed from the callee
* @param {String} type [Optional] Optional type of log message
* @param {Number} wait [Optional] Time (in ms) to wait before auto-hiding the log
*
* @return {Object}
*/
log : function (message, type, wait) {
// check to ensure the alertify dialog element
// has been successfully created
var check = function () {
if (elLog && elLog.scrollTop !== null) return;
else check();
};
// initialize alertify if it hasn't already been done
this.init();
check();
elLog.className = "alertify-logs";
this.notify(message, type, wait);
return this;
},
/**
* Add new log message
* If a type is passed, a class name "alertify-log-{type}" will get added.
* This allows for custom look and feel for various types of notifications.
*
* @param {String} message The message passed from the callee
* @param {String} type [Optional] Type of log message
* @param {Number} wait [Optional] Time (in ms) to wait before auto-hiding
*
* @return {undefined}
*/
notify : function (message, type, wait) {
var log = document.createElement("article");
log.className = "alertify-log" + ((typeof type === "string" && type !== "") ? " alertify-log-" + type : "");
log.innerHTML = message;
// append child
elLog.appendChild(log);
// triggers the CSS animation
setTimeout(function() { log.className = log.className + " alertify-log-show"; }, 50);
this.close(log, wait);
},
/**
* Set properties
*
* @param {Object} args Passing parameters
*
* @return {undefined}
*/
set : function (args) {
var k;
// error catching
if (typeof args !== "object" && args instanceof Array) throw new Error("args must be an object");
// set parameters
for (k in args) {
if (args.hasOwnProperty(k)) {
this[k] = args[k];
}
}
},
/**
* Common place to set focus to proper element
*
* @return {undefined}
*/
setFocus : function () {
if (input) {
input.focus();
input.select();
}
else btnFocus.focus();
},
/**
* Initiate all the required pieces for the dialog box
*
* @return {undefined}
*/
setup : function (fromQueue) {
var item = queue[0],
self = this,
transitionDone;
// dialog is open
isopen = true;
// Set button focus after transition
transitionDone = function (event) {
event.stopPropagation();
self.setFocus();
// unbind event so function only gets called once
self.unbind(elDialog, self.transition.type, transitionDone);
};
// whether CSS transition exists
if (this.transition.supported && !fromQueue) {
this.bind(elDialog, this.transition.type, transitionDone);
}
// build the proper dialog HTML
elDialog.innerHTML = this.build(item);
// assign all the common elements
btnReset = $("alertify-resetFocus");
btnResetBack = $("alertify-resetFocusBack");
btnOK = $("alertify-ok") || undefined;
btnCancel = $("alertify-cancel") || undefined;
btnFocus = (_alertify.buttonFocus === "cancel") ? btnCancel : ((_alertify.buttonFocus === "none") ? $("alertify-noneFocus") : btnOK),
input = $("alertify-text") || undefined;
form = $("alertify-form") || undefined;
// add placeholder value to the input field
if (typeof item.placeholder === "string" && item.placeholder !== "") input.value = item.placeholder;
if (fromQueue) this.setFocus();
this.addListeners(item.callback);
},
/**
* Unbind events to elements
*
* @param {Object} el HTML Object
* @param {Event} event Event to detach to element
* @param {Function} fn Callback function
*
* @return {undefined}
*/
unbind : function (el, event, fn) {
if (typeof el.removeEventListener === "function") {
el.removeEventListener(event, fn, false);
} else if (el.detachEvent) {
el.detachEvent("on" + event, fn);
}
}
};
return {
alert : function (message, fn, cssClass) { _alertify.dialog(message, "alert", fn, "", cssClass); return this; },
confirm : function (message, fn, cssClass) { _alertify.dialog(message, "confirm", fn, "", cssClass); return this; },
extend : _alertify.extend,
init : _alertify.init,
log : function (message, type, wait) { _alertify.log(message, type, wait); return this; },
prompt : function (message, fn, placeholder, cssClass) { _alertify.dialog(message, "prompt", fn, placeholder, cssClass); return this; },
success : function (message, wait) { _alertify.log(message, "success", wait); return this; },
error : function (message, wait) { _alertify.log(message, "error", wait); return this; },
set : function (args) { _alertify.set(args); },
labels : _alertify.labels,
debug : _alertify.handleErrors
};
};
// AMD and window support
if (typeof define === "function") {
define([], function () { return new Alertify(); });
} else if (typeof global.alertify === "undefined") {
global.alertify = new Alertify();
}
}(this));

File diff suppressed because it is too large Load Diff

View File

@@ -9,4 +9,8 @@ ALTER TABLE `categories` ADD COLUMN `category_description` VARCHAR(255) NULL AFT
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`;
-- To 1.1.2.2
ALTER TABLE `usrData` CHANGE COLUMN `user_login` `user_login` VARCHAR(50) NOT NULL ,CHANGE COLUMN `user_email` `user_email` VARCHAR(80) NULL DEFAULT NULL ;
-- To 1.1.2.3
CREATE TABLE `usrPassRecover` (`userpassr_id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `userpassr_userId` SMALLINT UNSIGNED NOT NULL,`userpassr_hash` VARBINARY(40) NOT NULL,`userpassr_date` INT UNSIGNED NOT NULL,`userpassr_used` BIT(1) NOT NULL DEFAULT b\'0\', PRIMARY KEY (`userpassr_id`),INDEX `IDX_userId` (`userpassr_userId` ASC, `userpassr_date` ASC)) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;
ALTER TABLE `log` ADD COLUMN `log_ipAddress` VARCHAR(45) NOT NULL AFTER `log_userId`;
ALTER TABLE `usrData` ADD COLUMN `user_isChangePass` BIT(1) NULL DEFAULT b'0' AFTER `user_isMigrate`;