Completed
Push — master ( 930a0f...8b07fe )
by Yannick
21:32
created

SpotterImport::get_Schedule()   D

Complexity

Conditions 19
Paths 319

Size

Total Lines 71
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 44
nc 319
nop 2
dl 0
loc 71
rs 4.1502
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
require_once(dirname(__FILE__).'/class.Connection.php');
3
require_once(dirname(__FILE__).'/class.Spotter.php');
4
require_once(dirname(__FILE__).'/class.SpotterLive.php');
5
require_once(dirname(__FILE__).'/class.SpotterArchive.php');
6
require_once(dirname(__FILE__).'/class.Scheduler.php');
7
require_once(dirname(__FILE__).'/class.Translation.php');
8
require_once(dirname(__FILE__).'/class.Stats.php');
9
require_once(dirname(__FILE__).'/class.Source.php');
10
11
class SpotterImport {
12
    private $all_flights = array();
13
    private $last_delete_hourly = 0;
14
    private $last_delete = 0;
15
    private $stats = array();
16
    private $tmd = 0;
17
    private $source_location = array();
18
    public $db = null;
19
    public $nb = 0;
20
21
    public function __construct($dbc = null) {
22
	global $globalBeta;
23
	$Connection = new Connection($dbc);
24
	$this->db = $Connection->db();
25
	date_default_timezone_set('UTC');
26
27
	// Get previous source stats
28
	$Stats = new Stats($dbc);
29
	$currentdate = date('Y-m-d');
30
	$sourcestat = $Stats->getStatsSource($currentdate);
31
	if (!empty($sourcestat)) {
32
	    foreach($sourcestat as $srcst) {
33
	    	$type = $srcst['stats_type'];
34
		if ($type == 'polar' || $type == 'hist') {
35
		    $source = $srcst['source_name'];
36
		    $data = $srcst['source_data'];
37
		    $this->stats[$currentdate][$source][$type] = json_decode($data,true);
38
	        }
39
	    }
40
	}
41
    }
42
43
    public function get_Schedule($id,$ident) {
44
	global $globalDebug, $globalFork, $globalSchedulesFetch;
45
	// Get schedule here, so it's done only one time
46
	
47
	/*
48
	if ($globalFork) {
49
		$Connection = new Connection();
50
		$dbc = $Connection->db;
51
	} else $dbc = $this->db;
52
	*/
53
	$dbc = $this->db;
54
	$this->all_flights[$id]['schedule_check'] = true;
55
	if ($globalSchedulesFetch) {
56
	if ($globalDebug) echo 'Getting schedule info...'."\n";
57
	$Spotter = new Spotter($dbc);
58
	$Schedule = new Schedule($dbc);
59
	$Translation = new Translation($dbc);
60
	$operator = $Spotter->getOperator($ident);
61
	$scheduleexist = false;
62
	if ($Schedule->checkSchedule($operator) == 0) {
63
	    $operator = $Translation->checkTranslation($ident);
64
	    if ($Schedule->checkSchedule($operator) == 0) {
65
		$schedule = $Schedule->fetchSchedule($operator);
66
		if (count($schedule) > 0 && isset($schedule['DepartureTime']) && isset($schedule['ArrivalTime'])) {
67
		    if ($globalDebug) echo "-> Schedule info for ".$operator." (".$ident.")\n";
68
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport_time' => $schedule['DepartureTime']));
69
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('arrival_airport_time' => $schedule['ArrivalTime']));
70
		    // Should also check if route schedule = route from DB
71
		    if ($schedule['DepartureAirportIATA'] != '') {
72
			if ($this->all_flights[$id]['departure_airport'] != $Spotter->getAirportIcao($schedule['DepartureAirportIATA'])) {
73
			    $airport_icao = $Spotter->getAirportIcao($schedule['DepartureAirportIATA']);
74
			    if ($airport_icao != '') {
75
				$this->all_flights[$id]['departure_airport'] = $airport_icao;
76
				if ($globalDebug) echo "-> Change departure airport to ".$airport_icao." for ".$ident."\n";
77
			    }
78
			}
79
		    }
80
		    if ($schedule['ArrivalAirportIATA'] != '') {
81
			if ($this->all_flights[$id]['arrival_airport'] != $Spotter->getAirportIcao($schedule['ArrivalAirportIATA'])) {
82
			    $airport_icao = $Spotter->getAirportIcao($schedule['ArrivalAirportIATA']);
83
			    if ($airport_icao != '') {
84
				$this->all_flights[$id]['arrival_airport'] = $airport_icao;
85
				if ($globalDebug) echo "-> Change arrival airport to ".$airport_icao." for ".$ident."\n";
86
			    }
87
			}
88
		    }
89
		    $Schedule->addSchedule($operator,$this->all_flights[$id]['departure_airport'],$this->all_flights[$id]['departure_airport_time'],$this->all_flights[$id]['arrival_airport'],$this->all_flights[$id]['arrival_airport_time'],$schedule['Source']);
90
		}
91
	    } else $scheduleexist = true;
92
	} else $scheduleexist = true;
93
	// close connection, at least one way will work ?
94
       if ($scheduleexist) {
95
		if ($globalDebug) echo "-> get arrival/departure airport info for ".$ident."\n";
96
    		$sch = $Schedule->getSchedule($operator);
97
		$this->all_flights[$id] = array_merge($this->all_flights[$id],array('arrival_airport' => $sch['arrival_airport_icao'],'departure_airport' => $sch['departure_airport_icao'],'departure_airport_time' => $sch['departure_airport_time'],'arrival_airport_time' => $sch['arrival_airport_time']));
98
       }
99
	$Spotter->db = null;
100
	$Schedule->db = null;
101
	$Translation->db = null;
102
	unset($Spotter->db);
103
	unset($Schedule->db);
104
	unset($Translation->db);
105
106
	/*
107
	if ($globalFork) {
108
	    $Connection->db = null;
109
	    unset($Connection->db);
110
	}
111
	  */
112
	}
113
    }
114
115
    public function checkAll() {
116
	global $globalDebug;
117
	if ($globalDebug) echo "Update last seen flights data...\n";
118
	foreach ($this->all_flights as $key => $flight) {
119
	    if (isset($this->all_flights[$key]['id'])) {
120
		//echo $this->all_flights[$key]['id'].' - '.$this->all_flights[$key]['latitude'].'  '.$this->all_flights[$key]['longitude']."\n";
121
    		$Spotter = new Spotter($this->db);
122
        	$real_arrival = $this->arrival($key);
123
        	$Spotter->updateLatestSpotterData($this->all_flights[$key]['id'],$this->all_flights[$key]['ident'],$this->all_flights[$key]['latitude'],$this->all_flights[$key]['longitude'],$this->all_flights[$key]['altitude'],$this->all_flights[$key]['ground'],$this->all_flights[$key]['speed'],$this->all_flights[$key]['datetime'],$real_arrival['airport_icao'],$real_arrival['airport_time']);
124
            }
125
	}
126
    }
127
128
    public function arrival($key) {
129
	global $globalClosestMinDist, $globalDebug;
130
	if ($globalDebug) echo 'Update arrival...'."\n";
131
	$Spotter = new Spotter($this->db);
132
        $airport_icao = '';
133
        $airport_time = '';
134
        if (!isset($globalClosestMinDist) || $globalClosestMinDist == '') $globalClosestMinDist = 50;
135
	if ($this->all_flights[$key]['latitude'] != '' && $this->all_flights[$key]['longitude'] != '') {
136
	    $closestAirports = $Spotter->closestAirports($this->all_flights[$key]['latitude'],$this->all_flights[$key]['longitude'],$globalClosestMinDist);
137
    	    if (isset($closestAirports[0])) {
138
        	if (isset($this->all_flights[$key]['arrival_airport']) && $this->all_flights[$key]['arrival_airport'] == $closestAirports[0]['icao']) {
139
        	    $airport_icao = $closestAirports[0]['icao'];
140
        	    $airport_time = $this->all_flights[$key]['datetime'];
141
        	    if ($globalDebug) echo "---++ Find arrival airport. airport_icao : ".$airport_icao."\n";
142
        	} elseif (count($closestAirports > 1) && isset($this->all_flights[$key]['arrival_airport']) && $this->all_flights[$key]['arrival_airport'] != '') {
143
        	    foreach ($closestAirports as $airport) {
144
        		if ($this->all_flights[$key]['arrival_airport'] == $airport['icao']) {
145
        		    $airport_icao = $airport['icao'];
146
        		    $airport_time = $this->all_flights[$key]['datetime'];
147
        		    if ($globalDebug) echo "---++ Find arrival airport. airport_icao : ".$airport_icao."\n";
148
        		    break;
149
        		}
150
        	    }
151
        	} elseif ($this->all_flights[$key]['altitude'] == 0 || ($this->all_flights[$key]['altitude_real'] != '' && ($closestAirports[0]['altitude'] < $this->all_flights[$key]['altitude_real'] && $this->all_flights[$key]['altitude_real'] < $closestAirports[0]['altitude']+5000))) {
152
        		$airport_icao = $closestAirports[0]['icao'];
153
        		$airport_time = $this->all_flights[$key]['datetime'];
154
        	} else {
155
        		if ($globalDebug) echo "----- Can't find arrival airport. Airport altitude : ".$closestAirports[0]['altitude'].' - flight altitude : '.$this->all_flights[$key]['altitude_real']."\n";
156
        	}
157
    	    } else {
158
    		    if ($globalDebug) echo "----- No Airport near last coord. Latitude : ".$this->all_flights[$key]['latitude'].' - Longitude : '.$this->all_flights[$key]['longitude'].' - MinDist : '.$globalClosestMinDist."\n";
159
    	    }
160
161
        } else {
162
        	if ($globalDebug) echo "---- No latitude or longitude. Ident : ".$this->all_flights[$key]['ident']."\n";
163
        }
164
        return array('airport_icao' => $airport_icao,'airport_time' => $airport_time);
165
    }
