Skip to content

Commit 51adf82

Browse files
committed
send pure json and csv files
1 parent 262706b commit 51adf82

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/server/api.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1568,7 +1568,7 @@ function meta_delphi() {
15681568

15691569
if(isset($_REQUEST['format']) && $_REQUEST['format'] == "csv") {
15701570
send_csv($data);
1571-
} if(isset($_REQUEST['format']) && $_REQUEST['format'] == "json") {
1571+
} else if(isset($_REQUEST['format']) && $_REQUEST['format'] == "json") {
15721572
send_json($data);
15731573
} else {
15741574
// send the response as a json object

src/server/api_helpers.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,13 +367,55 @@ function record_analytics($source, $data) {
367367
mysqli_query($dbh, "INSERT INTO `api_analytics` (`datetime`, `ip`, `ua`, `source`, `result`, `num_rows`) VALUES (now(), '{$ip}', '{$ua}', '{$source}', {$result}, {$num_rows})");
368368
}
369369

370+
function send_status(&$data) {
371+
if (intval($data["result"]) > 0 || intval($data["result"]) == -2) {
372+
return FALSE;
373+
}
374+
if ($data["message"] == 'database error') {
375+
http_response_code(500);
376+
} else if ($data["message"] == 'unauthenticated') {
377+
http_response_code(401);
378+
} else {
379+
http_response_code(400); // bad request
380+
}
381+
header('Content-Type: application/json');
382+
echo json_encode($data);
383+
return TRUE;
384+
}
370385

371386
function send_csv(&$data) {
387+
if (send_status($data)) {
388+
return;
389+
}
390+
header('Content-Type: text/csv');
391+
header('Content-Disposition: attachment; filename=epidata.csv');
392+
393+
if (intval(data["result"]) == -2) {
394+
// empty
395+
return;
396+
}
372397

398+
$rows = $data["epidata"];
399+
$headers = array_keys($rows[0]);
400+
$out = fopen('php://output', 'w');
401+
fputcsv($out, $headers);
402+
foreach ($rows as $row) {
403+
fputcsv($out, $row);
404+
}
405+
fclose($out);
373406
}
374407

375408
function send_json(&$data) {
409+
if (send_status($data)) {
410+
return;
411+
}
412+
header('Content-Type: application/json');
376413

414+
if (intval($data["result"]) == -2) {
415+
echo json_encode(array());
416+
} else {
417+
echo json_encode($data["epidata"]);
418+
}
377419
}
378420

379421
?>

0 commit comments

Comments
 (0)