Esempio n. 1
0
 /**
  * Creates a new Vote model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Vote();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
Esempio n. 2
0
 public function actionSubmit()
 {
     $token = Yii::$app->request->get('token');
     // Better way to get this?
     $code = Code::findCodeByToken($token);
     if (!$code || !$code->isValid()) {
         throw new UserException(Yii::t('app', 'Invalid voting code'));
     } elseif ($code->isUsed()) {
         throw new UserException(Yii::t('app', 'This voting code has already been used'));
     }
     $poll = $code->getPoll()->with('options')->one();
     $data = Yii::$app->request->getBodyParams();
     $optionIDs = $data['options'];
     if ($optionIDs === null || !is_array($optionIDs)) {
         throw new UserException(Yii::t('app', 'Bad Request'));
     }
     if (count($optionIDs) < $poll->select_min) {
         throw new UserException(Yii::t('app', 'Too few options selected'));
     }
     if (count($optionIDs) > $poll->select_max) {
         throw new UserException(Yii::t('app', 'Too many options selected'));
     }
     $transaction = Yii::$app->db->beginTransaction();
     $vote = new Vote();
     $vote->code_id = $code->id;
     if (!$vote->save()) {
         throw new UserException(Yii::t('app', 'Something went wrong'));
     }
     foreach ($optionIDs as $optionId) {
         $option = $poll->getOptions()->where(['id' => $optionId])->one();
         if (!$option) {
             $transaction->rollBack();
             throw new UserException(Yii::t('app', 'Invalid option'));
         }
         try {
             $vote->link('options', $option);
         } catch (Exception $e) {
             $transaction->rollBack();
             throw new UserException(Yii::t('app', 'Something went wrong'));
         }
     }
     $code->code_status = Code::CODE_STATUS_USED;
     if (!$code->save()) {
         $transaction->rollBack();
         throw new UserException(Yii::t('app', 'Something went wrong'));
     }
     $transaction->commit();
     // Log the vote in the vote log file.
     $arrayString = implode(", ", $optionIDs);
     $arrayString = "[{$arrayString}]";
     Yii::info("{$code->token} {$arrayString}", 'vote');
     return $data;
 }
 public function postVoteDream(Request $req)
 {
     $dream = $req->input('dream');
     if (Vote::where('id_dream', $dream)->where('cookie', $this->userService->cookie())->count() > 0) {
         return response()->json(['status' => 'ERROR', 'data' => '', 'messages' => 'Ati votat deja.']);
     }
     $vote = new Vote();
     $vote->id_dream = $dream;
     $vote->cookie = $this->userService->cookie();
     $vote->save();
     $dream = Dream::find($dream);
     $dream->votes += 1;
     $dream->save();
     return response()->json(['status' => 'OK', 'data' => $dream->votes, 'messages' => 'Proiect votat.']);
 }
Esempio n. 4
0
 public static function processVote()
 {
     if (!\Yii::$app->session->get('question_id')) {
         return false;
     }
     $user = User::findOne(['social_id' => Yii::$app->user->identity->social_id]);
     $vote = new Vote();
     $vote->user_id = $user->id;
     $vote->questions_id = Yii::$app->session->get('question_id');
     $vote->vote = 1;
     if (\Yii::$app->session->get('answer') and (1000001 == Yii::$app->session->get('question_id') or 1000002 == Yii::$app->session->get('question_id'))) {
         $vote->custom_answer = \Yii::$app->session->get('answer');
     }
     $vote->save();
     return true;
 }
Esempio n. 5
0
 /**
  * Tests whether the data can be retrieved from the database
  */
 public function testExtract()
 {
     // create users
     $user1 = factory(App\Models\User::class)->create();
     $user2 = factory(App\Models\User::class)->create();
     $user3 = factory(App\Models\User::class)->create();
     // create battle
     $battle = new Battle();
     $battle->rapper1_id = $user1->id;
     $battle->rapper2_id = $user2->id;
     $battle->save();
     // create some votes
     $vote1 = new Vote();
     $vote1->user_id = $user1->id;
     $vote1->battle_id = $battle->id;
     $vote1->rapper_number = 1;
     $vote1->save();
     $vote2 = new Vote();
     $vote2->user_id = $user2->id;
     $vote2->battle_id = $battle->id;
     $vote2->rapper_number = 0;
     $vote2->save();
     $vote3 = new Vote();
     $vote3->user_id = $user3->id;
     $vote3->battle_id = $battle->id;
     $vote3->rapper_number = 0;
     $vote3->save();
     // can user be retrieved?
     $this->assertEquals($user3->id, $vote3->user->id);
     // can battle be retrieved?
     $this->assertEquals($battle->id, $vote3->battle->id);
     // can a battle get it's votes?
     $battlevotecnt = $battle->votes()->count();
     $this->assertEquals(3, $battlevotecnt);
     $battlevotes = $battle->votes()->get()->values()->keyBy('user_id');
     $this->assertNotNull($battlevotes->get($user1->id));
     $this->assertNotNull($battlevotes->get($user2->id));
     $this->assertNotNull($battlevotes->get($user3->id));
     // can a user get their votes?
     $vote1id = $user1->votes()->get()->values()->keyBy('user_id')->get($user1->id)->id;
     $this->assertEquals($vote1->id, $vote1id);
 }
