Exemplo n.º 1
0
 /**
  * 投票
  *  1、如果vote不存在,则创建之
  * 2、如果vote存在,且value相同,则删除之
  * 3、如果vote存在,且value不同,则改变value
  * @param unknown_type $userId
  */
 public function toggleVote($userId, $value)
 {
     $value = $value > 0 ? 1 : 0;
     $owner = $this->getOwner();
     $vote = Vote::model()->findByAttributes(array('voteableEntityId' => $owner->entityId, 'userId' => $userId));
     //判断是否重复点击
     if ($vote && $vote->value == $value) {
         $result = $vote->delete();
         $this->refreshVoteNum();
         return $result;
     }
     //以前还没有点击过?
     if (!$vote) {
         $vote = new Vote();
         $isNew = true;
         $vote->value = $value;
         $vote->addTime = time();
         $vote->voteableEntityId = $owner->entityId;
         $vote->userId = $userId;
     }
     if ($vote->save()) {
         if ($isNew) {
             //触发响应函数
             $this->handleOnAdded(new CEvent($this, array('vote' => $vote)));
         }
         return true;
     }
 }
Exemplo n.º 2
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     $data = Input::all();
     $vote = new Vote();
     $vote->school_no = Session::get('school_no');
     $vote->school_name = Session::get('school_name');
     $vote->vote_title = $data['vote_title'];
     $vote->vote_amount = $data['vote_amount'];
     $vote->start_at = $data['start_at'];
     $vote->end_at = $data['end_at'];
     $vote->vote_goal = $data['vote_goal'];
     $vote->can_select = $data['can_select'];
     $vote->builder_name = Session::get('builder_name');
     $vote->save();
     $arr = ['vote' => $vote, 'flash' => ['type' => 'success', 'msg' => '新增成功!']];
     $vote_new = DB::table('votes')->orderBy('id', 'desc')->get();
     $vote_id = $vote_new[0]->id;
     $vote_data = [$vote_id, $vote->vote_amount];
     Session::put('vote_data', $vote_data);
     Session::put('redo', 1);
     $this->account_create();
     //$this->passsec($vote_id);
     //Session::put('vote_id_insert', $vote_id);
     //return Redirect::route('vote.insert-second');
     return Redirect::route('vote.insert-second', array('vote_id' => $vote_id));
     //Redirect::action('VoteController@passsec', ['id' => $vote_id]);
 }
