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

Last change on this file since 256102b was 69c8290, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago
  • Property mode set to 100644
File size: 13.8 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_once(__DIR__ ."/../../inc/envsetup.php");
24
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);
38 $this->_databaseFirstConnection = !file_exists($this->_databaseFile);
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)){
51 $errorMessage = _("Could not load the webservice configuration");
52 return DataDirectoryChecks::NoConfiguration;
53 }
54 if(!$this->_dataDirectory || empty($this->_dataDirectory)){
55 $errorMessage = _("Could not determine dataDirectory setting");
56 return DataDirectoryChecks::NoDirectoryPath;
57 }
58 if(!is_dir($this->_dataDirectory)){
59 $errorMessage = _("Data directory does not exists");
60 return DataDirectoryChecks::NotExist;
61 }
62 if(!is_writable($this->_dataDirectory)){
63 $errorMessage = \Translator::swGettext("Data directory is not writable for %s:%s (%s)",
64 $this->getProcessUser(), $this->getProcessGroup(), $this->_dataDirectory);
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){
81 // directory already exists, therefore there is no need to create it
82 return DataDirectoryChecks::Success;
83 }
84 if($result != DataDirectoryChecks::NotExist){
85 return $result;
86 }
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 = "";
90 if(!mkdir($this->_dataDirectory)){
91 $errorMessage = \Translator::swGettext("Could not create data directory (%s)", $this->_dataDirectory);
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)){
107 $errorMessage = \Translator::swGettext("Failed to extract directory from database file path (%s)", $this->_databaseFile);
108 return DatabaseChecks::NoDirectoryPath;
109 }
110 if(!is_dir($this->_databaseDirectory)){
111 $errorMessage = \Translator::swGettext("Database directory does not exists (%s)", $this->_databaseDirectory);
112 return DatabaseChecks::DirectoryDoesNotExist;
113 }
114 if(!is_writable($this->_databaseDirectory)){
115 $errorMessage = \Translator::swGettext("Database directory is not writable for %s:%s (%s)",
116 $this->getProcessUser(), $this->getProcessGroup(),
117 $this->_databaseDirectory);
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){
134 $errorMessage = "";
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)){
141 $errorMessage = \Translator::swGettext("Could not create database directory (%s)", $this->_databaseDirectory);
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)){
159 $errorMessage = \Translator::swGettext("No database file given (%s)", $this->_databaseHandler->lastErrorMessage());
160 return DatabaseChecks::NoDatabaseFile;
161 }
162 if(file_exists($this->_databaseFile)){
163 if(!is_writable($this->_databaseFile)){
164 $errorMessage = \Translator::swGettext("Database file is not writable for %s:%s (%s)",
165 $this->getProcessUser(), $this->getProcessGroup(),
166 $this->_databaseFile);
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)){
181 $errorMessage = _("No database handler");
182 return false;
183 }
184 if(!$this->_databaseHandler->connect()){
185 $errorMessage = \Translator::swGettext("Could not connect to the database (%s)", $this->_databaseHandler->lastErrorMessage());
186 return false;
187 }
188
189 // prepare Spatalite
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 }
203 }
204
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// }
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,";
238 $sql .= " name TEXT NOT NULL";
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
253 // prepare stations table
254 $table = "stations";
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 .= " city INTEGER,";
260 $sql .= " uuid TEXT NOT NULL,";
261 $sql .= " ownerMail TEXT NOT NULL,";
262 $sql .= " FOREIGN KEY(city) REFERENCES cities(id)";
263 $sql .= ")";
264 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
265 return false;
266 }
267 // creating a POINT Geometry column named center,
268 // taking two coordinates in SRID 4326 (WGS84) format
269 $sql = "SELECT AddGeometryColumn(\"". $table ."\", ";
270 $sql .= "\"location\", 4326, \"POINT\", \"XY\")";
271 if(!$this->_databaseHandler->exec($sql)){
272 $errorMessage = Translation::swGettext("Could not create location field for %s table", $table);
273 return false;
274 }
275 }
276
277 return true;
278 }
279
280 public function databaseVersionSqlite(&$errorMessage){
281 if(!is_object($this->_databaseHandler)){
282 return 0;
283 }
284 $result = $this->_databaseHandler->versionSqlite();
285 if($result == 0){
286 $errorMessage = $this->_databaseHandler->lastErrorMessage();
287 }
288 return $result;
289 }
290
291 public function databaseVersionSpatalite(&$errorMessage){
292 if(!is_object($this->_databaseHandler)){
293 return 0;
294 }
295 $result = $this->_databaseHandler->versionSpatialite();
296 if($result == 0){
297 $errorMessage = $this->_databaseHandler->lastErrorMessage();
298 }
299 return $result;
300 }
301
302 public function apiCheckWithoutRewrite(&$errorMessage){
303 return $this->apiCheck("index.php/stations", $errorMessage);
304 }
305
306 public function apiCheckWithRewrite(&$errorMessage){
307 return $this->apiCheck("stations", $errorMessage);
308 }
309
310 private function getProcessUser(){
311 $processUser = posix_getpwuid(posix_getuid());
312 return $processUser["name"];
313 }
314
315 private function getProcessGroup(){
316 $processGroup = posix_getgrgid(posix_getgid());
317 return $processGroup["name"];
318 }
319
320 private function apiCheck($url, &$errorMessage){
321 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();
322 if(!$baseUrl || empty($baseUrl)){
323 $errorMessage = _("No webservice base url given!");
324 return false;
325 }
326
327 # base_url needs to end with a /, otherwise the last element is chopped
328 $client = new \GuzzleHttp\Client
329 (
330 [
331 "base_uri" => $baseUrl,
332 "timeout" => 2.0,
333 "http_errors" => false,
334 ]
335 );
336 $response = $client->get($url);
337 if(is_null($response)){
338 $errorMessage = \Translator::swGettext("Webservice has not answered at url %s!", $baseUrl);
339 return false;
340 }
341 $result = $response->getStatusCode();
342 if($result != 200){
343 $errorMessage = \Translator::swGettext("Got http error %s (%s) at url %s", $result, $response->getReasonPhrase(), $baseUrl . $url);
344 return false;
345 }
346 $result = $response->getReasonPhrase();
347 if($result != "OK"){
348 $errorMessage = \Translator::swGettext("Got a http error reason with http code 200: %s", $result);
349 return false;
350 }
351
352 $body = $response->getBody();
353 if(empty($body)){
354 $errorMessage = _("Got empty return value");
355 return false;
356 }
357
358 $json = json_decode($body);
359 if(is_null($json)){
360 $errorMessage = _("Could not decode json message body");
361 return false;
362 }
363 return true;
364 }
365
366 private function databaseTableExists($table){
367 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
368 return false;
369 }
370 $statement = $this->_databaseHandler->prepare("SELECT COUNT(*) FROM sqlite_master WHERE type=\"table\" AND name=:name");
371 if(!$statement){
372 $errorMessage = \Translator::swGettext("Could not prepare query to check if table %s exists", $table);
373 return false;
374 }
375 $statement->bindValue(":name", $table);
376 $result = $statement->execute();
377 $row = $result->fetchArray();
378 if(!$row || !is_array($row) || count($row) < 1 || $row[0] != 1)
379 return false;
380 return true;
381 }
382
383 private function databaseTableCreate($table, $sqlStatement, &$errorMessage){
384 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
385 return false;
386 }
387 if(!$this->_databaseHandler->exec("BEGIN")){
388 $errorMessage = \Translator::swGettext("Could not start transaction to create table %s", $table);
389 return false;
390 }
391 if(!$this->_databaseHandler->exec($sqlStatement)){
392 $errorMessage = \Translator::swGettext("Could not execute sql statement to create table %s:\n%s", $table, $sqlStatement);
393 return false;
394 }
395 if(!$this->_databaseHandler->exec("COMMIT")){
396 $errorMessage = \Translator::swGettext("Could not commit transaction to create table %s", $table);
397 return false;
398 }
399 return true;
400 }
401
402 private $_webserviceConfig;
403 private $_dataDirectory;
404 private $_databaseHandler;
405 private $_databaseFile;
406 private $_databaseFirstConnection;
407}
408
409?>
Note: See TracBrowser for help on using the repository browser.