close Warning: AdminModule failed with TracError: Unable to instantiate component <class 'trac.admin.web_ui.BasicsAdminPanel'> (super(type, obj): obj (type BasicsAdminPanel) is not an instance or subtype of type (Markup).)

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

Last change on this file since d83a844 was 098c36e, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago

Improved setup routine regarding the api test functions

  • Property mode set to 100644
File size: 14.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
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,";
[69c8290]260 $sql .= " uuid TEXT NOT NULL,";
261 $sql .= " ownerMail TEXT NOT NULL,";
[b38cc03]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 }
[8c356c1]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){
[1e37648]307 return $this->apiCheck("stations", $errorMessage);
[8c356c1]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){
[1e37648]321 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();
[8c356c1]322 if(!$baseUrl || empty($baseUrl)){
[b38cc03]323 $errorMessage = _("No webservice base url given!");
[8c356c1]324 return false;
325 }
326
[1e37648]327 # base_url needs to end with a /, otherwise the last element is chopped
[098c36e]328 try{
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 }
339 catch(\GuzzleHttp\Exception\ConnectException $exception){
340 $errorMessage = \Translator::swGettext("Webservce has not answered at url %s! Error: %s", $baseUrl, $exception->getMessage());
341 return false;
342 }
[8c356c1]343 if(is_null($response)){
[b38cc03]344 $errorMessage = \Translator::swGettext("Webservice has not answered at url %s!", $baseUrl);
[8c356c1]345 return false;
346 }
347 $result = $response->getStatusCode();
348 if($result != 200){
[552da81]349 $errorMessage = \Translator::swGettext("Got http error %s (%s) at url %s", $result, $response->getReasonPhrase(), $baseUrl . $url);
[8c356c1]350 return false;
351 }
352 $result = $response->getReasonPhrase();
353 if($result != "OK"){
[b38cc03]354 $errorMessage = \Translator::swGettext("Got a http error reason with http code 200: %s", $result);
[8c356c1]355 return false;
356 }
357
358 $body = $response->getBody();
359 if(empty($body)){
[b38cc03]360 $errorMessage = _("Got empty return value");
[8c356c1]361 return false;
362 }
363
364 $json = json_decode($body);
365 if(is_null($json)){
[b38cc03]366 $errorMessage = _("Could not decode json message body");
367 return false;
368 }
369 return true;
370 }
371
372 private function databaseTableExists($table){
373 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
374 return false;
375 }
376 $statement = $this->_databaseHandler->prepare("SELECT COUNT(*) FROM sqlite_master WHERE type=\"table\" AND name=:name");
377 if(!$statement){
378 $errorMessage = \Translator::swGettext("Could not prepare query to check if table %s exists", $table);
379 return false;
380 }
381 $statement->bindValue(":name", $table);
382 $result = $statement->execute();
383 $row = $result->fetchArray();
384 if(!$row || !is_array($row) || count($row) < 1 || $row[0] != 1)
385 return false;
386 return true;
387 }
388
389 private function databaseTableCreate($table, $sqlStatement, &$errorMessage){
390 if(!$this->_databaseHandler || !is_object($this->_databaseHandler)){
391 return false;
392 }
393 if(!$this->_databaseHandler->exec("BEGIN")){
394 $errorMessage = \Translator::swGettext("Could not start transaction to create table %s", $table);
395 return false;
396 }
397 if(!$this->_databaseHandler->exec($sqlStatement)){
398 $errorMessage = \Translator::swGettext("Could not execute sql statement to create table %s:\n%s", $table, $sqlStatement);
399 return false;
400 }
401 if(!$this->_databaseHandler->exec("COMMIT")){
402 $errorMessage = \Translator::swGettext("Could not commit transaction to create table %s", $table);
[8c356c1]403 return false;
404 }
405 return true;
406 }
407
408 private $_webserviceConfig;
409 private $_dataDirectory;
410 private $_databaseHandler;
411 private $_databaseFile;
[b38cc03]412 private $_databaseFirstConnection;
[8c356c1]413}
414
415?>
Note: See TracBrowser for help on using the repository browser.