Fetch information about played games

@access public
@var    string $gamertag
@var    string $region
@return array
355374
public function fetch_games($gamertag, $region)
    {
        $gamertag  = trim($gamertag);
        $url       = 'https://live.xbox.com/' . $region . '/Activity';
        $key       = $this->version . ':games.' . $gamertag;
        $data      = $this->__cache->fetch($key);
        $freshness = 'from cache';

        if (!$data) {
            $data      = $this->fetch_url($url);
            $post_data = '__RequestVerificationToken=' . urlencode(trim($this->find($data, '<input name="__RequestVerificationToken" type="hidden" value="', '" />'))) . '&compareTo=' . urlencode($gamertag);
            $headers   = array('X-Requested-With: XMLHttpRequest', 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8');
            $data      = $this->fetch_url('https://live.xbox.com/' . $region . '/Activity/Summary?compareTo=' . urlencode($gamertag) . '&lc=1033', $url, 10, $post_data, $headers);
            $freshness = 'new';
            $this->__cache->store($key, $data, 3600);
        }

        $json = json_decode($data, true);

        if ($json['Success'] == 'true' && $json['Data']['Players'][0]['Gamertag'] != $this->account_gamertag) {
            $json                             = $json['Data'];
            $games                            = array();
            $games['gamertag']                = $g = $json['Players'][0]['Gamertag'];
            $games['gamerscore']['current']   = $json['Players'][0]['Gamerscore'];
            $games['gamerscore']['total']     = 0;
            $games['achievements']['current'] = 0;
            $games['achievements']['total']   = 0;
            $games['totalgames']              = $json['Players'][0]['GameCount'];
            $games['progress']                = $json['Players'][0]['PercentComplete'];

            $i = 0;
            foreach ($json['Games'] as $game) {
                if ($game['Progress'][$g]['LastPlayed'] !== 'null') {
                    $games['games'][$i]['id']                      = $game['Id'];
                    $games['games'][$i]['hid']                     = dechex($game['Id']);
                    $games['games'][$i]['isapp']                   = (bool)($game['PossibleScore'] == 0);
                    $games['games'][$i]['title']                   = $this->clean($game['Name']);
                    $games['games'][$i]['artwork']['small']        = 'http://download.xbox.com/content/images/66acd000-77fe-1000-9115-d802' . dechex($game['Id']) . '/1033/boxartsm.jpg';
                    $games['games'][$i]['artwork']['large']        = 'http://download.xbox.com/content/images/66acd000-77fe-1000-9115-d802' . dechex($game['Id']) . '/1033/boxartlg.jpg';
                    $games['games'][$i]['gamerscore']['current']   = $game['Progress'][$g]['Score'];
                    $games['games'][$i]['gamerscore']['total']     = $game['PossibleScore'];
                    $games['games'][$i]['achievements']['current'] = $game['Progress'][$g]['Achievements'];
                    $games['games'][$i]['achievements']['total']   = $game['PossibleAchievements'];
                    $games['games'][$i]['progress']                = 0;
                    $games['games'][$i]['lastplayed']              = (int)substr($game['Progress'][$g]['LastPlayed'], 6, 10);
                    $games['gamerscore']['total']                  = $games['gamerscore']['total'] + $games['games'][$i]['gamerscore']['total'];
                    $games['achievements']['current']              = $games['achievements']['current'] + $games['games'][$i]['achievements']['current'];
                    $games['achievements']['total']                = $games['achievements']['total'] + $games['games'][$i]['achievements']['total'];

                    if ($game['Progress'][$g]['Achievements'] !== 0) {
                        $games['games'][$i]['progress'] = round((($game['Progress'][$g]['Achievements'] / $game['PossibleAchievements']) * 100), 1);
                    }

                    $i++;
                }
            }

            $games['freshness'] = $freshness;
            return $games;
        } elseif ($json['Data']['Players'][0]['Gamertag'] == $this->account_gamertag) {
            $this->error = 501;
            return false;
        } else {
            $this->error = 500;
            $this->__cache->remove($key);
            $this->force_new_login();
            return false;
        }
    }
608954
public static function readgamestat($i)
    {
        //this array contains the info that will be returned
        $info = array(
                'num_players' => trim(str_replace('Players: ', '', $i[1])),
                'map' => trim(str_replace('Map: ', '', $i[2])),
                'mode' => trim(str_replace('Gamemode: ', '', $i[3])),
                'timeleft' => trim(str_replace('Timeleft: ', '', $i[4])),
                 );
        //support for the teambased gamemodes
        if ($info['mode'] == 'Capture the Flag' || $info['mode'] == 'Infiltration' || $info['mode'] == 'Teammatch') {
            $info['teams']['alpha'] = trim(str_replace('Team 1: ', '', $i[5]));
            $info['teams']['bravo'] = trim(str_replace('Team 2: ', '', $i[6]));
            $info['teams']['charlie'] = trim(str_replace('Team 3: ', '', $i[7]));
            $info['teams']['delta'] = trim(str_replace('Team 4: ', '', $i[8]));
            $players_line = 10;
        } else {
            $players_line = 6;
        }
        $pla = '';
        //get the player info a string
        for ($l = $players_line; $line = $i[$l], $l < count($i); ++$l) {
            $pla .= $line;
        }
        //explode then chunk that string
        $players_info = array_chunk(explode("\n", $pla), 5);
        //kill the last element since its empty
        array_pop($players_info);
        //add each player to the new array
        foreach ($players_info as $p) {
            $info['players'][] = array(
                    'name' => $p[0],
                    'kills' => $p[1],
                    'deaths' => $p[2],
                    'team' => $p[3],
                    'ping' => $p[4],
                    );
        }
        //return the info
        return $info;
    }
1211170
public function getCurrentRealmsAffections(): array
    {
        $realmsAffections = [];
        foreach ($this->getRealmsAffectionsSum() as $periodName => $periodSum) {
            $realmsAffections[$periodName] = new RealmsAffection([$periodSum, $periodName]);
        }

        return $realmsAffections;
    }
592996
public function getUpcommingGames($nb_hours, $limit = NULL, $onlyWithoutScore = TRUE) {
    $date_to = new \DateTime(null, new \DateTimeZone('UTC'));
    $date_to->add(new \DateInterval('PT' . (int) $nb_hours . 'H'));
    $now = new \DateTime(null, new \DateTimeZone('UTC'));

    $query = \Drupal::entityQuery('game');

    $query->condition('game_date', $now->format('Y-m-d\TH:i:s'), '>');
    $query->condition('game_date', $date_to->format('Y-m-d\TH:i:s'), '<=');

    if($onlyWithoutScore) {
      $group = $query->orConditionGroup();
      $group->condition('score_team_1', NULL, 'is');
      $group->condition('score_team_2', NULL, 'is');
      $query->condition($group);
    }

    $query->sort('game_date', 'ASC');
    $query->sort('id', 'ASC');

    if($limit) {
      $query->range(0, $limit);
    }

    $ids = $query->execute();
    if ($ids) {
      return Game::loadMultiple($ids);
    }
    return [];
  }
408018
public List<String> getPlayerNames() {
        return lastGameState.getPlayers().stream().map(Player::getUsername).collect(Collectors.toList());
    }
72825
def get_games(ctx):
    """"""

    username = ctx.obj['username']
    games = User(username).get_games_owned()

    for game in sorted(games.values(), key=itemgetter('title')):
        click.echo('%s [appid: %s]' % (game['title'], game['appid']))

    click.secho('Total gems owned by `%s`: %d' % (username, len(games)), fg='green')
437866
public function getGames() {
    $injected_database = Database::getConnection();
    $query = $injected_database->select('mespronos__game', 'g');
    $query->join('mespronos__day', 'd', 'd.id = g.day');
    $query->addField('g', 'id');
    $query->condition('d.league', $this->id());
    $results = $query->execute()->fetchAllAssoc('id');

    $results = array_map(function ($v) {return $v->id;}, $results);
    return Game::loadMultiple($results);
  }
468139
public function retrieveGameModeMapStats ()
    {
        $data = file_get_contents("http://battlefield.play4free.com/en/profile/stats/" .$this->_profileID. "/" .$this->_soldierID. "?g=[%22GameModeMapStats%22]");
        $gameModeMapStats = json_decode($data);
        return $gameModeMapStats;
    }
565161
public function GetUserStatsForGame($appId, $all = false)
    {
        // Set up the api details
        $this->method  = __FUNCTION__;
        $this->version = 'v0002';

        // Set up the arguments
        $arguments = [
            'steamid' => $this->steamId,
            'appid'   => $appId,
            'l'       => 'english',
        ];

        // Get the client
        $client = $this->setUpClient($arguments)->playerstats;

        // Games like DOTA and CS:GO have additional stats here.  Return everything if they are wanted.
        if ($all === true) {
            return $client;
        }

        return $client->achievements;
    }
262248
private function _getMatchesIdsFromMatches()
    {
        $_matchesIdsFromSlots = $this->_getMatchesIdsFromSlots();
        $db = Db::obtain();
        // basic matches data
        $matchesQuery = 'SELECT * FROM ' . Db::realTablename('matches') . '';
        $where = '';
        $data = array();

        if (null !== $this->getLeagueId()) {
            $where .= 'leagueid = ? AND ';
            array_push($data, $this->getLeagueId());
        }

        if (null !== $this->getTeamId()) {
            $where .= '(radiant_team_id = ? OR dire_team_id = ?) AND ';
            array_push($data, $this->getTeamId());
            array_push($data, $this->getTeamId());
        }

        if (count($_matchesIdsFromSlots)) {
            $where .= 'match_id IN (' . implode(',', $_matchesIdsFromSlots) . ') AND ';
        }

        if (null !== $this->getStartAtMatchId()) {
            $where .= 'match_id > ? AND ';
            array_push($data, $this->getStartAtMatchId());
        }

        if (trim($where) !== '') {
            $matchesQuery .= ' WHERE ' . substr($where, 0, strlen($where) - 4);
        }

        $matchesQuery .= ' ORDER BY start_time DESC';

        if (null !== $this->getMatchesRequested()) {
            $matchesQuery .= ' LIMIT ?';
            array_push($data, $this->getMatchesRequested());
        }

        $matchesInfo = $db->fetchArrayPDO($matchesQuery, $data);
        // no one match found
        if (count($matchesInfo) === 0) {
            return array();
        }
        return $matchesInfo;
    }
50629
protected function _getRegionData() {
        $this->_streamOutput->writeln('Downloading new region listing…');
        $regionsFile = $this->_getFileTmp('region.csv');
        $this->_download($regionsFile, self::REGION_URL);
        $regionsPath = $regionsFile->getPathOnLocalFilesystem();
        $handle = fopen($regionsPath, 'r');
        if (!$handle) {
            throw new CM_Exception('Could not open file', null, ['file' => $regionsPath]);
        }

        $this->_streamOutput->writeln('Reading new region listing…');
        $regionData = array();
        while (false !== ($row = fgetcsv($handle))) {
            if (count($row) >= 3) { // Skip empty lines
                $regionData[] = $row;
            }
        }
        if (!fclose($handle)) {
            throw new CM_Exception('Could not close file', null, ['file' => $regionsPath]);
        }
        return $regionData;
    }
295327
public function getGameEntries($header, $entries, $game)
    {
        $header = $this->getEntriesHeader($game);

        $results = array();

        foreach ($entries as $k => $entry) {
            $entryData = json_decode($entry['playerData'], true);
            foreach ($header as $key => $v) {
                if (isset($entryData[$key])) {
                    $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 H:i:s'):
                        $entry[$key];
                } else {
                    $results[$k][$key] = '';
                }
            }
        }

        return $results;
    }
281959
public function fetch($limit=null)
    {
        $data = Base::query('bf2cc serverchatbuffer');
        
        $spl = explode("\r\r", $data);
        
        $result = array();
        
        $i = 0;
        
        foreach ($spl as $chat) {
            $ex = explode("\t", $chat);
            
            if(count($ex) < 2) continue;
            
            list($index, $origin, $team, $type, $time, $message) = $ex;
            
            if (!$limit or $limit > count($spl)-$i) {
                $result[] = (object) array
                (
                    'origin'    =>  $origin,
                    'type'      =>  $type,
                    'team'      =>  $team,
                    'time'      =>  substr($time, 1, -1),
                    'message'   =>  $message,
                    'index'     =>  $index
                );
            }            
            ++$i;
        }
        return $result;
    }
684068
public function getAllSlotsDivided()
    {
        $return = array('radiant' => array(), 'dire' => array());
        foreach ($this->_slots as $slot) {
            $team = 'radiant';
            if ($slot->get('player_slot') > 5) {
                $team = 'dire';
            }
            array_push($return[$team], $slot);
        }
        return $return;
    }
169778
protected function fetchRecords($zoneid)
    {
        if (!$zoneid) {
            throw new \Exception('fetchRecords called with blank zone ID');
        }
        $uri = $this->baseuri.'/zones/'.$zoneid.'/dns_records';
        $result = $this->httpGet($uri);

        return $result;
    }
976811
public function getLastChunkInfo($region, $gameId, $chunkId)
    {
        try {
            $chunkInfo = $this->buzz->get(sprintf(
                $this->getUrl($region) . self::URL_CHUNK_INFO,
                $region,
                $gameId,
                $chunkId
            ));
        } catch (TimeoutException $e) {
            return false;
        } catch (RequestException $e) {
            return false;
        }

        return $chunkInfo->getContent();
    }
228362
public function fetch_search($query, $region)
    {
        $query     = trim($query);
        $url       = 'http://marketplace.xbox.com/' . $region . '/SiteSearch/xbox/?query=' . urlencode($query);
        $key       = $this->version . ':friends.' . $query;
        $data      = $this->__cache->fetch($key);
        $freshness = 'from cache';

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

        $json = json_decode($data, true);
        if ($json['totalEntries'] >= 1) {
            $search                 = array();
            $search['totalresults'] = $json['totalEntries'];
            $search['resultslink']  = 'http://marketplace.xbox.com' . $json['allResultsUrl'];

            $i = 0;
            foreach ($json['entries'] as $entry) {
                $search['results'][$i]['title']                 = $entry['title'];
                $search['results'][$i]['parent']                = $entry['parentTitle'];
                $search['results'][$i]['link']                  = 'http://marketplace.xbox.com' . $entry['detailsUrl'];
                $search['results'][$i]['image']                 = $entry['image'];
                $search['results'][$i]['downloadtype']['class'] = $entry['downloadTypeClass'];
                $search['results'][$i]['downloadtype']['title'] = $entry['downloadTypeText'];
                $search['results'][$i]['prices']['silver']      = $entry['prices']['silver'];
                $search['results'][$i]['prices']['gold']        = $entry['prices']['gold'];
                $i++;
            }

            $search['freshness'] = $freshness;
            return $search;
        } else {
            $this->error = 504;
            $this->__cache->remove($key);
            return false;
        }
    }