Find games associated to a mission and add the last entry of the user if it exists
@param unknown $mission
@return multitype:NULL
430970
public function getMissionGames($mission, $user)
    {
        $games = array();
        $missionGames = $this->findGamesByMission($mission);
        foreach ($missionGames as $missionGame) {
            $entry = $this->checkExistingEntry($missionGame->getGame(), $user);
            $games[$missionGame->getGame()->getIdentifier()]['game'] = $missionGame;
            $games[$missionGame->getGame()->getIdentifier()]['entry'] = $entry;
        }
    
        return $games;
    }
8417
public function query($query, $map = [])
    {
        $statement = parent::exec($query, $map);
        $lastSQL = parent::last();
        Container::get('logger')->info($lastSQL);
        array_push(self::$queries, $lastSQL);
        return $statement;
    }
1285113
@Override
    public void prepare(MissionInit missionInit)
    {
        super.prepare(missionInit);
        MinecraftForge.EVENT_BUS.register(this);
        MalmoMod.MalmoMessageHandler.registerForMessage(this, MalmoMessageType.SERVER_BUILDBATTLEREWARD);

        if (this.rscparams.getAddQuitProducer() != null)
        {
            // In order to trigger the end of the mission, we need to hook into the quit handlers.
            MissionBehaviour mb = parentBehaviour();
            final String quitDescription = this.rscparams.getAddQuitProducer().getDescription();
            mb.addQuitProducer(new IWantToQuit()
            {
                @Override
                public void prepare(MissionInit missionInit)
                {
                }
    
                @Override
                public String getOutcome()
                {
                    return quitDescription;
                }
    
                @Override
                public boolean doIWantToQuit(MissionInit missionInit)
                {
                    return RewardForStructureCopyingImplementation.this.structureHasBeenCompleted;
                }
    
                @Override
                public void cleanup()
                {
                }
            });
        }
    }
427177
public function getMissionMapper()
    {
        if (null === $this->missionMapper) {
            $this->missionMapper = $this->serviceLocator->get('playgroundgame_mission_mapper');
        }

        return $this->missionMapper;
    }
886021
public function getGameEntries($header, $entries, $game)
    {
        $results = array();

        foreach ($entries as $k => $entry) {
            $entryData = json_decode($entry['playerData'], true);
            $winner = $entry['winner'];

            foreach ($header as $key => $v) {
                if (isset($entryData[$key]) && $key !=='id') {
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
                } elseif (array_key_exists($key, $entry)) {
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?
                        $entry[$key]->format('Y-m-d'):
                        $entry[$key];
                } else {
                    $results[$k][$key] = '';
                }
            }
            // If the occurrenceType is code, this will be triggered for every entry. To be improved.
            if ($game->getOccurrenceType() === 'code' || ($game->getOccurrenceType() === 'datetime' && $winner)) {
                $entry = $this->getEntryMapper()->findById($entry['id']);
                $occurrence = $this->getInstantWinOccurrenceMapper()->findByEntry($entry);
                if ($occurrence !== null) {
                    $results[$k]['value'] = $occurrence->getValue();
                    if ($occurrence->getPrize()) {
                        $results[$k]['prize'] = $occurrence->getPrize()->getTitle();
                    }
                }
            }
        }

        return $results;
    }
246133
public function getAvailableGames($user, $maxResults = 2)
    {
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
        $today = new \DateTime("now");
        $today = $today->format('Y-m-d H:i:s');

        // Game active with a start_date before today (or without start_date)
        // and end_date after today (or without end-date)
        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
                WHERE NOT EXISTS (SELECT l FROM PlaygroundGame\Entity\Entry l WHERE l.game = g AND l.user = :user)
                AND (g.startDate <= :date OR g.startDate IS NULL)
                AND (g.endDate >= :date OR g.endDate IS NULL)
                AND g.active = 1 AND g.broadcastPlatform = 1
                ORDER BY g.startDate ASC');
        $query->setParameter('date', $today);
        $query->setParameter('user', $user);
        $query->setMaxResults($maxResults);
        $games = $query->getResult();

        return $games;
    }
909655
public function create($campaign)
    {
        if (is_array($campaign)) {
            $campaign["campaign_type"] = "PROMOTION";
        }
        elseif (is_object($campaign)) {
            $campaign->campaign_type = "PROMOTION";
        }

        return $this->campaigns->create($campaign);
    }
779404
public function checkDateOccurrenceByGameId($instant_win)
    {
        $now = new \DateTime("now");
        $now = $now->format('Y-m-d H:i:s');

        $query = $this->em->createQuery(
            'SELECT i FROM PlaygroundGame\Entity\InstantWinOccurrence i
                WHERE i.instantwin = :game
                AND i.active = 1
                AND i.value <= :now
                ORDER BY i.value DESC
                '
        );
        $query->setParameter('game', $instant_win);
        $query->setParameter('now', $now);
        $query->setMaxResults(1);
        $result = $query->getResult();

        if (count($result) == 1) {
            return current($result);
        } else {
            return null;
        }
    }
