This repository was archived by the owner on Aug 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy patheg-api.php
More file actions
323 lines (280 loc) · 13.2 KB
/
eg-api.php
File metadata and controls
323 lines (280 loc) · 13.2 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
<?php
include('CPCMS.php');
require_once('utils.php');
require_once('config.php');
include('expungehelpers.php');
include('helpers/mail_helper.php');
include('helpers/api_validator.php');
include('helpers/loggers.php');
include('helpers/request_builder.php');
//initialize the response that will get sent back to requester
$response = array();
//set default response code:
http_response_code(404);
$request = request_builder();
// Log the request, but strip identifying info
$test_headers = $request;
error_log("Logging a request to eg-api.");
$test_headers['apikey'] = preg_replace('/./', 'x', $test_headers['apikey']);
$test_headers['personFirst'] = preg_replace('/(?!^)./','x',$test_headers['personFirst']);
$test_headers['personLast'] = preg_replace('/(?!^)./','x',$test_headers['personLast']);
$test_headers['personStreet'] = preg_replace('/(?!^)./','x',$test_headers['personStreet']);
$log_trail = "";
// Test if the quest is well formed.
if(malformedRequest($request)) {
http_response_code(400);
$response['results']['status'] = malformedRequest($request);
$log_trail .= "malformed request";
} elseif(!validAPIKey($request, $db)) {
http_response_code(401);
$response['results']['status'] = "Invalid request.";
$log_trail .= "invalid request";
} else {
$user_id = validAPIKey($request, $db);
http_response_code(200);
error_log("Starting to process a good response.");
$log_trail .= "valid request"; //build a string that shows how the request moved through the script.
//Return it at the end in write_to_resource_log()
// a cpcmsSearch flag can be set to true in the post request
// to trigger a cpcms search.
if (isset($request['cpcmsSearch']) && preg_match('/^(t|true|1)$/i', $request['cpcmsSearch'])===1){
$log_trail .= ",cpcmsSearch";
$urlPerson = getPersonFromPostOrSession($request);
$cpcms = new CPCMS($urlPerson['First'],$urlPerson['Last'], $urlPerson['DOB']);
$status = $cpcms->cpcmsSearch();
$statusMDJ = $cpcms->cpcmsSearch(true);
if (!preg_match("/0/",$status[0]) && !preg_match("/0/", $statusMDJ[0])) {
$response['results'] = "Your CPCMS search returned no results.";
} else {
//only integrate the summary information if we
// have a DOB; otherwise what is the point?
if (!empty($urlPerson['DOB'])) {
$cpcms->integrateSummaryInformation();
}
// We need an array of docket numbers, so we take the list of results
// and extract only the docket number from each.
$docketNums = array();
foreach (array_merge($cpcms->getResults(), $cpcms->getMDJResults()) as $result) {
$docketNums[] = $result[0];
};
// remove the cpcmsSearch variable from the POST vars and then pass them to
// a display funciton that will display all of the arrests as a webform, with all
// of the post vars re-posted as hidden variables. Also pass this filename as the
// form action location.
unset($request['cpcmsSearch']);
}
} // end of processing cpcmsSearch
error_log("Done processing cpcmsSearch");
$arrests = array(); //an array to hold Arrest objects
$arrestSummary = new ArrestSummary();
$urlPerson = getPersonFromPostOrSession($request);
$person = new Person($urlPerson['First'],
$urlPerson['Last'],
$urlPerson['SSN'],
$urlPerson['Street'],
$urlPerson['City'],
$urlPerson['State'],
$urlPerson['Zip']);
// TODO get rid of this?
getInfoFromGetVars($request); //this sets session variables based on the GET or
// POST variables 'docket', 'act5Regardless', 'expungeRegardless', and
// 'zipOnly'
$response['personFirst'] = $urlPerson['First'];
$response['personLast'] = $urlPerson['Last'];
$response['dob'] = $urlPerson['DOB'];
$attorney = new Attorney($user_id, $db);
error_log("Figured out the Attorney:");
error_log("Attorney " . $request['current_user'] . " is " . $user_id);
$docketFiles = $_FILES;
if (!isset($docketNums)) {
// If $docketNums wasn't set in CPCMS search, initialize it to an empty array.
$docketNums = array();
}
if (isset($request['docketNums'])) {
// Add any docket numbers passed in POST request to $docketnums.
// POST[docketnums] should be a comma-delimited string like "MC-12345,CP-34566"
$log_trail .= ",requested docket numbers";
$docketNumsRequest = filter_var($request['docketNums'], FILTER_SANITIZE_SPECIAL_CHARS);
foreach (explode(",",$docketNumsRequest) as $doc) {
if ($doc) { //Doc will be false if the filter fails.
array_push($docketNums, $doc);
}
}
$response['results']['dockets'] = $docketNums;
}
// doExpungements prints a table to the screen.
// combineArrests also prints to the screen.
// I only want to print a response object to the screen, so I put the
// the functions that print
// into an OutputBuffer to prevent that.
ob_start();
if (count($docketNums)>0) {
//if the cpcms search has been run and has found dockets
//or of docket numbers were sent with the request to the api
$docketFiles = CPCMS::downloadDockets($docketNums);
$arrests = parseDockets($tempFile, $pdftotext, $arrestSummary, $person, $docketFiles);
integrateSummaryInformation($arrests, $person, $arrestSummary, True);
//set $isAPI in integrateSummaryInformation() to True to prevent printing to screen
$arrests = combineArrests($arrests);
$response['results']['arrestCount'] = count($arrests);
# TODO Could add a function to insert a string of arrest information into $response.
# TODO Could also add a function to insert information about chargeObjects (child of Arrest)
}
$sealable = checkIfSealable($arrests);
$files=[];
error_log("beginning to create petitions, if requested.");
if (preg_match('/^(t|true|1)$/i', $request['createPetitions'])===1) {
$files = doExpungements($arrests, $templateDir, $dataDir, $person,
$attorney, $_SESSION['expungeRegardless'],
$db, $sealable);
//$response['results']['sealing'] = $parsed_results['sealing'];
$files[] = createOverview($arrests, $templateDir, $dataDir, $person, $sealable);
}//end of creating petitions if createPetitions was set.
ob_end_clean();
$parsed_results = parseArrests($arrests, $sealable, $person);
$response['results']['expungements_redactions'] = $parsed_results['expungements_redactions'];
// create the zip file. The $files array contains the petitions; it will be empty if createPetitions
// isn't set to 1 or t or true
$zipFile = zipFiles($files, $dataDir, $docketFiles,
uniqid($person->getFirst() . $person->getLast(), true) . "Expungements");
if (count($docketNums) > 0) {
$response['results']['expungeZip'] = basename($zipFile);
} else {
$response['results']['status'] = "Error. No dockets downloaded. It would be nice if this message were more helpful.";
}
// write everything to the DB as long as this wasn't a "test" upload.
// we determine test upload if a SSN is entered. If there is no SSN, we assume that
// there was no expungement either - it was just a test to see whether expungements were
// possible or a test of the generator itself by yours truly.
error_log("starting to write to db");
if (isset($urlPerson['SSN']) && $urlPerson['SSN'] != "") {
//error_log("writing to db:");
//error_log("arrests:");
//file_put_contents('php://stderr', print_r($arrests), TRUE);
//error_log("person");
//file_put_contents('php://stderr', print_r($person), TRUE);
//error_log("attorney");
//file_put_contents('php://stderr', print_r($attorney), TRUE);
writeExpungementsToDatabase($arrests, $person, $attorney, $db);
//error_log("wrote to db");
}
//error_log("cleaning up files");
cleanupFiles($files);
//error_log("done writing to db");
error_log("checking whether to email petitions.");
if (isset($request['emailPetitions']) && preg_match('/^(t|true|1)$/i', $request['emailPetitions'])===1){
$log_trail .= ",emailing results";
if (!(isset($request['createPetitions']) && preg_match('/^(t|true|1)$/i', $request['createPetitions'])===1)) {
$file_path = NULL;
if (isset($response['results']['expungeZip'])) {
unset($response['results']['expungeZip']);
}
} else {
$file_path = $response['results']['expungeZip'];
$path_parts = pathinfo($response['results']['expungeZip']);
$response['results']['expungeZip'] = $baseURL . "secureServe.php?serveFile=" . $path_parts['filename'];
}
//mailPetition($_REQUEST['current_user'], $_REQUEST['current_user'], $response, $file_path);
error_log("Mailing to " . mailDestination($request));
mailPetition(mailDestination($request), mailDestination($request), $response, $file_path);
} else {
error_log("emailPetitions was not set");
}
}// end of processing req from a valid user
error_log("Finished api request.");
if (isset($user_id)) {
writeToResourceLog($user_id,"eg-api.php",$log_trail);
} else {
writeToResourceLog(-1,"eg-api.php",$log_trail);
}
print_r(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES, 10));
function malformedRequest($request) {
// Given a dictionary $request
// Return false if there are no missing values
// but return a message if any of certain conditions are true.
// This takes advantage of the truthiness of php strings
// to supply a helpful message.
// apikey should get checked first for a complicated reason. The requestbuilder also
// checks if an apikey is missing, and will assume the request data was json if the api key
// was missing. So if the request was HTTP, but missing an apikey, $request will be based on
// the input json data, which is empty and has _no_ keys. Putting apikey key first here will
// tell the user that the api key is missing, which is accurate, and gives them the right instruction
// for correcting the issue.
if ( empty($request['apikey']) ) {
return "Key missing from request.";
}
if (empty($request['current_user'])) {
return "User email missing from request.";
}
if ( ($request['cpcmsSearch'] == 'false') && empty($request['docketNums']) ) {
return "If you do not wish to do a CPCMS search, then you must supply docket numbers.";
}
if ( !isset($request['createPetitions']) || ($request['createPetitions'] == '') ) {
return "Should I create petitions? Please include createPetitions=[0|1] in your request.";
}
return False;
};//End of well-formed request
function parseArrests($arrests, $sealable, $person) {
// Similar to createOverview, but without the microsoft word
$results = Array();
//print("\nParsing arrests.\n");
//print_r($arrests);
//print("\n Size of arrests: ");
//print(sizeof($arrests));
//print("\n");
if (sizeof($arrests) == 0) {
$results['expungements_redactions'] = ["none"];
} else {
$results['expungements_redactions'] = Array();
$results['sealing'] = Array();
foreach($arrests as $arrest) {
$thisArrest = Array();
$thisArrest['docket'] = htmlspecialchars(implode(", ", $arrest->getDocketNumber()), ENT_COMPAT, 'UTF-8');
$thisArrest['otn'] = htmlspecialchars($arrest->getOTN(), ENT_COMPAT, 'UTF-8');
$expType = "No expungement possible";
if ($arrest->isArrestRedaction()) {
$expType = "Partial Expungement";
}
if ($arrest->isArrestExpungement()) {
$expType = "Expungement";
}
if ($arrest->isArrestARDExpungement()) {
$expType = "ARD Expungement***";
}
if ($arrest->isArrestSummaryExpungement($arrests)) {
$expType = "Summary Expungement";
}
if ($arrest->isArrestOver70Expungement($arrests, $person)) {
$expType = "Expungement (over 70)";
}
// Ignoring act 5 sealing for now
$thisArrest['expungement_type'] = $expType;
$thisArrest['unpaid_costs'] = htmlspecialchars(number_format($arrest->getCostsTotal() - $arrest->getBailTotal(),2),ENT_COMPAT, 'UTF-8');
$thisArrest['bail'] = htmlspecialchars(number_format($arrest->getBailTotalTotal(),2), ENT_COMPAT, 'UTF-8');
$results['expungements_redactions'][] = $thisArrest;
if ($arrest->isArrestSealable()>0) {
//then iterate over all the charges
foreach ($arrest->getCharges() as $charge) {
$thisCharge = Array();
// check if the charge is a conviction and if it is sealable (non conviction charges get a 1)
if ( $charge->isConviction() && ($charge->isSealable() >0) ) {
$thisCharge['case_number'] = htmlspecialchars($arrest->getFirstDocketNumber(), ENT_COMPAT, 'UTF-8');
$thisCharge['charge_name'] = htmlspecialchars($charge->getChargeName(), ENT_COMPAT, 'UTF-8');
$thisCharge['code_section'] = htmlspecialchars($charge->getCodeSection(), ENT_COMPAT, 'UTF-8');
if ($charge->isSealable()==1) {
$thisCharge['sealable'] = "Yes";
} else {
$thisCharge['sealable'] = "No";
}
$thisCharge['additional_information'] = htmlspecialchars($charge->getSealablePercent(), ENT_COMPAT, 'UTF-8');
$results['sealing'][] = $thisCharge;
} // end processing if a charge is a conviction that is sealable
} //end loop over charges for an arrest
} // end of checking if arrest is sealable
}//end of processing arrests
}// end of processing results
//error_log("Returning response:");
//error_log("-----------");
return $results;
}//end of parseArrests
?>