Completed
Push — master ( 347b49...ab55a5 )
by Yannick
05:41
created

daemon-spotter.php ➔ create_socket()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 4
nop 4
dl 0
loc 13
rs 8.8571
c 0
b 0
f 0
1
#!/usr/bin/php
2
<?php
3
/**
4
* This script is used to retrieve message from SBS source like Dump1090, Radarcape,.. or from phpvms, wazzup files,...
5
* This script can be used as cron job with $globalDaemon = FALSE
6
*/
7
8
require_once(dirname(__FILE__).'/../require/class.SpotterImport.php');
9
require_once(dirname(__FILE__).'/../require/class.SpotterServer.php');
10
//require_once(dirname(__FILE__).'/../require/class.APRS.php');
11
require_once(dirname(__FILE__).'/../require/class.ATC.php');
12
require_once(dirname(__FILE__).'/../require/class.ACARS.php');
13
require_once(dirname(__FILE__).'/../require/class.SBS.php');
14
require_once(dirname(__FILE__).'/../require/class.Connection.php');
15
require_once(dirname(__FILE__).'/../require/class.Common.php');
16
17
if (!isset($globalDebug)) $globalDebug = FALSE;
18
19
// Check if schema is at latest version
20
$Connection = new Connection();
21
if ($Connection->latest() === false) {
22
    echo "You MUST update to latest schema. Run install/index.php";
23
    exit();
24
}
25
26
27
// This is to be compatible with old version of settings.php
28
if (!isset($globalSources)) {
29
    if (isset($globalSBS1Hosts)) {
30
        //$hosts = $globalSBS1Hosts;
31
        foreach ($globalSBS1Hosts as $host) {
32
	    $globalSources[] = array('host' => $host);
33
    	}
34
    } else {
35
        if (!isset($globalSBS1Host)) {
36
	    echo '$globalSources MUST be defined !';
37
	    die;
38
	}
39
	//$hosts = array($globalSBS1Host.':'.$globalSBS1Port);
40
	$globalSources[] = array('host' => $globalSBS1Host,'port' => $globalSBS1Port);
41
    }
42
}
43
44
$options = getopt('s::',array('source::','server','idsource::'));
45
//if (isset($options['s'])) $hosts = array($options['s']);
46
//elseif (isset($options['source'])) $hosts = array($options['source']);
47
if (isset($options['s'])) {
48
    $globalSources = array();
49
    $globalSources[] = array('host' => $options['s']);
50
} elseif (isset($options['source'])) {
51
    $globalSources = array();
52
    $globalSources[] = array('host' => $options['source']);
53
}
54
if (isset($options['server'])) $globalServer = TRUE;
55
if (isset($options['idsource'])) $id_source = $options['idsource'];
56
else $id_source = 1;
57
if (isset($globalServer) && $globalServer) {
58
    if ($globalDebug) echo "Using Server Mode\n";
59
    $SI=new SpotterServer();
60
} else $SI=new SpotterImport($Connection->db);
61
//$APRS=new APRS($Connection->db);
62
$SBS=new SBS();
63
$ACARS=new ACARS($Connection->db);
64
$Common=new Common();
65
date_default_timezone_set('UTC');
66
//$servertz = system('date +%Z');
67
// signal handler - playing nice with sockets and dump1090
68
if (function_exists('pcntl_fork')) {
69
    pcntl_signal(SIGINT,  function() {
70
        global $sockets;
71
        echo "\n\nctrl-c or kill signal received. Tidying up ... ";
72
        die("Bye!\n");
73
    });
74
    pcntl_signal_dispatch();
75
}
76
77
// let's try and connect
78
if ($globalDebug) echo "Connecting...\n";
79
$use_aprs = false;
80
$aprs_full = false;
81
82
function create_socket($host, $port, &$errno, &$errstr) {
83
    $ip = gethostbyname($host);
84
    $s = socket_create(AF_INET, SOCK_STREAM, 0);
85
    $r = @socket_connect($s, $ip, $port);
86
    if (!socket_set_nonblock($s)) echo "Unable to set nonblock on socket\n";
87
    if ($r || socket_last_error() == 114 || socket_last_error() == 115) {
88
        return $s;
89
    }
90
    $errno = socket_last_error($s);
91
    $errstr = socket_strerror($errno);
92
    socket_close($s);
93
    return false;
94
}
95
96
function create_socket_udp($host, $port, &$errno, &$errstr) {
97
    echo "UDP !!";
98
    $ip = gethostbyname($host);
99
    $s = socket_create(AF_INET, SOCK_DGRAM, 0);
100
    $r = @socket_bind($s, $ip, $port);
101
    if ($r || socket_last_error() == 114 || socket_last_error() == 115) {
102
        return $s;
103
    }
104
    $errno = socket_last_error($s);
105
    $errstr = socket_strerror($errno);
106
    socket_close($s);
107
    return false;
108
}
109
110
function connect_all($hosts) {
111
    //global $sockets, $formats, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs;
112
    global $sockets, $globalSources, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs;
113
    if ($globalDebug) echo 'Connect to all...'."\n";
114
    foreach ($hosts as $id => $value) {
115
	$host = $value['host'];
116
	$globalSources[$id]['last_exec'] = 0;
117
	// Here we check type of source(s)
118
	if (filter_var($host,FILTER_VALIDATE_URL) && (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto')) {
119
            if (preg_match('/deltadb.txt$/i',$host)) {
120
        	//$formats[$id] = 'deltadbtxt';
121
        	$globalSources[$id]['format'] = 'deltadbtxt';
122
        	//$last_exec['deltadbtxt'] = 0;
123
        	if ($globalDebug) echo "Connect to deltadb source (".$host.")...\n";
124
            } else if (preg_match('/vatsim-data.txt$/i',$host)) {
125
        	//$formats[$id] = 'vatsimtxt';
126
        	$globalSources[$id]['format'] = 'vatsimtxt';
127
        	//$last_exec['vatsimtxt'] = 0;
128
        	if ($globalDebug) echo "Connect to vatsim source (".$host.")...\n";
129
    	    } else if (preg_match('/aircraftlist.json$/i',$host)) {
130
        	//$formats[$id] = 'aircraftlistjson';
131
        	$globalSources[$id]['format'] = 'aircraftlistjson';
132
        	//$last_exec['aircraftlistjson'] = 0;
133
        	if ($globalDebug) echo "Connect to aircraftlist.json source (".$host.")...\n";
134
    	    } else if (preg_match('/opensky/i',$host)) {
135
        	//$formats[$id] = 'aircraftlistjson';
136
        	$globalSources[$id]['format'] = 'opensky';
137
        	//$last_exec['aircraftlistjson'] = 0;
138
        	if ($globalDebug) echo "Connect to opensky source (".$host.")...\n";
139
    	    } else if (preg_match('/radarvirtuel.com\/file.json$/i',$host)) {
140
        	//$formats[$id] = 'radarvirtueljson';
141
        	$globalSources[$id]['format'] = 'radarvirtueljson';
142
        	//$last_exec['radarvirtueljson'] = 0;
143
        	if ($globalDebug) echo "Connect to radarvirtuel.com/file.json source (".$host.")...\n";
144
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
145
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
146
        	    exit(0);
147
        	}
148
    	    } else if (preg_match('/planeUpdateFAA.php$/i',$host)) {
149
        	//$formats[$id] = 'planeupdatefaa';
150
        	$globalSources[$id]['format'] = 'planeupdatefaa';
151
        	//$last_exec['planeupdatefaa'] = 0;
152
        	if ($globalDebug) echo "Connect to planeUpdateFAA.php source (".$host.")...\n";
153
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
154
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
155
        	    exit(0);
156
        	}
157
            } else if (preg_match('/\/action.php\/acars\/data$/i',$host)) {
158
        	//$formats[$id] = 'phpvmacars';
159
        	$globalSources[$id]['format'] = 'phpvmacars';
160
        	//$last_exec['phpvmacars'] = 0;
161
        	if ($globalDebug) echo "Connect to phpvmacars source (".$host.")...\n";
162
            } else if (preg_match('/whazzup/i',$host)) {
163
        	//$formats[$id] = 'whazzup';
164
        	$globalSources[$id]['format'] = 'whazzup';
165
        	//$last_exec['whazzup'] = 0;
166
        	if ($globalDebug) echo "Connect to whazzup source (".$host.")...\n";
167
            } else if (preg_match('/recentpireps/i',$host)) {
168
        	//$formats[$id] = 'pirepsjson';
169
        	$globalSources[$id]['format'] = 'pirepsjson';
170
        	//$last_exec['pirepsjson'] = 0;
171
        	if ($globalDebug) echo "Connect to pirepsjson source (".$host.")...\n";
172
            } else if (preg_match(':data.fr24.com/zones/fcgi/feed.js:i',$host)) {
173
        	//$formats[$id] = 'fr24json';
174
        	$globalSources[$id]['format'] = 'fr24json';
175
        	//$last_exec['fr24json'] = 0;
176
        	if ($globalDebug) echo "Connect to fr24 source (".$host.")...\n";
177
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
178
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
179
        	    exit(0);
180
        	}
181
            //} else if (preg_match('/10001/',$host)) {
182
            } else if (preg_match('/10001/',$host) || (isset($globalSources[$id]['port']) && $globalSources[$id]['port'] == '10001')) {
183
        	//$formats[$id] = 'tsv';
184
        	$globalSources[$id]['format'] = 'tsv';
185
        	if ($globalDebug) echo "Connect to tsv source (".$host.")...\n";
186
            }
187
        } elseif (filter_var($host,FILTER_VALIDATE_URL)) {
188
        	if ($globalDebug) echo "Connect to ".$globalSources[$id]['format']." source (".$host.")...\n";
189
        } elseif (!filter_var($host,FILTER_VALIDATE_URL)) {
190
	    $hostport = explode(':',$host);
191
	    if (isset($hostport[1])) {
192
		$port = $hostport[1];
193
		$hostn = $hostport[0];
194
	    } else {
195
		$port = $globalSources[$id]['port'];
196
		$hostn = $globalSources[$id]['host'];
197
	    }
198
	    if (!isset($globalSources[$id]['format']) || ($globalSources[$id]['format'] != 'acars' && $globalSources[$id]['format'] != 'flightgearsp')) {
199
        	$s = create_socket($hostn,$port, $errno, $errstr);
200
    	    } else {
201
        	$s = create_socket_udp($hostn,$port, $errno, $errstr);
202
	    }
203
	    if ($s) {
204
    	        $sockets[$id] = $s;
205
    	        if (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto') {
206
		    if (preg_match('/aprs/',$hostn)) {
207
			//$formats[$id] = 'aprs';
208
			$globalSources[$id]['format'] = 'aprs';
209
			//$aprs_connect = 0;
210
			//$use_aprs = true;
211
    		    } elseif ($port == '10001') {
212
        		//$formats[$id] = 'tsv';
213
        		$globalSources[$id]['format'] = 'tsv';
214
		    } elseif ($port == '30002') {
215
        		//$formats[$id] = 'raw';
216
        		$globalSources[$id]['format'] = 'raw';
217
		    } elseif ($port == '5001') {
218
        		//$formats[$id] = 'raw';
219
        		$globalSources[$id]['format'] = 'flightgearmp';
220
		    } elseif ($port == '30005') {
221
			// Not yet supported
222
        		//$formats[$id] = 'beast';
223
        		$globalSources[$id]['format'] = 'beast';
224
		    //} else $formats[$id] = 'sbs';
225
		    } else $globalSources[$id]['format'] = 'sbs';
226
		    //if ($globalDebug) echo 'Connection in progress to '.$host.'('.$formats[$id].')....'."\n";
227
		}
228
		if ($globalDebug) echo 'Connection in progress to '.$hostn.':'.$port.' ('.$globalSources[$id]['format'].')....'."\n";
229
            } else {
230
		if ($globalDebug) echo 'Connection failed to '.$hostn.':'.$port.' : '.$errno.' '.$errstr."\n";
231
    	    }
232
        }