166
167
168
169
    public function del() {
170
	global $globalDebug;
171
	// Delete old infos
172
	if ($globalDebug) echo 'Delete old values and update latest data...'."\n";
173
	foreach ($this->all_flights as $key => $flight) {
174
    	    if (isset($flight['lastupdate'])) {
175
        	if ($flight['lastupdate'] < (time()-3000)) {
176
            	    if (isset($this->all_flights[$key]['id'])) {
177
            		if ($globalDebug) echo "--- Delete old values with id ".$this->all_flights[$key]['id']."\n";
178
			/*
179
			$SpotterLive = new SpotterLive();
180
            		$SpotterLive->deleteLiveSpotterDataById($this->all_flights[$key]['id']);
181
			$SpotterLive->db = null;
182
			*/
183
            		$real_arrival = $this->arrival($key);
184
            		$Spotter = new Spotter($this->db);
185
            		if ($this->all_flights[$key]['latitude'] != '' && $this->all_flights[$key]['longitude'] != '') {
186
				$result = $Spotter->updateLatestSpotterData($this->all_flights[$key]['id'],$this->all_flights[$key]['ident'],$this->all_flights[$key]['latitude'],$this->all_flights[$key]['longitude'],$this->all_flights[$key]['altitude'],$this->all_flights[$key]['ground'],$this->all_flights[$key]['speed'],$this->all_flights[$key]['datetime'],$real_arrival['airport_icao'],$real_arrival['airport_time']);
187
				if ($globalDebug && $result != 'success') echo '!!! ERROR : '.$result."\n";
188
			}
189
			// Put in archive
190
//			$Spotter->db = null;
191
            	    }
192
            	    unset($this->all_flights[$key]);
193
    	        }
194
	    }
195
        }
196
    }
197
198
    public function add($line) {
199
	global $globalPilotIdAccept, $globalAirportAccept, $globalAirlineAccept, $globalAirlineIgnore, $globalAirportIgnore, $globalFork, $globalDistanceIgnore, $globalDaemon, $globalSBS1update, $globalDebug, $globalIVAO, $globalVATSIM, $globalphpVMS, $globalCoordMinChange, $globalDebugTimeElapsed, $globalCenterLatitude, $globalCenterLongitude, $globalBeta, $globalSourcesupdate, $globalAirlinesSource, $globalVAM, $globalAllFlights;
200
	//if (!isset($globalDebugTimeElapsed) || $globalDebugTimeElapsed == '') $globalDebugTimeElapsed = FALSE;
201
	if (!isset($globalCoordMinChange) || $globalCoordMinChange == '') $globalCoordMinChange = '0.02';
202
/*
203
	$Spotter = new Spotter();
204
	$dbc = $Spotter->db;
205
	$SpotterLive = new SpotterLive($dbc);
206
	$Common = new Common();
207
	$Schedule = new Schedule($dbc);
208
*/
209
	date_default_timezone_set('UTC');
210
	// signal handler - playing nice with sockets and dump1090
211
	// pcntl_signal_dispatch();
212
213
	// get the time (so we can figure the timeout)
214
	//$time = time();
215
216
	//pcntl_signal_dispatch();
217
	$dataFound = false;
218
	//$putinarchive = false;
219
	$send = false;
220
	
221
	// SBS format is CSV format
222
	if(is_array($line) && isset($line['hex'])) {
223
	    //print_r($line);
224
  	    if ($line['hex'] != '' && $line['hex'] != '00000' && $line['hex'] != '000000' && $line['hex'] != '111111' && ctype_xdigit($line['hex']) && strlen($line['hex']) === 6) {
225
226
		// Increment message number
227
		if (isset($line['sourcestats']) && $line['sourcestats'] == TRUE) {
228
		    $current_date = date('Y-m-d');
229
		    $source = $line['source_name'];
230
		    if ($source == '' || $line['format_source'] == 'aprs') $source = $line['format_source'];
231
		    if (!isset($this->stats[$current_date][$source]['msg'])) {
232
		    	$this->stats[$current_date][$source]['msg']['date'] = time();
233
		    	$this->stats[$current_date][$source]['msg']['nb'] = 1;
234
		    } else $this->stats[$current_date][$source]['msg']['nb'] += 1;
235
		}
236
		
237
		/*
238
		$dbc = $this->db;
239
		$Connection = new Connection($dbc);
240
		$Connection->connectionExists();
241
		$dbc = $Connection->db;
242
		*/
243
		//$Spotter = new Spotter($dbc);
244
		//$SpotterLive = new SpotterLive($dbc);
245
		$Common = new Common();
246
//		echo $this->nb++."\n";
247
		//$this->db = $dbc;
248
249
		$hex = trim($line['hex']);
250
	        if (!isset($line['id'])) $id = trim($line['hex']);
251
	        else $id = trim($line['id']);
252
		
253
		//print_r($this->all_flights);
254
		if (!isset($this->all_flights[$id]['hex']) && ctype_xdigit($hex)) {
255
		    $this->all_flights[$id] = array('hex' => $hex);
256
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('addedSpotter' => 0));
257
		    //if (isset($line['datetime']) && preg_match('/^(\d{4}(?:\-\d{2}){2} \d{2}(?:\:\d{2}){2})$/',$line['datetime'])) {
258
			//$this->all_flights[$id] = array_merge($this->all_flights[$id],array('datetime' => $line['datetime']));
259
		    //} else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('datetime' => date('Y-m-d H:i:s')));
260
		    if (!isset($line['aircraft_name']) && (!isset($line['aircraft_icao']) || $line['aircraft_icao'] == '????')) {
261
262
			$timeelapsed = microtime(true);
263
			$Spotter = new Spotter($this->db);
264
			$aircraft_icao = $Spotter->getAllAircraftType($hex);
265
			$Spotter->db = null;
266
			if ($globalDebugTimeElapsed) echo 'Time elapsed for update getallaircrattype : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
267
268
			if ($aircraft_icao == '' && isset($line['aircraft_type'])) {
269
			    if ($line['aircraft_type'] == 'PARA_GLIDER') $aircraft_icao = 'GLID';
270
			    elseif ($line['aircraft_type'] == 'HELICOPTER_ROTORCRAFT') $aircraft_icao = 'UHEL';
271
			    elseif ($line['aircraft_type'] == 'TOW_PLANE') $aircraft_icao = 'TOWPLANE';
272
			    elseif ($line['aircraft_type'] == 'POWERED_AIRCRAFT') $aircraft_icao = 'POWAIRC';
273
			}
274
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('aircraft_icao' => $aircraft_icao));
275
		    } else if (isset($line['aircraft_name'])) {
276
			// Get aircraft ICAO from aircraft name
277
			$Spotter = new Spotter($this->db);
278
			$aircraft_icao = $Spotter->getAircraftIcao($line['aircraft_name']);
279
			$Spotter->db = null;
280
			if ($aircraft_icao != '') $this->all_flights[$id] = array_merge($this->all_flights[$id],array('aircraft_icao' => $aircraft_icao));
281
			else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('aircraft_icao' => 'NA'));
282
		    } else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('aircraft_icao' => $line['aircraft_icao']));
