-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetar.php
285 lines (247 loc) · 9.29 KB
/
metar.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
/**
* METAR Information Web Service
*
* This script provides a web service that serves METAR (Meteorological Terminal Aviation Routine)
* weather reports for a specified geographic area. The data is sourced from aviationweather.gov
* and cached in a MySQL database for improved performance.
*
* Features:
* - Retrieves and caches METAR data from aviationweather.gov
* - Provides METAR information within a specified bounding box
* - Automatic cache updates when data is older than 5 minutes
* - XML output format matching aviationweather.gov schema
*
* URL Format:
* https://your-server.com/path/to/metar.php?format=xml&bbox=minLon,minLat,maxLon,maxLat
*
* Example:
* https://your-server.com/path/to/metar.php?format=xml&bbox=-5,45,15,55
*
* Required Environment Variables:
* - DB_USER: Database username
* - DB_PASS: Database password
*
* @author Stefan Kebekus
* @version 1.0
*/
// Set error reporting for production
error_reporting(E_ERROR);
ini_set('display_errors', 0);
/**
* MetarService Class
*
* Handles the retrieval, caching, and serving of METAR weather information.
*/
class MetarService {
/** @var PDO Database connection */
private $pdo;
/** @var string URL for fetching METAR data */
private $sourceUrl = 'https://aviationweather.gov/data/cache/metars.cache.xml.gz';
/** @var int Cache lifetime in seconds (5 minutes) */
private $maxAge = 300;
/**
* Constructor - Initializes database connection and ensures table exists
*
* @param string $host Database host
* @param string $dbname Database name
* @param string $username Database username
* @param string $password Database password
* @throws Exception If database connection fails
*/
public function __construct($host, $dbname, $username, $password) {
try {
$this->pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (PDOException $e) {
throw new Exception("Database connection failed: " . $e->getMessage());
}
$this->ensureTableExists();
}
/**
* Creates the cache table if it doesn't exist
*
* @throws Exception If table creation fails
*/
private function ensureTableExists() {
$sql = "CREATE TABLE IF NOT EXISTS metar_cache (
station_id VARCHAR(10) PRIMARY KEY,
latitude DECIMAL(10, 6),
longitude DECIMAL(10, 6),
metar_data TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$this->pdo->exec($sql);
}
/**
* Checks if the cached data needs to be updated
*
* @return bool True if cache is older than maxAge or empty
*/
private function needsUpdate() {
$sql = "SELECT MAX(last_updated) as last_update FROM metar_cache";
$stmt = $this->pdo->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result['last_update']) {
return true;
}
$lastUpdate = strtotime($result['last_update']);
return (time() - $lastUpdate) > $this->maxAge;
}
/**
* Updates the database with new METAR data
*
* @param string $xmlData Raw XML data from aviationweather.gov
* @throws Exception If database update fails
*/
private function updateDatabase($xmlData) {
$xml = new SimpleXMLElement($xmlData);
if (!$this->pdo->beginTransaction()) {
throw new Exception("Failed to begin transaction.");
}
try {
// Clear existing data
$this->pdo->exec("DELETE FROM metar_cache");
$insertSql = "INSERT INTO metar_cache
(station_id, latitude, longitude, metar_data)
VALUES (?, ?, ?, ?)";
$stmt = $this->pdo->prepare($insertSql);
foreach ($xml->data->METAR as $metar) {
$stmt->execute([
(string)$metar->station_id,
(float)$metar->latitude,
(float)$metar->longitude,
$metar->asXML()
]);
}
$this->pdo->commit();
} catch (Exception $e) {
$this->pdo->rollBack();
throw new Exception("Failed to update database: " . $e->getMessage());
}
}
/**
* Fetches METAR data from aviationweather.gov
*
* @return string Decompressed XML data
* @throws Exception If download or decompression fails
*/
private function fetchMetarData() {
$gzData = file_get_contents($this->sourceUrl);
if ($gzData === false) {
throw new Exception("Failed to download METAR data");
}
$xmlData = gzdecode($gzData);
if ($xmlData === false) {
throw new Exception("Failed to decompress METAR data");
}
return $xmlData;
}
/**
* Retrieves METAR data for stations within the specified bounding box
*
* @param float $minLon Minimum longitude
* @param float $minLat Minimum latitude
* @param float $maxLon Maximum longitude
* @param float $maxLat Maximum latitude
* @return array Array of METAR XML strings
* @throws Exception If data retrieval fails
*/
public function getMetarsInBoundingBox($minLon, $minLat, $maxLon, $maxLat) {
if ($this->needsUpdate()) {
$xmlData = $this->fetchMetarData();
$this->updateDatabase($xmlData);
}
$sql = "SELECT metar_data FROM metar_cache
WHERE latitude BETWEEN ? AND ?
AND longitude BETWEEN ? AND ?";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([$minLat, $maxLat, $minLon, $maxLon]);
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
}
// Configuration
$config = [
'host' => 'sql731.your-server.de',
'dbname' => 'enroutecaches',
'username' => getenv('DB_USER'),
'password' => getenv('DB_PASS')
];
// Validate input parameters
$format = $_GET['format'] ?? '';
$bbox = $_GET['bbox'] ?? '';
if ($format !== 'xml') {
header('Content-Type: application/xml');
$error = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response><errors><error>Invalid format parameter. Only XML is supported.</error></errors></response>');
echo $error->asXML();
exit;
}
if (empty($bbox)) {
header('Content-Type: application/xml');
$error = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response><errors><error>Missing bbox parameter</error></errors></response>');
echo $error->asXML();
exit;
}
// Parse and validate bbox parameter
$coords = array_map('floatval', explode(',', $bbox));
if (count($coords) !== 4) {
header('Content-Type: application/xml');
$error = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response><errors><error>Invalid bbox format. Expected: minLon,minLat,maxLon,maxLat</error></errors></response>');
echo $error->asXML();
exit;
}
[$minLat, $minLon, $maxLat, $maxLon] = $coords;
// Validate coordinate ranges
if ($minLat < -90 || $maxLat > 90 || $minLon < -180 || $maxLon > 180 || $minLat > $maxLat || $minLon > $maxLon) {
header('Content-Type: application/xml');
$error = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response><errors><error>Invalid coordinate ranges</error></errors></response>');
echo $error->asXML();
exit;
}
try {
$metarService = new MetarService(
$config['host'],
$config['dbname'],
$config['username'],
$config['password']
);
$metars = $metarService->getMetarsInBoundingBox($minLon, $minLat, $maxLon, $maxLat);
// Create response XML
$output = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' .
'<response version="1.3" ' .
'xsi:noNamespaceSchemaLocation="https://aviationweather.gov/data/schema/metar1_3.xsd" ' .
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' .
'<data_source name="metars"/>' .
'<request type="retrieve"/>' .
'<errors/>' .
'<warnings/>' .
'<time_taken_ms>0</time_taken_ms>' .
'<data/></response>');
// Set number of results
$output->data->addAttribute('num_results', count($metars));
// Add each METAR to the response
foreach ($metars as $metarXml) {
$metar = new SimpleXMLElement($metarXml);
$newMetar = $output->data->addChild('METAR');
foreach ($metar->children() as $child) {
$newChild = $newMetar->addChild($child->getName(), (string)$child);
// Copy all attributes
foreach ($child->attributes() as $key => $value) {
$newChild->addAttribute($key, (string)$value);
}
}
}
// Output XML
header('Content-Type: application/xml');
echo $output->asXML();
} catch (Exception $e) {
header('Content-Type: application/xml');
$error = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response><errors><error>' .
htmlspecialchars($e->getMessage()) .
'</error></errors></response>');
echo $error->asXML();
}