source: src/webservice/htdocs/SiWeather/Webservice/Setup.php@ fb602c6

Last change on this file since fb602c6 was e498070, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago
  • Property mode set to 100644
File size: 15.1 KB
RevLine 
[8c356c1]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
[b38cc03]23require_once(__DIR__ ."/../../inc/envsetup.php");
24
[8c356c1]25/**
26 * @brief Configures the Webservice and creates all needed files and directories (e.g. Databases)
27 *
28 * @note Requires php-posix!
29 */
30class Setup {
31
32 public function __construct(){
33 $this->_webserviceConfig = new WebserviceConfig();
34 $this->_dataDirectory = $this->_webserviceConfig->getConfig("dataDirectory");
35 $this->_databaseHandler = new DatabaseHandler();
36 $this->_databaseFile = $this->_databaseHandler->databaseFile();
37 $this->_databaseDirectory = pathinfo($this->_databaseFile, PATHINFO_DIRNAME);
[b38cc03]38 $this->_databaseFirstConnection = !file_exists($this->_databaseFile);
[8c356c1]39 }
40
41 /**
42 * @brief Checks if data directory is present and writable and returns a value from DatabaesChecks
43 *
44 * If an error occurs, the error message is stored into @p $errorMessage.
45 *
46 * @see DataDirectoryChecks
47 * @see dataDirectoryCreate()
48 */
49 public function dataDirectoryCheck(&$errorMessage){
50 if(!is_object($this->_webserviceConfig)){
[b38cc03]51 $errorMessage = _("Could not load the webservice configuration");
[8c356c1]52 return DataDirectoryChecks::NoConfiguration;
53 }
54 if(!$this->_dataDirectory || empty($this->_dataDirectory)){
[b38cc03]55 $errorMessage = _("Could not determine dataDirectory setting");
[8c356c1]56 return DataDirectoryChecks::NoDirectoryPath;
57 }
58 if(!is_dir($this->_dataDirectory)){
[b38cc03]59 $errorMessage = _("Data directory does not exists");
[8c356c1]60 return DataDirectoryChecks::NotExist;
61 }
62 if(!is_writable($this->_dataDirectory)){
[b38cc03]63 $errorMessage = \Translator::swGettext("Data directory is not writable for %s:%s (%s)",
64 $this->getProcessUser(), $this->getProcessGroup(), $this->_dataDirectory);
[8c356c1]65 return DataDirectoryChecks::NotWritable;
66 }
67 return DataDirectoryChecks::Success;
68 }
69
70 /**
71 * @brief Creates the data directory and returns a value from DatabaesChecks
72 *
73 * If an error occurs, the error message is stored into @p $errorMessage.
74 *
75 * @see DataDirectoryChecks
76 * @see dataDirectoryCreate()
77 */
78 public function dataDirectoryCreate(&$errorMessage){
79 $result = $this->dataDirectoryCheck($errorMessage);
80 if($result == DataDirectoryChecks::Success){
[b38cc03]81 // directory already exists, therefore there is no need to create it
[8c356c1]82 return DataDirectoryChecks::Success;
83 }
[b38cc03]84 if($result != DataDirectoryChecks::NotExist){
[8c356c1]85 return $result;
86 }
[b38cc03]87 // clear $errorMessage, because it contains the "Data directory does not exist" entry
88 // from dataDirectoryCheck(), which is not an error at this point!
89 $errorMessage = "";
[8c356c1]90 if(!mkdir($this->_dataDirectory)){
[b38cc03]91 $errorMessage = \Translator::swGettext("Could not create data directory (%s)", $this->_dataDirectory);
[8c356c1]92 return DataDirectoryChecks::Error;
93 }
94 return DataDirectoryChecks::Success;
95 }
96
97 /**
98 * @brief Checks everything related to the database path and returns a value from DatabaesChecks
99 *
100 * If an error occurs, the error message is stored into @p $errorMessage.
101 *
102 * @see DatabaseDirectoryChecks
103 * @see databaseDirectoryCreate()
104 */
105 public function databaseDirectoryCheck(&$errorMessage){
106 if(is_null($this->_databaseDirectory) || empty($this->_databaseDirectory)){
[b38cc03]107 $errorMessage = \Translator::swGettext("Failed to extract directory from database file path (%s)", $this->_databaseFile);
[8c356c1]108 return DatabaseChecks::NoDirectoryPath;
109 }
110 if(!is_dir($this->_databaseDirectory)){
[b38cc03]111 $errorMessage = \Translator::swGettext("Database directory does not exists (%s)", $this->_databaseDirectory);
[8c356c1]112 return DatabaseChecks::DirectoryDoesNotExist;
113 }
114 if(!is_writable($this->_databaseDirectory)){
[b38cc03]115 $errorMessage = \Translator::swGettext("Database directory is not writable for %s:%s (%s)",
116 $this->getProcessUser(), $this->getProcessGroup(),
117 $this->_databaseDirectory);
[8c356c1]118 return DatabaseChecks::DirectoryNotWritable;
119 }
120 return DatabaseChecks::Success;
121 }
122
123 /**
124 * @brief Creates the database directory and returns a value from DatabaesChecks
125 *
126 * If an error occurs, the error message is stored into @p $errorMessage.
127 *
128 * @see DatabaseDirectoryChecks
129 * @see databaseDirectoryCheck()
130 */
131 public function databaseDirectoryCreate(&$errorMessage){
132 $result = $this->databaseDirectoryChecks($errorMessage);
133 if($result == DatabaseChecks::Success){
[b38cc03]134 $errorMessage = "";
[8c356c1]135 return DatabaseChecks::Success;
136 }
137 if($result == DatabaseChecks::NoDatabaseFile || $result == DatabaseChecks::NoDirectoryPath || $result == DatabaseChecks::DirectoryNotWritable){
138 return $result;
139 }
140 if(!mkdir($this->_databaseDirectory)){
[b38cc03]141 $errorMessage = \Translator::swGettext("Could not create database directory (%s)", $this->_databaseDirectory);
[8c356c1]142 return DatabaseChecks::Error;
143 }
144 return DatabaseChecks::Success;
145 }
146
147 /**
148 * @brief Checks, if the database file is given and is in a writable path
149 *
150 * The database file itself is created by the DatabaseHandler. Therefore
151 * this function only checks, if the database directory exists, and it must be
152 * writable.
153 *
154 * @see DatabaseChecks
155 * @see databaseDirectoryCheck()
156 */
157 public function databaseFileCheck(&$errorMessage){
158 if(is_null($this->_databaseFile) || empty($this->_databaseFile)){
[b38cc03]159 $errorMessage = \Translator::swGettext("No database file given (%s)", $this->_databaseHandler->lastErrorMessage());
[8c356c1]160 return DatabaseChecks::NoDatabaseFile;
161 }
162 if(file_exists($this->_databaseFile)){
163 if(!is_writable($this->_databaseFile)){
[b38cc03]164 $errorMessage = \Translator::swGettext("Database file is not writable for %s:%s (%s)",
165 $this->getProcessUser(), $this->getProcessGroup(),
166 $this->_databaseFile);
[8c356c1]167 return DatabaseChecks::DatabaseFileNotWritable;
168 }
169 return DatabaseChecks::Success;
170 }
171 // if the databaseDirectoryCheck function return something other than success,
172 // we probably have a problem (like no write permission, ...)
173 if($this->databaseDirectoryCheck($errorMessage) != DatabaseChecks::Success){
174 return DatabaseChecks::Error;
175 }
176 return DatabaseChecks::Success;
177 }
178
179 public function databaseConnection(&$errorMessage){
180 if(!is_object($this->_databaseHandler)){
[b38cc03]181 $errorMessage = _("No database handler");
[8c356c1]182 return false;
183 }
184 if(!$this->_databaseHandler->connect()){
[b38cc03]185 $errorMessage = \Translator::swGettext("Could not connect to the database (%s)", $this->_databaseHandler->lastErrorMessage());
[8c356c1]186 return false;
187 }
188
189 // prepare Spatalite
[b38cc03]190 if(!$this->databaseTableExists("spatial_ref_sys")){
191 if(!$this->_databaseHandler->exec("BEGIN")){
192 $errorMessage = _("Could not start transaction to init Spatialite");
193 return false;
194 }
195 if(!$this->_databaseHandler->exec("SELECT InitSpatialMetadata()")){
196 $errorMessage = _("Could not initiate Spatialite metadata");
197 return false;
198 }
199 if(!$this->_databaseHandler->exec("COMMIT")){
200 $errorMessage = _("Could not commit transaction to init Spatialite");
201 return false;
202 }
[8c356c1]203 }
[b38cc03]204
[69c8290]205// // prepare countries table
206// $table = "countries";
207// if(!$this->databaseTableExists($table)){
208// $sql = "CREATE TABLE ". $table ." (";
209// $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
210// $sql .= " name TEXT NOT NULL,";
211// $sql .= " code VARCHAR(2)";
212// $sql .= ")";
213// if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
214// return false;
215// }
216// }
217//
218// // prepare regions table
219// $table = "regions";
220// if(!$this->databaseTableExists($table)){
221// $sql = "CREATE TABLE ". $table ." (";
222// $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
223// $sql .= " name TEXT NOT NULL,";
224// $sql .= " code VARCHAR(2),";
225// $sql .= " country INTEGER,";
226// $sql .= " FOREIGN KEY(country) REFERENCES countries(id)";
227// $sql .= ")";
228// if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
229// return false;
230// }
231// }
[b38cc03]232
233 // prepare cities table
234 $table = "cities";
235 if(!$this->databaseTableExists($table)){
236 $sql = "CREATE TABLE ". $table ." (";
237 $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
[69c8290]238 $sql .= " name TEXT NOT NULL";
[b38cc03]239 $sql .= ")";
240 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
241 return false;
242 }
243 // creating a POINT Geometry column named center,
244 // taking two coordinates in SRID 4326 (WGS84) format
245 $sql = "SELECT AddGeometryColumn(\"". $table ."\", ";
246 $sql .= "\"location\", 4326, \"POINT\", \"XY\")";
247 if(!$this->_databaseHandler->exec($sql)){
248 $errorMessage = Translation::swGettext("Could not create location field for %s table", $table);
249 return false;
250 }
251 }
252
[e498070]253 // prepare status table
254 $table = "status";
255 if(!$this->databaseTableExists($table)){
256 $sql = "CREATE TABLE ". $table ." (";
257 $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
258 $sql .= " name TEXT NOT NULL";
259 $sql .= ")";
260 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
261 return false;
262 }
263 $status = array("confirming", "active", "deletionrequested");
264 $sql = "INSERT INTO ". $table ." (name) VALUES(:name)";
265 $sqlStatement = $this->_databaseHandler->prepare($sql);
266 foreach ($status as $name){
267 $sqlStatement->clear();
268 $sqlStatement->bindValue(":name", $name);
269 if(!$sqlStatement->execute()){
270 $errorMessage = Translation::swGettext("Could not add status %s to the database", $name);
271 error_log($errorMessage);
272 return false;
273 }
274 $sqlStatement->reset();
275 }
276 }
277
[b38cc03]278 // prepare stations table
279 $table = "stations";
280 if(!$this->databaseTableExists($table)){
281 $sql = "CREATE TABLE ". $table ." (";
282 $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
283 $sql .= " name TEXT NOT NULL,";
[e498070]284 $sql .= " city INTEGER NOT NULL,";
[69c8290]285 $sql .= " uuid TEXT NOT NULL,";
286 $sql .= " ownerMail TEXT NOT NULL,";
[e498070]287 $sql .= " type TEXT NOT NULL,";
288 $sql .= " typeUrl TEXT,";
289 $sql .= " status INTEGER NOT NULL,";
[b38cc03]290 $sql .= " FOREIGN KEY(city) REFERENCES cities(id)";
[e498070]291 $sql .= " FOREIGN KEY(status) REFERENCES status(id)";
[b38cc03]292 $sql .= ")";
293 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
294 return false;
295 }
296 // creating a POINT Geometry column named center,
297 // taking two coordinates in SRID 4326 (WGS84) format
298 $sql = "SELECT AddGeometryColumn(\"". $table ."\", ";
299 $sql .= "\"location\", 4326, \"POINT\", \"XY\")";
300 if(!$this->_databaseHandler->exec($sql)){
301 $errorMessage = Translation::swGettext("Could not create location field for %s table", $table);
302 return false;
303 }
[8c356c1]304 }
305
306 return true;
307 }
308
309 public function databaseVersionSqlite(&$errorMessage){
310 if(!is_object($this->_databaseHandler)){
311 return 0;
312 }
313 $result = $this->_databaseHandler->versionSqlite();
314 if($result == 0){
315 $errorMessage = $this->_databaseHandler->lastErrorMessage();
316 }
317 return $result;
318 }
319
320 public function databaseVersionSpatalite(&$errorMessage){
321 if(!is_object($this->_databaseHandler)){
322 return 0;
323 }
324 $result = $this->_databaseHandler->versionSpatialite();
325 if($result == 0){
326 $errorMessage = $this->_databaseHandler->lastErrorMessage();
327 }
328 return $result;
329 }
330
331 public function apiCheckWithoutRewrite(&$errorMessage){
332 return $this->apiCheck("index.php/stations", $errorMessage);
333 }
334
335 public function apiCheckWithRewrite(&$errorMessage){
[1e37648]336 return $this->apiCheck("stations", $errorMessage);
[8c356c1]337 }
338
339 private function getProcessUser(){
340 $processUser = posix_getpwuid(posix_getuid());
341 return $processUser["name"];
342 }
343
344 private function getProcessGroup(){
345 $processGroup = posix_getgrgid(posix_getgid());
346 return $processGroup["name"];
347 }
348
349 private function apiCheck($url, &$errorMessage){
[1e37648]350 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();
[8c356c1]351 if(!$baseUrl || empty($baseUrl)){
[b38cc03]352 $errorMessage = _("No webservice base url given!");
[8c356c1]353 return false;
354 }
355
[1e37648]356 # base_url needs to end with a /, otherwise the last element is chopped
[098c36e]357 try{
358 $client = new \GuzzleHttp\Client
359 (
360 [
361 "base_uri" => $baseUrl,
362 "timeout" => 2.0,
363 "http_errors" => false,
364 ]
365 );
366 $response = $client->get($url);
367 }
368 catch(\GuzzleHttp\Exception\ConnectException $exception){
369 $errorMessage = \Translator::swGettext("Webservce has not answered at url %s! Error: %s", $baseUrl, $exception->getMessage());
370 return false;
371 }
[8c356c1]372 if(is_null($response)){
[b38cc03]373 $errorMessage = \Translator::swGettext("Webservice has not answered at url %s!", $baseUrl);
[8c356c1]374 return false;
375 }
376 $result = $response->getStatusCode();
377 if($result != 200){
[552da81]378 $errorMessage = \Translator::swGettext("Got http error %s (%s) at url %s", $result, $response->getReasonPhrase(), $baseUrl . $url);
[8c356c1]379 return false;
380 }
381 $result = $response->getReasonPhrase();
382 if($result != "OK"){
[b38cc03]383 $errorMessage = \Translator::swGettext("Got a http error reason with http code 200: %s", $result);
[8c356c1]384 return false;
385 }
386
387 $body = $response->getBody();
388 if(empty($body)){
[b38cc03]389 $errorMessage = _("Got empty return value");
[8c356c1]390 return false;
391 }
392
393 $json = json_decode($body);
394 if(is_null($json)){
[b38cc03]395 $errorMessage = _("Could not decode json message body");
396 return false;
397 }
398 return true;
399 }
400
401 private function databaseTableExists($table){
402 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
403 return false;
404 }
405 $statement = $this->_databaseHandler->prepare("SELECT COUNT(*) FROM sqlite_master WHERE type=\"table\" AND name=:name");
406 if(!$statement){
407 $errorMessage = \Translator::swGettext("Could not prepare query to check if table %s exists", $table);
408 return false;
409 }
410 $statement->bindValue(":name", $table);
411 $result = $statement->execute();
412 $row = $result->fetchArray();
413 if(!$row || !is_array($row) || count($row) < 1 || $row[0] != 1)
414 return false;
415 return true;
416 }
417
418 private function databaseTableCreate($table, $sqlStatement, &$errorMessage){
419 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
420 return false;
421 }
422 if(!$this->_databaseHandler->exec("BEGIN")){
423 $errorMessage = \Translator::swGettext("Could not start transaction to create table %s", $table);
424 return false;
425 }
426 if(!$this->_databaseHandler->exec($sqlStatement)){
427 $errorMessage = \Translator::swGettext("Could not execute sql statement to create table %s:\n%s", $table, $sqlStatement);
428 return false;
429 }
430 if(!$this->_databaseHandler->exec("COMMIT")){
431 $errorMessage = \Translator::swGettext("Could not commit transaction to create table %s", $table);
[8c356c1]432 return false;
433 }
434 return true;
435 }
436
437 private $_webserviceConfig;
438 private $_dataDirectory;
439 private $_databaseHandler;
440 private $_databaseFile;
[b38cc03]441 private $_databaseFirstConnection;
[8c356c1]442}
443
444?>
Note: See TracBrowser for help on using the repository browser.