Browse Source

Added backend code to repo

Víctor Hernández 3 years ago
parent
commit
274b72e9f2

+ 20
- 0
Backend/config.php View File

@@ -0,0 +1,20 @@
1
+<?php 
2
+
3
+$TREFFLE_BASE_URL = "https://trefle.io";
4
+$TREFFLE_LIST_PATH = "/api/v1/plants";
5
+$TREFFLE_SEARCH_PATH = "/api/v1/plants/search";
6
+$TREFFLE_TOKEN = "hg6M-l4XhrgVgn2A-qZC6KKMrVPMUuCffVfDgDPtc0I";
7
+
8
+$DB_HOST = "localhost";
9
+$DB_USER = "Floradex";
10
+$DB_PASSWORD = "13CUdcMOXiybeZuj";
11
+$DB_NAME = "Floradex";
12
+
13
+$connection = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
14
+
15
+if ($connection->connect_errno) {
16
+    echo "Failed to connect to MySQL: " . $connection->connect_error;
17
+    exit();
18
+}
19
+
20
+$connection->set_charset('utf8');

+ 179
- 0
Backend/listFlowers.php View File

@@ -0,0 +1,179 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "GET") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports GET requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get user input
15
+$userID = isset($_GET['user_id']) ? $_GET['user_id'] : '';
16
+$q = isset($_GET['q']) ? $_GET['q'] : '';
17
+$page = isset($_GET['page']) ? $_GET['page'] : '';
18
+$edible = isset($_GET['edible']) ? $_GET['edible'] : '';
19
+$vegetable = isset($_GET['vegetable']) ? $_GET['vegetable'] : '';
20
+$scientificName = isset($_GET['scientific_name']) ? $_GET['scientific_name'] : '';
21
+$growthMonths = isset($_GET['growth_months']) ? $_GET['growth_months'] : '';
22
+$bloomMonths = isset($_GET['bloom_months']) ? $_GET['bloom_months'] : '';
23
+$color = isset($_GET['flower_color']) ? $_GET['flower_color'] : '';
24
+
25
+
26
+// Clean user input
27
+$userID = $connection->real_escape_string($userID);
28
+
29
+
30
+function prepareQueryParams($q = '', $edible = '', $vegetable = '', $scientificName = '', $growthMonths = '', $bloomMonths = '', $color = '', $page = '') {
31
+
32
+    // QUERY PARAMETERS
33
+    // - q: String
34
+    // - page: Int
35
+    // - edible: Bool
36
+    // - vegetable: Bool
37
+    // - scientific_name: String
38
+    // - growth_months: Int
39
+    // - bloom_months: Int
40
+
41
+    global $TREFFLE_TOKEN;
42
+
43
+    // Define preliminar round of params
44
+    $queryParams = array(
45
+        "token" => $TREFFLE_TOKEN,
46
+        "page" => $page ? $page : '1',
47
+        "filter[edible]" => $edible ? $edible : 'false',
48
+        "filter[vegetable]" => $vegetable ? $vegetable : 'false',
49
+    );
50
+
51
+
52
+    // Set the rest of the params
53
+    if($q) {
54
+        $queryParams['q'] = $q;
55
+    }
56
+
57
+    if($scientificName) {
58
+        $queryParams['filter[scientific_name]'] = $scientificName;
59
+    }
60
+
61
+    if($growthMonths) {
62
+        $queryParams['filter[growth_months]'] = $growthMonths;
63
+    }
64
+
65
+    if($bloomMonths) {
66
+        $queryParams['filter[bloom_months]'] = $bloomMonths;
67
+    }
68
+    
69
+    if($color) {
70
+        $queryParams['filter[flower_color]'] = $color;
71
+    }
72
+
73
+    return $queryParams;
74
+
75
+}
76
+
77
+
78
+function callAPI($queryParams) {
79
+
80
+    global $TREFFLE_BASE_URL, $TREFFLE_LIST_PATH, $TREFFLE_SEARCH_PATH;
81
+
82
+    if(isset($queryParams['q']) && $queryParams['q'] != '') {
83
+        $endpoint = $TREFFLE_BASE_URL . $TREFFLE_SEARCH_PATH;
84
+    } else {
85
+        $endpoint = $TREFFLE_BASE_URL . $TREFFLE_LIST_PATH;
86
+    }
87
+    
88
+    $curl = curl_init();
89
+    $url = sprintf("%s?%s", $endpoint, http_build_query($queryParams));
90
+    curl_setopt($curl, CURLOPT_URL, $url);
91
+    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
92
+
93
+    $response = curl_exec($curl);
94
+    $http_response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
95
+    
96
+    curl_close($curl);
97
+
98
+    return array("data" => json_decode($response), "code" => $http_response_code);
99
+    
100
+}
101
+
102
+
103
+function listFlowers($userID, $q = '', $edible = '', $vegetable = '', $scientificName = '', $growthMonths = '', $bloomMonths = '', $color = '', $page = '') {
104
+
105
+    if ($userID == '') {
106
+        http_response_code(400); // use appropriate status code
107
+        echo json_encode(array("error" => "Field 'user_id' is required"));
108
+        return;
109
+    }
110
+
111
+    global $connection;
112
+
113
+    $query = "SELECT * 
114
+                FROM UserHistory AS H
115
+                WHERE H.user_id = '$userID';";
116
+
117
+    if ($result = $connection->query($query)) {
118
+
119
+
120
+        // Query API
121
+        $queryParams = prepareQueryParams($q, $edible, $vegetable, $scientificName, $growthMonths, $bloomMonths, $color, $page);
122
+        $apiOutput = callAPI($queryParams);
123
+        $data = $apiOutput['data'];
124
+        $code = $apiOutput['code'];
125
+
126
+
127
+        // Handle API errors        
128
+        if ($code >= 300 || $code < 200) {
129
+            http_response_code(500);
130
+            echo json_encode(array("error" => "Unknown error occurred with Treffle API (Code: $code)"));
131
+            return;
132
+        } elseif (isset($data->error) && $data->error == "true") {
133
+            http_reponse_code(400);
134
+            echo json_encode(array("error" => isset($data->messages) ? $data->messages : $data->message));
135
+            return;
136
+        }
137
+
138
+
139
+        // Extract flowers
140
+        $flowers = $data->data;
141
+
142
+        
143
+        // Initialize all both fields to false for all flowers
144
+        foreach($flowers as $f) {
145
+            $f->isFavorite = false;
146
+            $f->hasBeenFound = false;
147
+        }       
148
+
149
+
150
+        // Loop through each "favorited"/"marked" flower and update accordingly
151
+        // NOTE: WOULD'VE BEEN EASIER IF F WERE A DICT :(
152
+        while($row = $result->fetch_assoc()) {
153
+            foreach($flowers as $f) {
154
+                if($f->id == $row['flower_id']) {
155
+                    $f->isFavorite = $row['in_wishlist'] == "1" ? true : false;
156
+                    $f->hasBeenFound = $row['has_been_found'] == "1" ? true : false;
157
+                }
158
+            }
159
+        }
160
+        
161
+        
162
+        // Return response
163
+        http_response_code(200);
164
+        $response = new stdClass;
165
+        $response->data = $flowers;
166
+        $response->links = $data->links;
167
+        $response->meta = $data->meta;
168
+        echo json_encode($response);
169
+
170
+
171
+    } else {
172
+        http_response_code(500); // use appropriate status code
173
+        echo json_encode(array("error" => $connection->error));
174
+    }
175
+
176
+}
177
+
178
+
179
+listFlowers($userID, $q, $edible, $vegetable, $scientificName, $growthMonths, $bloomMonths, $color, $page);

