Completed
Push — master ( 072036...f3a36a )
by Yannick
29:27
created

SpotterLive::getAllLiveSpotterDataById()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 12
nop 2
dl 0
loc 26
rs 8.439
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
		if ($this->db === null) die('Error: No DB connection. (SpotterLive)');
12
	}
13
14
15
	/**
16
	* Get SQL query part for filter used
17
	* @param Array $filter the filter
18
	* @return Array the SQL part
19
	*/
20
	public function getFilter($filter = array(),$where = false,$and = false) {
21
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
22
		$filters = array();
23
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
24
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
25
				$filters = $globalStatsFilters[$globalFilterName];
26
			} else {
27
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
28
			}
29
		}
30
		if (isset($filter[0]['source'])) {
31
			$filters = array_merge($filters,$filter);
32
		}
33
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
34
		$filter_query_join = '';
35
		$filter_query_where = '';
36
		foreach($filters as $flt) {
37
			if (isset($flt['airlines']) && !empty($flt['airlines'])) {
38
				if ($flt['airlines'][0] != '' && $flt['airlines'][0] != 'all') {
39
					if (isset($flt['source'])) {
40
						$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";
41
					} else {
42
						$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";
43
					}
44
				}
45
			}
46
			if (isset($flt['pilots_id']) && !empty($flt['pilots_id'])) {
47
				if (isset($flt['source'])) {
48
					$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";
49
				} else {
50
					$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";
51
				}
52
			}
53
			if (isset($flt['idents']) && !empty($flt['idents'])) {
54
				if (isset($flt['source'])) {
55
					$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";
56
				} else {
57
					$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";
58
				}
59
			}
60
			if (isset($flt['registrations']) && !empty($flt['registrations'])) {
61
				if (isset($flt['source'])) {
62
					$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";
63
				} else {
64
					$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";
65
				}
66
			}
67
			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']))) {
68
				if (isset($flt['source'])) {
69
					$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";
70
				}
71
			}
72
		}
73
		if (isset($filter['airlines']) && !empty($filter['airlines'])) {
74
			if ($filter['airlines'][0] != '' && $filter['airlines'][0] != 'all') {
75
				$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";
76
			}
77
		}
78
		if (isset($filter['alliance']) && !empty($filter['alliance'])) {
79
			$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 ";
80
		}
81
		if (isset($filter['airlinestype']) && !empty($filter['airlinestype'])) {
82
			$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 ";
83
		}
84
		if (isset($filter['pilots_id']) && !empty($filter['pilots_id'])) {
85
			$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";
86
		}
87
		if (isset($filter['source']) && !empty($filter['source'])) {
88
			if (count($filter['source']) == 1) {
89
				$filter_query_where .= " AND format_source = '".$filter['source'][0]."'";
90
			} else {
91
				$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
92
			}
93
		}
94
		if (isset($filter['ident']) && !empty($filter['ident'])) {
95
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
96
		}
97
		if (isset($filter['id']) && !empty($filter['id'])) {
98
			$filter_query_where .= " AND flightaware_id = '".$filter['id']."'";
99
		}
100
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
101
			$filter_query_date = '';
102
			
103
			if (isset($filter['year']) && $filter['year'] != '') {
104
				if ($globalDBdriver == 'mysql') {
105
					$filter_query_date .= " AND YEAR(spotter_output.date) = '".$filter['year']."'";
106
				} else {
107
					$filter_query_date .= " AND EXTRACT(YEAR FROM spotter_output.date) = '".$filter['year']."'";
108
				}
109
			}
110
			if (isset($filter['month']) && $filter['month'] != '') {
111
				if ($globalDBdriver == 'mysql') {
112
					$filter_query_date .= " AND MONTH(spotter_output.date) = '".$filter['month']."'";
113
				} else {
114
					$filter_query_date .= " AND EXTRACT(MONTH FROM spotter_output.date) = '".$filter['month']."'";
115
				}
116
			}
117
			if (isset($filter['day']) && $filter['day'] != '') {
118
				if ($globalDBdriver == 'mysql') {
119
					$filter_query_date .= " AND DAY(spotter_output.date) = '".$filter['day']."'";
120
				} else {
121
					$filter_query_date .= " AND EXTRACT(DAY FROM spotter_output.date) = '".$filter['day']."'";
122
				}
123
			}
124
			$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";
125
		}
126
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
127
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
128
		}
129
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
130
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
131
		if ($filter_query_where != '') {
132
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
133
		}
