Ejemplo n.º 1
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.'));
     }
 }
Ejemplo n.º 2
0
 public function addOption(PollOption $option)
 {
     $this->options[] = $option;
     $this->votes += $option->getNumVotes();
     $this->options_loaded = true;
 }
Ejemplo n.º 3
0
<?php

/**
 * Created by PhpStorm.
 * User: Jakub
 * Date: 16/02/2016
 * Time: 21:52
 */
class PollOption extends Model
{
    public $polloptionid;
    public $pollid;
    public $title;
    public $description;
    public $dateline;
    public $userid;
    public $username;
    function getHash()
    {
        if (!isset($_SESSION['csrf'])) {
            $_SESSION['csrf'] = rand(1, 1000000000);
        }
        return md5($_SESSION['csrf'] . $this->polloptionid);
    }
}
PollOption::init('polloptions', 'polloptionid');
Ejemplo n.º 4
0
    /**
     * @return void
     */
    public function show()
    {
        if (!TwitterAuth::isLogged()) {
            ?>
            Sólo los administradores pueden ver esta página.
            <a href="<?=HTMLResponse::getRoute()?>?authenticate=1">
                Inicia sesión.
            </a><br>
            <?
            return;
        }
        else if (!Team::isAdmin()) {
            ?>
            Sólo los administradores pueden ver esta página.<br>
            <?
            return;
        }
        else {
            $title = trim(HTMLResponse::fromPOST('title', ''));
            $description = trim(HTMLResponse::fromPOST('description', ''));
            $options = [];
            for ($i=1; $i<6; $i++) {
                $value = trim(HTMLResponse::fromPOST('option'.$i, ''));
                if (strlen($value)) {
                    $options[] = $value;
                }
            }

            if (strlen($title) && count($options)>=2) {
                $poll = Poll::create();
                $poll->title = $title;
                $poll->description = $description;
                $poll->isvisible = true;
                $poll->isopen = true;
                $poll->username = TwitterAuth::getUserName();
                $poll->userid = TwitterAuth::getUserId();
                $poll->dateline = time();
                $poll->avatar = TwitterAuth::getAvatar();
                $poll->save();

                foreach($options as $index => $option) {
                    $pollOption = PollOption::create();
                    $pollOption->pollid = $poll->pollid;
                    $pollOption->userid = TwitterAuth::getUserId();
                    $pollOption->username = TwitterAuth::getUserName();
                    $pollOption->title = $option;
                    $pollOption->save();
                }

                HTMLResponse::exitWithRoute("/votaciones/{$poll->pollid}/");
            }

            ?>
            <form action="<?=HTMLResponse::getRoute()?>" method="post">
                <div style="padding:3px">
                    <div class="inblock middle" style="width:120px">
                        Título
                    </div>
                    <input name="title" value="<?=htmlentities($title)?>">
                </div>

                <div style="padding:3px">
                    <div class="inblock middle" style="width:120px">
                        Descripción
                    </div>
                    <input name="description" value="<?=htmlentities($description)?>">
                </div>

                <?
                for ($i=1; $i<=6; $i++) {
                    ?>
                    <div style="padding:3px">
                        <div class="inblock middle" style="width:120px">
                            Opción <?=$i?>
                        </div>
                        <input name="option<?=$i?>" value="<?=htmlentities($options[$i-1])?>">
                    </div>
                    <?
                }
                ?>

                <div style="padding:3px">
                    <div class="inblock middle" style="width:120px">

                    </div>
                    <input type="submit" value="Crear votación">
                </div>
            </form>
            <?


        }
    }
