Completed
Push — master ( 56221e...3c95ac )
by Yannick
07:57
created

daemon-spotter.php ➔ connect_all()   F

Complexity

Conditions 69
Paths 214

Size

Total Lines 147
Code Lines 97

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 69
eloc 97
nc 214
nop 1
dl 0
loc 147
rs 3.8133
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
#!/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
if (isset($globalTracker) && $globalTracker) require_once(dirname(__FILE__).'/../require/class.TrackerImport.php');
17
if (isset($globalMarine) && $globalMarine) {
18
    require_once(dirname(__FILE__).'/../require/class.AIS.php');
19
    require_once(dirname(__FILE__).'/../require/class.MarineImport.php');
20
}
21
22
if (!isset($globalDebug)) $globalDebug = FALSE;
23
24
// Check if schema is at latest version
25
$Connection = new Connection();
26
if ($Connection->latest() === false) {
27
    echo "You MUST update to latest schema. Run install/index.php";
28
    exit();
29
}
30
if (PHP_SAPI != 'cli') {
31
    echo "This script MUST be called from console, not a web browser.";
32
//    exit();
33
}
34
35
// This is to be compatible with old version of settings.php
36
if (!isset($globalSources)) {
37
    if (isset($globalSBS1Hosts)) {
38
        //$hosts = $globalSBS1Hosts;
39
        foreach ($globalSBS1Hosts as $host) {
40
	    $globalSources[] = array('host' => $host);
41
    	}
42
    } else {
43
        if (!isset($globalSBS1Host)) {
44
	    echo '$globalSources MUST be defined !';
45
	    die;
46
	}
47
	//$hosts = array($globalSBS1Host.':'.$globalSBS1Port);
48
	$globalSources[] = array('host' => $globalSBS1Host,'port' => $globalSBS1Port);
49
    }
50
}
51
52
$options = getopt('s::',array('source::','server','idsource::'));
53
//if (isset($options['s'])) $hosts = array($options['s']);
54
//elseif (isset($options['source'])) $hosts = array($options['source']);
55
if (isset($options['s'])) {
56
    $globalSources = array();
57
    $globalSources[] = array('host' => $options['s']);
58
} elseif (isset($options['source'])) {
59
    $globalSources = array();
60
    $globalSources[] = array('host' => $options['source']);
61
}
62
if (isset($options['server'])) $globalServer = TRUE;
63
if (isset($options['idsource'])) $id_source = $options['idsource'];
64
else $id_source = 1;
65
if (isset($globalServer) && $globalServer) {
66
    if ($globalDebug) echo "Using Server Mode\n";
67
    $SI=new SpotterServer();
68
/*
69
    require_once(dirname(__FILE__).'/../require/class.APRS.php');
70
    $SI = new adsb2aprs();
71
    $SI->connect();
72
*/
73
} else $SI=new SpotterImport($Connection->db);
74
if (isset($globalTracker) && $globalTracker) $TI = new TrackerImport($Connection->db);
75
if (isset($globalMarine) && $globalMarine) {
76
    $AIS = new AIS();
77
    $MI = new MarineImport($Connection->db);
78
}
79
//$APRS=new APRS($Connection->db);
80
$SBS=new SBS();
81
$ACARS=new ACARS($Connection->db);
82
$Common=new Common();
83
date_default_timezone_set('UTC');
84
//$servertz = system('date +%Z');
85
// signal handler - playing nice with sockets and dump1090
86
if (function_exists('pcntl_fork')) {
87
    pcntl_signal(SIGINT,  function() {
88
        global $sockets;
89
        echo "\n\nctrl-c or kill signal received. Tidying up ... ";
90
        die("Bye!\n");
91
    });
92
    pcntl_signal_dispatch();
93
}
94
95
// let's try and connect
96
if ($globalDebug) echo "Connecting...\n";
97
$use_aprs = false;
98
$aprs_full = false;
99
$reset = 0;
100
101
function connect_all($hosts) {
102
    //global $sockets, $formats, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs;
103
    global $sockets,$httpfeeds, $globalSources, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs, $reset,$context;
104
    $reset++;
105
    if ($globalDebug) echo 'Connect to all...'."\n";
106
    foreach ($hosts as $id => $value) {
107
	$host = $value['host'];
108
	$globalSources[$id]['last_exec'] = 0;
109
	// Here we check type of source(s)
110
	if (filter_var($host,FILTER_VALIDATE_URL) && (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto')) {
111
            if (preg_match('/deltadb.txt$/i',$host)) {
112
        	//$formats[$id] = 'deltadbtxt';
113
        	$globalSources[$id]['format'] = 'deltadbtxt';
114
        	//$last_exec['deltadbtxt'] = 0;
115
        	if ($globalDebug) echo "Connect to deltadb source (".$host.")...\n";
116
            } else if (preg_match('/vatsim-data.txt$/i',$host)) {
117
        	//$formats[$id] = 'vatsimtxt';
118
        	$globalSources[$id]['format'] = 'vatsimtxt';
119
        	//$last_exec['vatsimtxt'] = 0;
120
        	if ($globalDebug) echo "Connect to vatsim source (".$host.")...\n";
121
    	    } else if (preg_match('/aircraftlist.json$/i',$host)) {
122
        	//$formats[$id] = 'aircraftlistjson';
123
        	$globalSources[$id]['format'] = 'aircraftlistjson';
124
        	//$last_exec['aircraftlistjson'] = 0;
125
        	if ($globalDebug) echo "Connect to aircraftlist.json source (".$host.")...\n";
126
    	    } else if (preg_match('/opensky/i',$host)) {
127
        	//$formats[$id] = 'aircraftlistjson';
128
        	$globalSources[$id]['format'] = 'opensky';
129
        	//$last_exec['aircraftlistjson'] = 0;
130
        	if ($globalDebug) echo "Connect to opensky source (".$host.")...\n";
131
    	    } else if (preg_match('/radarvirtuel.com\/file.json$/i',$host)) {
132
        	//$formats[$id] = 'radarvirtueljson';
133
        	$globalSources[$id]['format'] = 'radarvirtueljson';
134
        	//$last_exec['radarvirtueljson'] = 0;
135
        	if ($globalDebug) echo "Connect to radarvirtuel.com/file.json source (".$host.")...\n";
136
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
137
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
138
        	    exit(0);
139
        	}
140
    	    } else if (preg_match('/planeUpdateFAA.php$/i',$host)) {
141
        	//$formats[$id] = 'planeupdatefaa';
142
        	$globalSources[$id]['format'] = 'planeupdatefaa';
143
        	//$last_exec['planeupdatefaa'] = 0;
144
        	if ($globalDebug) echo "Connect to planeUpdateFAA.php source (".$host.")...\n";
145
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
146
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
147
        	    exit(0);
148
        	}
149
            } else if (preg_match('/\/action.php\/acars\/data$/i',$host)) {
150
        	//$formats[$id] = 'phpvmacars';
151
        	$globalSources[$id]['format'] = 'phpvmacars';
152
        	//$last_exec['phpvmacars'] = 0;
153
        	if ($globalDebug) echo "Connect to phpvmacars source (".$host.")...\n";
154
            } else if (preg_match('/VAM-json.php$/i',$host)) {
155
        	//$formats[$id] = 'phpvmacars';
156
        	$globalSources[$id]['format'] = 'vam';
157
        	if ($globalDebug) echo "Connect to Vam source (".$host.")...\n";
158
            } else if (preg_match('/whazzup/i',$host)) {
159
        	//$formats[$id] = 'whazzup';
160
        	$globalSources[$id]['format'] = 'whazzup';
161
        	//$last_exec['whazzup'] = 0;
162
        	if ($globalDebug) echo "Connect to whazzup source (".$host.")...\n";
163
            } else if (preg_match('/recentpireps/i',$host)) {
164
        	//$formats[$id] = 'pirepsjson';
165
        	$globalSources[$id]['format'] = 'pirepsjson';
166
        	//$last_exec['pirepsjson'] = 0;
167
        	if ($globalDebug) echo "Connect to pirepsjson source (".$host.")...\n";
168
            } else if (preg_match(':data.fr24.com/zones/fcgi/feed.js:i',$host)) {
169
        	//$formats[$id] = 'fr24json';
170
        	$globalSources[$id]['format'] = 'fr24json';
171
        	//$last_exec['fr24json'] = 0;
172
        	if ($globalDebug) echo "Connect to fr24 source (".$host.")...\n";
173
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
174
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
175
        	    exit(0);
176
        	}
177
            } else if (preg_match(':myshiptracking.com/:i',$host)) {
178
        	//$formats[$id] = 'fr24json';
179
        	$globalSources[$id]['format'] = 'myshiptracking';
180
        	//$last_exec['fr24json'] = 0;
181
        	if ($globalDebug) echo "Connect to myshiptracking source (".$host.")...\n";
182
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
183
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
184
        	    exit(0);
185
        	}
186
            //} else if (preg_match('/10001/',$host)) {
187
            } else if (preg_match('/10001/',$host) || (isset($globalSources[$id]['port']) && $globalSources[$id]['port'] == '10001')) {
188
        	//$formats[$id] = 'tsv';
189
        	$globalSources[$id]['format'] = 'tsv';
190
        	if ($globalDebug) echo "Connect to tsv source (".$host.")...\n";
191
            }
