Пример #1
0
 public static function show()
 {
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $bet = new Bet($_POST);
         if ($bet->getErrorCount() == 0) {
             //make sure authenticatedUser is set
             $authenticatedUser = array_key_exists('authenticatedUser', $_SESSION) ? $_SESSION['authenticatedUser'] : null;
             if (is_null($authenticatedUser)) {
                 $bet->setError('user', 'USER_NOT_AUTH');
                 BetView::show($bet);
                 return;
             }
             $hockname = $authenticatedUser->getHockName();
             $bet->setUser(strtolower($hockname));
             //game exists check
             $games = GameDB::getGamesBy('id', $bet->getGameID());
             if (empty($games)) {
                 $bet->setError('game', 'NO_GAMEID');
                 BetView::show($bet);
                 return;
             }
             //user already has a bet check
             $game = $games[0];
             $bets = BetDB::getBetsBy('game', $game->getID());
             if (!empty($bets)) {
                 foreach ($bets as $bet) {
                     if (strcmp($bet->getUser(), strtolower($hockname)) == 0) {
                         $bet->setError('game', 'BET_ALREADY');
                         BetView::show($bet);
                         return;
                     }
                 }
             }
             //pending check
             if ($game->getPending() != 1) {
                 $bet->setError('game', 'GAME_NOT_PENDING');
                 BetView::show($bet);
                 return;
             }
             //game time check
             $start = new DateTime($game->getStart());
             $diff = $start->diff($bet->getTime());
             if ($diff->m != 0 || $diff->d != 0 || $diff->h != 0 || $diff->i >= 5) {
                 $bet->setError('game', 'LATE_BET');
                 BetView::show($bet);
                 return;
             }
             //Should be ok to submit bet...
             $id = BetDB::addBet($bet);
             $bet->setBetID($id);
             BetView::show($bet);
             //SimpleEchoView::show($bet);
         } else {
             BetView::show($bet);
         }
     } else {
         // Initial link
         BetView::show(null);
     }
 }
Пример #2
0
 /**
  * Generate a list of bets to process
  */
 public function genBetsToProcess()
 {
     foreach ($this->betList as $betId) {
         $bet = new Bet($betId);
         $match = $this->d->getMatchById($bet->getMatchId());
         if ($match->getScoreId() != NULL) {
             // Referee ID is -1 as long as score etc is not added to match
             // Match was played, add bet to list of betsToProcess
             array_push($this->betsToProcess, $bet);
         }
     }
 }
Пример #3
0
 public static function run()
 {
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
         $bet = new Bet($_POST);
         if ($bet->getErrorCount() == 0) {
             SimpleEchoView::show($bet);
         } else {
             BetView::show($bet);
         }
     } else {
         // Initial link
         BetView::show(null);
     }
 }
Пример #4
0
 /**
  * Get all stats by user
  * @param int $user_id
  * @return mixed|bool
  */
 static function GetByUser($user_id)
 {
     $stats = new Stats();
     $stats->total_bets_placed = 0;
     $stats->total_bets_won = 0;
     $stats->total_bets_lost = 0;
     $stats->total_points_won = 0;
     $stats->total_points_lost = 0;
     $stats->avg_bet_value = 0;
     $bets = Bet::GetAll();
     $totals = [];
     foreach ($bets as $bet) {
         if ($user_id == $bet->user_id) {
             $stats->total_bets_placed++;
             if ($bet->result == 1) {
                 $stats->total_bets_won++;
                 $stats->total_points_won += $bet->points_total;
             }
             if ($bet->result == 0) {
                 $stats->total_bets_lost++;
                 $stats->total_points_lost += $bet->points_total;
             }
             $totals[] = $bet->points_total;
         }
     }
     $stats->avg_bet_value = mmmr($totals, 'median');
     $stats->wealth_gap = wealthGap();
     return $stats;
 }
Пример #5
0
 /**
  * Enregistre un nouveau paris
  *
  * @return Response
  */
 public function store()
 {
     $user = User::getUserWithToken($_GET['token']);
     $input = Input::all();
     $input['user_id'] = $user->id;
     $validator = Validator::make($input, Bet::$rules, BaseController::$messages);
     if ($validator->fails()) {
         return Response::json(array('success' => false, 'payload' => array(), 'error' => $this->errorsArraytoString($validator->messages())), 400);
     }
     //On vérifie si la date du match n'est pas dépassé
     if (new DateTime() > new DateTime(Game::find($input['game_id'])->date)) {
         return Response::json(array('success' => false, 'payload' => array(), 'error' => "Le date du match est dépassé !"), 400);
     }
     $bet = Bet::whereRaw('user_id = ? && game_id = ?', array($input['user_id'], $input['game_id']))->first();
     //Si un paris sur le même match pour cet utilisateur existe, erreur envoyée.
     if ($bet) {
         return Response::json(array('success' => false, 'payload' => array(), 'error' => "Un paris existe déjà sur ce match !"), 400);
     }
     //On vérifie si la somme misé est disponible
     if ($input['points'] > $user->points) {
         return Response::json(array('success' => false, 'payload' => array(), 'error' => "Vous avez miser plus de points que vous en avez !"), 400);
     }
     $game = Game::find($input['game_id']);
     //On vérifie si le winner est bien une équipe du match
     if ($input['winner_id'] != $game->team1_id && $input['winner_id'] != $game->team2_id) {
         return Response::json(array('success' => false, 'payload' => array(), 'error' => "Veuillez mettre une équipe du match !"), 400);
     }
     $bet = Bet::create($input);
     Transaction::addTransaction($input['user_id'], $bet->id, $input['points'], 'bet');
     return Response::json(array('success' => true, 'payload' => $bet->toArray(), 'message' => 'Pari enregistré (' . $bet->points . ' points) sur : ' . $game->team1->name . ' (' . $bet->team1_goals . ') - (' . $bet->team2_goals . ') ' . $game->team2->name));
 }
