connect()){ echo json_encode ( [ "result" => "failed", "message" => "Could not connect to the database", ] ); return; } $db->exec("BEGIN"); $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"); if(!$sqlStatement){ $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could not fetch stations from database", ] ); return; } $result = $sqlStatement->execute(); while($row = $result->fetchArray()){ $station = Array(); $station["uuid"] = $row["uuid"]; $station["name"] = $row["name"]; $station["longitude"] = $row["longitude"]; $station["latitude"] = $row["latitude"]; $station["city"] = $row["city"]; // $station["values"] = Array(); // $station["values"][] = "temperature"; // $station["values"][] = "humidity"; $station["url"] = "stations/". $station["uuid"]; $stations[] = $station; } $db->exec("COMMIT"); echo json_encode($stations); } /** * @brief Registers a new weather station * * @note Call this function with a big timeout > 2seconds, because we use another webservice * to fetch location data. This fetch runs already max. 2 seconds. * @note Requires php-pecl-uuid * @note Requires php-pecl-rrd */ public static function stationsRegister(){ $geoLocationRadius = 5; try{ $app = \Slim\Slim::getInstance("siweather"); $body = $app->request->getBody(); $json = json_decode($body, true); $app->response()->header("Content-Type", "application/json"); if(!function_exists("uuid_create")){ error_log("pecl uuid extension not installed!"); echo json_encode ( [ "result" => "missinguuidcreate", "message" => "The function uuid_create() from pecl package http://pecl.php.net/package/uuid is not installed, but needed!", ] ); return; } if(!function_exists("rrd_create") || !function_exists("rrd_update")){ error_log("pecl rrd extension not installed!"); echo json_encode ( [ "result" => "missingrrd", "message" => "The function rrd_create() or rrd_update() from pecl package http://pecl.php.net/package/rrd is not installed, but needed!", ] ); return; } $expectedKeys = array("name", "city", "longitude", "latitude", "email", "type"); $missingKeys = array(); foreach($expectedKeys as $key){ if(!array_key_exists($key, $json)) $missingKeys[] = $key; } if(count($missingKeys) > 0){ echo json_encode ( [ "result" => "missingkeys", "message" => "Your request misses the following keys: ". implode(", ", $missingKeys), ] ); return; } if(!Location::ValidLatitude($json["latitude"])){ echo json_encode ( [ "result" => "invalid latitude", "message" => "Your specified an invalid latitude: ". $json["latitude"], ] ); return; } if(!Location::ValidLongitude($json["longitude"])){ echo json_encode ( [ "result" => "invalid longitude", "message" => "Your specified an invalid longitude: ". $json["longitude"], ] ); return; } if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){ echo json_encode ( [ "result" => "invalid email", "message" => "Your specified an invalid email address: ". $json["email"], ] ); return; } if(!array_key_exists("typeUrl", $json)){ $json["typeUrl"] = ""; } elseif(!empty($json["typeUrl"]) && !filter_var($json["typeUrl"], FILTER_VALIDATE_URL)){ echo json_encode ( [ "result" => "invalid type url", "message" => "Your specified type url is invalid: ". $json["typeUrl"] ." Set it to an empty value or fix it.", ] ); return; } $errorMessage = ""; $locations = GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage); if(!$locations || count($locations) < 1){ error_log($errorMessage); echo json_encode ( [ "result" => "unprovenlocation", "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.", ] ); return; } else{ $validatedLocation = false; foreach($locations as $location){ if($location->city() == $json["city"]){ $validatedLocation = $location; } } if(!$validatedLocation){ $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"; foreach($locations as $location){ $message .= " ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n"; } $message .= " Please make sure, your data is correct."; echo json_encode ( [ "result" => "unprovenlocation", "message" => $message, ] ); return; } } $db = new DatabaseHandler(); if(!$db->connect()){ echo json_encode ( [ "result" => "failed", "message" => "Could not connect to the database", ] ); return; } $db->exec("BEGIN"); // find out, if the city is already there $cityId = -1; $sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location"); if(!$sqlStatement){ $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could not fetch city from database", ] ); return; } $sqlStatement->bindValue(":name", $validatedLocation->city()); $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")"); $result = $sqlStatement->execute(); $row = $result->fetchArray(); if($row){ $cityId = $row[0]; } else{ $sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))"); if(!$sqlStatement){ error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage()); $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could insert city into the database", ] ); return; } $sqlStatement->bindValue(":name", $validatedLocation->city()); $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")"); $sqlResult = $sqlStatement->execute(); if(!$sqlResult){ error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage()); $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could not add city to the database", ] ); return; } $cityId = $db->lastInsertRowId(); } if(!is_numeric($cityId) || $cityId < 0){ error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage()); $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could not select city from the database", ] ); return; } // find out initial state $statusId = -1; $sqlStatement = $db->prepare("SELECT id FROM status WHERE name=:name"); if(!$sqlStatement){ $db->exec("ROLLBACK"); error_log("Could not find initial state to register station (Prepare): ". $db->lastDatabaseErrorMessage()); echo json_encode ( [ "result" => "failed", "message" => "Could not fetch status from database", ] ); return; } $sqlStatement->bindValue(":name", "confirming"); $result = $sqlStatement->execute(); $row = $result->fetchArray(); if($row){ $statusId = $row[0]; } else{ error_log("columns ". $result->numColumns() .", columnType: ". $result->columnType(0)); $db->exec("ROLLBACK"); error_log("Could not find initial state to register station (Execute): ". $db->lastDatabaseErrorMessage()); echo json_encode ( [ "result" => "failed", "message" => "Could not fetch status from database (Status not found)", ] ); return; } // insert station $uuid = uuid_create(4); $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))"); if(!$sqlStatement){ $db->exec("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could insert station into the database", ] ); return; } $sqlStatement->bindValue(":name", $json["name"]); $sqlStatement->bindValue(":city", $cityId); $sqlStatement->bindValue(":uuid", $uuid); $sqlStatement->bindValue(":ownerMail", $json["email"]); $sqlStatement->bindValue(":type", $json["type"]); $sqlStatement->bindValue(":typeUrl", $json["typeUrl"]); $sqlStatement->bindValue(":status", $statusId); $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")"); $sqlResult = $sqlStatement->execute(); if(!$sqlResult){ error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage()); $db->query("ROLLBACK"); echo json_encode ( [ "result" => "failed", "message" => "Could not add station to the database", ] ); return; } // creating rrd file $webserviceConfig = new WebserviceConfig(); $rrdFileName = $webserviceConfig->dataDirectory() . $uuid .".rrd"; $rrdCreator = new \RRDCreator($rrdFileName, "now", 900); $rrdCreator->addDataSource("Temp:GAUGE:1320:-100:100"); $rrdCreator->addDataSource("Humidity:GAUGE:1320:0:100"); $rrdCreator->addDataSource("Pressure:GAUGE:1320:800:1200"); $rrdCreator->addDataSource("WindSpeed:GAUGE:1320:0:999"); $rrdCreator->addDataSource("Winddirection:GAUGE:1320:1:360"); $rrdCreator->addDataSource("Rainfall:GAUGE:1320:0:999"); $rrdCreator->addArchive("AVERAGE:0.5:1:96"); $rrdCreator->addArchive("AVERAGE:0.5:4:96"); $rrdCreator->addArchive("AVERAGE:0.5:8:360"); $rrdCreator->addArchive("AVERAGE:0.5:16:2190"); $rrdCreator->addArchive("AVERAGE:0.5:24:146000"); $rrdCreator->addArchive("AVERAGE:0.5:48:146000"); $rrdCreator->addArchive("AVERAGE:0.5:96:146000"); $rrdCreator->addArchive("MIN:0.5:4:96"); $rrdCreator->addArchive("MIN:0.5:8:360"); $rrdCreator->addArchive("MIN:0.5:16:2190"); $rrdCreator->addArchive("MIN:0.5:24:146000"); $rrdCreator->addArchive("MIN:0.5:48:146000"); $rrdCreator->addArchive("MIN:0.5:96:146000"); $rrdCreator->addArchive("MAX:0.5:4:96"); $rrdCreator->addArchive("MAX:0.5:8:360"); $rrdCreator->addArchive("MAX:0.5:16:2190"); $rrdCreator->addArchive("MAX:0.5:24:146000"); $rrdCreator->addArchive("MAX:0.5:48:146000"); $rrdCreator->addArchive("MAX:0.5:96:146000"); if(!$rrdCreator->save()){ $db->query("ROLLBACK"); $errorMessage = rrd_error(); echo json_encode ( [ "result" => "failed", "message" => "Could not create rrd files for this station: ". $errorMessage, ] ); return; } // finish transaction $db->exec("COMMIT"); echo json_encode ( [ "result" => "success", "message" => "Confirmation request is send to ". $json["email"] .".", "uuid" => $uuid, ] ); } catch(Exception $exception){ error_log("Caught exception handling request stationsRegister: ". $exception->getMessage()); $app->response()->status(400); $app->response()->header("X-Status-Reason", $exception->getMessage()); } } } ?>