283
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('ident' => '','departure_airport' => '', 'arrival_airport' => '','latitude' => '', 'longitude' => '', 'speed' => '', 'altitude' => '','altitude_real' => '', 'heading' => '','departure_airport_time' => '','arrival_airport_time' => '','squawk' => '','route_stop' => '','registration' => '','pilot_id' => '','pilot_name' => '','waypoints' => '','ground' => '0', 'format_source' => '','source_name' => '','over_country' => '','verticalrate' => '','noarchive' => false,'putinarchive' => true));
284
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('lastupdate' => time()));
285
		    if (!isset($line['id'])) {
286
			if (!isset($globalDaemon)) $globalDaemon = TRUE;
287
//			if (isset($line['format_source']) && ($line['format_source'] == 'sbs' || $line['format_source'] == 'tsv' || $line['format_source'] == 'raw') && $globalDaemon) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident'].'-'.date('YmdGi')));
288
//			if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw' || $line['format_source'] === 'deltadbtxt' || $line['format_source'] === 'planeupdatefaa' || $line['format_source'] === 'aprs') && $globalDaemon) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.date('YmdHi')));
289
			if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw' || $line['format_source'] === 'deltadbtxt' || $line['format_source'] === 'planeupdatefaa' || $line['format_source'] === 'aprs' || $line['format_source'] === 'aircraftlistjson' || $line['format_source'] === 'radarvirtueljson')) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.date('YmdHi')));
290
		        //else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident']));
291
		     } else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $line['id']));
292
293
		    if ($globalDebug) echo "*********** New aircraft hex : ".$hex." ***********\n";
294
		    if ($globalAllFlights !== FALSE) $dataFound = true;
295
		}
296
		
297
		if (isset($line['datetime']) && preg_match('/^(\d{4}(?:\-\d{2}){2} \d{2}(?:\:\d{2}){2})$/',$line['datetime'])) {
298
		    if (!isset($this->all_flights[$id]['datetime']) || strtotime($line['datetime']) >= strtotime($this->all_flights[$id]['datetime'])) {
299
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('datetime' => $line['datetime']));
300
		    } else {
301
				if (strtotime($line['datetime']) == strtotime($this->all_flights[$id]['datetime']) && $globalDebug) echo "!!! Date is the same as previous data for ".$this->all_flights[$id]['hex']." - format : ".$line['format_source']."\n";
302
				elseif (strtotime($line['datetime']) > strtotime($this->all_flights[$id]['datetime']) && $globalDebug) echo "!!! Date previous latest data (".$line['datetime']." > ".$this->all_flights[$id]['datetime'].") !!! for ".$this->all_flights[$id]['hex']." - format : ".$line['format_source']."\n";
303
				/*
304
				echo strtotime($line['datetime']).' > '.strtotime($this->all_flights[$id]['datetime']);
305
				print_r($this->all_flights[$id]);
306
				print_r($line);
307
				*/
308
				return '';
309
		    }
310
		} else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('datetime' => date('Y-m-d H:i:s')));
311
312
		if (isset($line['registration']) && $line['registration'] != '' && $line['registration'] != 'z.NO-REG') {
313
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('registration' => $line['registration']));
314
		}
315
		if (isset($line['waypoints']) && $line['waypoints'] != '') {
316
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('waypoints' => $line['waypoints']));
317
		}
318
		if (isset($line['pilot_id']) && $line['pilot_id'] != '') {
319
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('pilot_id' => $line['pilot_id']));
320
		}
321
		if (isset($line['pilot_name']) && $line['pilot_name'] != '') {
322
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('pilot_name' => $line['pilot_name']));
323
		}
324
 
325
		if (isset($line['ident']) && $line['ident'] != '' && $line['ident'] != '????????' && $line['ident'] != '00000000' && ($this->all_flights[$id]['ident'] != trim($line['ident'])) && preg_match('/^[a-zA-Z0-9]+$/', $line['ident'])) {
326
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('ident' => trim($line['ident'])));
327
		    if ($this->all_flights[$id]['addedSpotter'] == 1) {
328
			$timeelapsed = microtime(true);
329
            		$Spotter = new Spotter($this->db);
330
            		$fromsource = NULL;
331
            		if (isset($globalAirlinesSource) && $globalAirlinesSource != '') $fromsource = $globalAirlinesSource;
332
            		elseif (isset($line['format_source']) && $line['format_source'] == 'vatsimtxt') $fromsource = 'vatsim';
333
			elseif (isset($line['format_source']) && $line['format_source'] == 'whazzup') $fromsource = 'ivao';
334
			elseif (isset($globalVATSIM) && $globalVATSIM) $fromsource = 'vatsim';
335
			elseif (isset($globalIVAO) && $globalIVAO) $fromsource = 'ivao';
336
            		$result = $Spotter->updateIdentSpotterData($this->all_flights[$id]['id'],$this->all_flights[$id]['ident'],$fromsource);
337
			if ($globalDebug && $result != 'success') echo '!!! ERROR : '.$result."\n";
338
			$Spotter->db = null;
339
			if ($globalDebugTimeElapsed) echo 'Time elapsed for update identspotterdata : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
340
		    }
341
342
/*
343
		    if (!isset($line['id'])) {
344
			if (!isset($globalDaemon)) $globalDaemon = TRUE;
345
//			if (isset($line['format_source']) && ($line['format_source'] == 'sbs' || $line['format_source'] == 'tsv' || $line['format_source'] == 'raw') && $globalDaemon) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident'].'-'.date('YmdGi')));
346
			if (isset($line['format_source']) && ($line['format_source'] == 'sbs' || $line['format_source'] == 'tsv' || $line['format_source'] == 'raw') && $globalDaemon) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.date('YmdGi')));
347
		        else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident']));
348
		     } else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $line['id']));
349
  */
350
		    if (!isset($this->all_flights[$id]['id'])) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident']));
351
352
		    //$putinarchive = true;
353
		    if (isset($line['departure_airport_time']) && $line['departure_airport_time'] != 0) {
354
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport_time' => $line['departure_airport_time']));
355
		    }
356
		    if (isset($line['arrival_airport_time']) && $line['arrival_airport_time'] != 0) {
357
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('arrival_airport_time' => $line['arrival_airport_time']));
358
		    }
359
		    if (isset($line['departure_airport_icao']) && isset($line['arrival_airport_icao'])) {
360
		    		$this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport' => $line['departure_airport_icao'],'arrival_airport' => $line['arrival_airport_icao'],'route_stop' => ''));
361
		    } elseif (isset($line['departure_airport_iata']) && isset($line['arrival_airport_iata'])) {
362
				$timeelapsed = microtime(true);
363
				$Spotter = new Spotter($this->db);
364
				$line['departure_airport_icao'] = $Spotter->getAirportIcao($line['departure_airport_iata']);
365
				$line['arrival_airport_icao'] = $Spotter->getAirportIcao($line['arrival_airport_iata']);
366
		    		$this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport' => $line['departure_airport_icao'],'arrival_airport' => $line['arrival_airport_icao'],'route_stop' => ''));
367
				if ($globalDebugTimeElapsed) echo 'Time elapsed for update getAirportICAO : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
368
369
		    } elseif (!isset($line['format_source']) || $line['format_source'] != 'aprs') {
370
			$timeelapsed = microtime(true);
371
			$Spotter = new Spotter($this->db);
372
			$route = $Spotter->getRouteInfo(trim($line['ident']));
373
			if (!isset($route['fromairport_icao']) && !isset($route['toairport_icao'])) {
374
				$Translation = new Translation($this->db);
375
				$ident = $Translation->checkTranslation(trim($line['ident']));
376
				$route = $Spotter->getRouteInfo($ident);
377
				$Translation->db = null;
378
			}
379
			$Spotter->db = null;
380
			if ($globalDebugTimeElapsed) echo 'Time elapsed for update getrouteinfo : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
381
382
			if (isset($route['fromairport_icao']) && isset($route['toairport_icao'])) {
383
			    //if ($route['FromAirport_ICAO'] != $route['ToAirport_ICAO']) {
384
			    if ($route['fromairport_icao'] != $route['toairport_icao']) {
385
				//    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport' => $route['FromAirport_ICAO'],'arrival_airport' => $route['ToAirport_ICAO'],'route_stop' => $route['RouteStop']));
386
		    		$this->all_flights[$id] = array_merge($this->all_flights[$id],array('departure_airport' => $route['fromairport_icao'],'arrival_airport' => $route['toairport_icao'],'route_stop' => $route['routestop']));
387
		    	    }
388
			}
389
			if (!isset($globalFork)) $globalFork = TRUE;
390
			if (!$globalIVAO && !$globalVATSIM && !$globalphpVMS && !$globalVAM && (!isset($line['format_source']) || $line['format_source'] != 'aprs')) {
391
				if (!isset($this->all_flights[$id]['schedule_check']) || $this->all_flights[$id]['schedule_check'] === false) $this->get_Schedule($id,trim($line['ident']));
392
			}
393
		    }
