Completed
Push — master ( aba7aa...4c247d )
by Yannick
07:22
created

SpotterLive::getMinLiveSpotterData()   C

Complexity

Conditions 8
Paths 24

Size

Total Lines 34
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 27
nc 24
nop 1
dl 0
loc 34
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;
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
/*
233
			$query  = 'SELECT a.aircraft_shadow, a.engine_type, a.engine_count, a.wake_category, 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 
234
			FROM spotter_live LEFT JOIN (SELECT aircraft_shadow,engine_type, engine_count, wake_category,icao FROM aircraft) a ON spotter_live.aircraft_icao = a.icao'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= spotter_live.date AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
235
			ORDER BY spotter_live.flightaware_id, spotter_live.date";
236
*/
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
                } else {
241
/*
242
			$query  = "SELECT a.aircraft_shadow, a.engine_type, a.engine_count, a.wake_category, 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 
243
			FROM spotter_live LEFT JOIN (SELECT aircraft_shadow,engine_type, engine_count, wake_category, icao FROM aircraft) a ON spotter_live.aircraft_icao = a.icao".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
244
			ORDER BY spotter_live.flightaware_id, spotter_live.date";
245
*/
246
			$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 
247
			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' 
248
			ORDER BY spotter_live.flightaware_id, spotter_live.date";
249
//			echo $query;
250
		}
251
252
    		try {
253
			$sth = $this->db->prepare($query);
254
			$sth->execute();
255
		} catch(PDOException $e) {
256
			echo $e->getMessage();
257
			die;
258
		}
259
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
260
		return $spotter_array;
261
	}
262
263
	/**
264
	* Gets number of latest data entry
265
	*
266
	* @return String number of entry
267
	*
268
	*/
269
	public function getLiveSpotterCount($filter = array())
270
	{
271
		global $globalDBdriver, $globalLiveInterval;
272
		$filter_query = $this->getFilter($filter,true,true);
273
274
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
275
		if ($globalDBdriver == 'mysql') {
276
			//$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;
277
			$query = 'SELECT COUNT(DISTINCT spotter_live.flightaware_id) as nb FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
278
		} else {
279
			//$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;
280
			$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";
281
		}
282
		try {
283
			$sth = $this->db->prepare($query);
284
			$sth->execute();
285
		} catch(PDOException $e) {
286
			echo $e->getMessage();
287
			die;
288
		}
289
		$result = $sth->fetch(PDO::FETCH_ASSOC);
290
		$sth->closeCursor();
291
		return $result['nb'];
292
	}
293
294
	/**
295
	* Gets all the spotter information based on the latest data entry and coord
296
	*
297
	* @return Array the spotter information
298
	*
299
	*/
300
	public function getLiveSpotterDatabyCoord($coord, $filter = array())
301
	{
302
		global $globalDBdriver, $globalLiveInterval;
303
		$Spotter = new Spotter($this->db);
304
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
305
		$filter_query = $this->getFilter($filter);
306
307
		if (is_array($coord)) {
308
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
309
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
310
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
311
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
312
		} else return array();
313
		if ($globalDBdriver == 'mysql') {
314
			$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;
315
		} else {
316
			$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;
317
318
		}
319
		$spotter_array = $Spotter->getDataFromDB($query);
320
		return $spotter_array;
321
	}
322
323
	/**
324
	* Gets all the spotter information based on the latest data entry and coord
325
	*
326
	* @return Array the spotter information
327
	*
328
	*/
329
	public function getMinLiveSpotterDatabyCoord($coord, $filter = array())
