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

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

The webservice sends an email to the station owner to confirm the station creation

  • Property mode set to 100644
File size: 13.9 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 max. 2 seconds.
86 * @note Requires php-pecl-uuid
87 * @note Requires php-pecl-rrd
88 */
89 public static function stationsRegister(){
90 $geoLocationRadius = 5;
91
92 try{
93 $app = \Slim\Slim::getInstance("siweather");
94 $body = $app->request->getBody();
95 $json = json_decode($body, true);
96
97 $app->response()->header("Content-Type", "application/json");
98
99 if(!function_exists("uuid_create")){
100 error_log("pecl uuid extension not installed!");
101 echo json_encode
102 (
103 [
104 "result" => "missinguuidcreate",
105 "message" => "The function uuid_create() from pecl package http://pecl.php.net/package/uuid is not installed, but needed!",
106 ]
107 );
108 return;
109 }
110
111 if(!function_exists("rrd_create") || !function_exists("rrd_update")){
112 error_log("pecl rrd extension not installed!");
113 echo json_encode
114 (
115 [
116 "result" => "missingrrd",
117 "message" => "The function rrd_create() or rrd_update() from pecl package http://pecl.php.net/package/rrd is not installed, but needed!",
118 ]
119 );
120 return;
121 }
122
123 $expectedKeys = array("name", "city", "longitude", "latitude", "email", "type");
124 $missingKeys = array();
125 foreach($expectedKeys as $key){
126 if(!array_key_exists($key, $json))
127 $missingKeys[] = $key;
128 }
129 if(count($missingKeys) > 0){
130 echo json_encode
131 (
132 [
133 "result" => "missingkeys",
134 "message" => "Your request misses the following keys: ". implode(", ", $missingKeys),
135 ]
136 );
137 return;
138 }
139
140 if(!Location::ValidLatitude($json["latitude"])){
141 echo json_encode
142 (
143 [
144 "result" => "invalid latitude",
145 "message" => "Your specified an invalid latitude: ". $json["latitude"],
146 ]
147 );
148 return;
149 }
150 if(!Location::ValidLongitude($json["longitude"])){
151 echo json_encode
152 (
153 [
154 "result" => "invalid longitude",
155 "message" => "Your specified an invalid longitude: ". $json["longitude"],
156 ]
157 );
158 return;
159 }
160 if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){
161 echo json_encode
162 (
163 [
164 "result" => "invalid email",
165 "message" => "Your specified an invalid email address: ". $json["email"],
166 ]
167 );
168 return;
169 }
170 if(!array_key_exists("typeUrl", $json)){
171 $json["typeUrl"] = "";
172 }
173 elseif(!empty($json["typeUrl"]) && !filter_var($json["typeUrl"], FILTER_VALIDATE_URL)){
174 echo json_encode
175 (
176 [
177 "result" => "invalid type url",
178 "message" => "Your specified type url is invalid: ". $json["typeUrl"] ." Set it to an empty value or fix it.",
179 ]
180 );
181 return;
182 }
183
184 $errorMessage = "";
185 $locations = GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage);
186 if(!$locations || count($locations) < 1){
187 error_log($errorMessage);
188 echo json_encode
189 (
190 [
191 "result" => "unprovenlocation",
192 "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.",
193 ]
194 );
195 return;
196 }
197 else{
198 $validatedLocation = false;
199 foreach($locations as $location){
200 if($location->city() == $json["city"]){
201 $validatedLocation = $location;
202 }
203 }
204 if(!$validatedLocation){
205 $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";
206 foreach($locations as $location){
207 $message .= " ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n";
208 }
209 $message .= " Please make sure, your data is correct.";
210
211 echo json_encode
212 (
213 [
214 "result" => "unprovenlocation",
215 "message" => $message,
216 ]
217 );
218 return;
219 }
220 }
221
222 $db = new DatabaseHandler();
223 if(!$db->connect()){
224 echo json_encode
225 (
226 [
227 "result" => "failed",
228 "message" => "Could not connect to the database",
229 ]
230 );
231 return;
232 }
233 $db->exec("BEGIN");
234
235 // find out, if the city is already there
236 $cityId = -1;
237 $sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location");
238 if(!$sqlStatement){
239 $db->exec("ROLLBACK");
240 echo json_encode
241 (
242 [
243 "result" => "failed",
244 "message" => "Could not fetch city from database",
245 ]
246 );
247 return;
248 }
249 $sqlStatement->bindValue(":name", $validatedLocation->city());
250 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
251 $result = $sqlStatement->execute();
252 $row = $result->fetchArray();
253 if($row){
254 $cityId = $row[0];
255 }
256 else{
257 $sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))");
258 if(!$sqlStatement){
259 error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());
260 $db->exec("ROLLBACK");
261 echo json_encode
262 (
263 [
264 "result" => "failed",
265 "message" => "Could insert city into the database",
266 ]
267 );
268 return;
269 }
270 $sqlStatement->bindValue(":name", $validatedLocation->city());
271 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
272 $sqlResult = $sqlStatement->execute();
273 if(!$sqlResult){
274 error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());
275 $db->exec("ROLLBACK");
276 echo json_encode
277 (
278 [
279 "result" => "failed",
280 "message" => "Could not add city to the database",
281 ]
282 );
283 return;
284 }
285 $cityId = $db->lastInsertRowId();
286 }
287 if(!is_numeric($cityId) || $cityId < 0){
288 error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage());
289 $db->exec("ROLLBACK");
290 echo json_encode
291 (
292 [
293 "result" => "failed",
294 "message" => "Could not select city from the database",
295 ]
296 );
297 return;
298 }
299
300 // find out initial state
301 $statusId = -1;
302 $sqlStatement = $db->prepare("SELECT id FROM status WHERE name=:name");
303 if(!$sqlStatement){
304 $db->exec("ROLLBACK");
305 error_log("Could not find initial state to register station (Prepare): ". $db->lastDatabaseErrorMessage());
306 echo json_encode
307 (
308 [
309 "result" => "failed",
310 "message" => "Could not fetch status from database",
311 ]
312 );
313 return;
314 }
315 $sqlStatement->bindValue(":name", "confirming");
316 $result = $sqlStatement->execute();
317 $row = $result->fetchArray();
318 if($row){
319 $statusId = $row[0];
320 }
321 else{
322 error_log("columns ". $result->numColumns() .", columnType: ". $result->columnType(0));
323 $db->exec("ROLLBACK");
324 error_log("Could not find initial state to register station (Execute): ". $db->lastDatabaseErrorMessage());
325 echo json_encode
326 (
327 [
328 "result" => "failed",
329 "message" => "Could not fetch status from database (Status not found)",
330 ]
331 );
332 return;
333 }
334
335 // insert station
336 $uuid = uuid_create(4);
337 $sqlStatement = $db->prepare("INSERT INTO stations (name, city, uuid, ownerMail, type, typeUrl, status, location) VALUES(:name, :city, :uuid, :ownerMail, :type, :typeUrl, :status, GeomFromText(:location, 4326))");
338 if(!$sqlStatement){
339 $db->exec("ROLLBACK");
340 echo json_encode
341 (
342 [
343 "result" => "failed",
344 "message" => "Could insert station into the database",
345 ]
346 );
347 return;
348 }
349 $sqlStatement->bindValue(":name", $json["name"]);
350 $sqlStatement->bindValue(":city", $cityId);
351 $sqlStatement->bindValue(":uuid", $uuid);
352 $sqlStatement->bindValue(":ownerMail", $json["email"]);
353 $sqlStatement->bindValue(":type", $json["type"]);
354 $sqlStatement->bindValue(":typeUrl", $json["typeUrl"]);
355 $sqlStatement->bindValue(":status", $statusId);
356 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
357 $sqlResult = $sqlStatement->execute();
358 if(!$sqlResult){
359 error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage());
360 $db->query("ROLLBACK");
361 echo json_encode
362 (
363 [
364 "result" => "failed",
365 "message" => "Could not add station to the database",
366 ]
367 );
368 return;
369 }
370
371 // creating rrd file
372 $webserviceConfig = new WebserviceConfig();
373 $rrdFileName = $webserviceConfig->dataDirectory() . $uuid .".rrd";
374 $rrdCreator = new \RRDCreator($rrdFileName, "now", 900);
375 $rrdCreator->addDataSource("Temp:GAUGE:1320:-100:100");
376 $rrdCreator->addDataSource("Humidity:GAUGE:1320:0:100");
377 $rrdCreator->addDataSource("Pressure:GAUGE:1320:800:1200");
378 $rrdCreator->addDataSource("WindSpeed:GAUGE:1320:0:999");
379 $rrdCreator->addDataSource("Winddirection:GAUGE:1320:1:360");
380 $rrdCreator->addDataSource("Rainfall:GAUGE:1320:0:999");
381 $rrdCreator->addArchive("AVERAGE:0.5:1:96");
382 $rrdCreator->addArchive("AVERAGE:0.5:4:96");
383 $rrdCreator->addArchive("AVERAGE:0.5:8:360");
384 $rrdCreator->addArchive("AVERAGE:0.5:16:2190");
385 $rrdCreator->addArchive("AVERAGE:0.5:24:146000");
386 $rrdCreator->addArchive("AVERAGE:0.5:48:146000");
387 $rrdCreator->addArchive("AVERAGE:0.5:96:146000");
388 $rrdCreator->addArchive("MIN:0.5:4:96");
389 $rrdCreator->addArchive("MIN:0.5:8:360");
390 $rrdCreator->addArchive("MIN:0.5:16:2190");
391 $rrdCreator->addArchive("MIN:0.5:24:146000");
392 $rrdCreator->addArchive("MIN:0.5:48:146000");
393 $rrdCreator->addArchive("MIN:0.5:96:146000");
394 $rrdCreator->addArchive("MAX:0.5:4:96");
395 $rrdCreator->addArchive("MAX:0.5:8:360");
396 $rrdCreator->addArchive("MAX:0.5:16:2190");
397 $rrdCreator->addArchive("MAX:0.5:24:146000");
398 $rrdCreator->addArchive("MAX:0.5:48:146000");
399 $rrdCreator->addArchive("MAX:0.5:96:146000");
400 if(!$rrdCreator->save()){
401 $db->query("ROLLBACK");
402 $errorMessage = rrd_error();
403 echo json_encode
404 (
405 [
406 "result" => "failed",
407 "message" => "Could not create rrd files for this station: ". $errorMessage,
408 ]
409 );
410 return;
411 }
412
413 // finish transaction
414 $db->exec("COMMIT");
415
416 $deletionDate = date(DATE_RFC850, time() + 14 * 24 * 60 * 60);
417 $mailRecipient = $json["email"];
418 $header = "From: ". WebserviceConfig::value("mailaddressFrom") ."\r\n" .
419 "Reply-To: ". WebserviceConfig::value("mailaddressFrom") ."\r\n" .
420 "CC: ". WebserviceConfig::value("mailaddressCC") ."\r\n" .
421 "X-Mailer: PHP/". phpversion();
422 $message = "Dear user,\r\n" .
423 "\r\n" .
424 "please visit the following Link to confirm your newly created weather station ". $json["name"] .".\r\n" .
425 "If you do not visit this link, your station will be delete in 14 days (". $deletionDate .").\r\n" .
426 "\r\n" .
427 WebserviceConfig::value("webserviceBaseUrl"). "/stations/". $uuid ."/confirm" ."\r\n" .
428 "\r\n" .
429 "Kind regards,\r\n" .
430 "Your weather service\r\n";
431 mail($mailRecipient, \Translator::swGettext("Weather station %s - Confirmation request", $uuid), $message, $header);
432 echo json_encode
433 (
434 [
435 "result" => "success",
436 "message" => "Confirmation request is send to ". $mailRecipient .". The station is fully functional already, but might be deleted in 14 days (". $deletionDate .") without any further warnings!",
437 "uuid" => $uuid,
438 ]
439 );
440 }
441 catch(Exception $exception){
442 error_log("Caught exception handling request stationsRegister: ". $exception->getMessage());
443 $app->response()->status(400);
444 $app->response()->header("X-Status-Reason", $exception->getMessage());
445 }
446 }
447}
448
449?>
Note: See TracBrowser for help on using the repository browser.