-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.php
262 lines (249 loc) · 12 KB
/
api.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<?php
include "credentials.php";
header("Content-type: application/json");
function apiError($message, $code) {
http_response_code($code);
echo('{"Error":"'.$message.'","Code":'.$code.'}');
return;
}
function sendResponse($data, $code) {
http_response_code($code);
for ($i = 0; $i < count($data); ++$i) {
$data[$i] = get_object_vars($data[$i]);
}
$output = json_encode($data, JSON_NUMERIC_CHECK);
if ($output === false) {
apiError("JSON failed: " . json_last_error(), 500);
}
echo $output;
}
function dbSELECT($conn, $query, $class, $values = null) {
$stmt = $conn->prepare($query);
$stmt->execute($values);
$arr = $stmt->fetchAll(PDO::FETCH_CLASS, $class);
$stmt = null;
if (empty($arr)) {
apiError("Not Found.", 404);
}
sendResponse($arr, 200);
}
function recaptchaVerify($token) {
global $recaptchaSecretKey;
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = array("secret" => $recaptchaSecretKey, "response" => $token);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result,true);
}
class Hlaska {
public $id;
public $date;
public $content;
public $edited;
public $likes;
public $teacher;
public $likeOffset;
private $teacher_id;
private $teacher_firstName;
private $teacher_lastName;
private $teacherId;
function __construct() {
$this->teacher = [
"id" => $this->teacher_id,
"firstName" => $this->teacher_firstName,
"lastName" => $this->teacher_lastName
];
if ($this->date === null) {
$this->date = "0000-00-00";
}
}
}
class Teacher {
public $id;
public $firstName;
public $lastName;
}
$path = $_GET["path"];
if (strpos($path, '/v2.0') === 0) {
$version = 'v2.0';
$regexVersion = str_replace(".","\.", $version);
if ($_SERVER["REQUEST_METHOD"] !== "GET" && parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) !== $_SERVER["HTTP_HOST"]) {
apiError("Refusing non-GET request from unknown referer.", 400);
return;
}
try {
$options = [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_CLASS,
];
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password, $options);
}
catch(PDOException $e)
{
apiError("Could not connect to database.", 500);
return;
}
if (preg_match("/^\/".$regexVersion."\/hlasky\/?$/", $path)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "GET":
if (!isset($_GET["filterByTeacher"]) && !isset($_GET["filterByDate"])) {
dbSELECT($conn, "SELECT hlasky.*, t.firstName AS 'teacher_firstName', t.lastName AS 'teacher_lastName', t.id AS 'teacher_id', ((SELECT COUNT(*) FROM likes_by_user WHERE likes_by_user.hlaskaId = hlasky.id)+hlasky.likeOffset) AS likes FROM hlasky JOIN teachers t ON teacherId = t.id ORDER BY hlasky.id DESC", 'Hlaska');
} elseif (!isset($_GET["filterByDate"])) {
dbSELECT($conn, "SELECT hlasky.*, t.firstName AS 'teacher_firstName', t.lastName AS 'teacher_lastName', t.id AS 'teacher_id', ((SELECT COUNT(*) FROM likes_by_user WHERE likes_by_user.hlaskaId = hlasky.id)+hlasky.likeOffset) AS likes FROM hlasky JOIN teachers t ON teacherId = t.id WHERE hlasky.teacherId = :teacherId ORDER BY hlasky.id DESC", 'Hlaska', ["teacherId" => $_GET["filterByTeacher"]]);
} elseif (!isset($_GET["filterByTeacher"])) {
dbSELECT($conn, "SELECT hlasky.*, t.firstName AS 'teacher_firstName', t.lastName AS 'teacher_lastName', t.id AS 'teacher_id', ((SELECT COUNT(*) FROM likes_by_user WHERE likes_by_user.hlaskaId = hlasky.id)+hlasky.likeOffset) AS likes FROM hlasky JOIN teachers t ON teacherId = t.id WHERE hlasky.date = :date ORDER BY hlasky.id DESC", 'Hlaska', ["date" => $_GET["filterByDate"]]);
} else {
dbSELECT($conn, "SELECT hlasky.*, t.firstName AS 'teacher_firstName', t.lastName AS 'teacher_lastName', t.id AS 'teacher_id', ((SELECT COUNT(*) FROM likes_by_user WHERE likes_by_user.hlaskaId = hlasky.id)+hlasky.likeOffset) AS likes FROM hlasky JOIN teachers t ON teacherId = t.id WHERE hlasky.date = :date AND hlasky.teacherId = :teacherId ORDER BY hlasky.id DESC", 'Hlaska', ["date" => $_GET["filterByDate"], "teacherId" => $_GET["filterByTeacher"]]);
}
break;
case "POST":
$recaptchaResponse = recaptchaVerify(getallheaders()["g-recaptcha-response"]);
if ($recaptchaResponse["success"] && $recaptchaResponse["score"] > 0.1 && $recaptchaResponse["action"] === "addQuote") {
if (getallheaders()["x-password"] === $passcode) {
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);
$statement = $conn->prepare('INSERT INTO hlasky (teacherId, date, content) VALUES (:teacherId, :date, :content)');
$statement->execute([
'teacherId' => $input["teacher"],
'content' => $input["content"],
'date' => $input["date"]
]);
http_response_code(201);
echo('{"Success": true, "Code": 201}');
} else {
apiError("Unauthorized.", 401);
}
} else {
apiError("ReCaptcha failed.", 429);
}
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else if (preg_match("/^\/".$regexVersion."\/hlasky\/(\d+)\/?$/", $path, $matches)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "GET":
$hlaskaId = $matches[1];
dbSELECT($conn,"SELECT hlasky.*, t.firstName AS 'teacher_firstName', t.lastName AS 'teacher_lastName', t.id AS 'teacher_id', ((SELECT COUNT(*) FROM likes_by_user WHERE likes_by_user.hlaskaId = hlasky.id)+hlasky.likeOffset) AS likes FROM hlasky JOIN teachers t ON teacherId = t.id WHERE hlasky.id = :id ORDER BY hlasky.id DESC", 'Hlaska', ["id" => $hlaskaId]);
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else if (preg_match("/^\/".$regexVersion."\/hlasky\/(\d+)\/likes\/?$/", $path, $matches)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "POST":
$stmt = $conn->prepare("SELECT * FROM users WHERE userId = :userId");
$stmt->execute(["userId" => $_COOKIE["userId"]]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($arr)) {
apiError("User does not exist.", 404);
return;
}
$stmt = $conn->prepare("SELECT * FROM hlasky WHERE id = :hlaskaId");
$stmt->execute(["hlaskaId" => $matches[1]]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($arr)) {
apiError("Hlaska does not exist.", 404);
return;
}
try {
$stmt = $conn->prepare("INSERT INTO likes_by_user (userId, hlaskaId) VALUES (:userId,:hlaskaId)");
$stmt->execute([
"userId" => $_COOKIE["userId"],
"hlaskaId" => $matches[1]
]);
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
apiError("Already liked.", 409);
return;
} else {
throw $e;
}
}
http_response_code(201);
echo('{"Success": true, "Code": 201}');
break;
case "DELETE":
$stmt = $conn->prepare("SELECT * FROM users WHERE userId = :userId");
$stmt->execute(["userId" => $_COOKIE["userId"]]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($arr)) {
apiError("User does not exist.", 404);
return;
}
$stmt = $conn->prepare("SELECT * FROM likes_by_user WHERE hlaskaId = :hlaskaId AND userId = :userId");
$stmt->execute([
"userId" => $_COOKIE["userId"],
"hlaskaId" => $matches[1]
]);
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($arr)) {
apiError("Not yet liked.", 409);
return;
}
$stmt = $conn->prepare("DELETE FROM likes_by_user WHERE hlaskaId = :hlaskaId AND userId = :userId");
$stmt->execute([
"userId" => $_COOKIE["userId"],
"hlaskaId" => $matches[1]
]);
http_response_code(201);
echo('{"Success": true, "Code": 201}');
break;
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else if (preg_match("/^\/".$regexVersion."\/users\/([0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12})\/likes\/?$/", $path, $matches)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "GET":
$stmt = $conn->prepare("SELECT hlaskaId FROM likes_by_user WHERE userId = :userId");
$stmt->execute(["userId" => $matches[1]]);
$arr = $stmt->fetchAll(PDO::FETCH_COLUMN);
http_response_code(200);
echo(json_encode($arr, JSON_NUMERIC_CHECK));
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else if (preg_match("/^\/".$regexVersion."\/users\/?$/", $path)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "POST":
$recaptchaResponse = recaptchaVerify(getallheaders()["g-recaptcha-response"]);
if ($recaptchaResponse["success"] && $recaptchaResponse["score"] > 0.5 && $recaptchaResponse["action"] === "newUser") {
$stmt = $conn->prepare("SELECT UUID()");
$stmt->execute();
$uuid = $stmt->fetch(PDO::FETCH_NUM)[0];
$stmt = $conn->prepare("INSERT INTO users (userId) VALUES (:uuid)");
$stmt->execute(["uuid" => $uuid]);
setcookie("userId", $uuid, 2147483647, "/");
http_response_code(201);
echo('{"Success": true, "Code": 201}');
} else {
apiError("ReCaptcha failed.", 429);
}
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else if (preg_match("/^\/".$regexVersion."\/teachers\/?$/", $path)) {
switch ($_SERVER["REQUEST_METHOD"]) {
case "GET":
dbSELECT($conn, 'SELECT * FROM teachers ORDER BY lastName, firstName','Teacher');
break;
default:
apiError("Method '".$_SERVER["REQUEST_METHOD"]."' Not Allowed on path '".$path."'.", 405);
}
} else {
apiError("Endpoint Not Found.", 404);
}
} else {
apiError("Version Not Found.", 404);
}