330
	{
331
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
332
		$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...
333
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
334
		$filter_query = $this->getFilter($filter,true,true);
335
336
		if (is_array($coord)) {
337
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
338
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
339
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
340
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
341
		} else return array();
342
		if ($globalDBdriver == 'mysql') {
343
			if (isset($globalArchive) && $globalArchive === TRUE) {
344
				$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 
345
				FROM spotter_live 
346
				'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= spotter_live.date 
347
				AND spotter_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND spotter_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
348
				AND spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
349
			} else {
350
				$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 
351
				FROM spotter_live 
352
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
353
				    FROM spotter_live l 
354
				    WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
355
				    AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
356
				    GROUP BY l.flightaware_id
357
				) s on spotter_live.flightaware_id = s.flightaware_id 
358
				AND spotter_live.date = s.maxdate'.$filter_query.' spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
359
			}
360
		} else {
361
			if (isset($globalArchive) && $globalArchive === TRUE) {
362
				$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 
363
				FROM spotter_live 
364
				".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date 
365
				AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
366
				AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
367
				AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
368
			} else {
369
				$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 
370
				FROM spotter_live 
371
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
372
				    FROM spotter_live l 
373
				    WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
374
				    AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
375
				    AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
376
				    GROUP BY l.flightaware_id
377
				) s on spotter_live.flightaware_id = s.flightaware_id 
378
				AND spotter_live.date = s.maxdate".$filter_query." spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
379
			}
380
		}
381
		try {
382
			$sth = $this->db->prepare($query);
383
			$sth->execute();
384
		} catch(PDOException $e) {
385
			echo $e->getMessage();
386
			die;
387
		}
388
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
389
		return $spotter_array;
390
	}
391
392
	/**
393
	* Gets all the spotter information based on a user's latitude and longitude
394
	*
395
	* @return Array the spotter information
396
	*
397
	*/
398
	public function getLatestSpotterForLayar($lat, $lng, $radius, $interval)
399
	{
400
		$Spotter = new Spotter($this->db);
401
		date_default_timezone_set('UTC');
402
		if ($lat != '') {
403
			if (!is_numeric($lat)) {
404
				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...
405
			}
406
		}
407
        if ($lng != '')
408
                {
409
                        if (!is_numeric($lng))
410
                        {
411
                                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...
412
                        }
413
                }
414
415
                if ($radius != '')
416
                {
417
                        if (!is_numeric($radius))
418
                        {
419
                                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...
420
                        }
421
                }
422
		$additional_query = '';
423
        if ($interval != '')
424
                {
425
                        if (!is_string($interval))
426
                        {
427
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
428
			        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...
429
                        } else {
430
                if ($interval == '1m')
431
                {
432
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
433
                } else if ($interval == '15m'){
434
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= spotter_live.date ';
435
                } 
436
            }
437
                } else {
438
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';   
439
        }
440
441
                $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 
442
                   WHERE spotter_live.latitude <> '' 
443
                                   AND spotter_live.longitude <> '' 
444
                   ".$additional_query."
445
                   HAVING distance < :radius  
446
                                   ORDER BY distance";
447
448
                $spotter_array = $Spotter->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
449
450
                return $spotter_array;
451
        }
452
453
    
454
        /**
455
	* Gets all the spotter information based on a particular callsign
456
	*
457
	* @return Array the spotter information
458
	*
459
	*/
460
	public function getLastLiveSpotterDataByIdent($ident)
461
	{
462
		$Spotter = new Spotter($this->db);
463
		date_default_timezone_set('UTC');
464
465
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
466
                $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';
467
468
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident),'',true);
469
470
		return $spotter_array;
471
	}
472
473
        /**
474
	* Gets all the spotter information based on a particular callsign
475
	*
476
	* @return Array the spotter information
477
	*
478
	*/
479
	public function getDateLiveSpotterDataByIdent($ident,$date)
480
	{
481
		$Spotter = new Spotter($this->db);
482
		date_default_timezone_set('UTC');
483
484
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
485
                $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';
486
487
                $date = date('c',$date);
488
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
489
490
		return $spotter_array;
491
	}
492
493
        /**
494
	* Gets last spotter information based on a particular callsign
495
	*
496
	* @return Array the spotter information
497
	*
498
	*/
499
	public function getLastLiveSpotterDataById($id)
500
	{
501
		$Spotter = new Spotter($this->db);
502
		date_default_timezone_set('UTC');
503
504
		$id = filter_var($id, FILTER_SANITIZE_STRING);
505
                $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';
506
507
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id),'',true);
508
509
		return $spotter_array;
510
	}
511
512
        /**
513
	* Gets last spotter information based on a particular callsign
514
	*
515
	* @return Array the spotter information
516
	*
517
	*/
518
	public function getDateLiveSpotterDataById($id,$date)