+ 70
- 0
Backend/login.php View File

@@ -0,0 +1,70 @@
1
+<?php 
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$email = isset($data->email) ? $data->email : '';
18
+$password = isset($data->password) ? $data->password : '';
19
+
20
+
21
+// Clean user input
22
+$email = $connection->real_escape_string($email);
23
+$password = $connection->real_escape_string($password);
24
+
25
+
26
+function Login($email, $password) {
27
+
28
+    if ($email === '' || $password === '') {
29
+        http_response_code(400); // use appropriate status
30
+        echo json_encode(array("error" => "Fields 'email' and 'password' are required"));
31
+        return;
32
+    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
33
+        http_response_code(400);
34
+        echo json_encode(array("error" => "Invalid email '$email'"));
35
+        return;
36
+    }
37
+
38
+    global $connection;
39
+    $passwordHash = md5($password);
40
+
41
+    $query = "SELECT * 
42
+                FROM UserData U
43
+                WHERE U.email = '$email'
44
+                AND U.password = '$passwordHash'";
45
+    
46
+    if ($result = $connection->query($query)) {
47
+        if ($row = $result->fetch_object()) {
48
+            
49
+            $user = array(
50
+                "id" => (int) $row->id,
51
+                "username" => $row->username,
52
+                "email" => $row->email,
53
+            );      
54
+            
55
+            http_response_code(200);
56
+            echo json_encode($user, JSON_UNESCAPED_UNICODE);
57
+            
58
+        } else {
59
+            http_response_code(400); // use appropriate status code
60
+            echo json_encode(array("error" => "No user with given credentials"));
61
+        }
62
+    } else {
63
+        http_response_code(500); // use appropriate status code
64
+        echo json_encode(array("error" => $connection->error));
65
+    }
66
+
67
+}
68
+
69
+// mail("vhernandezcastro@gmail.com", "test_login_android", json_encode($data));
70
+Login($email, $password);