Ejemplo n.º 5
0
    /**
     * @return void
     */
    public function show()
    {
        if (!TwitterAuth::isLogged()) {
            ?>
            Sólo los miembros pueden ver esta página.
            <a href="<?=HTMLResponse::getRoute()?>?authenticate=1">
                Inicia sesión.
            </a><br>
            <?
            return;
        }
        else {
            if (!Team::isMember()) {
                HTMLResponse::exitWithRoute('/votaciones/');
            }

            $answer = PollVote::findOne('userid = ? and pollid = ?',
                [TwitterAuth::getUserId(), $this->poll->pollid]);

            $options = PollOption::find('pollid = ? order by polloptionid asc', [$this->poll->pollid]);


            if (!$answer && strlen($hash = HTMLResponse::fromGET('hash', ''))) {
                $optionid = HTMLResponse::fromGET('vote');

                foreach($options as $index => $option) {
                    if ($option->polloptionid == $optionid && $option->getHash() == $hash) {
                        $answer = PollVote::create();
                        $answer->userid = TwitterAuth::getUserId();
                        $answer->dateline = time();
                        $answer->avatar = TwitterAuth::getAvatar();
                        $answer->pollid = $this->poll->pollid;
                        $answer->polloptionid = $option->polloptionid;
                        $answer->username = TwitterAuth::getUserName();
                        $answer->save();
                    }
                }
            }

            $answers = Model::groupBy(PollVote::find('pollid = ?', [$this->poll->pollid]), 'polloptionid');

            $hasAnswered = !!$answer;

            ?><div style="text-align:left; margin: 0 auto" class="inblock">
            <table style="width:640px">
                <thead>
                <tr>
                    <td>Lista de opciones</td>
                </tr>
                </thead>
                <?

                foreach($options as $index => $option) {
                    ?>
                    <tr><td class="row" style="text-align: left">
                            <div style="height: 6px"></div>
                            <div class="inblock middle" style="width:320px">
                                <b>Opción <?=$index+1?></b>: <?= htmlentities($option->title) ?>
                            </div>
                            <div class="inblock middle">
                                <div class="moreless inblock middle" style="width: 150px">
                                    <a href="javascript:void(0)" onclick="$(this).closest('.row').find('.moreless').toggle(); $(this).closest('.row').find('.onmore').slideDown(500);">+ Mostrar más</a>
                                </div>
                                <div class="moreless inblock middle" style="width: 150px; display: none">
                                    <a href="javascript:void(0)" onclick="$(this).closest('.row').find('.moreless').toggle(); $(this).closest('.row').find('.onmore').slideUp(400);">- Mostrar menos</a>
                                </div>
                            </div>
                            <div class="inblock middle">
                                <? if (!$hasAnswered) { ?>
                                    <a href="<?=HTMLResponse::getRoute()?>?vote=<?=$option->polloptionid?>&hash=<?=$option->getHash()?>" onclick="return confirm('¿Votas <?=htmlentities($option->title)?>?')">
                                        Votar esta opción
                                    </a>
                                <? } else if ($answer->polloptionid == $option->polloptionid) { ?>
                                    <i>Votaste esta opción</i>
                                <? } ?>
                            </div>
                            <div class="onmore" style="display: none; padding: 12px">
                                <?= $option->description ?>
                            </div>
                            <div style="height: 6px"></div>
                            <?
                            if (!$hasAnswered) {
                                ?><i>Vota primero para ver los resultados</i><?
                            }
                            else {
                                $optionAnswers = $answers[$option->polloptionid];
                                ?>
                                Votado por: <?= $optionAnswers
                                    ? '<b>'.implode(', ', Model::pluck($optionAnswers, 'username')).'</b> ('.count($optionAnswers).' votos)'
                                    : '<i>Nadie</i>'; ?>
                                <?
                            }
                            ?>
                            <div style="height: 6px"></div>
                        </td></tr>
                    <?
                }

                ?></table></div><br><br><?
        }
    }
