Completed
Push — master ( cc50d0...0f8c33 )
by Yannick
09:46
created

daemon-spotter.php ➔ connect_all()   F

Complexity

Conditions 62
Paths 206

Size

Total Lines 137
Code Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

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