Пример #6
0
 public static function checkExpired()
 {
     $expired = Bet::available()->where('expires_at', '<=', date('Y-m-d H:i:s'))->whereNull('accepted_by_user_id')->lists('id');
     if (count($expired) > 0) {
         Bet::whereIn('id', $expired)->update(array('expired' => 1));
     }
     $finished = Bet::where('expires_at', '<=', date('Y-m-d H:i:s'))->whereNotNull('accepted_by_user_id')->where('winner_paid', 0)->get();
     foreach ($finished as $bet) {
         $bet->handleWinner();
     }
 }
Пример #7
0
 function hasVoted($userid = null)
 {
     if ($userid == null) {
         $userid = TwitterAuth::getUserId();
     }
     $bet = Bet::findOne('matchid = ? and userid = ?', array($this->matchid, $userid));
     if (!$bet) {
         return false;
     } else {
         return $bet->teamid;
     }
 }
Пример #8
0
 /**
  * Get all users
  * @return User[]|bool
  */
 static function GetAll()
 {
     $db = new DB();
     if ($users = $db->fetch("SELECT * FROM User ORDER BY points DESC", null, 'User')) {
         foreach ($users as &$user) {
             $user->getAvatars();
             $user->getBadges();
             $user->bets = Bet::GetByUser($user->id);
         }
         return $users;
     } else {
         return false;
     }
 }
Пример #9
0
 public function getBets()
 {
     if (!Auth::check()) {
         App::abort(404);
     }
     $bets = Auth::user()->bets()->lists('id');
     $cross_bets = Auth::user()->crossBets()->lists('id');
     if (count($bets) || count($cross_bets)) {
         $bets = Bet::whereIn('id', array_merge($bets, $cross_bets))->orderBy('expires_at', 'asc')->get();
     } else {
         $bets = array();
     }
     return View::make('users.bets', compact('bets'));
 }
Пример #10
0
 public function postDelete()
 {
     if (!Input::has('bet_id')) {
         return array('success' => false);
     }
     $bet_id = Input::get('bet_id');
     $bet = Bet::where('id', $bet_id)->where('created_by_user_id', Auth::user()->id)->first();
     if (is_null($bet)) {
         return array('success' => false);
     } else {
         if ($bet->canBeDeleted()) {
             $bet->deleted = 1;
             $bet->price_when_deleted = Bitcoin::toUSD();
             $bet->deleted_at = time();
             $bet->save();
             Auth::user()->addToBalance($bet->bet_amount);
             return array('success' => true);
         } else {
             return array('success' => false);
         }
     }
 }
Пример #11
0
 /**
  * Ajoute une transaction
  * Utilisé uniquement par le code
  *
  * @param $user_id
  * @param $bet_id
  * @param $value
  * @param $type
  * @return bool
  */
 public static function addTransaction($user_id, $bet_id, $value, $type)
 {
     if (in_array($type, array('gain', 'bet')) && Bet::find($bet_id)) {
         $transaction = new Transaction();
         $transaction->user_id = $user_id;
         $transaction->bet_id = $bet_id;
         $transaction->value = $value;
         $transaction->type = $type;
         $transaction->save();
         //On déduit/ajoute les point de la transaction
         $user = User::find($user_id);
         if ($transaction->type == "bet") {
             $user->points -= $transaction->value;
         } else {
             if ($transaction->type == "gain") {
                 $user->points += $transaction->value;
             }
         }
         $user->save();
     }
     return false;
 }
