Пример #1
0
 public function validateToken($token, $player_id)
 {
     $check = Player::model()->findByAttributes(array('id' => $player_id, 'token' => $token));
     if ($check) {
         return true;
     }
     return false;
 }
Пример #2
0
 public function run()
 {
     if (Yii::app()->user->isGuest) {
         $this->render('_menuGuest');
     } else {
         $player = Player::model()->findByAttributes(array('email' => Yii::app()->user->id));
         $this->render('_menuPlayer', array('player' => $player));
     }
 }
Пример #3
0
 public static function getTournamentDetail($id)
 {
     if (!$id) {
         return false;
     }
     $return = Yii::app()->cache->get(self::CACHE_PREFIX . $id);
     if (!$return) {
         $tournament = Tournament::model()->findByPk($id);
         if (!$tournament) {
             return false;
         }
         $return['t'] = $tournament;
         if ($tournament->player_joined > 0) {
             if (in_array($tournament->status, array('playing', 'ended', 'signing'))) {
                 //查询参赛者数据
                 $players_id = Tournament_join::model()->getDbConnection()->createCommand('select * from tournament_join where tid=' . $id)->queryAll();
                 $tmp = array();
                 $return['players_join'] = array();
                 foreach ($players_id as $v) {
                     $tmp[] = $v['uid'];
                     $return['players_join'][$v['uid']] = $v;
                 }
                 $players = Player::model()->findAll('id in(' . implode(',', $tmp) . ')');
                 //整理player的id对应
                 $players_arr = array();
                 foreach ($players_id as $v) {
                     $players_arr[$v['uid']] = $v['t_sn'];
                 }
                 $return['players'] = array();
                 foreach ($players as $p) {
                     $return['players'][$players_arr[$p->id]] = $p;
                 }
                 ksort($return['players']);
             }
             if (in_array($tournament->status, array('playing', 'ended'))) {
                 //查询对局数据
                 $games = Games::model()->findAll('tid=' . $id);
                 //整理对阵表
                 $games_table = array();
                 foreach ($games as $g) {
                     $x = $g->black_id;
                     $y = $g->white_id;
                     //如果是单循环,只填充右上的一半对阵表
                     if ($tournament->t_kind == 'single') {
                         if ($players_arr[$x] < $players_arr[$y]) {
                             list($x, $y) = array($y, $x);
                         }
                     }
                     $games_table[$players_arr[$y]][$players_arr[$x]] = $g;
                 }
                 $return['games_table'] = $games_table;
             }
         }
         Yii::app()->cache->set(self::CACHE_PREFIX . $id, $return, 600);
     }
     return $return;
 }
Пример #4
0
 public function _userinfo()
 {
     if (!$this->userinfo) {
         if (!Yii::app()->user->isGuest) {
             $user_id = Yii::app()->user->getState('id');
             if ($user_id) {
                 $this->userinfo = Player::model()->findByPk($user_id);
             }
         }
     }
     return $this->userinfo;
 }
Пример #5
0
 public function authenticate()
 {
     $user = Player::model()->find('email=:user and password=:pass', array(':user' => $this->username, ':pass' => self::hashpwd($this->password)));
     if ($user) {
         $user->last_login_ip = MyController::getUserHostAddress();
         $user->last_login_time = date('Y-m-d H:i:s');
         $user->login_times++;
         $user->save();
         Yii::app()->user->setState('id', $user->id);
         return true;
     } else {
         return false;
     }
 }
Пример #6
0
 public function actionReg()
 {
     $email = trim(Yii::app()->request->getParam('email'));
     $nick = trim(Yii::app()->request->getParam('nickname'));
     $password = trim(Yii::app()->request->getParam('passwd'));
     $password2 = trim(Yii::app()->request->getParam('passwd2'));
     $refer = trim(Yii::app()->request->getParam('refer', '/'));
     if (!preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i', $email)) {
         $this->json_return(false, '请输入一个格式正确的Email地址');
     }
     if (!$password || $password != $password2) {
         $this->json_return(false, '2次输入的密码不一致');
     }
     if (!$nick) {
         $this->json_return(false, '请填写昵称');
     }
     if (mb_strlen($nick, 'UTF-8') > 9) {
         $this->json_return(false, '昵称长度请限制在9个字之内');
     }
     if (Player::model()->find('email=:email', array(':email' => $email))) {
         $this->json_return(false, '这个Email已经被注册了,您是否已经注册过了呢?');
     }
     if (Player::model()->find('nickname=:nick', array(':nick' => $nick))) {
         $this->json_return(false, '这个昵称已经被注册了,换一个吧');
     }
     $player = new Player();
     $player->email = $email;
     $player->nickname = $nick;
     $player->password = MyUserIdentity::hashpwd($password);
     $player->login_times = 0;
     $player->b_win = 0;
     $player->b_lose = 0;
     $player->w_win = 0;
     $player->w_lose = 0;
     $player->draw = 0;
     $player->reg_time = date('Y-m-d H:i:s');
     $player->reg_ip = MyController::getUserHostAddress();
     $player->last_login_time = date('Y-m-d H:i:s');
     $player->last_login_ip = MyController::getUserHostAddress();
     $player->score = Yii::app()->params['init_score'];
     if ($player->save()) {
         $identity = new MyUserIdentity($email, $password);
         if ($identity->authenticate()) {
             Yii::app()->user->login($identity, 3600);
             $this->json_return(true, '恭喜您注册成功!', $refer);
         }
     }
     $this->json_return(false, '注册失败啦,请与管理员联系。');
 }