Exemplo n.º 3
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Vote();
     if (isset($_POST['Vote'])) {
         $model->attributes = $_POST['Vote'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Exemplo n.º 4
0
 public function run()
 {
     DB::table('votes')->delete();
     $vote = new Vote();
     $vote->vote = 1;
     $quote = Quote::where('title', '=', 'Test Quote')->first();
     $user = User::where('username', '=', 'tjbenator')->first();
     $vote->user()->associate($user);
     $vote->quote()->associate($quote);
     $vote->save();
 }
Exemplo n.º 5
0
 /**
  * @param $vote : 这个参数应该是yes或者no,以便能够统一统计
  * @param Users $user
  */
 public function addVoteBy($YesOrNo, Users $user)
 {
     if (!$this->isVotedBy($user)) {
         $vote = new Vote();
         $vote->voteable_type = get_class($this);
         $vote->voteable_id = $this->id;
         $vote->user_id = $user->id;
         $vote->vote = $YesOrNo;
         $vote->save();
     }
     return $this;
 }
Exemplo n.º 6
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Vote();
     $model->imageId = 1;
     $model->fbid = $_SESSION["fbid"];
     $model->created = time();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Vote'])) {
         $model->attributes = $_POST['Vote'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Exemplo n.º 7
0
 public function actionAddVote()
 {
     if (Yii::app()->request->isPostRequest && Yii::app()->request->isAjaxRequest) {
         $modelType = Yii::app()->request->getPost('modelType');
         $model_id = (int) Yii::app()->request->getPost('model_id');
         $value = (int) Yii::app()->request->getPost('value');
         if (!$model_id || !$value || !$modelType) {
             Yii::app()->ajax->failure(Yii::t('VoteModule.vote', 'Произошла ошибка!'));
         }
         $model = new Vote();
         $model->setAttributes(array('model' => $modelType, 'model_id' => $model_id, 'value' => $value));
         if ($model->save()) {
             Yii::app()->ajax->success();
         }
         Yii::app()->ajax->failure(Yii::t('VoteModule.vote', 'Произошла ошибка!'));
     }
     throw new CHttpException(404, Yii::t('VoteModule.vote', 'Страница не найдена!'));
 }
 public function vote($id)
 {
     $album = Album::find($id);
     if ($album === null) {
         $error = 'Can not vote. No such album found.';
         return View::make('errors.error', array('errorMsg' => $error));
     }
     $input = Input::all();
     if (1 > $input['vote'] || $input['vote'] > 10) {
         $error = 'Invalid vote. Must be between 1 and 10.';
         return View::make('errors.error', array('errorMsg' => $error));
     }
     $vote = new Vote(['value' => $input['vote'], 'album_id' => $album->id, 'voter_id' => Auth::user()->id]);
     $album->rank = $album->rank + $vote->value;
     $album->save();
     $vote->save();
     return Redirect::to('/albums/' . $album->id);
 }
Exemplo n.º 9
0
 public function addVote($voteData, $voteItemList)
 {
     $vote = new Vote();
     foreach ($vote->attributes as $field => $value) {
         if (isset($voteData[$field])) {
             $vote->{$field} = $voteData[$field];
         }
     }
     $vote->save();
     $voteid = Yii::app()->db->getLastInsertID();
     for ($i = 0; $i < count($voteItemList); $i++) {
         $voteItem = new VoteItem();
         $voteItem->voteid = $voteid;
         $voteItem->content = $voteItemList[$i];
         $voteItem->number = 0;
         $voteItem->type = $voteData["voteItemType"];
         $voteItem->save();
     }
 }
Exemplo n.º 10
0
 protected function _processVote($request)
 {
     if ($request->hasParameter("brat") && $request->hasParameter("post")) {
         $post = Doctrine::getTable('Post')->find($request->getParameter("post"));
         $vote = new Vote();
         $vote->Post = $post;
         if (strtolower($request->getParameter("brat")) == "yes") {
             $vote->is_brat = true;
         } else {
             if (strtolower($request->getParameter("brat")) == "no") {
                 $vote->is_brat = false;
             }
         }
         if ($vote->is_brat !== null) {
             $vote->save();
         }
     }
     $this->redirect("vote/index");
 }
Exemplo n.º 11
0
 public function executeVote(sfWebRequest $request)
 {
     $this->forward404Unless($request->isMethod('post'));
     $user = $this->getUser();
     $blog_id = $user->getAttribute('blog_id');
     $vote_form = new VoteForm();
     $bind_value = array('blog_id' => $blog_id, 'value' => $request->getParameter('vote'));
     $vote_form->bind($bind_value);
     if ($vote_form->isValid()) {
         $vote = new Vote();
         $vote->setBlog_id($vote_form->getValue('blog_id'));
         $vote->setValue($vote_form->getValue('value'));
         $vote->save();
         // Update vote_SUM
         Doctrine_Query::create()->update('Blog b')->set('b.vote_sum', 'b.vote_sum + ' . $vote_form->getValue('value'))->where('b.id = ?', $vote_form->getValue('blog_id'))->execute();
         // Update vote_COUNT
         Doctrine_Query::create()->update('Blog b')->set('b.vote_count', 'b.vote_count + 1')->where('b.id = ?', $vote_form->getValue('blog_id'))->execute();
         if (sfConfig::get('sf_exclusion_list')) {
             // Exclusion list!
             $session_list = $user->getAttribute('already_voted_list');
             if (is_array($session_list) && count($session_list) > 0) {
             } else {
                 //No data in the array
                 $session_list = array();
             }
             $session_list[] = $vote_form->getValue('blog_id');
             $user->setAttribute('already_voted_list', $session_list);
         }
         // Check if the vote history is empty it it is initiate an empty list
         $vote_history = $user->getAttribute('vote_history');
         if (is_array($vote_history) && count($vote_history) > 0) {
         } else {
             $vote_history = array();
         }
         // Add the just rated blog to the vote_history
         $voted_blog = Doctrine::getTable('Blog')->find($vote_form->getValue('blog_id'));
         $vote_avg = $voted_blog->getVote_sum() / $voted_blog->getVote_count();
         $vote_info = array('my_vote' => $vote_form->getValue('value'), 'vote_avg' => $vote_avg, 'vote_count' => $voted_blog->getVote_count(), 'vote_sum' => $voted_blog->getVote_sum(), 'blog_url' => $voted_blog->getUrl(), 'blog_thmbnail' => $voted_blog->getThumbnail_url());
         array_unshift($vote_history, $vote_info);
         $user->setAttribute('vote_history', $vote_history);
         $this->redirect('blog/index');
     }
 }
Exemplo n.º 12
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     $data = Input::all();
     $vote = new Vote();
     $vote->school_no = Session::get('school_no');
     $vote->school_name = Session::get('school_name');
     $vote->vote_title = $data['vote_title'];
     $vote->vote_amount = $data['vote_amount'];
     $date_now = $this->getDatetimeNow();
     $date_n = new DateTime("now");
     $date_s = new DateTime($data['start_at']);
     $date_e = new DateTime($data['end_at']);
     if ($date_s < $date_n or $date_s > $date_e) {
         //dd($date_now,$data['start_at'] ,$data['end_at'] ) ;
         echo '<script type="text/javascript">';
         echo 'alert("起始時間不可大於結束時間或小於現在時間")';
         echo '</script>';
         return View::make('tasks.vote-insert-first', compact('votes', 'date_now'));
     }
     $temp_date = date("Y-m-d H:i:s", strtotime($data['start_at']));
     $vote->start_at = $temp_date;
     $temp_date = date("Y-m-d H:i:s", strtotime($data['end_at']));
     $vote->end_at = $temp_date;
     //判斷起始時間是否小於結束時間,並且比現在時間大。
     $vote->vote_goal = $data['vote_goal'];
     $vote->can_select = $data['can_select'];
     $vote->public_or_private = $data['public_or_private'];
     $vote->builder_name = Session::get('builder_name');
     $vote->save();
     $vote_new = DB::table('votes')->orderBy('id', 'desc')->get();
     $vote_id = $vote_new[0]->id;
     $vote_data = [$vote_id, $vote->vote_amount];
     Session::put('vote_data', $vote_data);
     Session::put('redo', 1);
     $this->account_create();
     //$this->passsec($vote_id);
     //Session::put('vote_id_insert', $vote_id);
     //return Redirect::route('vote.insert-second');
     return Redirect::route('vote.insert-second', array('vote_id' => $vote_id));
     //Redirect::action('VoteController@passsec', ['id' => $vote_id]);
 }
Exemplo n.º 13
0
 public function dislikePost()
 {
     $id = Input::get('id');
     $dislikeVote = Vote::where('type', 'dislike')->where('user_id', Auth::id())->where('post_id', $id)->first();
     if (!$dislikeVote) {
         $oppositeVote = Vote::where('type', 'like')->where('user_id', Auth::id())->where('post_id', $id)->first();
         if (!empty($oppositeVote)) {
             $oppositeVote->delete();
         }
         $vote = new Vote();
         $vote->user_id = Auth::id();
         $vote->post_id = $id;
         $vote->type = 'dislike';
         $vote->save();
     }
     $totalLikeVote = Vote::where('type', 'like')->where('post_id', $id)->count();
     $totalDislikeVote = Vote::where('type', 'dislike')->where('post_id', $id)->count();
     $result = array($totalLikeVote, $totalDislikeVote);
     return Response::json($result);
 }
Exemplo n.º 14
0
 public function executeVote(sfWebRequest $request)
 {
     $liste_id = $request->getParameter('id');
     if ($liste_id != 0) {
         $liste = $this->getRoute()->getObject();
     } else {
         $liste = 0;
     }
     if ($liste_id != 0 && !$liste) {
         $this->getUser()->setFlash('error', 'Cette liste n\'existe pas.');
     } else {
         if ($liste_id != 0 && $liste->getSemestreId() != sfConfig::get('app_portail_current_semestre')) {
             $this->getUser()->setFlash('error', 'Vous ne pouvez pas voter pour cette liste.');
         } else {
             if (!$this->isCotisant()) {
                 $this->getUser()->setFlash('error', 'Vous n\'êtes pas cotisant. Vous ne pouvez pas participer aux élections du BDE.');
             } else {
                 if (VoteTable::getInstance()->getVoteForUserAndSemestre($this->getUser()->getGuardUser()->getPrimaryKey(), sfConfig::get('app_portail_current_semestre'))->fetchOne()) {
                     $this->getUser()->setFlash('error', 'Vous avez déjà voté.');
                 } else {
                     $vote = new Vote();
                     $vote->setIp($_SERVER['REMOTE_ADDR']);
                     $vote->setSemestreId(sfConfig::get('app_portail_current_semestre'));
                     $vote->setUserId($this->getUser()->getGuardUser()->getId());
                     $vote->setLogin($this->getUser()->getGuardUser()->getUsername());
                     $vote->save();
                     if ($liste_id != 0) {
                         $pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
                         $stmt = $pdo->prepare('UPDATE `vote_liste` SET `count`=(`count`+1) WHERE `id` = :id');
                         $stmt->bindParam(':id', $liste->getPrimaryKey(), PDO::PARAM_INT);
                         $stmt->execute();
                     }
                     $this->getUser()->setFlash('success', 'Votre vote a été pris en compte.');
                 }
             }
         }
     }
     $this->redirect('homepage');
 }
Exemplo n.º 15
0
 public function actionRestcreate()
 {
     $this->checkRestAuth();
     if (!isset($_GET['dreamId']) || !isset($_POST['subOpenId'])) {
         return $this->sendResponse(400, 'missed required properties');
     }
     $dream = Dream::model()->findByPk($_GET['dreamId']);
     if ($dream == null || $dream->nickname == null) {
         $this->sendResponse(404, 'not found');
     }
     if ($dream->sub_open_id == $_POST['subOpenId']) {
         $this->sendResponse(400, 'forbidden to vote');
     }
     $criteria = new CDbCriteria();
     $criteria->addCondition('dream_id=:dreamId', 'and');
     $criteria->addCondition('sub_open_id=:sub_open_id');
     $criteria->params = array(':sub_open_id' => $_POST['subOpenId'], ':dreamId' => $_GET['dreamId']);
     $results = Vote::model()->findAll($criteria);
     if (count($results) > 0) {
         $this->sendResponse(400, 'voted');
     }
     // create vote
     $vote = new Vote();
     $vote->dream_id = $_GET['dreamId'];
     $vote->sub_open_id = $_POST['subOpenId'];
     $vote->nickname = $_POST['nickname'];
     $vote->headimgurl = $_POST['headimgurl'];
     $vote->bonus = (int) rand(100, 500);
     // 3 - 5元之间随机
     if (!$vote->save()) {
         return $this->sendResponse(500, 'faild to save vote');
     }
     $dream->bonus += $vote->bonus;
     if (!$dream->save()) {
         return $this->sendResponse(500, 'faild to save dream');
     }
     $this->sendResponse(201, $vote->id);
 }
Exemplo n.º 16
0
 public function voteDownQuestion($qid)
 {
     $dbCheck = Vote::where('user_id', '=', Auth::user()->user_id)->where('question_id', '=', $qid)->first();
     if ($dbCheck) {
         return Redirect::route('single-question', $qid)->with('global', 'Sorry, you Previously vote this question');
     } else {
         $vote = new Vote();
         $vote->user_id = Auth::user()->user_id;
         $vote->question_id = $qid;
         $vote->vote = 0;
         $vote->save();
         /*Insert point to the Vote user*/
         $insertPoint = User::find(Auth::user()->user_id);
         $insertPoint->points = $insertPoint->points - 1;
         $insertPoint->save();
         /*Insert point to the Question user*/
         $questionuser = Question::where('id', '=', $qid)->first();
         $insertPoint = User::find($questionuser->user_id);
         $insertPoint->points = $insertPoint->points - 2;
         $insertPoint->save();
         return Redirect::route('single-question', $qid)->with('global', 'Your Successfully vote down this question');
     }
 }
Exemplo n.º 17
0
 public function doVoting()
 {
     if (Auth::guest()) {
         echo json_encode(array('status' => 'error', 'message' => Lang::get('texts.request_login')));
         exit;
     }
     $user = Confide::user();
     $user_id = $user->id;
     $coinvote_id = $_POST['coinvote_id'];
     $user_vote = Vote::where('user_id', $user_id)->where('coinvote_id', $coinvote_id)->first();
     if (isset($user_vote->user_id)) {
         echo json_encode(array('status' => 'error', 'message' => Lang::get('texts.you_voted')));
         exit;
     } else {
         /*$trade = Trade::where('seller_id',$user_id)->orwhere('buyer_id',$user_id)->first();
         		if(!isset($trade->id)){
         			echo json_encode(array('status'=>'error','message'=> Lang::get('texts.must_have_trade')));
         			exit; 
         		}*/
         $date = date("Y-m-d");
         $times_vote = Vote::where('created_at', '>=', $date)->where('user_id', $user_id)->orderby('created_at', 'desc')->get()->toArray();
         $count = count($times_vote);
         if ($count > 5) {
             echo json_encode(array('status' => 'error', 'message' => Lang::get('texts.over_perday'), 'count' => $count, 'times_vote' => $times_vote));
             exit;
         } else {
             $vote = new Vote();
             //Vote::insert();
             $vote->coinvote_id = $coinvote_id;
             $vote->user_id = $user_id;
             $vote->save();
             echo json_encode(array('status' => 'success', 'message' => Lang::get('texts.vote_success'), 'count' => $count, 'times_vote' => $times_vote, 'vote_id' => $vote->id));
             exit;
         }
     }
 }
Exemplo n.º 18
0
Arquivo: index.php Projeto: slim/heer
<?php

require '../../../lib/link.php';
require '../../../lib/id.php';
require '../../../lib/vote.php';
Link::set_db('sqlite:../../../heer.db');
Vote::set_db('sqlite:../../../heer.db');
ID::set_seed(file_get_contents('../../../seed'));
$url = $_GET['u'];
$title = $_GET['t'];
$bookmarklet = new ID($_GET['i']);
$vote = new Vote($url, $bookmarklet);
if ($_GET['n']) {
    $vote->note = $_GET['n'];
}
$link = new Link($url, $title);
if ($bookmarklet->isAuthentic() && $vote->save()) {
    $link->save();
}
header("Location: {$url}");
Exemplo n.º 19
0
 public function testCreateMandateForCandidatesWithVotesCountGreaterThanQuote()
 {
     $candidates = $this->getFixtureManager()->getRows('candidate');
     $electionMock = $this->getPreparedElection(array('createMandate'));
     $electionMock->isNewRecord = false;
     $electionMock->id = $candidates[3]['election_id'];
     $electionMock->refresh();
     $electionMock->quote = 2;
     $this->assertEquals(Election::STATUS_PUBLISHED, $electionMock->status);
     $this->assertEquals('Published', $electionMock->statusState->stateName);
     $electionMock->status = Election::STATUS_REGISTRATION;
     $this->assertTrue($electionMock->save());
     $electionMock->status = Election::STATUS_ELECTION;
     $this->assertTrue($electionMock->save());
     $this->assertEquals(Election::STATUS_ELECTION, $electionMock->status);
     $this->assertEquals('Election', $electionMock->statusState->stateName);
     $vote = new Vote();
     $vote->candidate_id = $candidates[3]['id'];
     $vote->election_id = $candidates[3]['election_id'];
     $vote->user_id = $electionMock->electors[0]->user_id;
     $this->assertTrue($vote->save(), print_r($vote->getErrors(), true));
     $vote = new Vote();
     $vote->candidate_id = $candidates[3]['id'];
     $vote->election_id = $candidates[3]['election_id'];
     $vote->user_id = $electionMock->electors[1]->user_id;
     $this->assertTrue($vote->save(), print_r($vote->getErrors(), true));
     $vote = new Vote();
     $vote->candidate_id = $candidates[4]['id'];
     $vote->election_id = $candidates[3]['election_id'];
     $vote->user_id = $electionMock->electors[2]->user_id;
     $this->assertTrue($vote->save(), print_r($vote->getErrors(), true));
     $vote = new Vote();
     $vote->candidate_id = $candidates[4]['id'];
     $vote->election_id = $candidates[3]['election_id'];
     $vote->user_id = $electionMock->electors[3]->user_id;
     $this->assertTrue($vote->save(), print_r($vote->getErrors(), true));
     $vote = new Vote();
     $vote->candidate_id = $candidates[5]['id'];
     $vote->election_id = $candidates[3]['election_id'];
     $vote->user_id = $electionMock->electors[4]->user_id;
     $this->assertTrue($vote->save(), print_r($vote->getErrors(), true));
     $this->electionFinishedStateMock->expects($this->exactly(2))->method('createMandate');
     $this->electionFinishedStateMock->expects($this->at(0))->method('createMandate')->with($this->callback(function ($electedCandidate) use(&$candidates) {
         return $electedCandidate->id == $candidates[3]['id'];
     }));
     $this->electionFinishedStateMock->expects($this->at(1))->method('createMandate')->with($this->callback(function ($electedCandidate) use(&$candidates) {
         return $electedCandidate->id == $candidates[4]['id'];
     }));
     $this->assertEquals(Election::STATUS_ELECTION, $electionMock->status);
     $this->assertEquals('Election', $electionMock->statusState->stateName);
     $this->assertTrue($electionMock->canTransit('Finished'));
     $electionMock->status = Election::STATUS_FINISHED;
     $this->assertTrue($electionMock->save(), print_r($electionMock->getErrors(), true));
 }
Exemplo n.º 20
0
 public function vote($id, $votestatus)
 {
     if (Post::where('id', $id)->exists() && ($votestatus == 1 || $votestatus == 0)) {
         $post = Post::where('id', $id)->first();
         if (Vote::where('post_id', $id)->where('user_id', Auth::user()->id)->exists()) {
             return Redirect::back();
         }
         if ($post->user_id == Auth::user()->id) {
             return Redirect::back();
         }
         $vote = new Vote();
         $vote->user_id = Auth::user()->id;
         $vote->post_id = $id;
         $vote->vote = $votestatus;
         $vote->save();
     }
     return Redirect::back();
 }
Exemplo n.º 21
0
 public function actionvote()
 {
     $imageId = $_REQUEST['imageId'];
     if (isset($imageId)) {
         $n = Vote::model()->countBySql("SELECT COUNT(*) FROM votes WHERE fbid='" . $_SESSION["fbid"] . "' AND imageId=" . $imageId);
         if (isset($n) && $n < 1) {
             //you can vote
             //only when you have not voted yet
             $vote = new Vote();
             $vote->created = new CDbExpression('NOW()');
             $vote->imageId = $_POST['imageId'];
             $vote->fbid = $_SESSION["fbid"];
             $vote->save();
         }
         $n = Vote::model()->countBySql("SELECT COUNT(*) FROM votes WHERE imageId=" . $imageId);
         $image = FImage::model()->findByPk($imageId);
         if (isset($image)) {
             //update count of votes on image
             $image->votes = $n;
             $image->save();
         }
         echo $n;
         // . "&nbsp;hlasů&nbsp;&nbsp;&nbsp;<span>Už jsi hlasoval/a</span>";
         Yii::app()->end();
     }
 }
Exemplo n.º 22
0
 public function actionCreate($sid, $uid)
 {
     //var_dump($_POST);
     $criteria = new CDbCriteria();
     $criteria->condition = 'uid=:uid AND sid=:sid';
     $criteria->params = array(':uid' => $uid, ':sid' => $sid);
     $vote = Vote::model()->findAll($criteria);
     if ($vote) {
         $this->renderPartial('error', array('error_code' => '3', 'sid' => $sid));
     } else {
         if (isset($_POST['selectdel'])) {
             $count = count($_POST['selectdel']);
             $voteself = taxonomy_term_load($sid);
             $maxChoose = $voteself->field_limit['und'][0]['value'];
             //if($count>$maxChoose)
             if ($count < $maxChoose) {
                 /* 					$this->renderPartial('result',array(
                 						'info'=>'0',
                 						
                 					)); */
                 $this->renderPartial('error', array('error_code' => '4', 'maxChoose' => $maxChoose, 'sid' => $sid));
             } else {
                 if ($count > $maxChoose) {
                     /* 					$this->renderPartial('result',array(
                     						'info'=>'0',
                     						
                     					)); */
                     $this->renderPartial('error', array('error_code' => '5', 'maxChoose' => $maxChoose, 'sid' => $sid));
                 } else {
                     foreach ($_POST['selectdel'] as $itemid) {
                         $model = new Vote();
                         $model->setAttributes(array('sid' => $sid, 'nid' => $itemid, 'uid' => $uid));
                         $model->save(true);
                         $item = node_load($itemid);
                         $item->field_vote['und'][0]['value'] = $item->field_vote['und'][0]['value'] + 1;
                         node_save($item);
                     }
                     $this->renderPartial('error', array('error_code' => '6', 'sid' => $sid));
                 }
             }
         } else {
             $this->renderPartial('error', array('error_code' => '7', 'sid' => $sid));
         }
     }
 }
 public function support(Request $request)
 {
     if (Auth::guest()) {
         $message = ['error' => 'guest'];
         return $message;
     } else {
         // Recuperamos los datos enviados por el metodo POST
         $user_id = Auth::user()->id;
         //el id del usuario logueado
         $id_initiative = $request->input('id');
         $password = $request->input('password');
         //se crea un array que trae si el usuario ya voto por la iniciativa enviada en la consulta
         $user_votes = Vote::where('id_initiative', '=', $id_initiative)->where('user', '=', $user_id)->get();
         //se valida que la iniciativa no este votada por el usuario logueado
         if (empty($user_votes[0])) {
             // Si nuestros datos pasan la validacion creamos un nuevo objeto en base al modelo Initiative para actualizar el campo 'votes' de la iniciativa enviada
             $initiative = Initiative::find($id_initiative);
             if ($initiative->password == $password) {
                 $initiative->votes = $initiative->votes + 1;
                 $initiative->save();
                 //generamos un nuevo registro para la encuesta seleccionada
                 $vote = new Vote();
                 $vote->id_initiative = $id_initiative;
                 $vote->user = $user_id;
                 $vote->save();
                 $message = ['success' => 'ok'];
                 return $message;
             } else {
                 $message = ['error' => 'Token mismatch'];
                 return $message;
             }
         } else {
             $message = ['error' => 'there is already a vote for this initiative'];
             return $message;
         }
     }
 }
Exemplo n.º 24
0
 public function testNotRevokesWithRevoteLimitEqualsToZero()
 {
     $election = Election::model()->findByPk(1);
     $election->revotes_count = 0;
     $this->assertTrue($election->save());
     $vote = new Vote();
     $vote->election_id = 1;
     $vote->candidate_id = 3;
     $vote->user_id = 1;
     $this->assertTrue($vote->save());
     $this->setExpectedException('Exception', 'Revote limit has been reached');
     $vote->status = Vote::STATUS_REVOKED;
     $this->assertFalse($vote->save());
     $this->setExpectedException('Exception', 'Revote limit has been reached');
     $vote = new Vote();
     $vote->candidate_id = 5;
     $vote->user_id = 1;
     $vote->election_id = 1;
     $this->assertFalse($vote->save());
 }
Exemplo n.º 25
0
 public function applyVote($user, $type, $type_id, $updown)
 {
     //deal with item table
     $item = "";
     switch ($type) {
         case Constant::POST_TYPE:
             $item = Post::findOrFail($type_id);
             break;
         case Constant::COMMENT_TYPE:
             $item = Comment::findOrFail($type_id);
             Cache::forget(Constant::COMMENT_CACHE_NEWLIST_NAME . $item->post_id);
             break;
         case Constant::SECTION_TYPE:
             $item = Section::findOrFail($type_id);
             break;
         default:
             throw new UnexpectedValueException("type: {$type} not enumerated");
     }
     //increment our total vote counter
     $user->increment('votes');
     //decrement one point for voting
     $user->decrement('points');
     //double decrement for self upvote
     if ($type == Constant::POST_TYPE || $type == Constant::COMMENT_TYPE) {
         if ($item->user_id == Auth::user()->id && $updown == Constant::VOTE_UP) {
             $user->decrement('points');
         }
     }
     //upvote/downvote the item itself
     if ($updown == Constant::VOTE_UP) {
         $item->increment('upvotes');
     } else {
         if ($updown == Constant::VOTE_DOWN) {
             $item->increment('downvotes');
         }
     }
     //upvote/downvote user who posted (ignore for sections)
     if ($type == Constant::POST_TYPE || $type == Constant::COMMENT_TYPE) {
         $rec_user = User::findOrFail($item->user_id);
         if ($updown == Constant::VOTE_UP) {
             $rec_user->increment('points');
         } else {
             if ($updown == Constant::VOTE_DOWN) {
                 $rec_user->decrement('points');
             }
         }
     }
     //deal with votes table
     $vote = new Vote(array('type' => $type, 'user_id' => Auth::user()->id, 'item_id' => $type_id, 'updown' => $updown));
     $vote->save();
 }
Exemplo n.º 26
0
                $vote->setData('writein', $v);
            }
            if ($race == null || $keys[0] != 'race' || $raceID > sizeof($races) - 1 || $vote->candidate > sizeof($races[$raceID]->candidates) || (!isset($race->allowWriteIn) || $race->allowWriteIn != true) && sizeof($keys) == 3) {
                echo json_encode(array('success' => false, 'error' => 'There was an error submitting your vote. Please refresh and/or try again later.'));
                return;
            }
            $usrTags = $user->getData('tags') == null ? array() : $user->getData('tags');
            $restrictions = isset($race->restrictions) ? $race->restrictions : array();
            if (!empty($restrictions)) {
                $banKey = array_intersect($usrTags, $restrictions);
                if ($banKey != false) {
                    echo json_encode(array('success' => false, 'error' => 'You do not have permission to cast a vote in this election.'));
                    return;
                }
            }
            $vote->save($db);
        }
    }
    echo json_encode(array('success' => true, 'data' => $data, 'vote' => $vote));
})->name('voteFor');
$app->get('/results(/)', function () use($app, $db) {
    $app->render('resultsListing.html', array('elections' => $db->getElection()));
})->name('results');
$app->get('/about(/)', function () use($app) {
    $app->render('about.html');
})->name('about');
$app->get('/dashboard(/)', function () use($app, $db) {
    $user = $app->view->get('user');
    if ($user == false) {
        $app->flash('error', 'You must be logged in to access that page.');
        $app->redirect($app->urlFor('homepage'));
Exemplo n.º 27
0
 function actionDisagreevote()
 {
     $pk_id = $_POST['pk_id'];
     $modelName = isset($_POST['model']) ? $_POST['model'] : "answer";
     $return = array();
     $count = Vote::model()->count("create_user=:create_user and model=:model and pk_id=:pk_id", array(":pk_id" => $pk_id, ":create_user" => Yii::app()->user->id, ":model" => $modelName));
     if ($count > 0) {
         $Vote = Vote::model()->find("create_user=:create_user and model=:model and pk_id=:pk_id", array(":pk_id" => $pk_id, ":create_user" => Yii::app()->user->id, ":model" => $modelName));
         if ($Vote->opinion == 1) {
             $return['message'] = $Vote->delete() ? "ok" : "false";
         } else {
             $Vote->opinion = 1;
             $Vote->model = $modelName;
             $Vote->create_time = time();
             $return['message'] = $Vote->save() ? "ok" : "false";
         }
     } else {
         $model = new Vote();
         $model->pk_id = $pk_id;
         $model->create_user = Yii::app()->user->id;
         $model->create_time = time();
         $model->model = $modelName;
         $model->opinion = 1;
         $return['message'] = $model->save() ? "ok" : "false";
     }
     $return['count'] = Vote::model()->count("opinion=0 and model=:model and pk_id=:pk_id", array(":pk_id" => $pk_id, ":model" => $modelName));
     echo json_encode($return);
 }
Exemplo n.º 28
0
 /**
  * Aggiunge un voto al post selezionato e lo salva nel database.
  *
  * @param author: id dell'autore del voto
  * @param post: variabile di tipo Post
  * @param comment: il voto
  * @return: post aggiornato.
  */
 static function votePost($author, $post, $vote)
 {
     require_once "post/PostCommon.php";
     $v = self::loadVote($author, $post->getID());
     if ($v !== false) {
         self::removeVote($v);
     }
     //else
     //	echo $author . "-" . $post->getID();
     $v = new Vote($author, $post->getID(), $vote);
     $v->save();
     $post->addVote($v);
     return $post;
 }
Exemplo n.º 29
0
 public static function saveVote()
 {
     self::check_logged_in();
     $p = $_POST;
     $user = User::findByPK($p['user_id']);
     $poll = Poll::findByPK($p['poll_id']);
     $polloptions = PollOption::findByPollId($poll->id);
     $curruser = self::get_user_logged_in();
     if (!($curruser->id == $user->id)) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Virheellinen pyyntö!'));
     }
     $status = Poll::checkVoteStatus($user->id, $poll->id);
     if ($status === NULL) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Sinulla ei ole äänioikeutta pyytämääsi äänestykseen!'));
     } elseif ($status === TRUE) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Olet jo käyttänyt äänioikeutesi äänestyksessä ' . $poll->name . '!'));
     }
     $errors = array();
     $poll_start = new DateTime($poll->start_time);
     $poll_end = new DateTime($poll->end_time);
     if ($poll_start->getTimeStamp() >= time()) {
         $errors[] = 'Äänestys ei ole vielä alkanut!';
     }
     if ($poll_end->getTimeStamp() <= time()) {
         $errors[] = 'Äänestys on päättynyt – et voi enää äänestää!';
     }
     if (!isset($_POST['choice'])) {
         $errors[] = 'Et valinnut yhtään vaihtoehtoa. Valitse vaihtoehto äänestääksesi!';
     } else {
         $polloptions[$p['choice']]->chosen = TRUE;
     }
     if (!isset($_POST['accept'])) {
         $errors[] = 'Et ilmaissut hyväksyväsi äänioikeutesi ainutkertaisuuttä. Et voi äänestää hyväksymättä sitä.';
     }
     if (!empty($errors)) {
         View::make('poll/vote.html', array('user' => $user, 'poll' => $poll, 'polloptions' => $polloptions, 'errors' => $errors));
     } else {
         $vote = new Vote(array('users_id' => $user->id, 'polls_id' => $poll->id, 'poll_options_id' => $polloptions[$p['choice']]->id, 'time' => date('c')));
         $vote->save();
         Redirect::to('/user/' . $curruser->id, array('message' => 'Äänesi äänestyksessä ' . $poll->name . ' on tallennettu! Antamaasi ääntä ei voida yhdistää sinuun myöhemmin.'));
     }
 }
Exemplo n.º 30
0
<?php

/**
 * Created by PhpStorm.
 * User: DiD
 * Date: 30/09/2015
 * Time: 14:50
 */
include 'common.php';
if (isset($_GET['possibility-id']) && is_numeric($_GET['possibility-id']) && $loggedUser) {
    $possibility = Database::getOne('possibilities', array('id' => $_GET['possibility-id']));
    $idea = Database::getOne('ideas', array('id' => $possibility->idea));
    $idea->removeVote($loggedUser);
    if ($possibility) {
        $vote = new Vote();
        $vote->possibility = $possibility->id;
        $vote->user = $loggedUser->id;
        $vote->save();
        header('location:../?message=added-vote');
    } else {
        header('location:../?error=unknown-possibility');
    }
} else {
    header('location:../');
}