Completed
Push — master ( 4c247d...ce17c6 )
by Yannick
07:53
created

SpotterLive::getMinLastLiveSpotterData()   C

Complexity

Conditions 8
Paths 24

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 27
nc 24
nop 1
dl 0
loc 40
rs 5.3846
c 0
b 0
f 0
1
<?php
2
//$global_query = "SELECT spotter_live.* FROM spotter_live";
3
4
class SpotterLive {
5
	public $db;
6
	static $global_query = "SELECT spotter_live.* FROM spotter_live";
7
8
	public function __construct($dbc = null) {
9
		$Connection = new Connection($dbc);
10
		$this->db = $Connection->db();
11
	}
12
13
14
	/**
15
	* Get SQL query part for filter used
16
	* @param Array $filter the filter
17
	* @return Array the SQL part
18
	*/
19
	public function getFilter($filter = array(),$where = false,$and = false) {
20
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
21
		$filters = array();
22
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
23
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
24
				$filters = $globalStatsFilters[$globalFilterName];
25
			} else {
26
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
27
			}
28
		}
29
		if (isset($filter[0]['source'])) {
30
			$filters = array_merge($filters,$filter);
31
		}
32
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
33
		$filter_query_join = '';
34
		$filter_query_where = '';
35
		foreach($filters as $flt) {
36
			if (isset($flt['airlines']) && !empty($flt['airlines'])) {
37
				if ($flt['airlines'][0] != '') {
38
					if (isset($flt['source'])) {
39
						$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.airline_icao IN ('".implode("','",$flt['airlines'])."') AND spotter_output.format_source IN ('".implode("','",$flt['source'])."')) saf ON saf.flightaware_id = spotter_live.flightaware_id";
40
					} else {
41
						$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.airline_icao IN ('".implode("','",$flt['airlines'])."')) saf ON saf.flightaware_id = spotter_live.flightaware_id";
42
					}
43
				}
44
			}
45
			if (isset($flt['pilots_id']) && !empty($flt['pilots_id'])) {
46
				if (isset($flt['source'])) {
47
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.pilot_id IN ('".implode("','",$flt['pilots_id'])."') AND spotter_output.format_source IN ('".implode("','",$flt['source'])."')) spi ON spi.flightaware_id = spotter_live.flightaware_id";
48
				} else {
49
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.pilot_id IN ('".implode("','",$flt['pilots_id'])."')) spi ON spi.flightaware_id = spotter_live.flightaware_id";
50
				}
51
			}
52
			if (isset($flt['idents']) && !empty($flt['idents'])) {
53
				if (isset($flt['source'])) {
54
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.ident IN ('".implode("','",$flt['idents'])."') AND spotter_output.format_source IN ('".implode("','",$flt['source'])."')) spid ON spid.flightaware_id = spotter_live.flightaware_id";
55
				} else {
56
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.ident IN ('".implode("','",$flt['idents'])."')) spid ON spid.flightaware_id = spotter_live.flightaware_id";
57
				}
58
			}
59
			if (isset($flt['registrations']) && !empty($flt['registrations'])) {
60
				if (isset($flt['source'])) {
61
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.registration IN ('".implode("','",$flt['registrations'])."') AND spotter_output.format_source IN ('".implode("','",$flt['source'])."')) sre ON sre.flightaware_id = spotter_live.flightaware_id";
62
				} else {
63
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.registration IN ('".implode("','",$flt['registrations'])."')) sre ON sre.flightaware_id = spotter_live.flightaware_id";
64
				}
65
			}
66
			if ((isset($flt['airlines']) && empty($flt['airlines']) && isset($flt['pilots_id']) && empty($flt['pilots_id']) && isset($flt['idents']) && empty($flt['idents'])) || (!isset($flt['airlines']) && !isset($flt['pilots_id']) && !isset($flt['idents']) && !isset($flt['registrations']))) {
67
				if (isset($flt['source'])) {
68
					$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.format_source IN ('".implode("','",$flt['source'])."')) ssf ON ssf.flightaware_id = spotter_live.flightaware_id";
69
				}
70
			}
71
		}
72
		if (isset($filter['airlines']) && !empty($filter['airlines'])) {
73
			if ($filter['airlines'][0] != '') {
74
				$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.airline_icao IN ('".implode("','",$filter['airlines'])."')) sai ON sai.flightaware_id = spotter_live.flightaware_id";
75
			}
76
		}
77
		if (isset($filter['alliance']) && !empty($filter['alliance'])) {
78
			$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.airline_icao IN (SELECT icao FROM airlines WHERE alliance = '".$filter['alliance']."')) sal ON sal.flightaware_id = spotter_live.flightaware_id ";
79
		}
80
		if (isset($filter['airlinestype']) && !empty($filter['airlinestype'])) {
81
			$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.airline_type = '".$filter['airlinestype']."') sa ON sa.flightaware_id = spotter_live.flightaware_id ";
82
		}
83
		if (isset($filter['pilots_id']) && !empty($filter['pilots_id'])) {
84
			$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output WHERE spotter_output.pilot_id IN ('".implode("','",$filter['pilots_id'])."')) sp ON sp.flightaware_id = spotter_live.flightaware_id";
85
		}
86
		if (isset($filter['source']) && !empty($filter['source'])) {
87
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
88
		}
89
		if (isset($filter['ident']) && !empty($filter['ident'])) {
90
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
91
		}
92
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
93
			$filter_query_date = '';
94
			
95
			if (isset($filter['year']) && $filter['year'] != '') {
96
				if ($globalDBdriver == 'mysql') {
97
					$filter_query_date .= " AND YEAR(spotter_output.date) = '".$filter['year']."'";
98
				} else {
99
					$filter_query_date .= " AND EXTRACT(YEAR FROM spotter_output.date) = '".$filter['year']."'";
100
				}
101
			}