519
	{
520
		$Spotter = new Spotter($this->db);
521
		date_default_timezone_set('UTC');
522
523
		$id = filter_var($id, FILTER_SANITIZE_STRING);
524
                $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';
525
                $date = date('c',$date);
526
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
527
528
		return $spotter_array;
529
	}
530
531
        /**
532
	* Gets altitude information based on a particular callsign
533
	*
534
	* @return Array the spotter information
535
	*
536
	*/
537
	public function getAltitudeLiveSpotterDataByIdent($ident)
538
	{
539
540
		date_default_timezone_set('UTC');
541
542
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
543
                $query  = 'SELECT spotter_live.altitude, spotter_live.date FROM spotter_live WHERE spotter_live.ident = :ident';
544
545
    		try {
546
			
547
			$sth = $this->db->prepare($query);
548
			$sth->execute(array(':ident' => $ident));
549
		} catch(PDOException $e) {
550
			echo $e->getMessage();
551
			die;
552
		}
553
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
554
555
		return $spotter_array;
556
	}
557
558
        /**
559
	* Gets all the spotter information based on a particular id
560
	*
561
	* @return Array the spotter information
562
	*
563
	*/
564
	public function getAllLiveSpotterDataById($id,$liveinterval = false)
565
	{
566
		global $globalDBdriver, $globalLiveInterval;
567
		date_default_timezone_set('UTC');
568
		$id = filter_var($id, FILTER_SANITIZE_STRING);
569
		//$query  = self::$global_query.' WHERE spotter_live.flightaware_id = :id ORDER BY date';
570
		if ($globalDBdriver == 'mysql') {
571
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
572
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
573
			$query .= ' ORDER BY date';
574
		} else {
575
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
576
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
577
			$query .= ' ORDER BY date';
578
		}
579
580
		try {
581
			$sth = $this->db->prepare($query);
582
			$sth->execute(array(':id' => $id));
583
		} catch(PDOException $e) {
584
			echo $e->getMessage();
585
			die;
586
		}
587
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
588
		return $spotter_array;
589
	}
590
591
        /**
592
	* Gets all the spotter information based on a particular ident
593
	*
594
	* @return Array the spotter information
595
	*
596
	*/
597
	public function getAllLiveSpotterDataByIdent($ident)
598
	{
599
		date_default_timezone_set('UTC');
600
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
601
		$query  = self::$global_query.' WHERE spotter_live.ident = :ident';
602
    		try {
603
			
604
			$sth = $this->db->prepare($query);
605
			$sth->execute(array(':ident' => $ident));
606
		} catch(PDOException $e) {
607
			echo $e->getMessage();
608
			die;
609
		}
610
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
611
		return $spotter_array;
612
	}
613
614
615
	/**
616
	* Deletes all info in the table
617
	*
618
	* @return String success or false
619
	*
620
	*/
621
	public function deleteLiveSpotterData()
622
	{
623
		global $globalDBdriver;
624
		if ($globalDBdriver == 'mysql') {
625
			//$query  = "DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= spotter_live.date";
626
			$query  = 'DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= spotter_live.date';
627
            		//$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)";
628
		} else {
629
			$query  = "DELETE FROM spotter_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= spotter_live.date";
630
		}
631
        
632
    		try {
633
			
634
			$sth = $this->db->prepare($query);
635
			$sth->execute();
636
		} catch(PDOException $e) {
637
			return "error";
638
		}
639
640
		return "success";
641
	}
642
643
	/**
644
	* Deletes all info in the table for aircraft not seen since 2 HOUR
645
	*
646
	* @return String success or false
647
	*
648
	*/
649
	public function deleteLiveSpotterDataNotUpdated()