394
		}
395
396
		if (isset($line['speed']) && $line['speed'] != '') {
397
		//    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('speed' => $line[12]));
398
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('speed' => round($line['speed'])));
399
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('speed_fromsrc' => true));
400
		    //$dataFound = true;
401
		} else if (!isset($this->all_flights[$id]['speed_fromsrc']) && isset($this->all_flights[$id]['time_last_coord']) && $this->all_flights[$id]['time_last_coord'] != time() && isset($line['latitude']) && isset($line['longitude'])) {
402
		    $distance = $Common->distance($line['latitude'],$line['longitude'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],'m');
403
		    if ($distance > 1000 && $distance < 10000) {
404
		    // use datetime
405
			$speed = $distance/(time() - $this->all_flights[$id]['time_last_coord']);
406
			$speed = $speed*3.6;
407
			if ($speed < 1000) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('speed' => round($speed)));
408
  			if ($globalDebug) echo "ø Calculated Speed for ".$this->all_flights[$id]['hex']." : ".$speed." - distance : ".$distance."\n";
409
		    }
410
		}
411
412
413
414
	        if (isset($line['latitude']) && isset($line['longitude']) && $line['latitude'] != '' && $line['longitude'] != '' && is_numeric($line['latitude']) && is_numeric($line['longitude'])) {
415
	    	    if (isset($this->all_flights[$id]['time_last_coord'])) $timediff = round(time()-$this->all_flights[$id]['time_last_coord']);
416
	    	    else unset($timediff);
417
	    	    if ($this->tmd > 5 || (isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM) || (isset($globalphpVMS) && $globalphpVMS) || (isset($globalVAM) && $globalVAM) || !isset($timediff) || $timediff > 800 || ($timediff > 10 && isset($this->all_flights[$id]['latitude']) && isset($this->all_flights[$id]['longitude']) && $Common->withinThreshold($timediff,$Common->distance($line['latitude'],$line['longitude'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],'m')))) {
418
			if (isset($this->all_flights[$id]['archive_latitude']) && isset($this->all_flights[$id]['archive_longitude']) && isset($this->all_flights[$id]['livedb_latitude']) && isset($this->all_flights[$id]['livedb_longitude'])) {
419
			    if (!$Common->checkLine($this->all_flights[$id]['archive_latitude'],$this->all_flights[$id]['archive_longitude'],$this->all_flights[$id]['livedb_latitude'],$this->all_flights[$id]['livedb_longitude'],$line['latitude'],$line['longitude'])) {
420
				$this->all_flights[$id]['archive_latitude'] = $line['latitude'];
421
				$this->all_flights[$id]['archive_longitude'] = $line['longitude'];
422
				$this->all_flights[$id]['putinarchive'] = true;
423
				
424
				if ($globalDebug) echo "\n".' ------- Check Country for '.$this->all_flights[$id]['ident'].' with latitude : '.$line['latitude'].' and longitude : '.$line['longitude'].'.... ';
425
				$timeelapsed = microtime(true);
426
				$Spotter = new Spotter($this->db);
427
				$all_country = $Spotter->getCountryFromLatitudeLongitude($line['latitude'],$line['longitude']);
428
				if (!empty($all_country)) $this->all_flights[$id]['over_country'] = $all_country['iso2'];
429
				$Spotter->db = null;
430
				if ($globalDebugTimeElapsed) echo 'Time elapsed for update getCountryFromlatitudeLongitude : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
431
				$this->tmd = 0;
432
				if ($globalDebug) echo 'FOUND : '.$this->all_flights[$id]['over_country'].' ---------------'."\n";
433
			    }
434
			}
435
436
			if (isset($line['latitude']) && $line['latitude'] != '' && $line['latitude'] != 0 && $line['latitude'] < 91 && $line['latitude'] > -90) {
437
			    //if (!isset($this->all_flights[$id]['latitude']) || $this->all_flights[$id]['latitude'] == '' || abs($this->all_flights[$id]['latitude']-$line['latitude']) < 3 || $line['format_source'] != 'sbs' || time() - $this->all_flights[$id]['lastupdate'] > 30) {
438
				if (!isset($this->all_flights[$id]['archive_latitude'])) $this->all_flights[$id]['archive_latitude'] = $line['latitude'];
439
				if (!isset($this->all_flights[$id]['livedb_latitude']) || abs($this->all_flights[$id]['livedb_latitude']-$line['latitude']) > $globalCoordMinChange || $this->all_flights[$id]['format_source'] == 'aprs') {
440
				    $this->all_flights[$id]['livedb_latitude'] = $line['latitude'];
441
				    $dataFound = true;
442
				    $this->all_flights[$id]['time_last_coord'] = time();
443
				}
444
				// elseif ($globalDebug) echo '!*!*! Ignore data, too close to previous one'."\n";
445
				$this->all_flights[$id] = array_merge($this->all_flights[$id],array('latitude' => $line['latitude']));
446
				/*
447
				if (abs($this->all_flights[$id]['archive_latitude']-$this->all_flights[$id]['latitude']) > 0.3) {
448
				    $this->all_flights[$id]['archive_latitude'] = $line['latitude'];
449
				    $this->all_flights[$id]['putinarchive'] = true;
450
				    //$putinarchive = true;
451
				}
452
				*/
453
			    /*
454
			    } elseif (isset($this->all_flights[$id]['latitude'])) {
455
				if ($globalDebug) echo '!!! Strange latitude value - diff : '.abs($this->all_flights[$id]['latitude']-$line['latitude']).'- previous lat : '.$this->all_flights[$id]['latitude'].'- new lat : '.$line['latitude']."\n";
456
			    }
457
			    */
458
			}
459
			if (isset($line['longitude']) && $line['longitude'] != '' && $line['longitude'] != 0 && $line['longitude'] < 360 && $line['longitude'] > -180) {
460
			    if ($line['longitude'] > 180) $line['longitude'] = $line['longitude'] - 360;
461
			    //if (!isset($this->all_flights[$id]['longitude']) || $this->all_flights[$id]['longitude'] == ''  || abs($this->all_flights[$id]['longitude']-$line['longitude']) < 2 || $line['format_source'] != 'sbs' || time() - $this->all_flights[$id]['lastupdate'] > 30) {
462
				if (!isset($this->all_flights[$id]['archive_longitude'])) $this->all_flights[$id]['archive_longitude'] = $line['longitude'];
463
				if (!isset($this->all_flights[$id]['livedb_longitude']) || abs($this->all_flights[$id]['livedb_longitude']-$line['longitude']) > $globalCoordMinChange || $this->all_flights[$id]['format_source'] == 'aprs') {
464
				    $this->all_flights[$id]['livedb_longitude'] = $line['longitude'];
465
				    $dataFound = true;
466
				    $this->all_flights[$id]['time_last_coord'] = time();
467
				}
468
				// elseif ($globalDebug) echo '!*!*! Ignore data, too close to previous one'."\n";
469
				$this->all_flights[$id] = array_merge($this->all_flights[$id],array('longitude' => $line['longitude']));
470
				/*
471
				if (abs($this->all_flights[$id]['archive_longitude']-$this->all_flights[$id]['longitude']) > 0.3) {
472
				    $this->all_flights[$id]['archive_longitude'] = $line['longitude'];
473
				    $this->all_flights[$id]['putinarchive'] = true;
474
				    //$putinarchive = true;
475
				}
476
				*/
477
			/*
478
			    } elseif (isset($this->all_flights[$id]['longitude'])) {
479
				if ($globalDebug) echo '!!! Strange longitude value - diff : '.abs($this->all_flights[$id]['longitude']-$line['longitude']).'- previous lat : '.$this->all_flights[$id]['longitude'].'- new lat : '.$line['longitude']."\n";
480
			    }
481
			    */
482
			}
483
484
		    } else if ($globalDebug && $timediff > 20) {
485
			$this->tmd = $this->tmd + 1;
486
			echo '!!! Too much distance in short time... for '.$this->all_flights[$id]['ident']."\n";
487
			echo 'Time : '.$timediff.'s - Distance : '.$Common->distance($line['latitude'],$line['longitude'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],'m')."m -";
488
			echo 'Speed : '.(($Common->distance($line['latitude'],$line['longitude'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],'m')/$timediff)*3.6)." km/h - ";
489
			echo 'Lat : '.$line['latitude'].' - long : '.$line['longitude'].' - prev lat : '.$this->all_flights[$id]['latitude'].' - prev long : '.$this->all_flights[$id]['longitude']." \n";
490
		    }
491
		}
