-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsaveJSON.php
More file actions
113 lines (94 loc) · 2.59 KB
/
saveJSON.php
File metadata and controls
113 lines (94 loc) · 2.59 KB
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
<?php
/**
* Created by PhpStorm.
* User: Matt Jaquiery
* Date: 19/03/2019
* Time: 10:28
*
*/
/*
The $_POST[] array will contain a JSON string which decomposes into:
{
metadata:
studyId: study identifier (becomes eid below)
studyVersion: study version
idCode: participant id
data:
JSON string to write to file
privateData:
JSON string to write to a protected file
}
Data are saved in the ./data/[public|private]/raw directory as specified in the incoming metadata.
An JSON string is returned with the following properties:
{
error: description of any error which occurred,
code: response code,
content: message
}
*/
//phpinfo();
error_reporting(0);
//ini_set("display_errors", true);
ini_set("auto_detect_line_endings", true);
$log = "";
function sulk($err, $code) {
$out = array(
"error" => $err,
"code" => $code,
);
die(json_encode($out));
}
// Unpack POST data
$json = json_decode(file_get_contents("php://input"), true);
$meta = $json["metadata"];
$data = $json["data"];
$privateData = $json["privateData"];
$eid = (string) $meta["studyId"];
$version = (string) $meta["studyVersion"];
$version = str_replace(".", "-", $version);
$pid = $meta["idCode"];
// Check input is valid
function is_alphanumeric($str, $allowHyphen = false) {
if($allowHyphen)
return (bool) preg_match('/^[0-9a-z\-]+$/i', $str);
return (bool) preg_match('/^[0-9a-z]+$/i', $str);
}
if(!is_alphanumeric($version, true))
sulk("Invalid version format '$version'.", 403);
if(!is_alphanumeric($pid))
sulk("Invalid id '$pid'.", 403);
if(!is_alphanumeric($eid, true)) {
sulk("Invalid studyId '$eid'.", 403);
}
const PATH = "./data/";
$prefix = $eid . "_v" . $version;
$body = date('Y-m-d_H-i-s') . "_" . $prefix . "_" . $pid;
foreach(array("private", "public") as $privacy) {
$filename = PATH . $privacy . "/raw/" . $body . ".json";
if($privacy == "private")
$write = $privateData;
else
$write = $data;
$empty = true;
foreach(json_decode($write) as $x)
if(count($x)) {
$empty = false;
break;
}
if(!$empty) {
if (!file_exists($filename)) {
if (($handle = fopen($filename, "wb+")) !== false) {
fwrite($handle, $write);
fclose($handle);
} else
sulk("Unable to create file.", 500);
} else
sulk("File already exists!", 500);
}
}
// Send back the all clear
die(json_encode(array(
"error" => "",
"code" => 200,
"content" => "Data saved successfully."
)));