ACARS::getArchiveAcarsData()   F
last analyzed

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
nc 46692
nop 2
dl 0
loc 87
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This class is part of FlightAirmap. It's used to parse ACARS messages.
4
 *
5
 * Copyright (c) Ycarus (Yannick Chabanois) at Zugaina <[email protected]>
6
 * Licensed under AGPL license.
7
 * For more information see: https://www.flightairmap.com/
8
*/
9
10
require_once(dirname(__FILE__).'/class.Connection.php');
11
require_once(dirname(__FILE__).'/class.Spotter.php');
12
require_once(dirname(__FILE__).'/class.SpotterImport.php');
13
require_once(dirname(__FILE__).'/class.Image.php');
14
require_once(dirname(__FILE__).'/class.Scheduler.php');
15
require_once(dirname(__FILE__).'/class.Translation.php');
16
17
class ACARS {
18
	public $db;
19
	public $SI;
20
	private $fromACARSscript = false;
21
22
	/*
23
	 * Initialize DB connection
24
	*/
25
	public function __construct($dbc = null,$fromACARSscript = false) {
26
		$Connection = new Connection($dbc);
27
		$this->db = $Connection->db();
28
		if ($this->db === null) die('Error: No DB connection. (ACARS)');
29
		if ($fromACARSscript) {
30
			$this->fromACARSscript = true;
31
			$this->SI = new SpotterImport($this->db);
32
		}
33
	}
34
35
	/**
36
	* Change IATA to ICAO value for ident
37
	*
38
	* @param String $ident ident
39
	* @return String the icao
40
	*/
41
	public function ident2icao($ident) {
42
		if (substr($ident,0,2) == 'AF') {
43
			if (filter_var(substr($ident,2),FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))) $icao = $ident;
44
			else $icao = 'AFR'.ltrim(substr($ident,2),'0');
45
		} else {
46
			$Spotter = new Spotter($this->db);
47
			$identicao = $Spotter->getAllAirlineInfo(substr($ident,0,2));
48
			if (isset($identicao[0])) {
49
				$icao = $identicao[0]['icao'].ltrim(substr($ident,2),'0');
50
			} else $icao = $ident;
51
		}
52
		return $icao;
53
	}
54
55
	/**
56
	* Deletes all info in the live table
57
	*
58
	* @return String success or false
59
	*
60
	*/
61
	public function deleteLiveAcarsData()
62
	{
63
		global $globalDBdriver;
64
		if ($globalDBdriver == 'mysql') {
65
			$query  = "DELETE FROM acars_live WHERE acars_live.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)";
66
		} else {
67
			$query  = "DELETE FROM acars_live WHERE acars_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
68
		}
69
		try {
70
71
			$sth = $this->db->prepare($query);
72
			$sth->execute();
73
		} catch(PDOException $e) {
74
			return "error";
75
		}
76
		return "success";
77
	}
78
79
	/**
80
	* Deletes all info in the archive table
81
	*
82
	* @return String success or false
83
	*
84
	*/
85
	public function deleteArchiveAcarsData()
86
	{
87
		global $globalACARSArchiveKeepMonths, $globalDBdriver;
88
		if ($globalDBdriver == 'mysql') {
89
			$query  = "DELETE FROM acars_archive WHERE acars_archive.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL ".$globalACARSArchiveKeepMonths." MONTH)";
90
		} else {
91
			$query  = "DELETE FROM acars_archive WHERE acars_archive.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalACARSArchiveKeepMonths." MONTHS'";
92
		}
93
		try {
94
95
			$sth = $this->db->prepare($query);
96
			$sth->execute();
97
		} catch(PDOException $e) {
98
			return "error";
99
		}
100
		return "success";
101
	}
102
103
104
    /**
105
     * Parse ACARS data
106
     *
107
     * @param String ACARS data in acarsdec data
108
     *
109
     * @return array
110
     */