102
			if (isset($filter['month']) && $filter['month'] != '') {
103
				if ($globalDBdriver == 'mysql') {
104
					$filter_query_date .= " AND MONTH(spotter_output.date) = '".$filter['month']."'";
105
				} else {
106
					$filter_query_date .= " AND EXTRACT(MONTH FROM spotter_output.date) = '".$filter['month']."'";
107
				}
108
			}
109
			if (isset($filter['day']) && $filter['day'] != '') {
110
				if ($globalDBdriver == 'mysql') {
111
					$filter_query_date .= " AND DAY(spotter_output.date) = '".$filter['day']."'";
112
				} else {
113
					$filter_query_date .= " AND EXTRACT(DAY FROM spotter_output.date) = '".$filter['day']."'";
114
				}
115
			}
116
			$filter_query_join .= " INNER JOIN (SELECT flightaware_id FROM spotter_output".preg_replace('/^ AND/',' WHERE',$filter_query_date).") sd ON sd.flightaware_id = spotter_live.flightaware_id";
117
		}
118
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
119
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
120
		}
121
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
122
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
123
		if ($filter_query_where != '') {
124
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
125
		}
126
		$filter_query = $filter_query_join.$filter_query_where;
127
		return $filter_query;
128
	}
129
130
	/**
131
	* Gets all the spotter information based on the latest data entry
132
	*
133
	* @return Array the spotter information
134
	*
135
	*/
136
	public function getLiveSpotterData($limit = '', $sort = '', $filter = array())
137
	{
138
		global $globalDBdriver, $globalLiveInterval;
139
		$Spotter = new Spotter($this->db);
140
		date_default_timezone_set('UTC');
141
142
		$filter_query = $this->getFilter($filter);
143
		$limit_query = '';
144
		if ($limit != '')
145
		{
146
			$limit_array = explode(',', $limit);
147
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
148
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
149
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
150
			{
151
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
152
			}
153
		}
154
		$orderby_query = '';
155
		if ($sort != '')
156
		{
157
			$search_orderby_array = $this->getOrderBy();
158
			if (isset($search_orderby_array[$sort]['sql'])) 
159
			{
160
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
161
			}
162
		}
163
164
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
165
		if ($globalDBdriver == 'mysql') {
166
			//$query  = "SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND) <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate";
167
			$query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate'.$filter_query.$orderby_query;
168
		} else {
169
			$query  = "SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate".$filter_query.$orderby_query;
170
		}
171
		$spotter_array = $Spotter->getDataFromDB($query.$limit_query,array(),'',true);
172
173
		return $spotter_array;
174
	}
175
176
	/**
177
	* Gets Minimal Live Spotter data
178
	*
179
	* @return Array the spotter information
180
	*
181
	*/
182
	public function getMinLiveSpotterData($filter = array())
183
	{
184
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
185
		date_default_timezone_set('UTC');
186
		$filter_query = $this->getFilter($filter,true,true);
187
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
188
		if ($globalDBdriver == 'mysql') {
189
			if (isset($globalArchive) && $globalArchive === TRUE) {
190
				$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
191
				FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= spotter_live.date AND'." spotter_live.latitude <> 0 AND spotter_live.longitude <> 0";
192
			} else {
193
				$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
194
				FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate'.$filter_query." spotter_live.latitude <> 0 AND spotter_live.longitude <> 0";
195
			}
196
		} else {
197
			if (isset($globalArchive) && $globalArchive === TRUE) {
198
				$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
199
				FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date AND  spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
200
			} else {
201
				$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
202
				FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate".$filter_query." spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
203
			}
204
		}
205
206
		try {
207
			$sth = $this->db->prepare($query);
208
			$sth->execute();
209
		} catch(PDOException $e) {
210
			echo $e->getMessage();
211
			die;
212
		}
213
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
214
		return $spotter_array;
215
	}
216
217
	/**
218
	* Gets Minimal Live Spotter data since xx seconds
219
	*
220
	* @return Array the spotter information
221
	*
222
	*/
223
	public function getMinLastLiveSpotterData($filter = array())
224
	{
225
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
226
		date_default_timezone_set('UTC');
227
228
		$filter_query = $this->getFilter($filter,true,true);
229
230
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
231
		if ($globalDBdriver == 'mysql') {
232
			if (isset($globalArchive) && $globalArchive === TRUE) {
233
				$query  = 'SELECT spotter_archive.ident, spotter_archive.flightaware_id, spotter_archive.aircraft_icao, spotter_archive.departure_airport_icao as departure_airport, spotter_archive.arrival_airport_icao as arrival_airport, spotter_archive.latitude, spotter_archive.longitude, spotter_archive.altitude, spotter_archive.heading, spotter_archive.ground_speed, spotter_archive.squawk, spotter_archive.date, spotter_archive.format_source 
234
				FROM spotter_archive INNER JOIN (SELECT flightaware_id FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= spotter_live.date) l ON l.flightaware_id = spotter_archive.flightaware_id AND spotter_archive.latitude <> '0' AND spotter_archive.longitude <> '0' 
235
				ORDER BY spotter_archive.flightaware_id, spotter_archive.date";
236
			} else {
237
				$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
238
				FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= spotter_live.date AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
239
				ORDER BY spotter_live.flightaware_id, spotter_live.date";
240
			}
241
                } else {
242
			if (isset($globalArchive) && $globalArchive === TRUE) {
243
				$query  = "SELECT spotter_archive.ident, spotter_archive.flightaware_id, spotter_archive.aircraft_icao, spotter_archive.departure_airport_icao as departure_airport, spotter_archive.arrival_airport_icao as arrival_airport, spotter_archive.latitude, spotter_archive.longitude, spotter_archive.altitude, spotter_archive.heading, spotter_archive.ground_speed, spotter_archive.squawk, spotter_archive.date, spotter_archive.format_source 
244
				FROM spotter_archive INNER JOIN (SELECT flightaware_id FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date) l ON l.flightaware_id = spotter_archive.flightaware_id WHERE spotter_archive.latitude <> '0' AND spotter_archive.longitude <> '0' 
245
				ORDER BY spotter_archive.flightaware_id, spotter_archive.date";
246
			} else {
247
				$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
248
				FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
249
				ORDER BY spotter_live.flightaware_id, spotter_live.date";
250
			}
251
		}
252
253
    		try {
254
			$sth = $this->db->prepare($query);
255
			$sth->execute();
256
		} catch(PDOException $e) {
257
			echo $e->getMessage();
258
			die;
259
		}
260
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
261
		return $spotter_array;
262
	}