233
    }
234
}
235
if (!isset($globalMinFetch)) $globalMinFetch = 15;
236
237
// Initialize all
238
$status = array();
239
$sockets = array();
240
$formats = array();
241
$last_exec = array();
242
$time = time();
243
if (isset($globalSourcesTimeout)) $timeout = $globalSourcesTimeOut;
244
else if (isset($globalSBS1TimeOut)) $timeout = $globalSBS1TimeOut;
245
else $timeout = 20;
246
$errno = '';
247
$errstr='';
248
249
if (!isset($globalDaemon)) $globalDaemon = TRUE;
250
/* Initiate connections to all the hosts simultaneously */
251
//connect_all($hosts);
252
//connect_all($globalSources);
253
254
// APRS Configuration
255
if (!is_array($globalSources)) {
256
	echo '$globalSources in require/settings.php MUST be an array';
257
	die;
258
}
259
foreach ($globalSources as $key => $source) {
260
    if (!isset($source['format'])) {
261
        $globalSources[$key]['format'] = 'auto';
262
    }
263
}
264
connect_all($globalSources);
265
foreach ($globalSources as $key => $source) {
266
    if (isset($source['format']) && $source['format'] == 'aprs') {
267
	$aprs_connect = 0;
268
	$use_aprs = true;
269
	if (isset($source['port']) && $source['port'] == '10152') $aprs_full = true;
270
	break;
271
    }
272
}
273
274
if ($use_aprs) {
275
	require_once(dirname(__FILE__).'/../require/class.APRS.php');
276
	$APRS=new APRS();
277
	$aprs_connect = 0;
278
	$aprs_keep = 120;
279
	$aprs_last_tx = time();
280
	if (isset($globalAPRSversion)) $aprs_version = $globalAPRSversion;
281
	else $aprs_version = $globalName.' using FlightAirMap';
282
	//else $aprs_version = 'Perl Example App';
283
	if (isset($globalAPRSssid)) $aprs_ssid = $globalAPRSssid;
284
	else $aprs_ssid = 'FAM';
285
	//else $aprs_ssid = 'PerlEx';
286
	if (isset($globalAPRSfilter)) $aprs_filter = $globalAPRSfilter;
287
	else $aprs_filter =  'r/'.$globalCenterLatitude.'/'.$globalCenterLongitude.'/250.0';
288
	if ($aprs_full) $aprs_filter = '';
289
	if ($aprs_filter != '') $aprs_login = "user {$aprs_ssid} appid {$aprs_version} filter {$aprs_filter}\n";
290
	else $aprs_login = "user {$aprs_ssid} appid {$aprs_version}\n";
291
}
292
293
// connected - lets do some work
294
if ($globalDebug) echo "Connected!\n";
295
sleep(1);
296
if ($globalDebug) echo "SCAN MODE \n\n";
297
if (!isset($globalCronEnd)) $globalCronEnd = 60;
298
$endtime = time()+$globalCronEnd;
299
$i = 1;
300
$tt = array();
301
// Delete all ATC
302
if ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM)) {
303
	$ATC=new ATC($Connection->db);
304
}
305
if (!$globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
306
	$ATC->deleteAll();
307
}
308
309
// Infinite loop if daemon, else work for time defined in $globalCronEnd or only one time.
310
while ($i > 0) {
311
    if (!$globalDaemon) $i = $endtime-time();
312
    // Delete old ATC
313
    if ($globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
314
	if ($globalDebug) echo 'Delete old ATC...'."\n";
315
        $ATC->deleteOldATC();
316
    }
317
    
318
    if (count($last_exec) > 0) {
319
	$max = $globalMinFetch;
320
	foreach ($last_exec as $last) {
321
	    if ((time() - $last['last']) < $max) $max = time() - $last['last'];
322
	}
323
	if ($max != $globalMinFetch) {
324
	    if ($globalDebug) echo 'Sleeping...'."\n";
325
	    sleep($globalMinFetch-$max+2);
326
	}
327
    }
328
329
    
330
    //foreach ($formats as $id => $value) {
331
    foreach ($globalSources as $id => $value) {
332
	if (!isset($last_exec[$id]['last'])) $last_exec[$id]['last'] = 0;
333
	if ($value['format'] == 'deltadbtxt' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
334
	    //$buffer = $Common->getData($hosts[$id]);
335
	    $buffer = $Common->getData($value['host']);
336
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
337
	    $buffer = explode('\n',$buffer);
338
	    foreach ($buffer as $line) {
339
    		if ($line != '') {
340
    		    $line = explode(',', $line);
341
	            $data = array();
342
	            $data['hex'] = $line[1]; // hex
343
	            $data['ident'] = $line[2]; // ident
344
	            $data['altitude'] = $line[3]; // altitude
345
	            $data['speed'] = $line[4]; // speed
346
	            $data['heading'] = $line[5]; // heading
347
	            $data['latitude'] = $line[6]; // lat
348
	            $data['longitude'] = $line[7]; // long
349
	            $data['verticalrate'] = ''; // vertical rate
350
	            $data['squawk'] = ''; // squawk
351
	            $data['emergency'] = ''; // emergency
352
		    $data['datetime'] = date('Y-m-d H:i:s');
353
		    $data['format_source'] = 'deltadbtxt';
354
    		    $data['id_source'] = $id_source;
355
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
356
		    if (isset($value['sourcestats'])) $data['sourcestats'] = $value['sourcestats'];
357
    		    $SI->add($data);
358
		    unset($data);
359
    		}
360
    	    }
361
    	    $last_exec[$id]['last'] = time();
362
	//} elseif (($value == 'whazzup' && (time() - $last_exec['whazzup'] > $globalMinFetch)) || ($value == 'vatsimtxt' && (time() - $last_exec['vatsimtxt'] > $globalMinFetch))) {
363
	} elseif (($value['format'] == 'whazzup' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) || ($value['format'] == 'vatsimtxt' && (time() - $value[' last_exec'] > $globalMinFetch))) {
364
	    //$buffer = $Common->getData($hosts[$id]);
365
	    $buffer = $Common->getData($value['host']);
366
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
367
	    $buffer = explode('\n',$buffer);
368
	    foreach ($buffer as $line) {
369
    		if ($line != '') {
370
    		    $line = explode(':', $line);
371
    		    if (count($line) > 30 && $line[0] != 'callsign') {
372
			$data = array();
373
			$data['id'] = $line[1].'-'.$line[0];
374
			$data['pilot_id'] = $line[1];
375
			$data['pilot_name'] = $line[2];
376
			$data['hex'] = str_pad(dechex($line[1]),6,'000000',STR_PAD_LEFT);
377
			$data['ident'] = $line[0]; // ident
378
			if ($line[7] != '' && $line[7] != 0) $data['altitude'] = $line[7]; // altitude
379
			$data['speed'] = $line[8]; // speed
380
			if (isset($line[45])) $data['heading'] = $line[45]; // heading
381
			elseif (isset($line[38])) $data['heading'] = $line[38]; // heading
382
			$data['latitude'] = $line[5]; // lat
383
	        	$data['longitude'] = $line[6]; // long
384
	        	$data['verticalrate'] = ''; // vertical rate
385
	        	$data['squawk'] = ''; // squawk
386
	        	$data['emergency'] = ''; // emergency
387
	        	$data['waypoints'] = $line[30];
388
			$data['datetime'] = date('Y-m-d H:i:s');
389
			//$data['datetime'] = date('Y-m-d H:i:s',strtotime($line[37]));
390
			if (isset($line[37])) $data['last_update'] = $line[37];
391
		        $data['departure_airport_icao'] = $line[11];
392
		        $data['departure_airport_time'] = rtrim(chunk_split($line[22],2,':'),':');
393
		        $data['arrival_airport_icao'] = $line[13];
394
			$data['frequency'] = $line[4];
395
			$data['type'] = $line[18];
396
			$data['range'] = $line[19];
397
			if (isset($line[35])) $data['info'] = $line[35];
398
    			$data['id_source'] = $id_source;
399
	    		//$data['arrival_airport_time'] = ;
400
	    		if ($line[9] != '') {
401
	    		    $aircraft_data = explode('/',$line[9]);
402
	    		    if (isset($aircraft_data[1])) {
403
	    			$data['aircraft_icao'] = $aircraft_data[1];
404
	    		    }
405
        		}
406
	    		/*
407
	    		if ($value == 'whazzup') $data['format_source'] = 'whazzup';
408
	    		elseif ($value == 'vatsimtxt') $data['format_source'] = 'vatsimtxt';
409
	    		*/
410
	    		$data['format_source'] = $value['format'];
411
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
412
    			if ($line[3] == 'PILOT') $SI->add($data);
413
			elseif ($line[3] == 'ATC') {
414
				//print_r($data);
415
				$data['info'] = str_replace('^&sect;','<br />',$data['info']);
416
				$data['info'] = str_replace('&amp;sect;','',$data['info']);
417
				$typec = substr($data['ident'],-3);
418
				if ($typec == 'APP') $data['type'] = 'Approach';
419
				elseif ($typec == 'TWR') $data['type'] = 'Tower';
420
				elseif ($typec == 'OBS') $data['type'] = 'Observer';
421
				elseif ($typec == 'GND') $data['type'] = 'Ground';
422
				elseif ($typec == 'DEL') $data['type'] = 'Delivery';
423
				elseif ($typec == 'DEP') $data['type'] = 'Departure';
424
				elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
425
				elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
426
				elseif ($data['type'] == '') $data['type'] = 'Observer';
427
				
428
				echo $ATC->add($data['ident'],$data['frequency'],$data['latitude'],$data['longitude'],$data['range'],$data['info'],$data['datetime'],$data['type'],$data['pilot_id'],$data['pilot_name']);
429
			}
430
    			unset($data);
431
    		    }
432
    		}
433
    	    }
434
    	    //if ($value == 'whazzup') $last_exec['whazzup'] = time();
435
    	    //elseif ($value == 'vatsimtxt') $last_exec['vatsimtxt'] = time();
436
    	    $last_exec[$id]['last'] = time();
437
    	//} elseif ($value == 'aircraftlistjson' && (time() - $last_exec['aircraftlistjson'] > $globalMinFetch)) {
438
    	} elseif ($value['format'] == 'aircraftlistjson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
439
	    $buffer = $Common->getData($value['host'],'get','','','','','20');
440
	    if ($buffer != '') {
441
	    $all_data = json_decode($buffer,true);
442
	    if (isset($all_data['acList'])) {
443
		foreach ($all_data['acList'] as $line) {
444
		    $data = array();
445
		    $data['hex'] = $line['Icao']; // hex
446
		    if (isset($line['Call'])) $data['ident'] = $line['Call']; // ident
447
		    if (isset($line['Alt'])) $data['altitude'] = $line['Alt']; // altitude
448
		    if (isset($line['Spd'])) $data['speed'] = $line['Spd']; // speed
449
		    if (isset($line['Trak'])) $data['heading'] = $line['Trak']; // heading
450
		    if (isset($line['Lat'])) $data['latitude'] = $line['Lat']; // lat
451
		    if (isset($line['Long'])) $data['longitude'] = $line['Long']; // long
452
		    //$data['verticalrate'] = $line['']; // verticale rate
453
		    if (isset($line['Sqk'])) $data['squawk'] = $line['Sqk']; // squawk
454
		    $data['emergency'] = ''; // emergency
455
		    if (isset($line['Reg'])) $data['registration'] = $line['Reg'];
456
		    /*
457
		    if (isset($line['PosTime'])) $data['datetime'] = date('Y-m-d H:i:s',$line['PosTime']/1000);
458
		    else $data['datetime'] = date('Y-m-d H:i:s');
459
		    */
460
		    $data['datetime'] = date('Y-m-d H:i:s');
461
		    if (isset($line['Type'])) $data['aircraft_icao'] = $line['Type'];
462
	    	    $data['format_source'] = 'aircraftlistjson';
463
		    $data['id_source'] = $id_source;
464
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
465
		    if (isset($data['datetime'])) $SI->add($data);
466
		    unset($data);
467
		}
468
	    } else {
469
		foreach ($all_data as $line) {
470
		    $data = array();
471
		    $data['hex'] = $line['hex']; // hex
472
		    $data['ident'] = $line['flight']; // ident
473
		    $data['altitude'] = $line['altitude']; // altitude
474
		    $data['speed'] = $line['speed']; // speed
475
		    $data['heading'] = $line['track']; // heading
476
		    $data['latitude'] = $line['lat']; // lat
477
		    $data['longitude'] = $line['lon']; // long
478
		    $data['verticalrate'] = $line['vrt']; // verticale rate
479
		    $data['squawk'] = $line['squawk']; // squawk
480
		    $data['emergency'] = ''; // emergency
481
		    $data['datetime'] = date('Y-m-d H:i:s');
482
	    	    $data['format_source'] = 'aircraftlistjson';
483
    		    $data['id_source'] = $id_source;
484
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
485
		    $SI->add($data);
486
		    unset($data);
487
		}
488
	    }
489
	    }
490
    	    //$last_exec['aircraftlistjson'] = time();
491
    	    $last_exec[$id]['last'] = time();
492
    	//} elseif ($value == 'planeupdatefaa' && (time() - $last_exec['planeupdatefaa'] > $globalMinFetch)) {
493
    	} elseif ($value['format'] == 'planeupdatefaa' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
494
	    $buffer = $Common->getData($value['host']);
495
	    $all_data = json_decode($buffer,true);
496
	    if (isset($all_data['planes'])) {
497
		foreach ($all_data['planes'] as $key => $line) {
498
		    $data = array();
499
		    $data['hex'] = $key; // hex
500
		    $data['ident'] = $line[3]; // ident
501
		    $data['altitude'] = $line[6]; // altitude
502
		    $data['speed'] = $line[8]; // speed
503
		    $data['heading'] = $line[7]; // heading
504
		    $data['latitude'] = $line[4]; // lat
505
		    $data['longitude'] = $line[5]; // long
506
		    //$data['verticalrate'] = $line[]; // verticale rate
507
		    $data['squawk'] = $line[10]; // squawk
508
		    $data['emergency'] = ''; // emergency
509
		    $data['registration'] = $line[2];
510
		    $data['aircraft_icao'] = $line[0];
511
		    $deparr = explode('-',$line[1]);
512
		    if (count($deparr) == 2) {
513
			$data['departure_airport_icao'] = $deparr[0];
514
			$data['arrival_airport_icao'] = $deparr[1];
515
		    }
516
		    $data['datetime'] = date('Y-m-d H:i:s',$line[9]);
517
	    	    $data['format_source'] = 'planeupdatefaa';
518
    		    $data['id_source'] = $id_source;
519
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
520
		    $SI->add($data);
521
		    unset($data);
522
		}
523
	    }
524
    	    //$last_exec['planeupdatefaa'] = time();
525
    	    $last_exec[$id]['last'] = time();
526
    	} elseif ($value['format'] == 'opensky' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
527
	    $buffer = $Common->getData($value['host']);
528
	    $all_data = json_decode($buffer,true);
529
	    if (isset($all_data['states'])) {
530
		foreach ($all_data['states'] as $key => $line) {
531
		    $data = array();
532
		    $data['hex'] = $line[0]; // hex
533
		    $data['ident'] = trim($line[1]); // ident
534
		    $data['altitude'] = round($line[7]*3.28084); // altitude
535
		    $data['speed'] = round($line[9]*1.94384); // speed
536
		    $data['heading'] = round($line[10]); // heading
537
		    $data['latitude'] = $line[5]; // lat
538
		    $data['longitude'] = $line[6]; // long
539
		    $data['verticalrate'] = $line[11]; // verticale rate
540
		    //$data['squawk'] = $line[10]; // squawk
541
		    //$data['emergency'] = ''; // emergency
542
		    //$data['registration'] = $line[2];
543
		    //$data['aircraft_icao'] = $line[0];
544
		    $data['datetime'] = date('Y-m-d H:i:s',$line[3]);
545
	    	    $data['format_source'] = 'opensky';
546
    		    $data['id_source'] = $id_source;
547
		    $SI->add($data);
548
		    unset($data);
549
		}
550
	    }
551
    	    //$last_exec['planeupdatefaa'] = time();
552
    	    $last_exec[$id]['last'] = time();
553
    	//} elseif ($value == 'fr24json' && (time() - $last_exec['fr24json'] > $globalMinFetch)) {
554
    	} elseif ($value['format'] == 'fr24json' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
555
	    //$buffer = $Common->getData($hosts[$id]);
556
	    $buffer = $Common->getData($value['host']);
557
	    $all_data = json_decode($buffer,true);
558
	    foreach ($all_data as $key => $line) {
559
		if ($key != 'full_count' && $key != 'version' && $key != 'stats') {
560
		    $data = array();
561
		    $data['hex'] = $line[0];
562
		    $data['ident'] = $line[16]; //$line[13]
563
	    	    $data['altitude'] = $line[4]; // altitude
564
	    	    $data['speed'] = $line[5]; // speed
565
	    	    $data['heading'] = $line[3]; // heading
566
	    	    $data['latitude'] = $line[1]; // lat
567
	    	    $data['longitude'] = $line[2]; // long
568
	    	    $data['verticalrate'] = $line[15]; // verticale rate
569
	    	    $data['squawk'] = $line[6]; // squawk
570
	    	    $data['aircraft_icao'] = $line[8];
571
	    	    $data['registration'] = $line[9];
572
		    $data['departure_airport_iata'] = $line[11];
573
		    $data['arrival_airport_iata'] = $line[12];
574
	    	    $data['emergency'] = ''; // emergency
575
		    $data['datetime'] = date('Y-m-d H:i:s'); //$line[10]
576
	    	    $data['format_source'] = 'fr24json';
577
    		    $data['id_source'] = $id_source;
578
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
579
		    $SI->add($data);
580
		    unset($data);
581
		}
582
	    }
583
    	    //$last_exec['fr24json'] = time();
584
    	    $last_exec[$id]['last'] = time();
585
    	//} elseif ($value == 'radarvirtueljson' && (time() - $last_exec['radarvirtueljson'] > $globalMinFetch)) {
586
    	} elseif ($value['format'] == 'radarvirtueljson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
587
	    //$buffer = $Common->getData($hosts[$id],'get','','','','','150');
588
	    $buffer = $Common->getData($value['host'],'get','','','','','150');
589
	    //echo $buffer;
590
	    $buffer = str_replace(array("\n","\r"),"",$buffer);
591
	    $buffer = preg_replace('/,"num":(.+)/','}',$buffer);
592
	    $all_data = json_decode($buffer,true);
593
	    if (json_last_error() != JSON_ERROR_NONE) {
594
		die(json_last_error_msg());
595
	    }
596
	    if (isset($all_data['mrkrs'])) {
597
		foreach ($all_data['mrkrs'] as $key => $line) {
598
		    if (isset($line['inf'])) {
599
			$data = array();
600
			$data['hex'] = $line['inf']['ia'];
601
			if (isset($line['inf']['cs'])) $data['ident'] = $line['inf']['cs']; //$line[13]
602
	    		$data['altitude'] = round($line['inf']['al']*3.28084); // altitude
603
	    		if (isset($line['inf']['gs'])) $data['speed'] = round($line['inf']['gs']*0.539957); // speed
604
	    		if (isset($line['inf']['tr'])) $data['heading'] = $line['inf']['tr']; // heading
605
	    		$data['latitude'] = $line['pt'][0]; // lat
606
	    		$data['longitude'] = $line['pt'][1]; // long
607
	    		//if (isset($line['inf']['vs'])) $data['verticalrate'] = $line['inf']['vs']; // verticale rate
608
	    		if (isset($line['inf']['sq'])) $data['squawk'] = $line['inf']['sq']; // squawk
609
	    		//$data['aircraft_icao'] = $line[8];
610
	    		if (isset($line['inf']['rc'])) $data['registration'] = $line['inf']['rc'];
611
			//$data['departure_airport_iata'] = $line[11];
612
			//$data['arrival_airport_iata'] = $line[12];
613
	    		//$data['emergency'] = ''; // emergency
614
			$data['datetime'] = date('Y-m-d H:i:s',$line['inf']['dt']); //$line[10]
615
	    		$data['format_source'] = 'radarvirtueljson';
616
    			$data['id_source'] = $id_source;
617
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
618
			$SI->add($data);
619
			unset($data);
620
		    }
621
		}
622
	    }
623
    	    //$last_exec['radarvirtueljson'] = time();
624
    	    $last_exec[$id]['last'] = time();
625
    	//} elseif ($value == 'pirepsjson' && (time() - $last_exec['pirepsjson'] > $globalMinFetch)) {
626
    	} elseif ($value['format'] == 'pirepsjson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
627
	    //$buffer = $Common->getData($hosts[$id]);
628
	    $buffer = $Common->getData($value['host'].'?'.time());
629
	    $all_data = json_decode(utf8_encode($buffer),true);
630
	    
631
	    if (isset($all_data['pireps'])) {
632
	        foreach ($all_data['pireps'] as $line) {
633
		    $data = array();
634
		    $data['id'] = $line['id'];
635
		    $data['hex'] = substr(str_pad(dechex($line['id']),6,'000000',STR_PAD_LEFT),0,6);
636
		    $data['ident'] = $line['callsign']; // ident
637
		    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid']; // pilot id
638
		    if (isset($line['name'])) $data['pilot_name'] = $line['name']; // pilot name
639
		    if (isset($line['alt'])) $data['altitude'] = $line['alt']; // altitude
640
		    if (isset($line['gs'])) $data['speed'] = $line['gs']; // speed
641
		    if (isset($line['heading'])) $data['heading'] = $line['heading']; // heading
642
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
643
		    $data['latitude'] = $line['lat']; // lat
644
		    $data['longitude'] = $line['lon']; // long
645
		    //$data['verticalrate'] = $line['vrt']; // verticale rate
646
		    //$data['squawk'] = $line['squawk']; // squawk
647
		    //$data['emergency'] = ''; // emergency
648
		    if (isset($line['depicao'])) $data['departure_airport_icao'] = $line['depicao'];
649
		    if (isset($line['deptime'])) $data['departure_airport_time'] = $line['deptime'];
650
		    if (isset($line['arricao'])) $data['arrival_airport_icao'] = $line['arricao'];
651
		    //$data['arrival_airport_time'] = $line['arrtime'];
652
		    if (isset($line['aircraft'])) $data['aircraft_icao'] = $line['aircraft'];
653
		    if (isset($line['transponder'])) $data['squawk'] = $line['transponder'];
654
		    if (isset($line['atis'])) $data['info'] = $line['atis'];
655
		    else $data['info'] = '';
656
		    $data['format_source'] = 'pireps';
657
    		    $data['id_source'] = $id_source;
658
		    $data['datetime'] = date('Y-m-d H:i:s');
659
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
660
		    if ($line['icon'] == 'plane') {
661
			$SI->add($data);
662
		    //    print_r($data);
663
    		    } elseif ($line['icon'] == 'ct') {
664
			$data['info'] = str_replace('^&sect;','<br />',$data['info']);
665
			$data['info'] = str_replace('&amp;sect;','',$data['info']);
666
			$typec = substr($data['ident'],-3);
667
			$data['type'] = '';
668
			if ($typec == 'APP') $data['type'] = 'Approach';
669
			elseif ($typec == 'TWR') $data['type'] = 'Tower';
670
			elseif ($typec == 'OBS') $data['type'] = 'Observer';
671
			elseif ($typec == 'GND') $data['type'] = 'Ground';
672
			elseif ($typec == 'DEL') $data['type'] = 'Delivery';
673
			elseif ($typec == 'DEP') $data['type'] = 'Departure';
674
			elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
675
			elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
676
			else $data['type'] = 'Observer';
677
			echo $ATC->add($data['ident'],'',$data['latitude'],$data['longitude'],'0',$data['info'],$data['datetime'],$data['type'],$data['pilot_id'],$data['pilot_name']);
678
		    }
679
		    unset($data);
680
		}
681
	    }
682
    	    //$last_exec['pirepsjson'] = time();
683
    	    $last_exec[$id]['last'] = time();
684
    	//} elseif ($value == 'phpvmacars' && (time() - $last_exec['phpvmacars'] > $globalMinFetch)) {
685
    	} elseif ($value['format'] == 'phpvmacars' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
686
	    //$buffer = $Common->getData($hosts[$id]);
687
	    if ($globalDebug) echo 'Get Data...'."\n";
688
	    $buffer = $Common->getData($value['host']);
689
	    $all_data = json_decode($buffer,true);
690
	    if ($buffer != '' && is_array($all_data)) {
691
		foreach ($all_data as $line) {
692
	    	    $data = array();
693
	    	    //$data['id'] = $line['id']; // id not usable
694
	    	    if (isset($line['pilotid'])) $data['id'] = $line['pilotid'].$line['flightnum'];
695
	    	    $data['hex'] = substr(str_pad(bin2hex($line['flightnum']),6,'000000',STR_PAD_LEFT),-6); // hex
696
	    	    if (isset($line['pilotname'])) $data['pilot_name'] = $line['pilotname'];
697
	    	    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid'];
698
	    	    $data['ident'] = $line['flightnum']; // ident
699
	    	    $data['altitude'] = $line['alt']; // altitude
700
	    	    $data['speed'] = $line['gs']; // speed
701
	    	    $data['heading'] = $line['heading']; // heading
702
	    	    $data['latitude'] = $line['lat']; // lat
703
	    	    $data['longitude'] = $line['lng']; // long
704
	    	    $data['verticalrate'] = ''; // verticale rate
705
	    	    $data['squawk'] = ''; // squawk
706
	    	    $data['emergency'] = ''; // emergency
707
	    	    //$data['datetime'] = $line['lastupdate'];
708
	    	    $data['last_update'] = $line['lastupdate'];
709
		    $data['datetime'] = date('Y-m-d H:i:s');
710
	    	    $data['departure_airport_icao'] = $line['depicao'];
711
	    	    $data['departure_airport_time'] = $line['deptime'];
712
	    	    $data['arrival_airport_icao'] = $line['arricao'];
713
    		    $data['arrival_airport_time'] = $line['arrtime'];
714
    		    $data['registration'] = $line['aircraft'];
715
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
716
		    if (isset($line['aircraftname'])) {
717
			$line['aircraftname'] = strtoupper($line['aircraftname']);
718
			$line['aircraftname'] = str_replace('BOEING ','B',$line['aircraftname']);
719
	    		$aircraft_data = explode('-',$line['aircraftname']);
720
	    		if (isset($aircraft_data[1]) && strlen($aircraft_data[0]) < 5) $data['aircraft_icao'] = $aircraft_data[0];
721
	    		elseif (isset($aircraft_data[1]) && strlen($aircraft_data[1]) < 5) $data['aircraft_icao'] = $aircraft_data[1];
722
	    		else {
723
	    		    $aircraft_data = explode(' ',$line['aircraftname']);
724
	    		    if (isset($aircraft_data[1])) $data['aircraft_icao'] = $aircraft_data[1];
725
	    		    else $data['aircraft_icao'] = $line['aircraftname'];
726
	    		}
727
	    	    }
728
    		    if (isset($line['route'])) $data['waypoints'] = $line['route'];
729
    		    $data['id_source'] = $id_source;
730
	    	    $data['format_source'] = 'phpvmacars';
731
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
732
		    $SI->add($data);
733
		    unset($data);
734
		}
735
		if ($globalDebug) echo 'No more data...'."\n";
736
		unset($buffer);
737
		unset($all_data);
738
	    }
739
    	    //$last_exec['phpvmacars'] = time();
740
    	    $last_exec[$id]['last'] = time();
741
	//} elseif ($value == 'sbs' || $value == 'tsv' || $value == 'raw' || $value == 'aprs' || $value == 'beast') {
742
	} elseif ($value['format'] == 'sbs' || $value['format'] == 'tsv' || $value['format'] == 'raw' || $value['format'] == 'aprs' || $value['format'] == 'beast' || $value['format'] == 'flightgearmp' || $value['format'] == 'flightgearsp' || $value['format'] == 'acars') {
743
	    if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
744
    	    //$last_exec[$id]['last'] = time();
745
746
	    //$read = array( $sockets[$id] );
747
	    $read = $sockets;
748
	    $write = NULL;
749
	    $e = NULL;
750
	    $n = socket_select($read, $write, $e, $timeout);
751
	    if ($e != NULL) var_dump($e);
752
	    if ($n > 0) {
753
		foreach ($read as $nb => $r) {
754
		    //$value = $formats[$nb];
755
		    $format = $globalSources[$nb]['format'];
756
        	    if ($format == 'sbs' || $format == 'aprs' || $format == 'raw' || $format == 'tsv') {
757
        		$buffer = socket_read($r, 6000,PHP_NORMAL_READ);
758
        	    } else {
759
	    	        $az = socket_recvfrom($r,$buffer,6000,0,$remote_ip,$remote_port);
760
	    	    }
761
        	    //$buffer = socket_read($r, 60000,PHP_NORMAL_READ);
762
        	    //echo $buffer."\n";
763
		    // lets play nice and handle signals such as ctrl-c/kill properly
764
		    //if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
765
		    $error = false;
766
		    //$SI::del();
767
		    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'',$buffer));
768
		    // SBS format is CSV format
769
		    if ($buffer != '') {
770
			$tt[$format] = 0;
771
			if ($format == 'acarssbs3') {
772
			    echo $buffer."\n";
773
			} elseif ($format == 'raw') {
774
			    // AVR format
775
			    $data = $SBS->parse($buffer);
776
			    if (is_array($data)) {
777
				$data['datetime'] = date('Y-m-d H:i:s');
778
				$data['format_source'] = 'raw';
779
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
780
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
781
                                if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
782
                            }
783
                        } elseif ($format == 'flightgearsp') {
784
                    	    //echo $buffer."\n";
785
                    	    if (strlen($buffer) > 5) {
786
				$line = explode(',',$buffer);
787
				$data = array();
788
				//XGPS,2.0947,41.3093,-3047.6953,198.930,0.000,callsign,c172p
789
				$data['hex'] = substr(str_pad(bin2hex($line[6].$line[7]),6,'000000',STR_PAD_LEFT),0,6);
790
				$data['ident'] = $line[6];
791
				$data['aircraft_name'] = $line[7];
792
				$data['longitude'] = $line[1];
793
				$data['latitude'] = $line[2];
794
				$data['altitude'] = round($line[3]*3.28084);
795
				$data['heading'] = round($line[4]);
796
				$data['speed'] = round($line[5]*1.94384);
797
				$data['datetime'] = date('Y-m-d H:i:s');
798
				$data['format_source'] = 'flightgearsp';
799
				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
800
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
801
			    }
802
                        } elseif ($format == 'acars') {
803
                    	    if ($globalDebug) echo 'ACARS : '.$buffer."\n";
804
			    $ACARS->add(trim($buffer));
805
			    socket_sendto($r, "OK " . $buffer , 100 , 0 , $remote_ip , $remote_port);
806
			    $ACARS->deleteLiveAcarsData();
807
			} elseif ($format == 'flightgearmp') {
808
			    if (substr($buffer,0,1) != '#') {
809
				$data = array();
810
				//echo $buffer."\n";
811
				$line = explode(' ',$buffer);
812
				if (count($line) == 11) {
813
				    $userserver = explode('@',$line[0]);
814
				    $data['hex'] = substr(str_pad(bin2hex($line[0]),6,'000000',STR_PAD_LEFT),0,6); // hex
815
				    $data['ident'] = $userserver[0];
816
				    $data['registration'] = $userserver[0];
817
				    $data['latitude'] = $line[4];
818
				    $data['longitude'] = $line[5];
819
				    $data['altitude'] = $line[6];
820
				    $data['datetime'] = date('Y-m-d H:i:s');
821
				    $aircraft_type = $line[10];
822
				    $aircraft_type = preg_split(':/:',$aircraft_type);
823
				    $data['aircraft_name'] = substr(end($aircraft_type),0,-4);
824
				    if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
825
				}
826
			    }
827
			} elseif ($format == 'beast') {
828
			    echo 'Beast Binary format not yet supported. Beast AVR format is supported in alpha state'."\n";
829
			    die;
830
			} elseif ($format == 'tsv' || substr($buffer,0,4) == 'clock') {
831
			    $line = explode("\t", $buffer);
832
			    for($k = 0; $k < count($line); $k=$k+2) {
833
				$key = $line[$k];
834
			        $lined[$key] = $line[$k+1];
835
			    }
836
    			    if (count($lined) > 3) {
837
    				$data['hex'] = $lined['hexid'];
838
    				//$data['datetime'] = date('Y-m-d H:i:s',strtotime($lined['clock']));;
839
    				$data['datetime'] = date('Y-m-d H:i:s');;
840
    				if (isset($lined['ident'])) $data['ident'] = $lined['ident'];
841
    				if (isset($lined['lat'])) $data['latitude'] = $lined['lat'];
842
    				if (isset($lined['lon'])) $data['longitude'] = $lined['lon'];
843
    				if (isset($lined['speed'])) $data['speed'] = $lined['speed'];
844
    				if (isset($lined['squawk'])) $data['squawk'] = $lined['squawk'];
845
    				if (isset($lined['alt'])) $data['altitude'] = $lined['alt'];
846
    				if (isset($lined['heading'])) $data['heading'] = $lined['heading'];
847
    				$data['id_source'] = $id_source;
848
    				$data['format_source'] = 'tsv';
849
    				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
850
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
851
    				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
852
    				unset($lined);
853
    				unset($data);
854
    			    } else $error = true;
855
			} elseif ($format == 'aprs' && $use_aprs) {
856
			    if ($aprs_connect == 0) {
857
				$send = @ socket_send( $r  , $aprs_login , strlen($aprs_login) , 0 );
858
				$aprs_connect = 1;
859
			    }
860
			    if ( $aprs_keep>60 && time() - $aprs_last_tx > $aprs_keep ) {
861
				$aprs_last_tx = time();
862
				$data_aprs = "# Keep alive";
863
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
864
			    }
865
			    //echo 'Connect : '.$aprs_connect.' '.$buffer."\n";
866
			    $buffer = str_replace('APRS <- ','',$buffer);
867
			    $buffer = str_replace('APRS -> ','',$buffer);
868
			    if (substr($buffer,0,1) != '#' && substr($buffer,0,1) != '@' && substr($buffer,0,5) != 'APRS ') {
869
				$line = $APRS->parse($buffer);
870
				if (is_array($line) && isset($line['address']) && $line['address'] != '' && isset($line['ident'])) {
871
				    $data = array();
872
				    //print_r($line);
873
				    $data['hex'] = $line['address'];
874
				    $data['datetime'] = date('Y-m-d H:i:s',$line['timestamp']);
875
				    //$data['datetime'] = date('Y-m-d H:i:s');
876
				    $data['ident'] = $line['ident'];
877
				    $data['latitude'] = $line['latitude'];
878
				    $data['longitude'] = $line['longitude'];
879
				    //$data['verticalrate'] = $line[16];
880
				    if (isset($line['speed'])) $data['speed'] = $line['speed'];
881
				    else $data['speed'] = 0;
882
				    $data['altitude'] = $line['altitude'];
883
				    if (isset($line['course'])) $data['heading'] = $line['course'];
884
				    //else $data['heading'] = 0;
885
				    $data['aircraft_type'] = $line['stealth'];
886
				    if (!isset($globalAPRSarchive) || (isset($globalAPRSarchive) && $globalAPRSarchive == FALSE)) $data['noarchive'] = true;
887
    				    $data['id_source'] = $id_source;
888
				    $data['format_source'] = 'aprs';
889
				    $data['source_name'] = $line['source'];
890
    				    if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
891
				    $currentdate = date('Y-m-d H:i:s');
892
				    $aprsdate = strtotime($data['datetime']);
893
				    // Accept data if time <= system time + 20s
894
				    if ($line['stealth'] == 0 && (strtotime($data['datetime']) <= strtotime($currentdate)+20) && (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude'])))) $send = $SI->add($data);
895
				    else {
896
					if ($line['stealth'] != 0) echo '-------- '.$data['ident'].' : APRS stealth ON => not adding'."\n";
897
					else echo '--------- '.$data['ident'].' : Date APRS : '.$data['datetime'].' - Current date : '.$currentdate.' => not adding future event'."\n";
898
				    }
899
				    unset($data);
900
				} 
901
				//elseif ($line == false && $globalDebug) echo 'Ignored ('.$buffer.")\n";
902
				elseif ($line == true && $globalDebug) echo '!! Failed : '.$buffer."!!\n";
903
			    }
904
			} else {
905
			    $line = explode(',', $buffer);
906
    			    if (count($line) > 20) {
907
    			    	$data['hex'] = $line[4];
908
    				/*
909
    				$data['datetime'] = $line[6].' '.$line[7];
910
    					date_default_timezone_set($globalTimezone);
911
    					$datetime = new DateTime($data['datetime']);
912
    					$datetime->setTimezone(new DateTimeZone('UTC'));
913
    					$data['datetime'] = $datetime->format('Y-m-d H:i:s');
914
    					date_default_timezone_set('UTC');
915
    				*/
916
    				// Force datetime to current UTC datetime
917
    				$data['datetime'] = date('Y-m-d H:i:s');
918
    				$data['ident'] = trim($line[10]);
919
    				$data['latitude'] = $line[14];
920
    				$data['longitude'] = $line[15];
921
    				$data['verticalrate'] = $line[16];
922
    				$data['emergency'] = $line[20];
923
    				$data['speed'] = $line[12];
924
    				$data['squawk'] = $line[17];
925
    				$data['altitude'] = $line[11];
926
    				$data['heading'] = $line[13];
927
    				$data['ground'] = $line[21];
928
    				$data['emergency'] = $line[19];
929
    				$data['format_source'] = 'sbs';
930
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
931
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
932
    				$data['id_source'] = $id_source;
933
    				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $send = $SI->add($data);
934
    				else $error = true;
935
    				unset($data);
936
    			    } else $error = true;
937
			    if ($error) {
938
				if (count($line) > 1 && ($line[0] == 'STA' || $line[0] == 'AIR' || $line[0] == 'SEL' || $line[0] == 'ID' || $line[0] == 'CLK')) { 
939
					if ($globalDebug) echo "Not a message. Ignoring... \n";
940
				} else {
941
					if ($globalDebug) echo "Wrong line format. Ignoring... \n";
942
					if ($globalDebug) {
943
						echo $buffer;
944
						print_r($line);
945
					}
946
					//socket_close($r);
947
					if ($globalDebug) echo "Reconnect after an error...\n";
948
					if ($format == 'aprs') $aprs_connect = 0;
949
					$sourceer[$nb] = $globalSources[$nb];
950
					connect_all($sourceer);
951
					$sourceer = array();
952
				}
953
			    }
954
			}
955
			// Sleep for xxx microseconds
956
			if (isset($globalSBSSleep)) usleep($globalSBSSleep);
957
		    } else {
958
			if ($format == 'flightgearmp') {
959
			    	if ($globalDebug) echo "Reconnect FlightGear MP...";
960
				//@socket_close($r);
961
				sleep($globalMinFetch);
962
				$sourcefg[$nb] = $globalSources[$nb];
963
				connect_all($sourcefg);
964
				$sourcefg = array();
965
				break;
966
				
967
			} elseif ($format != 'acars' && $format != 'flightgearsp') {
968
			    if (isset($tt[$format])) $tt[$format]++;
969
			    else $tt[$format] = 0;
970
			    if ($tt[$format] > 30) {
971
				if ($globalDebug) echo "ERROR : Reconnect ".$format."...";
972
				//@socket_close($r);
973
				sleep(2);
974
				$aprs_connect = 0;
975
				$sourceee[$nb] = $globalSources[$nb];
976
				connect_all($sourceee);
977
				$sourceee = array();
978
				//connect_all($globalSources);
979
				$tt[$format]=0;
980
				break;
981
			    }
982
			}
983
		    }
984
		}
985
	    } else {
986
		$error = socket_strerror(socket_last_error());
987
		if ($globalDebug) echo "ERROR : socket_select give this error ".$error . "\n";
988
		if (($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) || time() - $time >= $timeout) {
989
			if (isset($globalDebug)) echo "Restarting...\n";
990
			// Restart the script if possible
991
			if (is_array($sockets)) {
992
			    if ($globalDebug) echo "Shutdown all sockets...";
993
			    
994
			    foreach ($sockets as $sock) {
995
				@socket_shutdown($sock,2);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
996
				@socket_close($sock);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
997
			    }
998
			    
999
			}
1000
			    if ($globalDebug) echo "Restart all connections...";
1001
			    sleep(2);
1002
			    $time = time();
1003
			    //connect_all($hosts);
1004
			    $aprs_connect = 0;
1005
			    connect_all($globalSources);
1006
1007
		}
1008
	    }
1009
	}
1010
	if ($globalDaemon === false) {
1011
	    if ($globalDebug) echo 'Check all...'."\n";
1012
	    $SI->checkAll();
1013
	}
1014
    }
1015
}
1016
1017
?>
1018