@param string $region
@param int    $gameId

@return string
352294
protected function getReplayDirPath($region, $gameId)
    {
        $stringGameId = (string) $gameId;

        return sprintf(
            '%s/%s/%s/%s/%s/%s',
            $this->replaysDirPath,
            $region,
            $stringGameId[0] . $stringGameId[1],
            $stringGameId[2],
            $stringGameId[3],
            $gameId
        );
    }
36592
protected function init(PlayerId $playerId, MiniGameId $gameId, $name)
    {
        $this->playerId = $playerId;
        $this->gameId = $gameId;
        $this->name = $name;
    }
1169388
private function getUrl($region)
    {
        if (!isset($this->servers[$region])) {
            $availableRegions = '';

            foreach ($this->servers as $key => $item) {
                $availableRegions .= $key . ', ';
            }

            $availableRegions = substr($availableRegions, 0, -2);

            throw new UnknownRegionException(
                'The region "' . $region . '" is unknown. Available regions : ' . $availableRegions
            );
        }

        return $this->servers[$region] . self::URL_PREFIX;
    }
255432
public static RegionOperationId of(RegionId regionId, String operation) {
    return new RegionOperationId(regionId.getProject(), regionId.getRegion(), operation);
  }
1248432
public function getRegion($region)
    {
        $session = $this->getSession();
        $regionObj = $session->getPage()->find('region', $region);
        if (!$regionObj) {
            throw new \Exception(sprintf('No region "%s" found on the page %s.', $region, $session->getCurrentUrl()));
        }

        return $regionObj;
    }
872529
public function fetch_achievements($gamertag, $gameid, $region)
    {
        $gamertag = trim($gamertag);
        $url      = 'https://live.xbox.com/' . $region . '/Activity/Details?titleId=' . urlencode($gameid) . '&compareTo=' . urlencode($gamertag);
        $key      = $this->version . ':achievements.' . $gamertag . '.' . $gameid;

        $data = $this->__cache->fetch($key);
        if (!$data) {
            $data      = $this->fetch_url($url);
            $freshness = 'new';
            $this->__cache->store($key, $data, 3600);
        } else {
            $freshness = 'from cache';
        }

        $json = $this->find($data, 'broker.publish(routes.activity.details.load, ', ');');
        $json = json_decode($json, true);

        if (!empty($json)) {
            $achievements                           = array();
            $achievements['gamertag']               = $g = $json['Players'][0]['Gamertag'];
            $achievements['game']                   = $this->clean($json['Game']['Name']);
            $achievements['id']                     = $json['Game']['Id'];
            $achievements['hid']                    = dechex($json['Game']['Id']);
            $achievements['gamerscore']['current']  = $json['Game']['Progress'][$g]['Score'];
            $achievements['gamerscore']['total']    = $json['Game']['PossibleScore'];
            $achievements['achievement']['current'] = $json['Game']['Progress'][$g]['Achievements'];
            $achievements['achievement']['total']   = $json['Game']['PossibleAchievements'];
            $achievements['progress']               = $json['Players'][0]['PercentComplete'];
            $achievements['lastplayed']             = (int)substr($json['Game']['Progress'][$g]['LastPlayed'], 6, 10);

            $i = 0;
            foreach ($json['Achievements'] as $achievement) {
                $achievements['achievements'][$i]['id']                  = $achievement['Id'];
                $achievements['achievements'][$i]['title']               = '';
                $achievements['achievements'][$i]['artwork']['locked']   = 'https://live.xbox.com/Content/Images/HiddenAchievement.png';
                $achievements['achievements'][$i]['artwork']['unlocked'] = 'https://live.xbox.com/Content/Images/HiddenAchievement.png';
                $achievements['achievements'][$i]['title']               = 'Secret Achievement';
                $achievements['achievements'][$i]['description']         = 'This is a secret achievement. Unlock it to find out more.';
                $achievements['achievements'][$i]['gamerscore']          = 0;
                $achievements['achievements'][$i]['secret']              = (bool)$achievement['IsHidden'];
                $achievements['achievements'][$i]['unlocked']            = false;
                $achievements['achievements'][$i]['unlockdate']          = null;
                $achievements['achievements'][$i]['unlockedoffline']     = null;

                if (!$achievement['IsHidden']) {
                    // find colored achievement tile
                    // get image name. removes url and extension
                    $ach_info  = pathinfo($achievement['TileUrl']);
                    // decode image name
                    $ach_str1  = base64_decode($ach_info['filename']);
                    // remove everything before /ach
                    $ach_str2  = strstr($ach_str1, '/ach');
                    // subtract last 12 spaces and/or whitespace from string
                    $ach_str3  = substr($ach_str2, 0, -11);
                    // create color tile source
                    $ach_color = 'https://image-ssl.xboxlive.com/global/t.' . dechex($json['Game']['Id']) . $ach_str3;

                    $achievements['achievements'][$i]['artwork']['locked']   = $achievement['TileUrl'];
                    $achievements['achievements'][$i]['artwork']['unlocked'] = $ach_color;
                }

                if (!empty($achievement['Name'])) {
                    $achievements['achievements'][$i]['title'] = $this->clean($achievement['Name']);
                }

                if (!empty($achievement['Description'])) {
                    $achievements['achievements'][$i]['description'] = $this->clean($achievement['Description']);
                }

                if (!empty($achievement['Score'])) {
                    $achievements['achievements'][$i]['gamerscore'] = $achievement['Score'];
                }

                if (!empty($achievement['EarnDates'][$g]['EarnedOn'])) {
                    $achievements['achievements'][$i]['unlocked']        = true;
                    $achievements['achievements'][$i]['unlockdate']      = (int)substr($achievement['EarnDates'][$g]['EarnedOn'], 6, 10);
                    $achievements['achievements'][$i]['unlockedoffline'] = (bool)$achievement['EarnDates'][$g]['IsOffline'];
                }

                $i++;
            }

            $achievements['freshness'] = $freshness;
            return $achievements;
        } elseif (stripos($data, 'errorCode: \'404\'')) {
            $this->error = 502;
            return false;
        } else {
            $this->error = 500;
            $this->__cache->remove($key);
            $this->force_new_login();
            return false;
        }
    }