492
		if (isset($line['last_update']) && $line['last_update'] != '') {
493
		    if (isset($this->all_flights[$id]['last_update']) && $this->all_flights[$id]['last_update'] != $line['last_update']) $dataFound = true;
494
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('last_update' => $line['last_update']));
495
		}
496
		if (isset($line['verticalrate']) && $line['verticalrate'] != '') {
497
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('verticalrate' => $line['verticalrate']));
498
		    //$dataFound = true;
499
		}
500
		if (isset($line['format_source']) && $line['format_source'] != '') {
501
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('format_source' => $line['format_source']));
502
		}
503
		if (isset($line['source_name']) && $line['source_name'] != '') {
504
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('source_name' => $line['source_name']));
505
		}
506
		if (isset($line['emergency']) && $line['emergency'] != '') {
507
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('emergency' => $line['emergency']));
508
		    //$dataFound = true;
509
		}
510
		if (isset($line['ground']) && $line['ground'] != '') {
511
		    if (isset($this->all_flights[$id]['ground']) && $this->all_flights[$id]['ground'] == 1 && $line['ground'] == 0) {
512
			// Here we force archive of flight because after ground it's a new one (or should be)
513
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('addedSpotter' => 0));
514
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('forcenew' => 1));
515
			if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw') && $globalDaemon) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.date('YmdGi')));
516
		        elseif (isset($line['id'])) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $line['id']));
517
			elseif (isset($this->all_flights[$id]['ident'])) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.$this->all_flights[$id]['ident']));
518
		    }
519
		    if ($line['ground'] != 1) $line['ground'] = 0;
520
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('ground' => $line['ground']));
521
		    //$dataFound = true;
522
		}
523
		if (isset($line['squawk']) && $line['squawk'] != '') {
524
		    if (isset($this->all_flights[$id]['squawk']) && $this->all_flights[$id]['squawk'] != '7500' && $this->all_flights[$id]['squawk'] != '7600' && $this->all_flights[$id]['squawk'] != '7700' && isset($this->all_flights[$id]['id'])) {
525
			    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('squawk' => $line['squawk']));
526
			    $highlight = '';
527
			    if ($this->all_flights[$id]['squawk'] == '7500') $highlight = 'Squawk 7500 : Hijack at '.date('Y-m-d G:i').' UTC';
528
			    if ($this->all_flights[$id]['squawk'] == '7600') $highlight = 'Squawk 7600 : Lost Comm (radio failure) at '.date('Y-m-d G:i').' UTC';
529
			    if ($this->all_flights[$id]['squawk'] == '7700') $highlight = 'Squawk 7700 : Emergency at '.date('Y-m-d G:i').' UTC';
530
			    if ($highlight != '') {
531
				$timeelapsed = microtime(true);
532
				$Spotter = new Spotter($this->db);
533
				$Spotter->setHighlightFlight($this->all_flights[$id]['id'],$highlight);
534
				$Spotter->db = null;
535
				if ($globalDebugTimeElapsed) echo 'Time elapsed for update sethighlightflight : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
536
537
				$this->all_flights[$id]['putinarchive'] = true;
538
				//$putinarchive = true;
539
				//$highlight = '';
540
			    }
541
			    
542
		    } else $this->all_flights[$id] = array_merge($this->all_flights[$id],array('squawk' => $line['squawk']));
543
		    //$dataFound = true;
544
		}
545
546
		if (isset($line['altitude']) && $line['altitude'] != '') {
547
		    //if (!isset($this->all_flights[$id]['altitude']) || $this->all_flights[$id]['altitude'] == '' || ($this->all_flights[$id]['altitude'] > 0 && $line['altitude'] != 0)) {
548
			if (is_int($this->all_flights[$id]['altitude']) && abs(round($line['altitude']/100)-$this->all_flights[$id]['altitude']) > 2) $this->all_flights[$id]['putinarchive'] = true;
549
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('altitude' => round($line['altitude']/100)));
550
			$this->all_flights[$id] = array_merge($this->all_flights[$id],array('altitude_real' => $line['altitude']));
551
			//$dataFound = true;
552
		    //} elseif ($globalDebug) echo "!!! Strange altitude data... not added.\n";
553
  		}
554
555
		if (isset($line['noarchive']) && $line['noarchive'] === true) {
556
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('noarchive' => true));
557
		}
558
		
559
		if (isset($line['heading']) && $line['heading'] != '') {
560
		    if (is_int($this->all_flights[$id]['heading']) && abs($this->all_flights[$id]['heading']-round($line['heading'])) > 2) $this->all_flights[$id]['putinarchive'] = true;
561
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('heading' => round($line['heading'])));
562
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('heading_fromsrc' => true));
563
		    //$dataFound = true;