Пример #12
0
    /**
     * @return void
     */
    public function show()
    {
        $matches = Match::find('seasonid = ? and result != 0', [$this->season->seasonid]);
        $matches = Model::indexBy($matches, 'matchid');

        $teams = Model::indexBy(Team::find('1=1'), 'teamid');

        $matchWinner = [];

        foreach($matches as $match) {
            if ($this->season->weekIsPublished($match->week) && !$match->isDelayed()) {
                $matchWinner[$match->matchid] = $match->getWinner();
            }
        }

        $totalBets = [];
        $correctBets = [];

        $usernames = [];
        $avatars = Model::pluck(Avatar::find('1=1'), 'url', 'userid');

        foreach(Bet::find('1=1') as $bet) {
            if (isset($matchWinner[$bet->matchid])) {
                if ($bet->teamid && $matchWinner[$bet->matchid] == $bet->teamid) {
                    $correctBets[$bet->userid]++;
                }
                $totalBets[$bet->userid]++;
            }
            if ($bet->username) {
                $usernames[$bet->userid] = $bet->username;
            }
        }

        $tiebreakers = [];
        foreach(array_keys($correctBets) as $userid) {
            $tiebreakers[$userid] = [-$correctBets[$userid], $totalBets[$userid], strtolower($usernames[$userid])];
        }
        asort($tiebreakers);


        if (TwitterAuth::isLogged()) {
            $userid = TwitterAuth::getUserId();
            $userBets = Bet::find('userid = ? order by matchid desc', [$userid]);

            $userpos = array_search($userid, array_keys($tiebreakers));
            $userpos = ($userpos === FALSE) ? 0 : $userpos+1;

            ?>
            <div class="inblock" style="text-align: left; margin-right: 20px">
                <h2>Tus estadísticas</h2>
                <table>
                    <thead>
                    <tr>
                        <td>Puesto</td>
                        <td>Nombre</td>
                        <td>Aciertos</td>
                        <td>Fallos</td>
                    </tr>
                    </thead>
                    <tr>
                        <td><?= $userpos ?>º</td>
                        <td style="text-align: left">
                            <div class="inblock" style="vertical-align: middle">
                                <a href="http://twitter.com/<?=htmlentities($usernames[$userid])?>" target="_blank">
                                    <img src="<?= htmlentities($avatars[$userid]) ?>" style="width:40px; height:40px; border-radius: 20px">
                                </a>
                            </div>
                            <div class="inblock" style="vertical-align: middle">
                                <a href="http://twitter.com/<?=htmlentities($usernames[$userid])?>" target="_blank">
                                    <?= htmlentities($usernames[$userid]) ?>
                                    <? if (!isset($usernames[$userid])) echo "<i>$userid</i>"; ?>
                                </a>
                            </div>
                        </td>
                        <td><?= $correctBets[$userid] ?></td>
                        <td><?= $totalBets[$userid]-$correctBets[$userid] ?></td>
                    </tr>
                </table>

                <h2>Tus apuestas</h2>
                <table>
                    <thead>
                    <tr>
                        <td>Jornada</td>
                        <td>Enfrentamiento</td>
                        <td>Acierto</td>
                    </tr>
                    </thead>
                    <? foreach($userBets as $bet) {
                        if (!isset($matches[$bet->matchid])) continue;
                        /**
                         * @var $match Match
                         */
                        $match = $matches[$bet->matchid];
                        if (!$match->isPublished() || $match->isDelayed()) continue;

                        $team1 = $teams[$match->team1id];
                        $team2 = $teams[$match->team2id];

                        $success = $match->getWinner() == $bet->teamid;
                        ?>
                        <tr>
                            <td><?= $match->week ?></td>
                            <td>
                                <div class="inblock">
                                    <div class="teamimg64">
                                        <img src="/<?= $team1->getImageLink(64, 64) ?>" class="<?= $match->getWinner() == $team1->teamid ? '' : 'grayscale' ?>">
                                    </div>
                                    <? if ($bet->teamid == $team1->teamid) { ?>
                                        <br><i style="font-size:11px">Votado</i>
                                    <? } ?>
                                </div>

                                <div class="inblock" style="line-height: 64px; margin: 0px 4px">
                                    VS
                                </div>

                                <div class="inblock">
                                    <div class="teamimg64">
                                        <img src="/<?= $team2->getImageLink(64, 64) ?>" class="<?= $match->getWinner() == $team2->teamid ? '' : 'grayscale' ?>">
                                    </div>
                                    <? if ($bet->teamid == $team2->teamid) { ?>
                                        <br><i style="font-size:11px">Votado</i>
                                    <? } ?>
                                </div>
                            </td>
                            <td>
                                <?= $success
                                    ? '<div class="success-icon">&#x2714;</div>'
                                    : '<div class="fail-icon">&#x2718</div>' ?>
                            </td>

                        </tr>
                        <?
                    } ?>
                </table>
            </div>
            <?
        }


        ?>
        <div class="inblock">
            <h2>Clasificación</h2>
            <table>
                <thead>
                <tr>
                    <td>Puesto</td>
                    <td>Nombre</td>
                    <td>Aciertos</td>
                    <td>Fallos</td>
                </tr>
                </thead>

                <?
                $lastTiebreakers = null;
                $lastPos = 0;
                foreach(array_keys($tiebreakers) as $pos => $userid) {
                    unset($tiebreakers[$userid][2]);

                    if ($lastTiebreakers != $tiebreakers[$userid]) {
                        $lastPos = $pos;
                    }

                    if (!isset($avatars[$userid])) {
                        Avatar::setUsersAvatar($userid, $usernames[$userid]);
                    }
                    ?>
                    <tr>
                        <td><?= $lastPos+1 ?>º</td>
                        <td style="text-align: left">
                            <div class="inblock" style="vertical-align: middle">
                                <a href="http://twitter.com/<?=htmlentities($usernames[$userid])?>" target="_blank">
                                    <img src="<?= htmlentities($avatars[$userid]) ?>" style="width:40px; height:40px; border-radius: 20px">
                                </a>
                            </div>
                            <div class="inblock" style="vertical-align: middle">
                                <a href="http://twitter.com/<?=htmlentities($usernames[$userid])?>" target="_blank">
                                    <?= htmlentities($usernames[$userid]) ?>
                                    <? if (!isset($usernames[$userid])) echo "<i>$userid</i>"; ?>
                                </a>
                            </div>
                        </td>
                        <td><?= $correctBets[$userid] ?></td>
                        <td><?= $totalBets[$userid]-$correctBets[$userid] ?></td>
                    </tr>
                    <?
                    $lastTiebreakers = $tiebreakers[$userid];
                }
                ?>
            </table>
        </div>
        <?
    }