589342
public function getLastAction(Campaign $campaign)
    {
        $lastAction = $this->getEdgeAction($campaign, 'last');

        // If there is a last action, make sure it does not equal the first action.
        if($lastAction){
            $firstAction = $this->getFirstAction($campaign);

            if($lastAction->getId() == $firstAction->getId()){
                return null;
            } else {
                return $lastAction;
            }
        }
    }
851581
public function play($game, $user, &$error = null)
    {
        //some entries can stay open during days.
        // The player can take back the entry to go on playing
        // like in a postvote or for quizzes
        // We create also an entry before the game when an optin is needed
        $entry = $this->checkExistingEntry($game, $user, true);

        // If the game needs an optin and the player has not opted in
        if ($entry && $game->getTermsOptin() && !$entry->getTermsOptin()) {
            $error = -2;
            return false;
        }

        // If the game has a cost and the player has not paid yet
        // (this case occurs when the entry has been created by the termsOptin
        // and the game has a price to play)
        if ($entry && !$entry->getPaid() && $game->getCostToPlay() > 0) {
            if (!$this->payToPlay($game, $user, $entry)) {
                $error = -3;
                return false;
            } else {
                $entry->setPaid(1);
                $entry->setPaidAmount($game->getCostToPlay());
                $entry = $this->getEntryMapper()->update($entry);
            }
        }

        if (! $entry) {
            // Play limit reached
            if ($this->hasReachedPlayLimit($game, $user)) {
                $error = -1;
                return false;
            }
            // Can't pay for the game
            if (!$this->canPayToPlay($game, $user)) {
                $error = -3;
                return false;
            }
            // Terms optin not checked
            if ($game->getTermsOptin()) {
                $error = -2;
                return false;
            }

            $ip = $this->getIp();
            $geoloc = $this->getGeoloc($ip);
            $entry = new Entry();
            $entry->setGame($game);
            $entry->setUser($user);
            $entry->setPoints(0);
            $entry->setIp($ip);
            $entry->setGeoloc($geoloc);
            $entry->setAnonymousId($this->getAnonymousId());
            
            if ($this->getAnonymousIdentifier()) {
                $entry->setAnonymousIdentifier($this->getAnonymousIdentifier());
            }
            if ($game->getCostToPlay() === 0) {
                $entry->setPaid(true);
                $entry = $this->getEntryMapper()->insert($entry);
                $this->getEventManager()->trigger(
                    __FUNCTION__ . '.post',
                    $this,
                    [
                        'user' => $user,
                        'game' => $game,
                        'entry' => $entry,
                    ]
                );
            } else {
                $entry = $this->getEntryMapper()->insert($entry);
                $entryPaid = $this->payToPlay($game, $user, $entry);
                if ($entryPaid) {
                    $entry = $this->getEntryMapper()->update($entryPaid);
                    $this->getEventManager()->trigger(
                        __FUNCTION__ . '.post',
                        $this,
                        [
                            'user' => $user,
                            'game' => $game,
                            'entry' => $entry,
                        ]
                    );
                } else {
                    $entry->setActive(false);
                    $entry = $this->getEntryMapper()->update($entry);
                    $error = -3;
                    return false;
                }
            }
        }

        return $entry;
    }
318796
public function getLastChunkInfo($region, $gameId, $currentChunkId, &$keyframeId = null)
    {
        $metas = $this->getMetas($region, $gameId);

        // Game loading information
        //$firstChunkId = $replayManager->findFirstChunkId($metas);
        $firstChunkId = $metas['firstChunkId'];

        // A bug appears when endStartupChunkId = 3 and startGameChunkId = 5, the game won't load
        if ($metas['endStartupChunkId'] + 2 == $firstChunkId) {
            $firstChunkId = $metas['startGameChunkId'] + 2;
        }

        $keyframeId = $this->findKeyframeByChunkId($metas, $firstChunkId);

        $lastChunkInfo = array(
            'chunkId'            => $firstChunkId,
            'availableSince'     => 30000,
            'nextAvailableChunk' => 30000,
            'keyFrameId'         => $keyframeId,
            'nextChunkId'        => $firstChunkId,
            'endStartupChunkId'  => $metas['endStartupChunkId'],
            'startGameChunkId'   => $metas['startGameChunkId'],
            'endGameChunkId'     => 0,
            'duration'           => 30000
        );

        // In game information
        if ($firstChunkId != $metas['startGameChunkId'] && $currentChunkId - 1 == $metas['startGameChunkId']) {
            $currentChunkId = $firstChunkId;
        }

        if ($currentChunkId > $metas['startGameChunkId']) {
            if ($currentChunkId > $metas['lastChunkId']) {
                $currentChunkId = $metas['lastChunkId'];
            } elseif ($currentChunkId < $metas['firstChunkId']) {
                $currentChunkId = $metas['firstChunkId'];
            }

            $keyframeId = $this->findKeyframeByChunkId($metas, $currentChunkId);

            $lastChunkInfo['chunkId']            = $currentChunkId;
            $lastChunkInfo['nextChunkId']        = $metas['lastChunkId'];
            $lastChunkInfo['keyFrameId']         = $keyframeId;
            $lastChunkInfo['nextAvailableChunk'] = $currentChunkId == $firstChunkId + 6 ? 30000 : 100; // wait for full loading
        }

        // End game, stop downloading
        if ($currentChunkId == $metas['lastChunkId']) {
            $lastChunkInfo['nextAvailableChunk'] = 90000;
            $lastChunkInfo['endGameChunkId']     = $metas['endGameChunkId'];
        }

        return $lastChunkInfo;
    }