+ 72
- 0
Backend/putFavoriteFlower.php View File

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$userID = isset($data->user_id) ? $data->user_id : '';
18
+$flowerID = isset($data->flower_id) ? $data->flower_id : '';
19
+
20
+
21
+// Clean user input
22
+$flowerID = $connection->real_escape_string($flowerID);
23
+$userID = $connection->real_escape_string($userID);
24
+
25
+
26
+function putFavoriteFlower($userID, $flowerID) {
27
+
28
+    if ($userID == '' || $flowerID == '') {
29
+        http_response_code(400); // use appropriate status code
30
+        echo json_encode(array("error" => "Fields 'user_id' and 'flower_id' are requried"));
31
+        return;
32
+    }
33
+
34
+    global $connection;
35
+    
36
+    $query = "SELECT * FROM UserHistory AS H WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
37
+    
38
+    if ($result = $connection->query($query)) {
39
+        if ($result->num_rows > 0) {
40
+        
41
+            $query = "UPDATE UserHistory AS H SET H.in_wishlist = 1 WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
42
+            
43
+            if ($connection->query($query)) {
44
+                http_response_code(200);
45
+            } else {
46
+                http_response_code(500); // use appropriate status code
47
+                echo json_encode(array("error" => $connection->error));
48
+            }
49
+        
50
+        } else {
51
+        
52
+            $query = "INSERT INTO UserHistory (`user_id`, `flower_id`, `in_wishlist`, `has_been_found`) VALUES ('$userID', '$flowerID', 1, 0);";
53
+
54
+            if ($connection->query($query)) {
55
+                http_response_code(200);
56
+            } else {
57
+                http_response_code(500); // use appropriate status code
58
+                echo json_encode(array("error" => $connection->error));
59
+            }
60
+            
61
+        }
62
+    } else {
63
+        http_response_code(500); // use appropriate status code
64
+        echo json_encode(array("error" => $connection->error));
65
+    }
66
+
67
+
68
+
69
+}
70
+
71
+
72
+putFavoriteFlower($userID, $flowerID);

