@@ -367,13 +367,55 @@ function record_analytics($source, $data) {
367
367
mysqli_query ($ dbh , "INSERT INTO `api_analytics` (`datetime`, `ip`, `ua`, `source`, `result`, `num_rows`) VALUES (now(), ' {$ ip }', ' {$ ua }', ' {$ source }', {$ result }, {$ num_rows }) " );
368
368
}
369
369
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
+ }
370
385
371
386
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
+ }
372
397
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 );
373
406
}
374
407
375
408
function send_json (&$ data ) {
409
+ if (send_status ($ data )) {
410
+ return ;
411
+ }
412
+ header ('Content-Type: application/json ' );
376
413
414
+ if (intval ($ data ["result " ]) == -2 ) {
415
+ echo json_encode (array ());
416
+ } else {
417
+ echo json_encode ($ data ["epidata " ]);
418
+ }
377
419
}
378
420
379
421
?>
0 commit comments