Esempio n. 6
0
 public function actionVote()
 {
     if (Yii::$app->request->isAjax) {
         Yii::$app->response->format = Response::FORMAT_JSON;
     }
     $id = Yii::$app->request->getQueryParam('id');
     $vote = Yii::$app->request->getQueryParam('vote');
     switch ($vote) {
         case 'up':
             $v = 1;
             break;
         case 'down':
             $v = -1;
             break;
         default:
             throw new InvalidParamException('Vote must be up or down!');
     }
     $vote = new Vote(['vote' => $v, 'ip' => ip2long(Yii::$app->request->userIP), 'fingerprint' => md5(Yii::$app->request->userAgent), 'snippet_id' => $id]);
     if ($vote->validate()) {
         $vote->save();
         $paste = Code::findOne($vote->snippet_id);
         $message = Yii::t('happycode', 'Voted!');
         if (Yii::$app->request->isAjax) {
             return ['id' => $id, 'message' => $message, 'score' => $paste->score];
         } else {
             AlertHelper::appendAlert('success', $message);
             return $this->goBack();
         }
     } else {
         Yii::$app->response->statusCode = 403;
         $message = Yii::t('happycode', 'Already voted on this paste.');
         if (Yii::$app->request->isAjax) {
             return ['id' => $id, 'message' => $message];
         } else {
             AlertHelper::appendAlert('warning', $message);
             return $this->goBack();
         }
     }
 }
 public function votePhoto()
 {
     $input = \Request::all();
     $vote_registered = 'false';
     $photo = $input['photo'];
     if (User::canVote($input['photo']['id'])) {
         $vote = new Vote();
         $vote->photo_id = $input['photo']['id'];
         $vote->user_id = Auth::user()->id;
         $vote->ip = $_SERVER['REMOTE_ADDR'];
         $vote->save();
         $vote_registered = 'true';
         $photo = UserPhoto::with(['user' => function ($query) {
             $query->select(['id', 'name', 'avatar']);
         }])->with('votesCount')->where('status', 1)->select('id', 'user_id', 'filename')->find($input['photo']['id']);
     }
     return ["photo" => $photo, "vote_registered" => $vote_registered];
 }