+ 72
- 0
Backend/putFoundFlower.php View File

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$userID = isset($data->user_id) ? $data->user_id : '';
18
+$flowerID = isset($data->flower_id) ? $data->flower_id : '';
19
+
20
+
21
+// Clean user input
22
+$flowerID = $connection->real_escape_string($flowerID);
23
+$userID = $connection->real_escape_string($userID);
24
+
25
+
26
+function putFoundFlower($userID, $flowerID) {
27
+
28
+    if ($userID == '' || $flowerID == '') {
29
+        http_response_code(400); // use appropriate status code
30
+        echo json_encode(array("error" => "Fields 'user_id' and 'flower_id' are requried"));
31
+        return;
32
+    }
33
+
34
+    global $connection;
35
+    
36
+    $query = "SELECT * FROM UserHistory AS H WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
37
+    
38
+    if ($result = $connection->query($query)) {
39
+        if ($result->num_rows > 0) {
40
+        
41
+            $query = "UPDATE UserHistory AS H SET H.has_been_found = 1 WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
42
+            
43
+            if ($connection->query($query)) {
44
+                http_response_code(200);
45
+            } else {
46
+                http_response_code(500); // use appropriate status code
47
+                echo json_encode(array("error" => $connection->error));
48
+            }
49
+        
50
+        } else {
51
+        
52
+            $query = "INSERT INTO UserHistory (`user_id`, `flower_id`, `in_wishlist`, `has_been_found`) VALUES ('$userID', '$flowerID', 0, 1);";
53
+
54
+            if ($connection->query($query)) {
55
+                http_response_code(200);
56
+            } else {
57
+                http_response_code(500); // use appropriate status code
58
+                echo json_encode(array("error" => $connection->error));
59
+            }
60
+            
61
+        }
62
+    } else {
63
+        http_response_code(500); // use appropriate status code
64
+        echo json_encode(array("error" => $connection->error));
65
+    }
66
+
67
+
68
+
69
+}
70
+
71
+
72
+putFoundFlower($userID, $flowerID);

+ 64
- 0
Backend/removeFavoriteFlower.php View File

@@ -0,0 +1,64 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$userID = isset($data->user_id) ? $data->user_id : '';
18
+$flowerID = isset($data->flower_id) ? $data->flower_id : '';
19
+
20
+
21
+// Clean user input
22
+$flowerID = $connection->real_escape_string($flowerID);
23
+$userID = $connection->real_escape_string($userID);
24
+
25
+
26
+function removeFavoriteFlower($userID, $flowerID) {
27
+
28
+    if ($userID == '' || $flowerID == '') {
29
+        http_response_code(400); // use appropriate status code
30
+        echo json_encode(array("error" => "Fields 'user_id' and 'flower_id' are requried"));
31
+        return;
32
+    }
33
+
34
+    global $connection;
35
+    
36
+    $query = "SELECT * FROM UserHistory AS H WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
37
+    
38
+    if ($result = $connection->query($query)) {
39
+        if ($result->num_rows > 0) {
40
+        
41
+            $query = "UPDATE UserHistory AS H SET H.in_wishlist = 0 WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
42
+            
43
+            if ($connection->query($query)) {
44
+                http_response_code(200);
45
+            } else {
46
+                http_response_code(500); // use appropriate status code
47
+                echo json_encode(array("error" => $connection->error));
48
+            }
49
+        
50
+        } else {
51
+        
52
+            // Theres nothing to remove, since it doesn't exist
53
+            http_response_code(200);
54
+            
55
+        }
56
+    } else {
57
+        http_response_code(500); // use appropriate status code
58
+        echo json_encode(array("error" => $connection->error));
59
+    }
60
+
61
+}
62
+
63
+// mail("vhernandezcastro@gmail.com", "test_remove_favorite_android", json_encode($data));
64
+removeFavoriteFlower($userID, $flowerID);

+ 64
- 0
Backend/removeFoundFlower.php View File