263
264
	/**
265
	* Gets number of latest data entry
266
	*
267
	* @return String number of entry
268
	*
269
	*/
270
	public function getLiveSpotterCount($filter = array())
271
	{
272
		global $globalDBdriver, $globalLiveInterval;
273
		$filter_query = $this->getFilter($filter,true,true);
274
275
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
276
		if ($globalDBdriver == 'mysql') {
277
			//$query  = 'SELECT COUNT(*) as nb FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate'.$filter_query;
278
			$query = 'SELECT COUNT(DISTINCT spotter_live.flightaware_id) as nb FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
279
		} else {
280
			//$query  = "SELECT COUNT(*) as nb FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE NOW() AT TIME ZONE 'UTC' - '".$globalLiveInterval." SECONDS'->INTERVAL <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate".$filter_query;
281
			$query = "SELECT COUNT(DISTINCT spotter_live.flightaware_id) as nb FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
282
		}
283
		try {
284
			$sth = $this->db->prepare($query);
285
			$sth->execute();
286
		} catch(PDOException $e) {
287
			echo $e->getMessage();
288
			die;
289
		}
290
		$result = $sth->fetch(PDO::FETCH_ASSOC);
291
		$sth->closeCursor();
292
		return $result['nb'];
293
	}
294
295
	/**
296
	* Gets all the spotter information based on the latest data entry and coord
297
	*
298
	* @return Array the spotter information
299
	*
300
	*/
301
	public function getLiveSpotterDatabyCoord($coord, $filter = array())
302
	{
303
		global $globalDBdriver, $globalLiveInterval;
304
		$Spotter = new Spotter($this->db);
305
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
306
		$filter_query = $this->getFilter($filter);
307
308
		if (is_array($coord)) {
309
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
310
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
311
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
312
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
313
		} else return array();
314
		if ($globalDBdriver == 'mysql') {
315
			$query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate AND spotter_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND spotter_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.' GROUP BY spotter_live.flightaware_id'.$filter_query;
316
		} else {
317
			$query  = "SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE NOW() at time zone 'UTC'  - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." GROUP BY spotter_live.flightaware_id".$filter_query;
318
319
		}
320
		$spotter_array = $Spotter->getDataFromDB($query);
321
		return $spotter_array;
322
	}
323
324
	/**
325
	* Gets all the spotter information based on the latest data entry and coord
326
	*
327
	* @return Array the spotter information
328
	*
329
	*/
330
	public function getMinLiveSpotterDatabyCoord($coord, $filter = array())
331
	{
332
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
333
		$Spotter = new Spotter($this->db);
0 ignored issues
show
Unused Code introduced by
$Spotter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
334
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
335
		$filter_query = $this->getFilter($filter,true,true);
336
337
		if (is_array($coord)) {
338
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
339
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
340
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
341
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
342
		} else return array();
343
		if ($globalDBdriver == 'mysql') {
344
			if (isset($globalArchive) && $globalArchive === TRUE) {
345
				$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
346
				FROM spotter_live 
347
				'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= spotter_live.date 
348
				AND spotter_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND spotter_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
349
				AND spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
350
			} else {
351
				$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
352
				FROM spotter_live 
353
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
354
				    FROM spotter_live l 
355
				    WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
356
				    AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
357
				    GROUP BY l.flightaware_id
358
				) s on spotter_live.flightaware_id = s.flightaware_id 
359
				AND spotter_live.date = s.maxdate'.$filter_query.' spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
360
			}
361
		} else {
362
			if (isset($globalArchive) && $globalArchive === TRUE) {
363
				$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
364
				FROM spotter_live 
365
				".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date 
366
				AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
367
				AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
368
				AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
369
			} else {
370
				$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id, spotter_live.aircraft_icao, spotter_live.departure_airport_icao as departure_airport, spotter_live.arrival_airport_icao as arrival_airport, spotter_live.latitude, spotter_live.longitude, spotter_live.altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
371
				FROM spotter_live 
372
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
373
				    FROM spotter_live l 
374
				    WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
375
				    AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
376
				    AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
377
				    GROUP BY l.flightaware_id
378
				) s on spotter_live.flightaware_id = s.flightaware_id 
379
				AND spotter_live.date = s.maxdate".$filter_query." spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
380
			}
381
		}
382
		try {
383
			$sth = $this->db->prepare($query);
384
			$sth->execute();
385
		} catch(PDOException $e) {
386
			echo $e->getMessage();
387
			die;
388
		}
389
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
390
		return $spotter_array;
391
	}
392
393
	/**
394
	* Gets all the spotter information based on a user's latitude and longitude
395
	*
396
	* @return Array the spotter information
397
	*
398
	*/
399
	public function getLatestSpotterForLayar($lat, $lng, $radius, $interval)