882051
private function buildQuery(string $url, string $locale = null, string $region = null): string
    {
        if (null !== $locale) {
            $url = sprintf('%s&language=%s', $url, $locale);
        }

        if (null !== $region) {
            $url = sprintf('%s&region=%s', $url, $region);
        }

        if (null !== $this->apiKey) {
            $url = sprintf('%s&key=%s', $url, $this->apiKey);
        }

        if (null !== $this->clientId) {
            $url = sprintf('%s&client=%s', $url, $this->clientId);

            if (null !== $this->channel) {
                $url = sprintf('%s&channel=%s', $url, $this->channel);
            }

            if (null !== $this->privateKey) {
                $url = $this->signQuery($url);
            }
        }

        return $url;
    }
760813
public function isGameExists($region, $gameId)
    {
        $metas = $this->buzz->get(sprintf($this->getUrl($region) . self::URL_META, $region, $gameId));

        // Check if game exists
        if ('HTTP/1.1 500 Internal Server Error' == $metas->getHeaders()[0]) {
            return false;
        }

        return true;
    }
1099128
public function getEndStats($region, $gameId)
    {
        $filePath = $this->getReplayDirPath($region, $gameId) . '/endstats';

        if (!is_file($filePath)) {
            throw new ReplayEndStatsNotFoundException('The endstats for game #' . $gameId . ' is not found');
        }

        return $filePath;
    }
169669
public function steamIdToCommunityId($steam_id)
    {
        $x = NULL;
        $y = NULL;
        if (preg_match('/(?i:STEAM)_0:[0-9]:[0-9]*/', $steam_id)) {
            $x = substr($steam_id, 8, 1);
            $y = substr($steam_id, 10);
        } elseif (preg_match('/0:[0-9]:[0-9]*/', $steam_id)) {
            $x = substr($steam_id, 2, 1);
            $y = substr($steam_id, 4);
        } else {
            throw new WrongIDException($steam_id);
        }
        return ($y * 2) + $x + 76561197960265728;
    }