@@ -0,0 +1,64 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$userID = isset($data->user_id) ? $data->user_id : '';
18
+$flowerID = isset($data->flower_id) ? $data->flower_id : '';
19
+
20
+
21
+// Clean user input
22
+$flowerID = $connection->real_escape_string($flowerID);
23
+$userID = $connection->real_escape_string($userID);
24
+
25
+
26
+function removeFoundFlower($userID, $flowerID) {
27
+
28
+    if ($userID == '' || $flowerID == '') {
29
+        http_response_code(400); // use appropriate status code
30
+        echo json_encode(array("error" => "Fields 'user_id' and 'flower_id' are requried"));
31
+        return;
32
+    }
33
+
34
+    global $connection;
35
+    
36
+    $query = "SELECT * FROM UserHistory AS H WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
37
+    
38
+    if ($result = $connection->query($query)) {
39
+        if ($result->num_rows > 0) {
40
+        
41
+            $query = "UPDATE UserHistory AS H SET H.has_been_found = 0 WHERE H.user_id = '$userID' AND H.flower_id = '$flowerID';";
42
+            
43
+            if ($connection->query($query)) {
44
+                http_response_code(200);
45
+            } else {
46
+                http_response_code(500); // use appropriate status code
47
+                echo json_encode(array("error" => $connection->error));
48
+            }
49
+        
50
+        } else {
51
+        
52
+            // Theres nothing to remove, since it doesn't exist
53
+            http_response_code(200);
54
+            
55
+        }
56
+    } else {
57
+        http_response_code(500); // use appropriate status code
58
+        echo json_encode(array("error" => $connection->error));
59
+    }
60
+
61
+}
62
+
63
+// mail("vhernandezcastro@gmail.com", "test_remove_favorite_android", json_encode($data));
64
+removeFoundFlower($userID, $flowerID);

+ 67
- 0
Backend/signup.php View File

@@ -0,0 +1,67 @@
1
+<?php
2
+
3
+require_once('config.php');
4
+
5
+
6
+// Filter unsupported HTTP requests
7
+if ($_SERVER["REQUEST_METHOD"] !== "POST") {
8
+    http_response_code(400); // use appropriate status
9
+    echo json_encode(array("error" => "Endpoint only supports POST requests"));
10
+    exit();
11
+}
12
+
13
+
14
+// Get input
15
+$json = file_get_contents('php://input');
16
+$data = json_decode($json);
17
+$username = isset($data->username) ? $data->username : '';
18
+$email = isset($data->email) ? $data->email : '';
19
+$password = isset($data->password) ? $data->password : '';
20
+
21
+
22
+// Clean user input
23
+$username = $connection->real_escape_string($username);
24
+$password = $connection->real_escape_string($password);
25
+$email = $connection->real_escape_string($email);
26
+
27
+
28
+function SignUp($username, $email, $password) {
29
+    
30
+    if ($username === '' || $password === '' || $email === '') {
31
+        http_response_code(400); // use appropriate status
32
+        echo json_encode(array("error" => "Fields 'username', 'email', and 'password' are required"));
33
+        return;
34
+    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
35
+        http_response_code(400);
36
+        echo json_encode(array("error" => "Invalid email '$email'"));
37
+        return;
38
+    }
39
+    
40
+    global $connection;
41
+    $passwordHash = md5($password);
42
+
43
+    $query = "INSERT INTO `UserData`
44
+                (`username`, `email`, `password`) 
45
+                VALUES
46
+                ('$username', '$email', '$passwordHash')";
47
+ 
48
+    if ($connection->query($query)) {
49
+        
50
+        $user = array(
51
+            "id" => (int) $connection->insert_id,
52
+            "username" => $username,
53
+            "email" => $email,
54
+        );
55
+        
56
+        http_response_code(200);
57
+        echo json_encode($user, JSON_UNESCAPED_UNICODE);
58
+        
59
+    } else {
60
+        http_response_code(500); // use appropriate status
61
+        echo json_encode(array("error" => $connection->error));
62
+    }
63
+
64
+}
65
+
66
+// mail("vhernandezcastro@gmail.com", "test_signup_android", json_encode($data));
67
+SignUp($username, $email, $password);