-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathytapi_cache.php
222 lines (179 loc) · 5.56 KB
/
ytapi_cache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
require 'credentials.php';
class CacheDb {
private $dbconn;
const TABLENAME = 'api_cache';
const CREATE_TABLE = <<< EOT
CREATE TABLE %s (
id integer primary key auto_increment,
endpoint varchar(32),
query JSON,
result JSON,
last_updated timestamp,
part varchar(20) AS (JSON_UNQUOTE(query->"$.part")),
apikey varchar(45) AS (JSON_UNQUOTE(query->"$.key")),
etag varchar(64) AS (JSON_UNQUOTE(query->"$.etag")),
key ep_part_key_ndx (endpoint,apikey,part)
);
EOT;
const API_URL = "https://www.googleapis.com/youtube/v3/";
public function __destruct() {
$this->dbconn->close();
}
public function query_row($query) {
//echo("query: $query\n");
$result = $this->dbconn->query($query);
if ($result !== TRUE) { // success with no result set or failure
if ($result !== FALSE) { // success with result set
if ($this->dbconn->affected_rows > 0) {;
$obj = $result->fetch_object();
$obj->affected_rows = $this->dbconn->affected_rows;
$result->free();
} else {
$obj=TRUE;
}
return $obj;
} else { // success with no result set
return TRUE;
}
}
return FALSE;
}
public function init() {
global $mysql_server,$mysql_user,$mysql_password,$mysql_database;
$this->dbconn = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_database);
if ($this->dbconn->connect_errno) {
error_exit("Sorry, this website is experiencing problems.");
}
$obj = $this->query_row("SHOW TABLES LIKE '".self::TABLENAME."'");
if ($obj === TRUE) {
$this->query_row(sprintf(self::CREATE_TABLE,self::TABLENAME));
}
}
public function lookup($endpoint,$query) {
$jsonx = array();
foreach ($query as $key => $value) {
array_push($jsonx,"query->'\$.$key' = '$value'");
}
$query_string = "SELECT id,result,etag,unix_timestamp()-unix_timestamp(last_updated) as age from ".self::TABLENAME." ".
"WHERE endpoint = '".$endpoint."' and ".
"part = '".
$query['part'].
"' and ".
"apikey = '".
$query['key'].
"' and ".
join(' and ',$jsonx);
return $this->query_row($query_string);
}
public function sanitize(&$obj) {
foreach ($obj as $key => $val) {
$this->escape($obj[$key]);
}
}
public function escape(&$string) {
$string = $this->dbconn->escape_string($string);
}
public function query_api($endpoint,$query,$etag = FALSE) {
global $api_referer;
// URL encoding breaks the google API because it doesn't urldecode the query string
$url = self::API_URL.$endpoint."?";
foreach($query as $key => $value) {
$parms[] = $key."=".$value;
}
$url.=join('&',$parms);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Referer: '.$api_referer
];
if ($etag !== FALSE) $headers[]='If-None-Match: '.$etag;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($http_code == 304) return TRUE;
return $result;
}
public function update_cache($id,$newdata,$metadata_update = FALSE) {
$this->escape($newdata);
// timestamps only update when the data is different, kinda defeats the purpose of a cache
if ($metadata_update !== TRUE) {
$query_string = "UPDATE ".self::TABLENAME." set ".
"last_updated = NOW(), ".
"result = '".$newdata."' ".
"WHERE id = ".$id;
} else { // only update cache metadata if the contents are the same
$query_string = "UPDATE ".self::TABLENAME." set ".
"last_updated = NOW() ".
"WHERE id = ".$id;
}
return $this->query_row($query_string);
}
public function insert_cache($endpoint,$query,$newdata) {
$this->escape($newdata);
$query_string = "INSERT INTO ".self::TABLENAME." set ".
"endpoint = '".$endpoint."',".
"query = '".json_encode($query)."',".
"result = '".$newdata."'";
return $this->query_row($query_string);
}
public function get_cache($endpoint,$query,$age) {
$this->escape($endpoint);
$this->sanitize($query);
$result = $this->lookup($endpoint,$query);
if ($result === TRUE) {
$newdata = $this->query_api($endpoint,$query);
$this->insert_cache($endpoint,$query,$newdata);
return $newdata;
} else if ($result !== TRUE && $result->age > $age) {
$newdata = $this->query_api($endpoint,$query,$result->etag);
if ($newdata === TRUE) { // only metadata update
$this->update_cache($result->id,$newdata,TRUE);
$json=json_decode($result->result,true);
$json['age']=$result->age;
return json_encode($json);
} else {
$this->update_cache($result->id,$newdata);
return $newdata;
}
} else if ($result !== FALSE) {
return $result->result;
}
}
}
$cache = new CacheDb;
$cache->init();
function error_exit($msg) {
echo json_encode($msg)."\n";
exit;
}
if (isset($_GET['endpoint'])) {
$endpoint = filter_var($_GET['endpoint'],FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if ($age === false) {
error_exit(array("Error"=>"endpoint contains invalid characters"));
}
unset($_GET['endpoint']);
} else {
error_exit(array("Error"=>"you must specify an endpoint"));
}
if (isset($_GET['age'])) {
$cache_age = filter_var($_GET['age'], FILTER_SANITIZE_NUMBER_INT);
if ($cache_age === false) {
error_exit(array("Error"=>"age must be an integer > 0"));
} else if ($cache_age === 0) {
$cache_age = 3600;
}
unset($_GET['age']);
} else {
$cache_age = 3600;
}
$query_data = filter_var_array($_GET, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if ($query_data === false) {
error_exit(array("Error"=>"query is invalid"));
}
$result = $cache->get_cache($endpoint,$query_data,$cache_age);
//var_dump($result);
echo($result."\n");
?>