400
	{
401
		$Spotter = new Spotter($this->db);
402
		date_default_timezone_set('UTC');
403
		if ($lat != '') {
404
			if (!is_numeric($lat)) {
405
				return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SpotterLive::getLatestSpotterForLayar of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
406
			}
407
		}
408
        if ($lng != '')
409
                {
410
                        if (!is_numeric($lng))
411
                        {
412
                                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SpotterLive::getLatestSpotterForLayar of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
413
                        }
414
                }
415
416
                if ($radius != '')
417
                {
418
                        if (!is_numeric($radius))
419
                        {
420
                                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SpotterLive::getLatestSpotterForLayar of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
421
                        }
422
                }
423
		$additional_query = '';
424
        if ($interval != '')
425
                {
426
                        if (!is_string($interval))
427
                        {
428
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
429
			        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SpotterLive::getLatestSpotterForLayar of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
430
                        } else {
431
                if ($interval == '1m')
432
                {
433
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
434
                } else if ($interval == '15m'){
435
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= spotter_live.date ';
436
                } 
437
            }
438
                } else {
439
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';   
440
        }
441
442
                $query  = "SELECT spotter_live.*, ( 6371 * acos( cos( radians(:lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:lng) ) + sin( radians(:lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM spotter_live 
443
                   WHERE spotter_live.latitude <> '' 
444
                                   AND spotter_live.longitude <> '' 
445
                   ".$additional_query."
446
                   HAVING distance < :radius  
447
                                   ORDER BY distance";
448
449
                $spotter_array = $Spotter->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
450
451
                return $spotter_array;
452
        }
453
454
    
455
        /**
456
	* Gets all the spotter information based on a particular callsign
457
	*
458
	* @return Array the spotter information
459
	*
460
	*/
461
	public function getLastLiveSpotterDataByIdent($ident)
462
	{
463
		$Spotter = new Spotter($this->db);
464
		date_default_timezone_set('UTC');
465
466
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
467
                $query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE l.ident = :ident GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate ORDER BY spotter_live.date DESC';
468
469
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident),'',true);
470
471
		return $spotter_array;
472
	}
473
474
        /**
475
	* Gets all the spotter information based on a particular callsign
476
	*
477
	* @return Array the spotter information
478
	*
479
	*/
480
	public function getDateLiveSpotterDataByIdent($ident,$date)
481
	{
482
		$Spotter = new Spotter($this->db);
483
		date_default_timezone_set('UTC');
484
485
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
486
                $query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE l.ident = :ident AND l.date <= :date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate ORDER BY spotter_live.date DESC';
487
488
                $date = date('c',$date);
489
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
490
491
		return $spotter_array;
492
	}
493
494
        /**
495
	* Gets last spotter information based on a particular callsign
496
	*
497
	* @return Array the spotter information
498
	*
499
	*/
500
	public function getLastLiveSpotterDataById($id)
501
	{
502
		$Spotter = new Spotter($this->db);
503
		date_default_timezone_set('UTC');
504
505
		$id = filter_var($id, FILTER_SANITIZE_STRING);
506
                $query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE l.flightaware_id = :id GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate ORDER BY spotter_live.date DESC';
507
508
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id),'',true);
509
510
		return $spotter_array;
511
	}
512
513
        /**
514
	* Gets last spotter information based on a particular callsign
515
	*
516
	* @return Array the spotter information
517
	*
518
	*/
519
	public function getDateLiveSpotterDataById($id,$date)
520
	{
521
		$Spotter = new Spotter($this->db);
522
		date_default_timezone_set('UTC');
523
524
		$id = filter_var($id, FILTER_SANITIZE_STRING);
525
                $query  = 'SELECT spotter_live.* FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l WHERE l.flightaware_id = :id AND l.date <= :date GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate ORDER BY spotter_live.date DESC';
526
                $date = date('c',$date);
527
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
528
529
		return $spotter_array;
530
	}
531
532
        /**
533
	* Gets altitude information based on a particular callsign
534
	*
535
	* @return Array the spotter information
536
	*
537
	*/
538
	public function getAltitudeLiveSpotterDataByIdent($ident)
539
	{
540
541
		date_default_timezone_set('UTC');
542
543
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
544
                $query  = 'SELECT spotter_live.altitude, spotter_live.date FROM spotter_live WHERE spotter_live.ident = :ident';
545
546
    		try {
547
			
548
			$sth = $this->db->prepare($query);
549
			$sth->execute(array(':ident' => $ident));
550
		} catch(PDOException $e) {
551
			echo $e->getMessage();
552
			die;
553
		}
554
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
555
556
		return $spotter_array;
557
	}
558
559
        /**
560
	* Gets all the spotter information based on a particular id
561
	*
562
	* @return Array the spotter information
563
	*
564
	*/
565
	public function getAllLiveSpotterDataById($id,$liveinterval = false)
566
	{
567
		global $globalDBdriver, $globalLiveInterval;
568
		date_default_timezone_set('UTC');
569
		$id = filter_var($id, FILTER_SANITIZE_STRING);
570
		//$query  = self::$global_query.' WHERE spotter_live.flightaware_id = :id ORDER BY date';
571
		if ($globalDBdriver == 'mysql') {
572
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
573
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
574
			$query .= ' ORDER BY date';
575
		} else {
576
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
577
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
578
			$query .= ' ORDER BY date';
579
		}
580
581
		try {
582
			$sth = $this->db->prepare($query);
583
			$sth->execute(array(':id' => $id));
584
		} catch(PDOException $e) {
585
			echo $e->getMessage();
586
			die;
587
		}
588
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
589
		return $spotter_array;
590
	}
591
592
        /**
593
	* Gets all the spotter information based on a particular ident
594
	*
595
	* @return Array the spotter information
596
	*
597
	*/