134
		$filter_query = $filter_query_join.$filter_query_where;
135
		return $filter_query;
136
	}
137
138
	/**
139
	* Gets all the spotter information based on the latest data entry
140
	*
141
	* @return Array the spotter information
142
	*
143
	*/
144
	public function getLiveSpotterData($limit = '', $sort = '', $filter = array())
145
	{
146
		global $globalDBdriver, $globalLiveInterval;
147
		$Spotter = new Spotter($this->db);
148
		date_default_timezone_set('UTC');
149
150
		$filter_query = $this->getFilter($filter);
151
		$limit_query = '';
152
		if ($limit != '')
153
		{
154
			$limit_array = explode(',', $limit);
155
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
156
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
157
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
158
			{
159
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
160
			}
161
		}
162
		$orderby_query = '';
163
		if ($sort != '')
164
		{
165
			$search_orderby_array = $this->getOrderBy();
166
			if (isset($search_orderby_array[$sort]['sql'])) 
167
			{
168
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
169
			}
170
		}
171
		if ($orderby_query == '') $orderby_query = ' ORDER BY date DESC';
172
173
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
174
		if ($globalDBdriver == 'mysql') {
175
			//$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";
176
			$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;
177
		} else {
178
			$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;
179
		}
180
		$spotter_array = $Spotter->getDataFromDB($query.$limit_query,array(),'',true);
181
182
		return $spotter_array;
183
	}
184
185
	/**
186
	* Gets Minimal Live Spotter data
187
	*
188
	* @return Array the spotter information
189
	*
190
	*/
191
	public function getMinLiveSpotterData($filter = array())
192
	{
193
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
194
		date_default_timezone_set('UTC');
195
		$filter_query = $this->getFilter($filter,true,true);
196
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
197
		if ($globalDBdriver == 'mysql') {
198
			if (isset($globalArchive) && $globalArchive === TRUE) {
199
				$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.real_altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source, spotter_live.registration 
200
				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 ORDER BY date DESC";
201
			} else {
202
				$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.real_altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source, spotter_live.registration 
203
				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 ORDER BY date DESC";
204
			}
205
		} else {
206
			if (isset($globalArchive) && $globalArchive === TRUE) {
207
				$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.real_altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source, spotter_live.registration 
208
				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' ORDER BY date DESC";
209
			} else {
210
				$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.real_altitude, spotter_live.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source, spotter_live.registration 
211
				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' ORDER BY date DESC";
212
			}
213
		}
214
215
		try {
216
			$sth = $this->db->prepare($query);
217
			$sth->execute();
218
		} catch(PDOException $e) {
219
			echo $e->getMessage();
220
			die;
221
		}
222
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
223
		return $spotter_array;
224
	}
225
226
	/**
227
	* Gets Minimal Live Spotter data since xx seconds
228
	*
229
	* @return Array the spotter information
230
	*
231
	*/
232
	public function getMinLastLiveSpotterData($coord = array(),$filter = array(), $limit = false, $id = '')
233
	{
234
		global $globalDBdriver, $globalLiveInterval, $globalArchive, $globalMap3DAircraftsLimit;
235
		date_default_timezone_set('UTC');
236
		$usecoord = false;
237
		if (is_array($coord) && !empty($coord)) {
238
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
239
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
240
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
241
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
242
			$usecoord = true;
243
		}
244
		$id = filter_var($id,FILTER_SANITIZE_STRING);
245
		$filter_query = $this->getFilter($filter,true,true);
246
247
		if (!isset($globalLiveInterval) || $globalLiveInterval == '') $globalLiveInterval = '200';
248
		if (!isset($globalMap3DAircraftsLimit) || $globalMap3DAircraftsLimit == '') $globalMap3DAircraftsLimit = '300';
249
		if ($globalDBdriver == 'mysql') {
250
			if (isset($globalArchive) && $globalArchive === TRUE) {
251
				/*
252
				$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 
253
				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 
254
				WHERE spotter_archive.latitude <> '0' AND spotter_archive.longitude <> '0' 
255
				ORDER BY spotter_archive.flightaware_id, spotter_archive.date";
256
				*/
257
				$query  = 'SELECT * FROM (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, spotter_archive.registration 
258
				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 ";
259
				if ($usecoord) $query .= "AND (spotter_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_archive.longitude BETWEEN ".$minlong." AND ".$maxlong.") ";
0 ignored issues
show
Bug introduced by
The variable $minlat does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $maxlat does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $minlong does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $maxlong does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

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