192
        } elseif (filter_var($host,FILTER_VALIDATE_URL)) {
193
    		if ($globalSources[$id]['format'] == 'aisnmeahttp') {
194
    		    $idf = fopen($globalSources[$id]['host'],'r',false,$context);
195
    		    if ($idf !== false) {
196
    			$httpfeeds[$id] = $idf;
197
        		if ($globalDebug) echo "Connected to ".$globalSources[$id]['format']." source (".$host.")...\n";
198
    		    }
199
    		    elseif ($globalDebug) echo "Can't connect to ".$globalSources[$id]['host']."\n";
200
    		} elseif ($globalDebug) echo "Connect to ".$globalSources[$id]['format']." source (".$host.")...\n";
201
        } elseif (!filter_var($host,FILTER_VALIDATE_URL)) {
202
	    $hostport = explode(':',$host);
203
	    if (isset($hostport[1])) {
204
		$port = $hostport[1];
205
		$hostn = $hostport[0];
206
	    } else {
207
		$port = $globalSources[$id]['port'];
208
		$hostn = $globalSources[$id]['host'];
209
	    }
210
	    $Common = new Common();
211
	    if (!isset($globalSources[$id]['format']) || ($globalSources[$id]['format'] != 'acars' && $globalSources[$id]['format'] != 'flightgearsp')) {
212
        	$s = $Common->create_socket($hostn,$port, $errno, $errstr);
213
    	    } else {
214
        	$s = $Common->create_socket_udp($hostn,$port, $errno, $errstr);
215
	    }
216
	    if ($s) {
217
    	        $sockets[$id] = $s;
218
    	        if (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto') {
219
		    if (preg_match('/aprs/',$hostn) || $port == '10152' || $port == '14580') {
220
			//$formats[$id] = 'aprs';
221
			$globalSources[$id]['format'] = 'aprs';
222
			//$aprs_connect = 0;
223
			//$use_aprs = true;
224
    		    } elseif ($port == '10001') {
225
        		//$formats[$id] = 'tsv';
226
        		$globalSources[$id]['format'] = 'tsv';
227
		    } elseif ($port == '30002') {
228
        		//$formats[$id] = 'raw';
229
        		$globalSources[$id]['format'] = 'raw';
230
		    } elseif ($port == '5001') {
231
        		//$formats[$id] = 'raw';
232
        		$globalSources[$id]['format'] = 'flightgearmp';
233
		    } elseif ($port == '30005') {
234
			// Not yet supported
235
        		//$formats[$id] = 'beast';
236
        		$globalSources[$id]['format'] = 'beast';
237
		    //} else $formats[$id] = 'sbs';
238
		    } else $globalSources[$id]['format'] = 'sbs';
239
		    //if ($globalDebug) echo 'Connection in progress to '.$host.'('.$formats[$id].')....'."\n";
240
		}
241
		if ($globalDebug) echo 'Connection in progress to '.$hostn.':'.$port.' ('.$globalSources[$id]['format'].')....'."\n";
242
            } else {
243
		if ($globalDebug) echo 'Connection failed to '.$hostn.':'.$port.' : '.$errno.' '.$errstr."\n";
244
    	    }
245
        }
246
    }