598
	public function getAllLiveSpotterDataByIdent($ident)
599
	{
600
		date_default_timezone_set('UTC');
601
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
602
		$query  = self::$global_query.' WHERE spotter_live.ident = :ident';
603
    		try {
604
			
605
			$sth = $this->db->prepare($query);
606
			$sth->execute(array(':ident' => $ident));
607
		} catch(PDOException $e) {
608
			echo $e->getMessage();
609
			die;
610
		}
611
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
612
		return $spotter_array;
613
	}
614
615
616
	/**
617
	* Deletes all info in the table
618
	*
619
	* @return String success or false
620
	*
621
	*/
622
	public function deleteLiveSpotterData()
623
	{
624
		global $globalDBdriver;
625
		if ($globalDBdriver == 'mysql') {
626
			//$query  = "DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= spotter_live.date";
627
			$query  = 'DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= spotter_live.date';
628
            		//$query  = "DELETE FROM spotter_live WHERE spotter_live.id IN (SELECT spotter_live.id FROM spotter_live INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate FROM spotter_live l GROUP BY l.flightaware_id) s on spotter_live.flightaware_id = s.flightaware_id AND spotter_live.date = s.maxdate AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) >= spotter_live.date)";
629
		} else {
630
			$query  = "DELETE FROM spotter_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= spotter_live.date";
631
		}
632
        
633
    		try {
634
			
635
			$sth = $this->db->prepare($query);
636
			$sth->execute();
637
		} catch(PDOException $e) {
638
			return "error";
639
		}
640
641
		return "success";
642
	}
643
644
	/**
645
	* Deletes all info in the table for aircraft not seen since 2 HOUR
646
	*
647
	* @return String success or false
648
	*
649
	*/
650
	public function deleteLiveSpotterDataNotUpdated()
651
	{
652
		global $globalDBdriver, $globalDebug;
653
		if ($globalDBdriver == 'mysql') {
654
			//$query = 'SELECT flightaware_id FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) >= spotter_live.date AND spotter_live.flightaware_id NOT IN (SELECT flightaware_id FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) < spotter_live.date) LIMIT 800 OFFSET 0';
655
    			$query = "SELECT spotter_live.flightaware_id FROM spotter_live INNER JOIN (SELECT flightaware_id,MAX(date) as max_date FROM spotter_live GROUP BY flightaware_id) s ON s.flightaware_id = spotter_live.flightaware_id AND DATE_SUB(UTC_TIMESTAMP(), INTERVAL 2 HOUR) >= s.max_date LIMIT 2000 OFFSET 0";
656
    			try {
657
				
658
				$sth = $this->db->prepare($query);
659
				$sth->execute();
660
			} catch(PDOException $e) {
661
				return "error";
662
			}
663
			$query_delete = 'DELETE FROM spotter_live WHERE flightaware_id IN (';
664
                        $i = 0;
665
                        $j =0;
666
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
667
			foreach($all as $row)
668
			{
669
				$i++;
670
				$j++;
671
				if ($j == 30) {
672
					if ($globalDebug) echo ".";
673
				    	try {
674
						
675
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
676
						$sth->execute();
677
					} catch(PDOException $e) {
678
						return "error";
679
					}
680
                                	$query_delete = 'DELETE FROM spotter_live WHERE flightaware_id IN (';
681
                                	$j = 0;
682
				}
683
				$query_delete .= "'".$row['flightaware_id']."',";
684
			}
685
			if ($i > 0) {
686
    				try {
687
					
688
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
689
					$sth->execute();
690
				} catch(PDOException $e) {
691
					return "error";
692
				}
693
			}
694
			return "success";
695
		} elseif ($globalDBdriver == 'pgsql') {
696
			//$query = "SELECT flightaware_id FROM spotter_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= spotter_live.date AND spotter_live.flightaware_id NOT IN (SELECT flightaware_id FROM spotter_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' < spotter_live.date) LIMIT 800 OFFSET 0";
697
    			//$query = "SELECT spotter_live.flightaware_id FROM spotter_live INNER JOIN (SELECT flightaware_id,MAX(date) as max_date FROM spotter_live GROUP BY flightaware_id) s ON s.flightaware_id = spotter_live.flightaware_id AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0";
698
    			$query = "DELETE FROM spotter_live WHERE flightaware_id IN (SELECT spotter_live.flightaware_id FROM spotter_live INNER JOIN (SELECT flightaware_id,MAX(date) as max_date FROM spotter_live GROUP BY flightaware_id) s ON s.flightaware_id = spotter_live.flightaware_id AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 2000 OFFSET 0)";
699
    			try {
700
				
701
				$sth = $this->db->prepare($query);
702
				$sth->execute();
703
			} catch(PDOException $e) {
704
				return "error";
705
			}
706
/*			$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
707
                        $i = 0;
708
                        $j =0;
709
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
710
			foreach($all as $row)
711
			{
712
				$i++;
713
				$j++;
714
				if ($j == 100) {
715
					if ($globalDebug) echo ".";
716
				    	try {
717
						
718
						$sth = $this->db->query(substr($query_delete,0,-1).")");
719
						//$sth->execute();
720
					} catch(PDOException $e) {
721
						return "error";
722
					}
723
                                	$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
724
                                	$j = 0;
725
				}
726
				$query_delete .= "'".$row['flightaware_id']."',";
727
			}
728
			if ($i > 0) {
729
    				try {
730
					
731
					$sth = $this->db->query(substr($query_delete,0,-1).")");
732
					//$sth->execute();
733
				} catch(PDOException $e) {
734
					return "error";
735
				}
736
			}
737
*/
738
			return "success";
739
		}
740
	}
741
742
	/**
743
	* Deletes all info in the table for an ident
744
	*
745
	* @return String success or false
746
	*
747
	*/
