/** * @return Lineage */ public function getL2() { if (!$this->_l2) { $this->_l2 = l2('ls', user()->getLsId())->connect(); } return $this->_l2; }
public function actionRemoveHwid() { if (request()->isPostRequest) { try { $gs = Gs::model()->opened()->findByPk(user()->getGsId()); $l2 = l2('ls', $gs->login_id)->connect(); $res = $l2->removeHWID(user()->get('login')); if ($res > 0) { // Логирую действие юзера if (app()->params['user_actions_log']) { $log = new UserActionsLog(); $log->user_id = user()->getId(); $log->action_id = UserActionsLog::ACTION_SERVICES_REMOVE_HWID; $log->save(FALSE); } user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Привязка к HWID удалена.')); } else { user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Аккаунт не привязан к HWID.')); } } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, __METHOD__ . ' ' . __LINE__); } $this->refresh(); } $this->render('//cabinet/services/remove-hwid'); }
public function init() { if (($data = cache()->get(CacheNames::SERVER_STATUS)) === FALSE) { if (config('server_status.allow') == 1) { $data['content'] = array(); $data['totalOnline'] = 0; $criteria = new CDbCriteria(array('select' => 't.name, t.id, t.fake_online, t.ip, t.port', 'scopes' => array('opened'), 'with' => array('ls' => array('select' => 'ls.ip, ls.port, ls.name', 'scopes' => array('opened'))))); $gsList = Gs::model()->findAll($criteria); if ($gsList) { foreach ($gsList as $gs) { try { $l2 = l2('gs', $gs->id)->connect(); // Кол-во игроков $online = $l2->getDb()->createCommand("SELECT COUNT(0) FROM `characters` WHERE `online` = 1")->queryScalar(); // Fake online if (is_numeric($gs->fake_online) && $gs->fake_online > 0) { $online += Lineage::fakeOnline($online, $gs->fake_online); } $data['content'][$gs->id] = array('gs_status' => Lineage::getServerStatus($gs->ip, $gs->port), 'ls_status' => isset($gs->ls) ? Lineage::getServerStatus($gs->ls->ip, $gs->ls->port) : 'offline', 'online' => $online, 'gs' => $gs); $data['totalOnline'] += $online; } catch (Exception $e) { $data[$gs->id]['error'] = $e->getMessage(); } } } if (config('server_status.cache') > 0) { cache()->set(CacheNames::SERVER_STATUS, $data, config('server_status.cache') * 60); } } } app()->controller->renderPartial('//server-status', $data); }
public function actionActivated($_hash) { $cache = new CFileCache(); $cache->init(); $hash = $cache->get('registerActivated' . $_hash); $cache->delete('registerActivated' . $_hash); // Ключ не найден, возможно пытаются подобрать или истекло время отведенное для активации аккаунта if ($hash === FALSE) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Ключ для активации аккаунта не найден.')); $this->redirect(array('index')); } $user = Users::model()->findByPk($hash['user_id']); if (!$user) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Аккаунт не найден.')); } elseif ($user->isActivated()) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Аккаунт уже активирован.')); } else { // Создаю игровой аккаунт try { $l2 = l2('ls', $user->ls_id)->connect(); $l2->insertAccount($user->login, $hash['password']); $user->activated = Users::STATUS_ACTIVATED; $user->save(FALSE); user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Активация аккаунта прошла успешно. Приятной игры!')); notify()->registerStep2($hash['email'], array('login' => $user->login, 'password' => $hash['password'])); } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, $e->getMessage()); } } $this->redirect(array('index')); }
/** * Проверка логина на сервере * * @param $attr */ public function loginExists($attr) { if (!$this->hasErrors($attr)) { $siteAccountUserId = NULL; try { $found = FALSE; $login = $this->getLogin(); $lsId = $this->getLsId(); $l2 = l2('ls', $lsId)->connect(); $command = $l2->getDb()->createCommand(); $command->where('login = :login', array('login' => $login)); $command->from('accounts'); $account = $command->queryRow(); // Ищю аккаунт на сайте $siteAccount = db()->createCommand("SELECT user_id FROM {{users}} WHERE login = :login LIMIT 1")->queryRow(TRUE, array('login' => $login)); if (isset($siteAccount['user_id'])) { $siteAccountUserId = $siteAccount['user_id']; } // Аккаунт на сервере найден if ($account) { if ($account['password'] == $l2->passwordEncrypt($this->getPassword())) { // Аккаунта на сайте нет, создаю его так как на сервере он уже есть if (!$siteAccount) { $email = NULL; $columnNames = $l2->getDb()->getSchema()->getTable('accounts')->getColumnNames(); if (is_array($columnNames)) { foreach ($columnNames as $column) { if (strpos($column, 'mail') !== FALSE && isset($account[$column])) { $email = $account[$column]; } } } // Создаю аккаунт на сайте $userModel = new Users(); $userModel->password = NULL; $userModel->login = $login; $userModel->email = $email; $userModel->activated = Users::STATUS_ACTIVATED; $userModel->role = Users::ROLE_DEFAULT; $userModel->ls_id = $lsId; $userModel->save(FALSE); $siteAccountUserId = $userModel->getPrimaryKey(); } $found = TRUE; } } // Аккаунт не найден if (!$found) { if ($siteAccountUserId) { UsersAuthLogs::model()->addErrorAuth($siteAccountUserId); } $this->incrementBadAttempt(); $this->addError($attr, Yii::t('main', 'Неправильный Логин или Пароль.')); } } catch (Exception $e) { $this->addError($attr, Yii::t('main', 'Произошла ошибка! Поробуйте повторить позже.')); } } }
public function actionActivation($bonus_id) { if (request()->isPostRequest) { $char_id = (int) request()->getPost('char_id'); $criteria = new CDbCriteria(); $criteria->addCondition('user_id = :user_id AND t.id = :id'); $criteria->params = array(':user_id' => user()->getId(), ':id' => $bonus_id); $criteria->with = array('bonusInfo' => array('scopes' => array('opened'), 'with' => array('items' => array('scopes' => array('opened'), 'with' => 'itemInfo')))); $bonus = UserBonuses::model()->find($criteria); if ($bonus === NULL) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Бонус не найден.')); } elseif ($bonus->status == 1) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Бонус уже активирован (дата активации: :date_activation).', array(':date_activation' => $bonus->updated_at))); } else { try { $l2 = l2('gs', user()->gs_id)->connect(); $charIdfieldName = $l2->getField('characters.char_id'); $character = $l2->getDb()->createCommand("SELECT COUNT(0) FROM {{characters}} WHERE " . $charIdfieldName . " = :char_id")->bindParam(':char_id', $char_id, PDO::PARAM_INT)->queryScalar(); if (!$character) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Персонаж на сервере не найден.')); } else { // Предметы для записи в БД $items = array(); foreach ($bonus->bonusInfo->items as $item) { $items[] = array('owner_id' => $char_id, 'item_id' => $item->item_id, 'count' => $item->count, 'enchant' => $item->enchant); } $res = $l2->multiInsertItem($items); if ($res > 0) { $bonus->status = 1; $bonus->save(FALSE); // Логирую действие юзера if (app()->params['user_actions_log']) { $log = new UserActionsLog(); $log->user_id = user()->getId(); $log->action_id = UserActionsLog::ACTION_ACTIVATED_BONUS; $log->params = json_encode($items); $log->save(FALSE); } user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Бонус активирован.')); } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Не удалось активировать Ваш бонус.')); } } } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, __METHOD__ . ' ' . __LINE__); } } } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Ошибка! Переданы не все параметры.')); } $this->redirectBack(); }
public function actionAccounts($ls_id) { $perPage = 20; try { $l2 = l2('ls', $ls_id)->connect(); $accounts = $l2->accounts()->queryAll(); $dataProvider = new CArrayDataProvider($accounts, array('id' => 'accounts', 'sort' => array('attributes' => array('login')), 'pagination' => array('pageSize' => $perPage, 'pageVar' => 'page'))); } catch (Exception $e) { Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, 'LoginServersController::' . __LINE__); user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('backend', $e->getMessage())); $this->redirect(array('index')); } $ls = $this->loadModel($ls_id); $this->render('//ls/accounts/index', array('ls' => $ls, 'dataProvider' => $dataProvider, 'perPage' => $perPage)); }
public function init() { if (($data = cache()->get(CacheNames::TOP_PK)) === FALSE) { if (config('top.pk.allow') == 1 && (int) config('top.pk.gs_id') > 0) { $data['content'] = array(); try { $data['content'] = l2('gs', config('top.pk.gs_id'))->connect()->getTopPk(config('top.pk.limit')); if (config('top.pk.cache') > 0) { cache()->set(CacheNames::TOP_PK, $data, config('top.pk.cache') * 60); } } catch (Exception $e) { $data['error'] = $e->getMessage(); } } } app()->controller->renderPartial('//toppk', $data); }
/** * Возвращает список персонажей * * @return mixed * * @throws Exception */ public function getCharacters() { $cacheName = strtr(CacheNames::CHARACTER_LIST, array(':gs_id' => $this->getGsId(), ':user_id' => $this->getId())); if (($characters = cache()->get($cacheName)) === FALSE) { try { $l2 = l2('gs', $this->getGsId())->connect(); $command = $l2->getDb()->createCommand(); $command->where('account_name = :account_name', array(':account_name' => $this->get('login'))); $command->setOrder('char_name'); $characters = $l2->characters($command)->queryAll(); cache()->set($cacheName, $characters, 300); } catch (Exception $e) { throw new Exception(Yii::t('main', 'Не удалось выбрать всех персонажей с сервера.')); } } return $characters; }
public function actionStep2($hash) { $cache = new CFileCache(); $cache->init(); if (($hashInfo = $cache->get($this->_cacheName . $hash)) !== FALSE) { $cache->delete($this->_cacheName . $hash); $user = db()->createCommand("SELECT COUNT(0) FROM `{{users}}` WHERE `email` = :email AND `login` = :login LIMIT 1")->bindParam('email', $hashInfo['email'], PDO::PARAM_STR)->bindParam('login', $hashInfo['login'], PDO::PARAM_STR)->queryScalar(); if ($user) { $newPassword = Users::generatePassword(rand(Users::PASSWORD_MIN_LENGTH, Users::PASSWORD_MAX_LENGTH)); // Обновляю пароль на сервере try { $l2 = l2('ls', $hashInfo['ls_id'])->connect(); $encryptPassword = $l2->passwordEncrypt($newPassword); $login = $hashInfo['login']; $email = $hashInfo['email']; $res = $l2->getDb()->createCommand("UPDATE {{accounts}} SET password = :password WHERE login = :login LIMIT 1")->bindParam('password', $encryptPassword, PDO::PARAM_STR)->bindParam('login', $login, PDO::PARAM_STR)->execute(); if ($res) { $encryptPassword = Users::hashPassword($newPassword); db()->createCommand("UPDATE {{users}} SET password = :password WHERE email = :email AND login = :login LIMIT 1")->bindParam('password', $encryptPassword, PDO::PARAM_STR)->bindParam('email', $email, PDO::PARAM_STR)->bindParam('login', $login, PDO::PARAM_STR)->execute(); notify()->forgottenPasswordStep2($email, array('password' => $newPassword)); user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'На почту указанную при регистрации отправлен новый пароль.')); } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); } } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, $e->getMessage()); } } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Аккаунт не найден.')); } } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Ключ для восстановления пароля не найден.')); } if (user()->hasFlash(FlashConst::MESSAGE_ERROR)) { $this->redirect(array('index')); } $this->redirect(array('/login/default/index')); }
private function items() { $items = array(); if ($this->_gs->stats_items_list != '') { $items = explode(',', $this->_gs->stats_items_list); $items = array_map('intval', $items); } return $this->renderPartial('//stats/' . __FUNCTION__, array('content' => l2('gs', $this->_gs_id)->connect()->getItemsControl($items)), TRUE); }
public function actionTeleport($char_id) { $statusOn = ActiveRecord::STATUS_ON; $gsId = user()->getGsId(); $cache = new CFileCache(); $cache->init(); $dependency = new CDbCacheDependency("SELECT MAX(UNIX_TIMESTAMP(updated_at)) FROM {{gs}} WHERE id = :id AND status = :status LIMIT 1"); $dependency->params = array('id' => $gsId, 'status' => $statusOn); $gsInfo = db()->cache(3600 * 24, $dependency)->createCommand("SELECT * FROM {{gs}} WHERE id = :id AND status = :status LIMIT 1")->bindParam('status', $statusOn, PDO::PARAM_INT)->bindParam('id', $gsId, PDO::PARAM_INT)->queryRow(); if ($gsInfo === FALSE || !$gsInfo['allow_teleport']) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Телепортация отключена.')); $this->redirect(array('index')); } $userId = user()->getId(); $cacheName = strtr(CacheNames::CHARACTER_TELEPORT, array(':user_id' => $userId, ':char_id' => $char_id, ':gs_id' => $gsId)); $teleportsInfo = $cache->get($cacheName); if ($teleportsInfo !== FALSE) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Вы уже недавно были телепортированы в :city.', array(':city' => '<b>' . $teleportsInfo['city'] . '</b>'))); $this->redirect(array('index')); } try { $l2 = l2('gs', $gsId)->connect(); $charIdFieldName = $l2->getField('characters.char_id'); $command = $l2->getDb()->createCommand(); $command->where($charIdFieldName . ' = :char_id AND account_name = :account_name', array(':char_id' => $char_id, ':account_name' => user()->get('login'))); $character = $l2->characters($command)->queryRow(); if ($character === FALSE) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Персонаж не найден.')); $this->redirect(array('index')); } // Если в игре if ($character['online'] != 0) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Персонаж в игре.')); $this->redirect(array('index')); } $city = Lineage::getRandomCity(); $userName = user()->get('login'); $x = $city['coordinates'][0]['x']; $y = $city['coordinates'][0]['y']; $z = $city['coordinates'][0]['z']; // Телепорт игрока $res = $l2->getDb()->createCommand("UPDATE {{characters}} SET x = :x, y = :y, z = :z WHERE " . $charIdFieldName . " = :char_id AND account_name = :account_name LIMIT 1")->bindParam('x', $x, PDO::PARAM_STR)->bindParam('y', $y, PDO::PARAM_STR)->bindParam('z', $z, PDO::PARAM_STR)->bindParam('char_id', $char_id, PDO::PARAM_INT)->bindParam('account_name', $userName, PDO::PARAM_STR)->execute(); if ($res) { $cache->set($cacheName, array('char_id' => $char_id, 'city' => $city['name']), $gsInfo['teleport_time'] * 60); // Логирую действие юзера if (app()->params['user_actions_log']) { $log = new UserActionsLog(); $log->user_id = user()->getId(); $log->action_id = UserActionsLog::ACTION_TELEPORT_TO_TOWN; $log->params = json_encode($city); $log->save(FALSE); } user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Персонаж был телепортрован в :city.', array(':city' => '<b>' . $city['name'] . '</b>'))); $this->redirect(array('index')); } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); $this->redirect(array('index')); } } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, __METHOD__ . ' ' . __LINE__); $this->redirect(array('index')); } }
/** * Проверка Логина и Email * * @param $attr * @param $params */ public function loginIsExists($attr, $params) { if (!$this->hasErrors()) { /** @var Users $user */ $user = Users::model()->find('login = :login AND email = :email', array(':login' => $this->login, ':email' => $this->email)); if ($user === NULL) { $this->addError(__FUNCTION__, Yii::t('main', 'Аккаунт не найден.')); } elseif ($user->isBanned()) { $this->addError(__FUNCTION__, Yii::t('main', 'Аккаунт заблокирован, восстановление пароля невозможно')); } elseif (!$user->isActivated()) { $this->addError(__FUNCTION__, Yii::t('main', 'Аккаунт не активирован, восстановление пароля невозможно')); } else { // Ищю аккаунт на сервере try { $l2 = l2('ls', $this->gs_list[$this->gs_id]['login_id'])->connect(); $res = $l2->getDb()->createCommand("SELECT * FROM {{accounts}} WHERE login = :login LIMIT 1")->bindParam('login', $this->login, PDO::PARAM_STR)->queryScalar(); if (!$res) { $this->addError(__FUNCTION__, Yii::t('main', 'Аккаунт не найден.')); } } catch (Exception $e) { $this->addError(__FUNCTION__, $e->getMessage()); } } } }
/** * Проверка Логина на уникальность * * @param $attribute * @param $params */ public function loginUnique($attribute, $params) { if (!$this->hasErrors()) { $login = $this->getLogin(); $lsId = $this->gs_list[$this->gs_id]['login_id']; $res = db()->createCommand("SELECT COUNT(0) FROM {{users}} WHERE login = :login AND ls_id = :ls_id LIMIT 1")->bindParam('login', $login, PDO::PARAM_STR)->bindParam('ls_id', $lsId, PDO::PARAM_INT)->queryScalar(); if ($res) { $this->addError('login', Yii::t('main', 'Логин :login уже существует.', array(':login' => '<b>' . $login . '</b>'))); return; } // Проверка логина на сервере try { $this->l2 = l2('ls', $lsId)->connect(); $res = $this->l2->getDb()->createCommand("SELECT COUNT(0) FROM {{accounts}} WHERE login = :login LIMIT 1")->bindParam('login', $login, PDO::PARAM_STR)->queryScalar(); if ($res) { $this->addError('login', Yii::t('main', 'Логин :login уже существует.', array(':login' => '<b>' . $login . '</b>'))); } } catch (Exception $e) { $this->addError('login', $e->getMessage()); } } }
/** * Покупка предметов * * @param string $category_link * * @return void */ public function actionBuy($category_link) { if (!request()->getIsPostRequest() || (!isset($_POST['pack_id']) || !filter_var($_POST['pack_id'], FILTER_VALIDATE_INT)) && $_POST['char_id'] > 0) { $this->redirect(array('index')); } // Предметы не выбраны if (!isset($_POST['items']) || !is_array($_POST['items']) || count($_POST['items']) < 1) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Выберите предметы.')); $this->redirectBack(); } // Не выбран персонаж if (!isset($_POST['char_id']) || !filter_var($_POST['char_id'], FILTER_VALIDATE_INT) && $_POST['char_id'] > 0) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Выберите персонажа.')); $this->redirectBack(); } $char_id = (int) $_POST['char_id']; $packId = (int) $_POST['pack_id']; $items = array(); foreach ($_POST['items'] as $item) { if (!isset($item['id']) || !isset($item['count'])) { continue; } $items[(int) $item['id']] = (int) $item['count']; } if (!$items) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Выберите предметы.')); $this->redirectBack(); } // Проверяю есть ли такой раздел $category = NULL; foreach ($this->getCategories() as $row) { if ($row->link == $category_link) { $category = $row; break; } } // Пытаюстся купить в закрытой/несуществующей категории if (!$category) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Покупка невозможна.')); $this->redirectBack(); } // Проверяю есть ли такой набор $pack = db()->createCommand("SELECT id FROM {{shop_items_packs}} WHERE id = ? AND category_id = ? AND status = ?")->queryRow(TRUE, array($packId, $category->getPrimaryKey(), ActiveRecord::STATUS_ON)); // Набор не найден if (!$pack) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Покупка невозможна.')); $this->redirectBack(); } // Ищю предметы в наборе $criteria = new CDbCriteria(array('condition' => 'pack_id = :pack_id', 'params' => array('pack_id' => $pack['id']), 'scopes' => array('opened'), 'with' => array('itemInfo'))); $criteria->addInCondition('id', array_keys($items)); $itemsDb = ShopItems::model()->findAll($criteria); // Если предметы не найдены if (!$itemsDb) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Покупка невозможна.')); $this->redirectBack(); } // Общая сумма $totalSum = 0; $itemsInfo = array(); // Подсчитываю что почём foreach ($itemsDb as $item) { $id = (int) $item->getPrimaryKey(); $discount = (double) $item->discount; $cost = (double) $item->cost; $costDiscount = ShopItems::costAtDiscount($cost, $discount); $count = (int) $item->count; $sum = 0; $costPerOne = (double) $cost / $count; $costPerOneDiscount = ShopItems::costAtDiscount($costPerOne, $discount); $itemsInfo[$id] = array('id' => $id, 'item_id' => (int) $item->item_id, 'cost' => $cost, 'cost_per_one' => $cost / $count, 'cost_per_one_discount' => $costPerOneDiscount, 'discount' => $discount, 'name' => $item->itemInfo->getFullName(), 'desc' => $item->itemInfo->description, 'enchant' => (int) $item->enchant); if (($count = $items[$id]) > 0) { $sum += $count * $costPerOneDiscount; } $itemsInfo[$id]['total_sum_o'] = $sum; if ($sum > 1) { $sum = round($sum, 2); } else { $sum = ceil($sum); } $itemsInfo[$id]['total_sum'] = $sum; $itemsInfo[$id]['count'] = $count; $totalSum += $sum; } // Проверка баланса if ($totalSum > 0 && user()->get('balance') < $totalSum) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'У Вас недостаточно средств на балансе для совершения сделки.')); $this->redirectBack(); } // Смотрю персонажа на сервере try { $l2 = l2('gs', user()->getGsId())->connect(); $charIdFieldName = $l2->getField('characters.char_id'); $login = user()->get('login'); $character = $l2->getDb()->createCommand("SELECT online FROM {{characters}} WHERE account_name = :account_name AND " . $charIdFieldName . " = :char_id LIMIT 1")->bindParam('account_name', $login, PDO::PARAM_STR)->bindParam('char_id', $char_id, PDO::PARAM_INT)->queryRow(); if (!$character) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Персонаж на сервере не найден.')); $this->redirectBack(); } if ($character['online'] != 0) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Персонаж НЕ должен находится в игре.')); $this->redirectBack(); } // Подготавливаю предметы для БД $itemsToDb = array(); foreach ($itemsInfo as $item) { $itemsToDb[] = array('owner_id' => $char_id, 'item_id' => $item['item_id'], 'count' => $item['count'], 'enchant' => $item['enchant']); } // Накидываю предмет(ы) в игру $res = $l2->multiInsertItem($itemsToDb); if ($res) { $userId = user()->getId(); if ($totalSum > 0) { db()->createCommand("UPDATE {{user_profiles}} SET balance = balance - :total_sum WHERE user_id = :user_id LIMIT 1")->execute(array('total_sum' => $totalSum, 'user_id' => $userId)); } // Записываю лог о сделке $itemsLog = array(); $itemList = ''; foreach ($itemsDb as $i => $item) { $itemId = $item->getPrimaryKey(); $itemList .= ++$i . ') ' . $item->itemInfo->getFullName() . ' x' . $itemsInfo[$itemId]['count'] . ' (' . $itemsInfo[$itemId]['total_sum'] . ' ' . $this->gs->currency_name . ')<br>'; $itemsLog[] = array('pack_id' => $item->pack_id, 'item_id' => $item->item_id, 'description' => $item->description, 'cost' => $item->cost, 'discount' => $item->discount, 'currency_type' => $item->currency_type, 'count' => $itemsInfo[$itemId]['count'], 'enchant' => $item->enchant, 'user_id' => user()->getId(), 'char_id' => $char_id, 'gs_id' => user()->getGsId(), 'created_at' => date('Y-m-d H:i:s')); } if ($itemsLog) { $builder = db()->schema->commandBuilder; $builder->createMultipleInsertCommand('{{purchase_items_log}}', $itemsLog)->execute(); } // Логирую действие юзера if (app()->params['user_actions_log']) { $log = new UserActionsLog(); $log->user_id = user()->getId(); $log->action_id = UserActionsLog::ACTION_DEPOSIT_SUCCESS; $log->params = json_encode($itemsLog); $log->save(FALSE); } user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Сделка прошла успешно, Нижеперечисленные предметы в ближайшее время будут зачислены на Вашего персонажа.<br><b>:item_list</b>', array(':item_list' => $itemList))); notify()->shopBuyItems(user()->get('email'), array('items' => $itemsInfo)); $this->redirectBack(); } } catch (Exception $e) { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, 'shop_buy'); $this->redirectBack(); } }