Пример #13
0
/* Get comments
 **********************************************************************************************************************/
$app->get('/matches/:id/comments', function ($id) use($app) {
    $match = Match::Get($id);
    $response = $match->getComments();
    $app->render_json($response);
});
/* Place bet
 **********************************************************************************************************************/
$app->post('/matches/:id/bet', function ($id) use($app) {
    $data = json_decode($app->request->getBody(), true);
    $type = $data['type'];
    $team = $data['team'];
    $user = User::GetByToken($app->request->headers->get('token'));
    // Create the bet
    $bet = new Bet();
    $bet->user_id = $user->id;
    $bet->match_id = $id;
    $bet->type = $type;
    $bet->team = $team;
    if ($type === 1) {
        $bet->points_simple = $data['points_simple'];
    } elseif ($type === 2) {
        $bet->points_goals = $data['points_goals'];
        $bet->points_yellowcards = $data['points_yellowcards'];
        $bet->points_redcards = $data['points_redcards'];
        $bet->points_defenses = $data['points_defenses'];
    }
    if ($bet_id = $bet->Create()) {
        $app->render_json(['id' => $bet_id]);
    } else {
Пример #14
0
 public function showCurrentBets()
 {
     // Get the current user
     $this->data['user'] = Confide::user();
     // Initialize the potential money that can be won as the current money the user has
     $this->data['potential_money'] = $this->data['user']->current_money;
     // Get all of the users outstanding bets
     $current_bets = Bet::where('user_id', '=', $this->data['user']->id)->where('final', false)->get();
     if ($current_bets) {
         $this->data['bet_objects'] = [];
         // Get all of the games
         $repo = App::make('GameRepository');
         $pending_games = $repo->getPendingGames('NFL', '4');
         foreach ($current_bets as $bet) {
             if (array_key_exists($bet->game_code, $pending_games)) {
                 // Get the game associated with the bet
                 $game = $pending_games[$bet->game_code];
                 $visiting_team = $game['visiting-team']['@attributes'];
                 $home_team = $game['home-team']['@attributes'];
                 if ($visiting_team['id'] === $bet->team) {
                     $picked_team = $visiting_team;
                     $opposing_team = $home_team;
                 } else {
                     $picked_team = $home_team;
                     $opposing_team = $visiting_team;
                 }
                 $bet_object = (object) [];
                 $bet_object->bet = $bet;
                 $bet_object->game = $game['gamestate']['@attributes'];
                 $bet_object->visiting_team = $visiting_team;
                 $bet_object->home_team = $home_team;
                 $bet_object->picked_team = $picked_team;
                 $bet_object->game_title = $visiting_team['display_name'] . ' ' . $visiting_team['nickname'] . ' at ' . $home_team['display_name'] . ' ' . $home_team['nickname'];
                 if ($bet->bet_type === 'pointspread') {
                     $adjusted_team_score = $picked_team['score'] + $bet->point_spread;
                 } else {
                     $adjusted_team_score = $picked_team['score'];
                 }
                 // If this is a current winning bet
                 if ($adjusted_team_score > $opposing_team['score']) {
                     // Payout will be the initial bet plus winnings
                     $payout = $bet->bet_amount + $bet->win_potential;
                     // If the game is over, record win and set bet to final
                     if ($bet_object->game['status'] === 'Final') {
                         $bet->won = true;
                         $bet->final = true;
                         $bet->save();
                         $this->data['user']->current_money += $payout;
                         $this->data['user']->save();
                     } else {
                         $bet_object->status = 'panel-success';
                         $this->data['potential_money'] += $payout;
                         $this->data['bet_objects'][] = $bet_object;
                     }
                 } else {
                     if ($adjusted_team_score === $opposing_team['score']) {
                         // Payout will be just the initial bet
                         $payout = $bet->bet_amount;
                         // If the game is over, record win and set bet to final
                         if ($bet_object->game['status'] === 'Final') {
                             $bet->won = true;
                             $bet->final = true;
                             $bet->save();
                             $this->data['user']->current_money += $payout;
                             $this->data['user']->save();
                         } else {
                             $bet_object->status = 'panel-warning';
                             // Payout will be just the initial bet
                             $this->data['potential_money'] += $payout;
                             $this->data['bet_objects'][] = $bet_object;
                         }
                     } else {
                         // If the game is over, set bet to final
                         if ($bet_object->game['status'] === 'Final') {
                             $bet->final = true;
                             $bet->save();
                         } else {
                             $bet_object->status = 'panel-danger';
                             $this->data['bet_objects'][] = $bet_object;
                         }
                     }
                 }
             }
         }
     }
     return View::make('bets', $this->data);
 }
Пример #15
0
    }
    $twig = Twig::get();
    $template = $twig->loadTemplate('managers-bets.html');
    echo $template->render(array());
});
$app->get('/managers/bets/request/', function () use($app) {
    // AUTHENTICATION FIRST
    if (!Sentry::check()) {
        // User is not logged in, or is not activated
        $app->status(401);
    }
    $user = Sentry::getUser();
    if (!$user->isSuperUser()) {
        $app->status(401);
    }
    $data = array();
    $counter = 0;
    $draws = Bet::orderBy('id', 'desc')->get()->toArray();
    foreach ($draws as $draw) {
        $data[$counter]['id'] = $draw['id'];
        $data[$counter]['draw_id'] = $draw['draw_id'];
        $data[$counter]['numbers'] = $draw['numbers'];
        $data[$counter]['ticket_number'] = $draw['ticket_number'];
        $data[$counter]['security_code'] = $draw['security_code'];
        $data[$counter]['lucky_pick'] = $draw['lucky_pick'];
        $data[$counter]['date'] = date("F j,Y H:i:s", strtotime($draw['created_at']));
        $counter++;
    }
    header("Content-Type:text/json");
    echo json_encode(array(array('per_page' => 25, 'total_entries' => count($data), 'total_pages' => ceil(count($data) / 25), 'page' => 1), $data), JSON_NUMERIC_CHECK);
});
Пример #16
0
    /**
     * @return void
     */
    public function show()
    {
        $week = $this->week;
        $canVote = $this->canVote;

        $publishTime = $this->season->getPublishTimeForWeek($week);

        if ($publishTime >= 1000) {

            $days = explode(',', 'Domingo,Lunes,Martes,Miércoles,Jueves,Viernes,Sábado');
            $months = explode(',', 'enero,febrero,marzo,abril,mayo,junio,julio,agosto,septiembre,octubre,noviembre,diciembre')

            ?>
            <div>
                <?= $days[date('w', $publishTime)] ?>
                <?= date('j', $publishTime)?> de <?= $months[date('m', $publishTime)-1] ?> de <?= date('Y', $publishTime) ?>,
                <?= date('H:i', $publishTime) ?> (hora española)
            </div>
        <? } ?>
        <div style="height: 6px"></div>
        <table style="border: 0; padding: 0; margin: 0; width: 100%">
            <tr>
                <td style="width: 150px; border: 0; padding: 0; margin: 0; text-align: left">
                    <?
                    if ($this->week > 1) {
                        ?>
                        <a style="float:left; margin-left: 24px" href="/<?=$this->season->getLink()?>/jornadas/<?=$this->week-1?>/">
                            &lt;&lt;
                            Ver <?= strtolower($this->season->getWeekName($this->week-1)) ?>
                        </a>
                        <?
                    }
                    ?>
                </td>
                <td style="border: 0; padding: 0; margin: 0; text-align: center">
                    <?
                    if (time() >= $publishTime) {
                        ?>
                        <a href="javascript:void(0)" onclick="$('._grayscale').toggleClass('grayscale'); $('.result').toggle(); $(this).find('span').toggle()">
                            <span>Mostrar resultados</span>
                            <span style="display: none">Ocultar resultados</span>
                        </a>
                        <?
                    }
                    ?>
                </td>
                <td style="width: 150px; border: 0; padding: 0; margin: 0; text-align: right"><?
                    if ($this->week < $this->maxWeek) {
                        ?>
                        <a style="float:right; margin-right: 24px" href="/<?=$this->season->getLink()?>/jornadas/<?=$this->week+1?>/">
                            Ver <?= strtolower($this->season->getWeekName($this->week+1)) ?>
                            &gt;&gt;
                        </a>
                        <?
                    }
                    ?>
                </td>
            </tr>
        </table>
        <?

        $matches = Match::find('seasonid = ? and week = ? order by matchid asc', [$this->season->seasonid, $week]);
        #shuffle($matches);

        if (!$matches) {
            ?>
            No hay enfrentamientos disponibles en estos momentos.<br><br>
            <?
            return;
        }

        foreach($matches as $match) {
            $team1 = $match->getTeam1();
            $team2 = $match->getTeam2();

            if (false && rand(0,1) == 1) {
                $tmp = $team2;
                $team2 = $team1;
                $team1 = $tmp;
            }


            $voteTeamid = HTMLResponse::fromPOST('teamid','') * 1;
            $voteMatchid = HTMLResponse::fromPOST('matchid','') * 1;
            $voteUnteamid = HTMLResponse::fromPOST('unteamid','') * 1;
            $voteUnmatchid = HTMLResponse::fromPOST('unmatchid','') * 1;

            if ($canVote && TwitterAuth::isLogged() && !$match->hasVoted() && $match->matchid &&
                $voteMatchid == $match->matchid && ($voteTeamid == $team1->teamid || $voteTeamid == $team2->teamid)) {
                $bet = Bet::create();
                $bet->matchid = $match->matchid;
                $bet->dateline = time();
                $bet->userid = TwitterAuth::getUserId();
                $bet->teamid = $voteTeamid;
                $bet->username = TwitterAuth::getUserName();
                $bet->avatar = $_SESSION['twitter-avatar'];
                $bet->save();
            }

            if ($canVote && TwitterAuth::isLogged() && $match->hasVoted() &&
                $voteUnmatchid == $match->matchid && ($voteUnteamid == $team1->teamid || $voteUnteamid == $team2->teamid)) {
                $bet = Bet::findOne('matchid = ? and teamid = ? and userid = ?', array($voteUnmatchid, $voteUnteamid, TwitterAuth::getUserId()));
                $bet->delete();
            }

            $votes = $match->getVotes();
            $votesCount = array_sum($votes);

            $team1votes = 0;
            $team2votes = 0;
            if ($votesCount != 0) {
                $team1votes = $votes[$team1->teamid]*1;
                $team2votes = $votes[$team2->teamid]*1;
            }

            ?>

            <div class="matchbox">
                <? $this->showTeamBox($match, $team1, $team1votes, $votesCount) ?>
                <div class="vsbox">
                    <? if ($match->isPublished() && $match->getWinner()) {
                        $score1 = $team1->teamid==$match->getWinner() ? 6-$match->getLooserKills() : 0;
                        $score2 = $team2->teamid==$match->getWinner() ? 6-$match->getLooserKills() : 0;
                        ?>
                        <div style="font-size:90%; display: none" class="result">
                            <?=$score1?>-<?=$score2?>
                        </div>
                        <?
                    } else if ($match->isPublished() && $match->isDelayed()) { ?>
                        <div style="font-size:90%; display: none" class="result">
                            Apl.
                        </div>
                    <? } ?>
                    VS
                </div>
                <? $this->showTeamBox($match, $team2, $team2votes, $votesCount) ?>
            </div>
            <?
        }
    }
