示例#1
0
 public function changePassword()
 {
     try {
         $l2 = $this->getL2();
         $newPassword = $l2->passwordEncrypt($this->getNewPassword());
         $login = user()->get('login');
         $res = $l2->getDb()->createCommand("UPDATE {{accounts}} SET password = :password WHERE login = :login LIMIT 1")->bindParam('password', $newPassword, PDO::PARAM_STR)->bindParam('login', $login, PDO::PARAM_STR)->execute();
         if ($res !== FALSE) {
             if (user()->get('email')) {
                 notify()->changePassword(user()->get('email'), array('password' => $this->getNewPassword()));
             }
             // Логирую действие юзера
             if (app()->params['user_actions_log']) {
                 $log = new UserActionsLog();
                 $log->user_id = user()->getId();
                 $log->action_id = UserActionsLog::ACTION_CHANGE_PASSWORD;
                 $log->save(FALSE);
             }
             return TRUE;
         }
     } catch (Exception $e) {
         Yii::log("Не удалось сменить пароль от аккаунта\nOld password: "******"\nNew password: "******"\nError: " . $e->getMessage() . "\n", CLogger::LEVEL_ERROR, 'cabinet_change_password');
     }
     return FALSE;
 }
示例#2
0
 public function actionIndex()
 {
     if (isset($_REQUEST)) {
         Yii::import('application.modules.deposit.extensions.Deposit.Deposit');
         $deposit = new Deposit();
         if (!$deposit->init()) {
             app()->end();
         }
         try {
             /**
              * @var Transactions $transaction
              */
             $transaction = $deposit->processed();
             $percents = (double) config('referral_program.percent');
             Yii::log("Deposit::log\n" . print_r($_REQUEST, TRUE), CLogger::LEVEL_INFO, 'application.modules.deposit.controllers.DefaultController::' . __LINE__);
             // Начисляю партнёрку
             if ($percents > 0 && $transaction) {
                 // Смотрю есть ли реферер
                 $referer = Referals::model()->find('referal = :referal', array(':referal' => $transaction->user_id));
                 if ($referer !== NULL) {
                     $refererProfile = UserProfiles::model()->with('user')->find('t.user_id = :user_id', array(':user_id' => $referer->referer));
                     if ($refererProfile) {
                         $gsModel = Gs::model()->findByPk($transaction->getGsId());
                         // Кол-во предметов которые были куплены, от них будет считаться % рефералу
                         $countItems = $transaction->getSum() / $gsModel->deposit_course_payments;
                         $profit = $countItems / 100 * $percents;
                         $refererProfile->balance += $profit;
                         $refererProfile->save(FALSE, array('balance', 'updated_at'));
                         // Логирую
                         $dataDb = array('referer_id' => $refererProfile->user_id, 'referal_id' => $transaction->getUserId(), 'profit' => $profit, 'sum' => $transaction->getSum(), 'percent' => $percents, 'transaction_id' => $transaction->getPrimaryKey(), 'created_at' => date('Y-m-d H:i:s'));
                         db()->createCommand()->insert('{{referals_profit}}', $dataDb);
                         // Отправляю письмо что баланс реферера был пополнен
                         notify()->rechargeBalanceByReferal($refererProfile->user->email, array('profit' => $profit));
                         // Логирую действие юзера
                         if (app()->params['user_actions_log']) {
                             $log = new UserActionsLog();
                             $log->user_id = $transaction->getUserId();
                             $log->action_id = UserActionsLog::ACTION_DEPOSIT_SUCCESS;
                             $log->params = json_encode($dataDb);
                             $log->save();
                         }
                     }
                 }
             }
             echo $deposit->success(Yii::t('main', 'Ваш баланс успешно пополнен.'));
         } catch (Exception $e) {
             echo $deposit->error($e->getMessage());
         }
     } else {
         $this->redirect(array('/index/default/index'));
     }
 }