Esempio n. 8
0
 /**
  * Главная страница с записями
  * @param null $query - строка поиска
  * @param bool|false $random - случайные записи
  * @return string
  */
 public function actionIndex($query = null, $random = false)
 {
     $this->query = $query;
     $queryText = "";
     if (preg_match('/^#([\\S]+)/i', $this->query, $queryTag)) {
         $postIds = (new Query())->distinct()->select('tag4post.post_id')->from('tag4post')->innerJoin('tag', 'tag.id=tag4post.tag_id')->andFilterWhere(['like', 'tag.name', $queryTag[1]])->all();
         $queryPostsByTag = [];
         if (!empty($postIds)) {
             foreach ($postIds as $postId) {
                 $queryPostsByTag[] = $postId['post_id'];
             }
         }
     } else {
         $queryText = $this->query;
         $queryPostsByTag = [];
     }
     $post_id = (int) Yii::$app->request->get('post_id', 0);
     if ($post_id != 0) {
         try {
             $vote = new Vote();
             $vote->post_id = abs($post_id);
             $vote->rating = $post_id > 0 ? 1 : -1;
             $vote->ip = Yii::$app->request->getUserIP();
             $vote->user_agent = Yii::$app->request->getUserAgent();
             $vote->created = date("Y-m-d H:i:s");
             $vote->save();
         } catch (Exception $e) {
         }
     }
     $posts = new ActiveDataProvider(['query' => Post::find()->with(['tags', 'votes'])->where('visible = 1')->andFilterWhere(['in', 'post.id', $queryPostsByTag])->andFilterWhere(['like', 'post.text', $queryText])->orderBy($random ? new Expression('rand()') : ['created' => SORT_DESC]), 'pagination' => ['pageSize' => self::PAGE_SIZE]]);
     $aKeywords = [];
     $aDescriptions = [];
     foreach ($posts->getModels() as $pagePost) {
         if (!empty($pagePost->tags)) {
             foreach ($pagePost->tags as $tag) {
                 $aKeywords[] = ArrayHelper::getValue($tag, 'name');
             }
         }
         if (!json_decode($pagePost->text)) {
             $aDescriptions[] = Html::encode($pagePost->text);
             // plain text, not json
         }
     }
     $keywords = implode(', ', array_unique($aKeywords));
     $description = implode("\r\n\r\n\r\n", $aDescriptions);
     $title = Yii::$app->params['name'] . ' - развлекательный сайт для всех!';
     return $this->render('index', ['posts' => $posts, 'title' => $title, 'keywords' => $keywords, 'description' => $description]);
 }
Esempio n. 9
0
 public function actionVoting()
 {
     $token = Yii::$app->session->get('token', null);
     if (!$token) {
         return $this->redirect(['index']);
     } else {
         // display the form from the poll options
         // get code through the token
         $code = Code::findCodeByToken($token);
         // check again if its not used etc.
         if ($code->checkCode()) {
             // display the form when code is not used and valid
             $model = new VotingForm($code);
             $success = false;
             if (Yii::$app->request->post($model->formName())) {
                 $model->load(Yii::$app->request->post());
                 if ($model->validate()) {
                     // save the vote and selected options
                     $transaction = \Yii::$app->db->beginTransaction();
                     try {
                         $vote = new Vote();
                         $vote->code_id = $code->id;
                         if ($vote->save()) {
                             // save selected options if there are any submitted, votes without options selected could also be done.
                             if (is_array($model->options)) {
                                 foreach ($model->options as $optionId) {
                                     $option = $model->getOptionById($optionId);
                                     $vote->link('options', $option);
                                     /*if (!$vote->link('options', $option)) {
                                           throw new \Exception("Option couldn't be linked to vote", 1);
                                       }*/
                                 }
                             }
                             $code->code_status = Code::CODE_STATUS_USED;
                             if (!$code->save()) {
                                 if ($code->getErrors()) {
                                     Yii::$app->getSession()->addFlash('error', Html::errorSummary($code, $options = ['header' => Yii::t('app/error', 'Failed to save due to error:')]));
                                 }
                                 throw new \Exception(Yii::t('app/error', "Code Couldn't be saved "), 1);
                             }
                         } else {
                             if ($vote->getErrors()) {
                                 Yii::$app->getSession()->addFlash('error', Html::errorSummary($vote, $options = ['header' => Yii::t('app/error', 'Failed to save due to error:')]));
                             }
                             throw new \Exception(Yii::t('app/error', "Vote Couldn't be saved "), 1);
                         }
                         $transaction->commit();
                         $success = true;
                     } catch (\Exception $e) {
                         $transaction->rollBack();
                         Yii::warning('There was an error on saving a vote: ' . $e->getMessage());
                         if (!Yii::$app->getSession()->hasFlash('error')) {
                             Yii::$app->getSession()->addFlash('error', $e->getMessage());
                         }
                         //throw new HttpException(400, 'There was an error on saving a vote: '.$e->getMessage());
                     }
                 }
             }
             if ($success) {
                 // remove the token
                 Yii::$app->session->remove('token');
                 return $this->render('voting_success');
             } else {
                 return $this->render('voting', ['show_form' => true, 'model' => $model]);
             }
         } else {
             Yii::$app->session->remove('token');
             Yii::$app->getSession()->setFlash('token-error', $code->getErrors('token')[0]);
         }
     }
     return $this->render('voting', ['show_form' => false, 'model' => null]);
 }