Пример #17
0
 // VALIDATE UNIQUE
 $numbers = array();
 foreach ($_POST['bet'] as $bet) {
     if (!in_array($bet, $numbers)) {
         $numbers[] = trim(intval($bet));
     }
 }
 if (count($_POST['bet']) != 6 && count($numbers) != 6) {
     $app->flash('error', 'Sorry you have to select atleast 6 numbers');
     $app->redirect('/bet');
 }
 $last = Bet::orderBy("id", "desc")->first();
 $additional_number = is_object($last) ? $last->id + 1 : 0;
 // FIND THE DRAW
 $todays_draw = $draw->first();
 $bet = new Bet();
 $bet->draw_id = $todays_draw->id;
 $bet->numbers = implode(",", $numbers);
 $bet->ticket_number = date("Ymd") . $additional_number;
 $bet->security_code = md5(date("YmdHis"));
 if (isset($_POST['lucky_pick'])) {
     $bet->lucky_pick = 1;
 } else {
     $bet->lucky_pick = 0;
 }
 $bet->save();
 $ticket = array();
 $ticket['draw_id'] = $bet->draw_id;
 $ticket['numbers'] = $bet->numbers;
 $ticket['ticket_number'] = $bet->ticket_number;
 $ticket['security_code'] = $bet->security_code;