示例#3
0
 public function actionAdd()
 {
     $model = new TicketsForm();
     $ticketModel = new Tickets();
     if (isset($_POST[CHtml::modelName($model)])) {
         $model->setAttributes($_POST[CHtml::modelName($model)]);
         if ($model->validate()) {
             $transaction = db()->beginTransaction();
             try {
                 // Сохраняю тикет
                 $ticket = new Tickets();
                 $ticket->category_id = $model->category_id;
                 $ticket->priority = $model->priority;
                 $ticket->date_incident = $model->date_incident;
                 $ticket->char_name = $model->char_name;
                 $ticket->title = $model->title;
                 $ticket->new_message_for_admin = 1;
                 $ticket->gs_id = user()->getGsId();
                 $ticket->status = Tickets::STATUS_ON;
                 $ticket->save(FALSE);
                 $ticketId = db()->getLastInsertID();
                 // Сохраняю переписку для тикета
                 $ticketAnswer = new TicketsAnswers();
                 $ticketAnswer->ticket_id = $ticketId;
                 $ticketAnswer->text = $model->text;
                 $ticketAnswer->save(FALSE);
                 // Логирую действие юзера
                 if (app()->params['user_actions_log']) {
                     $log = new UserActionsLog();
                     $log->user_id = user()->getId();
                     $log->action_id = UserActionsLog::ACTION_CREATE_TICKET;
                     $log->save(FALSE);
                 }
                 notify()->adminNoticeTicketAdd(array('user' => user()->getUser(), 'ticket' => $ticket));
                 user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Тикет создан.'));
                 $transaction->commit();
                 $this->redirect(array('index'));
             } catch (Exception $e) {
                 $transaction->rollback();
                 user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.'));
                 Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, __METHOD__ . ' ' . __LINE__);
             }
             $this->refresh();
         }
     }
     $this->render('//cabinet/tickets/add', array('model' => $model, 'ticketModel' => $ticketModel));
 }
 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'));
     }
 }
示例#5
0
 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');
 }
示例#6
0
 /**
  * Покупка предметов
  *
  * @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();
     }
 }
示例#7
0
 /**
  * Активация бонус кода
  */
 public function actionBonusCode()
 {
     $model = new BonusCodes('activated_code');
     if (isset($_POST['BonusCodes'])) {
         $model->setAttributes($_POST['BonusCodes']);
         if ($model->validate()) {
             $criteria = new CDbCriteria(array('condition' => 'code = :code', 'params' => array(':code' => $model->code), 'scopes' => array('opened'), 'with' => array('bonusInfo' => array('scopes' => array('opened')))));
             $bonus = BonusCodes::model()->find($criteria);
             if ($bonus === NULL) {
                 $model->addError('code', Yii::t('main', 'Неверный код.'));
             } else {
                 $bonusId = $bonus->getPrimaryKey();
                 $userId = user()->getId();
                 $bonusActivatedCount = db()->createCommand("SELECT COUNT(0) FROM {{bonus_codes_activated_logs}} WHERE code_id = :code_id")->bindParam('code_id', $bonusId, PDO::PARAM_INT)->queryScalar();
                 if ($bonus->limit > 0 && $bonusActivatedCount >= $bonus->limit) {
                     $model->addError('code', Yii::t('main', 'Код не действителен.'));
                 } elseif ($bonus->bonusInfo->date_end != '' && strtotime($bonus->bonusInfo->date_end) < time()) {
                     $model->addError('code', Yii::t('main', 'Время действия кода закончено.'));
                 } else {
                     // Проверка чтобы юзер заюзал код только один раз
                     $user = db()->createCommand("SELECT created_at FROM {{bonus_codes_activated_logs}} WHERE code_id = :code_id AND user_id = :user_id LIMIT 1")->bindParam('code_id', $bonusId, PDO::PARAM_INT)->bindParam('user_id', $userId, PDO::PARAM_INT)->queryrow();
                     if ($user) {
                         user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Вы уже активировали этот код (дата активации: :date_activation).', array(':date_activation' => $user['created_at'])));
                     } else {
                         $tr = db()->beginTransaction();
                         try {
                             $userBonuses = new UserBonuses();
                             $userBonuses->bonus_id = $bonus->bonus_id;
                             $userBonuses->user_id = user()->getId();
                             $userBonuses->save(FALSE);
                             // Логирую активацию
                             $log = new BonusCodesActivatedLogs();
                             $log->code_id = $bonus->getPrimaryKey();
                             $log->user_id = user()->getId();
                             $log->save(FALSE);
                             $tr->commit();
                             // Логирую действие юзера
                             if (app()->params['user_actions_log']) {
                                 $log = new UserActionsLog();
                                 $log->user_id = user()->getId();
                                 $log->action_id = UserActionsLog::ACTION_ACTIVATED_BONUS_CODE;
                                 $log->params = json_encode($bonus->getAttributes());
                                 $log->save(FALSE);
                             }
                             user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Бонус код активирован.'));
                         } catch (Exception $e) {
                             $tr->rollback();
                             user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.'));
                             Yii::log("Не удалось активировать бонус код\nBonus id: " . $bonusId . "\nError: " . $e->getMessage() . "\n", CLogger::LEVEL_ERROR, 'activation_bonus_code');
                         }
                     }
                     $this->refresh();
                 }
             }
         }
     }
     $this->render('//cabinet/bonuses/bonus-code', array('model' => $model));
 }