650
	{
651
		global $globalDBdriver, $globalDebug;
652
		if ($globalDBdriver == 'mysql') {
653
			//$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';
654
    			$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";
655
    			try {
656
				
657
				$sth = $this->db->prepare($query);
658
				$sth->execute();
659
			} catch(PDOException $e) {
660
				return "error";
661
			}
662
			$query_delete = 'DELETE FROM spotter_live WHERE flightaware_id IN (';
663
                        $i = 0;
664
                        $j =0;
665
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
666
			foreach($all as $row)
667
			{
668
				$i++;
669
				$j++;
670
				if ($j == 30) {
671
					if ($globalDebug) echo ".";
672
				    	try {
673
						
674
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
675
						$sth->execute();
676
					} catch(PDOException $e) {
677
						return "error";
678
					}
679
                                	$query_delete = 'DELETE FROM spotter_live WHERE flightaware_id IN (';
680
                                	$j = 0;
681
				}
682
				$query_delete .= "'".$row['flightaware_id']."',";
683
			}
684
			if ($i > 0) {
685
    				try {
686
					
687
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
688
					$sth->execute();
689
				} catch(PDOException $e) {
690
					return "error";
691
				}
692
			}
693
			return "success";
694
		} elseif ($globalDBdriver == 'pgsql') {
695
			//$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";
696
    			//$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";
697
    			$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)";
698
    			try {
699
				
700
				$sth = $this->db->prepare($query);
701
				$sth->execute();
702
			} catch(PDOException $e) {
703
				return "error";
704
			}
705
/*			$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
706
                        $i = 0;
707
                        $j =0;
708
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
709
			foreach($all as $row)
710
			{
711
				$i++;
712
				$j++;
713
				if ($j == 100) {
714
					if ($globalDebug) echo ".";
715
				    	try {
716
						
717
						$sth = $this->db->query(substr($query_delete,0,-1).")");
718
						//$sth->execute();
719
					} catch(PDOException $e) {
720
						return "error";
721
					}
722
                                	$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
723
                                	$j = 0;
724
				}
725
				$query_delete .= "'".$row['flightaware_id']."',";
726
			}
727
			if ($i > 0) {
728
    				try {
729
					
730
					$sth = $this->db->query(substr($query_delete,0,-1).")");
731
					//$sth->execute();
732
				} catch(PDOException $e) {
733
					return "error";
734
				}
735
			}
736
*/
737
			return "success";
738
		}
739
	}
740
741
	/**
742
	* Deletes all info in the table for an ident
743
	*
744
	* @return String success or false
745
	*
746
	*/
747
	public function deleteLiveSpotterDataByIdent($ident)
748
	{
749
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
750
		$query  = 'DELETE FROM spotter_live WHERE ident = :ident';
751
        
752
    		try {
753
			
754
			$sth = $this->db->prepare($query);
755
			$sth->execute(array(':ident' => $ident));
756
		} catch(PDOException $e) {
757
			return "error";
758
		}
759
760
		return "success";
761
	}
762
763
	/**
764
	* Deletes all info in the table for an id
765
	*
766
	* @return String success or false
767
	*
768
	*/
769
	public function deleteLiveSpotterDataById($id)
770
	{
771
		$id = filter_var($id, FILTER_SANITIZE_STRING);
772
		$query  = 'DELETE FROM spotter_live WHERE flightaware_id = :id';
773
        
774
    		try {
775
			
776
			$sth = $this->db->prepare($query);
777
			$sth->execute(array(':id' => $id));
778
		} catch(PDOException $e) {
779
			return "error";
780
		}
781
782
		return "success";
783
	}
784
785
786
	/**
787
	* Gets the aircraft ident within the last hour
788
	*
789
	* @return String the ident
790
	*
791
	*/
792
	public function getIdentFromLastHour($ident)
793
	{
794
		global $globalDBdriver, $globalTimezone;
795
		if ($globalDBdriver == 'mysql') {
796
			$query  = 'SELECT spotter_live.ident FROM spotter_live 
797
				WHERE spotter_live.ident = :ident 
798
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
799
				AND spotter_live.date < UTC_TIMESTAMP()';
800
			$query_data = array(':ident' => $ident);
801
		} else {
802
			$query  = "SELECT spotter_live.ident FROM spotter_live 
803
				WHERE spotter_live.ident = :ident 
804
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
805
				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
806
			$query_data = array(':ident' => $ident);
807
		}
808
		
809
		$sth = $this->db->prepare($query);
810
		$sth->execute($query_data);
811
		$ident_result='';
812
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
813
		{
814
			$ident_result = $row['ident'];
815
		}
816
		return $ident_result;
817
        }
818
819
	/**
820
	* Check recent aircraft
821
	*
822
	* @return String the ident
823
	*
824
	*/
825
	public function checkIdentRecent($ident)
