Completed
Push — master ( ed645a...c2dc56 )
by Yannick
07:30
created

daemon-spotter.php ➔ create_socket_udp()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 11

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 2
nop 4
dl 13
loc 13
rs 9.2
c 0
b 0
f 0
1
#!/usr/bin/php
2
<?php
3
/**
4
* This script is used to retrieve message from SBS source like Dump1090, Radarcape,.. or from phpvms, wazzup files,...
5
* This script can be used as cron job with $globalDaemon = FALSE
6
*/
7
8
require_once(dirname(__FILE__).'/../require/class.SpotterImport.php');
9
require_once(dirname(__FILE__).'/../require/class.SpotterServer.php');
10
//require_once(dirname(__FILE__).'/../require/class.APRS.php');
11
require_once(dirname(__FILE__).'/../require/class.ATC.php');
12
require_once(dirname(__FILE__).'/../require/class.ACARS.php');
13
require_once(dirname(__FILE__).'/../require/class.SBS.php');
14
require_once(dirname(__FILE__).'/../require/class.Connection.php');
15
require_once(dirname(__FILE__).'/../require/class.Common.php');
16
17
if (!isset($globalDebug)) $globalDebug = FALSE;
18
19
// Check if schema is at latest version
20
$Connection = new Connection();
21
if ($Connection->latest() === false) {
22
    echo "You MUST update to latest schema. Run install/index.php";
23
    exit();
24
}
25
26
27
// This is to be compatible with old version of settings.php
28
if (!isset($globalSources)) {
29
    if (isset($globalSBS1Hosts)) {
30
        //$hosts = $globalSBS1Hosts;
31
        foreach ($globalSBS1Hosts as $host) {
32
	    $globalSources[] = array('host' => $host);
33
    	}
34
    } else {
35
        if (!isset($globalSBS1Host)) {
36
	    echo '$globalSources MUST be defined !';
37
	    die;
38
	}
39
	//$hosts = array($globalSBS1Host.':'.$globalSBS1Port);
40
	$globalSources[] = array('host' => $globalSBS1Host.':'.$globalSBS1Port);
41
    }
42
}
43
44
$options = getopt('s::',array('source::','server','idsource::'));
45
//if (isset($options['s'])) $hosts = array($options['s']);
46
//elseif (isset($options['source'])) $hosts = array($options['source']);
47
if (isset($options['s'])) $globalSources[] = array('host' => $options['s']);
48
elseif (isset($options['source'])) $globalSources[] = array('host' => $options['source']);
49
if (isset($options['server'])) $globalServer = TRUE;
50
if (isset($options['idsource'])) $id_source = $options['idsource'];
51
else $id_source = 1;
52
if (isset($globalServer) && $globalServer) {
53
    if ($globalDebug) echo "Using Server Mode\n";
54
    $SI=new SpotterServer();
55
} else $SI=new SpotterImport($Connection->db);
56
//$APRS=new APRS($Connection->db);
57
$SBS=new SBS($Connection->db);
0 ignored issues
show
Unused Code introduced by
The call to SBS::__construct() has too many arguments starting with $Connection->db.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
58
$ACARS=new ACARS($Connection->db);
59
$Common=new Common();
60
date_default_timezone_set('UTC');
61
//$servertz = system('date +%Z');
62
// signal handler - playing nice with sockets and dump1090
63
if (function_exists('pcntl_fork')) {
64
    pcntl_signal(SIGINT,  function($signo) {
0 ignored issues
show
Unused Code introduced by
The parameter $signo is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
65
        global $sockets;
66
        echo "\n\nctrl-c or kill signal received. Tidying up ... ";
67
        die("Bye!\n");
68
    });
69
    pcntl_signal_dispatch();
70
}
71
72
// let's try and connect
73
if ($globalDebug) echo "Connecting...\n";
74
$use_aprs = false;
75
76 View Code Duplication
function create_socket($host, $port, &$errno, &$errstr) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
    $ip = gethostbyname($host);
78
    $s = socket_create(AF_INET, SOCK_STREAM, 0);
79
    $r = @socket_connect($s, $ip, $port);
80
    if (!socket_set_nonblock($s)) echo "Unable to set nonblock on socket\n";
81
    if ($r || socket_last_error() == 114 || socket_last_error() == 115) {
82
        return $s;
83
    }
84
    $errno = socket_last_error($s);
85
    $errstr = socket_strerror($errno);
86
    socket_close($s);
87
    return false;
88
}
89
90 View Code Duplication
function create_socket_udp($host, $port, &$errno, &$errstr) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
    echo "UDP !!";
92
    $ip = gethostbyname($host);
93
    $s = socket_create(AF_INET, SOCK_DGRAM, 0);
94
    $r = @socket_bind($s, $ip, $port);
95
    if ($r || socket_last_error() == 114 || socket_last_error() == 115) {
96
        return $s;
97
    }
98
    $errno = socket_last_error($s);
99
    $errstr = socket_strerror($errno);
100
    socket_close($s);
101
    return false;