564
  		} elseif (!isset($this->all_flights[$id]['heading_fromsrc']) && isset($this->all_flights[$id]['archive_latitude']) && $this->all_flights[$id]['archive_latitude'] != $this->all_flights[$id]['latitude'] && isset($this->all_flights[$id]['archive_longitude']) && $this->all_flights[$id]['archive_longitude'] != $this->all_flights[$id]['longitude']) {
565
  		    $heading = $Common->getHeading($this->all_flights[$id]['archive_latitude'],$this->all_flights[$id]['archive_longitude'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude']);
566
		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('heading' => round($heading)));
567
		    if (abs($this->all_flights[$id]['heading']-round($heading)) > 2) $this->all_flights[$id]['putinarchive'] = true;
568
  		    if ($globalDebug) echo "ø Calculated Heading for ".$this->all_flights[$id]['hex']." : ".$heading."\n";
569
  		} elseif (isset($this->all_flights[$id]['format_source']) && $this->all_flights[$id]['format_source'] == 'ACARS') {
570
  		    // If not enough messages and ACARS set heading to 0
571
  		    $this->all_flights[$id] = array_merge($this->all_flights[$id],array('heading' => 0));
572
  		}
573
		if (isset($globalSourcesupdate) && $globalSourcesupdate != '' && isset($this->all_flights[$id]['lastupdate']) && time()-$this->all_flights[$id]['lastupdate'] < $globalSourcesupdate) $dataFound = false;
574
		elseif (isset($globalSBS1update) && $globalSBS1update != '' && isset($this->all_flights[$id]['lastupdate']) && time()-$this->all_flights[$id]['lastupdate'] < $globalSBS1update) $dataFound = false;
575
576
//		print_r($this->all_flights[$id]);
577
		//gets the callsign from the last hour
578
		//if (time()-$this->all_flights[$id]['lastupdate'] > 30 && $dataFound == true && $this->all_flights[$id]['ident'] != '' && $this->all_flights[$id]['latitude'] != '' && $this->all_flights[$id]['longitude'] != '') {
579
		//if ($dataFound == true && isset($this->all_flights[$id]['hex']) && $this->all_flights[$id]['ident'] != '' && $this->all_flights[$id]['latitude'] != '' && $this->all_flights[$id]['longitude'] != '') {
580
		//if ($dataFound === true && isset($this->all_flights[$id]['hex']) && $this->all_flights[$id]['heading'] != '' && $this->all_flights[$id]['latitude'] != '' && $this->all_flights[$id]['longitude'] != '') {
581
		if ($dataFound === true && isset($this->all_flights[$id]['hex'])) {
582
		    $this->all_flights[$id]['lastupdate'] = time();
583
		    if ($this->all_flights[$id]['addedSpotter'] == 0) {
584
		        if (!isset($globalDistanceIgnore['latitude']) || $this->all_flights[$id]['longitude'] == ''  || $this->all_flights[$id]['latitude'] == '' || (isset($globalDistanceIgnore['latitude']) && $Common->distance($this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],$globalDistanceIgnore['latitude'],$globalDistanceIgnore['longitude']) < $globalDistanceIgnore['distance'])) {
585
			    //print_r($this->all_flights);
586
			    //echo $this->all_flights[$id]['id'].' - '.$this->all_flights[$id]['addedSpotter']."\n";
587
			    //$last_hour_ident = Spotter->getIdentFromLastHour($this->all_flights[$id]['ident']);
588
			    if (!isset($this->all_flights[$id]['forcenew']) || $this->all_flights[$id]['forcenew'] == 0) {
589
				if ($globalDebug) echo "Check if aircraft is already in DB...";
590
				$timeelapsed = microtime(true);
591
				$SpotterLive = new SpotterLive($this->db);
592
				if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw' || $line['format_source'] === 'deltadbtxt' || $line['format_source'] === 'planeupdatefaa' || $line['format_source'] === 'aprs' || $line['format_source'] === 'aircraftlistjson' || $line['format_source'] === 'radarvirtueljson')) {
593
				    $recent_ident = $SpotterLive->checkModeSRecent($this->all_flights[$id]['hex']);
594
				    if ($globalDebugTimeElapsed) echo 'Time elapsed for update checkModeSRecent : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
595
				} elseif (isset($line['id'])) {
596
				    $recent_ident = $SpotterLive->checkIdRecent($line['id']);
597
				    if ($globalDebugTimeElapsed) echo 'Time elapsed for update checkIdRecent : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
598
				} elseif (isset($this->all_flights[$id]['ident']) && $this->all_flights[$id]['ident'] != '') {
599
				    $recent_ident = $SpotterLive->checkIdentRecent($this->all_flights[$id]['ident']);
600
				    if ($globalDebugTimeElapsed) echo 'Time elapsed for update checkIdentRecent : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
601
				} else $recent_ident = '';
602
				$SpotterLive->db=null;
603
604
				if ($globalDebug && $recent_ident == '') echo " Not in DB.\n";
605
				elseif ($globalDebug && $recent_ident != '') echo " Already in DB.\n";
606
			    } else {
607
				$recent_ident = '';
608
				$this->all_flights[$id] = array_merge($this->all_flights[$id],array('forcenew' => 0));
609
			    }
610
			    //if there was no aircraft with the same callsign within the last hour and go post it into the archive
611
			    if($recent_ident == "")
612
			    {
613
				if ($globalDebug) echo "\o/ Add ".$this->all_flights[$id]['ident']." in archive DB : ";
614
				if ($this->all_flights[$id]['departure_airport'] == "") { $this->all_flights[$id]['departure_airport'] = "NA"; }
615
				if ($this->all_flights[$id]['arrival_airport'] == "") { $this->all_flights[$id]['arrival_airport'] = "NA"; }
616
				//adds the spotter data for the archive
617
				$ignoreImport = false;
618
				foreach($globalAirportIgnore as $airportIgnore) {
619
				    if (($this->all_flights[$id]['departure_airport'] == $airportIgnore) || ($this->all_flights[$id]['arrival_airport'] == $airportIgnore)) {
620
					$ignoreImport = true;
621
				    }
622
				}
623
				if (count($globalAirportAccept) > 0) {
624
				    $ignoreImport = true;
625
				    foreach($globalAirportIgnore as $airportIgnore) {
626
					if (($this->all_flights[$id]['departure_airport'] == $airportIgnore) || ($this->all_flights[$id]['arrival_airport'] == $airportIgnore)) {
627
					    $ignoreImport = false;
628
					}
629
				    }
630
				}
631
				if (isset($globalAirlineIgnore) && is_array($globalAirlineIgnore)) {
632
				    foreach($globalAirlineIgnore as $airlineIgnore) {
633
					if ((is_numeric(substr(substr($this->all_flights[$id]['ident'],0,4),-1,1)) && substr($this->all_flights[$id]['ident'],0,3) == $airlineIgnore) || (is_numeric(substr(substr($this->all_flights[$id]['ident'],0,3),-1,1)) && substr($this->all_flights[$id]['ident'],0,2) == $airlineIgnore)) {
634
					    $ignoreImport = true;
635
					}
636
				    }
637
				}
638
				if (isset($globalAirlineAccept) && count($globalAirlineAccept) > 0) {
639
				    $ignoreImport = true;
640
				    foreach($globalAirlineAccept as $airlineAccept) {
641
					if ((is_numeric(substr(substr($this->all_flights[$id]['ident'],0,4),-1,1)) && substr($this->all_flights[$id]['ident'],0,3) == $airlineAccept) || (is_numeric(substr(substr($this->all_flights[$id]['ident'],0,3),-1,1)) && substr($this->all_flights[$id]['ident'],0,2) == $airlineAccept)) {
642
					    $ignoreImport = false;
643
					}
644
				    }
645
				}
646
				if (isset($globalPilotIdAccept) && count($globalPilotIdAccept) > 0) {
647
				    $ignoreImport = true;
648
				    foreach($globalPilotIdAccept as $pilotIdAccept) {
649
					if ($this->all_flights[$id]['pilot_id'] == $pilotIdAccept) {
650
					    $ignoreImport = false;
651
					}
652
				    }
653
				}
654
				
655
				if (!$ignoreImport) {
656
				    $highlight = '';
657
				    if ($this->all_flights[$id]['squawk'] == '7500') $highlight = 'Squawk 7500 : Hijack';
658
				    if ($this->all_flights[$id]['squawk'] == '7600') $highlight = 'Squawk 7600 : Lost Comm (radio failure)';
659
				    if ($this->all_flights[$id]['squawk'] == '7700') $highlight = 'Squawk 7700 : Emergency';
660
				    if (!isset($this->all_flights[$id]['id'])) $this->all_flights[$id] = array_merge($this->all_flights[$id],array('id' => $this->all_flights[$id]['hex'].'-'.date('YmdHi')));
661
				    $timeelapsed = microtime(true);
662
				    $Spotter = new Spotter($this->db);
663
				    $result = $Spotter->addSpotterData($this->all_flights[$id]['id'], $this->all_flights[$id]['ident'], $this->all_flights[$id]['aircraft_icao'], $this->all_flights[$id]['departure_airport'], $this->all_flights[$id]['arrival_airport'], $this->all_flights[$id]['latitude'], $this->all_flights[$id]['longitude'], $this->all_flights[$id]['waypoints'], $this->all_flights[$id]['altitude'], $this->all_flights[$id]['heading'], $this->all_flights[$id]['speed'], $this->all_flights[$id]['datetime'], $this->all_flights[$id]['departure_airport_time'], $this->all_flights[$id]['arrival_airport_time'],$this->all_flights[$id]['squawk'],$this->all_flights[$id]['route_stop'],$highlight,$this->all_flights[$id]['hex'],$this->all_flights[$id]['registration'],$this->all_flights[$id]['pilot_id'],$this->all_flights[$id]['pilot_name'],$this->all_flights[$id]['verticalrate'],$this->all_flights[$id]['ground'],$this->all_flights[$id]['format_source'],$this->all_flights[$id]['source_name']);
664
				    $Spotter->db = null;
665
				    if ($globalDebug && isset($result)) echo $result."\n";
666
				    if ($globalDebugTimeElapsed) echo 'Time elapsed for update addspotterdata : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
667
				    
668
				    // Add source stat in DB
669
				    $Stats = new Stats($this->db);
670
				    if (!empty($this->stats)) {
671
					if ($globalDebug) echo 'Add source stats : ';
672
				        foreach($this->stats as $date => $data) {
673
					    foreach($data as $source => $sourced) {
674
					        //print_r($sourced);
675
				    	        if (isset($sourced['polar'])) echo $Stats->addStatSource(json_encode($sourced['polar']),$source,'polar',$date);
676
				    	        if (isset($sourced['hist'])) echo $Stats->addStatSource(json_encode($sourced['hist']),$source,'hist',$date);
677
				    		if (isset($sourced['msg'])) {
678
				    		    if (time() - $sourced['msg']['date'] > 10) {
679
				    		        $nbmsg = round($sourced['msg']['nb']/(time() - $sourced['msg']['date']));
680
				    		        echo $Stats->addStatSource($nbmsg,$source,'msg',$date);
681
			    			        unset($this->stats[$date][$source]['msg']);
682
			    			    }
683
			    			}
684
			    		    }
685
			    		    if ($date != date('Y-m-d')) {
686
			    			unset($this->stats[$date]);
687
			    		    }
688
				    	}
689
				    	if ($globalDebug) echo 'Done'."\n";
690
691
				    }
692
				    $Stats->db = null;
693
				    
694
				    $this->del();
695
				} elseif ($globalDebug) echo 'Ignore data'."\n";
696
				//$ignoreImport = false;
697
				$this->all_flights[$id]['addedSpotter'] = 1;
698
				//print_r($this->all_flights[$id]);
699
			/*
700
			if (isset($globalArchive) && $globalArchive) {
701
			    $archives_ident = SpotterLive->getAllLiveSpotterDataByIdent($this->all_flights[$id]['ident']);
702
			    foreach ($archives_ident as $archive) {
703
				SpotterArchive->addSpotterArchiveData($archive['flightaware_id'], $archive['ident'], $archive['registration'],$archive['airline_name'],$archive['airline_icao'],$archive['airline_country'],$archive['airline_type'],$archive['aircraft_icao'],$archive['aircraft_shadow'],$archive['aircraft_name'],$archive['aircraft_manufacturer'], $archive['departure_airport_icao'],$archive['departure_airport_name'],$archive['departure_airport_city'],$archive['departure_airport_country'],$archive['departure_airport_time'],
704
				$archive['arrival_airport_icao'],$archive['arrival_airport_name'],$archive['arrival_airport_city'],$archive['arrival_airport_country'],$archive['arrival_airport_time'],
705
				$archive['route_stop'],$archive['date'],$archive['latitude'], $archive['longitude'], $archive['waypoints'], $archive['altitude'], $archive['heading'], $archive['ground_speed'],
706
				$archive['squawk'],$archive['ModeS']);
707
			    }
708
			}
709
			*/
710
			//SpotterLive->deleteLiveSpotterDataByIdent($this->all_flights[$id]['ident']);
711
				if ($this->last_delete == 0 || time() - $this->last_delete > 1800) {
712
				    if ($globalDebug) echo "---- Deleting Live Spotter data older than 9 hours...";
713
				    //SpotterLive->deleteLiveSpotterDataNotUpdated();
714
				    $SpotterLive = new SpotterLive($this->db);
715
				    $SpotterLive->deleteLiveSpotterData();
716
				    $SpotterLive->db=null;
717
				    if ($globalDebug) echo " Done\n";
718
				    $this->last_delete = time();
719
				}
720
			    } else {
721
				if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw' || $line['format_source'] === 'deltadbtxt'|| $line['format_source'] === 'planeupdatefaa'  || $line['format_source'] === 'aprs' || $line['format_source'] === 'aircraftlistjson')) {
722
				    $this->all_flights[$id]['id'] = $recent_ident;
723
				    $this->all_flights[$id]['addedSpotter'] = 1;
724
				}
725
				if (isset($globalDaemon) && !$globalDaemon) {
726
					$Spotter = new Spotter($this->db);
727
					$Spotter->updateLatestSpotterData($this->all_flights[$id]['id'],$this->all_flights[$id]['ident'],$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],$this->all_flights[$id]['altitude'],$this->all_flights[$id]['ground'],$this->all_flights[$id]['speed'],$this->all_flights[$id]['datetime'],$this->all_flights[$id]['arrival_airport'],$this->all_flights[$id]['arrival_airport_time']);
728
					$Spotter->db = null;
729
				}
730
				
731
			    }
