username = $username;
$key = $_COOKIE["adminer_key"];
$hash = md5($password); // the cached token must not be used with a different secret, otherwise any password would be accepted
$cache = get_session("igdb_token"); // hash of the secret, expiration, token encrypted the same way as the password
if (idx($cache, 0) === $hash && $cache[1] > time()) {
$this->token = ($key ? decrypt_string($cache[2], $key) : $cache[2]);
}
if (!$this->token) {
$url = "https://id.twitch.tv/oauth2/token";
$context = stream_context_create(array('http' => array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded",
'content' => http_build_query(array('client_id' => $username, 'client_secret' => $password, 'grant_type' => 'client_credentials')),
'ignore_errors' => true,
)));
list($response, $status, , $error) = get_url($url, $context);
$json = (array) json_decode($response, true); // idx() requires an array
$this->token = $json['access_token'];
if (!$this->token) {
return "$url: " . ($error ?: idx($json, 'message', "HTTP $status")); // the URL is a constant so displaying the response doesn't disclose anything
}
set_session("igdb_token", array($hash, time() + $json['expires_in'], ($key ? encrypt_string($this->token, $key) : $this->token)));
}
return '';
}
function select_db(string $database): bool {
return ($database == "api");
}
function request(string $endpoint, string $query, string $method = 'POST') {
return adminer()->executeQuery("$method $endpoint: $query", function () use ($endpoint, $query, $method) {
return $this->execute($endpoint, $query, $method);
});
}
/** Send the request to the API
* @return array|false
*/
private function execute(string $endpoint, string $query, string $method) {
$context = stream_context_create(array('http' => array(
'method' => $method,
'header' => array(
"Content-Type: text/plain",
"Client-ID: $this->username",
"Authorization: Bearer $this->token",
),
'content' => $query,
'ignore_errors' => true,
)));
list($response, $status) = get_url("https://api.igdb.com/v4/$endpoint", $context);
$return = json_decode($response, true);
if ($status != 200) {
if (is_array($return)) {
foreach (is_array($return[0]) ? $return : array($return) as $rows) {
foreach ($rows as $key => $val) {
$this->error .= '' . h($key) . ': ' . (is_url($val) ? '' . h($val) . '' : h($val)) . '
';
}
}
} else {
$this->error = htmlspecialchars(strip_tags($response), 0, null, false);
}
return false;
}
return $return;
}
function query(string $query, bool $unbuffered = false) {
if (preg_match('~^SELECT COUNT\(\*\) FROM (\w+)(?: WHERE (search "(?:[^"\\\\]|\\\\.)*")?(?:(?: AND )?(.+))?)?$~s', $query, $match)) { // search "..." is built by fulltextSql()
$where = (isset($match[3]) ? 'where ' . str_replace(' AND ', ' & ', $match[3]) . ';' : '');
return new Result(array($match[1] == 'dumps' ? array('count' => 50) : $this->request("$match[1]/count", ($match[2] ? "$match[2];" : '') . $where)));
}
if (preg_match('~^\s*(GET|POST|DELETE)\s+([\w/?=]+)\s*;\s*(.*)$~s', $query, $match)) {
$endpoint = $match[2];
$response = $this->request($endpoint, $match[3], $match[1]);
if ($response === false) {
return $response;
}
$return = new Result(is_array($response[0]) ? $response : array($response));
$return->table = $endpoint;
if ($endpoint == 'multiquery') {
$return->results = $response;
}
return $return;
}
$this->error = "Syntax:
POST <endpoint>; fields ...;";
return false;
}
function store_result() {
if ($this->multi && ($result = current($this->multi->results))) {
echo "
" . h($result['name']) . "
\n";
$this->multi->__construct($result['count'] ? array(array('count' => $result['count'])) : $result['result']);
}
return $this->multi;
}
function next_result(): bool {
return $this->multi && next($this->multi->results);
}
function quote(string $string): string {
return $string;
}
}
class Result {
public $num_rows;
public $table;
public $results = array();
private $result;
private $fields;
function __construct(array $result) {
$keys = array();
foreach ($result as $i => $row) {
foreach ($row as $key => $val) {
$keys[$key] = null;
if (is_array($val) && is_int($val[0])) {
$result[$i][$key] = "(" . implode(",", $val) . ")";
}
}
}
foreach ($result as $i => $row) {
$result[$i] = array_merge($keys, $row);
}
$this->result = $result;
$this->num_rows = count($result);
$this->fields = array_keys(idx($result, 0, array()));
}
function fetch_assoc() {
$row = current($this->result);
next($this->result);
return $row;
}
function fetch_row() {
$row = $this->fetch_assoc();
return ($row ? array_values($row) : false);
}
function fetch_field(): \stdClass {
$field = current($this->fields);
next($this->fields);
return (object) ($field != '' ? array('name' => $field, 'orgtable' => $this->table) : array());
}
}
}
class Driver extends SqlDriver {
static $extensions = array("DOM + OpenSSL + allow_url_fopen");
static $jush = "igdb";
public $delimiter = ";;";
public $tables = array();
public $links = array();
public $fields = array();
public $foreignKeys = array();
public $foundRows = null;
function operators(?array $tableStatus): array {
return array("=", "<", ">", "<=", ">=", "!=", "~");
}
/** Get the JUSH module inlined in the released driver by the release script */
static function jushModule(): string {
return ""; // the repository and the source archive load adminer/static/jush/modules/jush-igdb.js
}
static function jushAutocomplete(array $tables, ?array $statements): string {
return ""; // the queries are not SQL
}
private static function docsFilename(): string {
return get_temp_dir() . "/adminer-igdb-api.html";
}
static function connect(string $server, string $username, string $password) {
$filename = self::docsFilename();
if (!file_exists($filename) || filemtime($filename) < time() - 7 * 24 * 60 * 60) {
list($contents, $status) = get_url("https://api-docs.igdb.com/", stream_context_create(array('http' => array('ignore_errors' => true))));
if ($status != 200 || !file_put_contents($filename, $contents)) {
return "Download https://api-docs.igdb.com/ and save it as $filename";
}
}
return parent::connect($server, $username, $password);
}
static function disconnect(): void {
set_session("igdb_token", null);
}
function __construct(Db $connection) {
parent::__construct($connection);
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
$dom->loadHTMLFile(self::docsFilename());
$xpath = new \DOMXPath($dom);
$els = $xpath->query('//div[@class="content"]/*');
$link = '';
foreach ($els as $i => $el) {
if ($el->tagName == 'h2') {
$link = $el->getAttribute('id');
}
if ($el->nodeValue == 'Request Path') {
$table = preg_replace('~^https://api.igdb.com/v4/~', '', $els[$i+1]->firstElementChild->nodeValue);
$comment = $els[$i-1]->tagName == 'p' ? $els[$i-1]->nodeValue : '';
if (preg_match('~^DEPRECATED!~', $comment)) {
continue;
}
$this->fields[$table]['id'] = array('full_type' => 'bigint', 'comment' => '');
$this->links[$link] = $table;
$this->tables[$table] = array('Name' => $table, 'Engine' => 'endpoint', 'Comment' => $comment);
foreach ($xpath->query('tbody/tr', $els[$i+2]) as $tr) {
$tds = $xpath->query('td', $tr);
$field = $tds[0]->nodeValue;
$comment = $tds[2]->nodeValue;
if (!in_array($field, array('checksum', 'content_descriptions', 'test_dummy')) && !preg_match('~^DEPRECATED!~', $comment)) {
$this->fields[$table][$field] = array(
'full_type' => str_replace(' ', ' ', $tds[1]->nodeValue),
'comment' => str_replace(' ', ' ', $comment),
);
$ref = $xpath->query('a/@href', $tds[1]);
if ($field == 'image_id') {
$this->fields[$table][$field]['doc'] = "https://api-docs.igdb.com/#images";
}
if (count($ref)) {
if (preg_match('~^#(tag-numbers|.*-enums)$~', $ref[0]->value)) {
$this->fields[$table][$field]['doc'] = "https://api-docs.igdb.com/" . $ref[0]->value;
} else {
$this->foreignKeys[$table][$field] = substr($ref[0]->value, 1);
}
} elseif ($field === 'game_id') { // game_time_to_beats, popularity_primitives
$this->foreignKeys[$table][$field] = 'game';
}
}
}
uksort($this->fields[$table], function ($a, $b) use ($table) {
return (($b == 'id') - ($a == 'id'))
?: (($b == 'name') - ($a == 'name'))
?: (($a == 'updated_at') - ($b == 'updated_at'))
?: (($a == 'created_at') - ($b == 'created_at'))
?: (!idx($this->foreignKeys[$table], $b) - !idx($this->foreignKeys[$table], $a))
?: ($a < $b ? -1 : 1)
;
});
}
}
$this->tables['dumps'] = array(
'Name' => 'dumps',
'Engine' => 'dumps',
'Comment' => 'Daily updated CSV Data Dumps which can be used to kick start your projects or keep your data up to date (within 24 hours)',
);
$this->links['data-dumps'] = 'dumps';
$this->fields['dumps'] = array(
's3_url' => array('comment' => 'The download Url is a presigned S3 url that is valid for 5 minutes'),
'endpoint' => array(),
'file_name' => array(),
'size_bytes' => array(),
'updated_at' => array('full_type' => 'datetime'),
'schema_version' => array('full_type' => 'datetime', 'comment' => 'Will change when the schema changes'),
'schema' => array('comment' => 'Reflects the current data structure and data type that the Dump is using'),
);
$this->tables['webhooks'] = array(
'Name' => 'webhooks',
'Engine' => 'webhooks',
'Comment' => 'Webhooks allow us to push data to you when it is added, updated, or deleted',
);
$this->links['webhooks'] = 'webhooks';
$this->fields['webhooks'] = array(
'endpoint' => array(
'full_type' => 'String',
'comment' => 'Specify what type of data you want from your webhook',
'privileges' => array('insert' => 1),
),
'id' => array('comment' => 'A unique ID for the webhook'),
'url' => array(
'full_type' => 'String',
'length' => '100',
'comment' => 'Your prepared url that is ready to accept data from us',
'privileges' => array('select' => 1, 'insert' => 1),
),
'method' => array(
'full_type' => 'enum',
'length' => "('create','delete','update')",
'comment' => 'The type of data you are expecting to your url, there are three types of methods',
'privileges' => array('insert' => 1),
),
'category' => array('comment' => 'Based on the endpoint you chose'),
'sub_category' => array('comment' => 'Based on your method (can be 0, 1, 2)'),
'active' => array('comment' => 'Is the webhook currently active'),
'api_key' => array('comment' => 'Displays the api key the webhook is connected to'),
'secret' => array(
'full_type' => 'String',
'comment' => 'Your “secret” password for your webhook',
'privileges' => array('select' => 1, 'insert' => 1),
),
'created_at' => array('comment' => 'Created at date'),
'updated_at' => array('comment' => 'Updated at date'),
);
}
function fulltextSql(string $name, array $index, string $query, bool $boolean): string {
return 'search "' . addcslashes($query, '\\"') . '"';
}
function select(string $table, array $select, array $where, array $group, array $order = array(), int $limit = 1, ?int $page = 0, bool $print = false) {
$query = '';
$search = preg_match('~^search "~', $where[0]); // the condition built by fulltextSql()
if ($search) {
$query = "$where[0];\n";
unset($where[0]);
}
foreach ($where as $i => $val) {
$where[$i] = str_replace(' OR ', ' | ', $val);
}
$limit = ($limit ?: 500); // 0 - all rows, used by export; 500 is the maximum accepted by the API, it has no way to get more
$columns = ($select != array('*') ? $select : array_keys($this->fields[$table]));
$common = ($where ? "\nwhere " . implode(" & ", $where) . ";" : "");
$method = ($table == 'webhooks' || $table == 'dumps' ? 'GET' : 'POST');
$endpoint = $table;
if ($method == 'GET' && $where) { // the GET endpoints accept only a single row by its primary key, the edit page passes 'id = 1', export of a checked row '((id = 1))'
if (!preg_match('~^\(*(?:id|endpoint) = (\w+)\)*$~', implode(' & ', $where), $match)) {
$this->conn->error = "Only a single row can be selected by its primary key.";
return false;
}
$endpoint .= "/$match[1]";
}
if ($method == 'POST') {
$query .= "fields " . implode(",", $select) . ";"
. ($select == array('*') ? "\nexclude checksum;" : "")
. $common
. ($order ? "\nsort " . strtolower(implode(",", $order)) . ";" : "")
. "\nlimit $limit;"
. ($page ? "\noffset " . ($page * $limit) . ";" : "")
;
}
$start = microtime(true);
$multi = (!$search && $method == 'POST' && array_key_exists($table, driver()->tables) && $table != 'search'); // multiquery rejects the search endpoint
$realQuery = str_replace("*;\nexclude checksum", implode(',', $columns), $query); // exclude deprecated columns
$return = ($multi
? $this->conn->request('multiquery', "query $table \"result\" { $realQuery };\nquery $table/count \"count\" { $common };")
: $this->conn->request($endpoint, $realQuery, $method)
);
$this->query = "$method $table;\n$query";
if ($print) {
echo adminer()->selectQuery($this->query, $start);
}
if ($return === false) {
return $return;
}
$this->foundRows = ($multi ? $return[1]['count'] : null);
$return = ($multi ? $return[0]['result'] : $return);
if ($table == 'dumps' && $where) {
$return = array($return);
} elseif ($return && $method == 'POST') {
$return[0] = array_merge(array_fill_keys($columns, null), $return[0]);
}
return new Result($return);
}
function insert(string $table, array $set) {
$content = array();
foreach ($set as $key => $val) {
if ($key != 'endpoint') {
$content[] = urlencode($key) . '=' . urlencode($val);
}
}
return queries("POST $set[endpoint]/$table; " . implode('&', $content));
}
function delete(string $table, string $queryWhere, int $limit = 0) {
preg_match_all('~\bid = (\d+)~', $queryWhere, $matches);
$this->conn->affected_rows = 0;
foreach ($matches[1] as $id) {
$result = queries("DELETE $table/$id;");
if (!$result) {
return false;
}
$row = $result->fetch_row();
if (!$row[0]) {
$this->conn->error = "ID $id not found.";
return false;
}
$this->conn->affected_rows++;
}
return true;
}
function value(?string $val, array $field): ?string {
return ($val && in_array($field['full_type'], array('Unix Time Stamp', 'datetime')) ? str_replace(' 00:00:00', '', gmdate('Y-m-d H:i:s', (int) $val)) : $val);
}
function tableHelp(string $name, bool $is_view = false) {
return strtolower("https://api-docs.igdb.com/#" . array_search($name, $this->links));
}
}
function logged_user(): string {
return $_GET["username"];
}
function get_databases(bool $flush): array {
return array("api");
}
function collations(): array {
return array();
}
function db_collation(string $db, array $collations) {
}
function information_schema(string $db) {
}
function indexes(string $table, ?Db $connection2 = null): array {
$return = array(array('type' => 'PRIMARY', 'columns' => array($table == 'dumps' ? 'endpoint' : 'id')));
if (in_array($table, array('characters', 'collections', 'games', 'platforms', 'search', 'themes'))) { // https://api-docs.igdb.com/#search-1
$return[] = array("type" => "FULLTEXT", "columns" => array("search"));
}
return $return;
}
function fields(string $table): array {
$return = array();
foreach (driver()->fields[$table] ?: array() as $key => $val) {
$type = strtolower(preg_replace('~ .*~', '', $val['full_type']));
$return[$key] = $val + array(
"field" => $key,
"type" => ($type == 'reference' ? 'int' : $type), // align right reference columns
"privileges" => array("select" => 1) + ($table == 'webhooks' || $table == 'dumps' ? array() : array("where" => 1, "order" => 1)),
);
}
return $return;
}
function convert_field(array $field) {
}
function unconvert_field(array $field, string $return): string {
return $return;
}
function limit(string $query, string $where, int $limit, int $offset = 0, string $separator = " "): string {
return $query;
}
function limit1(string $table, string $query, string $where, string $separator = "\n"): string {
return limit($query, $where, 1, 0, $separator);
}
function idf_escape(string $idf): string {
return $idf;
}
function table(string $idf): string {
return idf_escape($idf);
}
function foreign_keys(string $table): array {
$return = array();
foreach (driver()->foreignKeys[$table] ?: array() as $key => $val) {
$return[] = array(
'table' => driver()->links[$val],
'source' => array($key),
'target' => array('id'),
);
}
return $return;
}
function tables_list(): array {
return array_fill_keys(array_keys(table_status()), 'table');
}
function table_status(string $name = "", bool $fast = false): array {
$tables = driver()->tables;
return ($name != '' ? ($tables[$name] ? array($name => $tables[$name]) : array()) : $tables);
}
function count_tables(array $databases): array {
return array(reset($databases) => count(tables_list()));
}
function error(): string {
return connection()->error;
}
function explain(Db $connection, string $query) {
}
function is_view(array $table_status): bool {
return false;
}
function found_rows(array $table_status, array $where) {
return driver()->foundRows;
}
function fk_support(array $table_status): bool {
return true;
}
function last_id($result): string {
$row = $result->fetch_assoc();
return (string) $row['id'];
}
function support(string $feature): bool {
return in_array($feature, array('columns', 'comment', 'single_db', 'sql', 'table'));
}
}