748
	public function deleteLiveSpotterDataByIdent($ident)
749
	{
750
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
751
		$query  = 'DELETE FROM spotter_live WHERE ident = :ident';
752
        
753
    		try {
754
			
755
			$sth = $this->db->prepare($query);
756
			$sth->execute(array(':ident' => $ident));
757
		} catch(PDOException $e) {
758
			return "error";
759
		}
760
761
		return "success";
762
	}
763
764
	/**
765
	* Deletes all info in the table for an id
766
	*
767
	* @return String success or false
768
	*
769
	*/
770
	public function deleteLiveSpotterDataById($id)
771
	{
772
		$id = filter_var($id, FILTER_SANITIZE_STRING);
773
		$query  = 'DELETE FROM spotter_live WHERE flightaware_id = :id';
774
        
775
    		try {
776
			
777
			$sth = $this->db->prepare($query);
778
			$sth->execute(array(':id' => $id));
779
		} catch(PDOException $e) {
780
			return "error";
781
		}
782
783
		return "success";
784
	}
785
786
787
	/**
788
	* Gets the aircraft ident within the last hour
789
	*
790
	* @return String the ident
791
	*
792
	*/
793
	public function getIdentFromLastHour($ident)
794
	{
795
		global $globalDBdriver, $globalTimezone;
796
		if ($globalDBdriver == 'mysql') {
797
			$query  = 'SELECT spotter_live.ident FROM spotter_live 
798
				WHERE spotter_live.ident = :ident 
799
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
800
				AND spotter_live.date < UTC_TIMESTAMP()';
801
			$query_data = array(':ident' => $ident);
802
		} else {
803
			$query  = "SELECT spotter_live.ident FROM spotter_live 
804
				WHERE spotter_live.ident = :ident 
805
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
806
				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
807
			$query_data = array(':ident' => $ident);
808
		}
809
		
810
		$sth = $this->db->prepare($query);
811
		$sth->execute($query_data);
812
		$ident_result='';
813
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
814
		{
815
			$ident_result = $row['ident'];
816
		}
817
		return $ident_result;
818
        }
819
820
	/**
821
	* Check recent aircraft
822
	*
823
	* @return String the ident
824
	*
825
	*/
826
	public function checkIdentRecent($ident)
827
	{
828
		global $globalDBdriver, $globalTimezone;
829
		if ($globalDBdriver == 'mysql') {
830
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
831
				WHERE spotter_live.ident = :ident 
832
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
833
//				AND spotter_live.date < UTC_TIMESTAMP()";
834
			$query_data = array(':ident' => $ident);
835
		} else {
836
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
837
				WHERE spotter_live.ident = :ident 
838
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
839
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
840
			$query_data = array(':ident' => $ident);
841
		}
842
		
843
		$sth = $this->db->prepare($query);
844
		$sth->execute($query_data);
845
		$ident_result='';
846
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
847
		{
848
			$ident_result = $row['flightaware_id'];
849
		}
850
		return $ident_result;
851
        }
852
853
	/**
854
	* Check recent aircraft by id
855
	*
856
	* @return String the ident
857
	*
858
	*/
859
	public function checkIdRecent($id)
860
	{
861
		global $globalDBdriver, $globalTimezone;
862
		if ($globalDBdriver == 'mysql') {
863
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
864
				WHERE spotter_live.flightaware_id = :id 
865
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
866
//				AND spotter_live.date < UTC_TIMESTAMP()";
867
			$query_data = array(':id' => $id);
868
		} else {
869
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
870
				WHERE spotter_live.flightaware_id = :id 
871
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
872
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
873
			$query_data = array(':id' => $id);
874
		}
875
		
876
		$sth = $this->db->prepare($query);
877
		$sth->execute($query_data);
878
		$ident_result='';
879
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
880
		{
881
			$ident_result = $row['flightaware_id'];
882
		}
883
		return $ident_result;
884
        }
885
886
	/**
887
	* Check recent aircraft by ModeS
888
	*
889
	* @return String the ModeS
890
	*
891
	*/
892
	public function checkModeSRecent($modes)
893
	{
894
		global $globalDBdriver, $globalTimezone;
895
		if ($globalDBdriver == 'mysql') {
896
			$query  = 'SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
897
				WHERE spotter_live.ModeS = :modes 
898
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
899
//				AND spotter_live.date < UTC_TIMESTAMP()";
900
			$query_data = array(':modes' => $modes);
901
		} else {
902
			$query  = "SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
903
				WHERE spotter_live.ModeS = :modes 
904
				AND spotter_live.date >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 MINUTE'";
905
//			//	AND spotter_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
906
			$query_data = array(':modes' => $modes);
907
		}
908
		
909
		$sth = $this->db->prepare($query);
910
		$sth->execute($query_data);
911
		$ident_result='';
912
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
913
		{
914
			//$ident_result = $row['spotter_live_id'];
915
			$ident_result = $row['flightaware_id'];
916
		}
917
		return $ident_result;
918
        }
919
920
	/**
921
	* Adds a new spotter data
922
	*
923
	* @param String $flightaware_id the ID from flightaware
924
	* @param String $ident the flight ident
925
	* @param String $aircraft_icao the aircraft type
926
	* @param String $departure_airport_icao the departure airport
927
	* @param String $arrival_airport_icao the arrival airport
928
	* @return String success or false
929
	*
930
	*/
931
	public function addLiveSpotterData($flightaware_id = '', $ident = '', $aircraft_icao = '', $departure_airport_icao = '', $arrival_airport_icao = '', $latitude = '', $longitude = '', $waypoints = '', $altitude = '', $altitude_real = '',$heading = '', $groundspeed = '', $date = '',$departure_airport_time = '', $arrival_airport_time = '', $squawk = '', $route_stop = '', $ModeS = '', $putinarchive = false,$registration = '',$pilot_id = '', $pilot_name = '', $verticalrate = '', $noarchive = false, $ground = false,$format_source = '', $source_name = '', $over_country = '')