732
			}
733
		    }
734
		    //adds the spotter LIVE data
735
		    //SpotterLive->addLiveSpotterData($flightaware_id, $ident, $aircraft_type, $departure_airport, $arrival_airport, $latitude, $longitude, $waypoints, $altitude, $heading, $groundspeed);
736
		    //echo "\nAdd in Live !! \n";
737
		    //echo "{$line[8]} {$line[7]} - MODES:{$line[4]}  CALLSIGN:{$line[10]}   ALT:{$line[11]}   VEL:{$line[12]}   HDG:{$line[13]}   LAT:{$line[14]}   LON:{$line[15]}   VR:{$line[16]}   SQUAWK:{$line[17]}\n";
738
		    if ($globalDebug) {
739
			if ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM) || (isset($globalphpVMS) && $globalphpVMS) || (isset($globalVAM) && $globalVAM)) {
740
				if (isset($this->all_flights[$id]['source_name'])) echo 'DATA : hex : '.$this->all_flights[$id]['hex'].' - ident : '.$this->all_flights[$id]['ident'].' - ICAO : '.$this->all_flights[$id]['aircraft_icao'].' - Departure Airport : '.$this->all_flights[$id]['departure_airport'].' - Arrival Airport : '.$this->all_flights[$id]['arrival_airport'].' - Latitude : '.$this->all_flights[$id]['latitude'].' - Longitude : '.$this->all_flights[$id]['longitude'].' - waypoints : '.$this->all_flights[$id]['waypoints'].' - Altitude : '.$this->all_flights[$id]['altitude'].' - Heading : '.$this->all_flights[$id]['heading'].' - Speed : '.$this->all_flights[$id]['speed'].' - Departure Airport Time : '.$this->all_flights[$id]['departure_airport_time'].' - Arrival Airport time : '.$this->all_flights[$id]['arrival_airport_time'].' - Pilot : '.$this->all_flights[$id]['pilot_name'].' - Source name : '.$this->all_flights[$id]['source_name']."\n";
741
				else echo 'DATA : hex : '.$this->all_flights[$id]['hex'].' - ident : '.$this->all_flights[$id]['ident'].' - ICAO : '.$this->all_flights[$id]['aircraft_icao'].' - Departure Airport : '.$this->all_flights[$id]['departure_airport'].' - Arrival Airport : '.$this->all_flights[$id]['arrival_airport'].' - Latitude : '.$this->all_flights[$id]['latitude'].' - Longitude : '.$this->all_flights[$id]['longitude'].' - waypoints : '.$this->all_flights[$id]['waypoints'].' - Altitude : '.$this->all_flights[$id]['altitude'].' - Heading : '.$this->all_flights[$id]['heading'].' - Speed : '.$this->all_flights[$id]['speed'].' - Departure Airport Time : '.$this->all_flights[$id]['departure_airport_time'].' - Arrival Airport time : '.$this->all_flights[$id]['arrival_airport_time'].' - Pilot : '.$this->all_flights[$id]['pilot_name']."\n";
742
			} else {
743
				if (isset($this->all_flights[$id]['source_name'])) echo 'DATA : hex : '.$this->all_flights[$id]['hex'].' - ident : '.$this->all_flights[$id]['ident'].' - ICAO : '.$this->all_flights[$id]['aircraft_icao'].' - Departure Airport : '.$this->all_flights[$id]['departure_airport'].' - Arrival Airport : '.$this->all_flights[$id]['arrival_airport'].' - Latitude : '.$this->all_flights[$id]['latitude'].' - Longitude : '.$this->all_flights[$id]['longitude'].' - waypoints : '.$this->all_flights[$id]['waypoints'].' - Altitude : '.$this->all_flights[$id]['altitude'].' - Heading : '.$this->all_flights[$id]['heading'].' - Speed : '.$this->all_flights[$id]['speed'].' - Departure Airport Time : '.$this->all_flights[$id]['departure_airport_time'].' - Arrival Airport time : '.$this->all_flights[$id]['arrival_airport_time'].' - Source Name : '.$this->all_flights[$id]['source_name']."\n";
744
				else echo 'DATA : hex : '.$this->all_flights[$id]['hex'].' - ident : '.$this->all_flights[$id]['ident'].' - ICAO : '.$this->all_flights[$id]['aircraft_icao'].' - Departure Airport : '.$this->all_flights[$id]['departure_airport'].' - Arrival Airport : '.$this->all_flights[$id]['arrival_airport'].' - Latitude : '.$this->all_flights[$id]['latitude'].' - Longitude : '.$this->all_flights[$id]['longitude'].' - waypoints : '.$this->all_flights[$id]['waypoints'].' - Altitude : '.$this->all_flights[$id]['altitude'].' - Heading : '.$this->all_flights[$id]['heading'].' - Speed : '.$this->all_flights[$id]['speed'].' - Departure Airport Time : '.$this->all_flights[$id]['departure_airport_time'].' - Arrival Airport time : '.$this->all_flights[$id]['arrival_airport_time']."\n";
745
			}
746
		    }
747
		    $ignoreImport = false;
748
		    if ($this->all_flights[$id]['departure_airport'] == "") { $this->all_flights[$id]['departure_airport'] = "NA"; }
749
		    if ($this->all_flights[$id]['arrival_airport'] == "") { $this->all_flights[$id]['arrival_airport'] = "NA"; }
750
751
		    foreach($globalAirportIgnore as $airportIgnore) {
752
		        if (($this->all_flights[$id]['departure_airport'] == $airportIgnore) || ($this->all_flights[$id]['arrival_airport'] == $airportIgnore)) {
753
			    $ignoreImport = true;
754
			}
755
		    }
756
		    if (count($globalAirportAccept) > 0) {
757
		        $ignoreImport = true;
758
		        foreach($globalAirportIgnore as $airportIgnore) {
759
			    if (($this->all_flights[$id]['departure_airport'] == $airportIgnore) || ($this->all_flights[$id]['arrival_airport'] == $airportIgnore)) {
760
				$ignoreImport = false;
761
			    }
762
			}
763
		    }
