forked from iRail/iRail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vehicleinformation.php
371 lines (319 loc) · 13.6 KB
/
vehicleinformation.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
/**
* Copyright (C) 2011 by iRail vzw/asbl
* Copyright (C) 2015 by Open Knowledge Belgium vzw/asbl.
*
* This will fetch all vehicledata for the NMBS.
*
* * fillDataRoot will fill the entire dataroot with vehicleinformation
*/
include_once 'data/NMBS/tools.php';
include_once 'data/NMBS/stations.php';
include_once '../includes/simple_html_dom.php';
include_once '../includes/getUA.php';
class vehicleinformation
{
/**
* @param $dataroot
* @param $request
* @throws Exception
*/
public static function fillDataRoot($dataroot, $request)
{
$lang = $request->getLang();
$serverData = self::getServerData($request->getVehicleId(), $lang);
$html = str_get_html($serverData);
// Check if there is a valid result from the belgianrail website
if (! self::trainDrives($html)) {
throw new Exception('Route not available.', 404);
}
// Check if train splits
if (self::trainSplits($html)) {
// Two URL's, fetch serverData from matching URL
$serverData = self::parseCorrectUrl($html);
$html = str_get_html($serverData);
}
$dataroot->vehicle = self::getVehicleData($html, $request->getVehicleId(), $lang);
if ($request->getAlerts() && self::getAlerts($html)) {
$dataroot->alert = self::getAlerts($html);
}
$dataroot->stop = [];
$dataroot->stop = self::getData($html, $lang, $request->getFast());
}
/**
* @param $id
* @param $lang
* @return mixed
*/
private static function getServerData($id, $lang)
{
global $irailAgent; // from ../includes/getUA.php
$request_options = [
'referer' => 'http://api.irail.be/',
'timeout' => '30',
'useragent' => $irailAgent,
];
$scrapeURL = 'http://www.belgianrail.be/jp/sncb-nmbs-routeplanner/trainsearch.exe/'.$lang.'ld=std&seqnr=1&ident=at.02043113.1429435556&';
$id = preg_replace("/[a-z]+\.[a-z]+\.([a-zA-Z0-9]+)/smi", '\\1', $id);
$post_data = 'trainname='.$id.'&start=Zoeken&selectDate=oneday&date='.date('d%2fm%2fY').'&realtimeMode=Show';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scrapeURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $request_options['referer']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_options['timeout']);
curl_setopt($ch, CURLOPT_USERAGENT, $request_options['useragent']);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* @param $html
* @param $lang
* @param $fast
* @return array
* @throws Exception
*/
private static function getData($html, $lang, $fast)
{
try {
$stops = [];
$nodes = $html->getElementById('tq_trainroute_content_table_alteAnsicht')
->getElementByTagName('table')
->children;
$j = 0;
for ($i = 1; $i < count($nodes); $i++) {
$node = $nodes[$i];
if (! count($node->attr)) {
continue;
} // row with no class-attribute contain no data
// Delay and canceled
$splitter = '***';
$delaycontent = preg_replace("/<br\W*?\/>/", $splitter, $node->children[2]);
$delayelements = explode($splitter, strip_tags($delaycontent));
// print_r($delayelements);
$arrivalDelay = trim($delayelements[0]);
$arrivalCanceled = false;
if (!$arrivalDelay) {
$arrivalDelay = 0;
} elseif (stripos($arrivalDelay, '+') !== false) {
$arrivalDelay = preg_replace('/[^0-9]/', '', $arrivalDelay) * 60;
} else {
$arrivalDelay = 0;
$arrivalCanceled = true;
}
$departureDelay = trim($delayelements[1]);
$departureCanceled = false;
if (!$departureDelay) {
$departureDelay = $arrivalDelay ? $arrivalDelay : 0;
} elseif (stripos($departureDelay, '+') !== false) {
$departureDelay = preg_replace('/[^0-9]/', '', $departureDelay) * 60;
} else {
$departureDelay = 0;
$departureCanceled = true;
}
// Time
$timenodearray = $node->children[1]->find('span');
$arriveTime = reset($timenodearray[0]->nodes[0]->_);
$departureTime = count($nodes[$i]->children[1]->children) == 3 ? reset($nodes[$i]->children[1]->children[2]->nodes[0]->_) : $arriveTime;
if (count($node->children[3]->find('a'))) {
$as = $node->children[3]->find('a');
$stationname = reset($as[0]->nodes[0]->_);
} else {
$stationname = reset($node->children[3]->nodes[0]->_);
}
// Platform
$platformnodearray = $node->children[5]->find('span');
if (count($platformnodearray) > 0) {
$normalplatform = 0;
$platform = trim(reset($platformnodearray[0]->nodes[0]->_));
} else {
$normalplatform = 1;
$platform = trim(reset($node->children[5]->nodes[0]->_));
}
if ($platform == " ") {
$platform = '?'; // Indicate to end user platform is unknown
}
if (isset($node->children[3]->children[0])) {
$link = $node->children[3]->children[0]->{'attr'}['href'];
// With capital S
if (strpos($link, 'StationId=')) {
$nr = substr($link, strpos($link, 'StationId=') + strlen('StationId='));
} else {
$nr = substr($link, strpos($link, 'stationId=') + strlen('stationId='));
}
$nr = substr($nr, 0, strlen($nr) - 1); // delete ampersand on the end
$stationId = '00'.$nr;
}
$station = new Station();
if ($fast == 'true') {
$station->name = $stationname;
if ($stationId) {
$station->id = "BE.NMBS." . $stationId;
}
} else {
// Station ID can be parsed from the station URL
if ($stationId) {
$station = stations::getStationFromID($stationId, $lang);
} else {
$station = stations::getStationFromName($stationname, $lang);
}
}
$stops[$j] = new Stop();
$stops[$j]->station = $station;
$stops[$j]->delay = $departureDelay;
$stops[$j]->canceled = $departureCanceled;
$stops[$j]->time = tools::transformTime('00d'.$departureTime.':00', date('Ymd'));
$stops[$j]->platform = new Platform();
$stops[$j]->platform->name = $platform;
$stops[$j]->platform->normal = $normalplatform;
$j++;
}
return $stops;
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
/**
* @param $html
* @return null|Alerts
* @throws Exception
*/
private static function getAlerts($html)
{
$test = $html->getElementById('tq_trainroute_content_table_alteAnsicht');
if (! is_object($test)) {
throw new Exception('Vehicle not found', 500);
}
$tables = $html->getElementById('tq_trainroute_content_table_alteAnsicht')->getElementsByTagName('table');
$nodes = $tables[1]->getElementsByTagName('div');
$alerts = [];
foreach ($nodes as $alertnode) {
$bodysplitter = "*#*";
$alertbody = strip_tags($alertnode, '<strong>, <br>, <a>');
$alertbody = str_replace('</strong>', $bodysplitter, $alertbody);
$alertbody = str_replace('<strong>', '', $alertbody);
$alertelements = explode($bodysplitter, $alertbody);
$header = preg_replace("/ |\s*\(.*?\)\s*/i", '', $alertelements[0]);
$alert = new Alert();
$alert->header = html_entity_decode(htmlentities(trim($header)));
$alert->description = html_entity_decode(htmlentities(trim($alertelements[1])));
array_push($alerts, $alert);
}
return $alerts;
}
/**
* @param $html
* @param $id
* @param $lang
* @return null|Vehicle
* @throws Exception
*/
private static function getVehicleData($html, $id, $lang)
{
// determine the location of the vehicle
$test = $html->getElementById('tq_trainroute_content_table_alteAnsicht');
if (! is_object($test)) {
throw new Exception('Vehicle not found', 500);
} // catch errors
$nodes = $html->getElementById('tq_trainroute_content_table_alteAnsicht')->getElementByTagName('table')->children;
for ($i = 1; $i < count($nodes); $i++) {
$node = $nodes[$i];
if (! count($node->attr)) {
continue;
} // row with no class-attribute contain no data
if (count($node->children[3]->find('a'))) {
$as = $node->children[3]->find('a');
$stationname = reset($as[0]->nodes[0]->_);
} else {
// Foreign station, no anchorlink
$stationname = reset($node->children[3]->nodes[0]->_);
}
$locationX = 0;
$locationY = 0;
// Station ID can be parsed from the station URL
if (isset($node->children[3]->children[0])) {
$link = $node->children[3]->children[0]->{'attr'}['href'];
// With capital S
if (strpos($link, 'StationId=')) {
$nr = substr($link, strpos($link, 'StationId=') + strlen('StationId='));
} else {
$nr = substr($link, strpos($link, 'stationId=') + strlen('stationId='));
}
$nr = substr($nr, 0, strlen($nr) - 1); // delete ampersand on the end
$stationId = '00'.$nr;
$station = stations::getStationFromID($stationId, $lang);
} else {
$station = stations::getStationFromName($stationname, $lang);
}
if (isset($station)) {
$locationX = $station->locationX;
$locationY = $station->locationY;
}
$vehicle = new Vehicle();
$vehicle->name = $id;
$vehicle->locationX = $locationX;
$vehicle->locationY = $locationY;
return $vehicle;
}
return;
}
private static function trainSplits($html)
{
return ! is_object($html->getElementById('tq_trainroute_content_table_alteAnsicht'));
}
private static function trainDrives($html)
{
return is_object($html->getElementById('HFSResult')->getElementByTagName('table'));
}
private static function parseCorrectUrl($html)
{
$test = $html->getElementById('HFSResult')->getElementByTagName('table');
if (! is_object($test)) {
throw new Exception('Vehicle not found', 500);
} // catch errors
// Try first url
$url = $html->getElementById('HFSResult')
->getElementByTagName('table')
->children[1]->children[0]->children[0]->attr['href'];
$serverData = self::getServerDataByUrl($url);
// Check if no other route id in trainname column
if (self::isOtherTrain($serverData)) {
// Second url must be the right one
$url = $html->getElementById('HFSResult')
->getElementByTagName('table')
->children[2]->children[0]->children[0]->attr['href'];
$serverData = self::getServerDataByUrl($url);
}
return $serverData;
}
private static function isOtherTrain($serverData)
{
$html = str_get_html($serverData);
$traindata = $html->getElementById('tq_trainroute_content_table_alteAnsicht');
return ! is_object($traindata);
}
private static function getServerDataByUrl($url)
{
global $irailAgent; // from ../includes/getUA.php
include_once '../includes/getUA.php';
$request_options = [
'referer' => 'http://api.irail.be/',
'timeout' => '30',
'useragent' => $irailAgent,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $request_options['referer']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_options['timeout']);
curl_setopt($ch, CURLOPT_USERAGENT, $request_options['useragent']);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
};