0 ignored issues
show
Unused Code introduced by
The parameter $altitude_real 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...
932
	{
933
		global $globalURL, $globalArchive, $globalDebug;
934
		$Common = new Common();
935
		date_default_timezone_set('UTC');
936
937
		//getting the airline information
938
		if ($ident != '')
939
		{
940
			if (!is_string($ident))
941
			{
942
				return false;
943
			} 
944
		}
945
946
		//getting the aircraft information
947
		if ($aircraft_icao != '')
948
		{
949
			if (!is_string($aircraft_icao))
950
			{
951
				return false;
952
			} 
953
		} 
954
		//getting the departure airport information
955
		if ($departure_airport_icao != '')
956
		{
957
			if (!is_string($departure_airport_icao))
958
			{
959
				return false;
960
			} 
961
		}
962
963
		//getting the arrival airport information
964
		if ($arrival_airport_icao != '')
965
		{
966
			if (!is_string($arrival_airport_icao))
967
			{
968
				return false;
969
			}
970
		}
971
972
973
		if ($latitude != '')
974
		{
975
			if (!is_numeric($latitude))
976
			{
977
				return false;
978
			}
979
		} else return '';
980
981
		if ($longitude != '')
982
		{
983
			if (!is_numeric($longitude))
984
			{
985
				return false;
986
			}
987
		} else return '';
988
989
		if ($waypoints != '')
990
		{
991
			if (!is_string($waypoints))
992
			{
993
				return false;
994
			}
995
		}
996
997
		if ($altitude != '')
998
		{
999
			if (!is_numeric($altitude))
1000
			{
1001
				return false;
1002
			}
1003
		} else $altitude = 0;
1004
1005
		if ($heading != '')
1006
		{
1007
			if (!is_numeric($heading))
1008
			{
1009
				return false;
1010
			}
1011
		} else $heading = 0;
1012
1013
		if ($groundspeed != '')
1014
		{
1015
			if (!is_numeric($groundspeed))
1016
			{
1017
				return false;
1018
			}
1019
		} else $groundspeed = 0;
1020
		date_default_timezone_set('UTC');
1021
		if ($date == '') $date = date("Y-m-d H:i:s", time());
1022
1023
        
1024
		$flightaware_id = filter_var($flightaware_id,FILTER_SANITIZE_STRING);
1025
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1026
		$aircraft_icao = filter_var($aircraft_icao,FILTER_SANITIZE_STRING);
1027
		$departure_airport_icao = filter_var($departure_airport_icao,FILTER_SANITIZE_STRING);
1028
		$arrival_airport_icao = filter_var($arrival_airport_icao,FILTER_SANITIZE_STRING);
1029
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1030
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1031
		$waypoints = filter_var($waypoints,FILTER_SANITIZE_STRING);
1032
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1033
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
1034
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1035
		$squawk = filter_var($squawk,FILTER_SANITIZE_NUMBER_INT);
1036
		$route_stop = filter_var($route_stop,FILTER_SANITIZE_STRING);
1037
		$ModeS = filter_var($ModeS,FILTER_SANITIZE_STRING);
1038
		$pilot_id = filter_var($pilot_id,FILTER_SANITIZE_STRING);
1039
		$pilot_name = filter_var($pilot_name,FILTER_SANITIZE_STRING);
1040
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
1041
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
1042
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
1043
		$verticalrate = filter_var($verticalrate,FILTER_SANITIZE_NUMBER_INT);
1044
1045
		$airline_name = '';
1046
		$airline_icao = '';
1047
		$airline_country = '';
1048
		$airline_type = '';
1049
		$aircraft_shadow = '';
1050
		$aircraft_type = '';
1051
		$aircraft_manufacturer = '';
1052
1053
1054
1055
		$aircraft_name = '';
1056
		$departure_airport_name = '';
1057
		$departure_airport_city = '';
1058
		$departure_airport_country = '';
1059
		
1060
		$arrival_airport_name = '';
1061
		$arrival_airport_city = '';
1062
		$arrival_airport_country = '';
1063
		
1064
            	
1065
            	if ($squawk == '' || $Common->isInteger($squawk) === false ) $squawk = NULL;
1066
            	if ($verticalrate == '' || $Common->isInteger($verticalrate) === false ) $verticalrate = NULL;
1067
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
1068
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
1069
		
1070
		$query = '';
1071
		if ($globalArchive) {
1072
			if ($globalDebug) echo '-- Delete previous data -- ';
1073
			$query .= 'DELETE FROM spotter_live WHERE flightaware_id = :flightaware_id;';
1074
		}
1075
1076
		$query  .= 'INSERT INTO spotter_live (flightaware_id, ident, registration, airline_name, airline_icao, airline_country, airline_type, aircraft_icao, aircraft_shadow, aircraft_name, aircraft_manufacturer, departure_airport_icao, departure_airport_name, departure_airport_city, departure_airport_country, arrival_airport_icao, arrival_airport_name, arrival_airport_city, arrival_airport_country, latitude, longitude, waypoints, altitude, heading, ground_speed, date, departure_airport_time, arrival_airport_time, squawk, route_stop, ModeS, pilot_id, pilot_name, verticalrate, ground, format_source, source_name, over_country) 
1077
		VALUES (:flightaware_id,:ident,:registration,:airline_name,:airline_icao,:airline_country,:airline_type,:aircraft_icao,:aircraft_shadow,:aircraft_type,:aircraft_manufacturer,:departure_airport_icao,:departure_airport_name, :departure_airport_city, :departure_airport_country, :arrival_airport_icao, :arrival_airport_name, :arrival_airport_city, :arrival_airport_country, :latitude,:longitude,:waypoints,:altitude,:heading,:groundspeed,:date,:departure_airport_time,:arrival_airport_time,:squawk,:route_stop,:ModeS, :pilot_id, :pilot_name, :verticalrate, :ground, :format_source, :source_name, :over_country)';
1078
1079
		$query_values = array(':flightaware_id' => $flightaware_id,':ident' => $ident, ':registration' => $registration,':airline_name' => $airline_name,':airline_icao' => $airline_icao,':airline_country' => $airline_country,':airline_type' => $airline_type,':aircraft_icao' => $aircraft_icao,':aircraft_shadow' => $aircraft_shadow,':aircraft_type' => $aircraft_type,':aircraft_manufacturer' => $aircraft_manufacturer,':departure_airport_icao' => $departure_airport_icao,':departure_airport_name' => $departure_airport_name,':departure_airport_city' => $departure_airport_city,':departure_airport_country' => $departure_airport_country,':arrival_airport_icao' => $arrival_airport_icao,':arrival_airport_name' => $arrival_airport_name,':arrival_airport_city' => $arrival_airport_city,':arrival_airport_country' => $arrival_airport_country,':latitude' => $latitude,':longitude' => $longitude, ':waypoints' => $waypoints,':altitude' => $altitude,':heading' => $heading,':groundspeed' => $groundspeed,':date' => $date, ':departure_airport_time' => $departure_airport_time,':arrival_airport_time' => $arrival_airport_time, ':squawk' => $squawk,':route_stop' => $route_stop,':ModeS' => $ModeS, ':pilot_id' => $pilot_id, ':pilot_name' => $pilot_name, ':verticalrate' => $verticalrate, ':format_source' => $format_source,':ground' => $ground, ':source_name' => $source_name, ':over_country' => $over_country);
1080
		try {
1081
			
1082
			$sth = $this->db->prepare($query);
1083
			$sth->execute($query_values);
1084
			$sth->closeCursor();
1085
		} catch(PDOException $e) {
1086
			return "error : ".$e->getMessage();
1087
		}
1088
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
1089
		    if ($globalDebug) echo '(Add to SBS archive : ';
1090
		    $SpotterArchive = new SpotterArchive($this->db);
1091
		    $result =  $SpotterArchive->addSpotterArchiveData($flightaware_id, $ident, $registration, $airline_name, $airline_icao, $airline_country, $airline_type, $aircraft_icao, $aircraft_shadow, $aircraft_name, $aircraft_manufacturer, $departure_airport_icao, $departure_airport_name, $departure_airport_city, $departure_airport_country, $departure_airport_time,$arrival_airport_icao, $arrival_airport_name, $arrival_airport_city, $arrival_airport_country, $arrival_airport_time, $route_stop, $date,$latitude, $longitude, $waypoints, $altitude, $heading, $groundspeed, $squawk, $ModeS, $pilot_id, $pilot_name,$verticalrate,$format_source,$source_name, $over_country);
1092
		    if ($globalDebug) echo $result.')';
1093
		}