Пример #18
0
Файл: Bet.php Проект: xJakub/LCE
<?php

/**
 * Created by PhpStorm.
 * User: Jakub
 * Date: 30/10/2015
 * Time: 20:04
 */
class Bet extends Model
{
    public $betid;
    public $matchid;
    public $teamid;
    public $dateline;
    public $userid;
    public $username;
    public $avatar;
}
Bet::init('bets', 'betid');
Пример #19
0
<?php

/*
 * CRON SCRIPT: Simulate Bets
 * Runs every 30 minutes
 */
chdir(dirname(__FILE__));
require '../config.php';
$matches = Match::GetAll();
// Get the users accounts that represent the automated bots
$users = $db->fetch("SELECT * FROM User WHERE id IN (42, 43, 44, 28)", null, 'User');
foreach ($users as $user) {
    foreach ($matches as $match) {
        if (strtotime($match->start_time) > strtotime('now')) {
            // Filter by upcoming matches only
            // Setup the bet
            $bet = new Bet();
            $bet->user_id = $user->id;
            $bet->match_id = $match->id;
            $bet->type = 1;
            $bet->team = mt_rand(0, 2);
            $bet_amount = mt_rand(10, $user->points / 100) / 10 * 10;
            // Random bet amount up to a tenth of the user's balance
            $bet->points_simple = $bet_amount;
            // Create the bet
            $bet->Create();
        }
    }
}
Пример #20
0
                <tr>
                    <th>Made by</th>
                    <th>Team 1</th>
                    <th>Score</th>
                    <th>Team 2</th>
                    <th>Player that makes first goal</th>
                    <th># Red Cards</th>
                    <th># Yellow Cards</th>
                    <th>Amount</th>
                </tr>
                </thead>
                <tbody>
                    <?php 
        $bets = $this->getGroup()->getHandledbets();
        foreach ($bets as $betId) {
            $bet = new Bet($betId);
            ?>
                        <tr>
                        <td><?php 
            echo $bet->getUserName();
            ?>
</td>
                        <?php 
            echo $bet->dataAsColouredString();
            ?>
                        </tr>
                    <?php 
        }
        ?>
                    </tbody>
                </table>