111
	public function parse($data) {
112
		global $globalDebug;
113
		//$Image = new Image($this->db);
114
		//$Schedule = new Schedule($this->db);
115
		//$Translation = new Translation($this->db);
116
		$registration = '';
117
		$label = '';
118
		$block_id = '';
119
		$msg_no = '';
120
		$ident = '';
121
		$message = '';
122
		$result = array();
123
		$n = sscanf($data,'%*[0-9a-z.] %*d %*02d/%*02d/%*04d %*02d:%*02d:%*02d %*d %*[0-9-] %*[A-Z0-9] %7s %*c %2[0-9a-zA-Z_] %d %4[0-9A-Z] %6[0-9A-Z] %[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
124
		if ($n == 0 || $message == '') $n = sscanf($data,'AC%*c %7s %*c %2[0-9a-zA-Z_] %d %4[0-9A-Z] %6[0-9A-Z] %[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
125
		if ($n == 0 || $message == '') $n = sscanf($data,'%*04d-%*02d-%*02d,%*02d:%*02d:%*02d,%*7s,%*c,%6[0-9A-Z-],%*c,%2[0-9a-zA-Z_],%d,%4[0-9A-Z],%6[0-9A-Z],%[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
126
		if ($n == 0 || $message == '') $n = sscanf($data,'%*04d-%*02d-%*02d,%*02d:%*02d:%*02d,%*7s,%*c,%6[0-9A-Z-],,%2[0-9a-zA-Z_],%d,%4[0-9A-Z],%6[0-9A-Z],%[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
127
		if ($n == 0 || $message == '') $n = sscanf($data,'%*04d-%*02d-%*02d,%*02d:%*02d:%*02d,%*7s,%*c,%5[0-9A-Z],%*c,%2[0-9a-zA-Z_],%d,%4[0-9A-Z],%6[0-9A-Z],%[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
128
		if ($n == 0 || $message == '') $n = sscanf($data,'%*04d-%*02d-%*02d,%*02d:%*02d:%*02d,%*7s,%*c,%6[0-9A-Z-],%*c,%2[0-9a-zA-Z_],%d,%4[0-9A-Z],%6[0-9A-Z],%[^\r\n]',$registration,$label,$block_id,$msg_no,$ident,$message);
129
		if ($n != 0 && ($registration != '' || $ident != '' || $label != '' || $block_id != '' || $msg_no != '')) {
130
			$registration = str_replace('.','',$registration);
131
			$result = array('registration' => $registration, 'ident' => $ident,'label' => $label, 'block_id' => $block_id,'msg_no' => $msg_no,'message' => $message);
132
			if ($globalDebug) echo "Reg. : ".$registration." - Ident : ".$ident." - Label : ".$label." - Message : ".$message."\n";
133
		} else $message = $data;
134
		$decode = array();
135
		$found = false;
136
//		if ($registration != '' && $ident != '' && $registration != '!') {
137
			if (!$found) {
138
				// example message : "FST01EGLLLIRFN047599E0033586390  55  25- 4C 74254      487  2059194"
139
				//								    FST01MMMXEGKKN376904W079449733007380380 019061 XA1237 =>  wind direction and velocity (019/061)
140
				//$n = sscanf($message, "FST01%4c%4c%c%06d%c%07d%*11[0-9a-zA-Z ]-%02dC", $dair, $darr, $lac, $la, $lnc, $ln, $temp);
141
				$dair = '';
142
				$darr = '';
143
				$lac = '';
144
				$la = '';
145
				$lnc = '';
146
				$ln = '';
147
				$alt = '';
148
				$temp = '';
149
				$n = sscanf($message, "FST01%4c%4c%c%06d%c%07d%03d%*8[0-9a-zA-Z ]-%02dC", $dair, $darr, $lac, $la, $lnc, $ln, $alt, $temp);
150
				if ($n > 5 && ($lac == 'N' || $lac == 'S') && ($lnc == 'E' || $lnc == 'W')) {
151
					$latitude = $la / 10000.0;
152
					$longitude = $ln / 10000.0;
153
					if ($lac == 'S') $latitude = '-'.$latitude;
154
					if ($lnc == 'W') $longitude = '-'.$longitude;
155
					// Temp not always available
156
					if ($globalDebug) echo 'latitude : '.$latitude.' - longitude : '.$longitude.' - airport depart : '.$dair.' - airport arrival : '.$darr.' - température : '.$temp."°C\n";
157
					if ($temp == '') $decode = array('Latitude' => $latitude, 'Longitude' =>  $longitude, 'Departure airport' => $dair, 'Arrival airport' => $darr,'Altitude' => $alt);
158
					else $decode = array('Latitude' => $latitude, 'Longitude' =>  $longitude, 'Departure airport' => $dair, 'Arrival airport' => $darr, 'Altitude' => 'FL'.$alt,'Temperature' => $temp.'°C');
159
160
					//$icao = $Translation->checkTranslation($ident);
161
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
162
					$found = true;
163
				}
164
			}
165
			if (!$found && ($label == '10')) {
166
				$dair = '';
167
				$dhour = '';
168
				$darr = '';
169
				$ahour = '';
170
				$n = sscanf($message, "ARR01 %4[A-Z]%4d %4[A-Z]%4d", $dair, $dhour, $darr,$ahour);
171
				if ($n == 4 && strlen($darr) == 4) {
172
					if ($dhour != '') $dhour = substr(sprintf('%04d',$dhour),0,2).':'.substr(sprintf('%04d',$dhour),2);
173
					if ($ahour != '') $ahour = substr(sprintf('%04d',$ahour),0,2).':'.substr(sprintf('%04d',$ahour),2);
174
					if ($globalDebug) echo 'departure airport : '.$dair.' - arrival airport : '. $darr.' - departure hour : '. $dhour.' - arrival hour : '.$ahour."\n";
175
					//$icao = ACARS->ident2icao($ident);
176
					//$icao = $Translation->checkTranslation($ident);
177
					//$Schedule->addSchedule($icao,$dair,$dhour,$darr,$ahour,'ACARS');
178
					$decode = array('Departure airport' => $dair, 'Departure hour' => $dhour, 'Arrival airport' => $darr, 'Arrival hour' => $ahour);
179
					$found = true;
180
				}
181
				elseif ($n == 2 || $n  == 4) {
182
					if ($dhour != '') $dhour = substr(sprintf('%04d',$dhour),0,2).':'.substr(sprintf('%04d',$dhour),2);
183
					if ($globalDebug) echo 'airport arrival : '.$dair.' - arrival hour : '.$dhour."\n";
184
					//$icao = ACARS->ident2icao($ident);
185
					//$icao = $Translation->checkTranslation($ident);
186
					$decode = array('Arrival airport' => $dair, 'Arrival hour' => $dhour);
187
					$found = true;
188
				}
189
				elseif ($n == 1) {
190
					if ($globalDebug) echo 'airport arrival : '.$darr."\n";
191
					//$icao = ACARS->ident2icao($ident);
192
					//$icao = $Translation->checkTranslation($ident);
193
					$decode = array('Arrival airport' => $darr);
194
					$found = true;
195
				}
196
197
			}
198
			if (!$found && ($label == '13' || $label == '12')) {
199
				// example message : "Reg. : OO-DWA - Ident : SN01LY - Label : 13 - Message : EBBR,LFLL,26FEB15,1626,164626"
200
				/*
201
				Reg. : OO-SSP - Ident : SN01LY - Label : 13 - Message : EBBR,LFLL,27FEB15,1624,164400
202
				N 46.493,E  3.980,19810
203
				*/
204
				$dair = '';
205
				$darr = '';
206
				$n = sscanf($message, "%4c,%4c,%*7s,%*d", $dair, $darr);
207
				if ($n == 4) {
208
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
209
					//$icao = ACARS->ident2icao($ident);
210
					//$icao = $Translation->checkTranslation($ident);
211
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
212
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
213
					$found = true;
214
				}
215
			}
216
			if (!$found) {
217
				/*
218
				example message :
219
				    VER/071/A320/M
220
				    SCH/AF6244/LFPO/LFMN/25FEB/0905
221
				    FTX/ADDRESS/DEST STA/LFMN
222
				*/
223
				/*
224
				example message :
225
				    VER/070/A319/M
226
				    SCH/AF7671/LFML/LFPG/23FEB/1820
227
				    WXR/META/LFLL/LFLC/LFPG
228
				*/
229
230
				//$n = sscanf($message, "%*[0-9A-Z]/%*3d/%4s/%*c\nSCH/%6[0-9A-Z ]/%4c/%4c/%5s/%4d\n%*3c/%4d/%4c/%[0-9A-Z ]/", $airicao,$aident,$dair, $darr, $ddate, $dhour,$ahour, $aair, $apiste);
231
				$airicao = '';
232
				$aident = '';
233
				$dair = '';
234
				$darr = '';
235
				$ddate = '';
236
				$dhour = '';
237
				$ahour = '';
238
				$aair = '';
239
				$apiste = '';
240
				$n = sscanf(str_replace(array("\r\n", "\n", "\r"),'',$message), "%*[0-9A-Z]/%*3d/%4s/%*cSCH/%6[0-9A-Z ]/%4c/%4c/%5s/%4d%*3c/%4d/%4c/%[0-9A-Z ]/", $airicao,$aident,$dair, $darr, $ddate, $dhour,$ahour, $aair, $apiste);
241
				if ($n > 8) {
242
					if ($globalDebug) echo 'airicao : '. $airicao.' - ident : '.$aident.' - departure airport : '.$dair.' - arrival airport : '. $darr.' - date depart : '.$ddate.' - departure hour : '. $dhour.' - arrival hour : '.$ahour.' - arrival airport : '.$aair.' - arrival piste : '.$apiste."\n";
243
					if ($dhour != '') $dhour = substr(sprintf('%04d',$dhour),0,2).':'.substr(sprintf('%04d',$dhour),2);
244
					if ($ahour != '') $ahour = substr(sprintf('%04d',$ahour),0,2).':'.substr(sprintf('%04d',$ahour),2);
245
					$icao = trim($aident);
246
247
					//$decode = 'Departure airport : '.$dair.' ('.$ddate.' at '.$dhour.') - Arrival Airport : '.$aair.' (at '.$ahour.') way '.$apiste;
248
					if ($ahour == '') $decode = array('Departure airport' => $dair, 'Departure date' => $ddate, 'Departure hour' => $dhour, 'Arrival airport' => $darr);
249
					else $decode = array('Departure airport' => $dair, 'Departure date' => $ddate, 'Departure hour' => $dhour, 'Arrival airport' => $darr, 'Arrival hour' => $ahour, 'Arrival way' => $apiste);
250
					//$Schedule->addSchedule($icao,$dair,$dhour,$darr,$ahour,'ACARS');
251
					$decode['icao'] = $icao;
252
					$found = true;
253
				}
254
			}
255
256
			if (!$found) {
257
				// example message : "221111,34985,0817,  65,N 50.056 E 13.850"
258
				//Reg. : CS-TFY - Ident : CR0321 - Label : 16 - Message : 140600,34008,1440,  66,N 46.768 E  4.793
259
				$lac = '';
260
				$las = '';
261
				$lass = '';
262
				$lnc = '';
263
				$lns = '';
264
				$lnss = '';
265
				$n = sscanf($message, "%*6c,%*5c,%*4c,%*4c,%c%3d.%3d %c%3d.%3d,", $lac, $las, $lass, $lnc, $lns, $lnss);
266
				if ($n == 10 && ($lac == 'N' || $lac == 'S') && ($lnc == 'E' || $lnc == 'W')) {
267
					$las = $las.'.'.$lass;
268
					$lns = $lns.'.'.$lns;
269
					$latitude = $las / 1000.0;
270
					$longitude = $lns / 1000.0;
271
					if ($lac == 'S') $latitude = '-'.$latitude;
272
					if ($lnc == 'W') $longitude = '-'.$longitude;
273
					if ($globalDebug) echo 'latitude : '.$latitude.' - longitude : '.$longitude."\n";
274
					$decode = array('Latitude' => $latitude, 'Longitude' => $longitude);
275
					$found = true;
276
				}
277
			}
278
			if (!$found && $label == '5U') {
279
				/*
280
				example message :
281
				    Reg. : CN-RNR - Ident : AT816C - Label : 5U - Message :   01 WXRQ   816C/27 GMMN/EDDT .CN-RNR
282
				/TYP 1/STA EDDT/STA LSZH/STA EDDS
283
				Reg. : G-OOBD - Ident : DP079T - Label : 5U - Message :   01 WXRQ   079T/28 LIPX/EGKK .G-OOBD
284
				/TYP 1/STA EGKK/STA EGLL/STA EGHH
285
286
				*/
287
				$dair = '';
288
				$darr = '';
289
				$n = sscanf($message, "%*[0-9A-Z ]/%*s %4c/%4c .", $dair, $darr);
290
				if ($n == 4) {
291
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
292
					//$icao = $Translation->checkTranslation($ident);
293
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
294
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
295
					$found = true;
296
				}
297
			}
298
			if (!$found && $label == '1L') {
299
				// example message : "Reg. : TS-ION - Ident : TU0634 - Label : 1L - Message : 000442152001337,DTTJ,LFPO,1609"
300
				$dair = '';
301
				$darr = '';
302
				$n = sscanf($message, "%*[0-9],%4c,%4c,", $dair, $darr);
303
				if ($n == 4) {
304
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
305
					//$icao = $Translation->checkTranslation($ident);
306
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
307
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
308
					$found = true;
309
				}
310
			}
311
			if (!$found && $label == '5U') {
312
				// example message : "Reg. : OO-TAH - Ident : 3V042J - Label : 5U - Message : 002AF   EBLG EBBR                     N4621.5E  524.2195"
313
				$dair = '';
314
				$darr = '';
315
				$n = sscanf($message, "002AF %4c %4c ", $dair, $darr);
316
				if ($n == 2) {
317
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
318
					//$icao = $Translation->checkTranslation($ident);
319
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
320
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
321
					$found = true;
322
				}
323
			}
324
325
			if (!$found && $label == 'H1') {
326
				// example message : 'Reg. : F-GHQJ - Ident : AF6241 - Label : H1 - Message : #DFBA01/CCF-GHQJ,FEB27,205556,LFMN,LFPO,0241/C106,17404,5000,42,0010,0,0100,42,X/CEN270,36012,257,778,6106,299,B5B7G8/EC731134,42387,01439,41194,12/EE731212,44932,11870,43555,12/N10875,0875,0910,6330,1205,-----'
327
				$dair = '';
328
				$darr = '';
329
				$n = sscanf($message, "#DFBA%*02d/%*[A-Z-],%*[0-9A-Z],%*d,%4c,%4c", $dair, $darr);
330
				if ($n == 6) {
331
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
332
					//$icao = $Translation->checkTranslation($ident);
333
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
334
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
335
					$found = true;
336
				}
337
			}
338
			if (!$found && $label == 'H1') {
339
				// example message : 'Reg. : F-GUGP - Ident : AF1842 - Label : H1 - Message : #DFBA01/A31801,1,1/CCF-GUGP,MAR11,093856,LFPG,LSGG,1842/C106,55832,5000,37,0010,0,0100,37,X/CEN282,31018,277,750,5515,255,C11036/EC577870,02282,07070,01987,73,14/EE577871,02282,06947,01987,73/N10790,0790,0903,5'
340
				$dair = '';
341
				$darr = '';
342
				$n = sscanf($message, "#DFBA%*02d/%*[0-9A-Z,]/%*[A-Z-],%*[0-9A-Z],%*d,%4c,%4c", $dair, $darr);
343
				if ($n == 7) {
344
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
345
					//$icao = $Translation->checkTranslation($ident);
346
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
347
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
348
					$found = true;
349
				}
350
			}
351
			if (!$found) {
352
				/* example message :
353
				 Reg. : PH-BXO - Ident : KL079K - Label : H1 - Message : #DFB(POS-KLM79K  -4319N00252E/143435 F390
354
				RMK/FUEL   2.6 M0.79)
355
				*/
356
				//$n = sscanf($message, "#DFB(POS-%s -%4d%c%5d%c/%*d F%d\nRMK/FUEL %f M%f", $aident, $las, $lac, $lns, $lnc, $alt, $fuel, $speed);
357
				$aident = '';
358
				$las = '';
359
				$lac = '';
360
				$lns = '';
361
				$lnc = '';
362
				$alt = '';
363
				$fuel = '';
364
				$speed = '';
365
				$n = sscanf(str_replace(array("\r\n", "\n", "\r"),'',$message), "#DFB(POS-%s -%4d%c%5d%c/%*d F%dRMK/FUEL %f M%f", $aident, $las, $lac, $lns, $lnc, $alt, $fuel, $speed);
366
				if ($n == 9) {
367
					//if (self->$debug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
368
					$icao = trim($aident);
369
					$decode['icao'] = $icao;
370
					$latitude = $las / 100.0;
371
					$longitude = $lns / 100.0;
372
					if ($lac == 'S') $latitude = '-'.$latitude;
373
					if ($lnc == 'W') $longitude = '-'.$longitude;
374
375
					$decode = array('Latitude' => $latitude,'Longitude' => $longitude,'Altitude' => 'FL'.$alt,'Fuel' => $fuel,'speed' => $speed);
376
					$found = true;
377
				}
378
			}
379
			if (!$found) {
380
				/* example message :
381
				Reg. : F-HBSA - Ident : XK505F - Label : 16 - Message : LAT N 46.184/LON E  5.019
382
				*/
383
				$lac = '';
384
				$las = '';
385
				$lnc = '';
386
				$lns = '';
387
				$n = sscanf($message, "LAT %c %f/LON %c %f", $lac, $las, $lnc, $lns);
388
				if ($n == 4) {
389
					$latitude = $las;
390
					$longitude = $lns;
391
					if ($lac == 'S') $latitude = '-'.$latitude;
392
					if ($lnc == 'W') $longitude = '-'.$longitude;
393
394
					$decode = array('Latitude' => $latitude,'Longitude' => $longitude);
395
					$found = true;
396
				}
397
			}
398
399
			if (!$found && $label == '80') {
400
				/* example message :
401
				Reg. : EI-DSB - Ident : AZ0207 - Label : 80 - Message : 3X01 NLINFO 0207/28 EGLL/LIRF .EI-DSB
402
				/AZ/1783/28/FCO/N
403
				*/
404
				$dair = '';
405
				$darr = '';
406
				$n = sscanf($message, "%*[0-9A-Z] NLINFO %*d/%*d %4c/%4c .", $dair, $darr);
407
				if ($n == 5) {
408
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
409
					//$icao = $Translation->checkTranslation($ident);
410
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
411
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
412
					$found = true;
413
				}
414
			}
415
			if (!$found) {
416
				/* example message :
417
				Reg. : D-ABNK - Ident : AB930V - Label : 3O - Message : HB50,,
418
				930V,12MAR15,EDDH,LEPA,.D-ABNK,
419
				LEPA,
420
				AB7757,
421
				DABNK,10100,  7100,02:46, 200, 44068,52.4, 77000, 62500, 66000,3, 4,
422
				*/
423
				// $n = sscanf($message, "%*[0-9A-Z],,\n%*[0-9A-Z],%*[0-9A-Z],%4s,%4s,.%*6s,\n%*4[A-Z],\n%[0-9A-Z],", $dair, $darr, $aident);
424
				$dair = '';
425
				$darr = '';
426
				$aident = '';
427
				$n = sscanf(str_replace(array("\r\n", "\n", "\r"),'',$message), "%*[0-9A-Z],,%*[0-9A-Z],%*[0-9A-Z],%4s,%4s,.%*6s,%*4[A-Z],%[0-9A-Z],", $dair, $darr, $aident);
428
				if ($n == 8) {
429
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
430
					$icao = trim($aident);
431
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
432
					$decode['icao'] = $icao;
433
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
434
					$found = true;
435
				}
436
			}
437
			if (!$found) {
438
				/* example message :
439
				Reg. : N702DN - Ident : DL0008 - Label : 80 - Message : 3401/11 KATL/OMDB .N702DN
440
				ACK RDA
441
				*/
442
				$dair = '';
443
				$darr = '';
444
				$n = sscanf($message, "%*d/%*d %4s/%4s .%*6s", $dair, $darr);
445
				if ($n == 5) {
446
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
447
					//$icao = $Translation->checkTranslation($ident);
448
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
449
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
450
					$found = true;
451
				}
452
			}
453
			if (!$found) {
454
				/* example message :
455
				LFLLLFRS1315U2687X
456
				*/
457
				$dair = '';
458
				$darr = '';
459
				$n = sscanf($message,'%4[A-Z]%4[A-Z]%*4d',$dair,$darr);
460
				if ($n == 3) {
461
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
462
					//$icao = $Translation->checkTranslation($ident);
463
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
464
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
465
					$found = true;
466
				}
467
			}
468
			if (!$found) {
469
				/* example message :
470
				3J01 DSPTCH 7503/01 LFTH/LFPO .F-HMLF
471
				*/
472
				$dair = '';
473
				$darr = '';
474
				$n = sscanf($message,'3J01 DSPTCH %*d/%*d %4s/%4s .%*6s',$dair,$darr);
475
				if ($n == 3) {
476
					if ($globalDebug) echo 'airport depart : '.$dair.' - airport arrival : '.$darr."\n";
477
					//$icao = $Translation->checkTranslation($ident);
478
					//$Schedule->addSchedule($icao,$dair,'',$darr,'','ACARS');
479
					$decode = array('Departure airport' => $dair, 'Arrival airport' => $darr);
480
					$found = true;
481
				}
482
			}
483
			if (!$found) {
484
				$n = sscanf($message,'MET01%4c',$airport);
485
				if ($n == 1) {
486
					if ($globalDebug) echo 'airport name : '.$airport;
487
					$decode = array('Airport/Waypoint name' => $airport);
488
					$found = true;
489
				}
490
			}
491
			if ($label == 'H1') {
492
				if (preg_match('/^#CFBFLR/',$message) || preg_match('/^#CFBWRN/',$message)) {
493
					$decode = array_merge(array('Message nature' => 'Equipment failure'),$decode);
494
				}
495
				elseif (preg_match('/^#DFB\*TKO/',$message) || preg_match('/^#DFBTKO/',$message)) {
496
					$decode = array_merge(array('Message nature' => 'Take off performance data'),$decode);
497
				}
498
				elseif (preg_match('/^#DFB\*CRZ/',$message) || preg_match('/^#DFBCRZ/',$message)) {
499
					$decode = array_merge(array('Message nature' => 'Cruise performance data'),$decode);
500
				}
501
				elseif (preg_match('/^#DFB\*WOB/',$message) || preg_match('/^#DFBWOB/',$message)) {
502
					$decode = array_merge(array('Message nature' => 'Weather observation'),$decode);
503
				}
504
				elseif (preg_match(':^#DFB/PIREP:',$message)) {
505
					$decode = array_merge(array('Message nature' => 'Pilot Report'),$decode);
506
				}
507
				elseif (preg_match('/^#DFBEDA/',$message) || preg_match('/^#DFBENG/',$message)) {
508
					$decode = array_merge(array('Message nature' => 'Engine Data'),$decode);
509
				}
510
				elseif (preg_match(':^#M1AAEP:',$message)) {
511
					$decode = array_merge(array('Message nature' => 'Position/Weather Report'),$decode);
512
				}
513
				elseif (preg_match(':^#M2APWD:',$message)) {
514
					$decode = array_merge(array('Message nature' => 'Flight plan predicted wind data'),$decode);
515
				}
516
				elseif (preg_match(':^#M1BREQPWI:',$message)) {
517
					$decode = array_merge(array('Message nature' => 'Predicted wind info request'),$decode);
518
				}
519
				elseif (preg_match(':^#CF:',$message)) {
520
					$decode = array_merge(array('Message nature' => 'Central Fault Display'),$decode);
521
				}
522
				elseif (preg_match(':^#DF:',$message)) {
523
					$decode = array_merge(array('Message nature' => 'Digital Flight Data Acquisition Unit'),$decode);
524
				}
525
				elseif (preg_match(':^#EC:',$message)) {
526
					$decode = array_merge(array('Message nature' => 'Engine Display System'),$decode);
527
				}
528
				elseif (preg_match(':^#EI:',$message)) {
529
					$decode = array_merge(array('Message nature' => 'Engine Report'),$decode);
530
				}
531
				elseif (preg_match(':^#H1:',$message)) {
532
					$decode = array_merge(array('Message nature' => 'HF Data Radio - Left'),$decode);
533
				}
534
				elseif (preg_match(':^#H2:',$message)) {
535
					$decode = array_merge(array('Message nature' => 'HF Data Radio - Right'),$decode);
536
				}
537
				elseif (preg_match(':^#HD:',$message)) {
538
					$decode = array_merge(array('Message nature' => 'HF Data Radio - Selected'),$decode);
539
				}
540
				elseif (preg_match(':^#M1:',$message)) {
541
					$decode = array_merge(array('Message nature' => 'Flight Management Computer - Left'),$decode);
542
				}
543
				elseif (preg_match(':^#M2:',$message)) {
544
					$decode = array_merge(array('Message nature' => 'Flight Management Computer - Right'),$decode);
545
				}
546
				elseif (preg_match(':^#M3:',$message)) {
547
					$decode = array_merge(array('Message nature' => 'Flight Management Computer - Center'),$decode);
548
				}
549
				elseif (preg_match(':^#MD:',$message)) {
550
					$decode = array_merge(array('Message nature' => 'Flight Management Computer - Selected'),$decode);
551
				}
552
				elseif (preg_match(':^#PS:',$message)) {
553
					$decode = array_merge(array('Message nature' => 'Keyboard/Display Unit'),$decode);
554
				}
555
				elseif (preg_match(':^#S1:',$message)) {
556
					$decode = array_merge(array('Message nature' => 'SDU - Left'),$decode);
557
				}
558
				elseif (preg_match(':^#S2:',$message)) {
559
					$decode = array_merge(array('Message nature' => 'SDU - Right'),$decode);
560
				}
561
				elseif (preg_match(':^#SD:',$message)) {
562
					$decode = array_merge(array('Message nature' => 'SDU - Selected'),$decode);
563
				}
564
				elseif (preg_match(':^#T[0-8]:',$message)) {
565
					$decode = array_merge(array('Message nature' => 'Cabin Terminal Messages'),$decode);
566
				}
567
				elseif (preg_match(':^#WO:',$message)) {
568
					$decode = array_merge(array('Message nature' => 'Weather Observation Report'),$decode);
569
				}
570
				elseif (preg_match(':^#A1:',$message)) {
571
					$decode = array_merge(array('Message nature' => 'Oceanic Clearance'),$decode);
572
				}
573
				elseif (preg_match(':^#A3:',$message)) {
574
					$decode = array_merge(array('Message nature' => 'Departure Clearance Response'),$decode);
575
				}
576
				elseif (preg_match(':^#A4:',$message)) {
577
					$decode = array_merge(array('Message nature' => 'Flight Systems Message'),$decode);
578
				}
579
				elseif (preg_match(':^#A6:',$message)) {
580
					$decode = array_merge(array('Message nature' => 'Request ADS Reports'),$decode);
581
				}
582
				elseif (preg_match(':^#A8:',$message)) {
583
					$decode = array_merge(array('Message nature' => 'Deliver Departure Slot'),$decode);
584
				}
585
				elseif (preg_match(':^#A9:',$message)) {
586
					$decode = array_merge(array('Message nature' => 'ATIS report'),$decode);
587
				}
588
				elseif (preg_match(':^#A0:',$message)) {
589
					$decode = array_merge(array('Message nature' => 'ATIS Facility Notification (AFN)'),$decode);
590
				}
591
				elseif (preg_match(':^#AA:',$message)) {
592
					$decode = array_merge(array('Message nature' => 'ATCComm'),$decode);
593
				}
594
				elseif (preg_match(':^#AB:',$message)) {
595
					$decode = array_merge(array('Message nature' => 'TWIP Report'),$decode);
596
				}
597
				elseif (preg_match(':^#AC:',$message)) {
598
					$decode = array_merge(array('Message nature' => 'Pushback Clearance'),$decode);
599
				}
600
				elseif (preg_match(':^#AD:',$message)) {
601
					$decode = array_merge(array('Message nature' => 'Expected Taxi Clearance'),$decode);
602
				}
603
				elseif (preg_match(':^#AF:',$message)) {
604
					$decode = array_merge(array('Message nature' => 'CPC Command/Response'),$decode);
605
				}
606
				elseif (preg_match(':^#B1:',$message)) {
607
					$decode = array_merge(array('Message nature' => 'Request Oceanic Clearance'),$decode);
608
				}
609
				elseif (preg_match(':^#B2:',$message)) {
610
					$decode = array_merge(array('Message nature' => 'Oceanic Clearance Readback'),$decode);
611
				}
612
				elseif (preg_match(':^#B3:',$message)) {
613
					$decode = array_merge(array('Message nature' => 'Request Departure Clearance'),$decode);
614
				}
615
				elseif (preg_match(':^#B4:',$message)) {
616
					$decode = array_merge(array('Message nature' => 'Departure Clearance Readback'),$decode);
617
				}
618
				elseif (preg_match(':^#B6:',$message)) {
619
					$decode = array_merge(array('Message nature' => 'Provide ADS Report'),$decode);
620
				}
621
				elseif (preg_match(':^#B8:',$message)) {
622
					$decode = array_merge(array('Message nature' => 'Request Departure Slot'),$decode);
623
				}
624
				elseif (preg_match(':^#B9:',$message)) {
625
					$decode = array_merge(array('Message nature' => 'Request ATIS Report'),$decode);
626
				}
627
				elseif (preg_match(':^#B0:',$message)) {
628
					$decode = array_merge(array('Message nature' => 'ATS Facility Notification'),$decode);
629
				}
630
				elseif (preg_match(':^#BA:',$message)) {
631
					$decode = array_merge(array('Message nature' => 'ATCComm'),$decode);
632
				}
633
				elseif (preg_match(':^#BB:',$message)) {
634
					$decode = array_merge(array('Message nature' => 'Request TWIP Report'),$decode);
635
				}
636
				elseif (preg_match(':^#BC:',$message)) {
637
					$decode = array_merge(array('Message nature' => 'Pushback Clearance Request'),$decode);
638
				}
639
				elseif (preg_match(':^#BD:',$message)) {
640
					$decode = array_merge(array('Message nature' => 'Expected Taxi Clearance Request'),$decode);
641
				}
642
				elseif (preg_match(':^#BE:',$message)) {
643
					$decode = array_merge(array('Message nature' => 'CPC Aircraft Log-On/Off Request'),$decode);
644
				}
645
				elseif (preg_match(':^#BF:',$message)) {
646
					$decode = array_merge(array('Message nature' => 'CPC WILCO/UNABLE Response'),$decode);
647
				}
648
				elseif (preg_match(':^#H3:',$message)) {
649
					$decode = array_merge(array('Message nature' => 'Icing Report'),$decode);
650
				}
651
			}
652
			if ($label == '10') {
653
				if (preg_match(':^DTO01:',$message)) {
654
					$decode = array_merge(array('Message nature' => 'Delayed Takeoff Report'),$decode);
655
				}
656
				elseif (preg_match(':^AIS01:',$message)) {
657
					$decode = array_merge(array('Message nature' => 'AIS Request'),$decode);
658
				}
659
				elseif (preg_match(':^FTX01:',$message)) {
660
					$decode = array_merge(array('Message nature' => 'Free Text Downlink'),$decode);
661
				}
662
				elseif (preg_match(':^FPL01:',$message)) {
663
					$decode = array_merge(array('Message nature' => 'Flight Plan Request'),$decode);
664
				}
665
				elseif (preg_match(':^WAB01:',$message)) {
666
					$decode = array_merge(array('Message nature' => 'Weight & Balance Request'),$decode);
667
				}
668
				elseif (preg_match(':^MET01:',$message)) {
669
					$decode = array_merge(array('Message nature' => 'Weather Data Request'),$decode);
670
				}
671
				elseif (preg_match(':^WAB02:',$message)) {
672
					$decode = array_merge(array('Message nature' => 'Weight and Balance Acknowledgement'),$decode);
673
				}
674
			}
675
			if ($label == '15') {
676
				if (preg_match(':^FST01:',$message)) {
677
					$decode = array_merge(array('Message nature' => 'Flight Status Report'),$decode);
678
				}
679
			}
680
			if (!$found && $label == 'SA') {
681
				$n = sscanf($message, "%d%c%c%6[0-9]", $version,$state,$type,$at);
682
				if ($n == 4) {
683
					$vsta = array('Version' => $version);
684
					if ($state == 'E') {
685
						$vsta = array_merge($vsta,array('Link state' => 'Established'));
686
					}
687
					elseif ($state == 'L') {
688
						$vsta = array_merge($vsta,array('Link state' => 'Lost'));
689
					}
690
					else {
691
						$vsta = array_merge($vsta,array('Link state' => 'Unknown'));
692
					}
693
					if ($type == 'V') {
694
						$vsta = array_merge($vsta,array('Link type' => 'VHF ACARS'));
695
					}
696
					elseif ($type == 'S') {
697
						$vsta = array_merge($vsta,array('Link type' => 'Generic SATCOM'));
698
					}
699
					elseif ($type == 'H') {
700
						$vsta = array_merge($vsta,array('Link type' => 'HF'));
701
					}
702
					elseif ($type == 'G') {
703
						$vsta = array_merge($vsta,array('Link type' => 'GlobalStar SATCOM'));
704
					}
705
					elseif ($type == 'C') {
706
						$vsta = array_merge($vsta,array('Link type' => 'ICO SATCOM'));
707
					}
708
					elseif ($type == '2') {
709
						$vsta = array_merge($vsta,array('Link type' => 'VDL Mode 2'));
710
					}
711
					elseif ($type == 'X') {
712
						$vsta = array_merge($vsta,array('Link type' => 'Inmarsat Aero'));
713
					}
714
					elseif ($type == 'I') {
715
						$vsta = array_merge($vsta,array('Link type' => 'Irridium SATCOM'));
716
					}
717
					else {
718
						$vsta = array_merge($vsta,array('Link type' => 'Unknown'));
719
					}
720
					$vsta = array_merge($vsta,array('Event occured at' => implode(':',str_split($at,2))));
721
					$decode = array_merge($vsta,$decode);
722
				}
723
			}
724
725
			$title = $this->getTitlefromLabel($label);
726
			if ($title != '') $decode = array_merge(array('Message title' => $title),$decode);
727
			/*
728
			// Business jets always use GS0001
729
			if ($ident != 'GS0001') $info = $this->addModeSData($ident,$registration,$icao,$airicao,$latitude,$longitude);
730
			if ($globalDebug && isset($info) && $info != '') echo $info;
731
			$image_array = $Image->getSpotterImage($registration);
732
			if (!isset($image_array[0]['registration'])) {
733
				$Image->addSpotterImage($registration);
734
			}
735
			*/
736
			$result['decode'] = $decode;
737
//		}
738
		return $result;
739
	}
740
741
	/**
742
	* Add ACARS data
743
	*
744
	* @param String ACARS data in acarsdec data
745
	*
746
	*/
747
	public function add($data,$message = array()) {
748
		global $globalDebug, $globalACARSArchive;
749
		$Image = new Image($this->db);
750
		$Schedule = new Schedule($this->db);
751
		$Translation = new Translation($this->db);
752
753
		$message = array_merge($message,$this->parse($data));
754
		if (isset($message['registration']) && $message['registration'] != '' && $message['ident'] != '' && $message['registration'] != '!') {
755
			$ident = (string)$message['ident'];
756
			$label = $message['label'];
757
			$block_id = $message['block_id'];
758
			$msg_no = $message['msg_no'];
759
			$msg = $message['message'];
760
			$decode = $message['decode'];
761
			$registration = (string)$message['registration'];
762
			if (isset($decode['latitude'])) $latitude = $decode['latitude'];
763
			else $latitude = '';
764
			if (isset($decode['longitude'])) $longitude = $decode['longitude'];
765
			else $longitude = '';
766
			if (isset($decode['airicao'])) $airicao = $decode['airicao'];
767
			else $airicao = '';
768
			if (isset($decode['icao'])) $icao = $decode['icao'];
769
			else $icao = $Translation->checkTranslation($ident);
770
			$image_array = $Image->getSpotterImage($registration);
771
			if (!isset($image_array[0]['registration'])) {
772
				$Image->addSpotterImage($registration);
773
			}
774
			// Business jets always use GS0001
775
			if ($ident != 'GS0001') $info = $this->addModeSData($ident,$registration,$icao,$airicao,$latitude,$longitude);
776
			if ($globalDebug && isset($info) && $info != '') echo $info;
777
			if (count($decode) > 0) $decode_json = json_encode($decode);
778
			else $decode_json = '';
779
			if (isset($decode['Departure airport']) && isset($decode['Departure hour']) && isset($decode['Arrival airport']) && isset($decode['Arrival hour'])) {
780
				$Schedule->addSchedule($icao,$decode['Departure airport'],$decode['Departure hour'],$decode['Arrival airport'],$decode['Arrival hour'],'ACARS');
781
			} elseif (isset($decode['Departure airport']) && isset($decode['Arrival airport'])) {
782
				$Schedule->addSchedule($icao,$decode['Departure airport'],'',$decode['Arrival airport'],'','ACARS');
783
			}
784
			$result = $this->addLiveAcarsData($ident,$registration,$label,$block_id,$msg_no,$msg,$decode_json);
785
			if (!isset($globalACARSArchive)) $globalACARSArchive = array('10','80','81','82','3F');
786
			if ($result && in_array($label,$globalACARSArchive)) $this->addArchiveAcarsData($ident,$registration,$label,$block_id,$msg_no,$msg,$decode_json);
787
			if ($globalDebug && count($decode) > 0) {
788
				echo "Human readable data : ".implode(' - ',$decode)."\n";
789
			}
790
		}
791
	}
792
793
    /**
794
     * Add Live ACARS data in DB
795
     *
796
     * @param String $ident ident
797
     * @param String $registration Registration of the aircraft
798
     * @param String $label Label of the ACARS message
799
     * @param String $block_id Block id of the ACARS message
800
     * @param String $msg_no Number of the ACARS message
801
     * @param String $message ACARS message
802
     * @param string $decode
803
     * @return bool
804
     */
805
	public function addLiveAcarsData($ident,$registration,$label,$block_id,$msg_no,$message,$decode = '') {
806
		global $globalDebug;
807
		date_default_timezone_set('UTC');
808
		if ($label != 'SQ' && $label != 'Q0' && $label != '_d' && $message != '') {
809
			$Connection = new Connection($this->db);
810
			$this->db = $Connection->db;
811
			if ($globalDebug) echo "Test if not already in Live ACARS table...";
812
			$query_test = "SELECT COUNT(*) as nb FROM acars_live WHERE ident = :ident AND registration = :registration AND message = :message";
813
			$query_test_values = array(':ident' => $ident,':registration' => $registration, ':message' => $message);
814
			try {
815
				$stht = $this->db->prepare($query_test);
816
				$stht->execute($query_test_values);
817
			} catch(PDOException $e) {
818
				echo "error : ".$e->getMessage();
819
				return false;
820
			}
821
			if ($stht->fetchColumn() == 0) {
822
				if ($globalDebug) echo "Add Live ACARS data...";
823
				$query = "INSERT INTO acars_live (ident,registration,label,block_id,msg_no,message,decode,date) VALUES (:ident,:registration,:label,:block_id,:msg_no,:message,:decode,:date)";
824
				$query_values = array(':ident' => $ident,':registration' => $registration, ':label' => $label,':block_id' => $block_id, ':msg_no' => $msg_no, ':message' => $message, ':decode' => $decode,':date' => date("Y-m-d H:i:s"));
825
				try {
826
					$sth = $this->db->prepare($query);
827
					$sth->execute($query_values);
828
				} catch(PDOException $e) {
829
					echo "error : ".$e->getMessage();
830
					return false;
831
				}
832
			} else {
833
				if ($globalDebug) echo "Data already in DB...\n";
834
				return false;
835
			}
836
			if ($globalDebug) echo "Done\n";
837
			return true;
838
		}
839
		return false;
840
	}
841
842
    /**
843
     * Add Archive ACARS data in DB
844
     *
845
     * @param String $ident ident
846
     * @param String $registration Registration of the aircraft
847
     * @param String $label Label of the ACARS message
848
     * @param String $block_id Block id of the ACARS message
849
     * @param String $msg_no Number of the ACARS message
850
     * @param String $message ACARS message
851
     * @param string $decode
852
     * @return string
853
     */
854
	public function addArchiveAcarsData($ident,$registration,$label,$block_id,$msg_no,$message,$decode = '') {
855
		global $globalDebug;
856
		date_default_timezone_set('UTC');
857
		if ($label != 'SQ' && $label != 'Q0' && $label != '_d' && $message != '' && preg_match('/^MET0/',$message) === 0 && preg_match('/^ARR0/',$message) === 0 && preg_match('/^ETA/',$message) === 0 && preg_match('/^WXR/',$message) === 0 && preg_match('/^FTX01.FIC/',$message) === 0) {
858
			/*
859
				    if ($globalDebug) echo "Test if not already in Archive ACARS table...";
860
			    	    $query_test = "SELECT COUNT(*) as nb FROM acars_archive WHERE ident = :ident AND registration = :registration AND message = :message";
861
			    	    $query_test_values = array(':ident' => $ident,':registration' => $registration, ':message' => $message);
862
			    	    try {
863
			        	$stht = Connection->$db->prepare($query_test);
864
			            	$stht->execute($query_test_values);
865
			    	    } catch(PDOException $e) {
866
			                return "error : ".$e->getMessage();
867
			    	    }
868
				    if ($stht->fetchColumn() == 0) {
869
			*/
870
			if ($globalDebug) echo "Add Live ACARS data...";
871
			$query = "INSERT INTO acars_archive (ident,registration,label,block_id,msg_no,message,decode) VALUES (:ident,:registration,:label,:block_id,:msg_no,:message,:decode)";
872
			$query_values = array(':ident' => $ident,':registration' => $registration, ':label' => $label,':block_id' => $block_id, ':msg_no' => $msg_no, ':message' => $message, ':decode' => $decode);
873
			try {
874
				$sth = $this->db->prepare($query);
875
				$sth->execute($query_values);
876
			} catch(PDOException $e) {
877
				return "error : ".$e->getMessage();
878
			}
879
			if ($globalDebug) echo "Done\n";
880
		}
881
		return '';
882
	}
883
884
	/**
885
	* Get Message title from label from DB
886
	*
887
	* @param String $label
888
	* @return String Return ACARS title
889
	*/
890
	public function getTitlefromLabel($label) {
891
		$Connection = new Connection($this->db);
892
		$this->db = $Connection->db;
893
		$query = "SELECT * FROM acars_label WHERE label = :label";
894
		$query_values = array(':label' => $label);
895
		try {
896
			$sth = $this->db->prepare($query);
897
			$sth->execute($query_values);
898
		} catch(PDOException $e) {
899
			echo "error : ".$e->getMessage();
900
			return '';
901
		}
902
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
903
		if (count($row) > 0) return $row[0]['title'];
904
		else return '';
905
	}
906
907
	/**
908
	* List all Message title & label from DB
909
	*
910
	* @return array Return ACARS data in array
911
	*/
912
	public function getAllTitleLabel() {
913
		$query = "SELECT * FROM acars_label ORDER BY title";
914
		$query_values = array();
915
		try {
916
			$sth = $this->db->prepare($query);
917
			$sth->execute($query_values);
918
		} catch(PDOException $e) {
919
			echo "error : ".$e->getMessage();
920
			return array();
921
		}
922
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
923
		if (count($row) > 0) return $row;
924
		else return array();
925
	}
926
927
	/**
928
	* Get Live ACARS data from DB
929
	*
930
	* @param String $ident
931
	* @return array Return ACARS data in array
932
	*/
933
	public function getLiveAcarsData($ident) {
934
		$query = "SELECT * FROM acars_live WHERE ident = :ident ORDER BY acars_live_id DESC";
935
		$query_values = array(':ident' => $ident);
936
		try {
937
			$sth = $this->db->prepare($query);
938
			$sth->execute($query_values);
939
		} catch(PDOException $e) {
940
			echo "error : ".$e->getMessage();
941
			return array();
942
		}
943
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
944
		if (count($row) > 0) return $row[0];
945
		else return array();
946
	}
947
948
    /**
949
     * Get Latest ACARS data from DB
950
     *
951
     * @param string $limit
952
     * @param string $label
953
     * @return array Return ACARS data in array
954
     */
955
	public function getLatestAcarsData($limit = '',$label = '') {
956
		global $globalURL;
957
		$Image = new Image($this->db);
958
		$Spotter = new Spotter($this->db);
959
		$Translation = new Translation($this->db);
960
		date_default_timezone_set('UTC');
961
		$result = array();
962
		$limit_query = '';
963
		if ($limit != "")
964
		{
965
			$limit_array = explode(",", $limit);
966
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
967
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
968
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
969
			{
970
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
971
			}
972
		}
973
		if ($label != '') {
974
			$query = "SELECT * FROM acars_live WHERE label = :label ORDER BY acars_live_id DESC".$limit_query;
975
			$query_values = array(':label' => $label);
976
		} else {
977
			$query = "SELECT * FROM acars_live ORDER BY acars_live_id DESC".$limit_query;
978
			$query_values = array();
979
		}
980
		try {
981
			$sth = $this->db->prepare($query);
982
			$sth->execute($query_values);
983
		} catch(PDOException $e) {
984
			echo "error : ".$e->getMessage();
985
			return array();
986
		}
987
		$i = 0;
988
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
989
			$data = array();
990
			if ($row['registration'] != '') {
991
				$row['registration'] = str_replace('.','',$row['registration']);
992
				$image_array = $Image->getSpotterImage($row['registration']);
993
				if (count($image_array) > 0) $data = array_merge($data,array('image' => $image_array[0]['image'],'image_thumbnail' => $image_array[0]['image_thumbnail'],'image_copyright' => $image_array[0]['image_copyright'],'image_source' => $image_array[0]['image_source'],'image_source_website' => $image_array[0]['image_source_website']));
994
				else $data = array_merge($data,array('image' => '','image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
995
			} else $data = array_merge($data,array('image' => '','image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
996
			if ($row['registration'] == '') $row['registration'] = 'NA';
997
			if ($row['ident'] == '') $row['ident'] = 'NA';
998
			$identicao = $Spotter->getAllAirlineInfo(substr($row['ident'],0,2));
999
			if (isset($identicao[0])) {
1000
				if (substr($row['ident'],0,2) == 'AF') {
1001
					if (filter_var(substr($row['ident'],2),FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))) $icao = $row['ident'];
1002
					else $icao = 'AFR'.ltrim(substr($row['ident'],2),'0');
1003
				} else $icao = $identicao[0]['icao'].ltrim(substr($row['ident'],2),'0');
1004
				$data = array_merge($data,array('airline_icao' => $identicao[0]['icao'],'airline_name' => $identicao[0]['name']));
1005
			} else $icao = $row['ident'];
1006
			$icao = $Translation->checkTranslation($icao,false);
1007
			$decode = json_decode($row['decode'],true);
1008
			$found = false;
1009
			if ($decode != '' && array_key_exists('Departure airport',$decode)) {
1010
				$airport_info = $Spotter->getAllAirportInfo($decode['Departure airport']);
1011
				if (isset($airport_info[0]['icao'])) {
1012
					$decode['Departure airport'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1013
					$found = true;
1014
				}
1015
			}
1016
			if ($decode != '' && array_key_exists('Arrival airport',$decode)) {
1017
				$airport_info = $Spotter->getAllAirportInfo($decode['Arrival airport']);
1018
				if (isset($airport_info[0]['icao'])) {
1019
					$decode['Arrival airport'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1020
					$found = true;
1021
				}
1022
			}
1023
			if ($decode != '' && array_key_exists('Airport/Waypoint name',$decode)) {
1024
				$airport_info = $Spotter->getAllAirportInfo($decode['Airport/Waypoint name']);
1025
				if (isset($airport_info[0]['icao'])) {
1026
					$decode['Airport/Waypoint name'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1027
					$found = true;
1028
				}
1029
			}
1030
			if ($found) $row['decode'] = json_encode($decode);
1031
			$data = array_merge($data,array('registration' => $row['registration'],'message' => $row['message'], 'date' => $row['date'], 'ident' => $icao, 'decode' => $row['decode']));
1032
			$result[] = $data;
1033
			$i++;
1034
		}
1035
		if (isset($result)) {
1036
			$result[0]['query_number_rows'] = $i;
1037
			return $result;
1038
		}
1039
		else return array();
1040
	}
1041
1042
    /**
1043
     * Get Archive ACARS data from DB
1044
     *
1045
     * @param string $limit
1046
     * @param string $label
1047
     * @return array Return ACARS data in array
1048
     */
1049
	public function getArchiveAcarsData($limit = '',$label = '') {
1050
		global $globalURL;
1051
		$Image = new Image($this->db);
1052
		$Spotter = new Spotter($this->db);
1053
		$Translation = new Translation($this->db);
1054
		date_default_timezone_set('UTC');
1055
		$limit_query = '';
1056
		if ($limit != "")
1057
		{
1058
			$limit_array = explode(",", $limit);
1059
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
1060
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
1061
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
1062
			{
1063
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
1064
			}
1065
		}
1066
		if ($label != '') {
1067
			if ($label == 'undefined') {
1068
				$query = "SELECT * FROM acars_archive WHERE label NOT IN (SELECT label FROM acars_label) ORDER BY acars_archive_id DESC".$limit_query;
1069
				$query_values = array();
1070
			} else {
1071
				$query = "SELECT * FROM acars_archive WHERE label = :label ORDER BY acars_archive_id DESC".$limit_query;
1072
				$query_values = array(':label' => $label);
1073
			}
1074
		} else {
1075
			$query = "SELECT * FROM acars_archive ORDER BY acars_archive_id DESC".$limit_query;
1076
			$query_values = array();
1077
		}
1078
		try {
1079
			$sth = $this->db->prepare($query);
1080
			$sth->execute($query_values);
1081
		} catch(PDOException $e) {
1082
			echo "error : ".$e->getMessage();
1083
			return array();
1084
		}
1085
		$i=0;
1086
		$result = array();
1087
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
1088
			$data = array();
1089
			if ($row['registration'] != '') {
1090
				$row['registration'] = str_replace('.','',$row['registration']);
1091
				$image_array = $Image->getSpotterImage($row['registration']);
1092
				if (count($image_array) > 0) $data = array_merge($data,array('image_thumbnail' => $image_array[0]['image_thumbnail'],'image_copyright' => $image_array[0]['image_copyright'],'image_source' => $image_array[0]['image_source'],'image_source_website' => $image_array[0]['image_source_website']));
1093
				else $data = array_merge($data,array('image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
1094
			} else $data = array_merge($data,array('image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
1095
			$icao = '';
1096
			if ($row['registration'] == '') $row['registration'] = 'NA';
1097
			if ($row['ident'] == '') $row['ident'] = 'NA';
1098
			$identicao = $Spotter->getAllAirlineInfo(substr($row['ident'],0,2));
1099
			if (isset($identicao[0])) {
1100
				if (substr($row['ident'],0,2) == 'AF') {
1101
					if (filter_var(substr($row['ident'],2),FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))) $icao = $row['ident'];
1102
					else $icao = 'AFR'.ltrim(substr($row['ident'],2),'0');
1103
				} else $icao = $identicao[0]['icao'].ltrim(substr($row['ident'],2),'0');
1104
				$data = array_merge($data,array('airline_icao' => $identicao[0]['icao'],'airline_name' => $identicao[0]['name']));
1105
			} else $icao = $row['ident'];
1106
			$icao = $Translation->checkTranslation($icao);
1107
			$decode = json_decode($row['decode'],true);
1108
			$found = false;
1109
			if ($decode != '' && array_key_exists('Departure airport',$decode)) {
1110
				$airport_info = $Spotter->getAllAirportInfo($decode['Departure airport']);
1111
				if (isset($airport_info[0]['icao'])) $decode['Departure airport'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1112
				$found = true;
1113
			}
1114
			if ($decode != '' && array_key_exists('Arrival airport',$decode)) {
1115
				$airport_info = $Spotter->getAllAirportInfo($decode['Arrival airport']);
1116
				if (isset($airport_info[0]['icao'])) $decode['Arrival airport'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1117
				$found = true;
1118
			}
1119
			if ($decode != '' && array_key_exists('Airport/Waypoint name',$decode)) {
1120
				$airport_info = $Spotter->getAllAirportInfo($decode['Airport/Waypoint name']);
1121
				if (isset($airport_info[0]['icao'])) {
1122
					$decode['Airport/Waypoint name'] = '<a href="'.$globalURL.'/airport/'.$airport_info[0]['icao'].'">'.$airport_info[0]['city'].','.$airport_info[0]['country'].' ('.$airport_info[0]['icao'].')</a>';
1123
					$found = true;
1124
				}
1125
			}
1126
			if ($found) $row['decode'] = json_encode($decode);
1127
			$data = array_merge($data,array('registration' => $row['registration'],'message' => $row['message'], 'date' => $row['date'], 'ident' => $icao, 'decode' => $row['decode']));
1128
			$result[] = $data;
1129
			$i++;
1130
		}
1131
		if (!empty($result)) {
1132
			$result[0]['query_number_rows'] = $i;
1133
			return $result;
1134
		} else return array();
1135
	}
1136
1137
    /**
1138
     * Add ModeS data to DB
1139
     *
1140
     * @param String $ident ident
1141
     * @param String $registration Registration of the aircraft
1142
     * @param String $icao
1143
     * @param String $ICAOTypeCode
1144
     * @param string $latitude
1145
     * @param string $longitude
1146
     * @return string
1147
     */
1148
	public function addModeSData($ident,$registration,$icao = '',$ICAOTypeCode = '',$latitude = '', $longitude = '') {
1149
		global $globalDebug, $globalDBdriver;
1150
		$ident = trim($ident);
1151
		$Translation = new Translation($this->db);
1152
		$Spotter = new Spotter($this->db);
1153
		if ($globalDebug) echo "Test if we add ModeS data...";
1154
		//if ($icao == '') $icao = ACARS->ident2icao($ident);
1155
		if ($icao == '') $icao = $Translation->checkTranslation($ident);
1156
		if ($globalDebug) echo '- Ident : '.$icao.' - ';
1157
		if ($ident == '' || $registration == '') {
1158
			if ($globalDebug) echo "Ident or registration null, exit\n";
1159
			return '';
1160
		}
1161
		$registration = str_replace('.','',$registration);
1162
		$ident = $Translation->ident2icao($ident);
1163
		// Check if a flight with same registration is flying now, if ok check if callsign = name in ACARS, else add it to translation
1164
		if ($globalDebug) echo "Check if needed to add translation ".$ident.'... ';
1165
		$querysi = "SELECT ident FROM spotter_live s,aircraft_modes a WHERE a.ModeS = s.ModeS AND a.Registration = :registration AND s.format_source <> 'ACARS' LIMIT 1";
1166
		$querysi_values = array(':registration' => $registration);
1167
		try {
1168
			$sthsi = $this->db->prepare($querysi);
1169
			$sthsi->execute($querysi_values);
1170
		} catch(PDOException $e) {
1171
			if ($globalDebug) echo $e->getMessage();
1172
			return "error : ".$e->getMessage();
1173
		}
1174
		$resultsi = $sthsi->fetch(PDO::FETCH_ASSOC);
1175
		$sthsi->closeCursor();
1176
		if (count($resultsi) > 0 && $resultsi['ident'] != $ident && $resultsi['ident'] != '') {
1177
			$Translation = new Translation($this->db);
1178
			$trans_ident = $Translation->getOperator($resultsi['ident']);
1179
			if ($globalDebug) echo 'Add translation to table : '.$ident.' -> '.$resultsi['ident'].' ';
1180
			if ($ident != $trans_ident) $Translation->addOperator($resultsi['ident'],$ident,'ACARS');
1181
			elseif ($trans_ident == $ident) $Translation->updateOperator($resultsi['ident'],$ident,'ACARS');
1182
		} else {
1183
			if ($registration != '' && $latitude != '' && $longitude != '') {
1184
				$query = "SELECT ModeS FROM aircraft_modes WHERE Registration = :registration LIMIT 1";
1185
				$query_values = array(':registration' => $registration);
1186
				try {
1187
					$sth = $this->db->prepare($query);
1188
					$sth->execute($query_values);
1189
				} catch(PDOException $e) {
1190
					if ($globalDebug) echo $e->getMessage();
1191
					return "error : ".$e->getMessage();
1192
				}
1193
				$result = $sth->fetch(PDO::FETCH_ASSOC);
1194
				$sth->closeCursor();
1195
				if (isset($result['modes'])) $hex = $result['modes'];
1196
				else $hex = '';
1197
				$SI_data = array('hex' => $hex,'ident' => $ident,'aircraft_icao' => $ICAOTypeCode,'registration' => $registration,'latitude' => $latitude,'$longitude' => $longitude,'format_source' => 'ACARS');
1198
				if ($this->fromACARSscript) $this->SI->add($SI_data);
1199
			}
1200
		}
1201
		if ($globalDebug) echo 'Done'."\n";
1202
		$query = "SELECT flightaware_id, ModeS FROM spotter_output WHERE ident = :ident AND format_source <> 'ACARS' ORDER BY spotter_id DESC LIMIT 1";
1203
		$query_values = array(':ident' => $icao);
1204
		try {
1205
			$sth = $this->db->prepare($query);
1206
			$sth->execute($query_values);
1207
		} catch(PDOException $e) {
1208
			if ($globalDebug) echo $e->getMessage();
1209
			return "error : ".$e->getMessage();
1210
		}
1211
		$result = $sth->fetch(PDO::FETCH_ASSOC);
1212
		$sth->closeCursor();
1213
		if (isset($result['flightaware_id'])) {
1214
			if (isset($result['ModeS'])) $ModeS = $result['ModeS'];
1215
			else $ModeS = '';
1216
			if ($ModeS == '') {
1217
				$id = explode('-',$result['flightaware_id']);
1218
				$ModeS = $id[0];
1219
			}
1220
			if ($ModeS != '') {
1221
				$country = $Spotter->countryFromAircraftRegistration($registration);
1222
				$queryc = "SELECT * FROM aircraft_modes WHERE ModeS = :modes LIMIT 1";
1223
				$queryc_values = array(':modes' => $ModeS);
1224
				try {
1225
					$sthc = $this->db->prepare($queryc);
1226
					$sthc->execute($queryc_values);
1227
				} catch(PDOException $e) {
1228
					if ($globalDebug) echo $e->getMessage();
1229
					return "error : ".$e->getMessage();
1230
				}
1231
				$row = $sthc->fetch(PDO::FETCH_ASSOC);
1232
				$sthc->closeCursor();
1233
				if (count($row) ==  0) {
1234
					if ($globalDebug) echo " Add to ModeS table - ";
1235
					$queryi = "INSERT INTO aircraft_modes (ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:ModeSCountry,:Registration, :ICAOTypeCode,'ACARS')";
1236
					$queryi_values = array(':ModeS' => $ModeS,':ModeSCountry' => $country,':Registration' => $registration, ':ICAOTypeCode' => $ICAOTypeCode);
1237
					try {
1238
						$sthi = $this->db->prepare($queryi);
1239
						$sthi->execute($queryi_values);
1240
					} catch(PDOException $e) {
1241
						if ($globalDebug) echo $e->getMessage();
1242
						return "error : ".$e->getMessage();
1243
					}
1244
				} else {
1245
					if ($globalDebug) echo " Update ModeS table - ";
1246
					if ($ICAOTypeCode != '') {
1247
						$queryi = "UPDATE aircraft_modes SET ModeSCountry = :ModeSCountry,Registration = :Registration,ICAOTypeCode = :ICAOTypeCode,Source = 'ACARS',LastModified = NOW() WHERE ModeS = :ModeS";
1248
						$queryi_values = array(':ModeS' => $ModeS,':ModeSCountry' => $country,':Registration' => $registration, ':ICAOTypeCode' => $ICAOTypeCode);
1249
					} else {
1250
						$queryi = "UPDATE aircraft_modes SET ModeSCountry = :ModeSCountry,Registration = :Registration,Source = 'ACARS',LastModified = NOW() WHERE ModeS = :ModeS";
1251
						$queryi_values = array(':ModeS' => $ModeS,':ModeSCountry' => $country,':Registration' => $registration);
1252
					}
1253
					try {
1254
						$sthi = $this->db->prepare($queryi);
1255
						$sthi->execute($queryi_values);
1256
					} catch(PDOException $e) {
1257
						if ($globalDebug) echo $e->getMessage();
1258
						return "error : ".$e->getMessage();
1259
					}
1260
				}
1261
				/*
1262
				if ($globalDebug) echo " Update Spotter_live table - ";
1263
				if ($ICAOTypeCode != '') {
1264
				    $queryi = "UPDATE spotter_live SET registration = :Registration,aircraft_icao = :ICAOTypeCode WHERE ident = :ident";
1265
				    $queryi_values = array(':Registration' => $registration, ':ICAOTypeCode' => $ICAOTypeCode, ':ident' => $icao);
1266
				} else {
1267
				    $queryi = "UPDATE spotter_live SET registration = :Registration WHERE ident = :ident";
1268
				    $queryi_values = array(':Registration' => $registration,':ident' => $icao);
1269
				}
1270
				try {
1271
				    $sthi = $this->db->prepare($queryi);
1272
					    $sthi->execute($queryi_values);
1273
				} catch(PDOException $e) {
1274
				    if ($globalDebug) echo $e->getMessage();
1275
					    return "error : ".$e->getMessage();
1276
				}
1277
				*/
1278
				if ($globalDebug) echo " Update Spotter_output table - ";
1279
				if ($ICAOTypeCode != '') {
1280
					if ($globalDBdriver == 'mysql') {
1281
						$queryi = "UPDATE spotter_output SET registration = :Registration,aircraft_icao = :ICAOTypeCode WHERE ident = :ident AND date >= date_sub(UTC_TIMESTAMP(), INTERVAL 1 HOUR)";
1282
					} else if ($globalDBdriver == 'pgsql') {
1283
						$queryi = "UPDATE spotter_output SET registration = :Registration,aircraft_icao = :ICAOTypeCode WHERE ident = :ident AND date >= NOW() AT TIME ZONE 'UTC' - INTERVAL '1 HOUR'";
1284
					}
1285
					$queryi_values = array(':Registration' => $registration, ':ICAOTypeCode' => $ICAOTypeCode, ':ident' => $icao);
1286
				} else {
1287
					if ($globalDBdriver == 'mysql') {
1288
						$queryi = "UPDATE spotter_output SET registration = :Registration WHERE ident = :ident AND date >= date_sub(UTC_TIMESTAMP(), INTERVAL 1 HOUR)";
1289
					}
1290
					elseif ($globalDBdriver == 'pgsql') {
1291
						$queryi = "UPDATE spotter_output SET registration = :Registration WHERE ident = :ident AND date >= NOW() AT TIME ZONE 'UTC' - INTERVAL '1 HOUR'";
1292
					}
1293
					$queryi_values = array(':Registration' => $registration,':ident' => $icao);
1294
				}
1295
				try {
1296
					$sthi = $this->db->prepare($queryi);
1297
					$sthi->execute($queryi_values);
1298
				} catch(PDOException $e) {
1299
					if ($globalDebug) echo $e->getMessage();
1300
					return "error : ".$e->getMessage();
1301
				}
1302
			}
1303
		} else {
1304
			if ($globalDebug) echo " Can't find ModeS in spotter_output - ";
1305
		}
1306
		if ($globalDebug) echo "Done\n";
1307
		return '';
1308
	}
1309
}
1310
?>
1311