764
		    if (isset($globalAirlineIgnore) && is_array($globalAirlineIgnore)) {
765
			foreach($globalAirlineIgnore as $airlineIgnore) {
766
			    if ((is_numeric(substr(substr($this->all_flights[$id]['ident'],0,4),-1,1)) && substr($this->all_flights[$id]['ident'],0,3) == $airlineIgnore) || (is_numeric(substr(substr($this->all_flights[$id]['ident'],0,3),-1,1)) && substr($this->all_flights[$id]['ident'],0,2) == $airlineIgnore)) {
767
				$ignoreImport = true;
768
			    }
769
			}
770
		    }
771
		    if (isset($globalAirlineAccept) && count($globalAirlineAccept) > 0) {
772
			$ignoreImport = true;
773
			foreach($globalAirlineAccept as $airlineAccept) {
774
			    if ((is_numeric(substr(substr($this->all_flights[$id]['ident'],0,4),-1,1)) && substr($this->all_flights[$id]['ident'],0,3) == $airlineAccept) || (is_numeric(substr(substr($this->all_flights[$id]['ident'],0,3),-1,1)) && substr($this->all_flights[$id]['ident'],0,2) == $airlineAccept)) {
775
				$ignoreImport = false;
776
			    }
777
			}
778
		    }
779
		    if (isset($globalPilotIdAccept) && count($globalPilotIdAccept) > 0) {
780
			$ignoreImport = true;
781
			foreach($globalPilotIdAccept as $pilotIdAccept) {
782
			    if ($this->all_flights[$id]['pilot_id'] == $pilotIdAccept) {
783
			        $ignoreImport = false;
784
			    }
785
			}
786
		    }
787
788
		    if (!$ignoreImport) {
789
			if (!isset($globalDistanceIgnore['latitude']) || (isset($globalDistanceIgnore['latitude']) && $Common->distance($this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],$globalDistanceIgnore['latitude'],$globalDistanceIgnore['longitude']) < $globalDistanceIgnore['distance'])) {
790
				if ($globalDebug) echo "\o/ Add ".$this->all_flights[$id]['ident']." from ".$this->all_flights[$id]['format_source']." in Live DB : ";
791
				$timeelapsed = microtime(true);
792
				$SpotterLive = new SpotterLive($this->db);
793
				$result = $SpotterLive->addLiveSpotterData($this->all_flights[$id]['id'], $this->all_flights[$id]['ident'], $this->all_flights[$id]['aircraft_icao'], $this->all_flights[$id]['departure_airport'], $this->all_flights[$id]['arrival_airport'], $this->all_flights[$id]['latitude'], $this->all_flights[$id]['longitude'], $this->all_flights[$id]['waypoints'], $this->all_flights[$id]['altitude'], $this->all_flights[$id]['heading'], $this->all_flights[$id]['speed'],$this->all_flights[$id]['datetime'], $this->all_flights[$id]['departure_airport_time'], $this->all_flights[$id]['arrival_airport_time'], $this->all_flights[$id]['squawk'],$this->all_flights[$id]['route_stop'],$this->all_flights[$id]['hex'],$this->all_flights[$id]['putinarchive'],$this->all_flights[$id]['registration'],$this->all_flights[$id]['pilot_id'],$this->all_flights[$id]['pilot_name'], $this->all_flights[$id]['verticalrate'], $this->all_flights[$id]['noarchive'], $this->all_flights[$id]['ground'],$this->all_flights[$id]['format_source'],$this->all_flights[$id]['source_name'],$this->all_flights[$id]['over_country']);
794
				$SpotterLive->db = null;
795
				if ($globalDebugTimeElapsed) echo 'Time elapsed for update addlivespotterdata : '.round(microtime(true)-$timeelapsed,2).'s'."\n";
796
797
				// Put statistics in $this->stats variable
798
				//if ($line['format_source'] != 'aprs') {
799
				//if (isset($line['format_source']) && ($line['format_source'] === 'sbs' || $line['format_source'] === 'tsv' || $line['format_source'] === 'raw' || $line['format_source'] === 'deltadbtxt')) {
800
				if (isset($line['sourcestats']) && $line['sourcestats'] == TRUE && $line['format_source'] != 'aprs' && $this->all_flights[$id]['latitude'] != '' && $this->all_flights[$id]['longitude'] != '') {
801
					$source = $this->all_flights[$id]['source_name'];
802
					if ($source == '') $source = $this->all_flights[$id]['format_source'];
803
					if (!isset($this->source_location[$source])) {
804
						$Location = new Source();
805
						$coord = $Location->getLocationInfobySourceName($source);
806
						if (count($coord) > 0) {
807
							$latitude = $coord[0]['latitude'];
808
							$longitude = $coord[0]['longitude'];
809
						} else {
810
							$latitude = $globalCenterLatitude;
811
							$longitude = $globalCenterLongitude;
812
						}
813
						$this->source_location[$source] = array('latitude' => $latitude,'longitude' => $longitude);
814
					} else {
815
						$latitude = $this->source_location[$source]['latitude'];
816
						$longitude = $this->source_location[$source]['longitude'];
817
					}
818
					$stats_heading = $Common->getHeading($latitude,$longitude,$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude']);
819
					//$stats_heading = $stats_heading%22.5;
820
					$stats_heading = round($stats_heading/22.5);
821
					$stats_distance = $Common->distance($latitude,$longitude,$this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude']);
822
					$current_date = date('Y-m-d');
823
					if ($stats_heading == 16) $stats_heading = 0;
824
					if (!isset($this->stats[$current_date][$source]['polar'][1])) {
825
						for ($i=0;$i<=15;$i++) {
826
						    $this->stats[$current_date][$source]['polar'][$i] = 0;
827
						}
828
						$this->stats[$current_date][$source]['polar'][$stats_heading] = $stats_distance;
829
					} else {
830
						if ($this->stats[$current_date][$source]['polar'][$stats_heading] < $stats_distance) {
831
							$this->stats[$current_date][$source]['polar'][$stats_heading] = $stats_distance;
832
						}
833
					}
834
					$distance = (round($stats_distance/10)*10);
835
					//echo '$$$$$$$$$$ DISTANCE : '.$distance.' - '.$source."\n";
836
					//var_dump($this->stats);
837
					if (!isset($this->stats[$current_date][$source]['hist'][$distance])) {
838
						if (isset($this->stats[$current_date][$source]['hist'][0])) {
839
						    end($this->stats[$current_date][$source]['hist']);
840
						    $mini = key($this->stats[$current_date][$source]['hist'])+10;
841
						} else $mini = 0;
842
						for ($i=$mini;$i<=$distance;$i+=10) {
843
						    $this->stats[$current_date][$source]['hist'][$i] = 0;
844
						}
845
						$this->stats[$current_date][$source]['hist'][$distance] = 1;
846
					} else {
847
						$this->stats[$current_date][$source]['hist'][$distance] += 1;
848
					}
849
				}
850
851
				$this->all_flights[$id]['lastupdate'] = time();
852
				if ($this->all_flights[$id]['putinarchive']) $send = true;
853
				//if ($globalDebug) echo "Distance : ".Common->distance($this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],$globalDistanceIgnore['latitude'],$globalDistanceIgnore['longitude'])."\n";
854
				if ($globalDebug) echo $result."\n";
855
			} elseif (isset($this->all_flights[$id]['latitude']) && isset($globalDistanceIgnore['latitude']) && $globalDebug) echo "!! Too far -> Distance : ".$Common->distance($this->all_flights[$id]['latitude'],$this->all_flights[$id]['longitude'],$globalDistanceIgnore['latitude'],$globalDistanceIgnore['longitude'])."\n";
856
			//$this->del();
857
			
858
			
859
			if ($this->last_delete_hourly == 0 || time() - $this->last_delete_hourly > 900) {
860
			    if ($globalDebug) echo "---- Deleting Live Spotter data Not updated since 2 hour...";
861
			    $SpotterLive = new SpotterLive($this->db);
862
			    $SpotterLive->deleteLiveSpotterDataNotUpdated();
863
			    $SpotterLive->db = null;
864
			    //SpotterLive->deleteLiveSpotterData();
865
			    if ($globalDebug) echo " Done\n";
866
			    $this->last_delete_hourly = time();
867
			}
868
			
869
		    }
870
		    //$ignoreImport = false;
871
		}
872
		//if (function_exists('pcntl_fork') && $globalFork) pcntl_signal(SIGCHLD, SIG_IGN);
873
		if ($send) return $this->all_flights[$id];
874
	    }
875
	}
876
    }
877
}
878
?>
879