Esempio n. 10
0
 public function postVote(Request $request, $battle_id)
 {
     $this->validate($request, ['rapper_number' => 'required|integer']);
     $user = Auth::user();
     $battle = Battle::find($battle_id);
     if (is_null($user)) {
         return response('', 403);
     }
     // forbidden
     if (is_null($battle)) {
         return response('', 404);
     }
     // Not found
     // check if battle is votable
     if (!$battle->isOpenVoting()) {
         return response('', 405);
     }
     // Method not allowed
     // don't let the user change a vote
     if ($user->votes()->where('battle_id', $battle->id)->get()->first() == null) {
         // build new vote
         $vote = new Vote();
         $vote->user_id = $user->id;
         $vote->battle_id = $battle->id;
         $vote->rapper_number = $request->input('rapper_number');
         // update vote counter
         if ($vote->rapper_number == 0) {
             $battle->votes_rapper1++;
         } else {
             if ($vote->rapper_number == 1) {
                 $battle->votes_rapper2++;
             } else {
                 return response('', 422);
             }
         }
         // Unprocessable Entity
         // save vote count in battle
         $vote->save();
         $battle->save();
     } else {
         return response('', 405);
         // Method not allowed
     }
 }
Esempio n. 11
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Model::unguard();
     // config
     $usercnt = 20;
     $userRappercnt = 20;
     $battlecnt = 20;
     $battleRequestcnt = rand($userRappercnt / 4, $userRappercnt / 2);
     // max $userRappercnt / 2
     $openBattlecnt = rand($userRappercnt / 4, $userRappercnt / 2);
     // max $userRappercnt / 2
     // create users
     $users = factory(App\Models\User::class, $usercnt)->create();
     // rapper and non-rapper
     $usersRapper = factory(App\Models\User::class, 'rapper', $userRappercnt)->create();
     // rapper only
     //----------------------------------------------
     // create battles
     for ($i = 0; $i < $battlecnt; $i++) {
         $battle = new Battle();
         // get first rapper
         $battle->rapper1_id = $usersRapper->random()->id;
         // get second rapper != first rapper
         do {
             $battle->rapper2_id = $usersRapper->random()->id;
         } while ($battle->rapper1_id == $battle->rapper2_id);
         $battle->save();
         //-----------------------------------------
         // create votes
         // create list of all created users
         $usersAll = $users->keyBy('id')->merge($usersRapper->keyBy('id'));
         $usersAll->shuffle();
         $userVotescnt = rand(0, $usersAll->count());
         for ($j = 0; $j < $userVotescnt; $j++) {
             $vote = new Vote();
             $vote->user_id = $usersAll->get($j)->id;
             $vote->battle_id = $battle->id;
             $vote->rapper_number = rand(0, 1);
             $vote->save();
             // update vote counter
             if ($vote->rapper_number == 0) {
                 $battle->votes_rapper1++;
             } else {
                 $battle->votes_rapper2++;
             }
         }
         // save vote count in battle
         $battle->save();
         $battle->rapper1->updateRating();
         $battle->rapper2->updateRating();
     }
     //----------------------------------------------
     // create battle_requests
     for ($i = 0; $i < $battleRequestcnt * 2; $i += 2) {
         $battleRequest = new BattleRequest();
         $battleRequest->challenger_id = $usersRapper->get($i)->id;
         $battleRequest->challenged_id = $usersRapper->get($i + 1)->id;
         $battleRequest->save();
     }
     //----------------------------------------------
     // create open battles
     $usersRapper->shuffle();
     for ($i = 0; $i < $openBattlecnt * 2; $i += 2) {
         $openBattle = new OpenBattle();
         $openBattle->rapper1_id = $usersRapper->get($i)->id;
         $openBattle->rapper2_id = $usersRapper->get($i + 1)->id;
         $openBattle->phase = rand(1, 2);
         // TODO: how many phases?
         $openBattle->beat1_id = rand(0, 2);
         $openBattle->beat2_id = rand(0, 2);
         $openBattle->save();
     }
     Model::reguard();
 }