102
}
103
104
function connect_all($hosts) {
105
    //global $sockets, $formats, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs;
106
    global $sockets, $globalSources, $globalDebug,$aprs_connect,$last_exec, $globalSourcesRights, $use_aprs;
107
    foreach ($hosts as $id => $value) {
108
	$host = $value['host'];
109
	$globalSources[$id]['last_exec'] = 0;
110
	// Here we check type of source(s)
111
	if (filter_var($host,FILTER_VALIDATE_URL) && (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto')) {
112
            if (preg_match('/deltadb.txt$/i',$host)) {
113
        	//$formats[$id] = 'deltadbtxt';
114
        	$globalSources[$id]['format'] = 'deltadbtxt';
115
        	//$last_exec['deltadbtxt'] = 0;
116
        	if ($globalDebug) echo "Connect to deltadb source (".$host.")...\n";
117
            } else if (preg_match('/vatsim-data.txt$/i',$host)) {
118
        	//$formats[$id] = 'vatsimtxt';
119
        	$globalSources[$id]['format'] = 'vatsimtxt';
120
        	//$last_exec['vatsimtxt'] = 0;
121
        	if ($globalDebug) echo "Connect to vatsim source (".$host.")...\n";
122
    	    } else if (preg_match('/aircraftlist.json$/i',$host)) {
123
        	//$formats[$id] = 'aircraftlistjson';
124
        	$$globalSources[$id]['format'] = 'aircraftlistjson';
125
        	//$last_exec['aircraftlistjson'] = 0;
126
        	if ($globalDebug) echo "Connect to aircraftlist.json source (".$host.")...\n";
127
    	    } else if (preg_match('/radarvirtuel.com\/file.json$/i',$host)) {
128
        	//$formats[$id] = 'radarvirtueljson';
129
        	$globalSources[$id]['format'] = 'radarvirtueljson';
130
        	//$last_exec['radarvirtueljson'] = 0;
131
        	if ($globalDebug) echo "Connect to radarvirtuel.com/file.json source (".$host.")...\n";
132 View Code Duplication
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
134
        	    exit(0);
135
        	}
136
    	    } else if (preg_match('/planeUpdateFAA.php$/i',$host)) {
137
        	//$formats[$id] = 'planeupdatefaa';
138
        	$globalSources[$id]['format'] = 'planeupdatefaa';
139
        	//$last_exec['planeupdatefaa'] = 0;
140
        	if ($globalDebug) echo "Connect to planeUpdateFAA.php source (".$host.")...\n";
141 View Code Duplication
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
142
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
143
        	    exit(0);
144
        	}
145
            } else if (preg_match('/\/action.php\/acars\/data$/i',$host)) {
146
        	//$formats[$id] = 'phpvmacars';
147
        	$globalSources[$id]['format'] = 'phpvmacars';
148
        	//$last_exec['phpvmacars'] = 0;
149
        	if ($globalDebug) echo "Connect to phpvmacars source (".$host.")...\n";
150
            } else if (preg_match('/whazzup/i',$host)) {
151
        	//$formats[$id] = 'whazzup';
152
        	$globalSources[$id]['format'] = 'whazzup';
153
        	//$last_exec['whazzup'] = 0;
154
        	if ($globalDebug) echo "Connect to whazzup source (".$host.")...\n";
155
            } else if (preg_match('/recentpireps/i',$host)) {
156
        	//$formats[$id] = 'pirepsjson';
157
        	$globalSources[$id]['format'] = 'pirepsjson';
158
        	//$last_exec['pirepsjson'] = 0;
159
        	if ($globalDebug) echo "Connect to pirepsjson source (".$host.")...\n";
160
            } else if (preg_match(':data.fr24.com/zones/fcgi/feed.js:i',$host)) {
161
        	//$formats[$id] = 'fr24json';
162
        	$globalSources[$id]['format'] = 'fr24json';
163
        	//$last_exec['fr24json'] = 0;
164
        	if ($globalDebug) echo "Connect to fr24 source (".$host.")...\n";
165 View Code Duplication
        	if (!isset($globalSourcesRights) || (isset($globalSourcesRights) && !$globalSourcesRights)) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
        	    echo '!!! You MUST set $globalSourcesRights = TRUE in settings.php if you have the right to use this feed !!!'."\n";
167
        	    exit(0);
168
        	}
169
            //} else if (preg_match('/10001/',$host)) {
170
            } else if (preg_match('/10001/',$host) || $globalSources[$id]['port'] == '10001') {
171
        	//$formats[$id] = 'tsv';
172
        	$globalSources[$id]['format'] = 'tsv';
173
        	if ($globalDebug) echo "Connect to tsv source (".$host.")...\n";
174
            }
175
        } elseif (filter_var($host,FILTER_VALIDATE_URL)) {
176
        	if ($globalDebug) echo "Connect to ".$globalSources[$id]['format']." source (".$host.")...\n";
177
        } elseif (!filter_var($host,FILTER_VALIDATE_URL)) {
178
	    $hostport = explode(':',$host);
179
	    if (isset($hostport[1])) $port = $hostport[1];
180
	    else $port = $globalSources[$id]['port'];
181
	    if (!isset($globalSources[$id]['format']) || ($globalSources[$id]['format'] != 'acars' && $globalSources[$id]['format'] != 'flightgearsp')) {
182
        	$s = create_socket($host,$port, $errno, $errstr);
183
    	    } else {
184
        	$s = create_socket_udp($host,$port, $errno, $errstr);
185
	    }
186
	    if ($s) {
187
    	        $sockets[$id] = $s;
188
    	        if (!isset($globalSources[$id]['format']) || strtolower($globalSources[$id]['format']) == 'auto') {
189
		    if (preg_match('/aprs/',$host)) {
190
			//$formats[$id] = 'aprs';
191
			$globalSources[$id]['format'] = 'aprs';
192
			//$aprs_connect = 0;
193
			//$use_aprs = true;
194
    		    } elseif ($port == '10001') {
195
        		//$formats[$id] = 'tsv';
196
        		$globalSources[$id]['format'] = 'tsv';
197
		    } elseif ($port == '30002') {
198
        		//$formats[$id] = 'raw';
199
        		$globalSources[$id]['format'] = 'raw';
200
		    } elseif ($port == '5001') {
201
        		//$formats[$id] = 'raw';
202
        		$globalSources[$id]['format'] = 'flightgearmp';
203
		    } elseif ($port == '30005') {
204
			// Not yet supported
205
        		//$formats[$id] = 'beast';
206
        		$globalSources[$id]['format'] = 'beast';
207
		    //} else $formats[$id] = 'sbs';
208
		    } else $globalSources[$id]['format'] = 'sbs';
209
		    //if ($globalDebug) echo 'Connection in progress to '.$host.'('.$formats[$id].')....'."\n";
210
		}
211 View Code Duplication
		if ($globalDebug) echo 'Connection in progress to '.$host.':'.$port.' ('.$globalSources[$id]['format'].')....'."\n";
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212 View Code Duplication
            } else {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
		if ($globalDebug) echo 'Connection failed to '.$host.':'.$port.' : '.$errno.' '.$errstr."\n";
214
    	    }
215
        }
216
    }