1301444
public function queryTemplate(
        $gameKey
    ) {
        $gameKey = (string) $gameKey;
        $state = $this->query('template', [$gameKey]);

        return $state;
    }
1109463
public function getNumberOfPlayers($gameId = null)
    {
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
        $rsm = new \Doctrine\ORM\Query\ResultSetMapping;
        $rsm->addScalarResult('c', 'c');
        if ($gameId !== null) {
            $game = $this->getServiceManager()
                ->get('playgroundgame_lottery_service')
                ->getGameMapper()
                ->findById($gameId);

            if ($game && $game->getAnonymousAllowed()) {
                $query = $em->createNativeQuery('
                    SELECT COUNT(distinct e.anonymous_identifier) AS c
                    FROM game_entry e
                    WHERE e.game_id = '.((int) $gameId).'
                ', $rsm);
            } else {
                $query = $em->createNativeQuery('
                    SELECT COUNT(distinct e.user_id) AS c
                    FROM game_entry e
                    WHERE e.game_id = '.((int) $gameId).'
                ', $rsm);
            }
        } else {
            $query = $em->createNativeQuery('
                    SELECT COUNT(distinct e.user_id) AS c
                    FROM game_entry e
                ', $rsm);
        }
        
        $count = $query->getSingleScalarResult();
        return $count;
    }
328190
public function ValidTax($country = null, $region = null)
    {
        if (empty($country)) {
            // First try and get the locale from the member
            $member = Security::getCurrentUser();

            if ($member && $member->getLocale()) {
                $country = $member->getLocale();
            }
        }

        if (empty($country)) {
            $country = i18n::get_locale();
        }

        if (strlen($country) > 2) {
            $country = Locale::getRegion($country);
        }

        $filter = [
            'Global' => 1,
            "Zones.Regions.CountryCode" => $country
        ];

        $rates = $this
            ->Rates()
            ->filterAny($filter);

        if (isset($region)) {
            $rates = $rates->filter("Zones.Regions.Code", $region);
        }

        return $rates->first();
    }
549227
public function downloadKeyframe($region, $gameId, $keyframeId)
    {
        try {
            $keyframe = $this->buzz->get(sprintf(
                $this->getUrl($region) . self::URL_KEYFRAME_DOWNLOAD,
                $region,
                $gameId,
                $keyframeId
            ));
        } catch (TimeoutException $e) {
            return false;
        } catch (RequestException $e) {
            return false;
        }

        // Check if game exists
        $header = $keyframe->getHeaders()[0];
        if ('HTTP/1.1 500 Internal Server Error' == $header || 'HTTP/1.1 404 Not Found' == $header) {
            return false;
        }

        return $keyframe->getContent();
    }
372623
public function getPrizeCategoryGames($categoryid)
    {
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');

        $query = $em->createQuery('SELECT g FROM PlaygroundGame\Entity\Game g
            WHERE (g.prizeCategory = :categoryid AND g.broadcastPlatform = 1)
            ORDER BY g.publicationDate DESC');
        $query->setParameter('categoryid', $categoryid);
        $games = $query->getResult();

        return $games;
    }
110717
public function downloadChunk($region, $gameId, $chunkId)
    {
        try {
            $chunk = $this->buzz->get(sprintf(
                $this->getUrl($region) . self::URL_CHUNK_DOWNLOAD,
                $region,
                $gameId,
                $chunkId
            ));
        } catch (TimeoutException $e) {
            return false;
        } catch (RequestException $e) {
            return false;
        }

        // Check if game exists
        $header = $chunk->getHeaders()[0];

        if ('HTTP/1.1 500 Internal Server Error' == $header || 'HTTP/1.1 404 Not Found' == $header) {
            return false;
        }

        return $chunk->getContent();
    }
966012
public EndOfGameStats getTeamEndOfGameStats(TeamId teamId, long gameId) {
        return client.sendRpcAndWait(SERVICE, "getTeamEndOfGameStats", teamId, gameId);
    }