247
}
248
if (!isset($globalMinFetch)) $globalMinFetch = 15;
249
250
// Initialize all
251
$status = array();
252
$sockets = array();
253
$httpfeeds = array();
254
$formats = array();
255
$last_exec = array();
256
$time = time();
257
if (isset($globalSourcesTimeout)) $timeout = $globalSourcesTimeOut;
258
else if (isset($globalSBS1TimeOut)) $timeout = $globalSBS1TimeOut;
259
else $timeout = 20;
260
$errno = '';
261
$errstr='';
262
263
if (!isset($globalDaemon)) $globalDaemon = TRUE;
264
/* Initiate connections to all the hosts simultaneously */
265
//connect_all($hosts);
266
//connect_all($globalSources);
267
268
if (isset($globalProxy) && $globalProxy) {
269
    $context = stream_context_create(array('http' => array('timeout' => $timeout,'proxy' => $globalProxy,'request_fulluri' => true)));
270
} else {
271
    $context = stream_context_create(array('http' => array('timeout' => $timeout)));
272
}
273
274
// APRS Configuration
275
if (!is_array($globalSources)) {
276
	echo '$globalSources in require/settings.php MUST be an array';
277
	die;
278
}
279
foreach ($globalSources as $key => $source) {
280
    if (!isset($source['format'])) {
281
        $globalSources[$key]['format'] = 'auto';
282
    }
283
}
284
connect_all($globalSources);
285
foreach ($globalSources as $key => $source) {
286
    if (isset($source['format']) && $source['format'] == 'aprs') {
287
	$aprs_connect = 0;
288
	$use_aprs = true;
289
	if (isset($source['port']) && $source['port'] == '10152') $aprs_full = true;
290
	break;
291
    }
292
}
293
294
if ($use_aprs) {
295
	require_once(dirname(__FILE__).'/../require/class.APRS.php');
296
	$APRS=new APRS();
297
	$aprs_connect = 0;
298
	$aprs_keep = 120;
299
	$aprs_last_tx = time();
300
	if (isset($globalAPRSversion)) $aprs_version = $globalAPRSversion;
301
	else $aprs_version = 'FlightAirMap '.str_replace(' ','_',$globalName);
302
	if (isset($globalAPRSssid)) $aprs_ssid = $globalAPRSssid;
303
	else $aprs_ssid = substr('FAM'.strtoupper(str_replace(' ','_',$globalName)),0,8);
304
	if (isset($globalAPRSfilter)) $aprs_filter = $globalAPRSfilter;
305
	else $aprs_filter =  'r/'.$globalCenterLatitude.'/'.$globalCenterLongitude.'/250.0';
306
	if ($aprs_full) $aprs_filter = '';
307
	if (isset($globalAPRSpass)) $aprs_pass = $globalAPRSpass;
308
	else $aprs_pass = '-1';
309
310
	if ($aprs_filter != '') $aprs_login = "user {$aprs_ssid} pass {$aprs_pass} vers {$aprs_version} filter {$aprs_filter}\n";
311
	else $aprs_login = "user {$aprs_ssid} pass {$aprs_pass} vers {$aprs_version}\n";
312
}
313
314
// connected - lets do some work
315
if ($globalDebug) echo "Connected!\n";
316
sleep(1);
317
if ($globalDebug) echo "SCAN MODE \n\n";
318
if (!isset($globalCronEnd)) $globalCronEnd = 60;
319
$endtime = time()+$globalCronEnd;
320
$i = 1;
321
$tt = array();
322
// Delete all ATC
323
if ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM)) {
324
	$ATC=new ATC($Connection->db);
325
}
326
if (!$globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
327
	$ATC->deleteAll();
328
}
329
330
// Infinite loop if daemon, else work for time defined in $globalCronEnd or only one time.
331
while ($i > 0) {
332
    if (!$globalDaemon) $i = $endtime-time();
333
    // Delete old ATC
334
    if ($globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
335
	if ($globalDebug) echo 'Delete old ATC...'."\n";
336
        $ATC->deleteOldATC();
337
    }
338
    
339
    //if (count($last_exec) > 0) {
340
    if (count($last_exec) == count($globalSources)) {
341
	$max = $globalMinFetch;
342
	foreach ($last_exec as $last) {
343
	    if ((time() - $last['last']) < $max) $max = time() - $last['last'];
344
	}
345
	if ($max != $globalMinFetch) {
346
	    if ($globalDebug) echo 'Sleeping...'."\n";
347
	    sleep($globalMinFetch-$max+2);
348
	}
349
    }
350
351
    
352
    //foreach ($formats as $id => $value) {
353
    foreach ($globalSources as $id => $value) {
354
	date_default_timezone_set('UTC');
355
	if (!isset($last_exec[$id]['last'])) $last_exec[$id]['last'] = 0;
356
	if ($value['format'] == 'deltadbtxt' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
357
	    //$buffer = $Common->getData($hosts[$id]);
358
	    $buffer = $Common->getData($value['host']);
359
	    if ($buffer != '') $reset = 0;
360
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
361
	    $buffer = explode('\n',$buffer);
362
	    foreach ($buffer as $line) {
363
    		if ($line != '' && count($line) > 7) {
364
    		    $line = explode(',', $line);
365
	            $data = array();
366
	            $data['hex'] = $line[1]; // hex
367
	            $data['ident'] = $line[2]; // ident
368
	            if (isset($line[3])) $data['altitude'] = $line[3]; // altitude
369
	            if (isset($line[4])) $data['speed'] = $line[4]; // speed
370
	            if (isset($line[5])) $data['heading'] = $line[5]; // heading
371
	            if (isset($line[6])) $data['latitude'] = $line[6]; // lat
372
	            if (isset($line[7])) $data['longitude'] = $line[7]; // long
373
	            $data['verticalrate'] = ''; // vertical rate
374
	            //if (isset($line[9])) $data['squawk'] = $line[9]; // squawk
375
	            $data['emergency'] = ''; // emergency
376
		    $data['datetime'] = date('Y-m-d H:i:s');
377
		    $data['format_source'] = 'deltadbtxt';
378
    		    $data['id_source'] = $id_source;
379
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
380
		    if (isset($value['sourcestats'])) $data['sourcestats'] = $value['sourcestats'];
381
    		    $SI->add($data);
382
		    unset($data);
383
    		}
384
    	    }
385
    	    $last_exec[$id]['last'] = time();
386
	} elseif ($value['format'] == 'aisnmeatxt' && (time() - $last_exec[$id]['last'] > $globalMinFetch*3)) {
387
	    date_default_timezone_set('CET');
388
	    $buffer = $Common->getData(str_replace('{date}',date('Ymd'),$value['host']));
389
	    date_default_timezone_set('UTC');
390
	    if ($buffer != '') $reset = 0;
391
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
392
	    $buffer = explode('\n',$buffer);
393
	    foreach ($buffer as $line) {
394
		if ($line != '') {
395
		    echo "'".$line."'\n";
396
		    $add = false;
397
		    $ais_data = $AIS->parse_line(trim($line));
398
		    $data = array();
399
		    if (isset($ais_data['ident'])) $data['ident'] = $ais_data['ident'];
400
		    if (isset($ais_data['mmsi'])) $data['mmsi'] = $ais_data['mmsi'];
401
		    if (isset($ais_data['speed'])) $data['speed'] = $ais_data['speed'];
402
		    if (isset($ais_data['heading'])) $data['heading'] = $ais_data['heading'];
403
		    if (isset($ais_data['latitude'])) $data['latitude'] = $ais_data['latitude'];
404
		    if (isset($ais_data['longitude'])) $data['longitude'] = $ais_data['longitude'];
405
		    if (isset($ais_data['status'])) $data['status'] = $ais_data['status'];
406
		    if (isset($ais_data['type'])) $data['type'] = $ais_data['type'];
407
		    if (isset($ais_data['imo'])) $data['imo'] = $ais_data['imo'];
408
		    if (isset($ais_data['callsign'])) $data['callsign'] = $ais_data['callsign'];
409
		    if (isset($ais_data['timestamp'])) {
410
			$data['datetime'] = date('Y-m-d H:i:s',$ais_data['timestamp']);
411
			if (!isset($last_exec[$id]['timestamp']) || $ais_data['timestamp'] >= $last_exec[$id]['timestamp']) {
412
			    $last_exec[$id]['timestamp'] = $ais_data['timestamp'];
413
			    $add = true;
414
			}
415
		    } else {
416
			$data['datetime'] = date('Y-m-d H:i:s');
417
			$add = true;
418
		    }
419
		    $data['format_source'] = 'aisnmeatxt';
420
    		    $data['id_source'] = $id_source;
421
		    print_r($data);
422
		    echo 'Add...'."\n";
423
		    if ($add && $ais_data['mmsi_type'] == 'Ship') $MI->add($data);
424
		    unset($data);
425
		}
426
    	    }
427
    	    $last_exec[$id]['last'] = time();
428
	} elseif ($value['format'] == 'aisnmeahttp') {
429
	    $arr = $httpfeeds;
430
	    $w = $e = null;
431
	    
432
	    if (isset($arr[$id])) {
433
	    $nn = stream_select($arr,$w,$e,$timeout);
434
	    if ($nn > 0) {
435
		foreach ($httpfeeds as $feed) {
436
		    $buffer = stream_get_line($feed,2000,"\n");
437
		    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
438
		    $buffer = explode('\n',$buffer);
439
		    foreach ($buffer as $line) {
440
			if ($line != '') {
441
			    $ais_data = $AIS->parse_line(trim($line));
442
			    $data = array();
443
			    if (isset($ais_data['ident'])) $data['ident'] = $ais_data['ident'];
444
			    if (isset($ais_data['mmsi'])) $data['mmsi'] = $ais_data['mmsi'];
445
			    if (isset($ais_data['speed'])) $data['speed'] = $ais_data['speed'];
446
			    if (isset($ais_data['heading'])) $data['heading'] = $ais_data['heading'];
447
			    if (isset($ais_data['latitude'])) $data['latitude'] = $ais_data['latitude'];
448
			    if (isset($ais_data['longitude'])) $data['longitude'] = $ais_data['longitude'];
449
			    if (isset($ais_data['status'])) $data['status'] = $ais_data['status'];
450
			    if (isset($ais_data['type'])) $data['type'] = $ais_data['type'];
451
			    if (isset($ais_data['imo'])) $data['imo'] = $ais_data['imo'];
452
			    if (isset($ais_data['callsign'])) $data['callsign'] = $ais_data['callsign'];
453
			    if (isset($ais_data['destination'])) $data['arrival_code'] = $ais_data['destination'];
454
			    if (isset($ais_data['eta_ts'])) $data['arrival_date'] = date('Y-m-d H:i:s',$ais_data['eta_ts']);
455
			    if (isset($ais_data['timestamp'])) {
456
				$data['datetime'] = date('Y-m-d H:i:s',$ais_data['timestamp']);
457
			    } else {
458
				$data['datetime'] = date('Y-m-d H:i:s');
459
			    }
460
			    $data['format_source'] = 'aisnmeahttp';
461
			    $data['id_source'] = $id_source;
462
			    if ($ais_data['mmsi_type'] == 'Ship') $MI->add($data);
463
			    unset($data);
464
			}
465
		    }
466
		}
467
		}
468
	    }
469
	} elseif ($value['format'] == 'myshiptracking' && (time() - $last_exec[$id]['last'] > $globalMinFetch*3)) {
470
	    $buffer = $Common->getData($value['host'],'get','','','','','20');
471
	    if ($buffer != '') {
472
		//echo $buffer;
473
		$all_data = json_decode($buffer,true);
474
		//print_r($all_data);
475
		if (isset($all_data[0]['DATA'])) {
476
		foreach ($all_data[0]['DATA'] as $line) {
477
		    if ($line != '') {
478
			$data = array();
479
			$data['ident'] = $line['NAME'];
480
			$data['mmsi'] = $line['MMSI'];
481
			$data['speed'] = $line['SOG'];
482
			$data['heading'] = $line['COG'];
483
			$data['latitude'] = $line['LAT'];
484
			$data['longitude'] = $line['LNG'];
485
			//    if (isset($ais_data['type'])) $data['type'] = $ais_data['type'];
486
			$data['imo'] = $line['IMO'];
487
			//$data['arrival_code'] = $ais_data['destination'];
488
			$data['datetime'] = date('Y-m-d H:i:s',$line['T']);
489
			$data['format_source'] = 'myshiptracking';
490
			$data['id_source'] = $id_source;
491
			$MI->add($data);
492
			unset($data);
493
		    }
494
		}
495
		}
496
		
497
	    }
498
    	    $last_exec[$id]['last'] = time();
499
	} elseif ($value['format'] == 'boatbeaconapp' && (time() - $last_exec[$id]['last'] > $globalMinFetch*3)) {
500
	    echo 'Try ?'."\n";
501
	    $buffer = $Common->getData(str_replace('{timestamp}',time(),$value['host']));
502
	    echo $buffer;
503
	    if ($buffer != '') {
504
		//echo $buffer;
505
		$all_data = json_decode($buffer,true);
506
		print_r($all_data);
507
		if (isset($all_data[0]['mmsi'])) {
508
		foreach ($all_data as $line) {
509
		    if ($line != '') {
510
			$data = array();
511
			$data['ident'] = $line['shipname'];
512
			$data['callsign'] = $line['callsign'];
513
			$data['mmsi'] = $line['mmsi'];
514
			$data['speed'] = $line['sog'];
515
			if ($line['heading'] != '511') $data['heading'] = $line['heading'];
516
			$data['latitude'] = $line['latitude'];
517
			$data['longitude'] = $line['longitude'];
518
			$data['type_id'] = $line['shiptype'];
519
			$data['arrival_code'] = $line['destination'];
520
			$data['datetime'] = $line['time'];
521
			$data['format_source'] = 'boatbeaconapp';
522
			$data['id_source'] = $id_source;
523
			$MI->add($data);
524
			unset($data);
525
		    }
526
		}
527
		}
528
		
529
	    }
530
    	    $last_exec[$id]['last'] = time();
531
	} elseif ($value['format'] == 'shipplotter' && (time() - $last_exec[$id]['last'] > $globalMinFetch*3)) {
532
	    echo 'download...';
533
	    $buffer = $Common->getData($value['host'],'post',$value['post'],'','','','','ShipPlotter');
534
	    echo 'done !'."\n";
535
	    if ($buffer != '') $reset = 0;
536
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
537
	    $buffer = explode('\n',$buffer);
538
	    foreach ($buffer as $line) {
539
		if ($line != '') {
540
		    $data = array();
541
		    $data['mmsi'] = (int)substr($line,0,9);
542
		    $data['datetime'] = date('Y-m-d H:i:s',substr($line,10,10));
543
		    //$data['status'] = substr($line,21,2);
544
		    //$data['type'] = substr($line,24,3);
545
		    $data['latitude'] = substr($line,29,9);
546
		    $data['longitude'] = substr($line,41,9);
547
		    $data['speed'] = round(substr($line,51,5));
548
		    //$data['course'] = substr($line,57,5);
549
		    $data['heading'] = round(substr($line,63,3));
550
		    //$data['draft'] = substr($line,67,4);
551
		    //$data['length'] = substr($line,72,3);
552
		    //$data['beam'] = substr($line,76,2);
553
		    $data['ident'] = trim(utf8_encode(substr($line,79,20)));
554
		    //$data['callsign'] = trim(substr($line,100,7);
555
		    //$data['dest'] = substr($line,108,20);
556
		    //$data['etaDate'] = substr($line,129,5);
557
		    //$data['etaTime'] = substr($line,135,5);
558
		    $data['format_source'] = 'shipplotter';
559
    		    $data['id_source'] = $id_source;
560
		    print_r($data);
561
		    echo 'Add...'."\n";
562
		    $MI->add($data);
563
		    unset($data);
564
		}
565
    	    }
566
    	    $last_exec[$id]['last'] = time();
567
	//} elseif (($value == 'whazzup' && (time() - $last_exec['whazzup'] > $globalMinFetch)) || ($value == 'vatsimtxt' && (time() - $last_exec['vatsimtxt'] > $globalMinFetch))) {
568
	} elseif (($value['format'] == 'whazzup' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) || ($value['format'] == 'vatsimtxt' && (time() - $last_exec[$id]['last'] > $globalMinFetch))) {
569
	    //$buffer = $Common->getData($hosts[$id]);
570
	    $buffer = $Common->getData($value['host']);
571
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
572
	    $buffer = explode('\n',$buffer);
573
	    $reset = 0;
574
	    foreach ($buffer as $line) {
575
    		if ($line != '') {
576
    		    $line = explode(':', $line);
577
    		    if (count($line) > 30 && $line[0] != 'callsign') {
578
			$data = array();
579
			if (isset($line[37]) && $line[37] != '') $data['id'] = $value['format'].'-'.$line[1].'-'.$line[0].'-'.$line[37];
580
			else $data['id'] = $value['format'].'-'.$line[1].'-'.$line[0];
581
			$data['pilot_id'] = $line[1];
582
			$data['pilot_name'] = $line[2];
583
			$data['hex'] = str_pad(dechex($Common->str2int($line[1])),6,'000000',STR_PAD_LEFT);
584
			$data['ident'] = $line[0]; // ident
585
			if ($line[7] != '' && $line[7] != 0) $data['altitude'] = $line[7]; // altitude
586
			$data['speed'] = $line[8]; // speed
587
			if (isset($line[45])) $data['heading'] = $line[45]; // heading
588
			elseif (isset($line[38])) $data['heading'] = $line[38]; // heading
589
			$data['latitude'] = $line[5]; // lat
590
	        	$data['longitude'] = $line[6]; // long
591
	        	$data['verticalrate'] = ''; // vertical rate
592
	        	$data['squawk'] = ''; // squawk
593
	        	$data['emergency'] = ''; // emergency
594
	        	$data['waypoints'] = $line[30];
595
			$data['datetime'] = date('Y-m-d H:i:s');
596
			//$data['datetime'] = date('Y-m-d H:i:s',strtotime($line[37]));
597
			//if (isset($line[37])) $data['last_update'] = $line[37];
598
		        $data['departure_airport_icao'] = $line[11];
599
		        $data['departure_airport_time'] = rtrim(chunk_split($line[22],2,':'),':');
600
		        $data['arrival_airport_icao'] = $line[13];
601
			$data['frequency'] = $line[4];
602
			$data['type'] = $line[18];
603
			$data['range'] = $line[19];
604
			if (isset($line[35])) $data['info'] = $line[35];
605
    			$data['id_source'] = $id_source;
606
	    		//$data['arrival_airport_time'] = ;
607
	    		if ($line[9] != '') {
608
	    		    $aircraft_data = explode('/',$line[9]);
609
	    		    if (isset($aircraft_data[1])) {
610
	    			$data['aircraft_icao'] = $aircraft_data[1];
611
	    		    }
612
        		}
613
	    		/*
614
	    		if ($value == 'whazzup') $data['format_source'] = 'whazzup';
615
	    		elseif ($value == 'vatsimtxt') $data['format_source'] = 'vatsimtxt';
616
	    		*/
617
	    		$data['format_source'] = $value['format'];
618
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
619
    			if ($line[3] == 'PILOT') $SI->add($data);
620
			elseif ($line[3] == 'ATC') {
621
				//print_r($data);
622
				$data['info'] = str_replace('^&sect;','<br />',$data['info']);
623
				$data['info'] = str_replace('&amp;sect;','',$data['info']);
624
				$typec = substr($data['ident'],-3);
625
				if ($typec == 'APP') $data['type'] = 'Approach';
626
				elseif ($typec == 'TWR') $data['type'] = 'Tower';
627
				elseif ($typec == 'OBS') $data['type'] = 'Observer';
628
				elseif ($typec == 'GND') $data['type'] = 'Ground';
629
				elseif ($typec == 'DEL') $data['type'] = 'Delivery';
630
				elseif ($typec == 'DEP') $data['type'] = 'Departure';
631
				elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
632
				elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
633
				elseif ($data['type'] == '') $data['type'] = 'Observer';
634
				if (!isset($data['source_name'])) $data['source_name'] = '';
635
				if (isset($ATC)) 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'],$data['format_source'],$data['source_name']);
636
			}
637
    			unset($data);
638
    		    }
639
    		}
640
    	    }
641
    	    //if ($value == 'whazzup') $last_exec['whazzup'] = time();
642
    	    //elseif ($value == 'vatsimtxt') $last_exec['vatsimtxt'] = time();
643
    	    $last_exec[$id]['last'] = time();
644
    	//} elseif ($value == 'aircraftlistjson' && (time() - $last_exec['aircraftlistjson'] > $globalMinFetch)) {
645
    	} elseif ($value['format'] == 'aircraftlistjson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
646
	    $buffer = $Common->getData($value['host'],'get','','','','','20');
647
	    if ($buffer != '') {
648
	    $all_data = json_decode($buffer,true);
649
	    if (isset($all_data['acList'])) {
650
		$reset = 0;
651
		foreach ($all_data['acList'] as $line) {
652
		    $data = array();
653
		    $data['hex'] = $line['Icao']; // hex
654
		    if (isset($line['Call'])) $data['ident'] = $line['Call']; // ident
655
		    if (isset($line['Alt'])) $data['altitude'] = $line['Alt']; // altitude
656
		    if (isset($line['Spd'])) $data['speed'] = $line['Spd']; // speed
657
		    if (isset($line['Trak'])) $data['heading'] = $line['Trak']; // heading
658
		    if (isset($line['Lat'])) $data['latitude'] = $line['Lat']; // lat
659
		    if (isset($line['Long'])) $data['longitude'] = $line['Long']; // long
660
		    //$data['verticalrate'] = $line['']; // verticale rate
661
		    if (isset($line['Sqk'])) $data['squawk'] = $line['Sqk']; // squawk
662
		    $data['emergency'] = ''; // emergency
663
		    if (isset($line['Reg'])) $data['registration'] = $line['Reg'];
664
		    /*
665
		    if (isset($line['PosTime'])) $data['datetime'] = date('Y-m-d H:i:s',$line['PosTime']/1000);
666
		    else $data['datetime'] = date('Y-m-d H:i:s');
667
		    */
668
		    $data['datetime'] = date('Y-m-d H:i:s');
669
		    if (isset($line['Type'])) $data['aircraft_icao'] = $line['Type'];
670
	    	    $data['format_source'] = 'aircraftlistjson';
671
		    $data['id_source'] = $id_source;
672
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
673
		    if (isset($data['datetime'])) $SI->add($data);
674
		    unset($data);
675
		}
676
	    } else {
677
		$reset = 0;
678
		foreach ($all_data as $line) {
679
		    $data = array();
680
		    $data['hex'] = $line['hex']; // hex
681
		    $data['ident'] = $line['flight']; // ident
682
		    $data['altitude'] = $line['altitude']; // altitude
683
		    $data['speed'] = $line['speed']; // speed
684
		    $data['heading'] = $line['track']; // heading
685
		    $data['latitude'] = $line['lat']; // lat
686
		    $data['longitude'] = $line['lon']; // long
687
		    $data['verticalrate'] = $line['vrt']; // verticale rate
688
		    $data['squawk'] = $line['squawk']; // squawk
689
		    $data['emergency'] = ''; // emergency
690
		    $data['datetime'] = date('Y-m-d H:i:s');
691
	    	    $data['format_source'] = 'aircraftlistjson';
692
    		    $data['id_source'] = $id_source;
693
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
694
		    $SI->add($data);
695
		    unset($data);
696
		}
697
	    }
698
	    }
699
    	    //$last_exec['aircraftlistjson'] = time();
700
    	    $last_exec[$id]['last'] = time();
701
    	//} elseif ($value == 'planeupdatefaa' && (time() - $last_exec['planeupdatefaa'] > $globalMinFetch)) {
702
    	} elseif ($value['format'] == 'planeupdatefaa' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
703
	    $buffer = $Common->getData($value['host']);
704
	    $all_data = json_decode($buffer,true);
705
	    if (isset($all_data['planes'])) {
706
		$reset = 0;
707
		foreach ($all_data['planes'] as $key => $line) {
708
		    $data = array();
709
		    $data['hex'] = $key; // hex
710
		    $data['ident'] = $line[3]; // ident
711
		    $data['altitude'] = $line[6]; // altitude
712
		    $data['speed'] = $line[8]; // speed
713
		    $data['heading'] = $line[7]; // heading
714
		    $data['latitude'] = $line[4]; // lat
715
		    $data['longitude'] = $line[5]; // long
716
		    //$data['verticalrate'] = $line[]; // verticale rate
717
		    $data['squawk'] = $line[10]; // squawk
718
		    $data['emergency'] = ''; // emergency
719
		    $data['registration'] = $line[2];
720
		    $data['aircraft_icao'] = $line[0];
721
		    $deparr = explode('-',$line[1]);
722
		    if (count($deparr) == 2) {
723
			$data['departure_airport_icao'] = $deparr[0];
724
			$data['arrival_airport_icao'] = $deparr[1];
725
		    }
726
		    $data['datetime'] = date('Y-m-d H:i:s',$line[9]);
727
	    	    $data['format_source'] = 'planeupdatefaa';
728
    		    $data['id_source'] = $id_source;
729
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
730
		    $SI->add($data);
731
		    unset($data);
732
		}
733
	    }
734
    	    //$last_exec['planeupdatefaa'] = time();
735
    	    $last_exec[$id]['last'] = time();
736
    	} elseif ($value['format'] == 'opensky' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
737
	    $buffer = $Common->getData($value['host']);
738
	    $all_data = json_decode($buffer,true);
739
	    if (isset($all_data['states'])) {
740
		$reset = 0;
741
		foreach ($all_data['states'] as $key => $line) {
742
		    $data = array();
743
		    $data['hex'] = $line[0]; // hex
744
		    $data['ident'] = trim($line[1]); // ident
745
		    $data['altitude'] = round($line[7]*3.28084); // altitude
746
		    $data['speed'] = round($line[9]*1.94384); // speed
747
		    $data['heading'] = round($line[10]); // heading
748
		    $data['latitude'] = $line[5]; // lat
749
		    $data['longitude'] = $line[6]; // long
750
		    $data['verticalrate'] = $line[11]; // verticale rate
751
		    //$data['squawk'] = $line[10]; // squawk
752
		    //$data['emergency'] = ''; // emergency
753
		    //$data['registration'] = $line[2];
754
		    //$data['aircraft_icao'] = $line[0];
755
		    $data['datetime'] = date('Y-m-d H:i:s',$line[3]);
756
	    	    $data['format_source'] = 'opensky';
757
    		    $data['id_source'] = $id_source;
758
		    $SI->add($data);
759
		    unset($data);
760
		}
761
	    }
762
    	    //$last_exec['planeupdatefaa'] = time();
763
    	    $last_exec[$id]['last'] = time();
764
    	//} elseif ($value == 'fr24json' && (time() - $last_exec['fr24json'] > $globalMinFetch)) {
765
    	} elseif ($value['format'] == 'fr24json' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
766
	    //$buffer = $Common->getData($hosts[$id]);
767
	    $buffer = $Common->getData($value['host']);
768
	    $all_data = json_decode($buffer,true);
769
	    if (!empty($all_data)) $reset = 0;
770
	    foreach ($all_data as $key => $line) {
771
		if ($key != 'full_count' && $key != 'version' && $key != 'stats') {
772
		    $data = array();
773
		    $data['hex'] = $line[0];
774
		    $data['ident'] = $line[16]; //$line[13]
775
	    	    $data['altitude'] = $line[4]; // altitude
776
	    	    $data['speed'] = $line[5]; // speed
777
	    	    $data['heading'] = $line[3]; // heading
778
	    	    $data['latitude'] = $line[1]; // lat
779
	    	    $data['longitude'] = $line[2]; // long
780
	    	    $data['verticalrate'] = $line[15]; // verticale rate
781
	    	    $data['squawk'] = $line[6]; // squawk
782
	    	    $data['aircraft_icao'] = $line[8];
783
	    	    $data['registration'] = $line[9];
784
		    $data['departure_airport_iata'] = $line[11];
785
		    $data['arrival_airport_iata'] = $line[12];
786
	    	    $data['emergency'] = ''; // emergency
787
		    $data['datetime'] = date('Y-m-d H:i:s'); //$line[10]
788
	    	    $data['format_source'] = 'fr24json';
789
    		    $data['id_source'] = $id_source;
790
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
791
		    $SI->add($data);
792
		    unset($data);
793
		}
794
	    }
795
    	    //$last_exec['fr24json'] = time();
796
    	    $last_exec[$id]['last'] = time();
797
    	//} elseif ($value == 'radarvirtueljson' && (time() - $last_exec['radarvirtueljson'] > $globalMinFetch)) {
798
    	} elseif ($value['format'] == 'radarvirtueljson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
799
	    //$buffer = $Common->getData($hosts[$id],'get','','','','','150');
800
	    $buffer = $Common->getData($value['host'],'get','','','','','150');
801
	    //echo $buffer;
802
	    $buffer = str_replace(array("\n","\r"),"",$buffer);
803
	    $buffer = preg_replace('/,"num":(.+)/','}',$buffer);
804
	    $all_data = json_decode($buffer,true);
805
	    if (json_last_error() != JSON_ERROR_NONE) {
806
		die(json_last_error_msg());
807
	    }
808
	    if (isset($all_data['mrkrs'])) {
809
		$reset = 0;
810
		foreach ($all_data['mrkrs'] as $key => $line) {
811
		    if (isset($line['inf'])) {
812
			$data = array();
813
			$data['hex'] = $line['inf']['ia'];
814
			if (isset($line['inf']['cs'])) $data['ident'] = $line['inf']['cs']; //$line[13]
815
	    		$data['altitude'] = round($line['inf']['al']*3.28084); // altitude
816
	    		if (isset($line['inf']['gs'])) $data['speed'] = round($line['inf']['gs']*0.539957); // speed
817
	    		if (isset($line['inf']['tr'])) $data['heading'] = $line['inf']['tr']; // heading
818
	    		$data['latitude'] = $line['pt'][0]; // lat
819
	    		$data['longitude'] = $line['pt'][1]; // long
820
	    		//if (isset($line['inf']['vs'])) $data['verticalrate'] = $line['inf']['vs']; // verticale rate
821
	    		if (isset($line['inf']['sq'])) $data['squawk'] = $line['inf']['sq']; // squawk
822
	    		//$data['aircraft_icao'] = $line[8];
823
	    		if (isset($line['inf']['rc'])) $data['registration'] = $line['inf']['rc'];
824
			//$data['departure_airport_iata'] = $line[11];
825
			//$data['arrival_airport_iata'] = $line[12];
826
	    		//$data['emergency'] = ''; // emergency
827
			$data['datetime'] = date('Y-m-d H:i:s',$line['inf']['dt']); //$line[10]
828
	    		$data['format_source'] = 'radarvirtueljson';
829
    			$data['id_source'] = $id_source;
830
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
831
			$SI->add($data);
832
			unset($data);
833
		    }
834
		}
835
	    }
836
    	    //$last_exec['radarvirtueljson'] = time();
837
    	    $last_exec[$id]['last'] = time();
838
    	//} elseif ($value == 'pirepsjson' && (time() - $last_exec['pirepsjson'] > $globalMinFetch)) {
839
    	} elseif ($value['format'] == 'pirepsjson' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
840
	    //$buffer = $Common->getData($hosts[$id]);
841
	    $buffer = $Common->getData($value['host'].'?'.time());
842
	    $all_data = json_decode(utf8_encode($buffer),true);
843
	    
844
	    if (isset($all_data['pireps'])) {
845
		$reset = 0;
846
	        foreach ($all_data['pireps'] as $line) {
847
		    $data = array();
848
		    $data['id'] = $line['id'];
849
		    $data['hex'] = substr(str_pad(dechex($line['id']),6,'000000',STR_PAD_LEFT),0,6);
850
		    $data['ident'] = $line['callsign']; // ident
851
		    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid']; // pilot id
852
		    if (isset($line['name'])) $data['pilot_name'] = $line['name']; // pilot name
853
		    if (isset($line['alt'])) $data['altitude'] = $line['alt']; // altitude
854
		    if (isset($line['gs'])) $data['speed'] = $line['gs']; // speed
855
		    if (isset($line['heading'])) $data['heading'] = $line['heading']; // heading
856
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
857
		    $data['latitude'] = $line['lat']; // lat
858
		    $data['longitude'] = $line['lon']; // long
859
		    //$data['verticalrate'] = $line['vrt']; // verticale rate
860
		    //$data['squawk'] = $line['squawk']; // squawk
861
		    //$data['emergency'] = ''; // emergency
862
		    if (isset($line['depicao'])) $data['departure_airport_icao'] = $line['depicao'];
863
		    if (isset($line['deptime'])) $data['departure_airport_time'] = $line['deptime'];
864
		    if (isset($line['arricao'])) $data['arrival_airport_icao'] = $line['arricao'];
865
		    //$data['arrival_airport_time'] = $line['arrtime'];
866
		    if (isset($line['aircraft'])) $data['aircraft_icao'] = $line['aircraft'];
867
		    if (isset($line['transponder'])) $data['squawk'] = $line['transponder'];
868
		    if (isset($line['atis'])) $data['info'] = $line['atis'];
869
		    else $data['info'] = '';
870
		    $data['format_source'] = 'pireps';
871
    		    $data['id_source'] = $id_source;
872
		    $data['datetime'] = date('Y-m-d H:i:s');
873
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
874
		    if ($line['icon'] == 'plane') {
875
			$SI->add($data);
876
		    //    print_r($data);
877
    		    } elseif ($line['icon'] == 'ct') {
878
			$data['info'] = str_replace('^&sect;','<br />',$data['info']);
879
			$data['info'] = str_replace('&amp;sect;','',$data['info']);
880
			$typec = substr($data['ident'],-3);
881
			$data['type'] = '';
882
			if ($typec == 'APP') $data['type'] = 'Approach';
883
			elseif ($typec == 'TWR') $data['type'] = 'Tower';
884
			elseif ($typec == 'OBS') $data['type'] = 'Observer';
885
			elseif ($typec == 'GND') $data['type'] = 'Ground';
886
			elseif ($typec == 'DEL') $data['type'] = 'Delivery';
887
			elseif ($typec == 'DEP') $data['type'] = 'Departure';
888
			elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
889
			elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
890
			else $data['type'] = 'Observer';
891
			if (isset($ATC)) echo $ATC->add($data['ident'],'',$data['latitude'],$data['longitude'],'0',$data['info'],$data['datetime'],$data['type'],$data['pilot_id'],$data['pilot_name'],$data['format_source']);
892
		    }
893
		    unset($data);
894
		}
895
	    }
896
    	    //$last_exec['pirepsjson'] = time();
897
    	    $last_exec[$id]['last'] = time();
898
    	//} elseif ($value == 'phpvmacars' && (time() - $last_exec['phpvmacars'] > $globalMinFetch)) {
899
    	} elseif ($value['format'] == 'phpvmacars' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
900
	    //$buffer = $Common->getData($hosts[$id]);
901
	    if ($globalDebug) echo 'Get Data...'."\n";
902
	    $buffer = $Common->getData($value['host']);
903
	    $all_data = json_decode($buffer,true);
904
	    if ($buffer != '' && is_array($all_data)) {
905
		$reset = 0;
906
		foreach ($all_data as $line) {
907
	    	    $data = array();
908
	    	    //$data['id'] = $line['id']; // id not usable
909
	    	    if (isset($line['pilotid'])) $data['id'] = $line['pilotid'].$line['flightnum'];
910
	    	    $data['hex'] = substr(str_pad(bin2hex($line['flightnum']),6,'000000',STR_PAD_LEFT),-6); // hex
911
	    	    if (isset($line['pilotname'])) $data['pilot_name'] = $line['pilotname'];
912
	    	    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid'];
913
	    	    $data['ident'] = $line['flightnum']; // ident
914
	    	    $data['altitude'] = $line['alt']; // altitude
915
	    	    $data['speed'] = $line['gs']; // speed
916
	    	    $data['heading'] = $line['heading']; // heading
917
	    	    $data['latitude'] = $line['lat']; // lat
918
	    	    $data['longitude'] = $line['lng']; // long
919
	    	    $data['verticalrate'] = ''; // verticale rate
920
	    	    $data['squawk'] = ''; // squawk
921
	    	    $data['emergency'] = ''; // emergency
922
	    	    //$data['datetime'] = $line['lastupdate'];
923
	    	    $data['last_update'] = $line['lastupdate'];
924
		    $data['datetime'] = date('Y-m-d H:i:s');
925
	    	    $data['departure_airport_icao'] = $line['depicao'];
926
	    	    $data['departure_airport_time'] = $line['deptime'];
927
	    	    $data['arrival_airport_icao'] = $line['arricao'];
928
    		    $data['arrival_airport_time'] = $line['arrtime'];
929
    		    $data['registration'] = $line['aircraft'];
930
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
931
		    if (isset($line['aircraftname'])) {
932
			$line['aircraftname'] = strtoupper($line['aircraftname']);
933
			$line['aircraftname'] = str_replace('BOEING ','B',$line['aircraftname']);
934
	    		$aircraft_data = explode('-',$line['aircraftname']);
935
	    		if (isset($aircraft_data[1]) && strlen($aircraft_data[0]) < 5) $data['aircraft_icao'] = $aircraft_data[0];
936
	    		elseif (isset($aircraft_data[1]) && strlen($aircraft_data[1]) < 5) $data['aircraft_icao'] = $aircraft_data[1];
937
	    		else {
938
	    		    $aircraft_data = explode(' ',$line['aircraftname']);
939
	    		    if (isset($aircraft_data[1])) $data['aircraft_icao'] = $aircraft_data[1];
940
	    		    else $data['aircraft_icao'] = $line['aircraftname'];
941
	    		}
942
	    	    }
943
    		    if (isset($line['route'])) $data['waypoints'] = $line['route'];
944
    		    $data['id_source'] = $id_source;
945
	    	    $data['format_source'] = 'phpvmacars';
946
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
947
		    $SI->add($data);
948
		    unset($data);
949
		}
950
		if ($globalDebug) echo 'No more data...'."\n";
951
		unset($buffer);
952
		unset($all_data);
953
	    }
954
    	    //$last_exec['phpvmacars'] = time();
955
    	    $last_exec[$id]['last'] = time();
956
    	} elseif ($value['format'] == 'vam' && (time() - $last_exec[$id]['last'] > $globalMinFetch)) {
957
	    //$buffer = $Common->getData($hosts[$id]);
958
	    if ($globalDebug) echo 'Get Data...'."\n";
959
	    $buffer = $Common->getData($value['host']);
960
	    $all_data = json_decode($buffer,true);
961
	    if ($buffer != '' && is_array($all_data)) {
962
		$reset = 0;
963
		foreach ($all_data as $line) {
964
	    	    $data = array();
965
	    	    //$data['id'] = $line['id']; // id not usable
966
	    	    $data['id'] = trim($line['flight_id']);
967
	    	    $data['hex'] = substr(str_pad(bin2hex($line['callsign']),6,'000000',STR_PAD_LEFT),-6); // hex
968
	    	    $data['pilot_name'] = $line['pilot_name'];
969
	    	    $data['pilot_id'] = $line['pilot_id'];
970
	    	    $data['ident'] = trim($line['callsign']); // ident
971
	    	    $data['altitude'] = $line['altitude']; // altitude
972
	    	    $data['speed'] = $line['gs']; // speed
973
	    	    $data['heading'] = $line['heading']; // heading
974
	    	    $data['latitude'] = $line['latitude']; // lat
975
	    	    $data['longitude'] = $line['longitude']; // long
976
	    	    $data['verticalrate'] = ''; // verticale rate
977
	    	    $data['squawk'] = ''; // squawk
978
	    	    $data['emergency'] = ''; // emergency
979
	    	    //$data['datetime'] = $line['lastupdate'];
980
	    	    $data['last_update'] = $line['last_update'];
981
		    $data['datetime'] = date('Y-m-d H:i:s');
982
	    	    $data['departure_airport_icao'] = $line['departure'];
983
	    	    //$data['departure_airport_time'] = $line['departure_time'];
984
	    	    $data['arrival_airport_icao'] = $line['arrival'];
985
    		    //$data['arrival_airport_time'] = $line['arrival_time'];
986
    		    //$data['registration'] = $line['aircraft'];
987
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
988
	    	    $data['aircraft_icao'] = $line['plane_type'];
989
    		    $data['id_source'] = $id_source;
990
	    	    $data['format_source'] = 'vam';
991
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
992
		    $SI->add($data);
993
		    unset($data);
994
		}
995
		if ($globalDebug) echo 'No more data...'."\n";
996
		unset($buffer);
997
		unset($all_data);
998
	    }
999
    	    //$last_exec['phpvmacars'] = time();
1000
    	    $last_exec[$id]['last'] = time();
1001
	//} elseif ($value == 'sbs' || $value == 'tsv' || $value == 'raw' || $value == 'aprs' || $value == 'beast') {
1002
	} 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' || $value['format'] == 'acarssbs3' || $value['format'] == 'ais') {
1003
	    if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
1004
    	    //$last_exec[$id]['last'] = time();
1005
1006
	    //$read = array( $sockets[$id] );
1007
	    $read = $sockets;
1008
	    $write = NULL;
1009
	    $e = NULL;
1010
	    $n = socket_select($read, $write, $e, $timeout);
1011
	    if ($e != NULL) var_dump($e);
1012
	    if ($n > 0) {
1013
		$reset = 0;
1014
		foreach ($read as $nb => $r) {
1015
		    //$value = $formats[$nb];
1016
		    $format = $globalSources[$nb]['format'];
1017
        	    if ($format == 'sbs' || $format == 'aprs' || $format == 'raw' || $format == 'tsv' || $format == 'acarssbs3') {
1018
        		$buffer = socket_read($r, 6000,PHP_NORMAL_READ);
1019
        	    } else {
1020
	    	        $az = socket_recvfrom($r,$buffer,6000,0,$remote_ip,$remote_port);
1021
	    	    }
1022
        	    //$buffer = socket_read($r, 60000,PHP_NORMAL_READ);
1023
        	    //echo $buffer."\n";
1024
		    // lets play nice and handle signals such as ctrl-c/kill properly
1025
		    //if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
1026
		    $error = false;
1027
		    //$SI::del();
1028
		    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'',$buffer));
1029
		    // SBS format is CSV format
1030
		    if ($buffer != '') {
1031
			$tt[$format] = 0;
1032
			if ($format == 'acarssbs3') {
1033
                    	    if ($globalDebug) echo 'ACARS : '.$buffer."\n";
1034
			    $ACARS->add(trim($buffer));
1035
			    $ACARS->deleteLiveAcarsData();
1036
			} elseif ($format == 'raw') {
1037
			    // AVR format
1038
			    $data = $SBS->parse($buffer);
1039
			    if (is_array($data)) {
1040
				$data['datetime'] = date('Y-m-d H:i:s');
1041
				$data['format_source'] = 'raw';
1042
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1043
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1044
                                if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
1045
                            }
1046
                        } elseif ($format == 'ais') {
1047
			    $ais_data = $AIS->parse_line(trim($buffer));
1048
			    $data = array();
1049
			    if (isset($ais_data['ident'])) $data['ident'] = $ais_data['ident'];
1050
			    if (isset($ais_data['mmsi'])) $data['mmsi'] = $ais_data['mmsi'];
1051
			    if (isset($ais_data['speed'])) $data['speed'] = $ais_data['speed'];
1052
			    if (isset($ais_data['heading'])) $data['heading'] = $ais_data['heading'];
1053
			    if (isset($ais_data['latitude'])) $data['latitude'] = $ais_data['latitude'];
1054
			    if (isset($ais_data['longitude'])) $data['longitude'] = $ais_data['longitude'];
1055
			    if (isset($ais_data['status'])) $data['status'] = $ais_data['status'];
1056
			    if (isset($ais_data['type'])) $data['type'] = $ais_data['type'];
1057
			    if (isset($ais_data['imo'])) $data['imo'] = $ais_data['imo'];
1058
			    if (isset($ais_data['callsign'])) $data['callsign'] = $ais_data['callsign'];
1059
			    if (isset($ais_data['destination'])) $data['arrival_code'] = $ais_data['destination'];
1060
			    if (isset($ais_data['eta_ts'])) $data['arrival_date'] = date('Y-m-d H:i:s',$ais_data['eta_ts']);
1061
1062
			    if (isset($ais_data['timestamp'])) {
1063
				$data['datetime'] = date('Y-m-d H:i:s',$ais_data['timestamp']);
1064
			    } else {
1065
				$data['datetime'] = date('Y-m-d H:i:s');
1066
			    }
1067
			    $data['format_source'] = 'aisnmea';
1068
    			    $data['id_source'] = $id_source;
1069
			    if (isset($ais_data['mmsi_type']) && $ais_data['mmsi_type'] == 'Ship') $MI->add($data);
1070
			    unset($data);
1071
                        } elseif ($format == 'flightgearsp') {
1072
                    	    //echo $buffer."\n";
1073
                    	    if (strlen($buffer) > 5) {
1074
				$line = explode(',',$buffer);
1075
				$data = array();
1076
				//XGPS,2.0947,41.3093,-3047.6953,198.930,0.000,callsign,c172p
1077
				$data['hex'] = substr(str_pad(bin2hex($line[6].$line[7]),6,'000000',STR_PAD_LEFT),0,6);
1078
				$data['ident'] = $line[6];
1079
				$data['aircraft_name'] = $line[7];
1080
				$data['longitude'] = $line[1];
1081
				$data['latitude'] = $line[2];
1082
				$data['altitude'] = round($line[3]*3.28084);
1083
				$data['heading'] = round($line[4]);
1084
				$data['speed'] = round($line[5]*1.94384);
1085
				$data['datetime'] = date('Y-m-d H:i:s');
1086
				$data['format_source'] = 'flightgearsp';
1087
				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
1088
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
1089
			    }
1090
                        } elseif ($format == 'acars') {
1091
                    	    if ($globalDebug) echo 'ACARS : '.$buffer."\n";
1092
			    $ACARS->add(trim($buffer));
1093
			    socket_sendto($r, "OK " . $buffer , 100 , 0 , $remote_ip , $remote_port);
1094
			    $ACARS->deleteLiveAcarsData();
1095
			} elseif ($format == 'flightgearmp') {
1096
			    if (substr($buffer,0,1) != '#') {
1097
				$data = array();
1098
				//echo $buffer."\n";
1099
				$line = explode(' ',$buffer);
1100
				if (count($line) == 11) {
1101
				    $userserver = explode('@',$line[0]);
1102
				    $data['hex'] = substr(str_pad(bin2hex($line[0]),6,'000000',STR_PAD_LEFT),0,6); // hex
1103
				    $data['ident'] = $userserver[0];
1104
				    $data['registration'] = $userserver[0];
1105
				    $data['latitude'] = $line[4];
1106
				    $data['longitude'] = $line[5];
1107
				    $data['altitude'] = $line[6];
1108
				    $data['datetime'] = date('Y-m-d H:i:s');
1109
				    $aircraft_type = $line[10];
1110
				    $aircraft_type = preg_split(':/:',$aircraft_type);
1111
				    $data['aircraft_name'] = substr(end($aircraft_type),0,-4);
1112
				    if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
1113
				}
1114
			    }
1115
			} elseif ($format == 'beast') {
1116
			    echo 'Beast Binary format not yet supported. Beast AVR format is supported in alpha state'."\n";
1117
			    die;
1118
			} elseif ($format == 'tsv' || substr($buffer,0,4) == 'clock') {
1119
			    $line = explode("\t", $buffer);
1120
			    for($k = 0; $k < count($line); $k=$k+2) {
1121
				$key = $line[$k];
1122
			        $lined[$key] = $line[$k+1];
1123
			    }
1124
    			    if (count($lined) > 3) {
1125
    				$data['hex'] = $lined['hexid'];
1126
    				//$data['datetime'] = date('Y-m-d H:i:s',strtotime($lined['clock']));;
1127
    				$data['datetime'] = date('Y-m-d H:i:s');;
1128
    				if (isset($lined['ident'])) $data['ident'] = $lined['ident'];
1129
    				if (isset($lined['lat'])) $data['latitude'] = $lined['lat'];
1130
    				if (isset($lined['lon'])) $data['longitude'] = $lined['lon'];
1131
    				if (isset($lined['speed'])) $data['speed'] = $lined['speed'];
1132
    				if (isset($lined['squawk'])) $data['squawk'] = $lined['squawk'];
1133
    				if (isset($lined['alt'])) $data['altitude'] = $lined['alt'];
1134
    				if (isset($lined['heading'])) $data['heading'] = $lined['heading'];
1135
    				$data['id_source'] = $id_source;
1136
    				$data['format_source'] = 'tsv';
1137
    				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1138
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1139
    				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $SI->add($data);
1140
    				unset($lined);
1141
    				unset($data);
1142
    			    } else $error = true;
1143
			} elseif ($format == 'aprs' && $use_aprs) {
1144
			    if ($aprs_connect == 0) {
1145
				$send = @ socket_send( $r  , $aprs_login , strlen($aprs_login) , 0 );
1146
				$aprs_connect = 1;
1147
			    }
1148
			    
1149
			    if ( $aprs_keep>60 && time() - $aprs_last_tx > $aprs_keep ) {
1150
				$aprs_last_tx = time();
1151
				$data_aprs = "# Keep alive";
1152
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
1153
			    }
1154
			    
1155
			    //echo 'Connect : '.$aprs_connect.' '.$buffer."\n";
1156
			    //echo 'APRS data : '.$buffer."\n";
1157
			    $buffer = str_replace('APRS <- ','',$buffer);
1158
			    $buffer = str_replace('APRS -> ','',$buffer);
1159
			    //echo $buffer."\n";
1160
			    if (substr($buffer,0,1) != '#' && substr($buffer,0,1) != '@' && substr($buffer,0,5) != 'APRS ') {
1161
				$line = $APRS->parse($buffer);
1162
				//print_r($line);
1163
				//if (is_array($line) && isset($line['address']) && $line['address'] != '' && isset($line['ident'])) {
1164
				if (is_array($line) && isset($line['latitude']) && isset($line['longitude']) && isset($line['ident'])) {
1165
				    $aprs_last_tx = time();
1166
				    $data = array();
1167
				    //print_r($line);
1168
				    if (isset($line['address'])) $data['hex'] = $line['address'];
1169
				    if (isset($line['timestamp'])) $data['datetime'] = date('Y-m-d H:i:s',$line['timestamp']);
1170
				    else $data['datetime'] = date('Y-m-d H:i:s');
1171
				    //$data['datetime'] = date('Y-m-d H:i:s');
1172
				    $data['ident'] = $line['ident'];
1173
				    $data['latitude'] = $line['latitude'];
1174
				    $data['longitude'] = $line['longitude'];
1175
				    //$data['verticalrate'] = $line[16];
1176
				    if (isset($line['speed'])) $data['speed'] = $line['speed'];
1177
				    else $data['speed'] = 0;
1178
				    if (isset($line['altitude'])) $data['altitude'] = $line['altitude'];
1179
				    if (isset($line['comment'])) $data['comment'] = $line['comment'];
1180
				    if (isset($line['symbol'])) $data['type'] = $line['symbol'];
1181
				    if (isset($line['heading'])) $data['heading'] = $line['heading'];
1182
				    //else $data['heading'] = 0;
1183
				    if (isset($line['stealth'])) $data['aircraft_type'] = $line['stealth'];
1184
				    if (!isset($globalAPRSarchive) || (isset($globalAPRSarchive) && $globalAPRSarchive == FALSE)) $data['noarchive'] = true;
1185
    				    $data['id_source'] = $id_source;
1186
				    $data['format_source'] = 'aprs';
1187
				    $data['source_name'] = $line['source'];
1188
				    $data['source_type'] = 'flarm';
1189
    				    if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1190
				    $currentdate = date('Y-m-d H:i:s');
1191
				    $aprsdate = strtotime($data['datetime']);
1192
				    // Accept data if time <= system time + 20s
1193
				    if (isset($line['stealth']) && ($line['stealth'] == 0 || $line['stealth'] == '') && (strtotime($data['datetime']) <= strtotime($currentdate)+20) && (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude'])))) {
1194
					$send = $SI->add($data);
1195
				    } elseif (isset($line['stealth'])) {
1196
					if ($line['stealth'] != 0) echo '-------- '.$data['ident'].' : APRS stealth ON => not adding'."\n";
1197
					else echo '--------- '.$data['ident'].' : Date APRS : '.$data['datetime'].' - Current date : '.$currentdate.' => not adding future event'."\n";
1198
				    //} elseif (isset($line['symbol']) && isset($line['latitude']) && isset($line['longitude']) && ($line['symbol'] == 'Car' || $line['symbol'] == 'Ambulance' || $line['symbol'] == 'Van' || $line['symbol'] == 'Truck' || $line['symbol'] == 'Truck (18 Wheeler)' || $line['symbol'] == 'Motorcycle' || $line['symbol'] == 'Police' || $line['symbol'] == 'Bike' || $line['symbol'] == 'Jogger' || $line['symbol'] == 'Bus' || $line['symbol'] == 'Jeep' || $line['symbol'] == 'Recreational Vehicle' || $line['symbol'] == 'Yacht (Sail)' || $line['symbol'] == 'Ship (Power Boat)' || $line['symbol'] == 'Firetruck' || $line['symbol'] == 'Balloon' || $line['symbol'] == 'Aircraft (small)' || $line['symbol'] == 'Helicopter')) {
1199
				    } elseif (isset($line['symbol']) && isset($line['latitude']) && isset($line['longitude']) && isset($line['speed']) && $line['symbol'] != 'Weather Station' && $line['symbol'] != 'House QTH (VHF)' && $line['symbol'] != 'Dot' && $line['symbol'] != 'TCP-IP' && $line['symbol'] != 'xAPRS (UNIX)' && $line['symbol'] != 'Antenna' && $line['symbol'] != 'Cloudy' && $line['symbol'] != 'HF Gateway' && $line['symbol'] != 'Yagi At QTH' && $line['symbol'] != 'Digi' && $line['symbol'] != '8' && $line['symbol'] != 'MacAPRS') {
1200
					//echo '!!!!!!!!!!!!!!!! SEND !!!!!!!!!!!!!!!!!!!!'."\n";
1201
					if (isset($globalTracker) && $globalTracker) $send = $TI->add($data);
1202
				    }
1203
				    unset($data);
1204
				} 
1205
				elseif (is_array($line) && $globalDebug && isset($line['symbol']) && $line['symbol'] == 'Weather Station') {
1206
					echo '!! Weather Station not yet supported'."\n";
1207
				}
1208
				elseif (is_array($line) && $globalDebug && isset($line['symbol']) && isset($line['latitude']) && isset($line['longitude']) && ($line['symbol'] == 'Car' || $line['symbol'] == 'Ambulance' || $line['symbol'] == 'Van' || $line['symbol'] == 'Truck' || $line['symbol'] == 'Truck (18 Wheeler)' || $line['symbol'] == 'Motorcycle')) {
1209
					echo '!! Car & Trucks not yet supported'."\n";
1210
				}
1211
				//elseif ($line == false && $globalDebug) echo 'Ignored ('.$buffer.")\n";
1212
				//elseif ($line == true && $globalDebug) echo '!! Failed : '.$buffer."!!\n";
1213
			    }
1214
			} else {
1215
			    $line = explode(',', $buffer);
1216
    			    if (count($line) > 20) {
1217
    			    	$data['hex'] = $line[4];
1218
    				/*
1219
    				$data['datetime'] = $line[6].' '.$line[7];
1220
    					date_default_timezone_set($globalTimezone);
1221
    					$datetime = new DateTime($data['datetime']);
1222
    					$datetime->setTimezone(new DateTimeZone('UTC'));
1223
    					$data['datetime'] = $datetime->format('Y-m-d H:i:s');
1224
    					date_default_timezone_set('UTC');
1225
    				*/
1226
    				// Force datetime to current UTC datetime
1227
    				date_default_timezone_set('UTC');
1228
    				$data['datetime'] = date('Y-m-d H:i:s');
1229
    				$data['ident'] = trim($line[10]);
1230
    				$data['latitude'] = $line[14];
1231
    				$data['longitude'] = $line[15];
1232
    				$data['verticalrate'] = $line[16];
1233
    				$data['emergency'] = $line[20];
1234
    				$data['speed'] = $line[12];
1235
    				$data['squawk'] = $line[17];
1236
    				$data['altitude'] = $line[11];
1237
    				$data['heading'] = $line[13];
1238
    				$data['ground'] = $line[21];
1239
    				$data['emergency'] = $line[19];
1240
    				$data['format_source'] = 'sbs';
1241
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1242
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1243
    				$data['id_source'] = $id_source;
1244
    				if (($data['latitude'] == '' && $data['longitude'] == '') || (is_numeric($data['latitude']) && is_numeric($data['longitude']))) $send = $SI->add($data);
1245
    				else $error = true;
1246
    				unset($data);
1247
    			    } else $error = true;
1248
			    if ($error) {
1249
				if (count($line) > 1 && ($line[0] == 'STA' || $line[0] == 'AIR' || $line[0] == 'SEL' || $line[0] == 'ID' || $line[0] == 'CLK')) { 
1250
					if ($globalDebug) echo "Not a message. Ignoring... \n";
1251
				} else {
1252
					if ($globalDebug) echo "Wrong line format. Ignoring... \n";
1253
					if ($globalDebug) {
1254
						echo $buffer;
1255
						print_r($line);
1256
					}
1257
					//socket_close($r);
1258
					if ($globalDebug) echo "Reconnect after an error...\n";
1259
					if ($format == 'aprs') $aprs_connect = 0;
1260
					$sourceer[$nb] = $globalSources[$nb];
1261
					connect_all($sourceer);
1262
					$sourceer = array();
1263
				}
1264
			    }
1265
			}
1266
			// Sleep for xxx microseconds
1267
			if (isset($globalSBSSleep)) usleep($globalSBSSleep);
1268
		    } else {
1269
			if ($format == 'flightgearmp') {
1270
			    	if ($globalDebug) echo "Reconnect FlightGear MP...";
1271
				//@socket_close($r);
1272
				sleep($globalMinFetch);
1273
				$sourcefg[$nb] = $globalSources[$nb];
1274
				connect_all($sourcefg);
1275
				$sourcefg = array();
1276
				break;
1277
				
1278
			} elseif ($format != 'acars' && $format != 'flightgearsp') {
1279
			    if (isset($tt[$format])) $tt[$format]++;
1280
			    else $tt[$format] = 0;
1281
			    if ($tt[$format] > 30) {
1282
				if ($globalDebug) echo "ERROR : Reconnect ".$format."...";
1283
				//@socket_close($r);
1284
				sleep(2);
1285
				$aprs_connect = 0;
1286
				$sourceee[$nb] = $globalSources[$nb];
1287
				connect_all($sourceee);
1288
				$sourceee = array();
1289
				//connect_all($globalSources);
1290
				$tt[$format]=0;
1291
				break;
1292
			    }
1293
			}
1294
		    }
1295
		}
1296
	    } else {
1297
		$error = socket_strerror(socket_last_error());
1298
		if (($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY && $error != 'Success') || (time() - $time >= $timeout && $error != 'Success')) {
1299
			if ($globalDebug) echo "ERROR : socket_select give this error ".$error . "\n";
1300
			if (isset($globalDebug)) echo "Restarting...\n";
1301
			// Restart the script if possible
1302
			if (is_array($sockets)) {
1303
			    if ($globalDebug) echo "Shutdown all sockets...";
1304
			    
1305
			    foreach ($sockets as $sock) {
1306
				@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...
1307
				@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...
1308
			    }
1309
			    
1310
			}
1311
			if ($globalDebug) echo "Restart all connections...";
1312
			sleep(2);
1313
			$time = time();
1314
			//connect_all($hosts);
1315
			$aprs_connect = 0;
1316
			if ($reset > 40) exit('Too many attempts...');
1317
			connect_all($globalSources);
1318
		}
1319
	    }
1320
	}
1321
	if ($globalDaemon === false) {
1322
	    if ($globalDebug) echo 'Check all...'."\n";
1323
	    $SI->checkAll();
1324
	}
1325
    }
1326
}
1327
1328
?>
1329