Ejemplo n.º 1
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.']);
 }
Ejemplo n.º 3
0
 public function getTodayVotessCountAttribute()
 {
     $order = Order::today();
     if ($order == null) {
         return '0';
     }
     return Vote::where('order_id', '=', $order->id)->where('place_id', '=', $this->id)->count();
 }
Ejemplo n.º 4
0
 public static function canVote($photo_id)
 {
     $canVote = true;
     $oneHourAgo = date('Y-m-d H:i:s', time() - 60 * 60);
     $votes = Vote::where('user_id', \Auth::user()->id)->where('photo_id', $photo_id)->where('created_at', '>', $oneHourAgo)->get();
     if ($votes->count() > 0) {
         $canVote = false;
     }
     return $canVote;
 }
Ejemplo 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);
 }
Ejemplo n.º 6
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Vote::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'user_id' => $this->user_id, 'questions_id' => $this->questions_id, 'vote' => $this->vote]);
     return $dataProvider;
 }
Ejemplo n.º 7
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();
         }
     }
 }
Ejemplo n.º 8
0
 public static function cheLikeUser($id, $nomination)
 {
     if (isset(Yii::$app->user->identity->id)) {
         if (!isset($id) && $id == null) {
             return false;
         }
         $vote = Vote::find()->where(['user_id' => Yii::$app->user->identity->id, 'story_id' => $id])->one();
         if (!empty($vote) && $vote != null) {
             $story_nomination = Story::find()->where(['id' => $vote->story_id])->one();
             if ($story_nomination->nomination === $nomination) {
                 return true;
             } else {
                 return false;
             }
         } else {
             $vote = Vote::find()->where(['user_id' => Yii::$app->user->identity->id])->all();
             $arr = [];
             foreach ($vote as $k => $v) {
                 $story_nomination = Story::find()->where(['id' => $v->story_id])->one();
                 if ($story_nomination->nomination === $nomination) {
                     $arr[$story_nomination->nomination] = $story_nomination->nomination;
                 }
             }
             if (empty($arr)) {
                 return false;
             } else {
                 return true;
             }
         }
     } else {
         return false;
     }
 }
Ejemplo n.º 9
0
 public function actionTestVote()
 {
     Vote::processVote();
     /*$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;
             $vote->save();
     
             echo '<pre>';
             print_r($vote);
             print_r( $vote->getErrors());*/
 }
Ejemplo n.º 10
0
 private static function _loadVoted()
 {
     self::$_voted = array_map(function ($a) {
         return $a['snippet_id'];
     }, Vote::find()->select('snippet_id')->where(['ip' => ip2long(Yii::$app->request->userIP), 'fingerprint' => md5(Yii::$app->request->userAgent)])->asArray()->all());
 }
 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];
 }
Ejemplo n.º 12
0
 public function getCountVotesAttribute()
 {
     return Vote::where('order_id', '=', $this->id)->get();
 }
Ejemplo n.º 13
0
 public function actionResult()
 {
     if (!Yii::$app->user->identity) {
         return $this->goHome();
     }
     \Yii::$app->view->registerMetaTag(['name' => 'description', 'content' => '']);
     $this->getMetaTagsDefault();
     $questionsYes = Questions::find()->andWhere(['yes' => 1])->all();
     $questionsNo = Questions::find()->andWhere(['no' => 1])->all();
     $customYes = new Questions();
     $customYes->id = 1000001;
     $customYes->questions = 'Iншi';
     $customYes->yes = 1;
     $questionsYes[] = $customYes;
     $customNo = new Questions();
     $customNo->id = 1000002;
     $customNo->questions = 'Iншi';
     $customNo->no = 1;
     $questionsNo[] = $customNo;
     $result = Vote::getResult();
     return $this->render('result', ['questionsYes' => $questionsYes, 'questionsNo' => $questionsNo, 'result' => $result]);
 }
Ejemplo n.º 14
0
 public function count()
 {
     return Vote::where('order_id', '=', $this->order_id)->count();
 }
Ejemplo n.º 15
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getVote()
 {
     //return $this->hasMany(Vote::className(), ['code_id' => 'id']);
     return $this->hasOne(Vote::className(), ['code_id' => 'id']);
 }