217
}
218
if (!isset($globalMinFetch)) $globalMinFetch = 0;
219
220
// Initialize all
221
$status = array();
222
$sockets = array();
223
$formats = array();
224
$last_exec = array();
225
$time = time();
226
if (isset($globalSourcesTimeout)) $timeout = $globalSourcesTimeOut;
227
else if (isset($globalSBS1TimeOut)) $timeout = $globalSBS1TimeOut;
228
else $timeout = 20;
229
$errno = '';
230
$errstr='';
231
232
if (!isset($globalDaemon)) $globalDaemon = TRUE;
233
/* Initiate connections to all the hosts simultaneously */
234
//connect_all($hosts);
235
connect_all($globalSources);
236
237
// APRS Configuration
238
foreach ($globalSources as $key => $source) {
0 ignored issues
show
Bug introduced by
The expression $globalSources of type null is not traversable.
Loading history...
239
    if (isset($source['format']) && $source['format'] == 'aprs') {
240
	$aprs_connect = 0;
241
	$use_aprs = true;
242
	break;
243
    } elseif (!isset($source['format'])) {
244
        $globalSources[$key]['format'] = 'auto';
245
    }
246
}
247
248
if ($use_aprs) {
249
	require_once(dirname(__FILE__).'/../require/class.APRS.php');
250
	$APRS=new APRS($Connection->db);
0 ignored issues
show
Unused Code introduced by
The call to aprs::__construct() has too many arguments starting with $Connection->db.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
251
	$aprs_connect = 0;
252
	$aprs_keep = 240;
253
	$aprs_last_tx = time();
254
	if (isset($globalAPRSversion)) $aprs_version = $globalAPRSversion;
255
	else $aprs_version = $globalName.' using FlightAirMap';
256
	//else $aprs_version = 'Perl Example App';
257
	if (isset($globalAPRSssid)) $aprs_ssid = $globalAPRSssid;
258
	else $aprs_ssid = 'FAM';
259
	//else $aprs_ssid = 'PerlEx';
260
	if (isset($globalAPRSfilter)) $aprs_filter = $globalAPRSfilter;
261
	else $aprs_filter =  'r/'.$globalCenterLatitude.'/'.$globalCenterLongitude.'/250.0';
262
	if ($aprs_filter != '') $aprs_login = "user {$aprs_ssid} appid {$aprs_version} filter {$aprs_filter}\n";
263
	else $aprs_login = "user {$aprs_ssid} appid {$aprs_version}\n";
264
}
265
266
// connected - lets do some work
267
if ($globalDebug) echo "Connected!\n";
268
sleep(1);
269
if ($globalDebug) echo "SCAN MODE \n\n";
270
if (!isset($globalCronEnd)) $globalCronEnd = 60;
271
$endtime = time()+$globalCronEnd;
272
$i = 1;
273
$tt = 0;
274
275
// Delete all ATC
276
if ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM)) {
277
	$ATC=new ATC($Connection->db);
278
}
279
if (!$globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
280
	$ATC->deleteAll();
281
}
282
283
// Infinite loop if daemon, else work for time defined in $globalCronEnd or only one time.
284
while ($i > 0) {
285
    if (!$globalDaemon) $i = $endtime-time();
286
    // Delete old ATC
287
    if ($globalDaemon && ((isset($globalIVAO) && $globalIVAO) || (isset($globalVATSIM) && $globalVATSIM))) {
288
        $ATC->deleteOldATC();
289
    }
290
    //foreach ($formats as $id => $value) {
291
    foreach ($globalSources as $id => $value) {
0 ignored issues
show
Bug introduced by
The expression $globalSources of type null is not traversable.
Loading history...
292
	//if ($value == 'deltadbtxt' && (time() - $last_exec['deltadbtxt'] > $globalMinFetch)) {
293
	if ($value['format'] == 'deltadbtxt' && (time() - $value['last_exec'] > $globalMinFetch)) {
294
	    //$buffer = $Common->getData($hosts[$id]);
295
	    $buffer = $Common->getData($value['host']);
296
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
297
	    $buffer = explode('\n',$buffer);
298
	    foreach ($buffer as $line) {
299
    		if ($line != '') {
300
    		    $line = explode(',', $line);
301
	            $data = array();
302
	            $data['hex'] = $line[1]; // hex
303
	            $data['ident'] = $line[2]; // ident
304
	            $data['altitude'] = $line[3]; // altitude
305
	            $data['speed'] = $line[4]; // speed
306
	            $data['heading'] = $line[5]; // heading
307
	            $data['latitude'] = $line[6]; // lat
308
	            $data['longitude'] = $line[7]; // long
309
	            $data['verticalrate'] = ''; // vertical rate
310
	            $data['squawk'] = ''; // squawk
311
	            $data['emergency'] = ''; // emergency
312
		    $data['datetime'] = date('Y-m-d H:i:s');
313
		    $data['format_source'] = 'deltadbtxt';
314
    		    $data['id_source'] = $id_source;
315 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
316
		    if (isset($value['sourcestats'])) $data['sourcestats'] = $value['sourcestats'];
317
    		    $SI->add($data);
318
		    unset($data);
319
    		}
320
    	    }
321
    	    $value['last_exec'] = time();
322
	//} elseif (($value == 'whazzup' && (time() - $last_exec['whazzup'] > $globalMinFetch)) || ($value == 'vatsimtxt' && (time() - $last_exec['vatsimtxt'] > $globalMinFetch))) {
323
	} elseif (($value['format'] == 'whazzup' && (time() - $value['last_exec'] > $globalMinFetch)) || ($value['format'] == 'vatsimtxt' && (time() - $value['last_exec'] > $globalMinFetch))) {
324
	    //$buffer = $Common->getData($hosts[$id]);
325
	    $buffer = $Common->getData($value['host']);
326
    	    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'\n',$buffer));
327
	    $buffer = explode('\n',$buffer);
328
	    foreach ($buffer as $line) {
329
    		if ($line != '') {
330
    		    $line = explode(':', $line);
331
    		    if (count($line) > 30 && $line[0] != 'callsign') {
332
			$data = array();
333
			$data['id'] = $line[1].'-'.$line[0];
334
			$data['pilot_id'] = $line[1];
335
			$data['pilot_name'] = $line[2];
336
			$data['hex'] = str_pad(dechex($line[1]),6,'000000',STR_PAD_LEFT);
337
			$data['ident'] = $line[0]; // ident
338
			if ($line[7] != '' && $line[7] != 0) $data['altitude'] = $line[7]; // altitude
339
			$data['speed'] = $line[8]; // speed
340
			if (isset($line[45])) $data['heading'] = $line[45]; // heading
341
			elseif (isset($line[38])) $data['heading'] = $line[38]; // heading
342
			$data['latitude'] = $line[5]; // lat
343
	        	$data['longitude'] = $line[6]; // long
344
	        	$data['verticalrate'] = ''; // vertical rate
345
	        	$data['squawk'] = ''; // squawk
346
	        	$data['emergency'] = ''; // emergency
347
	        	$data['waypoints'] = $line[30];
348
			$data['datetime'] = date('Y-m-d H:i:s');
349
			//$data['datetime'] = date('Y-m-d H:i:s',strtotime($line[37]));
350
		        $data['departure_airport_icao'] = $line[11];
351
		        $data['departure_airport_time'] = rtrim(chunk_split($line[22],2,':'),':');
352
		        $data['arrival_airport_icao'] = $line[13];
353
			$data['frequency'] = $line[4];
354
			$data['type'] = $line[18];
355
			$data['range'] = $line[19];
356
			if (isset($line[35])) $data['info'] = $line[35];
357
    			$data['id_source'] = $id_source;
358
	    		//$data['arrival_airport_time'] = ;
359 View Code Duplication
	    		if ($line[9] != '') {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
360
	    		    $aircraft_data = explode('/',$line[9]);
361
	    		    if (isset($aircraft_data[1])) {
362
	    			$data['aircraft_icao'] = $aircraft_data[1];
363
	    		    }
364
        		}
365
	    		/*
366
	    		if ($value == 'whazzup') $data['format_source'] = 'whazzup';
367
	    		elseif ($value == 'vatsimtxt') $data['format_source'] = 'vatsimtxt';
368
	    		*/
369
	    		$data['format_source'] = $value['format'];
370 View Code Duplication
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
371
    			if ($line[3] == 'PILOT') $SI->add($data);
372
			elseif ($line[3] == 'ATC') {
373
				//print_r($data);
374
				$data['info'] = str_replace('^&sect;','<br />',$data['info']);
375
				$data['info'] = str_replace('&amp;sect;','',$data['info']);
376
				$typec = substr($data['ident'],-3);
377 View Code Duplication
				if ($typec == 'APP') $data['type'] = 'Approach';
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
378
				elseif ($typec == 'TWR') $data['type'] = 'Tower';
379
				elseif ($typec == 'OBS') $data['type'] = 'Observer';
380
				elseif ($typec == 'GND') $data['type'] = 'Ground';
381
				elseif ($typec == 'DEL') $data['type'] = 'Delivery';
382
				elseif ($typec == 'DEP') $data['type'] = 'Departure';
383
				elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
384
				elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
385
				elseif ($data['type'] == '') $data['type'] = 'Observer';
386
				
387
				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']);
388
			}
389
    			unset($data);
390
    		    }
391
    		}
392
    	    }
393
    	    //if ($value == 'whazzup') $last_exec['whazzup'] = time();
394
    	    //elseif ($value == 'vatsimtxt') $last_exec['vatsimtxt'] = time();
395
    	    $value['last_exec'] = time();
396
    	//} elseif ($value == 'aircraftlistjson' && (time() - $last_exec['aircraftlistjson'] > $globalMinFetch)) {
397
    	} elseif ($value['format'] == 'aircraftlistjson' && (time() - $value['last_exec'] > $globalMinFetch)) {
398
	    $buffer = $Common->getData($value['host'],'get','','','','','20');
399
	    if ($buffer != '') {
400
	    $all_data = json_decode($buffer,true);
401
	    if (isset($all_data['acList'])) {
402
		foreach ($all_data['acList'] as $line) {
403
		    $data = array();
404
		    $data['hex'] = $line['Icao']; // hex
405
		    if (isset($line['Call'])) $data['ident'] = $line['Call']; // ident
406
		    if (isset($line['Alt'])) $data['altitude'] = $line['Alt']; // altitude
407
		    if (isset($line['Spd'])) $data['speed'] = $line['Spd']; // speed
408
		    if (isset($line['Trak'])) $data['heading'] = $line['Trak']; // heading
409
		    if (isset($line['Lat'])) $data['latitude'] = $line['Lat']; // lat
410
		    if (isset($line['Long'])) $data['longitude'] = $line['Long']; // long
411
		    //$data['verticalrate'] = $line['']; // verticale rate
412
		    if (isset($line['Sqk'])) $data['squawk'] = $line['Sqk']; // squawk
413
		    $data['emergency'] = ''; // emergency
414
		    if (isset($line['Reg'])) $data['registration'] = $line['Reg'];
415
		    /*
416
		    if (isset($line['PosTime'])) $data['datetime'] = date('Y-m-d H:i:s',$line['PosTime']/1000);
417
		    else $data['datetime'] = date('Y-m-d H:i:s');
418
		    */
419
		    $data['datetime'] = date('Y-m-d H:i:s');
420
		    if (isset($line['Type'])) $data['aircraft_icao'] = $line['Type'];
421
	    	    $data['format_source'] = 'aircraftlistjson';
422
		    $data['id_source'] = $id_source;
423 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
424
		    if (isset($data['datetime'])) $SI->add($data);
425
		    unset($data);
426
		}
427
	    } else {
428
		foreach ($all_data as $line) {
429
		    $data = array();
430
		    $data['hex'] = $line['hex']; // hex
431
		    $data['ident'] = $line['flight']; // ident
432
		    $data['altitude'] = $line['altitude']; // altitude
433
		    $data['speed'] = $line['speed']; // speed
434
		    $data['heading'] = $line['track']; // heading
435
		    $data['latitude'] = $line['lat']; // lat
436
		    $data['longitude'] = $line['lon']; // long
437
		    $data['verticalrate'] = $line['vrt']; // verticale rate
438
		    $data['squawk'] = $line['squawk']; // squawk
439
		    $data['emergency'] = ''; // emergency
440
		    $data['datetime'] = date('Y-m-d H:i:s');
441
	    	    $data['format_source'] = 'aircraftlistjson';
442
    		    $data['id_source'] = $id_source;
443 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
444
		    $SI->add($data);
445
		    unset($data);
446
		}
447
	    }
448
	    }
449
    	    //$last_exec['aircraftlistjson'] = time();
450
    	    $value['last_exec'] = time();
451
    	//} elseif ($value == 'planeupdatefaa' && (time() - $last_exec['planeupdatefaa'] > $globalMinFetch)) {
452
    	} elseif ($value['format'] == 'planeupdatefaa' && (time() - $value['last_exec'] > $globalMinFetch)) {
453
	    $buffer = $Common->getData($value['host']);
454
	    $all_data = json_decode($buffer,true);
455
	    if (isset($all_data['planes'])) {
456
		foreach ($all_data['planes'] as $key => $line) {
457
		    $data = array();
458
		    $data['hex'] = $key; // hex
459
		    $data['ident'] = $line[3]; // ident
460
		    $data['altitude'] = $line[6]; // altitude
461
		    $data['speed'] = $line[8]; // speed
462
		    $data['heading'] = $line[7]; // heading
463
		    $data['latitude'] = $line[4]; // lat
464
		    $data['longitude'] = $line[5]; // long
465
		    //$data['verticalrate'] = $line[]; // verticale rate
466
		    $data['squawk'] = $line[10]; // squawk
467
		    $data['emergency'] = ''; // emergency
468
		    $data['registration'] = $line[2];
469
		    $data['aircraft_icao'] = $line[0];
470
		    $deparr = explode('-',$line[1]);
471
		    if (count($deparr) == 2) {
472
			$data['departure_airport_icao'] = $deparr[0];
473
			$data['arrival_airport_icao'] = $deparr[1];
474
		    }
475
		    $data['datetime'] = date('Y-m-d H:i:s',$line[9]);
476
	    	    $data['format_source'] = 'planeupdatefaa';
477
    		    $data['id_source'] = $id_source;
478 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
479
		    $SI->add($data);
480
		    unset($data);
481
		}
482
	    }
483
    	    //$last_exec['planeupdatefaa'] = time();
484
    	    $value['last_exec'] = time();
485
    	//} elseif ($value == 'fr24json' && (time() - $last_exec['fr24json'] > $globalMinFetch)) {
486
    	} elseif ($value['format'] == 'fr24json' && (time() - $value['last_exec'] > $globalMinFetch)) {
487
	    //$buffer = $Common->getData($hosts[$id]);
488
	    $buffer = $Common->getData($value['host']);
489
	    $all_data = json_decode($buffer,true);
490
	    foreach ($all_data as $key => $line) {
491
		if ($key != 'full_count' && $key != 'version' && $key != 'stats') {
492
		    $data = array();
493
		    $data['hex'] = $line[0];
494
		    $data['ident'] = $line[16]; //$line[13]
495
	    	    $data['altitude'] = $line[4]; // altitude
496
	    	    $data['speed'] = $line[5]; // speed
497
	    	    $data['heading'] = $line[3]; // heading
498
	    	    $data['latitude'] = $line[1]; // lat
499
	    	    $data['longitude'] = $line[2]; // long
500
	    	    $data['verticalrate'] = $line[15]; // verticale rate
501
	    	    $data['squawk'] = $line[6]; // squawk
502
	    	    $data['aircraft_icao'] = $line[8];
503
	    	    $data['registration'] = $line[9];
504
		    $data['departure_airport_iata'] = $line[11];
505
		    $data['arrival_airport_iata'] = $line[12];
506
	    	    $data['emergency'] = ''; // emergency
507
		    $data['datetime'] = date('Y-m-d H:i:s'); //$line[10]
508
	    	    $data['format_source'] = 'fr24json';
509
    		    $data['id_source'] = $id_source;
510 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
511
		    $SI->add($data);
512
		    unset($data);
513
		}
514
	    }
515
    	    //$last_exec['fr24json'] = time();
516
    	    $value['last_exec'] = time();
517
    	//} elseif ($value == 'radarvirtueljson' && (time() - $last_exec['radarvirtueljson'] > $globalMinFetch)) {
518
    	} elseif ($value['format'] == 'radarvirtueljson' && (time() - $value['last_exec'] > $globalMinFetch)) {
519
	    //$buffer = $Common->getData($hosts[$id],'get','','','','','150');
520
	    $buffer = $Common->getData($value['host'],'get','','','','','150');
521
	    //echo $buffer;
522
	    $buffer = str_replace(array("\n","\r"),"",$buffer);
523
	    $buffer = preg_replace('/,"num":(.+)/','}',$buffer);
524
	    $all_data = json_decode($buffer,true);
525
	    if (json_last_error() != JSON_ERROR_NONE) {
526
		die(json_last_error_msg());
527
	    }
528
	    if (isset($all_data['mrkrs'])) {
529
		foreach ($all_data['mrkrs'] as $key => $line) {
530
		    if (isset($line['inf'])) {
531
			$data = array();
532
			$data['hex'] = $line['inf']['ia'];
533
			if (isset($line['inf']['cs'])) $data['ident'] = $line['inf']['cs']; //$line[13]
534
	    		$data['altitude'] = round($line['inf']['al']*3.28084); // altitude
535
	    		if (isset($line['inf']['gs'])) $data['speed'] = round($line['inf']['gs']*0.539957); // speed
536
	    		if (isset($line['inf']['tr'])) $data['heading'] = $line['inf']['tr']; // heading
537
	    		$data['latitude'] = $line['pt'][0]; // lat
538
	    		$data['longitude'] = $line['pt'][1]; // long
539
	    		//if (isset($line['inf']['vs'])) $data['verticalrate'] = $line['inf']['vs']; // verticale rate
540
	    		if (isset($line['inf']['sq'])) $data['squawk'] = $line['inf']['sq']; // squawk
541
	    		//$data['aircraft_icao'] = $line[8];
542
	    		if (isset($line['inf']['rc'])) $data['registration'] = $line['inf']['rc'];
543
			//$data['departure_airport_iata'] = $line[11];
544
			//$data['arrival_airport_iata'] = $line[12];
545
	    		//$data['emergency'] = ''; // emergency
546
			$data['datetime'] = date('Y-m-d H:i:s',$line['inf']['dt']); //$line[10]
547
	    		$data['format_source'] = 'radarvirtueljson';
548
    			$data['id_source'] = $id_source;
549 View Code Duplication
			if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
550
			$SI->add($data);
551
			unset($data);
552
		    }
553
		}
554
	    }
555
    	    //$last_exec['radarvirtueljson'] = time();
556
    	    $value['last_exec'] = time();
557
    	//} elseif ($value == 'pirepsjson' && (time() - $last_exec['pirepsjson'] > $globalMinFetch)) {
558
    	} elseif ($value['format'] == 'pirepsjson' && (time() - $value['last_exec'] > $globalMinFetch)) {
559
	    //$buffer = $Common->getData($hosts[$id]);
560
	    $buffer = $Common->getData($value['host']);
561
	    $all_data = json_decode(utf8_encode($buffer),true);
562
	    
563
	    if (isset($all_data['pireps'])) {
564
	        foreach ($all_data['pireps'] as $line) {
565
		    $data = array();
566
		    $data['hex'] = str_pad(dechex($line['id']),6,'000000',STR_PAD_LEFT);
567
		    $data['ident'] = $line['callsign']; // ident
568
		    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid']; // pilot id
569
		    if (isset($line['name'])) $data['pilot_name'] = $line['name']; // pilot name
570
		    if (isset($line['alt'])) $data['altitude'] = $line['alt']; // altitude
571
		    if (isset($line['gs'])) $data['speed'] = $line['gs']; // speed
572
		    if (isset($line['heading'])) $data['heading'] = $line['heading']; // heading
573
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
574
		    $data['latitude'] = $line['lat']; // lat
575
		    $data['longitude'] = $line['lon']; // long
576
		    //$data['verticalrate'] = $line['vrt']; // verticale rate
577
		    //$data['squawk'] = $line['squawk']; // squawk
578
		    //$data['emergency'] = ''; // emergency
579
		    if (isset($line['depicao'])) $data['departure_airport_icao'] = $line['depicao'];
580
		    if (isset($line['deptime'])) $data['departure_airport_time'] = $line['deptime'];
581
		    if (isset($line['arricao'])) $data['arrival_airport_icao'] = $line['arricao'];
582
		    //$data['arrival_airport_time'] = $line['arrtime'];
583
		    if (isset($line['aircraft'])) $data['aircraft_icao'] = $line['aircraft'];
584
		    if (isset($line['transponder'])) $data['squawk'] = $line['transponder'];
585
		    if (isset($line['atis'])) $data['info'] = $line['atis'];
586
		    else $data['info'] = '';
587
		    $data['format_source'] = 'pireps';
588
    		    $data['id_source'] = $id_source;
589
		    $data['datetime'] = date('Y-m-d H:i:s');
590 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
591
		    if ($line['icon'] == 'plane') {
592
			$SI->add($data);
593
		    //    print_r($data);
594
    		    } elseif ($line['icon'] == 'ct') {
595
			$data['info'] = str_replace('^&sect;','<br />',$data['info']);
596
			$data['info'] = str_replace('&amp;sect;','',$data['info']);
597
			$typec = substr($data['ident'],-3);
598
			$data['type'] = '';
599 View Code Duplication
			if ($typec == 'APP') $data['type'] = 'Approach';
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
600
			elseif ($typec == 'TWR') $data['type'] = 'Tower';
601
			elseif ($typec == 'OBS') $data['type'] = 'Observer';
602
			elseif ($typec == 'GND') $data['type'] = 'Ground';
603
			elseif ($typec == 'DEL') $data['type'] = 'Delivery';
604
			elseif ($typec == 'DEP') $data['type'] = 'Departure';
605
			elseif ($typec == 'FSS') $data['type'] = 'Flight Service Station';
606
			elseif ($typec == 'CTR') $data['type'] = 'Control Radar or Centre';
607
			else $data['type'] = 'Observer';
608
			echo $ATC->add($data['ident'],'',$data['latitude'],$data['longitude'],'0',$data['info'],$data['datetime'],$data['type'],$data['pilot_id'],$data['pilot_name']);
609
		    }
610
		    unset($data);
611
		}
612
	    }
613
    	    //$last_exec['pirepsjson'] = time();
614
    	    $value['last_exec'] = time();
615
    	//} elseif ($value == 'phpvmacars' && (time() - $last_exec['phpvmacars'] > $globalMinFetch)) {
616
    	} elseif ($value['format'] == 'phpvmacars' && (time() - $value['last_exec'] > $globalMinFetch)) {
617
	    //$buffer = $Common->getData($hosts[$id]);
618
	    $buffer = $Common->getData($value['host']);
619
	    $all_data = json_decode($buffer,true);
620
	    if ($buffer != '' && is_array($all_data)) {
621
		foreach ($all_data as $line) {
622
	    	    $data = array();
623
	    	    //$data['id'] = $line['id']; // id not usable
624
	    	    $data['hex'] = substr(str_pad(bin2hex($line['flightnum']),6,'000000',STR_PAD_LEFT),-6); // hex
625
	    	    if (isset($line['pilotname'])) $data['pilot_name'] = $line['pilotname'];
626
	    	    if (isset($line['pilotid'])) $data['pilot_id'] = $line['pilotid'];
627
	    	    $data['ident'] = $line['flightnum']; // ident
628
	    	    $data['altitude'] = $line['alt']; // altitude
629
	    	    $data['speed'] = $line['gs']; // speed
630
	    	    $data['heading'] = $line['heading']; // heading
631
	    	    $data['latitude'] = $line['lat']; // lat
632
	    	    $data['longitude'] = $line['lng']; // long
633
	    	    $data['verticalrate'] = ''; // verticale rate
634
	    	    $data['squawk'] = ''; // squawk
635
	    	    $data['emergency'] = ''; // emergency
636
	    	    //$data['datetime'] = $line['lastupdate'];
637
		    $data['datetime'] = date('Y-m-d H:i:s');
638
	    	    $data['departure_airport_icao'] = $line['depicao'];
639
	    	    $data['departure_airport_time'] = $line['deptime'];
640
	    	    $data['arrival_airport_icao'] = $line['arricao'];
641
    		    $data['arrival_airport_time'] = $line['arrtime'];
642
    		    $data['registration'] = $line['aircraft'];
643
		    if (isset($line['route'])) $data['waypoints'] = $line['route']; // route
644
		    if (isset($line['aircraftname'])) {
645
			$line['aircraftname'] = strtoupper($line['aircraftname']);
646
			$line['aircraftname'] = str_replace('BOEING ','B',$line['aircraftname']);
647
	    		$aircraft_data = explode('-',$line['aircraftname']);
648
	    		if (isset($aircraft_data[1]) && strlen($aircraft_data[0]) < 5) $data['aircraft_icao'] = $aircraft_data[0];
649
	    		elseif (isset($aircraft_data[1]) && strlen($aircraft_data[1]) < 5) $data['aircraft_icao'] = $aircraft_data[1];
650 View Code Duplication
	    		else {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
651
	    		    $aircraft_data = explode(' ',$line['aircraftname']);
652
	    		    if (isset($aircraft_data[1])) $data['aircraft_icao'] = $aircraft_data[1];
653
	    		    else $data['aircraft_icao'] = $line['aircraftname'];
654
	    		}
655
	    	    }
656
    		    if (isset($line['route'])) $data['waypoints'] = $line['route'];
657
    		    $data['id_source'] = $id_source;
658
	    	    $data['format_source'] = 'phpvmacars';
659 View Code Duplication
		    if (isset($value['name']) && $value['name'] != '') $data['source_name'] = $value['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
660
		    $SI->add($data);
661
		    unset($data);
662
		}
663
	    }
664
    	    //$last_exec['phpvmacars'] = time();
665
    	    $value['last_exec'] = time();
666
	//} elseif ($value == 'sbs' || $value == 'tsv' || $value == 'raw' || $value == 'aprs' || $value == 'beast') {
667
	} 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') {
668
	    if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
669
    	    $value['last_exec'] = time();
670
671
	    //$read = array( $sockets[$id] );
672
	    $read = $sockets;
673
	    $write = NULL;
674
	    $e = NULL;
675
	    $n = socket_select($read, $write, $e, $timeout);
676
	    if ($e != NULL) var_dump($e);
677
	    if ($n > 0) {
678
		foreach ($read as $nb => $r) {
679
		    //$value = $formats[$nb];
680
		    $format = $globalSources[$nb]['format'];
681
        	    //$buffer = socket_read($r, 6000,PHP_NORMAL_READ);
682
        	    $az = socket_recvfrom($r,$buffer,6000,0,$remote_ip,$remote_port);
683
        	    //$buffer = socket_read($r, 60000,PHP_NORMAL_READ);
684
        	    //echo $buffer."\n";
685
		    // lets play nice and handle signals such as ctrl-c/kill properly
686
		    //if (function_exists('pcntl_fork')) pcntl_signal_dispatch();
687
		    $error = false;
688
		    //$SI::del();
689
		    $buffer=trim(str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),'',$buffer));
690
		    // SBS format is CSV format
691
		    if ($buffer != '') {
692
			$tt = 0;
693
			if ($format == 'raw') {
694
			    // AVR format
695
			    $data = $SBS->parse($buffer);
696
			    if (is_array($data)) {
697
				$data['datetime'] = date('Y-m-d H:i:s');
698
				$data['format_source'] = 'raw';
699 View Code Duplication
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
700 View Code Duplication
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
701
                                $SI->add($data);
702
                            }
703
                        } elseif ($format == 'flightgearsp') {
704
                    	    //echo $buffer."\n";
705
                    	    if (strlen($buffer) > 5) {
706
				$line = explode(',',$buffer);
707
				$data = array();
708
				//XGPS,2.0947,41.3093,-3047.6953,198.930,0.000,callsign,c172p
709
				$data['hex'] = substr(str_pad(bin2hex($line[6].$line[7]),6,'000000',STR_PAD_LEFT),0,6);
710
				$data['ident'] = $line[6];
711
				$data['aircraft_name'] = $line[7];
712
				$data['longitude'] = $line[1];
713
				$data['latitude'] = $line[2];
714
				$data['altitude'] = round($line[3]*3.28084);
715
				$data['heading'] = round($line[4]);
716
				$data['speed'] = round($line[5]*1.94384);
717
				$data['datetime'] = date('Y-m-d H:i:s');
718
				$data['format_source'] = 'flightgearsp';
719
				$SI->add($data);
720
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
721
			    }
722
                        } elseif ($format == 'acars') {
723
                    	    if ($globalDebug) echo 'ACARS : '.$buffer."\n";
724
			    $ACARS->add(trim($buffer));
725
			    socket_sendto($r, "OK " . $buffer , 100 , 0 , $remote_ip , $remote_port);
726
			    $ACARS->deleteLiveAcarsData();
727
			} elseif ($format == 'flightgearmp') {
728
			    //
729
			    if (substr($buffer,0,1) != '#') {
730
				$data = array();
731
				//echo $buffer."\n";
732
				$line = explode(' ',$buffer);
733
				if (count($line) == 11) {
734
				    $userserver = explode('@',$line[0]);
735
				    $data['hex'] = substr(str_pad(bin2hex($line[0]),6,'000000',STR_PAD_LEFT),0,6); // hex
736
				    $data['ident'] = $userserver[0];
737
				    $data['registration'] = $userserver[0];
738
				    $data['latitude'] = $line[4];
739
				    $data['longitude'] = $line[5];
740
				    $data['altitude'] = $line[6];
741
				    $data['datetime'] = date('Y-m-d H:i:s');
742
				    $aircraft_type = $line[10];
743
				    $aircraft_type = preg_split(':/:',$aircraft_type);
744
				    $data['aircraft_name'] = substr(end($aircraft_type),0,-4);
745
				    $SI->add($data);
746
				}
747
			    }
748
			} elseif ($format == 'beast') {
749
			    echo 'Beast Binary format not yet supported. Beast AVR format is supported in alpha state'."\n";
750
			    die;
751
			} elseif ($format == 'tsv' || substr($buffer,0,4) == 'clock') {
752
			    $line = explode("\t", $buffer);
753
			    for($k = 0; $k < count($line); $k=$k+2) {
754
				$key = $line[$k];
755
			        $lined[$key] = $line[$k+1];
756
			    }
757
    			    if (count($lined) > 3) {
758
    				$data['hex'] = $lined['hexid'];
759
    				//$data['datetime'] = date('Y-m-d H:i:s',strtotime($lined['clock']));;
760
    				$data['datetime'] = date('Y-m-d H:i:s');;
761
    				if (isset($lined['ident'])) $data['ident'] = $lined['ident'];
762
    				if (isset($lined['lat'])) $data['latitude'] = $lined['lat'];
763
    				if (isset($lined['lon'])) $data['longitude'] = $lined['lon'];
764
    				if (isset($lined['speed'])) $data['speed'] = $lined['speed'];
765
    				if (isset($lined['squawk'])) $data['squawk'] = $lined['squawk'];
766
    				if (isset($lined['alt'])) $data['altitude'] = $lined['alt'];
767
    				if (isset($lined['heading'])) $data['heading'] = $lined['heading'];
768
    				$data['id_source'] = $id_source;
769
    				$data['format_source'] = 'tsv';
770 View Code Duplication
    				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
771 View Code Duplication
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
772
    				$SI->add($data);
773
    				unset($lined);
774
    				unset($data);
775
    			    } else $error = true;
776
			} elseif ($format == 'aprs' && $use_aprs) {
777
			    if ($aprs_connect == 0) {
778
				$send = @ socket_send( $r  , $aprs_login , strlen($aprs_login) , 0 );
779
				$aprs_connect = 1;
780
			    }
781
			    if ( $aprs_keep>60 && time() - $aprs_last_tx > $aprs_keep ) {
782
				$aprs_last_tx = time();
783
				$data_aprs = "# Keep alive";
784
				$send = @ socket_send( $r  , $data_aprs , strlen($data_aprs) , 0 );
785
			    }
786
			    //echo 'Connect : '.$aprs_connect.' '.$buffer."\n";
787
			    if (substr($buffer,0,1) != '#') {
788
				$line = $APRS->parse($buffer);
789
				if (is_array($line) && isset($line['address']) && $line['address'] != '' && isset($line['ident'])) {
790
				    $data = array();
791
				    //print_r($line);
792
				    $data['hex'] = $line['address'];
793
				    $data['datetime'] = date('Y-m-d H:i:s',$line['timestamp']);
794
				    //$data['datetime'] = date('Y-m-d H:i:s');
795
				    $data['ident'] = $line['ident'];
796
				    $data['latitude'] = $line['latitude'];
797
				    $data['longitude'] = $line['longitude'];
798
				    //$data['verticalrate'] = $line[16];
799
				    if (isset($line['speed'])) $data['speed'] = $line['speed'];
800
				    else $data['speed'] = 0;
801
				    $data['altitude'] = $line['altitude'];
802
				    if (isset($line['course'])) $data['heading'] = $line['course'];
803
				    //else $data['heading'] = 0;
804
				    $data['aircraft_type'] = $line['stealth'];
805
				    if (!isset($globalAPRSarchive) || (isset($globalAPRSarchive) && $globalAPRSarchive == FALSE)) $data['noarchive'] = true;
806
    				    $data['id_source'] = $id_source;
807
				    $data['format_source'] = 'aprs';
808
				    $data['source_name'] = $line['source'];
809 View Code Duplication
    				    if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
810
				    $currentdate = date('Y-m-d H:i:s');
811
				    $aprsdate = strtotime($data['datetime']);
812
				    // Accept data if time <= system time + 20s
813
				    if ($line['stealth'] == 0 && (strtotime($data['datetime']) <= strtotime($currentdate)+20)) $send = $SI->add($data);
814
				    else {
815
					if ($line['stealth'] != 0) echo '-------- '.$data['ident'].' : APRS stealth ON => not adding'."\n";
816
					else echo '--------- '.$data['ident'].' : Date APRS : '.$data['datetime'].' - Current date : '.$currentdate.' => not adding future event'."\n";
817
				    }
818
				    unset($data);
819
				} 
820
				//elseif ($line == false && $globalDebug) echo 'Ignored ('.$buffer.")\n";
821
				elseif ($line == true && $globalDebug) echo '!! Failed : '.$buffer."!!\n";
822
			    }
823
			} else {
824
			    $line = explode(',', $buffer);
825
    			    if (count($line) > 20) {
826
    			    	$data['hex'] = $line[4];
827
    				/*
828
    				$data['datetime'] = $line[6].' '.$line[7];
829
    					date_default_timezone_set($globalTimezone);
830
    					$datetime = new DateTime($data['datetime']);
831
    					$datetime->setTimezone(new DateTimeZone('UTC'));
832
    					$data['datetime'] = $datetime->format('Y-m-d H:i:s');
833
    					date_default_timezone_set('UTC');
834
    				*/
835
    				// Force datetime to current UTC datetime
836
    				$data['datetime'] = date('Y-m-d H:i:s');
837
    				$data['ident'] = trim($line[10]);
838
    				$data['latitude'] = $line[14];
839
    				$data['longitude'] = $line[15];
840
    				$data['verticalrate'] = $line[16];
841
    				$data['emergency'] = $line[20];
842
    				$data['speed'] = $line[12];
843
    				$data['squawk'] = $line[17];
844
    				$data['altitude'] = $line[11];
845
    				$data['heading'] = $line[13];
846
    				$data['ground'] = $line[21];
847
    				$data['emergency'] = $line[19];
848
    				$data['format_source'] = 'sbs';
849 View Code Duplication
				if (isset($globalSources[$nb]['name']) && $globalSources[$nb]['name'] != '') $data['source_name'] = $globalSources[$nb]['name'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
850 View Code Duplication
    				if (isset($globalSources[$nb]['sourcestats'])) $data['sourcestats'] = $globalSources[$nb]['sourcestats'];
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
851
    				$data['id_source'] = $id_source;
852
    				$send = $SI->add($data);
853
    				unset($data);
854
    			    } else $error = true;
855
			    if ($error) {
856
				if (count($line) > 1 && ($line[0] == 'STA' || $line[0] == 'AIR' || $line[0] == 'SEL' || $line[0] == 'ID' || $line[0] == 'CLK')) { 
857
					if ($globalDebug) echo "Not a message. Ignoring... \n";
858
				} else {
859
					if ($globalDebug) echo "Wrong line format. Ignoring... \n";
860
					if ($globalDebug) {
861
						echo $buffer;
862
						print_r($line);
863
					}
864
					//socket_close($r);
865
					if ($globalDebug) echo "Reconnect after an error...\n";
866
					connect_all($globalSources);
867
				}
868
			    }
869
			}
870
			// Sleep for xxx microseconds
871
			if (isset($globalSBSSleep)) usleep($globalSBSSleep);
872
		    } else {
873
			if ($format == 'flightgearmp') {
874
			    	if ($globalDebug) echo "Reconnect FlightGear MP...";
875
				//@socket_close($r);
876
				sleep($globalMinFetch);
877
				$sourcefg[$nb] = $globalSources[$nb];
878
				connect_all($sourcefg);
879
				break;
880
				
881
			} elseif ($format != 'acars' && $format != 'flightgearsp') {
882
			    $tt++;
883
			    if ($tt > 30) {
884
				if ($globalDebug)echo "ERROR : Reconnect...";
885
				//@socket_close($r);
886
				sleep(2);
887
				connect_all($globalSources);
888
				break;
889
				$tt = 0;
890
			    }
891
			}
892
		    }
893
		}
894
	    } else {
895
		$error = socket_strerror(socket_last_error());
896
		if ($globalDebug) echo "ERROR : socket_select give this error ".$error . "\n";
897
		if (($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) || time() - $time >= $timeout) {
898
			if (isset($globalDebug)) echo "Restarting...\n";
899
			// Restart the script if possible
900
			if (is_array($sockets)) {
901
			    if ($globalDebug) echo "Shutdown all sockets...";
902
			    
903
			    foreach ($sockets as $sock) {
904
				@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...
905
				@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...
906
			    }
907
			    
908
			}
909
			    if ($globalDebug) echo "Restart all connections...";
910
			    sleep(2);
911
			    $time = time();
912
			    //connect_all($hosts);
913
			    connect_all($globalSources);
914
915
		}
916
	    }
917
	}
918
	if ($globalDaemon == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
919
	    $SI->checkAll();
920
	}
921
    }
922
}
923
924
?>
925