public static function checkLoginOrEmailExists($login, $email) { $sql = 'SELECT * FROM `%s` WHERE STRCMP(`login`,"%s") = 0 or (LENGTH("%s") > 0 and STRCMP(`email`,"%s") = 0) '; $sql = sprintf($sql, USERS_TABLE, DB::escape($login), DB::escape($email), DB::escape($email)); $aResult = DB::query($sql); if (!empty($aResult)) { throw new Exception('Login or email already registered. Login - ' . $login . ' Email:' . $email); } }
/** * Обновляет запись об частоте */ public static function update($id, $priority, $change) { $sql = 'UPDATE `%s` SET `sitemap_xml_priority`="%f",`sitemap_xml_change`="%s" WHERE `id`="%d"'; $sql = sprintf($sql, SITEMAP_TABLE, floatval($priority), \Faid\DB::escape($change), intval($id)); DB::post($sql); $register = new SystemRegister('System/Sitemap/'); if ($register->get('sitemap.xml.disable')->value == 0) { self::generate(); } }
/** * * Отыскивает запись о пользователе в БД по его логину * @param string $login * @throws Exception * @return array */ public static function getByLogin($login) { $sql = 'select * from `%s` where `login`="%s" '; $sql = sprintf($sql, USERS_TABLE, \Faid\DB::escape($login)); $found = DB::get($sql); if (empty($found)) { throw new \NotFoundException('User with login `' . $login . '` not found'); } return $found; }
protected static function isLimitExceeded() { $sql = sprintf(' select count(*) as `count` from %s where `ip`="%d" ', self::TableName, DB::escape(ip2long(self::$ip))); $data = DB::get($sql); if (!empty($data)) { $result = $data['count']; } else { $result = 0; } self::cleanDB(); return $result >= self::$config['MaxConnections']; }
protected function loadLastFail() { $lastId = !empty($this->successId) ? $this->successId : 0; $condition = array('user_id' => $this->user->id->getValue(), 'status' => LoginAttempt::FailStatus, sprintf('`id` > "%d"', DB::escape($lastId)), sprintf('`date` < NOW() ')); $this->failCount = DBSimple::getRowsCount(LoginAttempt::TableName, $condition); $last = DBSimple::get(LoginAttempt::TableName, $condition, 'order by `id` desc'); if (!empty($last)) { $model = new LoginAttempt($last); $this->failLastIp = $model->host->getValue(); $this->failLastDate = $model->date->getValue(); } }
/** * Обновляет данные о пользователе * @param $id * @param $login * @param $password * @param $rights */ public static function updateUser($id, $login, $password, $rights = '') { if (is_array($rights)) { $rights = implode("\r\n", $rights); } $id = intval($id); $login = \Faid\DB::escape($login); $password = \Faid\DB::escape($password); $rights = \Faid\DB::escape($rights); // $sql = 'UPDATE `%s` SET `login`="%s",`password`="%s",`rights`="%s" WHERE `id`="%d"'; $sql = sprintf($sql, CMS_AUTH_TABLE, $login, $password, $rights, $id); DB::post($sql); }
/** * Осуществляет сортировку по определенному полю у конкретного документа */ public static function sortByField($nId, $szDocumentName, $szFieldName, $bAsc = true) { // $nId = IntegerHelper::toNatural($nId); $szDocumentName = \Faid\DB::escape($szDocumentName); $szFieldName = \Faid\DB::escape($szFieldName); $bAsc = intval($bAsc); // // Получаем всех детей элемента, которые имеют указанный документ в кач. имени // $szTable = call_user_func([$szDocumentName, 'getTableName']); $sql = <<<SQL \tSELECT `sitemap`.id,`sitemap`.document_id \tFROM `%s` as `sitemap` \tINNER JOIN `%s` as `document` \tON `sitemap`.`parent` = %d and `sitemap`.document_id = `document`.id and `sitemap`.document_name = "%s" \tORDER BY `document`.%s %s SQL; $sql = sprintf($sql, SITEMAP_TABLE, $szTable, $nId, $szDocumentName, $szFieldName, $bAsc ? ' ASC' : ' DESC'); $aDocumentsData = DB::query($sql); // Получаем всех остальных детей $sql = 'SELECT * FROM `%s` WHERE `parent`="%d" and STRCMP(`document_name`,"%s") <> 0 ORDER by `order`'; $sql = sprintf($sql, SITEMAP_TABLE, $nId, $szDocumentName); $aOtherData = DB::query($sql); // Выстраиваем детей совмещаем массивы, неотсортированные элементы остаются на своих местах $aResult = array(); $nOrder = 0; while (sizeof($aDocumentsData) > 0 || sizeof($aOtherData) > 0) { if (!empty($aOtherData) && $aOtherData[0]['order'] == $nOrder) { $aElement = array_shift($aOtherData); $aResult[] = $aElement['id']; } else { // $aElement = array_shift($aDocumentsData); $aResult[] = $aElement['id']; } $nOrder++; } // Sitemap::manualOrder($nId, $aResult); }
public function update($group, $permissions) { if (empty($group)) { $this->AddAlert('Группа пользователей не выбрана'); $this->jump('./'); } set_time_limit(0); $page = 0; $groupInfo = DBSimple::get(ACL_TABLE, ['name' => $group]); if (empty($groupInfo)) { throw new \InvalidArgumentException(sprintf('Group "%s" not found, failed to update group permissions', htmlspecialchars($group))); } $permissions = $this->filterPermissionsByGroup($group, $permissions); do { // получаем пользователей $sql = <<<SQL \tselect u.* from %s as u \tinner join %s as r \ton r.entity = concat("%s", u.id) \twhere r.actionId = "%s" \torder by id asc \tlimit %d,%d SQL; $sql = sprintf($sql, \UserAccount::getTableName(), \ACL_GRANT_TABLE, \Faid\DB::escape(\UserAccount::ModelName), $groupInfo['id'], $page * self::Limit, self::Limit); $data = DB::query($sql); // устанавливаем каждому права foreach ($data as $row) { $user = new \UserAccount($row); $tmp = $user->rights->getValue(); $tmp = array_merge($tmp, $permissions); $user->rights = $tmp; $user->update(); } $page++; } while (sizeof($data) != 0); $this->addAlert('Права обновлены'); $this->jump('./'); }
public static function autoLoadFromCookie() { $isCookieSet = !empty($_COOKIE[self::cookieName]); if (!$isCookieSet) { return; } $passwordHash = $_COOKIE[self::cookieName]; // Запрос провещяюрий есть ли юзер или нет и не забанен ли он $sql = 'SELECT * FROM `%s` WHERE LENGTH(`confirmation_code`) = 0 and md5(CONCAT(`password`,"%s",`id`)) = "%s"'; $sql = sprintf($sql, USERS_TABLE, DB::escape(\Faid\Configure\Configure::read(\Extasy\CMS::SaltConfigureKey)), DB::escape($passwordHash)); // $aFound = DB::get($sql); if (empty($aFound)) { return false; } try { self::forceLogin(new UserAccount($aFound)); return true; } catch (Exception $e) { // Игнорируем случай неверной аутентификации } return false; }
/** * @name Функция export * @author Midgard * * @desc Функция экспортирует .sql файл из базы. * Параметр $db_table * Если указан массив таблиц, то делается дамп указанных таблиц. * Если $db_table - строка (имя таблицы), то дамп делается только этой таблицы. * * @param $dbase Экспортируемая база данных. * @param $db_table Необязательный параметр. пспользуется при экспорте выбранных(-ой) * таблиц(-ы) * @param $storeTableData bool - Если флаг равен true то делается также дамп данных */ function export($dbase = '', $db_table = '', $storeTableData = true) { if (empty($db_table)) { // выбираю все таблицы из базы $aTable = array(); if (!empty($dbase)) { $aTable = $this->execQuery('SHOW TABLES FROM `' . $dbase . '`', false); } else { $aTable = $this->execQuery('SHOW TABLES', false); } foreach ($aTable as $key => $row) { $aTable[$key] = $row[0]; } } else { $aTable = array($db_table); } // получаем список create table; $aTableCreate = array(); foreach ($aTable as $row) { if (!empty($dbase)) { $sql = 'SHOW CREATE TABLE `' . \Faid\DB::escape($dbase) . '`.`' . \Faid\DB::escape($row) . '`'; } else { $sql = 'SHOW CREATE TABLE `' . \Faid\DB::escape($row) . '`'; } $aTmp = $this->execQuery($sql, false); $aTableCreate[$row] = $aTmp[0][1]; } // пишем заголовки и с учетом дропа таблицы $szSQLCreate = ''; $szSQLTemplate = 'DROP TABLE IF EXISTS `%s` ;' . "\r\n"; foreach ($aTableCreate as $szTableName => $szTableCreate) { $szSQLCreate .= sprintf($szSQLTemplate, \Faid\DB::escape($szTableName)); $szSQLCreate .= $szTableCreate . ';' . "\r\n"; } $szResult = $szSQLCreate; // получаем все данные для каждой таблицы if ($storeTableData) { $aTableData = array(); foreach ($aTable as $row) { if (!empty($dbase)) { $sql = 'SELECT * FROM `' . \Faid\DB::escape($dbase) . '`.`' . \Faid\DB::escape($row) . '`'; } else { $sql = 'SELECT * FROM `' . \Faid\DB::escape($row) . '`'; } $aTableData[$row] = $this->execQuery($sql, true); } // формируем SQL-запросы $sqlInsert = ''; $sqlTemplate = 'INSERT INTO `%s` SET %s;' . "\r\n"; foreach ($aTableData as $szTableName => $aCurrentTableData) { foreach ($aCurrentTableData as $row) { $aTmp = array(); foreach ($row as $field_name => $field_value) { $aTmp[] = '`' . \Faid\DB::escape($field_name) . '`="' . \Faid\DB::escape($field_value) . '"'; } $szTmp = implode(',', $aTmp); $sqlInsert .= sprintf($sqlTemplate, \Faid\DB::escape($szTableName), $szTmp); } } $szResult .= "\r\n" . $sqlInsert; } return $szResult; }
/** * ------------------------------------------------------------------------------------------- * Сохраняет результат работы метода exec * @return * ------------------------------------------------------------------------------------------- */ public static function storeRows() { $sqlTemplate = 'UPDATE `%s` SET `full_url`="%s" where `id`="%d"'; foreach (self::$aResult as $nId => $szFullUrl) { $sql = sprintf($sqlTemplate, SITEMAP_TABLE, \Faid\DB::escape($szFullUrl), intval($nId)); DB::post($sql); } }
public static function selectAllGrantsForEntity($entity) { $sql = <<<SQL \t\tselect a.fullPath FROM `%s` AS g \t\tINNER JOIN `%s` AS a \t\tON a.id = g.actionId \t\tWHERE g.entity = "%s" SQL; $sql = sprintf($sql, ACL_GRANT_TABLE, ACL_TABLE, \Faid\DB::escape($entity)); $data = DB::query($sql); $result = array(); foreach ($data as $row) { $result[$row['fullPath']] = true; } return $result; }
protected static function selectDocumentScriptParents($documentName) { // Получаем скрипты, где может быть дочерним этот документ $sql = 'SELECT * FROM `%s` WHERE `script` in (SELECT `path` FROM `%s` WHERE `document_name` = "%s")'; $sql = sprintf($sql, SITEMAP_TABLE, SITEMAP_SCRIPT_CHILD_TABLE, \Faid\DB::escape($documentName)); return DB::query($sql); }
/** * Метод осуществляет поиск по карте сайте * @param string $szKeyword строка поисковая ключа * @return array */ public static function search($szKeyword, $nStart, $nLimit, $filter = array()) { $szKeyword = to_search_string($szKeyword); $nStart = intval($nStart); $nLimit = intval($nLimit); // if (strlen($szKeyword) < 2) { throw new Exception('Can`t start search. Search keyword too small'); } if (!empty($filter)) { foreach ($filter as $key => $row) { $filter[$key] = '"' . DB::escape($row) . '"'; } $sqlFilter = sprintf(' and `document_name` in (%s)', implode(',', $filter)); } else { $sqlFilter = ''; } $sql = 'SELECT SQL_CALC_FOUND_ROWS *,UNIX_TIMESTAMP(`date_updated`) as `unixtimestamp` FROM `%s` WHERE ( `name` LIKE "%%%s%%" or `full_url` LIKE "%%%s%%" ) and (`document_id` != 0 or LENGTH(`script_admin_url`) > 0) %s ORDER by `name` LIMIT %d,%d'; $sql = sprintf($sql, SITEMAP_TABLE, $szKeyword, $szKeyword, $sqlFilter, $nStart, $nLimit); $aResult = DB::query($sql); $sql = 'SELECT FOUND_ROWS() as `totalcount`'; $aFound = DB::Get($sql); self::$nItemCount = $aFound['totalcount']; return $aResult; }
public static function deleteAlias($id, $url) { $id = IntegerHelper::toNatural($id); $sql = 'DELETE FROM `%s` WHERE `page_id`="%d" and `url`="%s" '; $sql = sprintf($sql, SITEMAP_HISTORY_TABLE, $id, \Faid\DB::escape($url)); DB::post($sql); }
/** * Сохраняет значение в контроле */ public function setValue($data) { $this->value = $data; $sql = 'update `%s` set `value`="%s" where `id` = "%d"'; $sql = sprintf($sql, CCONFIG_CONTROL_TABLE, \Faid\DB::escape($data), $this->id); DB::post($sql); }
/** * Обновляет лист в бд */ public static function update(SystemRegister $parent, $id, $szName, $szValue, $szComment, $szType) { // Экранируем переменные $id = intval($id); $szName = \Faid\DB::escape($szName); $szValue = \Faid\DB::escape($szValue); $szComment = \Faid\DB::escape($szComment); $szType = \Faid\DB::escape($szType); // запрос $sql = 'UPDATE `%s` SET `name`="%s",`value`="%s",`comment`="%s",`type`="%s" WHERE `id`="%s"'; $sql = sprintf($sql, SYSTEMREGISTER_TABLE, $szName, $szValue, $szComment, $szType, $id); // DB::post($sql); // обновляем кеш предка self::updateChildCache($parent->getId()); self::updateGetCache($szName, $parent->getId()); return $id; }
protected static function buildSQLSelectCondition() { $parts = array(); if (!empty(self::$lastSearchRequest->search_phrase)) { $parts[] = sprintf('( `short` like "%%%s%%" or `full` like "%%%s%%" )', to_search_string(self::$lastSearchRequest->search_phrase), to_search_string(self::$lastSearchRequest->search_phrase)); } $emptyDate = '0000-00-00 00:00:00'; $validateDateFrom = !empty(self::$lastSearchRequest->date_from) && $emptyDate != self::$lastSearchRequest->date_from; if ($validateDateFrom) { $parts[] = sprintf('a.date >= "%s"', DB::escape(selF::$lastSearchRequest->date_from)); } $validateDateTo = !empty(self::$lastSearchRequest->date_to) && $emptyDate != self::$lastSearchRequest->date_to; if ($validateDateTo) { $parts[] = sprintf('a.date <= "%s"', DB::escape(selF::$lastSearchRequest->date_to)); } if (!empty(self::$lastSearchRequest->user)) { $parts[] = sprintf(' a.user_login = "******"', DB::escape(self::$lastSearchRequest->user)); } if (!empty($parts)) { return implode(' and ', $parts); } else { return ' 1 '; } }
protected static function checkSchemaExists($schemaName) { // Делаем запрос, на проверку существования записей в контролах $sql = 'select * from `%s` WHERE `name`="%s"'; $sql = sprintf($sql, CCONFIG_SCHEMA_TABLE, \Faid\DB::escape($schemaName)); $result = DB::get($sql); if (!empty($result)) { return $result; } else { return false; } }
/** * Проверяет что урл доступен */ protected static function checkUrlAvailable($sitemapId, $parentId, $urlKey) { $sitemapId = IntegerHelper::toNatural($sitemapId); $parentId = IntegerHelper::toNatural($parentId); $urlKey = \Faid\DB::escape($urlKey); // Получаем все документы с указанным url_key и parent $sql = 'select * from `%s` where parent = "%d" and `url_key`="%s" '; $sql = sprintf($sql, SITEMAP_TABLE, $parentId, $urlKey); $data = DB::query($sql); // Если их 0, то всё ок if (sizeof($data) == 0) { return; } // Если их больше 1 if (sizeof($data) > 1) { // бросаем исключение $message = 'Sitemap tree conflict in parent_id=%d and url_key=%s '; $message = sprintf($message, $parentId, $urlKey); throw new SiteMapException($message); } // Если одна, то сравниваем индексы $data = $data[0]; if ($data['id'] != $sitemapId) { // не совпадают // бросаем исключение $message = 'Sitemap tree conflict for sitemap_id=%d in parent_id=%d and url_key=%s url already used by sitemap_id="%d"'; $message = sprintf($message, $sitemapId, $parentId, $urlKey, $data['id']); throw new SiteMapException($message); } }
/** * Сохраняет в бд данные */ protected function store() { // Сохраняем вкладки $sql = 'update `%s` set `name`="%s",`title`="%s",`sitemapId`="%d" where `id`="%d"'; $sql = sprintf($sql, CCONFIG_SCHEMA_TABLE, \Faid\DB::escape($this->name), \Faid\DB::escape($this->title), \Faid\DB::escape($this->sitemapId), $this->id); DB::post($sql); }
/** * ------------------------------------------------------------------------------------------- * @desc Создает строку для поиска в MySQL таблице * @return * ------------------------------------------------------------------------------------------- */ function to_search_string($str) { return addCslashes(str_replace('\\', '\\\\', htmlspecialchars(\Faid\DB::escape(trim($str)))), '_%'); }
public static function selectChildWithoutAdditionalByDocument($nId, $szDocument, $nCount = 0, $nStart = 0) { $szDocument = \Faid\DB::escape($szDocument); $nId = intval($nId); $nCount = intval($nCount); $nStart = intval($nStart); $nStart = $nStart < 0 ? 0 : $nStart; // Проверяем работают ли языковые версии $szAdditionalSQL = ' and `document_name`="' . $szDocument . '" '; return self::selectChilds($nId, $szAdditionalSQL, '', $nStart, $nCount); }