1094
		return "success";
1095
1096
	}
1097
1098
	public function getOrderBy()
1099
	{
1100
		$orderby = array("aircraft_asc" => array("key" => "aircraft_asc", "value" => "Aircraft Type - ASC", "sql" => "ORDER BY spotter_live.aircraft_icao ASC"), "aircraft_desc" => array("key" => "aircraft_desc", "value" => "Aircraft Type - DESC", "sql" => "ORDER BY spotter_live.aircraft_icao DESC"),"manufacturer_asc" => array("key" => "manufacturer_asc", "value" => "Aircraft Manufacturer - ASC", "sql" => "ORDER BY spotter_live.aircraft_manufacturer ASC"), "manufacturer_desc" => array("key" => "manufacturer_desc", "value" => "Aircraft Manufacturer - DESC", "sql" => "ORDER BY spotter_live.aircraft_manufacturer DESC"),"airline_name_asc" => array("key" => "airline_name_asc", "value" => "Airline Name - ASC", "sql" => "ORDER BY spotter_live.airline_name ASC"), "airline_name_desc" => array("key" => "airline_name_desc", "value" => "Airline Name - DESC", "sql" => "ORDER BY spotter_live.airline_name DESC"), "ident_asc" => array("key" => "ident_asc", "value" => "Ident - ASC", "sql" => "ORDER BY spotter_live.ident ASC"), "ident_desc" => array("key" => "ident_desc", "value" => "Ident - DESC", "sql" => "ORDER BY spotter_live.ident DESC"), "airport_departure_asc" => array("key" => "airport_departure_asc", "value" => "Departure Airport - ASC", "sql" => "ORDER BY spotter_live.departure_airport_city ASC"), "airport_departure_desc" => array("key" => "airport_departure_desc", "value" => "Departure Airport - DESC", "sql" => "ORDER BY spotter_live.departure_airport_city DESC"), "airport_arrival_asc" => array("key" => "airport_arrival_asc", "value" => "Arrival Airport - ASC", "sql" => "ORDER BY spotter_live.arrival_airport_city ASC"), "airport_arrival_desc" => array("key" => "airport_arrival_desc", "value" => "Arrival Airport - DESC", "sql" => "ORDER BY spotter_live.arrival_airport_city DESC"), "date_asc" => array("key" => "date_asc", "value" => "Date - ASC", "sql" => "ORDER BY spotter_live.date ASC"), "date_desc" => array("key" => "date_desc", "value" => "Date - DESC", "sql" => "ORDER BY spotter_live.date DESC"));
1101
		return $orderby;
1102
	}
1103
1104
}
1105
1106
1107
?>
1108