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

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

Fixed inconsistent slash handling in WEBSERVICE_BASE_URL cmake setting and further processing in the php files

  • 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 .= " zipcode TEXT,";
240 $sql .= " region INTEGER,";
241 $sql .= " FOREIGN KEY(region) REFERENCES regions(id)";
242 $sql .= ")";
243 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
244 return false;
245 }
246 // creating a POINT Geometry column named center,
247 // taking two coordinates in SRID 4326 (WGS84) format
248 $sql = "SELECT AddGeometryColumn(\"". $table ."\", ";
249 $sql .= "\"location\", 4326, \"POINT\", \"XY\")";
250 if(!$this->_databaseHandler->exec($sql)){
251 $errorMessage = Translation::swGettext("Could not create location field for %s table", $table);
252 return false;
253 }
254 }
255
256 // prepare stations table
257 $table = "stations";
258 if(!$this->databaseTableExists($table)){
259 $sql = "CREATE TABLE ". $table ." (";
260 $sql .= " id INTEGER NOT NULL PRIMARY KEY,";
261 $sql .= " name TEXT NOT NULL,";
262 $sql .= " city INTEGER,";
263 $sql .= " FOREIGN KEY(city) REFERENCES cities(id)";
264 $sql .= ")";
265 if(!$this->databaseTableCreate($table, $sql, $errorMessage)){
266 return false;
267 }
268 // creating a POINT Geometry column named center,
269 // taking two coordinates in SRID 4326 (WGS84) format
270 $sql = "SELECT AddGeometryColumn(\"". $table ."\", ";
271 $sql .= "\"location\", 4326, \"POINT\", \"XY\")";
272 if(!$this->_databaseHandler->exec($sql)){
273 $errorMessage = Translation::swGettext("Could not create location field for %s table", $table);
274 return false;
275 }
276 }
277
278 return true;
279 }
280
281 public function databaseVersionSqlite(&$errorMessage){
282 if(!is_object($this->_databaseHandler)){
283 return 0;
284 }
285 $result = $this->_databaseHandler->versionSqlite();
286 if($result == 0){
287 $errorMessage = $this->_databaseHandler->lastErrorMessage();
288 }
289 return $result;
290 }
291
292 public function databaseVersionSpatalite(&$errorMessage){
293 if(!is_object($this->_databaseHandler)){
294 return 0;
295 }
296 $result = $this->_databaseHandler->versionSpatialite();
297 if($result == 0){
298 $errorMessage = $this->_databaseHandler->lastErrorMessage();
299 }
300 return $result;
301 }
302
303 public function apiCheckWithoutRewrite(&$errorMessage){
304 return $this->apiCheck("index.php/stations", $errorMessage);
305 }
306
307 public function apiCheckWithRewrite(&$errorMessage){
308 return $this->apiCheck("stations", $errorMessage);
309 }
310
311 private function getProcessUser(){
312 $processUser = posix_getpwuid(posix_getuid());
313 return $processUser["name"];
314 }
315
316 private function getProcessGroup(){
317 $processGroup = posix_getgrgid(posix_getgid());
318 return $processGroup["name"];
319 }
320
321 private function apiCheck($url, &$errorMessage){
322 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();
323 if(!$baseUrl || empty($baseUrl)){
324 $errorMessage = _("No webservice base url given!");
325 return false;
326 }
327
328 # base_url needs to end with a /, otherwise the last element is chopped
329 $client = new \GuzzleHttp\Client
330 (
331 [
332 "base_uri" => $baseUrl,
333 "timeout" => 2.0,
334 "http_errors" => false,
335 ]
336 );
337 $response = $client->get($url);
338 if(is_null($response)){
339 $errorMessage = \Translator::swGettext("Webservice has not answered at url %s!", $baseUrl);
340 return false;
341 }
342 $result = $response->getStatusCode();
343 if($result != 200){
344 $errorMessage = \Translator::swGettext("Got http error %s (%s) at url %s", $result, $response->getReasonPhrase(), $baseUrl . $url);
345 return false;
346 }
347 $result = $response->getReasonPhrase();
348 if($result != "OK"){
349 $errorMessage = \Translator::swGettext("Got a http error reason with http code 200: %s", $result);
350 return false;
351 }
352
353 $body = $response->getBody();
354 if(empty($body)){
355 $errorMessage = _("Got empty return value");
356 return false;
357 }
358
359 $json = json_decode($body);
360 if(is_null($json)){
361 $errorMessage = _("Could not decode json message body");
362 return false;
363 }
364 return true;
365 }
366
367 private function databaseTableExists($table){
368 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
369 return false;
370 }
371 $statement = $this->_databaseHandler->prepare("SELECT COUNT(*) FROM sqlite_master WHERE type=\"table\" AND name=:name");
372 if(!$statement){
373 $errorMessage = \Translator::swGettext("Could not prepare query to check if table %s exists", $table);
374 return false;
375 }
376 $statement->bindValue(":name", $table);
377 $result = $statement->execute();
378 $row = $result->fetchArray();
379 if(!$row || !is_array($row) || count($row) < 1 || $row[0] != 1)
380 return false;
381 return true;
382 }
383
384 private function databaseTableCreate($table, $sqlStatement, &$errorMessage){
385 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
386 return false;
387 }
388 if(!$this->_databaseHandler->exec("BEGIN")){
389 $errorMessage = \Translator::swGettext("Could not start transaction to create table %s", $table);
390 return false;
391 }
392 if(!$this->_databaseHandler->exec($sqlStatement)){
393 $errorMessage = \Translator::swGettext("Could not execute sql statement to create table %s:\n%s", $table, $sqlStatement);
394 return false;
395 }
396 if(!$this->_databaseHandler->exec("COMMIT")){
397 $errorMessage = \Translator::swGettext("Could not commit transaction to create table %s", $table);
398 return false;
399 }
400 return true;
401 }
402
403 private $_webserviceConfig;
404 private $_dataDirectory;
405 private $_databaseHandler;
406 private $_databaseFile;
407 private $_databaseFirstConnection;
408}
409
410?>
Note: See TracBrowser for help on using the repository browser.