Ejemplo n.º 16
0
 public function getChiTiet($id)
 {
     $brands = $this->brands;
     $socho = $this->sochoxe;
     $tintucs = $this->tintucs;
     $binhluans = Comment::where('xe_id', $id)->orderBy('id', 'desc')->paginate(3);
     foreach ($binhluans as $key => $value) {
         if ($value->nguoidung_id != NULL) {
             $user = User::where('nguoidung_id', $value->nguoidung_id)->get()->first();
             $value->nguoidung_id = $user->tendaydu;
         }
     }
     //dd($binhluans);
     // xe hiện tại
     $xe = Cars::where('xe_id', $id)->get()->first();
     // tên lái xe theo xe
     $tenlaixe = TaiXe::where('taixe_id', $xe->tai_xe_id)->get()->first();
     $xekhac = Cars::whereNotIn('xe_id', [$id])->where(function ($query) use($xe) {
         $query->where('socho_xe', $xe->socho_xe)->orWhere('hang_id', $xe->hang_id);
     })->get();
     //dd($xekhac);
     //dd($xe); die();
     $vote_id = Vote::where('cars_id', $id)->get()->first();
     if ($vote_id->sovotes != 0) {
         $roundVote = round($vote_id->tongdiem / $vote_id->sovotes, 1);
     } else {
         $roundVote = 0;
     }
     //dd($vote_id);
     return view('frontend.pages.chitiet', compact('vote_id', 'binhluans', 'xe', 'socho', 'brands', 'tintucs', 'tenlaixe', 'xekhac', 'roundVote'));
 }
Ejemplo n.º 17
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getVotes()
 {
     return $this->hasMany(Vote::className(), ['created_by' => 'id']);
 }
Ejemplo n.º 18
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getVote()
 {
     return $this->hasOne(Vote::className(), ['id' => 'vote_id']);
 }
Ejemplo n.º 19
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
     }
 }
Ejemplo n.º 20
0
 public static function getResult()
 {
     $result = [];
     //get from db
     $votes = self::find()->all();
     $questions = Questions::find()->all();
     //add custom questions
     $customYes = new Questions();
     $customYes->id = 1000001;
     $customYes->questions = 'Iншi';
     $customYes->yes = 1;
     $customYes->no = 0;
     $questions[] = $customYes;
     $customNo = new Questions();
     $customNo->id = 1000002;
     $customNo->questions = 'Iншi';
     $customNo->no = 1;
     $customNo->yes = 0;
     $questions[] = $customNo;
     //total
     $result['yes']['count'] = Vote::find()->yesOnly()->count();
     $result['no']['count'] = Vote::find()->noOnly()->count();
     $result['yes']['count'] += Vote::find()->where(['questions_id' => 1000001])->count();
     $result['no']['count'] += Vote::find()->where(['questions_id' => 1000002])->count();
     // echo '<pre>';
     // var_dump($result);
     // echo '</pre>';
     // echo '<pre>';
     // var_dump($customYes);
     // echo '</pre>';
     //get total count
     foreach ($questions as $key => $value) {
         if (!empty($value->yes)) {
             $result['yes']['count'] += $value->vote;
         }
         if (!empty($value->no)) {
             $result['no']['count'] += $value->vote;
         }
     }
     //set total values
     $totalCount = $result['yes']['count'] + $result['no']['count'];
     $result['yes']['percent'] = round($result['yes']['count'] / $totalCount * 100);
     $result['no']['percent'] = round($result['no']['count'] / $totalCount * 100);
     //set percent
     //   \yii\helpers\VarDumper::dump($questions, 11, 1);
     foreach ($questions as $key => $value) {
         $result['questions'][$value->id] = ['count' => $value->vote, 'vote' => $value->vote];
         if (!empty($value->yes)) {
             // \yii\helpers\VarDumper::dump($result['questions'], 11, 1);
             $result['questions'][$value->id]['group'] = 'yes';
             $result['questions'][$value->id]['percent'] = round($result['questions'][$value->id]['count'] / $result['yes']['count'] * 100);
         }
         if (!empty($value->no)) {
             $result['questions'][$value->id]['group'] = 'no';
             $result['questions'][$value->id]['percent'] = round($result['questions'][$value->id]['count'] / $result['no']['count'] * 100);
         }
     }
     //         \yii\helpers\VarDumper::dump($result, 11, 1);
     // die();
     //add each vote to array
     foreach ($votes as $key => $vote) {
         if ('yes' == $result['questions'][$vote->questions_id]['group']) {
             $result['questions'][$vote->questions_id]['count'] = $result['questions'][$vote->questions_id]['count'] + 1;
             $result['questions'][$vote->questions_id]['percent'] = round($result['questions'][$vote->questions_id]['count'] / $result['yes']['count'] * 100);
         }
         if ('no' == $result['questions'][$vote->questions_id]['group']) {
             $result['questions'][$vote->questions_id]['count'] = $result['questions'][$vote->questions_id]['count'] + 1;
             $result['questions'][$vote->questions_id]['percent'] = round($result['questions'][$vote->questions_id]['count'] / $result['no']['count'] * 100);
         }
     }
     //set smile
     foreach ($questions as $key => $value) {
         $result['questions'][$value->id]['smile'] = 10 - round($result['questions'][$value->id]['percent'] / 10);
         if ($result['questions'][$value->id]['smile'] < 1) {
             $result['questions'][$value->id]['smile'] = 1;
         }
     }
     /*echo '<pre>';
             print_r($result);
     
             die();*/
     //  echo '<pre>';
     // var_dump($result);
     // echo '</pre>';
     // die();
     return $result;
 }