Пример #21
0
 public function setFinished($num_team)
 {
     //Si l'équipe une a gagnée, on redistribue les points pour les paris corrects (paris sur l'équipe une)
     if ($num_team == 1) {
         foreach (Bet::whereRaw('game_id = ? && winner_id = ?', array($this->id, $this->team1_id))->get() as $bet) {
             $cote = $this->getTeam1CoteAttribute();
             $points = $bet->points * $cote;
             if ($this->team1_goals == $bet->team1_goals && $this->team2_goals == $bet->team2_goals) {
                 $points += $bet->points / 10 * $cote;
             }
             Transaction::addTransaction($bet->user_id, $bet->id, $points, 'gain');
         }
         $this->winner_id = $this->team1_id;
         //Si l'équipe deux a gagnée, on redistribue les points pour les paris corrects (paris sur l'équipe deux)
     } else {
         foreach (Bet::whereRaw('game_id = ? && winner_id = ?', array($this->id, $this->team2_id))->get() as $bet) {
             $cote = $this->getTeam2CoteAttribute();
             $points = $bet->points * $cote;
             if ($this->team1_goals == $bet->team1_goals && $this->team2_goals == $bet->team2_goals) {
                 $points += $bet->points / 10 * $cote;
             }
             Transaction::addTransaction($bet->user_id, $bet->id, $points, 'gain');
         }
         $this->winner_id = $this->team2_id;
     }
     /////////////////////////////////////////////////
     //******************* ROUND X *****************//
     /////////////////////////////////////////////////
     //On inscrit l'équipe gagnante dans son prochain match
     $id = $this->stage()->first()->next_stage()->first()->id;
     $num_game = round($this->stage_game_num / 2);
     $game = Game::whereRaw("stage_id = ? && stage_game_num = ?", array($id, $num_game))->first();
     if ($this->stage_game_num % 2 == 1) {
         $game->team1_id = $this->winner_id;
     } else {
         $game->team2_id = $this->winner_id;
     }
     $game->save();
     /////////////////////////////////////////////////
     //******************* 3e place ****************//
     /////////////////////////////////////////////////
     //Si on est lors des demi, on va définir aussi la 3e finale
     if ($this->stage()->first()->next_stage()->first()->next_stage == null) {
         $stage_third = Stage::getThirdStage()->id;
         $gamme_third = Game::whereRaw('stage_id = ?', array($stage_third))->first();
         //Si équipe 1 a gagné on met l'équipe 2 en 3e place
         if ($num_game == 1) {
             if ($this->stage_game_num % 2 == 1) {
                 $gamme_third->team1_id = $this->team1_id;
             } else {
                 $gamme_third->team2_id = $this->team1_id;
             }
         } else {
             if ($this->stage_game_num % 2 == 1) {
                 $gamme_third->team1_id = $this->team2_id;
             } else {
                 $gamme_third->team2_id = $this->team2_id;
             }
         }
         $gamme_third->save();
     }
     $this->save();
 }