826
	{
827
		global $globalDBdriver, $globalTimezone;
828
		if ($globalDBdriver == 'mysql') {
829
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
830
				WHERE spotter_live.ident = :ident 
831
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
832
//				AND spotter_live.date < UTC_TIMESTAMP()";
833
			$query_data = array(':ident' => $ident);
834
		} else {
835
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
836
				WHERE spotter_live.ident = :ident 
837
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
838
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
839
			$query_data = array(':ident' => $ident);
840
		}
841
		
842
		$sth = $this->db->prepare($query);
843
		$sth->execute($query_data);
844
		$ident_result='';
845
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
846
		{
847
			$ident_result = $row['flightaware_id'];
848
		}
849
		return $ident_result;
850
        }
851
852
	/**
853
	* Check recent aircraft by id
854
	*
855
	* @return String the ident
856
	*
857
	*/
858
	public function checkIdRecent($id)
859
	{
860
		global $globalDBdriver, $globalTimezone;
861
		if ($globalDBdriver == 'mysql') {
862
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
863
				WHERE spotter_live.flightaware_id = :id 
864
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
865
//				AND spotter_live.date < UTC_TIMESTAMP()";
866
			$query_data = array(':id' => $id);
867
		} else {
868
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
869
				WHERE spotter_live.flightaware_id = :id 
870
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
871
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
872
			$query_data = array(':id' => $id);
873
		}
874
		
875
		$sth = $this->db->prepare($query);
876
		$sth->execute($query_data);
877
		$ident_result='';
878
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
879
		{
880
			$ident_result = $row['flightaware_id'];
881
		}
882
		return $ident_result;
883
        }
884
885
	/**
886
	* Check recent aircraft by ModeS
887
	*
888
	* @return String the ModeS
889
	*
890
	*/
891
	public function checkModeSRecent($modes)
892
	{
893
		global $globalDBdriver, $globalTimezone;
894
		if ($globalDBdriver == 'mysql') {
895
			$query  = 'SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
896
				WHERE spotter_live.ModeS = :modes 
897
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
898
//				AND spotter_live.date < UTC_TIMESTAMP()";
899
			$query_data = array(':modes' => $modes);
900
		} else {
901
			$query  = "SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
902
				WHERE spotter_live.ModeS = :modes 
903
				AND spotter_live.date >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 MINUTE'";
904
//			//	AND spotter_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
905
			$query_data = array(':modes' => $modes);
906
		}
907
		
908
		$sth = $this->db->prepare($query);
909
		$sth->execute($query_data);
910
		$ident_result='';
911
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
912
		{
913
			//$ident_result = $row['spotter_live_id'];
914
			$ident_result = $row['flightaware_id'];
915
		}
916
		return $ident_result;
917
        }
918
919
	/**
920
	* Adds a new spotter data
921
	*
922
	* @param String $flightaware_id the ID from flightaware
923
	* @param String $ident the flight ident
924
	* @param String $aircraft_icao the aircraft type
925
	* @param String $departure_airport_icao the departure airport
926
	* @param String $arrival_airport_icao the arrival airport
927
	* @return String success or false
928
	*
929
	*/
930
	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...
