-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapi.php
92 lines (80 loc) · 2.74 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
<?php
require_once('config.php');
require_once('vendor/autoload.php');
require_once('utilities.php');
require_once('ChromePhp.php');
require_once('mongo.php'); // Loading our MongoDB wrapper
// Generates a new invitation ID using
// the same algorithm as Parse.
function newObjectId ($size) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .
'abcdefghijklmnopqrstuvwxyz' .
'0123456789';
$objectId = '';
$bytes = random_bytes($size);
for ($i = 0; $i < strlen($bytes); ++$i) {
$index = unpack('C', $bytes[$i])[1] % strlen($chars);
$objectId .= $chars[$index];
}
return $objectId;
}
try {
// Initialize library
$mongo = new MongoInvoice();
switch (get_parameter('type')) {
// Returns information of the invoice that has given invitation ID
case 'get':
$res = $mongo->get(get_parameter('invID'));
die(json_encode($res));
break;
// Creates a new invoice with information from GET parameters
case 'create':
$invId = newObjectId(10);
$input = json_decode(file_get_contents('php://input'));
$res = $mongo->save($invId, $input->invoice);
if ($res['ok']) {
die(json_encode([ 'invId' => $invId ]));
}
if ($isDevelopment) {
die(json_encode(['error' => 'Failed to create new object, with error message: ' + $res['errmsg']]));
} else {
die(json_encode(['error' => 'Failed to create new object']));
}
break;
// Saves receiver and sender mail addresses to database
case 'save_email':
$input = json_decode(file_get_contents('php://input'));
$res = $mongo->save_email($input);
$invId = $res['invId'];
// Check if invoice inserted to MongoDB successfully
if ($res['ok']) {
die(json_encode([ 'invId' => $invId ]));
}
if ($isDevelopment) {
die(json_encode(['error' => 'Failed to create new object, with error message: ' + $res['errmsg']]));
} else {
die(json_encode(['error' => 'Failed to create new object']));
}
break;
}
// Error Handling
// Error messages are hidden on production mode but printed out on development mode
} catch ( MongoConnectionException $e ) {
if ($isDevelopment) {
die(json_encode(['error' => 'Error connecting to MongoDB server: ' + $e->getMessage()]));
} else {
die(json_encode(['error' => 'Failed to create new object']));
}
} catch ( MongoException $e ) {
if ($isDevelopment) {
die(json_encode(['error' => 'Mongo Error: ' . $e->getMessage()]));
} else {
die(json_encode(['error' => 'Failed to create new object']));
}
} catch ( Exception $e ) {
if ($isDevelopment) {
die(json_encode(['error' => 'Error: ' . $e->getMessage()]));
} else {
die(json_encode(['error' => 'Failed to create new object']));
}
}