Пример #22
0
 $draw_id = $draw->id;
 $draw_winning_price = $draw->winning_price;
 // GENERATE RANDOM NUMBERS FROM 1-42
 $range = range(1, 42);
 shuffle($range);
 $num = 6;
 $r = array();
 for ($i = 0; $i < $num; $i++) {
     $r[] = $range[$i];
 }
 $shuffled = $num == 1 ? $r[0] : $r;
 sort($shuffled, SORT_NUMERIC);
 // SAVE THE WINNING NUMBER TO DATABASE
 $draw = Draw::where("date", "=", $date)->update(array('numbers' => implode(",", $shuffled), 'status' => 'closed'));
 // FIND WINNERS
 $bets = Bet::where("draw_id", "=", $draw_id)->where("numbers", "=", implode(",", $shuffled));
 // GET NUMBER OF WINNERS AND DIVIDED IT
 $price = $draw_winning_price / $bets->count();
 // WINNERS
 $winners = $bets->get();
 // SAVE WINNERS TO DATABASE
 foreach ($winners as $winner) {
     $w = new Winner();
     $w->draw_id = $draw_id;
     $w->winning_numbers = implode(",", $shuffled);
     $w->winning_price = $price;
     $w->ticket_number = $winner->ticket_number;
     $w->security_code = $winner->security_code;
     $w->draw_date = $date;
     $w->save();
     echo "Winner Saved";
Пример #23
0
$matches = Match::GetAll();
foreach ($matches as $match) {
    if (strtotime($match->end_time) < strtotime('now')) {
        $team1_id = $match->progress[0]['team_id'];
        $team1_goals = $match->progress[0]['goals'];
        $team1_yellow_cards = $match->progress[0]['yellow_cards'];
        $team1_redcards = $match->progress[0]['redcards'];
        $team1_defenses = $match->progress[0]['defenses'];
        $team2_id = $match->progress[1]['team_id'];
        $team2_goals = $match->progress[1]['goals'];
        $team2_yellow_cards = $match->progress[1]['yellow_cards'];
        $team2_redcards = $match->progress[1]['redcards'];
        $team2_defenses = $match->progress[1]['defenses'];
        $team1_rank = 0;
        $team2_rank = 0;
        if ($bets = Bet::GetByMatch($match->id)) {
            foreach ($bets as $bet) {
                if ($bet->result == null) {
                    $user = User::Get($bet->user_id);
                    $result = null;
                    // Simple bet
                    if ($bet->type == 1) {
                        if ($team1_goals > $team2_goals) {
                            $result = 1;
                            $team1_rank += $bet->points_total;
                            $team2_rank -= $bet->points_total;
                        } elseif ($team1_goals == $team2_goals) {
                            $result = 0;
                        } elseif ($team1_goals > $team2_goals) {
                            $result = 2;
                            $team2_rank += $bet->points_total;
Пример #24
0
    </table>

    <h2>Bets - History</h2>
    <table class="table table-striped">
        <tr>
            <th>Team 1</th>
            <th>Score</th>
            <th>Team 2</th>
            <th>Player that makes first goal</th>
            <th># Red Cards</th>
            <th># Yellow Cards</th>
            <th>Amount</th>
        </tr>
    <?php 
    $bets = $this->getHandledBets();
    foreach ($bets as $betId) {
        $bet = new Bet($betId);
        ?>
        <tr>
            <?php 
        echo $bet->dataAsColouredString();
        ?>
        </tr>
    <?php 
    }
}
?>
    </table>
</div>

Пример #25
0
 public static function getBetsArray($rowSets)
 {
     // Returns an array of bet objects extracted from $rowSets
     $bets = array();
     if (!empty($rowSets)) {
         foreach ($rowSets as $betRow) {
             $bet = new Bet($betRow);
             $bet->setBetID($betRow['id']);
             array_push($bets, $bet);
         }
     }
     return $bets;
 }
Пример #26
0
}
?>

<h2>It should extract the parameters that went in</h2>
<?php 
$props = $s1->getParameters();
print_r($props);
?>

<h2>It should not allow a bet more than 10</h2>
<?php 
$validTest = array("game" => "123123", "betAmount" => "11");
$s1 = new Bet($validTest);
echo "{$s1}<br>";
$test2 = empty($s1->getErrors()) ? '' : 'Failed: It should have errors when invalid input is provided<br>';
echo $test2;
if ($test2 != "") {
    echo implode("|", $s1->getErrors());
}
?>

<h2>It should not allow a bet less than 1</h2>
<?php 
$validTest = array("game" => "123123", "betAmount" => "-1");
$s1 = new Bet($validTest);
echo "{$s1}<br>";
$test2 = empty($s1->getErrors()) ? '' : 'Failed: It should have errors when invalid input is provided<br>';
echo $test2;
if ($test2 != "") {
    echo implode("|", $s1->getErrors());
}
Пример #27
0
    if ($request->getMethod() === 'POST') {
        Route::callRouteFilter('custom_csrf', array(), '', $request);
    }
});
$btc_price = Bitcoin::toUSD();
View::share('btc_price', $btc_price);
$updated_at = strtotime(DB::table('price_hist')->orderBy('id', 'desc')->pluck('created_at'));
View::share('updated_at', $updated_at);
Bet::checkExpired();
Route::get('logout', function () {
    Auth::logout();
    return Redirect::to('/');
});
Route::get('/', function () {
    $prices = DB::table('price_hist')->get();
    $bets = Bet::available()->paginate(4);
    $server_time = date('H:i:s');
    return View::make('hello', compact('server_time', 'bets', 'prices'));
});
Route::post('/contact/submit', function () {
    $data = array('from' => Input::get('email'), 'body' => Input::get('message'));
    Mail::queue('emails.contact', $data, function ($message) {
        $message->to('*****@*****.**', 'Connor Smith')->subject('BinaryBTC Contact Form');
    });
    return array();
});
Route::get('/faq', function () {
    return View::make('faq');
});
Route::get('/latest_price', function () {
    if (!Request::ajax()) {