931
	{
932
		global $globalURL, $globalArchive, $globalDebug;
933
		$Common = new Common();
934
		date_default_timezone_set('UTC');
935
936
		//getting the airline information
937
		if ($ident != '')
938
		{
939
			if (!is_string($ident))
940
			{
941
				return false;
942
			} 
943
		}
944
945
		//getting the aircraft information
946
		if ($aircraft_icao != '')
947
		{
948
			if (!is_string($aircraft_icao))
949
			{
950
				return false;
951
			} 
952
		} 
953
		//getting the departure airport information
954
		if ($departure_airport_icao != '')
955
		{
956
			if (!is_string($departure_airport_icao))
957
			{
958
				return false;
959
			} 
960
		}
961
962
		//getting the arrival airport information
963
		if ($arrival_airport_icao != '')
964
		{
965
			if (!is_string($arrival_airport_icao))
966
			{
967
				return false;
968
			}
969
		}
970
971
972
		if ($latitude != '')
973
		{
974
			if (!is_numeric($latitude))
975
			{
976
				return false;
977
			}
978
		} else return '';
979
980
		if ($longitude != '')
981
		{
982
			if (!is_numeric($longitude))
983
			{
984
				return false;
985
			}
986
		} else return '';
987
988
		if ($waypoints != '')
989
		{
990
			if (!is_string($waypoints))
991
			{
992
				return false;
993
			}
994
		}
995
996
		if ($altitude != '')
997
		{
998
			if (!is_numeric($altitude))
999
			{
1000
				return false;
1001
			}
1002
		} else $altitude = 0;
1003
1004
		if ($heading != '')
1005
		{
1006
			if (!is_numeric($heading))
1007
			{
1008
				return false;
1009
			}
1010
		} else $heading = 0;
1011
1012
		if ($groundspeed != '')
1013
		{
1014
			if (!is_numeric($groundspeed))
1015
			{
1016
				return false;
1017
			}
1018
		} else $groundspeed = 0;
1019
		date_default_timezone_set('UTC');
1020
		if ($date == '') $date = date("Y-m-d H:i:s", time());
1021
1022
        
1023
		$flightaware_id = filter_var($flightaware_id,FILTER_SANITIZE_STRING);
1024
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1025
		$aircraft_icao = filter_var($aircraft_icao,FILTER_SANITIZE_STRING);
1026
		$departure_airport_icao = filter_var($departure_airport_icao,FILTER_SANITIZE_STRING);
1027
		$arrival_airport_icao = filter_var($arrival_airport_icao,FILTER_SANITIZE_STRING);
1028
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1029
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1030
		$waypoints = filter_var($waypoints,FILTER_SANITIZE_STRING);
1031
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1032
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
1033
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1034
		$squawk = filter_var($squawk,FILTER_SANITIZE_NUMBER_INT);
1035
		$route_stop = filter_var($route_stop,FILTER_SANITIZE_STRING);
1036
		$ModeS = filter_var($ModeS,FILTER_SANITIZE_STRING);
1037
		$pilot_id = filter_var($pilot_id,FILTER_SANITIZE_STRING);
1038
		$pilot_name = filter_var($pilot_name,FILTER_SANITIZE_STRING);
1039
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
1040
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
1041
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
1042
		$verticalrate = filter_var($verticalrate,FILTER_SANITIZE_NUMBER_INT);
1043
1044
		$airline_name = '';
1045
		$airline_icao = '';
1046
		$airline_country = '';
1047
		$airline_type = '';
1048
		$aircraft_shadow = '';
1049
		$aircraft_type = '';
1050
		$aircraft_manufacturer = '';
1051
1052
1053
1054
		$aircraft_name = '';
1055
		$departure_airport_name = '';
1056
		$departure_airport_city = '';
1057
		$departure_airport_country = '';
1058
		
1059
		$arrival_airport_name = '';
1060
		$arrival_airport_city = '';
1061
		$arrival_airport_country = '';
1062
		
1063
            	
1064
            	if ($squawk == '' || $Common->isInteger($squawk) === false ) $squawk = NULL;
1065
            	if ($verticalrate == '' || $Common->isInteger($verticalrate) === false ) $verticalrate = NULL;
1066
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
1067
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
1068
		
1069
		$query = '';
1070
		if ($globalArchive) {
1071
			if ($globalDebug) echo '-- Delete previous data -- ';
1072
			$query .= 'DELETE FROM spotter_live WHERE flightaware_id = :flightaware_id;';
1073
		}
1074
1075
		$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) 
1076
		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)';
1077
1078
		$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);
1079
		try {
1080
			
1081
			$sth = $this->db->prepare($query);
1082
			$sth->execute($query_values);
1083
			$sth->closeCursor();
1084
		} catch(PDOException $e) {
1085
			return "error : ".$e->getMessage();
1086
		}
1087
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
1088
		    if ($globalDebug) echo '(Add to SBS archive : ';
1089
		    $SpotterArchive = new SpotterArchive($this->db);
1090
		    $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);
1091
		    if ($globalDebug) echo $result.')';
1092
		}
1093
		return "success";
1094
1095
	}
1096
1097
	public function getOrderBy()
1098
	{
1099
		$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"));
1100
		return $orderby;
1101
	}
1102
1103
}
1104
1105
1106
?>
1107