source: src/webservice/htdocs/SiWeather/Webservice/WebserviceApi.php@ 7271978

Last change on this file since 7271978 was 7271978, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago

WebserviceApi::stationsRegister checks whether uuid_create is available and if not returns an error message

  • Property mode set to 100644
File size: 9.0 KB
Line 
1<?php
2/*
3 Copyright (C) 2015 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 MA 02110-1301 USA.
19*/
20
21namespace SiWeather\Webservice;
22
23require(__DIR__ ."/../../inc/envsetup.php");
24
25/**
26 * @brief Implementation of the Webservice API
27 *
28 * @module WebserviceAPI
29 */
30class WebserviceApi {
31 /**
32 * @brief Handles the stations (list) REST requests
33 */
34 public static function stations(){
35 $stations = Array();
36
37 $db = new DatabaseHandler();
38 if(!$db->connect()){
39 echo json_encode
40 (
41 [
42 "result" => "failed",
43 "message" => "Could not connect to the database",
44 ]
45 );
46 return;
47 }
48 $db->exec("BEGIN");
49
50 $sqlStatement = $db->prepare("SELECT stations.uuid as uuid, stations.name as name, X(stations.location) as longitude, Y(stations.location) as latitude, cities.name as city FROM stations, cities WHERE stations.city=cities.id");
51 if(!$sqlStatement){
52 $db->exec("ROLLBACK");
53 echo json_encode
54 (
55 [
56 "result" => "failed",
57 "message" => "Could not fetch stations from database",
58 ]
59 );
60 return;
61 }
62 $result = $sqlStatement->execute();
63 while($row = $result->fetchArray()){
64 $station = Array();
65 $station["uuid"] = $row["uuid"];
66 $station["name"] = $row["name"];
67 $station["longitude"] = $row["longitude"];
68 $station["latitude"] = $row["latitude"];
69 $station["city"] = $row["city"];
70 // $station["values"] = Array();
71 // $station["values"][] = "temperature";
72 // $station["values"][] = "humidity";
73 $station["url"] = "stations/". $station["uuid"];
74 $stations[] = $station;
75 }
76 $db->exec("COMMIT");
77
78 echo json_encode($stations);
79 }
80
81 /**
82 * @brief Registers a new weather station
83 *
84 * @note Call this function with a big timeout > 2seconds, because we use another webservice
85 * to fetch location data. This fetch runs already 2seconds.
86 * @note Requires php-pecl-uuid
87 */
88 public static function stationsRegister(){
89 $geoLocationRadius = 5;
90
91 try{
92 $app = \Slim\Slim::getInstance("siweather");
93 $body = $app->request->getBody();
94 $json = json_decode($body, true);
95
96 $app->response()->header("Content-Type", "application/json");
97
98 if(!function_exists("uuid_create")){
99 echo json_encode
100 (
101 [
102 "result" => "missinguuidcreate",
103 "message" => "The function uuid_create() from pecl package http://pecl.php.net/package/uuid is not installed, but needed!",
104 ]
105 );
106 return;
107 }
108
109 $expectedKeys = array("name", "city", "longitude", "latitude", "email");
110 $missingKeys = array();
111 foreach($expectedKeys as $key){
112 if(!array_key_exists($key, $json))
113 $missingKeys[] = $key;
114 }
115 if(count($missingKeys) > 0){
116 echo json_encode
117 (
118 [
119 "result" => "missingkeys",
120 "message" => "Your request misses the following keys: ". implode(", ", $missingKeys),
121 ]
122 );
123 return;
124 }
125
126 if(!Location::ValidLatitude($json["latitude"])){
127 echo json_encode
128 (
129 [
130 "result" => "invalid latitude",
131 "message" => "Your specified an invalid latitude: ". $json["latitude"],
132 ]
133 );
134 return;
135 }
136 if(!Location::ValidLongitude($json["longitude"])){
137 echo json_encode
138 (
139 [
140 "result" => "invalid longitude",
141 "message" => "Your specified an invalid longitude: ". $json["longitude"],
142 ]
143 );
144 return;
145 }
146 if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){
147 echo json_encode
148 (
149 [
150 "result" => "invalid email",
151 "message" => "Your specified an invalid email address: ". $json["email"],
152 ]
153 );
154 return;
155 }
156
157 $errorMessage = "";
158 $locations = GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage);
159 if(!$locations || count($locations) < 1){
160 error_log($errorMessage);
161 echo json_encode
162 (
163 [
164 "result" => "unprovenlocation",
165 "message" => "Could not check the city (". $json["city"] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send with help of your city and geo coordinates. Please make sure, your data is correct.",
166 ]
167 );
168 return;
169 }
170 else{
171 $validatedLocation = false;
172 foreach($locations as $location){
173 if($location->city() == $json["city"]){
174 $validatedLocation = $location;
175 }
176 }
177 if(!$validatedLocation){
178 $message = "The city (". $json[city] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send, does not suite with locations we found at your given location (city, latitude, longitude):\n";
179 foreach($locations as $location){
180 $message .= " ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n";
181 }
182 $message .= " Please make sure, your data is correct.";
183
184 echo json_encode
185 (
186 [
187 "result" => "unprovenlocation",
188 "message" => $message,
189 ]
190 );
191 return;
192 }
193 }
194
195 $db = new DatabaseHandler();
196 if(!$db->connect()){
197 echo json_encode
198 (
199 [
200 "result" => "failed",
201 "message" => "Could not connect to the database",
202 ]
203 );
204 return;
205 }
206 $db->exec("BEGIN");
207
208 // find out, if the city is already there
209 $cityId = -1;
210 $sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location");
211 if(!$sqlStatement){
212 $db->exec("ROLLBACK");
213 echo json_encode
214 (
215 [
216 "result" => "failed",
217 "message" => "Could not fetch city from database",
218 ]
219 );
220 return;
221 }
222 $sqlStatement->bindValue(":name", $validatedLocation->city());
223 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
224 $result = $sqlStatement->execute();
225 if($result->numColumns() && $result->columnType(0) != SQLITE3_NULL){
226 error_log("not cool");
227 $row = $result->fetchArray();
228 $cityId = $row[0];
229 error_log($row[0]);
230 }
231 else{
232 $sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))");
233 if(!$sqlStatement){
234 $db->exec("ROLLBACK");
235 echo json_encode
236 (
237 [
238 "result" => "failed",
239 "message" => "Could insert city into the database",
240 ]
241 );
242 return;
243 }
244 $sqlStatement->bindValue(":name", $validatedLocation->city());
245 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
246 $sqlResult = $sqlStatement->execute();
247 if(!$sqlResult){
248 error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());
249 $db->exec("ROLLBACK");
250 echo json_encode
251 (
252 [
253 "result" => "failed",
254 "message" => "Could not add city to the database",
255 ]
256 );
257 return;
258 }
259 $cityId = $db->lastInsertRowId();
260 }
261 if($cityId < 0){
262 error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage());
263 $db->exec("ROLLBACK");
264 echo json_encode
265 (
266 [
267 "result" => "failed",
268 "message" => "Could not select city from the database",
269 ]
270 );
271 return;
272 }
273
274 // insert station
275 $uuid = uuid_create(4);
276 $sqlStatement = $db->prepare("INSERT INTO stations (name, city, uuid, ownerMail, location) VALUES(:name, :city, :uuid, :ownerMail, GeomFromText(:location, 4326))");
277 if(!$sqlStatement){
278 $db->exec("ROLLBACK");
279 echo json_encode
280 (
281 [
282 "result" => "failed",
283 "message" => "Could insert station into the database",
284 ]
285 );
286 return;
287 }
288 $sqlStatement->bindValue(":name", $json["name"]);
289 $sqlStatement->bindValue(":city", $cityId);
290 $sqlStatement->bindValue(":uuid", $uuid);
291 $sqlStatement->bindValue(":ownerMail",$json["email"]);
292 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
293 $sqlResult = $sqlStatement->execute();
294 if(!$sqlResult){
295 error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage());
296 $db->query("ROLLBACK");
297 echo json_encode
298 (
299 [
300 "result" => "failed",
301 "message" => "Could not add station to the database",
302 ]
303 );
304 return;
305 }
306
307 // finish transaction
308 $db->exec("COMMIT");
309
310 echo json_encode
311 (
312 [
313 "result" => "success",
314 "uuid" => $uuid,
315 ]
316 );
317 }
318 catch(Exception $exception){
319 error_log("Caught exception handling request stationsRegister: ". $exception->getMessage());
320 $app->response()->status(400);
321 $app->response()->header("X-Status-Reason", $exception->getMessage());
322 }
323 }
324}
325
326?>
Note: See TracBrowser for help on using the repository browser.