Ejemplo n.º 6
0
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function postUpdate($id)
 {
     if (Session::get('user_level') < Config::get('cms.editPolls')) {
         return Redirect::to(_l(URL::action('AdminHomeController@getIndex')))->with('message', Lang::get('admin.notPermitted'))->with('notif', 'warning');
     }
     $rules = array('question' => 'Required', 'options' => 'Required');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to(_l(URL::action('PollController@getCreate')))->withErrors($validator)->withInput();
     } else {
         try {
             $poll = Poll::findOrFail($id);
             if (Input::get('createdAt')) {
                 $poll->created_at = date("Y-m-d H:i:s", strtotime(Input::get('createdAt')));
             } else {
                 $poll->created_at = date("Y-m-d H:i:s", strtotime('now'));
             }
             $poll->title = Input::get('question');
             if (Input::get('endDate')) {
                 $poll->end_date = date("Y-m-d H:i:s", strtotime(Input::get('endDate')));
             } else {
                 $poll->end_date = date("Y-m-d H:i:s", strtotime('1.1.1970'));
             }
             $poll->published = Input::get('published');
             $poll->save();
             $votes = Input::get('voteCount');
             $options = $poll->pollOptions;
             $poll->pollOptions()->delete();
             foreach (Input::get('options') as $key => $option) {
                 $done = false;
                 foreach ($options as $key2 => $option2) {
                     if ($key == $option2->id) {
                         $poption = new PollOption();
                         $poption->title = $option;
                         $poption->poll_id = $poll->id;
                         $poption->id = $option2->id;
                         if (isset($votes[$key]) && $votes[$key] != 0) {
                             $poption->vote_count = $votes[$key];
                         }
                         $poption->save();
                         $done = true;
                         continue;
                     }
                 }
                 if (!$done) {
                     $pollOption = new PollOption();
                     $pollOption->poll_id = $poll->id;
                     $pollOption->title = $option;
                     if (isset($votes[$key]) && $votes[$key] != 0) {
                         $pollOption->vote_count = $votes[$key];
                     } else {
                         $pollOption->vote_count = 0;
                     }
                     $pollOption->save();
                 }
             }
             //return;
             return Redirect::to(_l(URL::action('PollController@getEdit') . "/" . $poll->id))->with('message', Lang::get('admin.pollSaved'))->with('notif', 'success');
         } catch (Exception $e) {
             return Redirect::to(_l(URL::action('PollController@getIndex')))->with('message', Lang::get('admin.noSuchPoll'))->with('notif', 'danger');
         }
     }
 }
Ejemplo n.º 7
0
 public function getPollResults($id)
 {
     try {
         $this->googleAnalytics('/polls/poll-results/' . $id);
         $poll = Poll::findOrFail($id);
         $poll_options = PollOption::where('poll_id', '=', $id)->orderBy('vote_count', 'asc')->get();
         foreach ($poll_options as $key => $option) {
             $poll_options[$key]->title = __($option->title);
         }
         $total_votes = PollOPtion::where('poll_id', '=', $id)->sum('vote_count');
         $response = array("status" => 'success', "poll" => $poll, "poll_options" => $poll_options, "total_votes" => $total_votes, "totalvotes" => "Укупно " . $total_votes . " гласова");
         return Response::json($response);
     } catch (Exception $e) {
         return Response::json(array("status" => "success", "text" => __("Десила се грешка")));
     }
 }
Ejemplo n.º 8
0
 public function getResults()
 {
     $r = array('id' => $this->id, 'name' => $this->name, 'eligible_count' => $this->getEligibleVotersCount(), 'vote_count' => 0, 'turnout' => 0.0, 'options' => array());
     $options = PollOption::findByPollId($this->id);
     foreach ($options as $option) {
         $r['options'][$option->id] = array('id' => $option->id, 'name' => $option->name, 'vote_count' => 0);
         $votes = Vote::findByPollIdAndOptionId($this->id, $option->id);
         foreach ($votes as $vote) {
             ++$r['vote_count'];
             ++$r['options'][$option->id]['vote_count'];
         }
         $r['options'][$option->id]['percentage'] = $r['eligible_count'] > 0 ? round($r['options'][$option->id]['vote_count'] / $r['eligible_count'] * 100) : 0;
     }
     $r['turnout'] = $r['eligible_count'] > 0 ? round($r['vote_count'] / $r['eligible_count'] * 100) : 0;
     uasort($r['options'], "self::cmpVoteCount");
     return $r;
 }