Ejemplo n.º 21
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();
 }
Ejemplo n.º 22
0
 /**
  * Deletes an existing Story model.
  * If deletion is successful, the browser will be redirected to the 'index' page.
  * @param string $id
  * @return mixed
  */
 public function actionDelete($id)
 {
     $model = $this->findModel($id);
     $model->delete();
     if ($model->photo != '' && is_file(__DIR__ . '/../../../web/upload/220_125/220_125_' . $model->photo)) {
         unlink(__DIR__ . '/../../../web/upload/220_125/220_125_' . $model->photo);
     }
     if ($model->photo != '' && file_exists(__DIR__ . '/../../../web/upload/story/' . $model->photo)) {
         unlink(__DIR__ . '/../../../web/upload/story/' . $model->photo);
     }
     if ($model->photo != '' && file_exists(__DIR__ . '/../../../web/upload/300_174/300_174_' . $model->photo)) {
         unlink(__DIR__ . '/../../../web/upload/300_174/300_174_' . $model->photo);
     }
     $vote = Vote::find()->where(['story_id' => $model->id])->one();
     if ($vote != '' && $vote !== null) {
         $vote->delete();
     }
     return $this->redirect(['index']);
 }
Ejemplo n.º 23
0
 public function getVotes()
 {
     return $this->hasMany(Vote::className(), ['id' => 'vote_id'])->viaTable('vote_option', ['option_id' => 'id']);
 }
Ejemplo n.º 24
0
 public function getVotes($ip = NULL, $id = NULL)
 {
     return $id == NULL ? Vote::all() : Vote::where('ip_address', '=', $ip)->where('id_post', '=', $id)->get();
 }
Ejemplo n.º 25
0
 public static function myVote($me)
 {
     return Vote::where('user_id', '=', $me->id)->where('order_id', '=', Order::today()->id)->first();
 }
Ejemplo n.º 26
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]);
 }
Ejemplo n.º 27
0
 public function deleteMemberData()
 {
     // Delete all existing members.
     // get member ids to delete
     $memberIds = ArrayHelper::getColumn($this->members, 'id');
     if (sizeof($memberIds) > 0) {
         // without members there should be no contact etc.
         $transaction = Yii::$app->db->beginTransaction();
         try {
             // delete contacts by member_id
             Contact::deleteAll(['member_id' => $memberIds]);
             /*
             $codes = app\models\Code::find()
                 ->select('id')
                 //->where(['poll_id' => $this->id, 'member_id' => $memberIds]) // member_id not required because i will delete all anyhow?
                 ->where(['poll_id' => $this->id])
                 ->asArray()
                 ->all();
             $codeIds = ArrayHelper::getColumn($codes, 'id');
             */
             // alternative also over the codes relation depends on what is "faster"
             $codeIds = ArrayHelper::getColumn($this->codes, 'id');
             // delete the votes by the code_id
             Vote::deleteAll(['code_id' => $codeIds]);
             // delete the Codes by poll_id and member_id
             //Code::deleteAll(['poll_id'=> $this->id, 'member_id' => $memberIds]);
             Code::deleteAll(['poll_id' => $this->id]);
             // member_id not required because i will delete all anyhow?
             // also delete member entries by id
             Member::deleteAll(['id' => $memberIds]);
             $transaction->commit();
             return true;
         } catch (Exception $e) {
             $transaction->rollBack();
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 28
0
 /**
  * Finds the Vote model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param string $id
  * @return Vote the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Vote::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Ejemplo n.º 29
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getVotes()
 {
     return $this->hasMany(Vote::className(), ['election_id' => 'id']);
 }
Ejemplo n.º 30
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]);
 }