347291
public function getTransaction( $transaction = self::TRANSACTION_LAST_USED, $throwExceptionIfNotFound = true )
    {

        if( $transaction === self::TRANSACTIONS_ALL ) {
            return array_keys( $this->queue );
        }

        if( $transaction === self::TRANSACTION_LAST_CREATED ) {
            if( !$this->queue) {
                $this->newTransaction();
            }
            $queue = array_keys( $this->queue );
            return array_pop( $queue );
        }

        if( $transaction === self::TRANSACTION_LAST_USED ) {
            if( !$this->queue) {
                $this->newTransaction();
            }
            return $this->lastTransaction;
        }

        if( $transaction === self::TRANSACTION_NEW ) {
            return $this->newTransaction();
        }

        if( !array_key_exists( $transaction, $this->queue ) ) {
            if( $throwExceptionIfNotFound ) {
                throw new TransactionDoesNotExistException(
                    "Transaction with this name `{$transaction}` doesn't exist. Sorry."
                );
            }
            return null;
        }

        return $transaction;

    }
1103906
protected function getMatch($index)
    {

        return isset($this->lastMatches[$index]) ? $this->lastMatches[$index] : null;
    }
315541
public function game() : ?Game
    {
        if (!isset($this->info()->titleId)) return null;

        return new Game($this->client, $this->info()->titleId);
    }
836353
public function update($time = null)
    {
        if (!$this->currentVote || $this->currentVote->getStatus() == Vote::STATUS_CANCEL) {
            return;
        }

        if (is_null($time)) {
            $time = time();
        }

        $playerCount = count($this->playerStorage->getOnline());

        // Check if vote passes when we suppose that all palyers that didn't vote would vote NO.
        if ($playerCount > 0 && ($this->currentVote->getYes() / $playerCount) > $this->ratio) {
            $this->votePassed();
            return;
        }

        // If the vote is still not decided wait for the end to decide.
        if (($time - $this->currentVote->getStartTime()) > $this->duration) {
            $totalVotes = $this->currentVote->getYes() + $this->currentVote->getNo() * 1.0;

            if ($totalVotes >= 1 && ($this->currentVote->getYes() / $totalVotes) > $this->ratio) {
                $this->votePassed();
            } else {
                $this->voteFailed();
            }
        }
    }
1255569
public function getGameEntries($header, $entries, $game)
    {
        $results = array();

        foreach ($entries as $k => $entry) {
            $entryData = json_decode($entry['playerData'], true);
            $postElements = $entry[0]->getPostElements();

            foreach ($header as $key => $v) {
                if (isset($entryData[$key]) && $key !=='id') {
                    $results[$k][$key] = (is_array($entryData[$key]))?implode(', ', $entryData[$key]):$entryData[$key];
                } elseif (array_key_exists($key, $entry)) {
                    $results[$k][$key] = ($entry[$key] instanceof \DateTime)?$entry[$key]->format('Y-m-d'):$entry[$key];
                } else {
                    $results[$k][$key] = '';
                }

                foreach ($postElements as $e) {
                    if ($key === $e->getName()) {
                        $results[$k][$key] = (is_array($e->getValue()))?implode(', ', $e->getValue()):$e->getValue();
                        break;
                    }
                }
            }
        }

        return $results;
    }
1325028
public function fulfillConditions($entry = null)
    {
        foreach ($this->getConditions() as $condition) {
            if ($condition->getAttribute() == MissionGameCondition::NONE) {
                continue;
            }
    
            // On passe au suivant si on a gagné
            if ($condition->getAttribute() == MissionGameCondition::VICTORY) {
                if (!$entry || !$entry->getWinner()) {
                    return false;
                }
            }
    
            // On passe au suivant si on a perdu
            if ($condition->getAttribute() == MissionGameCondition::DEFEAT) {
                if (!$entry || $entry->getWinner()) {
                    return false;
                }
            }
    
            // On passe au suivant si on a plus de n points
            if ($condition->getAttribute() == MissionGameCondition::GREATER) {
                if (!$entry || !($entry->getPoints() >= $condition->getValue())) {
                    return false;
                }
            }
    
            // On passe au suivant si on a moins de n points
            if ($condition->getAttribute() == MissionGameCondition::LESS) {
                if (!$entry || !($entry->getPoints() < $condition->getValue())) {
                    return false;
                }
            }
        }

        return true;
    }