Пример #7
0
 /**
  * Authenticates a user.
  * The example implementation makes sure if the username and password
  * are both 'demo'.
  * In practical applications, this should be changed to authenticate
  * against some persistent user identity storage (e.g. database).
  * @return boolean whether authentication succeeds.
  */
 public function authenticate()
 {
     $user = Player::model()->findByAttributes(array('email' => $this->username));
     if ($user === null) {
         // No user was found!
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if (md5($this->password) !== $user->password) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             // User/pass match
             $this->_id = $user->id;
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
Пример #8
0
 public function checkToChanging()
 {
     $player = Player::model()->findByAttributes(array('email' => Yii::app()->user->id));
     if ($this->validate()) {
         if ($player->getSummExit() >= $this->summ) {
             if ($player->setSummExitPlus(-$this->summ)) {
                 $player->setSummBuyPlus($this->summ * 1.1);
                 $this->redirect($this->createUrl('player/Myship'));
             } else {
                 $this->addError('summ', 'Ошибка. Обмен не произошел!');
             }
         } else {
             $this->addError('summ', 'Обмен не произошел, возможно не хватает средств.');
             return false;
         }
     } else {
         return false;
     }
 }
Пример #9
0
 /**
  * Manages Player Results
  * @param Integer $id
  * @param Integer $playerId
  */
 public function actionManageMatchGameByPlayer($id, $playerId)
 {
     $MATCH_TYPE = 2;
     $ACTIVE = 1;
     $model = $this->loadModel($id);
     $playerModel = Player::model()->findByPK($playerId);
     if ($playerModel === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     if (isset($_POST['PlayerResult'])) {
         $players = $_POST['PlayerResult'];
         foreach ($players as $playerResultPost) {
             $catResult = isset($playerResultPost['RESULT_ID']) ? $playerResultPost['RESULT_ID'] : -1;
             $matchId = isset($playerResultPost['MATCH_ID']) ? $playerResultPost['MATCH_ID'] : -1;
             $playerResult = PlayerResult::model()->findByPK(array('RESULT_ID' => $catResult, 'PLAYER_ID' => $playerId, 'MATCH_ID' => $matchId));
             if ($playerResult != null) {
                 $playerResult->attributes = $playerResultPost;
                 $playerResult->save();
             } else {
                 throw new CHttpException(404, 'The requested page does not exist.');
             }
         }
         $this->redirect(array('manage', 'id' => $matchId));
     }
     $catResult = new CatResult();
     $catResult->TYPE_RESULT = $MATCH_TYPE;
     $catResult->ACTIVE = $ACTIVE;
     $catResults = array();
     $catResults = $catResult->search()->getData();
     $playerResults = array();
     foreach ($catResults as $_catResult) {
         $playerResult = PlayerResult::model()->findByPK(array('RESULT_ID' => $_catResult->ID, 'PLAYER_ID' => $playerId, 'MATCH_ID' => $id));
         if ($playerResult === null) {
             $playerResult = new PlayerResult();
             $playerResult->MATCH_ID = $id;
             $playerResult->PLAYER_ID = $playerId;
             $playerResult->RESULT_ID = $_catResult->ID;
             $playerResult->save();
         }
         $playerResults[] = $playerResult;
     }
     $this->renderPartial('_playerResultForm', array('model' => $model, 'playerModel' => $playerModel, 'playerResults' => $playerResults));
 }
Пример #10
0
 /**
  * Displays the contact page
  */
 public function actionRun()
 {
     require __DIR__ . '/../../../vendor/autoload.php';
     $evm = new EventManager();
     $data = array();
     $collect = function ($info) use(&$data) {
         $data[] = $info;
     };
     $evm->on('game.run', $collect);
     $evm->on('game.addplayer', $collect);
     $evm->on('game.start', $collect);
     $evm->on('game.turn', $collect);
     $evm->on('game.end', $collect);
     $evm->on('player.start', $collect);
     $evm->on('player.attack', $collect);
     $evm->on('player.defense', $collect);
     $evm->on('player.damage', $collect);
     $game = new Game($evm);
     foreach (Player::model()->findAll() as $player) {
         $game->addPlayer(new EPlayer($player->name, (int) $player->life, (int) $player->strong, (int) $player->speed, new EResource($player->resource->name, (int) $player->resource->attack, (int) $player->resource->defense, new Dice((int) $player->resource->dice)), $game));
     }
     $game->run(new Dice(20));
     $this->render('run', array('data' => $data));
 }
Пример #11
0
 public function actionScorelog()
 {
     $id = intval(Yii::app()->request->getParam('id'));
     $player = Player::model()->findByPk($id);
     if (!$id || !$player) {
         throw new CHttpException(404);
     }
     $history = Score_log::model()->findAll("player_id={$id} order by id desc");
     //TODO 分页
     $this->pageTitle = '用户等级分历史记录:' . $player->nickname . '  ' . Yii::app()->params['title'];
     $this->render('scorelog', array('player' => $player, 'history' => $history));
 }
Пример #12
0
 public function getLeaderBoardFriends($user_id, $friends, $quiz)
 {
     $sql = "SELECT derived.player_id, sum(derived.best_score) AS player_points \nFROM (\n    SELECT tbl_game.quiz_id, tbl_game.player_id, max(tbl_game.player_points) AS best_score \n    FROM `tbl_game` \n    WHERE tbl_game.player_id IN {$friends} \n    AND tbl_game.quiz_id = {$quiz}\n    GROUP BY tbl_game.player_id\n) as derived \nGROUP BY derived.player_id\nORDER BY player_points DESC";
     $players = Game::model()->findAllBySql($sql);
     $arr = array();
     //        $player_id_arr = array();
     //        $player_points_arr = array();
     foreach ($players as $item) {
         $arr[$item->player_id] = $item->player_points;
         // $player_points_arr
     }
     $player_point = null;
     $position = array_search($user_id, array_keys($arr));
     if ($position === FALSE) {
         $position = null;
     }
     //echo $position; die;
     if (isset($position)) {
         $player_point = $arr[$user_id];
     }
     $returnArr = array();
     //  var_dump($player_point); die;
     foreach ($players as $player) {
         $itemArr = array();
         $itemArr['player_info'] = Player::model()->findByPk($player->player_id);
         $itemArr['player_points'] = $player->player_points;
         $returnArr[] = $itemArr;
     }
     return array('items' => $returnArr, 'current_position' => $position, 'current_points' => $player_point);
 }
 public function actionOutsHighDartModal()
 {
     if (Yii::app()->request->isPostRequest) {
         throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
     }
     $message = 'success';
     if (isset($_GET['data'])) {
         $data = $_GET['data'];
         $tournament_id = $data['tournament_id'];
         $player_id = $data['player_id'];
         $player = Player::model()->findByPk($player_id);
         $outs = $player->getOuts($tournament_id);
         $high_dart = $player->getHighDart($tournament_id);
     }
     echo CJSON::encode(array('status' => $message, 'outs' => $outs, 'high_dart' => $high_dart));
 }
Пример #14
0

<div class="view">

<?php 
//get player complement Data
$player = Player::model()->findByPk($data->PLAYER_ID);
$imgDel = CHtml::image(Yii::app()->request->baseUrl . '/images/del.png', '');
$imgEdit = CHtml::image(Yii::app()->request->baseUrl . '/images/update.png', '');
?>

<table>
<tr>
<td width="70%">
	<b><?php 
echo CHtml::encode($data->getAttributeLabel('ID'));
?>
:</b>
	<?php 
echo CHtml::link(CHtml::encode($data->PLAYER_ID), array('view', 'id' => $data->PLAYER_ID));
?>

	&nbsp;
	<b><?php 
echo CHtml::encode($player->getAttributeLabel('NAME'));
?>
:</b>
	<?php 
echo CHtml::encode($player->NAME);
?>
	<br />
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = Player::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
 public function actionEditPermissionsConfig($id)
 {
     Yii::app()->user->can($id, 'edit configs', true);
     $model = $this->loadModel($id);
     $error = '';
     $world = $model->world ? $model->world : 'world';
     if (@$_POST['save'] === 'true') {
         require_once dirname(__FILE__) . '/../extensions/spyc/spyc.php';
         $groups['groups'] = array();
         $def = User::getLevelRole($model->default_level);
         $prev = false;
         foreach (User::$roles as $role) {
             if ($role == 'none') {
                 continue;
             }
             $lbl = $role;
             //User::getRoleLabel($role);
             $groups['groups'][$lbl] = $this->getRolePerms($role, $role == $def, $_POST['prefix_' . $role], $_POST['suffix_' . $role], $_POST['build_' . $role] == 0, $_POST['perms_' . $role]);
             if ($prev) {
                 $groups['groups'][$lbl]['inheritance'] = array($prev);
             }
             $prev = $lbl;
         }
         $plrs = Player::model()->findAllByAttributes(array('server_id' => $model->id));
         $users['users'] = array();
         foreach ($plrs as $plr) {
             $users['users'][$plr->name] = array('groups' => array(User::getLevelRole($plr->level)));
         }
         $groups = Spyc::YAMLDump($groups, 4, 0);
         $users = Spyc::YAMLDump($users, 4, 0);
         $groupsData = $groups ? str_replace(array('\\', ' ;'), array('\\\\', ' \\;'), $groups) : '';
         $groupsData = preg_replace('/\\n\\r?/', ' ;', $groupsData);
         $usersData = $users ? str_replace(array('\\', ' ;'), array('\\\\', ' \\;'), $users) : '';
         $usersData = preg_replace('/\\n\\r?/', ' ;', $usersData);
         $d = null;
         if (!McBridge::get()->serverCmd($id, 'cfgfile setlist:groups.yml:plugins/Permissions/' . $world . ':' . $groupsData, $d)) {
             $error = McBridge::get()->lastError();
         } else {
             if (@$d[0]['accepted'] != 'True') {
                 $error = isset($d[0]['message']) ? $d[0]['message'] : Yii::t('mc', 'Error updating config file!');
             } else {
                 if (!McBridge::get()->serverCmd($id, 'cfgfile setlist:users.yml:plugins/Permissions/' . $world . ':' . $usersData, $d)) {
                     $error = McBridge::get()->lastError();
                 } else {
                     if (@$d[0]['accepted'] != 'True') {
                         $error = isset($d[0]['message']) ? $d[0]['message'] : Yii::t('mc', 'Error updating config file!');
                     } else {
                         Yii::app()->user->setFlash('server', Yii::t('mc', 'Config File saved.'));
                         $this->redirect(array('configs', 'id' => $id));
                     }
                 }
             }
         }
     } else {
         require_once dirname(__FILE__) . '/../extensions/spyc/spyc.php';
         $groupsData = array();
         $usersData = array();
         if (!McBridge::get()->serverCmd($id, 'cfgfile getlist:groups.yml:plugins/Permissions/' . $world . ':', $groupsData)) {
             $error = McBridge::get()->lastError();
         }
         if (!McBridge::get()->serverCmd($id, 'cfgfile getlist:users.yml:plugins/Permissions/' . $world . ':', $usersData)) {
             $error = McBridge::get()->lastError();
         }
         $users = '';
         $groups = '';
         if (count($groupsData)) {
             foreach ($groupsData as $line) {
                 if (isset($line['line'])) {
                     $groups .= $line['line'] . "\n";
                 }
             }
         }
         if (count($usersData)) {
             foreach ($usersData as $line) {
                 if (isset($line['line'])) {
                     $users .= $line['line'] . "\n";
                 }
             }
         }
         $groups = Spyc::YAMLLoadString($groups);
         foreach (User::$roles as $role) {
             if ($role == 'none') {
                 continue;
             }
             $lbl = $role;
             //User::getRoleLabel($role);
             $_POST['prefix_' . $role] = @$groups['groups'][$lbl]['info']['prefix'];
             $_POST['suffix_' . $role] = @$groups['groups'][$lbl]['info']['suffix'];
             $_POST['build_' . $role] = isset($groups['groups'][$lbl]['info']['build']) && !$groups['groups'][$lbl]['info']['build'] ? 1 : 0;
             if (isset($groups['groups'][$lbl]['permissions'][0]) && $groups['groups'][$lbl]['permissions'][0]) {
                 $_POST['perms_' . $role] = implode(', ', array_map(array($this, 'toYmlStr'), $groups['groups'][$lbl]['permissions']));
             }
         }
     }
     $this->render('editPermissionsConfig', array('model' => $model, 'error' => $error));
 }
Пример #17
0
$attribs[] = array('label' => $form->labelEx($model, 'name'), 'type' => 'raw', 'value' => $form->textField($model, 'name') . ' ' . $form->error($model, 'name'));
if (!$model->isNewRecord) {
    $attribs[] = array('label' => $form->labelEx($model, 'last_run_ts'), 'value' => ($model->last_run_ts ? @date(Yii::t('mc', 'd. M Y, H:i'), $model->last_run_ts) : Yii::t('mc', 'Never')) . $form->error($model, 'last_run_ts'));
    $attribs[] = array('label' => $form->labelEx($model, 'status'), 'value' => Schedule::getStatusValues($model->status));
}
$attribs[] = array('label' => $model->isNewRecord ? $form->labelEx($model, 'status') : Yii::t('mc', 'Change status to'), 'type' => 'raw', 'value' => $form->dropDownList($model, 'status', array(0 => Schedule::getStatusValues(0), 3 => Schedule::getStatusValues(3))) . ' ' . $form->error($model, 'status'));
$attribs[] = array('label' => $form->labelEx($model, 'scheduled_ts'), 'type' => 'raw', 'value' => $this->widget('application.extensions.timepicker.EJuiDateTimePicker', array('value' => @date(Yii::t('mc', 'd. M Y H:i'), $model->scheduled_ts ? $model->scheduled_ts : time()), 'name' => 'scheduled_ts', 'options' => array('dateFormat' => Yii::t('mc', 'dd. M yy'))), true) . ' ' . $form->error($model, 'scheduled_ts'));
$attribs[] = array('name' => 'interval', 'type' => 'raw', 'value' => CHtml::checkBox('ival_do', $model->interval > 0) . ' ' . CHtml::dropDownList('ival_nr', $ival_nr, range(1, 59)) . ' ' . CHtml::dropDownList('ival_type', $ival_type, array(Yii::t('mc', 'Minutes'), Yii::t('mc', 'Hours'), Yii::t('mc', 'Days'))));
$fnd = array('server_id' => (int) $sv);
if (Command::model()->hasAttribute('hidden') && !Yii::app()->user->isSuperuser()) {
    $fnd['hidden'] = 0;
}
$attribs[] = array('name' => $form->labelEx($model, 'command'), 'type' => 'raw', 'value' => $form->dropDownList($model, 'command', array('0' => Yii::t('mc', 'None')) + CHtml::listData(Command::model()->findAllByAttributes($fnd), 'id', 'name')) . ' ' . $form->error($model, 'command'));
$attribs[] = array('name' => $form->labelEx($model, 'args'), 'type' => 'raw', 'value' => $form->textField($model, 'args') . ' ' . $form->error($model, 'command'), 'hint' => Yii::t('mc', 'For example the text for the say command.'));
$players = array(0 => Yii::t('mc', 'Server'), -1 => Yii::t('mc', 'Everyone'));
$cmd = Player::model()->getDbConnection()->createCommand('select `id`, `name` from `player` where `server_id`=?');
$plrs = $cmd->query(array(1 => $model->server_id));
foreach ($plrs as $pl) {
    $players[$pl['id']] = $pl['name'];
}
$attribs[] = array('label' => $form->labelEx($model, 'run_for'), 'type' => 'raw', 'value' => $form->dropDownList($model, 'run_for', $players) . ' ' . $form->error($model, 'run_for'), 'hint' => Yii::t('mc', 'Runs only for players that are online, or always if "Server" is selected.'));
$attribs[] = array('label' => '', 'type' => 'raw', 'value' => CHtml::submitButton($model->isNewRecord ? Yii::t('mc', 'Create') : Yii::t('mc', 'Save')));
$this->widget('zii.widgets.CDetailView', array('data' => $model, 'attributes' => $attribs));
$this->endWidget();
echo CHtml::script('
function chIval(t)
{
    $("#ival_nr").toggle(t);
    $("#ival_type").toggle(t);
}
$("#ival_do").click(function() {
Пример #18
0
 public function actionResult()
 {
     $rc = Yii::app()->robokassa;
     // Коллбэк для события "оплата произведена"
     $rc->onSuccess = function ($event) {
         // Запишем в модель оплаты что оплата прошла
         $payForm = Yii::app()->robokassa->params['order'];
         $payForm->status = 'succes';
         $payForm->save();
         // получим пользователя из модели оплаты
         $player = Player::model()->findByPk($payForm->id_player);
         // Прибавим в статистике пользователя параметр инвестиции
         $statistic = Statistic::model()->findByAttributes(array('id_player' => $player->id));
         $statistic->invest_summ += $payForm->summ;
         $statistic->save();
         // Добавим пользователю сумму на счет оплаты !!!*1000!!!
         $player->setSummBuyPlus($payForm->summ);
         // Увеличим лемит вывода
         $current_summ_limit = $payForm->summ * 0.4;
         $player->setSummLimitPlus($current_summ_limit);
         // Получить реферала, если есть(?)
         $referal = Referals::model()->findByAttributes(array('id_referal' => $player->id));
         if ($referal != null) {
             // Получить пригласившего
             $parent_referal = Player::model()->findByAttributes(array('id' => $referal->id_player));
             // Получить статистику пригласившего и записать в базу
             $statistic_referal = Statistic::model()->findByAttributes(array('id_player' => $parent_referal->id));
             // Если еще не оплачивал, отметить что оплатил, добавить реферала в сумму рефералов прегласившего
             if ($referal->is_active == 0) {
                 $referal->is_active = 1;
                 $statistic_referal->referals += 1;
             }
             $summ_pay = $payForm->summ;
             $parent_referal->setReferalBonuses($summ_pay, $statistic_referal);
         }
     };
     // Коллбэк для события "отказ от оплаты"
     $rc->onFail = function ($event) {
         $InvId = Yii::app()->request->getParam('InvId');
         $payForm = Pays::model()->findByAttributes(array('id' => $InvId));
         if ($payForm != null) {
             $payForm->status = 'fail';
             $payForm->save();
         }
     };
     // Обработка ответа робокассы
     $rc->result();
 }
Пример #19
0
 /**
  * 
  * 邀请其他用户对局的页面。
  * 接受get参数 id 邀请记录,只有双方可访问
  * 接受user_id参数,被邀请人的id,不可以是自己。
  * 
  * 处理的post参数:
  * action 可能是cancel、reject、create、edit、accept
  * cancel时必须操作者是from
  * reject、edit、accept必须是to
  * 除了create其他都要id
  */
 public function actionInvite()
 {
     $this->needlogin();
     $id = intval(Yii::app()->request->getParam('id'));
     $invite = '';
     if ($id) {
         $invite = Game_invite::model()->findByPk($id);
     }
     $user_id = intval(Yii::app()->request->getParam('user_id'));
     $user = '';
     if ($user_id) {
         $user = Player::model()->findByPk($user_id);
     }
     $useblack = intval(Yii::app()->request->getParam('useblack'));
     $days = intval(Yii::app()->request->getParam('days'));
     $hours = intval(Yii::app()->request->getParam('hours'));
     $rule = Yii::app()->request->getParam('rule');
     $free_opening = intval(Yii::app()->request->getParam('free_open'));
     $free_opening = $free_opening ? 1 : 0;
     if (!in_array($rule, Yii::app()->params['rules'])) {
         $rule = Yii::app()->params['rules'][0];
     }
     $comment = trim(Yii::app()->request->getParam('comment'));
     $game_time = $days * 24 + $hours;
     if ($game_time < 1) {
         $game_time = 1;
     }
     if ($game_time > Yii::app()->params['max_hours']) {
         //如果设置了大于30天的时间,那么就直接设置为30天。
         $game_time = Yii::app()->params['max_hours'];
     }
     $action = trim(Yii::app()->request->getParam('action'));
     if ($action) {
         switch ($action) {
             case 'cancel':
                 //取消
                 if (!$invite || $invite->status != '等待回应') {
                     $this->json_return(false, '此邀请不存在或者已经失效了。', '/my_invites.html');
                 }
                 if ($this->_userinfo()->id != $invite->from) {
                     $this->json_return(false, '您不是此邀请的发起人,您不能取消这个邀请。', '/my_invites.html');
                 }
                 $invite->status = '已取消';
                 $invite->save();
                 $this->json_return(true, '', '/my_invites.html');
                 break;
             case 'reject':
                 //拒绝
                 if (!$invite || $invite->status != '等待回应') {
                     $this->json_return(false, '此邀请不存在或者已经失效了。', '/invite_me.html');
                 }
                 if ($this->_userinfo()->id != $invite->to) {
                     $this->json_return(false, '这个邀请不是发给您的,您不能操作这个邀请。', '/invite_me.html');
                 }
                 $invite->status = '已拒绝';
                 $invite->save();
                 $this->json_return(true, '', '/invite_me.html');
                 break;
             case 'create':
                 //创建
                 $to_id = intval(Yii::app()->request->getParam('to_user'));
                 $to_user = Player::model()->findByPk($to_id);
                 if ($to_id == $this->_userinfo()->id) {
                     $this->json_return(false, '您不能邀请自己对局。');
                 }
                 if (!$to_id || !$to_user) {
                     $this->json_return(false, '您邀请的玩家不存在。', '/home.html');
                 }
                 $invite = new Game_invite();
                 $invite->from = $this->_userinfo()->id;
                 $invite->to = $to_id;
                 $invite->black_id = $useblack ? $this->_userinfo()->id : $to_id;
                 $invite->message = $comment;
                 $invite->totaltime = $game_time;
                 $invite->rule = $rule;
                 $invite->free_opening = $free_opening;
                 $invite->status = '等待回应';
                 $invite->game_id = 0;
                 $invite->updtime = date('Y-m-d H:i:s');
                 $invite->save();
                 $this->json_return(true, '您的邀请已经发送给对方,请等待回应。', '/my_invites.html');
                 break;
             case 'accept':
                 //接受。分为2种状态,如果提交数据与原数据一致,则直接接受,创建新局,如果不同,则edit
                 if (!$invite || $invite->status != '等待回应') {
                     $this->json_return(false, '此邀请不存在或者已经失效了。', '/invite_me.html');
                 }
                 if ($this->_userinfo()->id != $invite->to) {
                     $this->json_return(false, '这个邀请不是发给您的,您不能操作这个邀请。', '/invite_me.html');
                 }
                 $black_id = $useblack ? $this->_userinfo()->id : $invite->from;
                 if ($invite->totaltime == $game_time && $invite->black_id == $black_id && $invite->free_opening == $free_opening && $invite->rule == $rule) {
                     $game_id = $this->create_game($invite);
                     $invite->status = '已接受';
                     $invite->message = $comment;
                     $invite->game_id = $game_id;
                     $invite->save();
                     $this->json_return(true, '您已经接受了对方的邀请,棋局开始。', "/game_{$game_id}.html");
                 } else {
                     $invite->to = $invite->from;
                     $invite->from = $this->_userinfo()->id;
                     $invite->black_id = $black_id;
                     $invite->message = $comment;
                     $invite->totaltime = $game_time;
                     $invite->rule = $rule;
                     $invite->free_opening = $free_opening;
                     $invite->status = '等待回应';
                     $invite->game_id = 0;
                     $invite->updtime = date('Y-m-d H:i:s');
                     $invite->save();
                     $this->json_return(true, '您的邀请已经发送给对方,请到等待回应。', '/my_invites.html');
                 }
                 break;
             default:
                 break;
         }
     }
     //如果当前用户是此invite 的任何一方,或者invite不存在,则显示。
     if ($user || $invite && ($invite->from == $this->_userinfo()->id || $invite->to == $this->_userinfo()->id)) {
         $this->pageTitle = '邀请对局-' . Yii::app()->params['title'];
         $this->js = array('invite');
         $this->render('invite', array('invite' => $invite, 'user' => $user));
     } else {
         $this->redirect('/invite_me.html');
     }
 }
Пример #20
0
 /**
  * Add Player to The team
  * @param unknown $idTeam
  * @param unknown $idPlayer
  */
 public function actionAddPlayerTeam($idTeam, $idPlayer)
 {
     $player = Player::model()->findByPk($idPlayer);
     $playerTeam = PlayerTeam::model()->findByAttributes(array('PLAYER_ID' => $idPlayer, 'TEAM_ID' => $idTeam));
     if ($playerTeam === null) {
         $playerTeam = new PlayerTeam();
     }
     if ($player === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     $team = $this->loadModel($idTeam);
     if (isset($_POST['PlayerTeam'])) {
         $playerTeam->attributes = $_POST['PlayerTeam'];
         //$playerPost =$_POST['Player'];
         //$teamPost =$_POST['team'];
         $playerTeam->TEAM_ID = $idTeam;
         $playerTeam->PLAYER_ID = $idPlayer;
         if ($playerTeam->save()) {
             $this->redirect(array('manageTeamPlayer', 'id' => $idTeam));
         }
     }
     $this->render('addPlayerTeam', array('model' => $player, 'team' => $team, 'playerTeam' => $playerTeam));
 }
Пример #21
0
 /**
  * Если пользователь зарегистрировался и сохранился то возвращаем //тру
  *
  * @return boolean
  */
 public function checkAndLoginNewplayer()
 {
     if ($this->validate()) {
         // Если пароли не совпадают выдадим ошибку
         if ($this->password != $this->password_repeat) {
             $this->addError('password', 'Вы указали разные значения в поле пароль');
             return false;
         } else {
             $this->password = md5($this->password);
             $this->date_regist = time();
             if ($this->save()) {
                 // Отправить письмо с подтверждением email
                 $this->sendAndCheckEmail();
                 // Проверка и создание реферала
                 $session = new CHttpSession();
                 $session->open();
                 if (isset($session['ref_id'])) {
                     $player = Player::model()->findByAttributes(array('id' => (int) $session['ref_id']));
                     if ($player != null) {
                         $referal = new Referals();
                         $referal->id_player = $player->id;
                         $referal->id_referal = $this->id;
                         $referal->is_active = Referals::$NOT_ACTIVE;
                         $referal->save();
                     }
                 }
                 $statistic = new Statistic();
                 $statistic->id_player = $this->id;
                 $statistic->invest_summ = 0;
                 $statistic->out_sum = 0;
                 $statistic->questions_summ_complette = 0;
                 $statistic->referals = 0;
                 $statistic->save();
                 $identity = new UserIdentity($this->email, $this->password);
                 $identity->authenticate();
                 Yii::app()->user->login($identity, 0);
                 return true;
             } else {
                 return false;
             }
         }
     } else {
         return false;
     }
 }
Пример #22
0
 /**
  ** Player Functions
  **/
 public function actionListPlayers($server_id)
 {
     $this->check($server_id);
     $plrs = Player::model()->findAllByAttributes(array('server_id' => (int) $server_id));
     $this->ls('Player', $plrs);
 }
Пример #23
0
 public function actionMyFightsComplete()
 {
     $player = Player::model()->findByAttributes(array('email' => Yii::app()->user->id));
     $ship = Ship::model()->findByAttributes(array('id' => $player->id));
     $criteria = new CDbCriteria();
     $criteria->condition = 'id_player = :id_player AND ( status = :die OR status = :win OR status = :nothing )';
     $criteria->params = array(':id_player' => $player->id, ':die' => ArenaJoiners::$STATUS_LOOSE, ':win' => ArenaJoiners::$STATUS_WIN, ':nothing' => ArenaJoiners::$STATUS_NOTHING);
     $joins = ArenaJoiners::model()->findAll($criteria);
     $pks = [];
     foreach ($joins as $join) {
         array_push($pks, $join->id_room);
     }
     $rooms = ArenaRoom::model()->findAllByPk($pks);
     if ($rooms != null) {
         foreach ($rooms as $key => $game) {
             $winner_ship = null;
             if ($game->winner_id != 0) {
                 $winner_ship = Ship::model()->findByAttributes(array('id' => $game->winner_id));
             }
             ////////////////////////////////////////////////////////////////////
             // Если игрок продал корабль или НИЧЬЯ
             ////////////////////////////////////////////////////////////////////
             $game->winner_ship = $winner_ship;
         }
     }
     $this->render('show_my_fights', array('player' => $player, 'ship' => $ship, 'joins' => $joins, 'rooms' => $rooms));
 }
Пример #24
0
 public function afterDelete()
 {
     ServerConfig::model()->deleteByPk($this->id);
     UserServer::model()->deleteAllByAttributes(array('server_id' => $this->id));
     FtpUserServer::model()->deleteAllByAttributes(array('server_id' => $this->id));
     Command::model()->deleteAllByAttributes(array('server_id' => $this->id));
     Schedule::model()->deleteAllByAttributes(array('server_id' => $this->id));
     $plrs = Player::model()->findAllByAttributes(array('server_id' => $this->id));
     foreach ($plrs as $plr) {
         $plr->delete();
     }
     return parent::afterDelete();
 }
Пример #25
0
 public function actionAddship()
 {
     $player = Player::model()->findByAttributes(array('email' => Yii::app()->user->id));
     if (isset($_POST['Ship'])) {
         $ship = new Ship();
         $ship->attributes = $_POST['Ship'];
         if ($ship->addship($player)) {
             $this->redirect($this->createUrl('player/myship'));
         } else {
             $this->render('shipBuy', array('model' => $ship, 'player' => $player));
         }
     }
     $ship = Ship::model()->findByAttributes(array('id' => $player->id));
     if ($ship != null) {
         $this->render('needSellship');
         return;
     }
     $ship = new Ship();
     $this->render('shipBuy', array('model' => $ship, 'player' => $player));
 }
Пример #26
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = Player::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'El enlace o direccion solicitado no existe');
     }
     return $model;
 }