diff --git a/ajax/ajax_accountSave.php b/ajax/ajax_accountSave.php index 62a16c06..87761656 100644 --- a/ajax/ajax_accountSave.php +++ b/ajax/ajax_accountSave.php @@ -3,8 +3,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -61,7 +61,7 @@ $frmChangesHash = SP_Common::parseParams('p', 'hash'); $userId = SP_Common::parseParams('s', 'uid', 0); $groupId = SP_Common::parseParams('s', 'ugroup', 0); -if ($frmSaveType == 1) { +if ($frmSaveType == 1) { // Nueva Cuenta // Comprobaciones para nueva cuenta if (!$frmName) { SP_Common::printJSON(_('Es necesario un nombre de cuenta')); @@ -82,7 +82,7 @@ if ($frmSaveType == 1) { if ($frmPassword != $frmPasswordV) { SP_Common::printJSON(_('Las claves no coinciden')); } -} elseif ($frmSaveType == 2) { +} elseif ($frmSaveType == 2) { // Modificar Cuenta // Comprobaciones para modificación de cuenta if (!$frmSelCustomer && !$frmNewCustomer) { SP_Common::printJSON(_('Es necesario un nombre de cliente')); @@ -95,11 +95,11 @@ if ($frmSaveType == 1) { if (!$frmLogin) { SP_Common::printJSON(_('Es necesario un usuario')); } -} elseif ($frmSaveType == 3) { +} elseif ($frmSaveType == 3) { // Eliminar Cuenta if (!$frmAccountId) { SP_Common::printJSON(_('Id inválido')); } -} elseif ($frmSaveType == 4) { +} elseif ($frmSaveType == 4) { // Modificar Clave // Comprobaciones para modficación de clave if (!$frmPassword && !$frmPasswordV) { SP_Common::printJSON(_('La clave no puede estar en blanco')); @@ -108,7 +108,7 @@ if ($frmSaveType == 1) { if ($frmPassword != $frmPasswordV) { SP_Common::printJSON(_('Las claves no coinciden')); } -} elseif ($frmSaveType == 5) { +} elseif ($frmSaveType == 5) { // Restaurar Cuenta if (!$frmAccountId) { SP_Common::printJSON(_('Id inválido')); } @@ -135,12 +135,12 @@ if ($frmSaveType == 1 || $frmSaveType == 4) { $account = new SP_Account; switch ($frmSaveType) { - case 1: + case 1: // Nueva Cuenta SP_Customer::$customerName = $frmNewCustomer; // Comprobar si se ha introducido un nuevo cliente if ($frmNewCustomer) { - if (!SP_Customer::checkDupCustomer()) { + if (SP_Customer::checkDupCustomer()) { SP_Common::printJSON(_('Cliente duplicado')); } @@ -171,9 +171,10 @@ switch ($frmSaveType) { if ($account->createAccount()) { SP_Common::printJSON(_('Cuenta creada'), 0); } + SP_Common::printJSON(_('Error al crear la cuenta'), 0); break; - case 2: + case 2: // Modificar Cuenta SP_Customer::$customerName = $frmNewCustomer; $account->accountId = $frmAccountId; $account->accountName = $frmName; @@ -189,7 +190,7 @@ switch ($frmSaveType) { // Comprobar si se ha introducido un nuevo cliente if ($frmNewCustomer) { - if (!SP_Customer::checkDupCustomer()) { + if (SP_Customer::checkDupCustomer()) { SP_Common::printJSON(_('Cliente duplicado')); } @@ -211,9 +212,10 @@ switch ($frmSaveType) { if ($account->updateAccount()) { SP_Common::printJSON(_('Cuenta actualizada'), 0); } + SP_Common::printJSON(_('Error al modificar la cuenta')); break; - case 3: + case 3: // Eliminar Cuenta $account->accountId = $frmAccountId; // Eliminar cuenta @@ -222,7 +224,7 @@ switch ($frmSaveType) { } SP_Common::printJSON(_('Error al eliminar la cuenta')); break; - case 4: + case 4: // Modificar Clave $account->accountId = $frmAccountId; $account->accountPass = $accountPass; $account->accountIV = $accountIV; @@ -232,9 +234,10 @@ switch ($frmSaveType) { if ($account->updateAccountPass()) { SP_Common::printJSON(_('Clave actualizada'), 0); } + SP_Common::printJSON(_('Error al actualizar la clave')); break; - case 5: + case 5: // Restaurar Cuenta $account->accountId = $frmAccountId; $accountHistData = $account->getAccountHistory(); @@ -254,7 +257,7 @@ switch ($frmSaveType) { $account->accountUserEditId = $userId; // Restaurar cuenta y clave - if ($account->updateAccount(true) && $account->updateAccountPass(false,true)) { + if ($account->updateAccount(true) && $account->updateAccountPass(false, true)) { SP_Common::printJSON(_('Cuenta restaurada'), 0); } diff --git a/ajax/ajax_appMgmtSave.php b/ajax/ajax_appMgmtSave.php index b0d0d3a2..af45e783 100644 --- a/ajax/ajax_appMgmtSave.php +++ b/ajax/ajax_appMgmtSave.php @@ -192,7 +192,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) { SP_Groups::$groupName = $frmGrpName; SP_Groups::$groupDescription = $frmGrpDesc; - if (!SP_Groups::checkGroupExist()) { + if (SP_Groups::checkGroupExist()) { SP_Common::printJSON(_('Nombre de grupo duplicado'), 2); } @@ -272,7 +272,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) { SP_Profiles::$profileName = $frmProfileName; - if (!SP_Profiles::checkProfileExist()) { + if (SP_Profiles::checkProfileExist()) { SP_Common::printJSON(_('Nombre de perfil duplicado'), 2); } @@ -330,7 +330,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) { SP_Customer::$customerName = $frmCustomerName; SP_Customer::$customerDescription = $frmCustomerDesc; - if (!SP_Customer::checkDupCustomer($frmItemId)) { + if (SP_Customer::checkDupCustomer($frmItemId)) { SP_Common::printJSON(_('Nombre de cliente duplicado'), 2); } @@ -381,7 +381,7 @@ if ($frmSaveType == 1 || $frmSaveType == 2) { SP_Category::$categoryName = $frmCategoryName; SP_Category::$categoryDescription = $frmCategoryDesc; - if (!SP_Category::checkDupCategory($frmItemId)) { + if (SP_Category::checkDupCategory($frmItemId)) { SP_Common::printJSON(_('Nombre de categoría duplicado'), 2); } diff --git a/ajax/ajax_search.php b/ajax/ajax_search.php index bc9a3637..75aee8ec 100644 --- a/ajax/ajax_search.php +++ b/ajax/ajax_search.php @@ -71,23 +71,20 @@ $userId = SP_Common::parseParams('s', 'uid', 0); $filterOn = ($sortKey > 1 || $customerId || $categoryId || $searchTxt) ? true : false; $colors = array( - 'FF66CC', - 'FF99FF', - 'CC99FF', - '9999FF', - '6699FF', - '3399FF', - '0099FF', - '6699FF', - '3399FF', - '00CC66', - '00CC66', - '00CC99', - '00CCCC', - 'FFCC66', - 'FF9999', - 'FF6699', - 'FF99CC' + 'ef5350', + 'ec407a', + 'ab47bc', + '7e57c2', + '5c6bc0', + '42a5f5', + '29b6f6', + '26c6da', + '26a69a', + '66bb6a', + '9ccc65', + 'ff7043', + '8d6e63', + '78909c' ); $objAccount = new SP_Account; diff --git a/ajax/ajax_viewpass.php b/ajax/ajax_viewpass.php index bba9d9de..d7076dcc 100644 --- a/ajax/ajax_viewpass.php +++ b/ajax/ajax_viewpass.php @@ -34,7 +34,7 @@ if (!SP_Init::isLoggedIn()) { $accountId = SP_Common::parseParams('p', 'accountid', false); $fullTxt = SP_Common::parseParams('p', 'full', 0); -$isHistory = SP_Common::parseParams('p', 'isHistory', 0); +$isHistory = SP_Common::parseParams('p', 'isHistory', false); if (!$accountId) { return; @@ -43,24 +43,19 @@ if (!$accountId) { $account = new SP_Account; $account->accountParentId = ( isset($_SESSION["accParentId"]) ) ? $_SESSION["accParentId"] : ""; $account->accountId = $accountId; -$account->accountIsHistory = $isHistory; +//$account->accountIsHistory = $isHistory; -if (!$isHistory) { - $accountData = $account->getAccount(); +$accountData = $account->getAccountPass($isHistory); - if (!SP_ACL::checkAccountAccess("accviewpass", $account->getAccountDataForACL()) || !SP_ACL::checkUserAccess("accviewpass")) { - die('' . _('No tiene permisos para acceder a esta cuenta') . ''); - } -} else { - if ($account->checkAccountMPass()) { - $accountData = $account->getAccountHistory(); - if (!SP_ACL::checkAccountAccess("accviewpass", $account->getAccountDataForACL()) || !SP_ACL::checkUserAccess("accviewpass")) { - die('' . _('No tiene permisos para acceder a esta cuenta') . ''); - } - } else { - echo '
| - | account_login; ?> | +login; ?> |
| diff --git a/inc/account.class.php b/inc/account.class.php index 090e7a4c..3b07ae28 100644 --- a/inc/account.class.php +++ b/inc/account.class.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -74,14 +74,17 @@ class SP_Account */ public static function getAccountRequestData($accountId) { - $query = "SELECT account_userId," - . "account_userEditId," - . "account_name," - . "customer_name " - . "FROM accounts " - . "LEFT JOIN customers ON account_customerId = customer_id " - . "WHERE account_id = " . (int)$accountId . " LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT account_userId,' + . 'account_userEditId,' + . 'account_name,' + . 'customer_name ' + . 'FROM accounts ' + . 'LEFT JOIN customers ON account_customerId = customer_id ' + . 'WHERE account_id = :id LIMIT 1'; + + $data['id'] = $accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -98,12 +101,14 @@ class SP_Account */ public static function getAccountUsersName($accountId) { - $query = "SELECT user_name " - . "FROM accUsers " - . "JOIN usrData ON accuser_userId = user_id " - . "WHERE accuser_accountId = " . (int)$accountId; + $query = 'SELECT user_name ' + . 'FROM accUsers ' + . 'JOIN usrData ON accuser_userId = user_id ' + . 'WHERE accuser_accountId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -130,116 +135,140 @@ class SP_Account */ public function getAccounts($searchFilter) { - $isAdmin = ($_SESSION["uisadminapp"] || $_SESSION["uisadminacc"]); - $globalSearch = (SP_Config::getValue('globalsearch', 0) && $searchFilter["globalSearch"] === 1); + $isAdmin = ($_SESSION['uisadminapp'] || $_SESSION['uisadminacc']); + $globalSearch = ($searchFilter['globalSearch'] === 1 && SP_Config::getValue('globalsearch', 0)); $arrFilterCommon = array(); $arrFilterSelect = array(); $arrFilterUser = array(); $arrQueryWhere = array(); - switch ($searchFilter["keyId"]) { + switch ($searchFilter['keyId']) { case 1: - $orderKey = "account_name"; + $orderKey = 'account_name'; break; case 2: - $orderKey = "category_name"; + $orderKey = 'category_name'; break; case 3: - $orderKey = "account_login"; + $orderKey = 'account_login'; break; case 4: - $orderKey = "account_url"; + $orderKey = 'account_url'; break; case 5: - $orderKey = "account_customerId"; + $orderKey = 'account_customerId'; break; default : - $orderKey = "customer_name, account_name"; + $orderKey = 'customer_name, account_name'; break; } - $querySelect = "SELECT SQL_CALC_FOUND_ROWS DISTINCT " - . "account_id," - . "account_customerId," - . "category_name," - . "account_name," - . "account_login," - . "account_url," - . "account_notes," - . "account_userId," - . "account_userGroupId," - . "account_otherUserEdit," - . "account_otherGroupEdit," - . "usergroup_name," - . "customer_name " - . "FROM accounts " - . "LEFT JOIN categories ON account_categoryId = category_id " - . "LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id " - . "LEFT JOIN customers ON customer_id = account_customerId " - . "LEFT JOIN accUsers ON accuser_accountId = account_id " - . "LEFT JOIN accGroups ON accgroup_accountId = account_id"; + $querySelect = 'SELECT DISTINCT ' + . 'account_id,' + . 'account_customerId,' + . 'category_name,' + . 'account_name,' + . 'account_login,' + . 'account_url,' + . 'account_notes,' + . 'account_userId,' + . 'account_userGroupId,' + . 'BIN(account_otherUserEdit) AS account_otherUserEdit,' + . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,' + . 'usergroup_name,' + . 'customer_name ' + . 'FROM accounts ' + . 'LEFT JOIN categories ON account_categoryId = category_id ' + . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id ' + . 'LEFT JOIN customers ON customer_id = account_customerId ' + . 'LEFT JOIN accUsers ON accuser_accountId = account_id ' + . 'LEFT JOIN accGroups ON accgroup_accountId = account_id'; - if ($searchFilter["txtSearch"]) { - $arrFilterCommon[] = "account_name LIKE '%" . DB::escape($searchFilter["txtSearch"]) . "%'"; - $arrFilterCommon[] = "account_login LIKE '%" . DB::escape($searchFilter["txtSearch"]) . "%'"; - $arrFilterCommon[] = "account_url LIKE '%" . DB::escape($searchFilter["txtSearch"]) . "%'"; - $arrFilterCommon[] = "account_notes LIKE '%" . DB::escape($searchFilter["txtSearch"]) . "%'"; + if ($searchFilter['txtSearch']) { + $arrFilterCommon[] = 'account_name LIKE :name'; + $arrFilterCommon[] = 'account_login LIKE :login'; + $arrFilterCommon[] = 'account_url LIKE :url'; + $arrFilterCommon[] = 'account_notes LIKE :notes'; + + $data['name'] = '%' . $searchFilter['txtSearch'] . '%'; + $data['login'] = '%' . $searchFilter['txtSearch'] . '%'; + $data['url'] = '%' . $searchFilter['txtSearch'] . '%'; + $data['notes'] = '%' . $searchFilter['txtSearch'] . '%'; } - if ($searchFilter["categoryId"] != 0) { - $arrFilterSelect[] = "category_id = " . $searchFilter["categoryId"]; - } - if ($searchFilter["customerId"] != 0) { - $arrFilterSelect[] = "account_customerId = " . $searchFilter["customerId"]; - } + if ($searchFilter['categoryId'] != 0) { + $arrFilterSelect[] = 'category_id = :categoryId'; + $data['categoryId'] = $searchFilter['categoryId']; + } + if ($searchFilter['customerId'] != 0) { + $arrFilterSelect[] = 'account_customerId = :customerId'; + + $data['customerId'] = $searchFilter['customerId']; + } if (count($arrFilterCommon) > 0) { - $arrQueryWhere[] = "(" . implode(" OR ", $arrFilterCommon) . ")"; + $arrQueryWhere[] = '(' . implode(' OR ', $arrFilterCommon) . ')'; } if (count($arrFilterSelect) > 0) { - $arrQueryWhere[] = "(" . implode(" AND ", $arrFilterSelect) . ")"; + $arrQueryWhere[] = '(' . implode(' AND ', $arrFilterSelect) . ')'; } if (!$isAdmin && !$globalSearch) { - $arrFilterUser[] = "account_userGroupId = " . (int) $searchFilter["groupId"]; - $arrFilterUser[] = "account_userId = " . $searchFilter["userId"]; - $arrFilterUser[] = "accgroup_groupId = " . $searchFilter["groupId"]; - $arrFilterUser[] = "accuser_userId = " . $searchFilter["userId"]; + $arrFilterUser[] = 'account_userGroupId = :userGroupId'; + $arrFilterUser[] = 'account_userId = :userId'; + $arrFilterUser[] = 'accgroup_groupId = :accgroup_groupId'; + $arrFilterUser[] = 'accuser_userId = :accuser_userId'; - $arrQueryWhere[] = "(" . implode(" OR ", $arrFilterUser) . ")"; + $data['userGroupId'] = $searchFilter['groupId']; + $data['userId'] = $searchFilter['userId']; + $data['accgroup_groupId'] = $searchFilter['groupId']; + $data['accuser_userId'] = $searchFilter['userId']; + + //$arrQueryWhere[] = '(' . implode(' OR ', $arrFilterUser) . ')'; + $arrQueryWhere[] = implode(' OR ', $arrFilterUser); } - $order = ($searchFilter["txtOrder"] == 0) ? 'ASC' : 'DESC'; + $orderDir = ($searchFilter["txtOrder"] == 0) ? 'ASC' : 'DESC'; + $queryOrder = 'ORDER BY ' . $orderKey . ' ' . $orderDir; - $queryOrder = " ORDER BY $orderKey " . $order; + if ($searchFilter['limitCount'] != 99) { + $queryLimit = 'LIMIT :limitStart,:limitCount'; - if ($searchFilter["limitCount"] != 99) { - $queryLimit = "LIMIT " . $searchFilter["limitStart"] . ", " . $searchFilter["limitCount"]; + $data['limitStart'] = $searchFilter['limitStart']; + $data['limitCount'] = $searchFilter['limitCount']; } if (count($arrQueryWhere) === 1) { - $query = $querySelect . " WHERE " . implode($arrQueryWhere) . " " . $queryOrder . " " . $queryLimit; + $query = $querySelect . ' WHERE ' . implode($arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit; } elseif (count($arrQueryWhere) > 1) { - $query = $querySelect . " WHERE " . implode(" AND ", $arrQueryWhere) . " " . $queryOrder . " " . $queryLimit; + $query = $querySelect . ' WHERE ' . implode(' AND ', $arrQueryWhere) . ' ' . $queryOrder . ' ' . $queryLimit; } else { - $query = $querySelect . $queryOrder . " " . $queryLimit; + $query = $querySelect . ' ' . $queryOrder . ' ' . $queryLimit; } $this->query = $query; + // Obtener el número total de cuentas visibles por el usuario + DB::setFullRowCount(); + + // Obtener los resultados siempre en array de objetos + DB::setReturnArray(); + // Consulta de la búsqueda de cuentas - $queryRes = DB::getResults($query, __FUNCTION__, true); + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { +// print_r($query); +// var_dump($data); return false; } + // Obtenemos el número de registros totales de la consulta sin contar el LIMIT - $resQueryNumRows = DB::getResults("SELECT FOUND_ROWS() as numRows", __FUNCTION__); - $this->queryNumRows = $resQueryNumRows->numRows; + $this->queryNumRows = DB::$last_num_rows; $_SESSION["accountSearchTxt"] = $searchFilter["txtSearch"]; $_SESSION["accountSearchCustomer"] = $searchFilter["customerId"]; @@ -262,41 +291,43 @@ class SP_Account */ public function getAccountHistory() { - $query = "SELECT acchistory_accountId as account_id," - . "acchistory_customerId as account_customerId," - . "acchistory_categoryId as account_categoryId," - . "acchistory_name as account_name," - . "acchistory_login as account_login," - . "acchistory_url as account_url," - . "acchistory_pass as account_pass," - . "acchistory_IV as account_IV," - . "acchistory_notes as account_notes," - . "acchistory_countView as account_countView," - . "acchistory_countDecrypt as account_countDecrypt," - . "acchistory_dateAdd as account_dateAdd," - . "acchistory_dateEdit as account_dateEdit," - . "acchistory_userId as account_userId," - . "acchistory_userGroupId as account_userGroupId," - . "acchistory_userEditId as account_userEditId," - . "acchistory_isModify," - . "acchistory_isDeleted," - . "acchistory_otherUserEdit as account_otherUserEdit," - . "acchistory_otherGroupEdit as account_otherGroupEdit," - . "u1.user_name," - . "u1.user_login," - . "usergroup_name," - . "u2.user_name as user_editName," - . "u2.user_login as user_editLogin," - . "category_name, customer_name " - . "FROM accHistory " - . "LEFT JOIN categories ON acchistory_categoryId = category_id " - . "LEFT JOIN usrGroups ON acchistory_userGroupId = usergroup_id " - . "LEFT JOIN usrData u1 ON acchistory_userId = u1.user_id " - . "LEFT JOIN usrData u2 ON acchistory_userEditId = u2.user_id " - . "LEFT JOIN customers ON acchistory_customerId = customer_id " - . "WHERE acchistory_id = " . (int)$this->accountId . " LIMIT 1"; + $query = 'SELECT acchistory_accountId as account_id,' + . 'acchistory_customerId as account_customerId,' + . 'acchistory_categoryId as account_categoryId,' + . 'acchistory_name as account_name,' + . 'acchistory_login as account_login,' + . 'acchistory_url as account_url,' + . 'acchistory_pass as account_pass,' + . 'acchistory_IV as account_IV,' + . 'acchistory_notes as account_notes,' + . 'acchistory_countView as account_countView,' + . 'acchistory_countDecrypt as account_countDecrypt,' + . 'acchistory_dateAdd as account_dateAdd,' + . 'acchistory_dateEdit as account_dateEdit,' + . 'acchistory_userId as account_userId,' + . 'acchistory_userGroupId as account_userGroupId,' + . 'acchistory_userEditId as account_userEditId,' + . 'acchistory_isModify,' + . 'acchistory_isDeleted,' + . 'acchistory_otherUserEdit + 0 AS account_otherUserEdit,' + . 'acchistory_otherGroupEdit + 0 AS account_otherGroupEdit,' + . 'u1.user_name,' + . 'u1.user_login,' + . 'usergroup_name,' + . 'u2.user_name as user_editName,' + . 'u2.user_login as user_editLogin,' + . 'category_name, customer_name ' + . 'FROM accHistory ' + . 'LEFT JOIN categories ON acchistory_categoryId = category_id ' + . 'LEFT JOIN usrGroups ON acchistory_userGroupId = usergroup_id ' + . 'LEFT JOIN usrData u1 ON acchistory_userId = u1.user_id ' + . 'LEFT JOIN usrData u2 ON acchistory_userEditId = u2.user_id ' + . 'LEFT JOIN customers ON acchistory_customerId = customer_id ' + . 'WHERE acchistory_id = :id LIMIT 1'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $this->accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -318,7 +349,7 @@ class SP_Account */ public function updateAccount($isRestore = false) { - $message['action'][] = __FUNCTION__; + $message['action'] = __FUNCTION__; // Guardamos una copia de la cuenta en el histórico if (!$this->addHistory($this->accountId, $this->accountUserEditId, false)) { @@ -327,7 +358,7 @@ class SP_Account return false; } - if ( ! $isRestore ){ + if (!$isRestore) { $message['action'] = _('Actualizar Cuenta'); if (!SP_Groups::updateGroupsForAccount($this->accountId, $this->accountUserGroupsId)) { @@ -345,21 +376,31 @@ class SP_Account $message['action'] = _('Restaurar Cuenta'); } - $query = "UPDATE accounts SET " - . "account_customerId = " . (int)$this->accountCustomerId . "," - . "account_categoryId = " . (int)$this->accountCategoryId . "," - . "account_name = '" . DB::escape($this->accountName) . "'," - . "account_login = '" . DB::escape($this->accountLogin) . "'," - . "account_url = '" . DB::escape($this->accountUrl) . "'," - . "account_notes = '" . DB::escape($this->accountNotes) . "'," - . "account_userEditId = " . (int)$this->accountUserEditId . "," - . "account_dateEdit = NOW(), " - . "account_otherUserEdit = " . (int)$this->accountOtherUserEdit . "," - . "account_otherGroupEdit = " . (int)$this->accountOtherGroupEdit . " " - . "WHERE account_id = " . (int)$this->accountId; + $query = 'UPDATE accounts SET ' + . 'account_customerId = :accountCustomerId,' + . 'account_categoryId = :accountCategoryId,' + . 'account_name = :accountName,' + . 'account_login = :accountLogin,' + . 'account_url = :accountUrl,' + . 'account_notes = :accountNotes,' + . 'account_userEditId = :accountUserEditId,' + . 'account_dateEdit = NOW(),' + . 'account_otherUserEdit = :accountOtherUserEdit,' + . 'account_otherGroupEdit = :accountOtherGroupEdit ' + . 'WHERE account_id = :accountId'; + $data['accountCustomerId'] = $this->accountCustomerId; + $data['accountCategoryId'] = $this->accountCategoryId; + $data['accountName'] = $this->accountName; + $data['accountLogin'] = $this->accountLogin; + $data['accountUrl'] = $this->accountUrl; + $data['accountNotes'] = $this->accountNotes; + $data['accountUserEditId'] = $this->accountUserEditId; + $data['accountOtherUserEdit'] = intval($this->accountOtherUserEdit); + $data['accountOtherGroupEdit'] = intval($this->accountOtherGroupEdit); + $data['accountId'] = $this->accountId; - if (DB::doQuery($query, __FUNCTION__) === false) { + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -367,8 +408,8 @@ class SP_Account $this->getAccountInfoById($accountInfo); $message['action'] = _('Cuenta actualizada'); - $message['text'][] = SP_Html::strongText(_('Cliente') . ": ") . $this->cacheParams['customer_name']; - $message['text'][] = SP_Html::strongText(_('Cuenta') . ": ") . "$this->accountName ($this->accountId)"; + $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name']; + $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . "$this->accountName ($this->accountId)"; SP_Log::wrLogInfo($message); SP_Common::sendEmail($message); @@ -384,99 +425,57 @@ class SP_Account */ private function addHistory($isDelete = false) { - $objAccountHist = new SP_Account; + $query = 'INSERT INTO accHistory ' + . '(acchistory_accountId,' + . 'acchistory_categoryId,' + . 'acchistory_customerId,' + . 'acchistory_name,' + . 'acchistory_login,' + . 'acchistory_url,' + . 'acchistory_pass,' + . 'acchistory_IV,' + . 'acchistory_notes,' + . 'acchistory_countView,' + . 'acchistory_countDecrypt,' + . 'acchistory_dateAdd,' + . 'acchistory_dateEdit,' + . 'acchistory_userId,' + . 'acchistory_userGroupId,' + . 'acchistory_userEditId,' + . 'acchistory_otherUserEdit,' + . 'acchistory_otherGroupEdit,' + . 'acchistory_isModify,' + . 'acchistory_isDeleted,' + . 'acchistory_mPassHash) ' + . 'SELECT account_id,' + . 'account_categoryId,' + . 'account_customerId,' + . 'account_name,' + . 'account_login,' + . 'account_url,' + . 'account_pass,' + . 'account_IV,' + . 'account_notes,' + . 'account_countView,' + . 'account_countDecrypt,' + . 'account_dateAdd,' + . 'account_dateEdit,' + . 'account_userId,' + . 'account_userGroupId,' + . 'account_userEditId,' + . 'account_otherUserEdit,' + . 'account_otherGroupEdit,' + . ':isModify,' + . ':isDelete,' + . ':masterPwd ' + . 'FROM accounts WHERE account_id = :account_id'; - $objAccountHist->accountId = $this->accountId; - $accountData = $objAccountHist->getAccount(); + $data['account_id'] = $this->accountId; + $data['isModify'] = ($isDelete === false) ? 1 : 0; + $data['isDelete'] = ($isDelete === false) ? 0 : 1; + $data['masterPwd'] = SP_Config::getConfigValue('masterPwd'); - $isModify = ($isDelete === false) ? 1 : 0; - $isDelete = ($isDelete === false) ? 0 : 1; - - $query = "INSERT INTO accHistory SET " - . "acchistory_accountId = " . $objAccountHist->accountId . "," - . "acchistory_categoryId = " . $accountData->account_categoryId . "," - . "acchistory_customerId = " . $accountData->account_customerId . "," - . "acchistory_name = '" . DB::escape($accountData->account_name) . "'," - . "acchistory_login = '" . DB::escape($accountData->account_login) . "'," - . "acchistory_url = '" . DB::escape($accountData->account_url) . "'," - . "acchistory_pass = '" . DB::escape($accountData->account_pass) . "'," - . "acchistory_IV = '" . DB::escape($accountData->account_IV) . "'," - . "acchistory_notes = '" . DB::escape($accountData->account_notes) . "'," - . "acchistory_countView = " . $accountData->account_countView . "," - . "acchistory_countDecrypt = " . $accountData->account_countDecrypt . "," - . "acchistory_dateAdd = '" . $accountData->account_dateAdd . "'," - . "acchistory_dateEdit = '" . $accountData->account_dateEdit . "'," - . "acchistory_userId = " . $accountData->account_userId . "," - . "acchistory_userGroupId = " . $accountData->account_userGroupId . "," - . "acchistory_userEditId = " . $accountData->account_userEditId . "," - . "acchistory_isModify = " . $isModify . "," - . "acchistory_isDeleted = " . $isDelete . "," - . "acchistory_otherUserEdit = " . $accountData->account_otherUserEdit . "," - . "acchistory_otherGroupEdit = " . $accountData->account_otherGroupEdit . "," - . "acchistory_mPassHash = '" . DB::escape(SP_Config::getConfigValue('masterPwd')) . "'"; - - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } - - return true; - } - - /** - * Obtener los datos de una cuenta. - * Esta funcion realiza la consulta a la BBDD y guarda los datos en las variables de la clase. - * - * @return object|false - */ - public function getAccount() - { - $query = "SELECT account_id," - . "account_name," - . "account_categoryId," - . "account_userId," - . "account_customerId," - . "account_userGroupId," - . "account_userEditId," - . "category_name," - . "account_login," - . "account_url," - . "account_pass," - . "account_IV," - . "account_notes," - . "account_countView," - . "account_countDecrypt," - . "account_dateAdd," - . "account_dateEdit," - . "account_otherUserEdit," - . "account_otherGroupEdit," - . "u1.user_name," - . "u1.user_login," - . "u2.user_name as user_editName," - . "u2.user_login as user_editLogin," - . "usergroup_name," - . "customer_name, " - . "CONCAT(account_name,account_categoryId,account_customerId,account_login,account_url,account_notes,BIN(account_otherUserEdit),BIN(account_otherGroupEdit)) as modHash " - . "FROM accounts " - . "LEFT JOIN categories ON account_categoryId = category_id " - . "LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id " - . "LEFT JOIN usrData u1 ON account_userId = u1.user_id " - . "LEFT JOIN usrData u2 ON account_userEditId = u2.user_id " - . "LEFT JOIN customers ON account_customerId = customer_id " - . "WHERE account_id = " . (int)$this->accountId . " LIMIT 1"; - - $queryRes = DB::getResults($query, __FUNCTION__); - - if ($queryRes === false) { - return false; - } - - $this->accountUserId = $queryRes->account_userId; - $this->accountUserGroupId = $queryRes->account_userGroupId; - $this->accountOtherUserEdit = $queryRes->account_otherUserEdit; - $this->accountOtherGroupEdit = $queryRes->account_otherGroupEdit; - $this->accountModHash = $queryRes->modHash; - - return $queryRes; + return DB::getQuery($query, __FUNCTION__, $data); } /** @@ -507,14 +506,17 @@ class SP_Account } } - $query = "SELECT " . implode(',', $params) . " " - . "FROM accounts " - . "LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id " - . "LEFT JOIN usrData u1 ON account_userId = u1.user_id " - . "LEFT JOIN usrData u2 ON account_userEditId = u2.user_id " - . "LEFT JOIN customers ON account_customerId = customer_id " - . "WHERE account_id = " . (int)$this->accountId . " LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT ' . implode(',', $params) . ' ' + . 'FROM accounts ' + . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id ' + . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id ' + . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id ' + . 'LEFT JOIN customers ON account_customerId = customer_id ' + . 'WHERE account_id = :id LIMIT 1'; + + $data['id'] = $this->accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -527,6 +529,113 @@ class SP_Account return true; } + /** + * Obtener los datos de una cuenta para mostrar la clave + * Esta funcion realiza la consulta a la BBDD y devuelve los datos. + * + * @return object|false + */ + public function getAccountPass($isHistory = false) + { + if (!$isHistory) { + $query = 'SELECT account_name AS name,' + . 'account_userId AS userId,' + . 'account_userGroupId AS groupId,' + . 'account_login AS login,' + . 'account_pass AS pass,' + . 'account_IV AS iv,' + . 'customer_name ' + . 'FROM accounts ' + . 'LEFT JOIN customers ON account_customerId = customer_id ' + . 'WHERE account_id = :id LIMIT 1'; + } else { + $query = 'SELECT acchistory_name AS name,' + . 'acchistory_userId AS userId,' + . 'acchistory_userGroupId AS groupId,' + . 'acchistory_login AS login,' + . 'acchistory_pass AS pass,' + . 'acchistory_IV AS iv,' + . 'customer_name ' + . 'FROM accHistory ' + . 'LEFT JOIN customers ON acchistory_customerId = customer_id ' + . 'WHERE acchistory_id = :id LIMIT 1'; + } + + $data['id'] = $this->accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); + + if ($queryRes === false) { + return false; + } + + $this->accountUserId = $queryRes->userId; + $this->accountUserGroupId = $queryRes->groupId; + $this->accountPass = $queryRes->pass; + $this->accountIV = $queryRes->iv; + + return $queryRes; + } + + /** + * Obtener los datos de una cuenta. + * Esta funcion realiza la consulta a la BBDD y guarda los datos en las variables de la clase. + * + * @return object|false + */ + public function getAccount() + { + $query = 'SELECT account_id,' + . 'account_name,' + . 'account_categoryId,' + . 'account_userId,' + . 'account_customerId,' + . 'account_userGroupId,' + . 'account_userEditId,' + . 'category_name,' + . 'account_login,' + . 'account_url,' + . 'account_pass,' + . 'account_IV,' + . 'account_notes,' + . 'account_countView,' + . 'account_countDecrypt,' + . 'account_dateAdd,' + . 'account_dateEdit,' + . 'BIN(account_otherUserEdit) AS account_otherUserEdit,' + . 'BIN(account_otherGroupEdit) AS account_otherGroupEdit,' + . 'u1.user_name,' + . 'u1.user_login,' + . 'u2.user_name as user_editName,' + . 'u2.user_login as user_editLogin,' + . 'usergroup_name,' + . 'customer_name, ' + . 'CONCAT(account_name,account_categoryId,account_customerId,account_login,account_url,account_notes,BIN(account_otherUserEdit),BIN(account_otherGroupEdit)) as modHash ' + . 'FROM accounts ' + . 'LEFT JOIN categories ON account_categoryId = category_id ' + . 'LEFT JOIN usrGroups ug ON account_userGroupId = usergroup_id ' + . 'LEFT JOIN usrData u1 ON account_userId = u1.user_id ' + . 'LEFT JOIN usrData u2 ON account_userEditId = u2.user_id ' + . 'LEFT JOIN customers ON account_customerId = customer_id ' + . 'WHERE account_id = :id LIMIT 1'; + + $data['id'] = $this->accountId; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); + + if ($queryRes === false) { + return false; + } + + $this->accountUserId = $queryRes->account_userId; + $this->accountUserGroupId = $queryRes->account_userGroupId; + $this->accountOtherUserEdit = $queryRes->account_otherUserEdit; + $this->accountOtherGroupEdit = $queryRes->account_otherGroupEdit; + $this->accountModHash = $queryRes->modHash; + + return $queryRes; + } + /** * Crea una nueva cuenta en la BBDD * @@ -534,22 +643,35 @@ class SP_Account */ public function createAccount() { - $query = "INSERT INTO accounts SET " - . "account_customerId = " . (int)$this->accountCustomerId . "," - . "account_categoryId = " . (int)$this->accountCategoryId . "," - . "account_name = '" . DB::escape($this->accountName) . "'," - . "account_login = '" . DB::escape($this->accountLogin) . "'," - . "account_url = '" . DB::escape($this->accountUrl) . "'," - . "account_pass = '$this->accountPass'," - . "account_IV = '" . DB::escape($this->accountIV) . "'," - . "account_notes = '" . DB::escape($this->accountNotes) . "'," - . "account_dateAdd = NOW()," - . "account_userId = " . (int)$this->accountUserId . "," - . "account_userGroupId = " . (int)$this->accountUserGroupId . "," - . "account_otherUserEdit = " . (int)$this->accountOtherUserEdit . "," - . "account_otherGroupEdit = " . (int)$this->accountOtherGroupEdit; + $query = 'INSERT INTO accounts SET ' + . 'account_customerId = :accountCustomerId,' + . 'account_categoryId = :accountCategoryId,' + . 'account_name = :accountName,' + . 'account_login = :accountLogin,' + . 'account_url = :accountUrl,' + . 'account_pass = :accountPass,' + . 'account_IV = :accountIV,' + . 'account_notes = :accountNotes,' + . 'account_dateAdd = NOW(),' + . 'account_userId = :accountUserId,' + . 'account_userGroupId = :accountUserGroupId,' + . 'account_otherUserEdit = :accountOtherUserEdit,' + . 'account_otherGroupEdit = :accountOtherGroupEdit'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['accountCustomerId'] = $this->accountCustomerId; + $data['accountCategoryId'] = $this->accountCategoryId; + $data['accountName'] = $this->accountName; + $data['accountLogin'] = $this->accountLogin; + $data['accountUrl'] = $this->accountUrl; + $data['accountPass'] = $this->accountPass; + $data['accountIV'] = $this->accountIV; + $data['accountNotes'] = $this->accountNotes; + $data['accountUserId'] = $this->accountUserId; + $data['accountUserGroupId'] = $this->accountUserGroupId; + $data['accountOtherUserEdit'] = $this->accountOtherUserEdit; + $data['accountOtherGroupEdit'] = $this->accountOtherGroupEdit; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -557,7 +679,7 @@ class SP_Account $message['action'] = __FUNCTION__; - if ( is_array($this->accountUserGroupsId) ){ + if (is_array($this->accountUserGroupsId)) { if (!SP_Groups::addGroupsForAccount($this->accountId, $this->accountUserGroupsId)) { $message['text'][] = _('Error al actualizar los grupos secundarios'); SP_Log::wrLogInfo($message); @@ -565,7 +687,7 @@ class SP_Account } } - if ( is_array($this->accountUsersId) ){ + if (is_array($this->accountUsersId)) { if (!SP_Users::addUsersForAccount($this->accountId, $this->accountUsersId)) { $message['text'][] = _('Error al actualizar los usuarios de la cuenta'); SP_Log::wrLogInfo($message); @@ -577,8 +699,8 @@ class SP_Account $this->getAccountInfoById($accountInfo); $message['action'] = _('Nueva Cuenta'); - $message['text'][] = SP_Html::strongText(_('Cliente') . ": ") . $this->cacheParams['customer_name']; - $message['text'][] = SP_Html::strongText(_('Cuenta') . ": ") . "$this->accountName ($this->accountId)"; + $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name']; + $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . "$this->accountName ($this->accountId)"; SP_Log::wrLogInfo($message); SP_Common::sendEmail($message); @@ -600,13 +722,14 @@ class SP_Account $this->getAccountInfoById($accountInfo); $message['action'] = _('Eliminar Cuenta'); - $message['text'][] = SP_Html::strongText(_('Cliente') . ": ") . $this->cacheParams['customer_name']; - $message['text'][] = SP_Html::strongText(_('Cuenta') . ": ") . $this->cacheParams['account_name'] . " ($this->accountId)"; + $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name']; + $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $this->cacheParams['account_name'] . " ($this->accountId)"; - $query = "DELETE FROM accounts " - . "WHERE account_id = " . (int)$this->accountId . " LIMIT 1"; + $query = 'DELETE FROM accounts WHERE account_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $this->accountId; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -635,18 +758,22 @@ class SP_Account */ public function getAccountHistoryList() { - $query = "SELECT acchistory_id," - . "acchistory_dateEdit," - . "u1.user_login as user_edit," - . "u2.user_login as user_add," - . "acchistory_dateAdd " - . "FROM accHistory " - . "LEFT JOIN usrData u1 ON acchistory_userEditId = u1.user_id " - . "LEFT JOIN usrData u2 ON acchistory_userId = u2.user_id " - . "WHERE acchistory_accountId = " . $_SESSION["accParentId"] . " " - . "ORDER BY acchistory_id DESC"; + $query = 'SELECT acchistory_id,' + . 'acchistory_dateEdit,' + . 'u1.user_login as user_edit,' + . 'u2.user_login as user_add,' + . 'acchistory_dateAdd ' + . 'FROM accHistory ' + . 'LEFT JOIN usrData u1 ON acchistory_userEditId = u1.user_id ' + . 'LEFT JOIN usrData u2 ON acchistory_userId = u2.user_id ' + . 'WHERE acchistory_accountId = :id ' + . 'ORDER BY acchistory_id DESC'; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $data['id'] = $_SESSION["accParentId"]; + + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -655,10 +782,11 @@ class SP_Account $arrHistory = array(); foreach ($queryRes as $history) { - if ($history->acchistory_dateEdit == '0000-00-00 00:00:00') { - $arrHistory[$history->acchistory_id] = $history->acchistory_dateAdd . " - " . $history->user_add; + // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición) + if ($history->acchistory_dateEdit === null || $history->acchistory_dateEdit == '0000-00-00 00:00:00') { + $arrHistory[$history->acchistory_id] = $history->acchistory_dateAdd . ' - ' . $history->user_add; } else { - $arrHistory[$history->acchistory_id] = $history->acchistory_dateEdit . " - " . $history->user_edit; + $arrHistory[$history->acchistory_id] = $history->acchistory_dateEdit . ' - ' . $history->user_edit; } } @@ -672,15 +800,11 @@ class SP_Account */ public function incrementViewCounter() { - $query = "UPDATE accounts " - . "SET account_countView = (account_countView + 1) " - . "WHERE account_id = " . (int)$this->accountId; + $query = 'UPDATE accounts SET account_countView = (account_countView + 1) WHERE account_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['id'] = $this->accountId; - return true; + return DB::getQuery($query, __FUNCTION__, $data); } /** @@ -690,14 +814,11 @@ class SP_Account */ public function incrementDecryptCounter() { - $query = "UPDATE accounts SET account_countDecrypt = (account_countDecrypt + 1) " - . "WHERE account_id = " . (int)$this->accountId; + $query = 'UPDATE accounts SET account_countDecrypt = (account_countDecrypt + 1) WHERE account_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['id'] = $this->accountId; - return true; + return DB::getQuery($query, __FUNCTION__, $data); } /** @@ -712,18 +833,25 @@ class SP_Account $userIsAdminApp = $_SESSION['uisadminapp']; $userIsAdminAcc = $_SESSION['uisadminacc']; + $data = null; + if (!$userIsAdminApp && !$userIsAdminAcc) { - $query = "SELECT COUNT(DISTINCT account_id) as numacc " - . "FROM accounts " - . "LEFT JOIN accGroups ON account_id = accgroup_accountId " - . "WHERE account_userGroupId = " . (int)$userGroupId . " " - . "OR account_userId = " . (int)$userId . " " - . "OR accgroup_groupId = " . (int)$userGroupId; + $query = 'SELECT COUNT(DISTINCT account_id) as numacc ' + . 'FROM accounts ' + . 'LEFT JOIN accGroups ON account_id = accgroup_accountId ' + . 'WHERE account_userGroupId = :userGroupId ' + . 'OR account_userId = :userId ' + . 'OR accgroup_groupId = :groupId'; + + $data['userGroupId'] = $userGroupId; + $data['groupId'] = $userGroupId; + $data['userId'] = $userId; + } else { - $query = "SELECT COUNT(account_id) as numacc FROM accounts"; + $query = "SELECT COUNT(*) as numacc FROM accounts"; } - $queryRes = DB::getResults($query, __FUNCTION__); + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -736,13 +864,13 @@ class SP_Account * Actualiza las claves de todas las cuentas con la nueva clave maestra. * * @param string $currentMasterPass con la clave maestra actual - * @param string $newMasterPass con la nueva clave maestra + * @param string $newMasterPass con la nueva clave maestra * @return bool */ public function updateAllAccountsMPass($currentMasterPass, $newMasterPass) { $accountsOk = array(); - $userId = $_SESSION["uid"]; + $userId = $_SESSION['uid']; $errorCount = 0; $demoEnabled = SP_Util::demoIsEnabled(); @@ -778,6 +906,12 @@ class SP_Account continue; } + if (strlen($account->account_IV) < 32){ + $errorCount++; + $message['text'][] = _('IV de encriptación incorrecto') . " (" . $account->account_id . ")"; + continue; + } + $decryptedPass = SP_Crypt::getDecrypt($account->account_pass, $currentMasterPass, $account->account_IV); $this->accountPass = SP_Crypt::mkEncrypt($decryptedPass, $newMasterPass); $this->accountIV = SP_Crypt::$strInitialVector; @@ -789,8 +923,10 @@ class SP_Account if (!$this->updateAccountPass(true)) { $errorCount++; - $message['text'][] = _('Fallo al actualizar la clave de la cuenta') . "(" . $this->accountId . ")"; + $message['text'][] = _('Fallo al actualizar la clave de la cuenta') . '(' . $this->accountId . ')'; + continue; } + $accountsOk[] = $this->accountId; } @@ -801,7 +937,7 @@ class SP_Account } if ($accountsOk) { - $message['text'][] = _('Cuentas actualizadas:') . ": " . implode(',', $accountsOk); + $message['text'][] = _('Cuentas actualizadas') . ': ' . implode(',', $accountsOk); SP_Log::wrLogInfo($message); $message['text'] = array(); } @@ -824,17 +960,9 @@ class SP_Account */ private function getAccountsPassData() { - $query = "SELECT account_id," - . "account_pass," - . "account_IV " - . "FROM accounts"; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $query = 'SELECT account_id, account_pass, account_IV FROM accounts'; - if ($queryRes === false) { - return false; - } - - return $queryRes; + return DB::getResults($query, __FUNCTION__); } /** @@ -858,14 +986,20 @@ class SP_Account } } - $query = "UPDATE accounts SET " - . "account_pass = '" . DB::escape($this->accountPass) . "'," - . "account_IV = '" . DB::escape($this->accountIV) . "'," - . "account_userEditId = " . (int)$this->accountUserEditId . "," - . "account_dateEdit = NOW() " - . "WHERE account_id = " . (int)$this->accountId; + $query = 'UPDATE accounts SET ' + . 'account_pass = :accountPass,' + . 'account_IV = :accountIV,' + . 'account_userEditId = :accountUserEditId,' + . 'account_dateEdit = NOW() ' + . 'WHERE account_id = :accountId'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['accountPass'] = $this->accountPass; + $data['accountIV'] = $this->accountIV; + $data['accountUserEditId'] = $this->accountUserEditId; + $data['accountId'] = $this->accountId; + + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -876,8 +1010,8 @@ class SP_Account $this->getAccountInfoById($accountInfo); $message['action'] = _('Modificar Clave'); - $message['text'][] = SP_Html::strongText(_('Cliente') . ": ") . $this->cacheParams['customer_name']; - $message['text'][] = SP_Html::strongText(_('Cuenta') . ": ") . $this->cacheParams['account_name'] . " ($this->accountId)"; + $message['text'][] = SP_Html::strongText(_('Cliente') . ': ') . $this->cacheParams['customer_name']; + $message['text'][] = SP_Html::strongText(_('Cuenta') . ': ') . $this->cacheParams['account_name'] . " ($this->accountId)"; SP_Log::wrLogInfo($message); SP_Common::sendEmail($message); @@ -890,8 +1024,8 @@ class SP_Account * Actualiza las claves de todas las cuentas en el histórico con la nueva clave maestra. * * @param string $currentMasterPass con la clave maestra actual - * @param string $newMasterPass con la nueva clave maestra - * @param string $newHash con el nuevo hash de la clave maestra + * @param string $newMasterPass con la nueva clave maestra + * @param string $newHash con el nuevo hash de la clave maestra * @return bool */ public function updateAllAccountsHistoryMPass($currentMasterPass, $newMasterPass, $newHash) @@ -931,7 +1065,13 @@ class SP_Account if (!$this->checkAccountMPass($account->acchistory_id)) { $errorCount++; - $message['text'][] = _('La clave maestra del registro no coincide') . " (" . $account->acchistory_id . ")"; + $message['text'][] = _('La clave maestra del registro no coincide') . ' (' . $account->acchistory_id . ')'; + continue; + } + + if (strlen($account->acchistory_IV) < 32){ + $errorCount++; + $message['text'][] = _('IV de encriptación incorrecto') . ' (' . $account->acchistory_id . ')'; continue; } @@ -947,7 +1087,8 @@ class SP_Account if (!$this->updateAccountHistoryPass($account->acchistory_id, $newHash)) { $errorCount++; - $message['text'][] = _('Fallo al actualizar la clave del histórico') . " (" . $account->acchistory_id . ")"; + $message['text'][] = _('Fallo al actualizar la clave del histórico') . ' (' . $account->acchistory_id . ')'; + continue; } $idOk[] = $account->acchistory_id; @@ -960,7 +1101,7 @@ class SP_Account } if ($idOk) { - $message['text'][] = _('Registros actualizados:') . ": " . implode(',', $idOk); + $message['text'][] = _('Registros actualizados') . ': ' . implode(',', $idOk); SP_Log::wrLogInfo($message); $message['text'] = array(); } @@ -982,17 +1123,11 @@ class SP_Account */ private function getAccountsHistoryPassData() { - $query = "SELECT acchistory_id," - . "acchistory_pass," - . "acchistory_IV " - . "FROM accHistory"; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $query = 'SELECT acchistory_id, acchistory_pass, acchistory_IV FROM accHistory'; - if ($queryRes === false) { - return false; - } + DB::setReturnArray(); - return $queryRes; + return DB::getResults($query, __FUNCTION__); } /** @@ -1001,48 +1136,39 @@ class SP_Account * @param int $id opcional, con el Id del registro a comprobar * @return bool */ - public function checkAccountMPass($id = NULL) + public function checkAccountMPass($id = null) { - if (is_null($id)) { - $id = $this->accountId; - } + $query = 'SELECT acchistory_mPassHash ' . + 'FROM accHistory ' . + 'WHERE acchistory_id = :id AND acchistory_mPassHash = :mPassHash'; - $query = "SELECT acchistory_mPassHash " - . "FROM accHistory " - . "WHERE acchistory_id = " . (int)$id; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = (is_null($id)) ? $this->accountId : $id; + $data['mPassHash'] = SP_Config::getConfigValue('masterPwd'); - if ($queryRes === false) { - return false; - } - - if ($queryRes->acchistory_mPassHash != SP_Config::getConfigValue('masterPwd')) { - return false; - } - - return true; + return (DB::getResults($query, __FUNCTION__, $data) !== false); } /** * Actualiza la clave del histórico de una cuenta en la BBDD. * - * @param int $id con el id del registro a actualizar + * @param int $id con el id del registro a actualizar * @param string $newHash con el hash de la clave maestra * @return bool */ public function updateAccountHistoryPass($id, $newHash) { - $query = "UPDATE accHistory SET " - . "acchistory_pass = '" . DB::escape($this->accountPass) . "'," - . "acchistory_IV = '" . DB::escape($this->accountIV) . "'," - . "acchistory_mPassHash = '" . DB::escape($newHash) . "' " - . "WHERE acchistory_id = " . (int)$id; + $query = 'UPDATE accHistory SET ' + . 'acchistory_pass = :accountPass,' + . 'acchistory_IV = :accountIV,' + . 'acchistory_mPassHash = :newHash ' + . 'WHERE acchistory_id = :id'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['accountPass'] = $this->accountPass; + $data['accountIV'] = $this->accountIV; + $data['newHash'] = $newHash; + $data['id'] = $id; - return true; + return DB::getQuery($query, __FUNCTION__, $data); } /** @@ -1081,19 +1207,19 @@ class SP_Account } } - if ( ! empty($this->accountModHash) ){ - $hashItems = $this->accountModHash.(int)$users.(int)$groups; + if (!empty($this->accountModHash)) { + $hashItems = $this->accountModHash . (int)$users . (int)$groups; //error_log("HASH MySQL: ".$hashItems); - } else{ - $hashItems = $this->accountName. - $this->accountCategoryId. - $this->accountCustomerId. - $this->accountLogin. - $this->accountUrl. - $this->accountNotes. - $this->accountOtherUserEdit. - $this->accountOtherGroupEdit. - (int)$users. + } else { + $hashItems = $this->accountName . + $this->accountCategoryId . + $this->accountCustomerId . + $this->accountLogin . + $this->accountUrl . + $this->accountNotes . + $this->accountOtherUserEdit . + $this->accountOtherGroupEdit . + (int)$users . (int)$groups; //error_log("HASH PHP: ".$hashItems); } @@ -1124,6 +1250,7 @@ class SP_Account /** * Obtiene el listado usuarios con acceso a una cuenta. + * Lo almacena en la cache de sesión como array de cuentas * * @return array Con los registros con id de cuenta como clave e id de usuario como valor */ @@ -1131,33 +1258,25 @@ class SP_Account { $accId = ($this->accountIsHistory && $this->accountParentId) ? $this->accountParentId : $this->accountId; - if (!is_array($this->accountCacheUsersId)) { - //error_log('Users cache MISS'); - $this->accountCacheUsersId = array($accId => array()); - } else { - if (array_key_exists($accId, $this->accountCacheUsersId)) { - //error_log('Users cache HIT'); - return $this->accountCacheUsersId[$accId]; - } + $cacheUsers = &$_SESSION['cache']['usersId']; + + if (!is_array($cacheUsers)) { + $cacheUsers = array($accId => array(), 'expires' => 0); } - //error_log('Users cache MISS '.$accId); - - $users = SP_Users::getUsersForAccount($accId); - - if (!is_array($users)) { - return array(); + if (!isset($cacheUsers[$accId]) + || time() > $cacheUsers['expires']) + { + $cacheUsers[$accId] = SP_Users::getUsersForAccount($accId); + $cacheUsers['expires'] = time() + 300; } - foreach ($users as $user) { - $this->accountCacheUsersId[$accId][] = $user->accuser_userId; - } - - return $this->accountCacheUsersId[$accId]; + return $cacheUsers[$accId]; } /** * Obtiene el listado de grupos secundarios de una cuenta. + * Lo almacena en la cache de sesión como array de cuentas * * @return array con los registros con id de cuenta como clave e id de grupo como valor */ @@ -1165,28 +1284,20 @@ class SP_Account { $accId = ($this->accountIsHistory && $this->accountParentId) ? $this->accountParentId : $this->accountId; - if (!is_array($this->accountCacheUserGroupsId)) { + $cacheUserGroups = &$_SESSION['cache']['userGroupsId']; + + if (!is_array($cacheUserGroups)) { //error_log('Groups cache NO_INIT'); - $this->accountCacheUserGroupsId = array($accId => array()); - } else { - if (array_key_exists($accId, $this->accountCacheUserGroupsId)) { - //error_log('Groups cache HIT'); - return $this->accountCacheUserGroupsId[$accId]; - } + $cacheUserGroups = array($accId => array(), 'expires' => 0); } - //error_log('Groups cache MISS'); - - $groups = SP_Groups::getGroupsForAccount($accId); - - if (!is_array($groups)) { - return array(); + if (!isset($cacheUserGroups[$accId]) + || time() > $cacheUserGroups['expires']) + { + $cacheUserGroups[$accId] = SP_Groups::getGroupsForAccount($accId); + $cacheUserGroups['expires'] = time() + 300; } - foreach ($groups as $group) { - $this->accountCacheUserGroupsId[$accId][] = $group->accgroup_groupId; - } - - return $this->accountCacheUserGroupsId[$accId]; + return $cacheUserGroups[$accId]; } } \ No newline at end of file diff --git a/inc/auth.class.php b/inc/auth.class.php index 7ddef49f..18217f00 100644 --- a/inc/auth.class.php +++ b/inc/auth.class.php @@ -152,22 +152,16 @@ class SP_Auth } } - $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"; + $query = 'SELECT user_login, user_pass ' + . 'FROM usrData ' + . 'WHERE user_login = :login AND user_isMigrate = 0 ' + . 'AND user_pass = SHA1(CONCAT(user_hashSalt, :pass)) LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['login'] = $userLogin; + $data['pass'] = $userPass; - if (count(DB::$last_result) == 0) { - return false; - } - - return true; + return (DB::getQuery($query, __FUNCTION__, $data) === true && DB::$last_num_rows === 1); +// return ($db->getFullRowCount($query) === 1); } /** diff --git a/inc/backup.class.php b/inc/backup.class.php index 174a33de..1fb2abdb 100644 --- a/inc/backup.class.php +++ b/inc/backup.class.php @@ -105,10 +105,14 @@ class SP_Backup $sqlOut .= $txtCreate->{'Create Table'} . ';' . PHP_EOL . PHP_EOL; fwrite($handle, $sqlOut); - // Consulta para obtener los registros de la tabla - $queryRes = DB::getResults('SELECT * FROM ' . $tableName, __FUNCTION__, false, true); + DB::setUnbuffered(); - while ($row = $queryRes->fetch_row()) { + // Consulta para obtener los registros de la tabla + $queryRes = DB::getResults('SELECT * FROM ' . $tableName, __FUNCTION__); + + $numColumns = $queryRes->columnCount(); + + while ($row = $queryRes->fetch(PDO::FETCH_NUM)) { fwrite($handle, 'INSERT INTO `' . $tableName . '` VALUES('); $field = 1; @@ -116,10 +120,10 @@ class SP_Backup if (is_numeric($value)) { fwrite($handle, $value); } else { - fwrite($handle, '"' . DB::escape($value) . '"'); + fwrite($handle, DB::escape($value)); } - if ($field < $queryRes->field_count) { + if ($field < $numColumns) { fwrite($handle, ','); } @@ -128,6 +132,8 @@ class SP_Backup fwrite($handle, ');' . PHP_EOL); } fwrite($handle, PHP_EOL . PHP_EOL); + + DB::setUnbuffered(false); } $sqlOut = '--' . PHP_EOL; diff --git a/inc/category.class.php b/inc/category.class.php index b242f1a0..10bdc14a 100644 --- a/inc/category.class.php +++ b/inc/category.class.php @@ -43,20 +43,17 @@ class SP_Category */ public static function getCategoryIdByName($categoryName) { - $query = "SELECT category_id " - . "FROM categories " - . "WHERE category_name = '" . DB::escape($categoryName) . "' LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT category_id FROM categories WHERE category_name = :name LIMIT 1'; - if ($queryRes === false) { + $data['name'] = $categoryName; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); + + if ($queryRes === false || DB::$last_num_rows === 0) { return false; } - if (DB::$num_rows == 0) { - return false; - } else { - return $queryRes->category_id; - } + return $queryRes->category_id; } /** @@ -66,11 +63,12 @@ class SP_Category */ public static function addCategory() { - $query = "INSERT INTO categories " - . "SET category_name = '" . DB::escape(self::$categoryName) . "'," - . "category_description = '" . DB::escape(self::$categoryDescription) . "'"; + $query = 'INSERT INTO categories SET category_name = :name ,category_description = :description'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$categoryName; + $data['description'] = self::$categoryDescription; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -91,28 +89,20 @@ class SP_Category * @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) . "'"; + $query = 'SELECT category_id FROM categories WHERE category_name = :name'; } else { - $query = "SELECT category_id " - . "FROM categories " - . "WHERE category_name = '" . DB::escape(self::$categoryName) . "' AND category_id <> " . $id; + $query = 'SELECT category_id FROM categories WHERE category_name = :name AND category_id <> :id'; + + $data['id'] = $id; } - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['name'] = self::$categoryName; - if (count(DB::$last_result) >= 1) { - return false; - } - - return true; + return (DB::getQuery($query, __FUNCTION__, $data) === false || DB::$last_num_rows >= 1); } /** @@ -125,10 +115,11 @@ class SP_Category { $categoryName = self::getCategoryNameById($id); - $query = "DELETE FROM categories " - . "WHERE category_id = " . (int)$id . " LIMIT 1"; + $query = 'DELETE FROM categories WHERE category_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $id; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -149,10 +140,11 @@ class SP_Category */ public static function getCategoryNameById($id) { - $query = "SELECT category_name " - . "FROM categories " - . "WHERE category_id = " . (int)$id; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT category_name FROM categories WHERE category_id = :id LIMIT 1'; + + $data['id'] = $id; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -171,12 +163,15 @@ class SP_Category { $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"; + $query = 'UPDATE categories ' + . 'SET category_name = :name, category_description = :description ' + . 'WHERE category_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$categoryName; + $data['description'] = self::$categoryDescription; + $data['id'] = $id; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -223,20 +218,22 @@ class SP_Category * @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) + public static function getCategories($id = null, $retAssocArray = false) { - $query = "SELECT category_id," - . "category_name," - . "category_description " - . "FROM categories "; + $query = 'SELECT category_id, category_name,category_description FROM categories '; + + $data = null; if (!is_null($id)) { - $query .= "WHERE category_id = " . (int)$id . " LIMIT 1"; + $query .= "WHERE category_id = :id LIMIT 1"; + $data['id'] = $id; } else { $query .= "ORDER BY category_name"; } - $queryRes = DB::getResults($query, __FUNCTION__, true); + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return array(); @@ -286,17 +283,13 @@ class SP_Category */ private static function getCategoriesInAccounts($id) { - $query = "SELECT COUNT(*) as uses " - . "FROM accounts " - . "WHERE account_categoryId = " . (int)$id; + $query = 'SELECT account_id FROM accounts WHERE account_categoryId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $id; - if ($queryRes === false) { - return false; - } - - return $queryRes->uses; + $db = new DB(); + $db->setParamData($data); + return $db->getFullRowCount($query); } } diff --git a/inc/config.class.php b/inc/config.class.php index 614afeba..ac8c853f 100644 --- a/inc/config.class.php +++ b/inc/config.class.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -56,10 +56,11 @@ class SP_Config */ public static function getConfigValue($param) { - $query = "SELECT config_value " - . "FROM config " - . "WHERE config_parameter = '$param'"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT config_value FROM config WHERE config_parameter = :parameter LIMIT 1'; + + $data['parameter'] = $param; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -75,10 +76,9 @@ class SP_Config */ public static function getConfig() { - $query = "SELECT config_parameter," - . "config_value " - . "FROM config"; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $query = 'SELECT config_parameter, config_value FROM config'; + + $queryRes = DB::getResults($query, __FUNCTION__); if ($queryRes === false) { return false; @@ -99,21 +99,19 @@ class SP_Config */ public static function writeConfig($mkInsert = false) { - foreach (self::$arrConfigValue as $key => $value) { - $key = DB::escape($key); - $value = DB::escape($value); - + foreach (self::$arrConfigValue as $param => $value) { if ($mkInsert) { - $query = "INSERT INTO config " - . "VALUES ('$key','$value') " - . "ON DUPLICATE KEY UPDATE config_value = '$value' "; + $query = 'INSERT INTO config VALUES (:param,:value) ON DUPLICATE KEY UPDATE config_value = :valuedup'; + + $data['valuedup'] = $value; } else { - $query = "UPDATE config SET " - . "config_value = '$value' " - . "WHERE config_parameter = '$key'"; + $query = 'UPDATE config SET config_value = :value WHERE config_parameter = :param'; } - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['param'] = $param; + $data['value'] = $value; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } } @@ -137,11 +135,15 @@ class SP_Config 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 = :param," + . "config_value = :value " + . "ON DUPLICATE KEY UPDATE config_value = :valuedup"; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['param'] = $param; + $data['value'] = $value; + $data['valuedup'] = $value; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -170,10 +172,9 @@ class SP_Config return true; } - $query = "SELECT config_parameter," - . "config_value " - . "FROM config"; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $query = 'SELECT config_parameter, config_value FROM config'; + + $queryRes = DB::getResults($query, __FUNCTION__); if ($queryRes === false) { return false; @@ -196,7 +197,7 @@ class SP_Config /** * Obtiene un valor de configuración desde el archivo config.php * - * @param string $key clave + * @param string $key clave * @param string $default = null valor por defecto * @return string el valor o $default */ @@ -220,7 +221,7 @@ class SP_Config return true; } - $configFile = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'config'. DIRECTORY_SEPARATOR . 'config.php'; + $configFile = SP_Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'; if (!file_exists($configFile)) { return false; @@ -340,7 +341,7 @@ class SP_Config self::setValue('ldap_userattr', ''); self::setValue('mail_server', ''); self::setValue('mail_from', ''); - self::setValue('site_lang', str_replace('.utf8','',SP_Init::$LANG)); + self::setValue('site_lang', str_replace('.utf8', '', SP_Init::$LANG)); self::setValue('session_timeout', '300'); self::setValue('account_link', 1); self::setValue('account_count', 12); @@ -351,7 +352,7 @@ class SP_Config * Esta función establece el valor y reescribe config.php. Si el archivo * no se puede escribir, devolverá false. * - * @param string $key clave + * @param string $key clave * @param string $value valor * @return bool */ diff --git a/inc/customer.class.php b/inc/customer.class.php index 0d9e774a..6d8b8c6c 100644 --- a/inc/customer.class.php +++ b/inc/customer.class.php @@ -44,11 +44,12 @@ class SP_Customer */ public static function addCustomer() { - $query = "INSERT INTO customers " - . "SET customer_name = '" . DB::escape(self::$customerName) . "'," - . "customer_hash = '" . self::mkCustomerHash() . "'"; + $query = 'INSERT INTO customers SET customer_name = :name,customer_hash = :hash'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$customerName; + $data['hash'] = self::mkCustomerHash(); + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -92,12 +93,17 @@ class SP_Customer $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; + . "SET customer_name = :name," + . "customer_description = :description," + . "customer_hash = :hash " + . "WHERE customer_id = :id"; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$customerName; + $data['description'] = self::$customerDescription; + $data['hash'] = self::mkCustomerHash(); + $data['id'] = $id; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -120,10 +126,11 @@ class SP_Customer { $customerName = self::getCustomerById($id); - $query = "DELETE FROM customers " - . "WHERE customer_id = " . (int)$id . " LIMIT 1"; + $query = 'DELETE FROM customers WHERE customer_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $id; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -144,10 +151,11 @@ class SP_Customer */ public static function getCustomerById($id) { - $query = "SELECT customer_name " - . "FROM customers " - . "WHERE customer_id = " . (int)$id . " LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT customer_name FROM customers WHERE customer_id = :id LIMIT 1'; + + $data['id'] = $id; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -165,24 +173,18 @@ class SP_Customer public static function checkDupCustomer($id = NULL) { if ($id === NULL) { - $query = "SELECT customer_id " - . "FROM customers " - . "WHERE customer_hash = '" . self::mkCustomerHash() . "'"; + $query = 'SELECT customer_id FROM customers WHERE customer_hash = :hash'; } else { - $query = "SELECT customer_id " - . "FROM customers " - . "WHERE customer_hash = '" . self::mkCustomerHash() . "' AND customer_id <> " . $id; + $query = 'SELECT customer_id FROM customers WHERE customer_hash = :hash AND customer_id <> :id'; + + $data['id'] = $id; } - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['hash'] = self::mkCustomerHash(); - if (count(DB::$last_result) >= 1) { - return false; - } + return (DB::getQuery($query, __FUNCTION__, $data) === false || DB::$last_num_rows >= 1); - return true; +// return ($db->getFullRowCount($query) >= 1); } /** @@ -192,10 +194,11 @@ class SP_Customer */ public static function getCustomerByName() { - $query = "SELECT customer_id " - . "FROM customers " - . "WHERE customer_hash = '" . self::mkCustomerHash() . "' LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT customer_id FROM customers WHERE customer_hash = :hash LIMIT 1'; + + $data['hash'] = self::mkCustomerHash(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -238,20 +241,21 @@ class SP_Customer * @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) + public static function getCustomers($customerId = null, $retAssocArray = false) { - $query = "SELECT customer_id," - . "customer_name, " - . "customer_description " - . "FROM customers "; + $query = 'SELECT customer_id, customer_name, customer_description FROM customers '; + $data = null; if (!is_null($customerId)) { - $query .= "WHERE customer_id = " . (int)$customerId . " LIMIT 1"; + $query .= "WHERE customer_id = :id LIMIT 1"; + $data['id'] = $customerId; } else { $query .= "ORDER BY customer_name"; } - $queryRes = DB::getResults($query, __FUNCTION__, true); + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return array(); @@ -287,20 +291,16 @@ class SP_Customer * Obtener el número de cuentas que usan un cliente. * * @param int $id con el Id del cliente a consultar - * @return false|int con el número total de cuentas + * @return int con el número total de cuentas */ private static function getCustomerInAccounts($id) { - $query = "SELECT COUNT(*) as uses " - . "FROM accounts " - . "WHERE account_customerId = " . (int)$id; + $query = 'SELECT account_id FROM accounts WHERE account_customerId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $id; - if ($queryRes === false) { - return false; - } + DB::getQuery($query, __FUNCTION__, $data); - return $queryRes->uses; + return DB::$last_num_rows; } } diff --git a/inc/db.class.php b/inc/db.class.php index 468db306..4b7dfdfa 100644 --- a/inc/db.class.php +++ b/inc/db.class.php @@ -3,8 +3,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -26,106 +26,145 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo')); +/** + * Class DBConnectionFactory + * + * Esta clase se encarga de crear las conexiones a la BD + */ +class DBConnectionFactory +{ + private static $factory; + private $db; + + public static function getFactory() + { + if (!self::$factory) { +// FIXME +// error_log('NEW FACTORY'); + self::$factory = new DBConnectionFactory(); + } + + return self::$factory; + } + + /** + * Realizar la conexión con la BBDD. + * Esta función utiliza PDO para conectar con la base de datos. + * + * @throws Exception + * @return object|bool + */ + + public function getConnection() + { + if (!$this->db) { +// FIXME +// error_log('NEW DB_CONNECTION'); + $isInstalled = SP_Config::getValue('installed'); + + $dbhost = SP_Config::getValue("dbhost"); + $dbuser = SP_Config::getValue("dbuser"); + $dbpass = SP_Config::getValue("dbpass"); + $dbname = SP_Config::getValue("dbname"); + + if (empty($dbhost) || empty($dbuser) || empty($dbpass) || empty($dbname)) { + if ($isInstalled) { + SP_Init::initError(_('No es posible conectar con la BD'), _('Compruebe los datos de conexión')); + } else { + throw new SPDatabaseException(_('No es posible conectar con la BD'), 1); + } + } + + try { + $dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname . ';charset=utf8'; +// $this->db = new PDO($dsn, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true)); + $this->db = new PDO($dsn, $dbuser, $dbpass); + } catch (PDOException $e) { + if ($isInstalled) { + if ($this->db->connect_errno === 1049) { + SP_Config::setValue('installed', '0'); + } + + SP_Init::initError(_('No es posible conectar con la BD'), 'Error ' . $this->db->errorCode() . ': ' . $this->db->errorInfo()); + } else { + throw new SPDatabaseException($e->getMessage(), $e->getCode()); + } + } + } + + $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + return $this->db; + } +} + +/** + * Class SPDatabaseException + * + * Clase para excepciones de BD de sysPass + */ +class SPDatabaseException extends Exception +{ +} + /** * Esta clase es la encargada de realizar las operaciones con la BBDD de sysPass. */ class DB { - static $last_result; - static $affected_rows; - static $lastId; - static $txtError; - static $numError; - static $num_rows; - static $num_fields; - private static $_db; + static $txtError = ''; + static $numError = 0; + static $last_num_rows = 0; + static $lastId = null; + private static $retArray = false; + private static $unbuffered = false; + private static $fullRowCount = false; + + public $num_rows = 0; + public $num_fields = 0; + private $last_result = null; + private $querySource; + + /** + * Datos para el objeto PDOStatement + * + * @var array + */ + private $stData; /** * Comprobar que la base de datos existe. * * @return bool + * @throws SPDatabaseException */ public static function checkDatabaseExist() { - if (!self::connection()) { - return false; - } + try { + $db = DBConnectionFactory::getFactory()->getConnection(); - $query = 'SELECT COUNT(*) ' - . 'FROM information_schema.tables' - . " WHERE table_schema='" . SP_Config::getValue("dbname") . "' " - . "AND table_name = 'usrData';"; + $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; - } - - /** - * Realizar la conexión con la BBDD. - * Esta función utiliza mysqli para conectar con la base de datos. - * Guarda el objeto creado en la variable $_db de la clase - * - * @return bool - */ - private static function connection() - { - if (is_object(self::$_db)) { - return true; - } - - $isInstalled = SP_Config::getValue('installed'); - - $dbhost = SP_Config::getValue("dbhost"); - $dbuser = SP_Config::getValue("dbuser"); - $dbpass = SP_Config::getValue("dbpass"); - $dbname = SP_Config::getValue("dbname"); - - if (empty($dbhost) || empty($dbuser) || empty($dbpass) || empty($dbname)) { - if ($isInstalled) { - SP_Init::initError(_('No es posible conectar con la BD'), _('Compruebe los datos de conexión')); - } else { - return false; + if ($db->query($query)->fetchColumn() !== 0) { + return true; } + } catch (PDOException $e) { + throw new SPDatabaseException($e->getMessage(), $e->getCode()); } - self::$_db = @new mysqli($dbhost, $dbuser, $dbpass, $dbname); - - if (!is_object(self::$_db) || self::$_db->connect_errno) { - if ($isInstalled) { - if (self::$_db->connect_errno === 1049) { - SP_Config::setValue('installed', '0'); - } - - SP_Init::initError(_('No es posible conectar con la BD'), 'Error ' . self::$_db->connect_errno . ': ' . self::$_db->connect_error); - } else { - return false; - } - } - - if (!self::$_db->set_charset("utf8")) { - SP_Init::initError(_('No es posible conectar con la BD'), 'Error ' . self::$_db->connect_errno . ': ' . self::$_db->connect_error); - } - - return true; + return false; } /** * 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 $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 + * @param array $arrFilter con las columnas a filtrar + * @param array $arrOrder con el orden de las columnas * @return false|array con los valores del select con el Id como clave y el nombre como valor */ public static function getValuesForSelect($tblName, $tblColId, $tblColName, $arrFilter = NULL, $arrOrder = NULL) @@ -138,7 +177,9 @@ class DB $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); + + self::setReturnArray(); + $queryRes = self::getResults($query, __FUNCTION__); if ($queryRes === false) { return false; @@ -153,103 +194,217 @@ class DB return $arrValues; } + public static function setReturnArray() + { + self::$retArray = true; + } + /** * Obtener los resultados de una consulta. * - * @param string $query con la consulta a realizar + * @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 - * @param bool $unbuffered devolver el resultado registro a registro + * @param array $data con los datos de la consulta * @return bool|array devuelve bool si hay un error. Devuelve array con el array de registros devueltos */ - public static function getResults($query, $querySource, $retArray = false, $unbuffered = false) + public static function getResults($query, $querySource, &$data = null) { - if ($query) { - self::doQuery($query, $querySource, $unbuffered); - } - - if (self::$numError || self::$num_rows === 0) { + if (empty($query)) { + self::resetVars(); return false; } - if (is_null(self::$numError) && count(self::$last_result) === 0) { - return true; + try { + $db = new DB(); + $db->querySource = $querySource; + $db->stData = $data; + $doQuery = $db->doQuery($query, $querySource, self::$unbuffered); + } catch (SPDatabaseException $e) { + $db->logDBException($query, $e->getMessage(), $e->getCode()); + return false; } - if ($retArray === true && is_object(self::$last_result)) { - return array(self::$last_result); + if (self::$unbuffered && is_object($doQuery) && get_class($doQuery) == "PDOStatement"){ + return $doQuery; } - return self::$last_result; + DB::$last_num_rows = (self::$fullRowCount === false) ? $db->num_rows : $db->getFullRowCount($query); + + if ($db->num_rows == 0) { + self::resetVars(); + return false; + } + + if ($db->num_rows == 1 && self::$retArray === false) { + self::resetVars(); + return $db->last_result[0]; + } + + self::resetVars(); + return $db->last_result; } /** * Realizar una consulta a la BBDD. * - * @param string $query con la consulta a realizar + * @param string $query con la consulta a realizar * @param string $querySource con el nombre de la función que realiza la consulta - * @param bool $unbuffered realizar la consulta para obtener registro a registro + * @param bool $unbuffered realizar la consulta para obtener registro a registro * @return false|int devuelve bool si hay un error. Devuelve int con el número de registros + * @throws SPDatabaseException */ - public static function doQuery($query, $querySource, $unbuffered = false) + public function doQuery(&$query, $querySource, $unbuffered = false) { - if (!self::connection()) { - return false; - } - - $isSelect = preg_match("/^.*(select|show)\s/i", $query); + $isSelect = preg_match("/^(select|show)\s/i", $query); // Limpiar valores de caché y errores - self::$last_result = array(); - self::$numError = 0; - self::$txtError = ''; + $this->last_result = array(); - // Comprobamos si la consulta debe de ser devuelta completa o por registro - if (!$unbuffered) { - $queryRes = self::$_db->query($query); - } else { - $queryRes = self::$_db->real_query($query); - } - - if (!$queryRes) { - self::$numError = self::$_db->errno; - self::$txtError = self::$_db->error; - - $message['action'] = $querySource; - $message['text'][] = self::$_db->error . '(' . self::$_db->errno . ')'; - $message['text'][] = "SQL: " . self::escape($query); - - SP_Log::wrLogInfo($message); - return false; + try { + $queryRes = $this->prepareQueryData($query); + } catch (SPDatabaseException $e) { + throw new SPDatabaseException($e->getMessage(), $e->getCode()); } if ($isSelect) { - //self::$num_rows = $queryRes->num_rows; - self::$num_rows = self::$_db->affected_rows; - if (!$unbuffered) { - self::$num_fields = self::$_db->field_count; - - if (self::$num_rows === 1) { - self::$last_result = @$queryRes->fetch_object(); - } else { - $num_row = 0; - - while ($row = @$queryRes->fetch_object()) { - self::$last_result[$num_row] = $row; - $num_row++; - } - } - - $queryRes->close(); - } else { - self::$last_result = self::$_db->use_result(); + $this->num_fields = $queryRes->columnCount(); + $this->last_result = $queryRes->fetchAll(PDO::FETCH_OBJ); + } else{ + return $queryRes; } + + $queryRes->closeCursor(); + +// $this->num_rows = $this->getFullRowCount($query); + $this->num_rows = count($this->last_result); + +// return $this->num_rows; + } + } + + /** + * Asociar los parámetros de la consulta utilizando el tipo adecuado + * + * @param &$query + * @param $isCount + * @return bool + * @throws SPDatabaseException + */ + private function prepareQueryData(&$query, $isCount = false) + { + if ($isCount === true) { + // No incluimos en el array de parámetros de posición los valores + // utilizados para LIMIT + preg_match_all('/(\?|:)/', $query, $count); + + // Indice a partir del cual no se incluyen valores + $paramMaxIndex = (count($count[1]) > 0) ? count($count[1]) : 0; } - self::$lastId = self::$_db->insert_id; + try { + $db = DBConnectionFactory::getFactory()->getConnection(); - return self::$num_rows; + if (is_array($this->stData)) { + $sth = $db->prepare($query); + $paramIndex = 0; + + foreach ($this->stData as $param => $value) { + // Si la clave es un número utilizamos marcadores de posición "?" en + // la consulta. En caso contrario marcadores de nombre + $param = (is_int($param)) ? $param + 1 : ':' . $param; + + if ($isCount === true && count($count) > 0 && $paramIndex >= $paramMaxIndex) { + continue; + } + + if ($param == 'blobcontent'){ + $sth->bindValue($param, $value, PDO::PARAM_LOB); + } elseif (is_int($value)) { + //error_log("INT: " . $param . " -> " . $value); + $sth->bindValue($param, $value, PDO::PARAM_INT); + } else { + //error_log("STR: " . $param . " -> " . $value); + $sth->bindValue($param, $value, PDO::PARAM_STR); + } + + $paramIndex++; + } + + $sth->execute(); + } else { + $sth = $db->query($query); + } + + DB::$lastId = $db->lastInsertId(); + + return $sth; + } catch (PDOException $e) { + error_log("Exception: " . $e->getMessage()); + throw new SPDatabaseException($e->getMessage()); + } + + return false; + } + + /** + * Obtener el número de filas de una consulta realizada + * + * @return int Número de files de la consulta + * @throws SPDatabaseException + */ + public function getFullRowCount(&$query) + { + if (empty($query)) { + return 0; + } + + $patterns = array('/(LIMIT|ORDER BY).*/i', '/SELECT.*FROM/i'); + $replace = array('', 'SELECT COUNT(*) FROM'); + + $query = preg_replace($patterns, $replace, $query); + + try { + $db = DBConnectionFactory::getFactory()->getConnection(); + + if (!is_array($this->stData)) { + $queryRes = $db->query($query); + $num = intval($queryRes->fetchColumn()); + } else { + if ($queryRes = $this->prepareQueryData($query, true)) { + $num = intval($queryRes->fetchColumn()); + } + } + + // FIXME + //error_log("numrows: " . $num); + + $queryRes->closeCursor(); + + return $num; + } catch (PDOException $e) { + error_log("Exception: " . $e->getMessage()); + throw new SPDatabaseException($e->getMessage()); + } + + return 0; + } + + /** + * Método para registar los eventos de BD en el log + * + * @param $query + * @param $errorMsg + * @param $errorCode + */ + private function logDBException($query, $errorMsg, $errorCode) + { + $message['action'] = $this->querySource; + $message['text'][] = $errorMsg . '(' . $errorCode . ')'; + $message['text'][] = "SQL: " . DB::escape($query); + + error_log($query); + error_log($errorMsg); } /** @@ -260,10 +415,71 @@ class DB */ public static function escape($str) { - if (self::connection()) { - return self::$_db->real_escape_string(trim($str)); - } else { + try { + $db = DBConnectionFactory::getFactory()->getConnection(); + + return $db->quote(trim($str)); + } catch (SPDatabaseException $e) { return $str; } } + + /** + * Realizar una consulta y devolver el resultado sin datos + * + * @param $query + * @param $querySource + * @param bool $unbuffered + * @return bool + */ + public static function getQuery($query, $querySource, &$data = null, $unbuffered = false) + { + if (empty($query)) { + return false; + } + + try { + $db = new DB(); + $db->querySource = $querySource; + $db->stData = $data; + $db->doQuery($query, $querySource, $unbuffered); + DB::$last_num_rows = $db->num_rows; + } catch (SPDatabaseException $e) { + $db->logDBException($query, $e->getMessage(), $e->getCode()); + + DB::$txtError = $e->getMessage(); + DB::$numError = $e->getCode(); + + return false; + } + + return true; + } + + public static function setUnbuffered($on = true) + { + self::$unbuffered = (bool)$on; + } + + public static function setFullRowCount() + { + self::$fullRowCount = true; + } + + private static function resetVars() + { + self::$unbuffered = false; + self::$fullRowCount = false; + self::$retArray = false; + } + + /** + * Establecer los parámetos de la consulta preparada + * + * @param &$data array Con los datos de los parámetros de la consulta + */ + public function setParamData(&$data) + { + $this->stData = $data; + } } diff --git a/inc/dbstructure.sql b/inc/dbstructure.sql index 5158d8cf..2e7c5e54 100644 --- a/inc/dbstructure.sql +++ b/inc/dbstructure.sql @@ -73,8 +73,8 @@ CREATE TABLE `accHistory` ( `acchistory_isModify` bit(1) DEFAULT NULL, `acchistory_isDeleted` bit(1) DEFAULT NULL, `acchistory_mPassHash` varbinary(128) NOT NULL, - `accHistory_otherUserEdit` bit(1) DEFAULT NULL, - `accHistory_otherGroupEdit` varchar(45) DEFAULT NULL, + `accHistory_otherUserEdit` bit(1) DEFAULT b'0', + `accHistory_otherGroupEdit` bit(1) DEFAULT b'0', PRIMARY KEY (`acchistory_id`), KEY `IDX_accountId` (`acchistory_accountId`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; diff --git a/inc/files.class.php b/inc/files.class.php index 3c35bad6..36738e69 100644 --- a/inc/files.class.php +++ b/inc/files.class.php @@ -38,17 +38,24 @@ class SP_Files * @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 = '" . DB::escape($fileData['name']) . "'," - . "accfile_type = '" . $fileData['type'] . "'," - . "accfile_size = '" . $fileData['size'] . "'," - . "accfile_content = '" . DB::escape($fileData['content']) . "'," - . "accfile_extension = '" . DB::escape($fileData['extension']) . "'"; + . "SET accfile_accountId = :accountId," + . "accfile_name = :name," + . "accfile_type = :type," + . "accfile_size = :size," + . "accfile_content = :blobcontent," + . "accfile_extension = :extension"; - if (DB::doQuery($query, __FUNCTION__) !== false) { + $data['accountId'] = $accountId; + $data['name'] = $fileData['name']; + $data['type'] = $fileData['type']; + $data['size'] = $fileData['size']; + $data['blobcontent'] = $fileData['content']; + $data['extension'] = $fileData['extension']; + + if (DB::getQuery($query, __FUNCTION__, $data) === true) { $message['action'] = _('Subir Archivo'); $message['text'][] = _('Cuenta') . ": " . $accountId; $message['text'][] = _('Archivo') . ": " . $fileData['name']; @@ -74,19 +81,11 @@ class SP_Files public static function fileDownload($fileId) { // Obtenemos el archivo de la BBDD - $query = "SELECT * FROM accFiles " - . "WHERE accfile_id = " . (int)$fileId . " LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + $query = 'SELECT * FROM accFiles WHERE accfile_id = :id LIMIT 1'; - if ($queryRes === false) { - return false; - } + $data['id'] = $fileId; - if (DB::$num_rows == 0) { - return false; - } - - return $queryRes; + return DB::getResults($query, __FUNCTION__, $data); } /** @@ -100,11 +99,11 @@ class SP_Files $fileInfo = self::getFileInfo($fileId); // Eliminamos el archivo de la BBDD - $query = "DELETE FROM accFiles " - . "WHERE accfile_id = " . (int)$fileId . " LIMIT 1"; - $queryRes = DB::doQuery($query, __FUNCTION__); + $query = 'DELETE FROM accFiles WHERE accfile_id = :id LIMIT 1'; - if ($queryRes !== false) { + $data['id'] = $fileId; + + if (DB::getQuery($query, __FUNCTION__, $data) === true) { $message['action'] = _('Eliminar Archivo'); $message['text'][] = _('ID') . ": " . $fileId; $message['text'][] = _('Archivo') . ": " . $fileInfo->accfile_name; @@ -132,17 +131,11 @@ class SP_Files . "accfile_size," . "accfile_type " . "FROM accFiles " - . "WHERE accfile_id = " . (int)$fileId . " LIMIT 1"; - $queryRes = DB::getResults($query, __FUNCTION__); + . "WHERE accfile_id = :id LIMIT 1"; - if ($queryRes === false) { - return false; - } + $data['id'] = $fileId; - if (DB::$num_rows === 0) { - echo _('El archivo no existe'); - return false; - } + $queryRes = DB::getResults($query, __FUNCTION__, $data); return $queryRes; } @@ -159,8 +152,13 @@ class SP_Files . "accfile_name," . "accfile_size " . "FROM accFiles " - . "WHERE accfile_accountId = " . (int)$accountId; - $queryRes = DB::getResults($query, __FUNCTION__, true); + . "WHERE accfile_accountId = :id"; + + $data['id'] = $accountId; + + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -183,20 +181,18 @@ class SP_Files * Obtener el número de archivo de una cuenta. * * @param int $accountId con el Id de la cuenta - * @return false|int con el número de archivos + * @return int con el número de archivos */ 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; + $query = 'SELECT accfile_id FROM accFiles WHERE accfile_accountId = :id'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['id'] = $accountId; - return count(DB::$last_result); + DB::getQuery($query, __FUNCTION__, $data); + + return DB::$last_num_rows; } @@ -208,13 +204,10 @@ class SP_Files */ public static function deleteAccountFiles($accountId) { - $query = "DELETE FROM accFiles " - . "WHERE accfile_accountId = " . (int)$accountId; + $query = 'DELETE FROM accFiles WHERE accfile_accountId = :id'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['id'] = $accountId; - return true; + return DB::getQuery($query, __FUNCTION__, $data); } } \ No newline at end of file diff --git a/inc/groups.class.php b/inc/groups.class.php index d2ccd473..c11f4038 100644 --- a/inc/groups.class.php +++ b/inc/groups.class.php @@ -3,8 +3,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -67,25 +67,29 @@ class SP_Groups /** * Obtener los grupos de usuarios. * - * @param int $groupId opcional, con el Id del grupo a consultar + * @param int $groupId opcional, con el Id del grupo a consultar * @param bool $returnArray opcional, si se debe de devolver un array asociativo * @return false|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 "; + $data = null; if (!is_null($groupId)) { - $query .= "WHERE usergroup_id = " . (int)$groupId . " LIMIT 1"; + $query .= "WHERE usergroup_id = :id LIMIT 1"; + $data['id'] = $groupId; } else { $query .= "ORDER BY usergroup_name"; } - $queryRes = DB::getResults($query, __FUNCTION__, true); + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -113,25 +117,15 @@ class SP_Groups $groupName = strtoupper(self::$groupName); if ($groupId) { - $query = "SELECT usergroup_name - FROM usrGroups - WHERE UPPER(usergroup_name) = '" . DB::escape($groupName) . "' - AND usergroup_id != " . (int)$groupId; + $query = "SELECT usergroup_name FROM usrGroups WHERE UPPER(usergroup_name) = :name AND usergroup_id != :id"; + $data['id'] = $groupId; } else { - $query = "SELECT usergroup_name - FROM usrGroups - WHERE UPPER(usergroup_name) = '" . DB::escape($groupName) . "'"; + $query = "SELECT usergroup_name FROM usrGroups WHERE UPPER(usergroup_name) = :name"; } - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['name'] = $groupName; - if (count(DB::$last_result) >= 1) { - return false; - } - - return true; + return (DB::getQuery($query, __FUNCTION__, $data) === false || DB::$last_num_rows >= 1); } /** @@ -141,11 +135,12 @@ class SP_Groups */ public static function addGroup() { - $query = "INSERT INTO usrGroups SET - usergroup_name = '" . DB::escape(self::$groupName) . "', - usergroup_description = '" . DB::escape(self::$groupDescription) . "'"; + $query = 'INSERT INTO usrGroups SET usergroup_name = :name, usergroup_description = :description'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$groupName; + $data['description'] = self::$groupDescription; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -169,12 +164,13 @@ class SP_Groups { $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; + $query = 'UPDATE usrGroups SET usergroup_name = :name, usergroup_description = :description WHERE usergroup_id = :id'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$groupName; + $data['description'] = self::$groupDescription; + $data['id'] = self::$groupId; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -189,6 +185,27 @@ class SP_Groups return true; } + /** + * Obtener el nombre de un grupo por a partir del Id. + * + * @param int $id con el Id del grupo + * @return false|string con el nombre del grupo + */ + public static function getGroupNameById($id) + { + $query = 'SELECT usergroup_name FROM usrGroups WHERE usergroup_id = :id LIMIT 1'; + + $data['id'] = $id; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); + + if ($queryRes === false) { + return false; + } + + return $queryRes->usergroup_name; + } + /** * Eliminar un grupo. * @@ -198,10 +215,11 @@ class SP_Groups { $groupName = self::getGroupNameById(self::$groupId); - $query = "DELETE FROM usrGroups " - . "WHERE usergroup_id = " . (int)self::$groupId . " LIMIT 1"; + $query = 'DELETE FROM usrGroups WHERE usergroup_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = self::$groupId; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -231,41 +249,33 @@ class SP_Groups /** * Obtener el número de usuarios que usan un grupo. * - * @return false|int con el número total de cuentas + * @return int con el número total de cuentas */ private static function getGroupInUsers() { - $query = "SELECT COUNT(*) as uses " - . "FROM usrData " - . "WHERE user_groupId = " . (int)self::$groupId; + $query = 'SELECT user_groupId FROM usrData WHERE user_groupId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = self::$groupId; - if ($queryRes === false) { - return false; - } + DB::getQuery($query, __FUNCTION__, $data); - return $queryRes->uses; + return DB::$last_num_rows; } /** * Obtener el número de cuentas que usan un grupo como primario. * - * @return false|int con el número total de cuentas + * @return int con el número total de cuentas */ private static function getGroupInAccounts() { - $query = "SELECT COUNT(*) as uses " - . "FROM accounts " - . "WHERE account_userGroupId = " . (int)self::$groupId; + $query = 'SELECT account_userGroupId FROM accounts WHERE account_userGroupId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = self::$groupId; - if ($queryRes === false) { - return false; - } + DB::getQuery($query, __FUNCTION__, $data); - return $queryRes->uses; + return DB::$last_num_rows; } /** @@ -275,38 +285,13 @@ class SP_Groups */ private static function getGroupInAccountsSec() { - $query = "SELECT COUNT(*) as uses " - . "FROM accGroups " - . "WHERE accgroup_groupId = " . (int)self::$groupId; + $query = 'SELECT accgroup_groupId FROM accGroups WHERE accgroup_groupId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = self::$groupId; - if ($queryRes === false) { - return false; - } + DB::getQuery($query, __FUNCTION__, $data); - return $queryRes->uses; - } - - /** - * Obtener el nombre de un grupo por a partir del Id. - * - * @param int $id con el Id del grupo - * @return false|string con el nombre del grupo - */ - public static function getGroupNameById($id) - { - $query = "SELECT usergroup_name " - . "FROM usrGroups " - . "WHERE usergroup_id = " . (int)$id . " LIMIT 1"; - - $queryRes = DB::getResults($query, __FUNCTION__); - - if ($queryRes === false) { - return false; - } - - return $queryRes->usergroup_name; + return DB::$last_num_rows; } /** @@ -317,13 +302,17 @@ class SP_Groups */ 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; + $query = 'SELECT usergroup_id,' + . 'usergroup_name ' + . 'FROM accGroups ' + . 'JOIN usrGroups ON accgroup_groupId = usergroup_id ' + . 'WHERE accgroup_accountId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $data['id'] = $accountId; + + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -341,7 +330,7 @@ class SP_Groups /** * Actualizar la asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta + * @param int $accountId con el Id de la cuenta * @param array $groupsId con los grupos de la cuenta * @return bool */ @@ -357,72 +346,62 @@ class SP_Groups /** * Eliminar la asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta + * @param int $accountId con el Id de la cuenta * @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) . ')'; + array_map('intval', $groupsId); + + $queryExcluded = 'AND accgroup_groupId NOT IN (' . implode(',', $groupsId) . ')'; } - $query = 'DELETE FROM accGroups ' - . 'WHERE accgroup_accountId = ' . (int)$accountId . $queryExcluded; + $query = 'DELETE FROM accGroups WHERE accgroup_accountId = :id ' . $queryExcluded; - //error_log($query); + $data['id'] = $accountId; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } - - return true; + return DB::getQuery($query, __FUNCTION__, $data); } /** * Crear asociación de grupos con cuentas. * - * @param int $accountId con el Id de la cuenta + * @param int $accountId con el Id de la cuenta * @param array $groupsId con los grupos de la cuenta * @return bool */ public static function addGroupsForAccount($accountId, $groupsId) { + if(!is_array($groupsId)){ + return true; + } + $values = ''; // Obtenemos los grupos actuales - $currentGroups = self::getGroupsForAccount($accountId); - - if (is_array($currentGroups)) { - foreach ($currentGroups as $group) { - $groupsExcluded[] = $group->accgroup_groupId; - } - } + $groupsExcluded = self::getGroupsForAccount($accountId); foreach ($groupsId as $groupId) { // Excluimos los grupos actuales - if (is_array($groupsExcluded) && in_array($groupId, $groupsExcluded)) { + if (isset($groupsExcluded) && is_array($groupsExcluded) && in_array($groupId, $groupsExcluded)) { continue; } - $values[] = '(' . $accountId . ',' . $groupId . ')'; + $values[] = '(' . (int)$accountId . ',' . (int)$groupId . ')'; } if (!is_array($values)) { return true; } - $query = 'INSERT INTO accGroups (accgroup_accountId, accgroup_groupId) ' - . 'VALUES ' . implode(',', $values); + $query = 'INSERT INTO accGroups (accgroup_accountId, accgroup_groupId) VALUES ' . implode(',', $values); - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } - - return true; + return DB::getQuery($query, __FUNCTION__); } /** @@ -433,17 +412,23 @@ class SP_Groups */ public static function getGroupsForAccount($accountId) { - $query = "SELECT accgroup_groupId " - . "FROM accGroups " - . "WHERE accgroup_accountId = " . (int)$accountId; + $query = 'SELECT accgroup_groupId FROM accGroups WHERE accgroup_accountId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $data['id'] = $accountId; - if ($queryRes === false) { + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); + + if ($queryRes === false){ return false; } - return $queryRes; + foreach ($queryRes as $group) { + $groups[]= $group->accgroup_groupId; + } + + return $groups; } } diff --git a/inc/import.class.php b/inc/import.class.php index e889b808..f6481777 100644 --- a/inc/import.class.php +++ b/inc/import.class.php @@ -165,6 +165,8 @@ class SP_Import $message['text'][] = $data; SP_Log::wrLogInfo($message); + + unset($message); } } @@ -189,7 +191,7 @@ class SP_Import // Comprobamos si existe el cliente o lo creamos SP_Customer::$customerName = $customerName; - if (!SP_Customer::checkDupCustomer()) { + if (SP_Customer::checkDupCustomer()) { $customerId = SP_Customer::getCustomerByName(); } else { SP_Customer::addCustomer(); diff --git a/inc/installer.class.php b/inc/installer.class.php index 97cda201..f151c2d6 100644 --- a/inc/installer.class.php +++ b/inc/installer.class.php @@ -172,7 +172,10 @@ class SP_Installer self::setupMySQLDatabase(); self::createAdminAccount(); } catch (InstallerException $e) { - $error[] = array('type' => $e->getType(), 'description' => $e->getMessage(), 'hint' => $e->getHint()); + $error[] = array( + 'type' => $e->getType(), + 'description' => $e->getMessage(), + 'hint' => $e->getHint()); return ($error); } @@ -196,9 +199,10 @@ class SP_Installer */ private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass) { - self::$dbc = @new mysqli($dbhost, $dbadmin, $dbpass); - - if (!is_object(self::$dbc) || self::$dbc->connect_errno) { + try { + $dsn = 'mysql:host=' . $dbhost . ';charset=utf8'; + self::$dbc = new PDO($dsn, $dbadmin, $dbpass); + } catch (PDOException $e){ throw new InstallerException('critical' , _('El usuario/clave de MySQL no es correcto') , _('Verifique el usuario de conexión con la Base de Datos')); @@ -270,7 +274,9 @@ class SP_Installer $query = "CREATE USER '" . self::$dbuser . "'@'localhost' IDENTIFIED BY '" . $dbpassword . "'"; - if (!self::$dbc->query($query)) { + try { + self::$dbc->query($query); + } catch (PDOException $e){ throw new InstallerException('critical' , _('El usuario de MySQL ya existe') . " (" . self::$dbuser . ")" , _('Indique un nuevo usuario o elimine el existente')); @@ -288,20 +294,22 @@ class SP_Installer { $query = "CREATE DATABASE IF NOT EXISTS `" . self::$dbname . "`"; - if (!self::$dbc->query($query)) { + try { + self::$dbc->query($query); + } catch (PDOException $e){ throw new InstallerException('critical' - , _('Error al crear la BBDD') . " (" . self::$dbc->error . ")" + , _('Error al crear la BBDD') . " (" . $e->getMessage() . ")" , _('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)) { + try { + self::$dbc->query($query); + } catch (PDOException $e){ throw new InstallerException('critical' - , _('Error al establecer permisos de la BBDD') . " (" . self::$dbc->error . ")" + , _('Error al establecer permisos de la BBDD') . " (" . $e->getMessage() . ")" , _('Verifique los permisos del usuario de la Base de Datos')); } } @@ -317,19 +325,9 @@ class SP_Installer $query = "SELECT COUNT(*) " . "FROM information_schema.tables " . "WHERE table_schema = '" . self::$dbname . "' " - . "AND table_name = 'usrData';"; + . "AND table_name = 'usrData' LIMIT 1"; - $resquery = self::$dbc->query($query); - - if ($resquery) { - $row = $resquery->fetch_row(); - } - - if (!$resquery || $row[0] == 0) { - return false; - } - - return true; + return (intval(self::$dbc->query($query)->fetchColumn()) === 0); } /** @@ -350,9 +348,11 @@ class SP_Installer } // Usar la base de datos de sysPass - if (!self::$dbc->select_db(self::$dbname)) { + try { + self::$dbc->query('USE ' . self::$dbname); + } catch (PDOException $e){ throw new InstallerException('critical' - , _('Error al seleccionar la BBDD') . " '" . self::$dbname . "' (" . self::$dbc->error . ")" + , _('Error al seleccionar la BBDD') . " '" . self::$dbname . "' (" . $e->getMessage() . ")" , _('No es posible usar la Base de Datos para crear la estructura. Compruebe los permisos y que no exista.')); } @@ -363,11 +363,14 @@ class SP_Installer while (!feof($handle)) { $buffer = stream_get_line($handle, 1000000, ";\n"); if (strlen(trim($buffer)) > 0) { - if (!self::$dbc->query($buffer)) { + try { + self::$dbc->query($buffer); + } catch (PDOException $e) { // drop database on error self::$dbc->query("DROP DATABASE " . self::$dbname . ";"); + throw new InstallerException('critical' - , _('Error al crear la BBDD') + , _('Error al crear la BBDD') . ' (' . $e->getMessage() . ')' , _('Error al crear la estructura de la Base de Datos.')); } } @@ -471,11 +474,14 @@ class SP_Installer */ 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 . "'@'%';"); - SP_Config::deleteKey('dbuser'); - SP_Config::deleteKey('dbpass'); + try { + 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 . "'@'%';"); + } catch(PDOException $e){ + SP_Config::deleteKey('dbuser'); + SP_Config::deleteKey('dbpass'); + } } } \ No newline at end of file diff --git a/inc/log.class.php b/inc/log.class.php index 35bdb00d..24f8856d 100644 --- a/inc/log.class.php +++ b/inc/log.class.php @@ -40,26 +40,32 @@ class SP_Log */ public static function getEvents($start) { - $query = 'SELECT SQL_CALC_FOUND_ROWS ' . + $query = 'SELECT ' . 'log_id,' . - 'FROM_UNIXTIME(log_date) as date,' . + 'FROM_UNIXTIME(log_date) as log_date,' . 'log_action,' . 'log_login,' . 'log_ipAddress,' . 'log_description ' . 'FROM log ' . 'ORDER BY log_id DESC ' . - 'LIMIT ' . $start . ', 50'; + 'LIMIT :start, 50'; - $queryRes = DB::getResults($query, __FUNCTION__, true); + $data['start'] = $start; + + // Obtenemos el número total de registros + DB::setFullRowCount(); + + // Devolver un array siempre + DB::setReturnArray(); + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; } - $numRows = DB::getResults("SELECT FOUND_ROWS() as numRows", __FUNCTION__); - - self::$numRows = $numRows->numRows; + self::$numRows = DB::$last_num_rows; return $queryRes; } @@ -73,14 +79,13 @@ class SP_Log { $query = 'TRUNCATE TABLE log'; - $queryRes = DB::doQuery($query, __FUNCTION__); - - if ($queryRes === false) { + if (DB::getQuery($query, __FUNCTION__) === false) { return false; } $message['action'] = _('Vaciar Eventos'); $message['text'][] = _('Vaciar registro de eventos'); + self::wrLogInfo($message); SP_Common::sendEmail($message); @@ -108,16 +113,20 @@ class SP_Log error_log('Action: ' . $action . ' -- Description: ' . $description); } - $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) . "'"; + $query = 'INSERT INTO log SET ' . + 'log_date = UNIX_TIMESTAMP(),' . + 'log_login = :login,' . + 'log_userId = :userId,' . + 'log_ipAddress = :ipAddress,' . + 'log_action = :action,' . + 'log_description = :description'; - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['login'] = $login; + $data['userId'] = $userId; + $data['ipAddress'] = $_SERVER['REMOTE_ADDR']; + $data['action'] = $action; + $data['description'] = $description; + + return DB::getQuery($query, __FUNCTION__, $data); } } \ No newline at end of file diff --git a/inc/migrate.class.php b/inc/migrate.class.php index 483246d9..d5bd4632 100644 --- a/inc/migrate.class.php +++ b/inc/migrate.class.php @@ -2,8 +2,8 @@ /** * sysPass * - * @author nuxsmin - * @link http://syspass.org + * @author nuxsmin + * @link http://syspass.org * @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org * * This file is part of sysPass. @@ -119,47 +119,38 @@ class SP_Migrate /** * Comprobar si la conexión con la BBDD de phpPMS es posible. * - * @param string $dbhost host de conexión + * @param string $dbhost host de conexión * @param string $dbadmin usuario de conexión - * @param string $dbpass clave de conexión - * @param string $dbname nombre de la base de datos + * @param string $dbpass clave de conexión + * @param string $dbname nombre de la base de datos * @throws MigrateException * @return none */ private static function checkDatabaseAdmin($dbhost, $dbadmin, $dbpass, $dbname) { - self::$dbc = new mysqli($dbhost, $dbadmin, $dbpass, $dbname); - - if (self::$dbc->connect_errno) { - throw new MigrateException('critical', - _('El usuario/clave de MySQL no es correcto'), - _('Verifique el usuario de conexión con la Base de Datos')); + try { + $dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname . ';charset=utf8'; + self::$dbc = new PDO($dsn, $dbadmin, $dbpass); + } catch (PDOException $e) { + throw new MigrateException('critical' + , _('El usuario/clave de MySQL no es correcto') + , _('Verifique el usuario de conexión con la Base de Datos')); } } /** * Comprobar si la BBDD existe. * - * @return none + * @return int */ private static function checkDatabaseExist() { - $query = "SELECT COUNT(*) " - . "FROM information_schema.tables " - . "WHERE table_schema='" . self::$dbname . "' " - . "AND table_name = 'users';"; + $query = 'SELECT COUNT(*) ' + . 'FROM information_schema.tables ' + . 'WHERE table_schema = \'' . self::$dbname . '\' ' + . 'AND table_name = \'usrData\' LIMIT 1'; - $queryRes = self::$dbc->query($query); - - if ($queryRes) { - $row = $queryRes->fetch_row(); - } - - if (!$queryRes || $row[0] == 0) { - return false; - } - - return true; + return (intval(self::$dbc->query($query)->fetchColumn()) === 0); } /** @@ -189,19 +180,15 @@ class SP_Migrate */ private static function getSourceConfig() { - $query = 'SELECT vacValue as value,' - . 'vacParameter as parameter ' - . 'FROM config'; - $queryRes = self::$dbc->query($query); + $query = 'SELECT vacValue as value,vacParameter as parameter FROM config'; + + try { + self::parseSourceConfig(self::$dbc->query($query)); + } catch (PDOException $e) { - if (!$queryRes) { throw new MigrateException('critical', _('Error al obtener la configuración'), - self::$dbc->error); - } - - while ($row = @$queryRes->fetch_assoc()) { - self::parseSourceConfig($row); + $e->getMessage()); } } @@ -225,8 +212,6 @@ class SP_Migrate // Guardar la configuración anterior self::$oldConfig[$config['parameter']] = $value; - - //error_log($config['parameter'].' >> '.$value); } /** @@ -243,9 +228,8 @@ class SP_Migrate // Limpiar datos de las tablas foreach ($tables as $table) { $query = 'TRUNCATE TABLE ' . $table; - $queryRes = DB::doQuery($query, __FUNCTION__); - if ($queryRes === false) { + if (DB::getQuery($query, __FUNCTION__) === false) { throw new MigrateException('critical', _('Error al vaciar tabla') . ' (' . $table . ')', DB::$txtError); @@ -257,17 +241,15 @@ class SP_Migrate // Limpiar datos de usuarios manteniendo el usuario actual if (self::checkAdminAccount($currentUserId)) { $query = 'DELETE FROM usrData WHERE user_id != ' . $currentUserId; - $queryRes = DB::doQuery($query, __FUNCTION__); - if ($queryRes === false) { + if (DB::getQuery($query, __FUNCTION__) === false) { throw new MigrateException('critical', _('Error al vaciar tabla') . ' (' . $table . ')', DB::$txtError); } } else { throw new MigrateException('critical', - _('Usuario actual no es administrador de la aplicación'), - DB::$txtError); + _('Usuario actual no es administrador de la aplicación'), 1); } } @@ -279,16 +261,14 @@ class SP_Migrate */ private static function checkAdminAccount($currentUserId) { - $query = 'SELECT COUNT(*) ' - . 'FROM usrData ' - . 'WHERE user_id = ' . $currentUserId . ' AND user_isAdminApp = 1'; - $queryRes = DB::doQuery($query, __FUNCTION__); + $query = 'SELECT user_id FROM usrData WHERE user_id = :id AND user_isAdminApp = 1 LIMIT 1'; - if ($queryRes !== 1) { - return false; - } + $data['id'] = $currentUserId; - return true; + $db = new DB(); + $db->setParamData($data); + + return ($db->getFullRowCount($query) === 0); } /** @@ -307,7 +287,7 @@ class SP_Migrate foreach ($customers as $customer) { SP_Customer::$customerName = $customer; - if (!SP_Customer::checkDupCustomer()) { + if (SP_Customer::checkDupCustomer()) { $num++; continue; } @@ -324,8 +304,6 @@ class SP_Migrate $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Clientes')." - $num / $totalRecords"; } /** @@ -337,19 +315,18 @@ class SP_Migrate private static function getCustomers() { $query = 'SELECT DISTINCT vacCliente FROM accounts'; - $queryRes = self::$dbc->query($query); - if (!$queryRes) { + try { + foreach (self::$dbc->query($query) as $row) { + $customers[] = trim($row['vacCliente']); + } + + return $customers; + } catch (PDOException $e) { throw new MigrateException('critical', _('Error al obtener los clientes'), - self::$dbc->error); + $e->getMessage()); } - - while ($row = @$queryRes->fetch_row()) { - $customers[] = trim($row[0]); - } - - return $customers; } /** @@ -376,30 +353,28 @@ class SP_Migrate . 'intCountDecrypt,' . 'datAdded,datChanged ' . 'FROM accounts '; - $queryRes = self::$dbc->query($query); - if (!$queryRes) { - throw new MigrateException('critical', - _('Error al obtener cuentas'), - self::$dbc->error); - } - - $totalRecords = $queryRes->num_rows; + $totalRecords = 0; $num = 0; - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertAccounts($row)) { - $num++; + try { + foreach (self::$dbc->query($query) as $row) { + if (self::insertAccounts($row)) { + $num++; + } + $totalRecords++; } + } catch (PDOException $e) { + throw new MigrateException('critical', + _('Error al obtener cuentas'), + $e->getMessage()); } $message['action'] = _('Importar Cuentas'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Cuentas')." - $num / $totalRecords"; } /** @@ -426,25 +401,42 @@ class SP_Migrate return false; } - $query = "INSERT INTO accounts SET - account_id = " . $account['intAccountId'] . ", - account_userGroupId = " . $account['intUGroupFId'] . ", - account_userId = " . $account['intUserFId'] . ", - account_userEditId = " . $account['intUEditFId'] . ", - account_customerId = " . $customerId . ", - account_name = '" . DB::escape($account['vacName']) . "', - account_categoryId = " . $account['intCategoryFid'] . ", - account_login = '" . DB::escape($account['vacLogin']) . "', - account_url = '" . DB::escape($account['vacUrl']) . "', - account_pass = '" . $account['vacPassword'] . "', - account_IV = '" . $account['vacInitialValue'] . "', - account_notes = '" . DB::escape($account['txtNotice']) . "', - account_countView = " . $account['intCountView'] . ", - account_countDecrypt = " . $account['intCountDecrypt'] . ", - account_dateAdd = '" . $account['datAdded'] . "', - account_dateEdit = '" . $account['datChanged'] . "'"; + $query = 'INSERT INTO accounts SET ' . + 'account_id = :id,' . + 'account_userGroupId = :userGroupId,' . + 'account_userId = :userId,' . + 'account_userEditId = :userEditId,' . + 'account_customerId = :customerId,' . + 'account_name = :name,' . + 'account_categoryId = :categoryId,' . + 'account_login = :login,' . + 'account_url = :url,' . + 'account_pass = :pass,' . + 'account_IV = :iv,' . + 'account_notes = :notes,' . + 'account_countView = :countView,' . + 'account_countDecrypt = :countDecrypt,' . + 'account_dateAdd = :dateAdd,' . + 'account_dateEdit = :dateEdit'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $account['intAccountId']; + $data['userGroupId'] = $account['intUGroupFId']; + $data['userId'] = $account['intUserFId']; + $data['userEditId'] = $account['intUEditFId']; + $data['customerId'] = $customerId; + $data['name'] = $account['vacName']; + $data['categoryId'] = $account['intCategoryFid']; + $data['login'] = $account['vacLogin']; + $data['url'] = $account['vacUrl']; + $data['pass'] = $account['vacPassword']; + $data['iv'] = $account['vacInitialValue']; + $data['notes'] = $account['txtNotice']; + $data['countView'] = $account['intCountView']; + $data['countDecrypt'] = $account['intCountDecrypt']; + $data['dateAdd'] = $account['datAdded']; + $data['dateEdit'] = $account['datChanged']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { self::$currentQuery = DB::escape($query); throw new MigrateException('critical', _('Error al migrar cuenta'), @@ -462,32 +454,29 @@ class SP_Migrate */ private static function migrateAccountsGroups() { - $query = 'SELECT intAccId,' - . 'intUGroupId ' - . 'FROM acc_usergroups'; - $queryRes = self::$dbc->query($query); + $query = 'SELECT intAccId,intUGroupId FROM acc_usergroups'; - if (!$queryRes) { - throw new MigrateException('critical', - _('Error al obtener los grupos de cuentas'), - self::$dbc->error); - } - - $totalRecords = $queryRes->num_rows; + $totalRecords = 0; $num = 0; - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertAccountsGroups($row)) { - $num++; + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertAccountsGroups($row)) { + $num++; + } + $totalRecords++; } + } catch(PDOException $e){ + throw new MigrateException('critical', + _('Error al obtener los grupos de cuentas'), + $e->getMessage()); } $message['action'] = _('Importar Grupos de Cuentas'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); -// self::$result['ok'][] = _('Importar Grupos de Cuentas')." - $num / $totalRecords"; } /** @@ -499,11 +488,12 @@ class SP_Migrate */ private static function insertAccountsGroups($accountGroup) { - $query = "INSERT INTO accGroups " - . "SET accgroup_accountId = " . $accountGroup['intAccId'] . "," - . "accgroup_groupId = " . $accountGroup['intUGroupId']; + $query = 'INSERT INTO accGroups SET accgroup_accountId = :accountId,accgroup_groupId = :groudId'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['accountId'] = $accountGroup['intAccId']; + $data['groupId'] = $accountGroup['intUGroupId']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear grupos de cuentas'), DB::$txtError); @@ -539,30 +529,28 @@ class SP_Migrate . 'blnModificada,' . 'blnEliminada ' . 'FROM acc_history'; - $queryRes = self::$dbc->query($query); - if (!$queryRes) { + $totalRecords = 0; + $num = 0; + + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertAccountsHistory($row)) { + $num++; + } + $totalRecords++; + } + } catch(PDOException $e){ throw new MigrateException('critical', _('Error al obtener el historico de cuentas'), self::$dbc->error); } - $totalRecords = $queryRes->num_rows; - $num = 0; - - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertAccountsHistory($row)) { - $num++; - } - } - $message['action'] = _('Importar Histórico de Cuentas'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Histórico de Cuentas')." - $num / $totalRecords"; } /** @@ -575,7 +563,7 @@ class SP_Migrate private static function insertAccountsHistory($accountHistory) { if (!is_array(self::$customersByName)) { - $customers = SP_Customer::getCustomers(NULL, true); + $customers = SP_Customer::getCustomers(null, true); self::$customersByName = array_flip($customers); } @@ -587,27 +575,46 @@ class SP_Migrate return false; } - $query = "INSERT INTO accHistory SET - acchistory_accountId = " . $accountHistory['intAccountId'] . ", - acchistory_userGroupId = " . $accountHistory['intUGroupFId'] . ", - acchistory_userId = " . $accountHistory['intUserFId'] . ", - acchistory_userEditId = " . $accountHistory['intUEditFId'] . ", - acchistory_customerId = " . $customerId . ", - acchistory_name = '" . DB::escape($accountHistory['vacName']) . "', - acchistory_categoryId = " . $accountHistory['intCategoryFid'] . ", - acchistory_login = '" . DB::escape($accountHistory['vacLogin']) . "', - acchistory_url = '" . DB::escape($accountHistory['vacUrl']) . "', - acchistory_pass = '" . $accountHistory['vacPassword'] . "', - acchistory_IV = '" . $accountHistory['vacInitialValue'] . "', - acchistory_notes = '" . DB::escape($accountHistory['txtNotice']) . "', - acchistory_countView = " . $accountHistory['intCountView'] . ", - acchistory_countDecrypt = " . $accountHistory['intCountDecrypt'] . ", - acchistory_dateAdd = '" . $accountHistory['datAdded'] . "', - acchistory_dateEdit = '" . $accountHistory['datChanged'] . "', - acchistory_isModify = " . $accountHistory['blnModificada'] . ", - acchistory_isDeleted = " . $accountHistory['blnEliminada']; + $query = 'INSERT INTO accHistory SET ' . + 'acchistory_accountId = :id,' . + 'acchistory_userGroupId = :userGroupId,' . + 'acchistory_userId = :userId,' . + 'acchistory_userEditId = :userEditId,' . + 'acchistory_customerId = :customerId,' . + 'acchistory_name = :name,' . + 'acchistory_categoryId = :categoryId,' . + 'acchistory_login = :login,' . + 'acchistory_url = :url,' . + 'acchistory_pass = :pass,' . + 'acchistory_IV = :iv,' . + 'acchistory_notes = :notes,' . + 'acchistory_countView = :countView,' . + 'acchistory_countDecrypt = :countDecrypt,' . + 'acchistory_dateAdd = :dateAdd,' . + 'acchistory_dateEdit = :dateEdit,' . + 'acchistory_isModify = :isModify,' . + 'acchistory_isDeleted = :isDeleted'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $accountHistory['intAccountId']; + $data['userGroupId'] = $accountHistory['intUGroupFId']; + $data['userId'] = $accountHistory['intUserFId']; + $data['userEditId'] = $accountHistory['intUEditFId']; + $data['customerId'] = $customerId; + $data['name'] = $accountHistory['vacName']; + $data['categoryId'] = $accountHistory['intCategoryFid']; + $data['login'] = $accountHistory['vacLogin']; + $data['url'] = $accountHistory['vacUrl']; + $data['pass'] = $accountHistory['vacPassword']; + $data['iv'] = $accountHistory['vacInitialValue']; + $data['notes'] = $accountHistory['txtNotice']; + $data['countView'] = $accountHistory['intCountView']; + $data['countDecrypt'] = $accountHistory['intCountDecrypt']; + $data['dateAdd'] = $accountHistory['datAdded']; + $data['dateEdit'] = $accountHistory['datChanged']; + $data['isModify'] = $accountHistory['blnModificada']; + $data['isDeleted'] = $accountHistory['blnEliminada']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear historico de cuentas'), DB::$txtError); @@ -631,30 +638,28 @@ class SP_Migrate . 'blobContent,' . 'vacExtension ' . 'FROM files'; - $queryRes = self::$dbc->query($query); - if (!$queryRes) { + $totalRecords = 0; + $num = 0; + + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertAccountsFiles($row)) { + $num++; + } + $totalRecords++; + } + } catch(PDOException $e){ throw new MigrateException('critical', _('Error al obtener los archivos de cuentas'), self::$dbc->error); } - $totalRecords = $queryRes->num_rows; - $num = 0; - - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertAccountsFiles($row)) { - $num++; - } - } - $message['action'] = _('Importar Archivos de Cuentas'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Archivos de Cuentas')." - $num / $totalRecords"; } /** @@ -666,15 +671,22 @@ class SP_Migrate */ private static function insertAccountsFiles($accountFile) { - $query = "INSERT INTO accFiles " - . "SET accfile_accountId = " . $accountFile['intAccountId'] . "," - . "accfile_name = '" . DB::escape($accountFile['vacName']) . "'," - . "accfile_type = '" . DB::escape($accountFile['vacType']) . "'," - . "accfile_size = " . $accountFile['intSize'] . "," - . "accfile_content = '" . DB::escape($accountFile['blobContent']) . "'," - . "accfile_extension = '" . DB::escape($accountFile['vacExtension']) . "'"; + $query = 'INSERT INTO accFiles ' + . 'SET accfile_accountId = :id,' + . 'accfile_name = :name,' + . 'accfile_type = :type,' + . 'accfile_size = :size,' + . 'accfile_content = :blobcontent,' + . 'accfile_extension = :extension'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $accountFile['intAccountId']; + $data['name'] = $accountFile['vacName']; + $data['type'] = $accountFile['vacType']; + $data['size'] = $accountFile['intSize']; + $data['blobcontent'] = $accountFile['blobContent']; + $data['extension'] = $accountFile['vacExtension']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear archivos de cuentas'), DB::$txtError); @@ -691,33 +703,29 @@ class SP_Migrate */ private static function migrateAccountsCategories() { - $query = 'SELECT intCategoryId,' - . 'vacCategoryName ' - . 'FROM categories'; - $queryRes = self::$dbc->query($query); + $query = 'SELECT intCategoryId,vacCategoryName FROM categories'; - if (!$queryRes) { + $totalRecords = 0; + $num = 0; + + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertAccountsCategories($row)) { + $num++; + } + $totalRecords++; + } + } catch(PDOException $e){ throw new MigrateException('critical', _('Error al obtener las categorías de cuentas'), self::$dbc->error); } - $totalRecords = $queryRes->num_rows; - $num = 0; - - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertAccountsCategories($row)) { - $num++; - } - } - $message['action'] = _('Importar Categorías de Cuentas'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Categorías de Cuentas')." - $num / $totalRecords"; } /** @@ -729,11 +737,12 @@ class SP_Migrate */ private static function insertAccountsCategories($accountCategory) { - $query = "INSERT INTO categories " - . "SET category_id = " . $accountCategory['intCategoryId'] . "," - . "category_name = '" . DB::escape($accountCategory['vacCategoryName']) . "'"; + $query = 'INSERT INTO categories SET category_id = :id,category_name = :name'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $accountCategory['intCategoryId']; + $data['name'] = $accountCategory['vacCategoryName']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear categorías de cuentas'), DB::$txtError); @@ -770,30 +779,28 @@ class SP_Migrate . 'blnDisabled ' . 'FROM users ' . 'WHERE intUserId <> ' . $_SESSION['uid']; - $queryRes = self::$dbc->query($query); - if (!$queryRes) { + $totalRecords = 0; + $num = 0; + + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertUsers($row)) { + $num++; + } + $totalRecords++; + } + } catch(PDOException $e){ throw new MigrateException('critical', _('Error al obtener los usuarios'), self::$dbc->error); } - $totalRecords = $queryRes->num_rows; - $num = 0; - - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertUsers($row)) { - $num++; - } - } - $message['action'] = _('Importar Usuarios'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Usuarios')." - $num / $totalRecords"; } /** @@ -807,28 +814,45 @@ class SP_Migrate */ private static function insertUsers($users) { - $query = "INSERT INTO usrData " - . "SET user_id = " . $users['intUserId'] . "," - . "user_name = '" . DB::escape($users['vacUName']) . "'," - . "user_groupId = " . $users['intUGroupFid'] . "," - . "user_login = '" . DB::escape($users['vacULogin']) . "'," - . "user_pass = '" . DB::escape($users['vacUPassword']) . "'," - . "user_mPass = '" . DB::escape($users['vacUserMPwd']) . "'," - . "user_mIV = '" . DB::escape($users['vacUserMIv']) . "'," - . "user_email = '" . DB::escape($users['vacUEmail']) . "'," - . "user_notes = '" . DB::escape($users['txtUNotes']) . "'," - . "user_count = " . $users['intUCount'] . "," - . "user_profileId = 0," - . "user_lastLogin = '" . $users['datULastLogin'] . "'," - . "user_lastUpdate = '" . $users['datULastUpdate'] . "'," - . "user_lastUpdateMPass = " . $users['datUserLastUpdateMPass'] . "," - . "user_isAdminApp = " . $users['blnIsAdminApp'] . "," - . "user_isAdminAcc = " . $users['blnIsAdminAcc'] . "," - . "user_isLdap = " . $users['blnFromLdap'] . "," - . "user_isDisabled = 1," - . "user_isMigrate = 1"; + $query = 'INSERT INTO usrData ' + . 'SET user_id = :id,' + . 'user_name = :name,' + . 'user_groupId = :goupId,' + . 'user_login = :login,' + . 'user_pass = :pass,' + . 'user_mPass = :mpass,' + . 'user_mIV = :miv,' + . 'user_email = :email,' + . 'user_notes = :notes,' + . 'user_count = :count,' + . 'user_profileId = 0,' + . 'user_lastLogin = :lastLogin,' + . 'user_lastUpdate = :lastUpdate,' + . 'user_lastUpdateMPass = :lastUpdateMPass,' + . 'user_isAdminApp = :isAdminApp,' + . 'user_isAdminAcc = :isAdminAcc,' + . 'user_isLdap = :isLdap,' + . 'user_isDisabled = 1,' + . 'user_isMigrate = 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $users['intUserId']; + $data['name'] = $users['vacUName']; + $data['groupId'] = $users['intUGroupFid']; + $data['login'] = $users['vacULogin']; + $data['pass'] = $users['vacUPassword']; + $data['mpass'] = $users['vacUserMPwd']; + $data['miv'] = $users['vacUserMIv']; + $data['email'] = $users['vacUEmail']; + $data['notes'] = $users['txtUNotes']; + $data['count'] = $users['intUCount']; + $data['lastLogin'] = $users['datULastLogin']; + $data['lastUpdate'] = $users['datULastUpdate']; + $data['lastUpdateMPass'] = $users['datUserLastUpdateMPass']; + $data['isAdminApp'] = $users['blnIsAdminApp']; + $data['isAdminAcc'] = $users['blnIsAdminAcc']; + $data['isLdap'] = $users['blnFromLdap']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear usuarios'), DB::$txtError); @@ -845,34 +869,29 @@ class SP_Migrate */ private static function migrateUsersGroups() { - $query = 'SELECT intUGroupId,' - . 'vacUGroupName,' - . 'vacUGroupDesc ' - . 'FROM usergroups'; - $queryRes = self::$dbc->query($query); + $query = 'SELECT intUGroupId,vacUGroupName,vacUGroupDesc FROM usergroups'; - if (!$queryRes) { + $totalRecords = 0; + $num = 0; + + try { + foreach(self::$dbc->query($query) as $row){ + if (self::insertUsersGroups($row)) { + $num++; + } + $totalRecords++; + } + } catch(PDOException $e){ throw new MigrateException('critical', _('Error al obtener los grupos de usuarios'), self::$dbc->error); } - $totalRecords = $queryRes->num_rows; - $num = 0; - - while ($row = @$queryRes->fetch_assoc()) { - if (self::insertUsersGroups($row)) { - $num++; - } - } - $message['action'] = _('Importar Grupos de Usuarios'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalRecords; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalRecords; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Grupos de Usuarios')." - $num / $totalRecords"; } /** @@ -884,12 +903,16 @@ class SP_Migrate */ private static function insertUsersGroups($usersGroups) { - $query = "INSERT INTO usrGroups " - . "SET usergroup_id = " . $usersGroups['intUGroupId'] . "," - . "usergroup_name = '" . DB::escape($usersGroups['vacUGroupName']) . "'," - . "usergroup_description = '" . DB::escape($usersGroups['vacUGroupDesc']) . "'"; + $query = 'INSERT INTO usrGroups ' + . 'SET usergroup_id = :id,' + . 'usergroup_name = :name,' + . 'usergroup_description = :description'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = $usersGroups['intUGroupId']; + $data['name'] = $usersGroups['vacUGroupName']; + $data['description'] = $usersGroups['vacUGroupDesc']; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { throw new MigrateException('critical', _('Error al crear los grupos de usuarios'), DB::$txtError); @@ -923,7 +946,6 @@ class SP_Migrate 'password_show', 'lastupdatempass', 'passwordsalt'); - //$savedConfig = array_diff_key($skip, SP_Config::getKeys()); $totalParams = count(self::$oldConfig); $num = 0; @@ -939,10 +961,8 @@ class SP_Migrate $message['action'] = _('Importar Configuración'); $message['text'][] = 'OK'; - $message['text'][] = _('Registros') . ': ' . $num . ' / ' . $totalParams; + $message['text'][] = _('Registros') . ': ' . $num . '/' . $totalParams; SP_Log::wrLogInfo($message); - -// self::$result['ok'][] = _('Importar Configuración')." - $num / $totalParams"; } } \ No newline at end of file diff --git a/inc/profiles.class.php b/inc/profiles.class.php index 8f87b97c..f2c4d4b4 100644 --- a/inc/profiles.class.php +++ b/inc/profiles.class.php @@ -43,25 +43,25 @@ class SP_Profiles public static function getProfileData($id = 0) { - $profile = array('userprofile_id' => 0, - 'userprofile_name' => '', - 'userProfile_pView' => 0, - 'userProfile_pViewPass' => 0, - 'userProfile_pViewHistory' => 0, - 'userProfile_pEdit' => 0, - 'userProfile_pEditPass' => 0, - 'userProfile_pAdd' => 0, - 'userProfile_pDelete' => 0, - 'userProfile_pFiles' => 0, - 'userProfile_pConfig' => 0, - 'userProfile_pConfigMasterPass' => 0, - 'userProfile_pConfigBackup' => 0, - 'userProfile_pAppMgmtCategories' => 0, - 'userProfile_pAppMgmtCustomers' => 0, - 'userProfile_pUsers' => 0, - 'userProfile_pGroups' => 0, - 'userProfile_pProfiles' => 0, - 'userProfile_pEventlog' => 0, + $profile = array('id' => 0, + 'name' => '', + 'pView' => 0, + 'pViewPass' => 0, + 'pViewHistory' => 0, + 'pEdit' => 0, + 'pEditPass' => 0, + 'pAdd' => 0, + 'pDelete' => 0, + 'pFiles' => 0, + 'pConfig' => 0, + 'pConfigMasterPass' => 0, + 'pConfigBackup' => 0, + 'pAppMgmtCategories' => 0, + 'pAppMgmtCustomers' => 0, + 'pUsers' => 0, + 'pGroups' => 0, + 'pProfiles' => 0, + 'pEventlog' => 0, 'action' => 1); if ($id > 0) { @@ -69,8 +69,8 @@ class SP_Profiles if ($usersProfiles) { foreach ($usersProfiles[0] as $name => $value) { - if (preg_match('/^.*_p[A-Z].*$/', $name)) { - $profile[$name] = ((int)$value === 1) ? "CHECKED" : ""; + if (preg_match('/^p[A-Za-z].*$/', $name)) { + $profile[$name] = (intval($value) === 1) ? "CHECKED" : ""; } else { $profile[$name] = $value; } @@ -88,30 +88,34 @@ 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) { + $data = 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 ' + $query = 'SELECT userprofile_id AS id,' + . 'userprofile_name AS name,' + . 'BIN(userProfile_pView) AS pView,' + . 'BIN(userProfile_pViewPass) AS pViewPass,' + . 'BIN(userProfile_pViewHistory) AS pViewHistory,' + . 'BIN(userProfile_pEdit) AS pEdit,' + . 'BIN(userProfile_pEditPass) AS pEditPass,' + . 'BIN(userProfile_pAdd) AS pAdd,' + . 'BIN(userProfile_pDelete) AS pDelete,' + . 'BIN(userProfile_pFiles) AS pFiles,' + . 'BIN(userProfile_pConfig) AS pConfig,' + . 'BIN(userProfile_pConfigMasterPass) AS pConfigMasterPass,' + . 'BIN(userProfile_pConfigBackup) AS pConfigBackup,' + . 'BIN(userProfile_pAppMgmtCategories) AS pAppMgmtCategories,' + . 'BIN(userProfile_pAppMgmtCustomers) AS pAppMgmtCustomers,' + . 'BIN(userProfile_pUsers) AS pUsers,' + . 'BIN(userProfile_pGroups) AS pGroups,' + . 'BIN(userProfile_pProfiles) AS pProfiles,' + . 'BIN(userProfile_pEventlog) AS pEventlog ' . 'FROM usrProfiles ' - . 'WHERE userprofile_id = ' . (int)$profileId . ' LIMIT 1'; + . 'WHERE userprofile_id = :id LIMIT 1'; + + $data['id'] = $profileId; } else { $query = 'SELECT userprofile_id,' . 'userprofile_name ' @@ -119,13 +123,9 @@ class SP_Profiles . 'ORDER BY userprofile_name'; } - $queryRes = DB::getResults($query, __FUNCTION__, true); + DB::setReturnArray(); - if ($queryRes === false) { - return false; - } - - return $queryRes; + return DB::getResults($query, __FUNCTION__, $data); } /** @@ -138,25 +138,21 @@ class SP_Profiles $profileName = strtoupper(self::$profileName); if ($profileId) { - $query = "SELECT userprofile_name " - . "FROM usrProfiles " - . "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "' " - . "AND userprofile_id != " . $profileId; + $query = 'SELECT userprofile_name ' + . 'FROM usrProfiles ' + . 'WHERE UPPER(userprofile_name) = :name ' + . 'AND userprofile_id != :id'; + + $data['id'] = $profileId; } else { - $query = "SELECT userprofile_name " - . "FROM usrProfiles " - . "WHERE UPPER(userprofile_name) = '" . DB::escape($profileName) . "'"; + $query = 'SELECT userprofile_name ' + . 'FROM usrProfiles ' + . 'WHERE UPPER(userprofile_name) = :name'; } - if (DB::doQuery($query, __FUNCTION__) === false) { - return false; - } + $data['name'] = $profileName; - if (count(DB::$last_result) >= 1) { - return false; - } - - return true; + return (DB::getQuery($query, __FUNCTION__, $data) === true && DB::$last_num_rows >= 1); } /** @@ -164,36 +160,58 @@ class SP_Profiles * @param array $profileProp con las propiedades del perfil * @return bool */ - public static function addProfile($profileProp = NULL) + public static function addProfile(&$profileProp) { - $enableConfig = (int)($profileProp["pConfig"] || $profileProp["pConfigCat"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]); + $enableConfig = (int)($profileProp["pConfig"] || $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"]; + $query = 'INSERT INTO usrProfiles SET ' + . 'userprofile_name = :name,' + . 'userProfile_pView = :pView,' + . 'userProfile_pViewPass = :pViewPass,' + . 'userProfile_pViewHistory = :pViewHistory,' + . 'userProfile_pEdit = :pEdit,' + . 'userProfile_pEditPass = :pEditPass,' + . 'userProfile_pAdd = :pAdd,' + . 'userProfile_pDelete = :pDelete,' + . 'userProfile_pFiles = :pFiles,' + . 'userProfile_pConfigMenu = :pConfigMenu,' + . 'userProfile_pConfig = :pConfig,' + . 'userProfile_pConfigMasterPass = :pConfigMasterPass,' + . 'userProfile_pConfigBackup = :pConfigBackup,' + . 'userProfile_pAppMgmtMenu = :pAppMgmtMenu,' + . 'userProfile_pAppMgmtCategories = :pAppMgmtCategories,' + . 'userProfile_pAppMgmtCustomers = :pAppMgmtCustomers,' + . 'userProfile_pUsersMenu = :pUsersMenu,' + . 'userProfile_pUsers = :pUsers,' + . 'userProfile_pGroups = :pGroups,' + . 'userProfile_pProfiles = :pProfiles,' + . 'userProfile_pEventlog = :pEventlog'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['name'] = self::$profileName; + $data['pView'] = $profileProp["pAccView"]; + $data['pViewPass'] = $profileProp["pAccViewPass"]; + $data['pViewHistory'] = $profileProp["pAccViewHistory"]; + $data['pEdit'] = $profileProp["pAccEdit"]; + $data['pEditPass'] = $profileProp["pAccEditPass"]; + $data['pAdd'] = $profileProp["pAccAdd"]; + $data['pDelete'] = $profileProp["pAccDel"]; + $data['pFiles'] = $profileProp["pAccFiles"]; + $data['pConfigMenu'] = $enableConfig; + $data['pConfig'] = $profileProp["pConfig"]; + $data['pConfigMasterPass'] = $profileProp["pConfigMpw"]; + $data['pConfigBackup'] = $profileProp["pConfigBack"]; + $data['pAppMgmtMenu'] = $enableAppMgmt; + $data['pAppMgmtCategories'] = $profileProp["pAppMgmtCat"]; + $data['pAppMgmtCustomers'] = $profileProp["pAppMgmtCust"]; + $data['pUsersMenu'] = $enableUsers; + $data['pUsers'] = $profileProp["pUsers"]; + $data['pGroups'] = $profileProp["pGroups"]; + $data['pProfiles'] = $profileProp["pProfiles"]; + $data['pEventlog'] = $profileProp["pEventlog"]; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -214,38 +232,61 @@ class SP_Profiles * @param array $profileProp con las propiedades del perfil * @return bool */ - public static function updateProfile($profileProp = NULL) + public static function updateProfile(&$profileProp) { $enableConfig = (int)($profileProp["pConfig"] || $profileProp["pConfigMpw"] || $profileProp["pConfigBack"]); $enableAppMgmt = (int)($profileProp["pAppMgmtCat"] || $profileProp["pAppMgmtCust"]); $enableUsers = (int)($profileProp["pUsers"] || $profileProp["pGroups"] || $profileProp["pProfiles"]); $profileName = self::getProfileNameById(self::$profileId); - $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"; + $query = 'UPDATE usrProfiles SET ' + . 'userprofile_name = :name,' + . 'userProfile_pView = :pView,' + . 'userProfile_pViewPass = :pViewPass,' + . 'userProfile_pViewHistory = :pViewHistory,' + . 'userProfile_pEdit = :pEdit,' + . 'userProfile_pEditPass = :pEditPass,' + . 'userProfile_pAdd = :pAdd,' + . 'userProfile_pDelete = :pDelete,' + . 'userProfile_pFiles = :pFiles,' + . 'userProfile_pConfigMenu = :pConfigMenu,' + . 'userProfile_pConfig = :pConfig,' + . 'userProfile_pConfigMasterPass = :pConfigMasterPass,' + . 'userProfile_pConfigBackup = :pConfigBackup,' + . 'userProfile_pAppMgmtMenu = :pAppMgmtMenu,' + . 'userProfile_pAppMgmtCategories = :pAppMgmtCategories,' + . 'userProfile_pAppMgmtCustomers = :pAppMgmtCustomers,' + . 'userProfile_pUsersMenu = :pUsersMenu,' + . 'userProfile_pUsers = :pUsers,' + . 'userProfile_pGroups = :pGroups,' + . 'userProfile_pProfiles = :pProfiles,' + . 'userProfile_pEventlog = :pEventlog ' + . 'WHERE userprofile_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = self::$profileId; + $data['name'] = self::$profileName; + $data['pView'] = $profileProp["pAccView"]; + $data['pViewPass'] = $profileProp["pAccViewPass"]; + $data['pViewHistory'] = $profileProp["pAccViewHistory"]; + $data['pEdit'] = $profileProp["pAccEdit"]; + $data['pEditPass'] = $profileProp["pAccEditPass"]; + $data['pAdd'] = $profileProp["pAccAdd"]; + $data['pDelete'] = $profileProp["pAccDel"]; + $data['pFiles'] = $profileProp["pAccFiles"]; + $data['pConfigMenu'] = $enableConfig; + $data['pConfig'] = $profileProp["pConfig"]; + $data['pConfigMasterPass'] = $profileProp["pConfigMpw"]; + $data['pConfigBackup'] = $profileProp["pConfigBack"]; + $data['pAppMgmtMenu'] = $enableAppMgmt; + $data['pAppMgmtCategories'] = $profileProp["pAppMgmtCat"]; + $data['pAppMgmtCustomers'] = $profileProp["pAppMgmtCust"]; + $data['pUsersMenu'] = $enableUsers; + $data['pUsers'] = $profileProp["pUsers"]; + $data['pGroups'] = $profileProp["pGroups"]; + $data['pProfiles'] = $profileProp["pProfiles"]; + $data['pEventlog'] = $profileProp["pEventlog"]; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -267,10 +308,11 @@ class SP_Profiles */ public static function deleteProfile() { - $query = "DELETE FROM usrProfiles " - . "WHERE userprofile_id = " . (int)self::$profileId . " LIMIT 1"; + $query = 'DELETE FROM usrProfiles WHERE userprofile_id = :id LIMIT 1'; - if (DB::doQuery($query, __FUNCTION__) === false) { + $data['id'] = self::$profileId; + + if (DB::getQuery($query, __FUNCTION__, $data) === false) { return false; } @@ -297,17 +339,13 @@ class SP_Profiles */ private static function getProfileInUsers() { - $query = "SELECT COUNT(*) as uses " - . "FROM usrData " - . "WHERE user_profileId = " . (int)self::$profileId; + $query = 'SELECT user_profileId FROM usrData WHERE user_profileId = :id'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = self::$profileId; - if ($queryRes === false) { - return false; - } + DB::getQuery($query, __FUNCTION__, $data); - return $queryRes->uses; + return DB::$last_num_rows; } /** @@ -318,11 +356,11 @@ class SP_Profiles */ public static function getProfileNameById($id) { - $query = "SELECT userprofile_name " - . "FROM usrProfiles " - . "WHERE userprofile_id = " . (int)$id . " LIMIT 1"; + $query = 'SELECT userprofile_name FROM usrProfiles WHERE userprofile_id = :id LIMIT 1'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $id; + + $queryRes = DB::getResults($query, __FUNCTION__, $data); if ($queryRes === false) { return false; @@ -346,37 +384,30 @@ class SP_Profiles 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"; + $query = 'SELECT user_profileId,' + . 'BIN(userProfile_pView) AS pView,' + . 'BIN(userProfile_pViewPass) AS pViewPass,' + . 'BIN(userProfile_pViewHistory) AS pViewHistory,' + . 'BIN(userProfile_pEdit) AS pEdit,' + . 'BIN(userProfile_pEditPass) AS pEditPass,' + . 'BIN(userProfile_pAdd) AS pAdd,' + . 'BIN(userProfile_pDelete) AS pDelete,' + . 'BIN(userProfile_pFiles) AS pFiles,' + . 'BIN(userProfile_pConfig) AS pConfig,' + . 'BIN(userProfile_pConfigMasterPass) AS pConfigMasterPass,' + . 'BIN(userProfile_pConfigBackup) AS pConfigBackup,' + . 'BIN(userProfile_pAppMgmtCategories) AS pAppMgmtCategories,' + . 'BIN(userProfile_pAppMgmtCustomers) AS pAppMgmtCustomers,' + . 'BIN(userProfile_pUsers) AS pUsers,' + . 'BIN(userProfile_pGroups) AS pGroups,' + . 'BIN(userProfile_pProfiles) AS pProfiles,' + . 'BIN(userProfile_pEventlog) AS pEventlog ' + . 'FROM usrData ' + . 'JOIN usrProfiles ON userProfile_Id = user_profileId ' + . 'WHERE user_id = :id LIMIT 1'; - $queryRes = DB::getResults($query, __FUNCTION__); + $data['id'] = $userId; - if ($queryRes === false) { - return false; - } - - return $queryRes; + return DB::getResults($query, __FUNCTION__, $data); } } diff --git a/inc/tpl/accounts.php b/inc/tpl/accounts.php index 40ad80e4..2234f644 100644 --- a/inc/tpl/accounts.php +++ b/inc/tpl/accounts.php @@ -54,18 +54,18 @@ switch ($action) { $showform = true; $nextaction = 'acccopy'; - $accountUsers = $account->getUsersAccount(); - $accountGroups = $account->getGroupsAccount(); + $account->accountUsersId = SP_Users::getUsersForAccount($account->accountId); + $account->accountUserGroupsId = SP_Groups::getGroupsForAccount($account->accountId); $accountData = $account->getAccount(); break; case "accedit": $savetype = 2; $title = array('class' => 'titleOrange', 'name' => _('Editar Cuenta')); $showform = true; - $nextaction = 'accedit'; + $nextaction = 'accview'; - $accountUsers = $account->getUsersAccount(); - $accountGroups = $account->getGroupsAccount(); + $account->accountUsersId = SP_Users::getUsersForAccount($account->accountId); + $account->accountUserGroupsId = SP_Groups::getGroupsForAccount($account->accountId); $accountData = $account->getAccount(); break; case "accdelete": @@ -82,8 +82,8 @@ switch ($action) { $_SESSION["accParentId"] = $data['id']; $account->incrementViewCounter(); - $accountUsers = $account->getUsersAccount(); - $accountGroups = $account->getGroupsAccount(); + $account->accountUsersId = SP_Users::getUsersForAccount($account->accountId); + $account->accountUserGroupsId = SP_Groups::getGroupsForAccount($account->accountId); $accountData = $account->getAccount(); break; case "accviewhistory": @@ -92,8 +92,8 @@ switch ($action) { $showform = false; $account->accountIsHistory = true; - $accountUsers = $account->getUsersAccount(); - $accountGroups = $account->getGroupsAccount(); + $account->accountUsersId = SP_Users::getUsersForAccount($account->accountId); + $account->accountUserGroupsId = SP_Groups::getGroupsForAccount($account->accountId); $accountData = $account->getAccountHistory(); break; default : @@ -287,8 +287,8 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); $userSelected = ''; if ($gotData && $otherUserId != $accountData->account_userId) { - if (isset($accountUsers) && is_array($accountUsers)) { - $userSelected = (in_array($otherUserId, $accountUsers)) ? "selected" : ""; + if (isset($account->accountUsersId ) && is_array($account->accountUsersId )) { + $userSelected = (in_array($otherUserId, $account->accountUsersId )) ? "selected" : ""; } echo ""; } else{ @@ -318,8 +318,8 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); $uGroupSelected = ''; if ($gotData && $otherGroupId != $accountData->account_userGroupId) { - if (isset($accountGroups) && is_array($accountGroups)) { - $uGroupSelected = (in_array($otherGroupId, $accountGroups)) ? "selected" : ""; + if (isset($account->accountUserGroupsId) && is_array($account->accountUserGroupsId)) { + $uGroupSelected = (in_array($otherGroupId, $account->accountUserGroupsId)) ? "selected" : ""; } echo ""; } else{ @@ -429,7 +429,7 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); | usergroup_name; ?> | |
| @@ -438,7 +438,7 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); foreach ($users as $userId => $userName) { if ($userId != $accountData->account_userId) { - if (in_array($userId, $accountUsers)) { + if (in_array($userId, $account->accountUsersId )) { $accUsers[] = $userName; } } @@ -450,7 +450,7 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); | ||
| @@ -459,7 +459,7 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); foreach ($groups as $groupId => $groupName) { if ($groupId != $accountData->account_userGroupId) { - if (in_array($groupId, $accountGroups)) { + if (in_array($groupId, $account->accountUserGroupsId)) { $accGroups[] = $groupName; } } @@ -486,9 +486,8 @@ $maxFileSize = round(SP_Config::getValue('files_allowed_size') / 1024, 1); accountIsHistory): ?> - |