Completed
Push — master ( 39c0a3...691470 )
by Yannick
28:40
created

SpotterLive::getLastLiveSpotterDataById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 9
rs 9.6666
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] != '') {
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] != '') {
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['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
98
			$filter_query_date = '';
99
			
100
			if (isset($filter['year']) && $filter['year'] != '') {
101
				if ($globalDBdriver == 'mysql') {
102
					$filter_query_date .= " AND YEAR(spotter_output.date) = '".$filter['year']."'";
103
				} else {
104
					$filter_query_date .= " AND EXTRACT(YEAR FROM spotter_output.date) = '".$filter['year']."'";
105
				}
106
			}
107
			if (isset($filter['month']) && $filter['month'] != '') {
108
				if ($globalDBdriver == 'mysql') {
109
					$filter_query_date .= " AND MONTH(spotter_output.date) = '".$filter['month']."'";
110
				} else {
111
					$filter_query_date .= " AND EXTRACT(MONTH FROM spotter_output.date) = '".$filter['month']."'";
112
				}
113
			}
114
			if (isset($filter['day']) && $filter['day'] != '') {
115
				if ($globalDBdriver == 'mysql') {
116
					$filter_query_date .= " AND DAY(spotter_output.date) = '".$filter['day']."'";
117
				} else {
118
					$filter_query_date .= " AND EXTRACT(DAY FROM spotter_output.date) = '".$filter['day']."'";
119
				}
120
			}
121
			$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";
122
		}
123
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
124
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
125
		}
126
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
127
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
128
		if ($filter_query_where != '') {
129
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
130
		}
131
		$filter_query = $filter_query_join.$filter_query_where;
132
		return $filter_query;
133
	}
134
135
	/**
136
	* Gets all the spotter information based on the latest data entry
137
	*
138
	* @return Array the spotter information
139
	*
140
	*/
141
	public function getLiveSpotterData($limit = '', $sort = '', $filter = array())
142
	{
143
		global $globalDBdriver, $globalLiveInterval;
144
		$Spotter = new Spotter($this->db);
145
		date_default_timezone_set('UTC');
146
147
		$filter_query = $this->getFilter($filter);
148
		$limit_query = '';
149
		if ($limit != '')
150
		{
151
			$limit_array = explode(',', $limit);
152
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
153
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
154
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
155
			{
156
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
157
			}
158
		}
159
		$orderby_query = '';
160
		if ($sort != '')
161
		{
162
			$search_orderby_array = $this->getOrderBy();
163
			if (isset($search_orderby_array[$sort]['sql'])) 
164
			{
165
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
166
			}
167
		}
168
		if ($orderby_query == '') $orderby_query = ' ORDER BY date DESC';
169
170
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
171
		if ($globalDBdriver == 'mysql') {
172
			//$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";
173
			$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;
174
		} else {
175
			$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;
176
		}
177
		$spotter_array = $Spotter->getDataFromDB($query.$limit_query,array(),'',true);
178
179
		return $spotter_array;
180
	}
181
182
	/**
183
	* Gets Minimal Live Spotter data
184
	*
185
	* @return Array the spotter information
186
	*
187
	*/
188
	public function getMinLiveSpotterData($filter = array())
189
	{
190
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
191
		date_default_timezone_set('UTC');
192
		$filter_query = $this->getFilter($filter,true,true);
193
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
194
		if ($globalDBdriver == 'mysql') {
195
			if (isset($globalArchive) && $globalArchive === TRUE) {
196
				$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 
197
				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";
198
			} else {
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.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
200
				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";
201
			}
202
		} else {
203
			if (isset($globalArchive) && $globalArchive === TRUE) {
204
				$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 
205
				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'";
206
			} else {
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.heading, spotter_live.ground_speed, spotter_live.squawk, spotter_live.date, spotter_live.format_source 
208
				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'";
209
			}
210
		}
211
212
		try {
213
			$sth = $this->db->prepare($query);
214
			$sth->execute();
215
		} catch(PDOException $e) {
216
			echo $e->getMessage();
217
			die;
218
		}
219
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
220
		return $spotter_array;
221
	}
222
223
	/**
224
	* Gets Minimal Live Spotter data since xx seconds
225
	*
226
	* @return Array the spotter information
227
	*
228
	*/
229
	public function getMinLastLiveSpotterData($coord = array(),$filter = array(), $limit = false)
230
	{
231
		global $globalDBdriver, $globalLiveInterval, $globalArchive, $globalMap3DAircraftsLimit;
232
		date_default_timezone_set('UTC');
233
		$usecoord = false;
234
		if (is_array($coord) && !empty($coord)) {
235
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
236
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
237
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
238
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
239
			$usecoord = true;
240
		}
241
		$filter_query = $this->getFilter($filter,true,true);
242
243
		if (!isset($globalLiveInterval) || $globalLiveInterval == '') $globalLiveInterval = '200';
244
		if (!isset($globalMap3DAircraftsLimit) || $globalMap3DAircraftsLimit == '') $globalMap3DAircraftsLimit = '300';
245
		if ($globalDBdriver == 'mysql') {
246
			if (isset($globalArchive) && $globalArchive === TRUE) {
247
				/*
248
				$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 
249
				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 
250
				WHERE spotter_archive.latitude <> '0' AND spotter_archive.longitude <> '0' 
251
				ORDER BY spotter_archive.flightaware_id, spotter_archive.date";
252
				*/
253
				$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 
254
				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 ";
255
				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...
256
				$query .= "UNION
257
				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 
258
				FROM spotter_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= spotter_live.date";
259
				if ($usecoord) $query .= " AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
260
				$query .= ") AS spotter 
261
				WHERE latitude <> '0' AND longitude <> '0' 
262
				ORDER BY flightaware_id, date";
263
				if ($limit) $query .= " LIMIT ".$globalMap3DAircraftsLimit;
264
			} else {
265
				$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 
266
				FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= spotter_live.date ";
267
				if ($usecoord) $query .= "AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
268
				$query .= "AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
269
				ORDER BY spotter_live.flightaware_id, spotter_live.date";
270
				if ($limit) $query .= " LIMIT ".$globalMap3DAircraftsLimit;
271
			}
272
		} else {
273
			if (isset($globalArchive) && $globalArchive === TRUE) {
274
				/*
275
				$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 
276
				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 
277
				WHERE spotter_archive.latitude <> '0' AND spotter_archive.longitude <> '0' 
278
				ORDER BY spotter_archive.flightaware_id, spotter_archive.date";
279
                               */
280
				$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 
281
				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 ";
282
				if ($usecoord) $query .= "AND spotter_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
283
				$query .= "UNION
284
				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 
285
				FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date";
286
				if ($usecoord) $query .= " AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
287
				$query .= ") AS spotter WHERE latitude <> '0' AND longitude <> '0' ";
288
				$query .= "ORDER BY flightaware_id, date";
289
				if ($limit) $query .= " LIMIT ".$globalMap3DAircraftsLimit;
290
			} else {
291
				$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 
292
				FROM spotter_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date ";
293
				if ($usecoord) $query .= "AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
294
				$query .= "AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0' 
295
				ORDER BY spotter_live.flightaware_id, spotter_live.date";
296
				if ($limit) $query .= " LIMIT ".$globalMap3DAircraftsLimit;
297
			}
298
		}
299
		try {
300
			$sth = $this->db->prepare($query);
301
			$sth->execute();
302
		} catch(PDOException $e) {
303
			echo $e->getMessage();
304
			die;
305
		}
306
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
307
		return $spotter_array;
308
	}
309
310
	/**
311
	* Gets number of latest data entry
312
	*
313
	* @return String number of entry
314
	*
315
	*/
316
	public function getLiveSpotterCount($filter = array())
317
	{
318
		global $globalDBdriver, $globalLiveInterval;
319
		$filter_query = $this->getFilter($filter,true,true);
320
321
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
322
		if ($globalDBdriver == 'mysql') {
323
			//$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;
324
			$query = 'SELECT COUNT(DISTINCT spotter_live.flightaware_id) as nb FROM spotter_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
325
		} else {
326
			//$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;
327
			$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";
328
		}
329
		try {
330
			$sth = $this->db->prepare($query);
331
			$sth->execute();
332
		} catch(PDOException $e) {
333
			echo $e->getMessage();
334
			die;
335
		}
336
		$result = $sth->fetch(PDO::FETCH_ASSOC);
337
		$sth->closeCursor();
338
		return $result['nb'];
339
	}
340
341
	/**
342
	* Gets all the spotter information based on the latest data entry and coord
343
	*
344
	* @return Array the spotter information
345
	*
346
	*/
347
	public function getLiveSpotterDatabyCoord($coord, $filter = array())
348
	{
349
		global $globalDBdriver, $globalLiveInterval;
350
		$Spotter = new Spotter($this->db);
351
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
352
		$filter_query = $this->getFilter($filter);
353
354
		if (is_array($coord)) {
355
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
356
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
357
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
358
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
359
		} else return array();
360
		if ($globalDBdriver == 'mysql') {
361
			$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;
362
		} else {
363
			$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;
364
365
		}
366
		$spotter_array = $Spotter->getDataFromDB($query);
367
		return $spotter_array;
368
	}
369
370
	/**
371
	* Gets all the spotter information based on the latest data entry and coord
372
	*
373
	* @return Array the spotter information
374
	*
375
	*/
376
	public function getMinLiveSpotterDatabyCoord($coord, $filter = array())
377
	{
378
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
379
		$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...
380
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
381
		$filter_query = $this->getFilter($filter,true,true);
382
383
		if (is_array($coord)) {
384
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
385
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
386
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
387
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
388
		} else return array();
389
		if ($globalDBdriver == 'mysql') {
390
			if (isset($globalArchive) && $globalArchive === TRUE) {
391
				$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 
392
				FROM spotter_live 
393
				'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= spotter_live.date 
394
				AND spotter_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND spotter_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
395
				AND spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
396
			} else {
397
				$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 
398
				FROM spotter_live 
399
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
400
				    FROM spotter_live l 
401
				    WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
402
				    AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
403
				    GROUP BY l.flightaware_id
404
				) s on spotter_live.flightaware_id = s.flightaware_id 
405
				AND spotter_live.date = s.maxdate'.$filter_query.' spotter_live.latitude <> 0 AND spotter_live.longitude <> 0';
406
			}
407
		} else {
408
			if (isset($globalArchive) && $globalArchive === TRUE) {
409
				$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 
410
				FROM spotter_live 
411
				".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= spotter_live.date 
412
				AND spotter_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
413
				AND spotter_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
414
				AND spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
415
			} else {
416
				$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 
417
				FROM spotter_live 
418
				INNER JOIN (SELECT l.flightaware_id, max(l.date) as maxdate 
419
				    FROM spotter_live l 
420
				    WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
421
				    AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
422
				    AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
423
				    GROUP BY l.flightaware_id
424
				) s on spotter_live.flightaware_id = s.flightaware_id 
425
				AND spotter_live.date = s.maxdate".$filter_query." spotter_live.latitude <> '0' AND spotter_live.longitude <> '0'";
426
			}
427
		}
428
		try {
429
			$sth = $this->db->prepare($query);
430
			$sth->execute();
431
		} catch(PDOException $e) {
432
			echo $e->getMessage();
433
			die;
434
		}
435
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
436
		return $spotter_array;
437
	}
438
439
	/**
440
	* Gets all the spotter information based on a user's latitude and longitude
441
	*
442
	* @return Array the spotter information
443
	*
444
	*/
445
	public function getLatestSpotterForLayar($lat, $lng, $radius, $interval)
446
	{
447
		$Spotter = new Spotter($this->db);
448
		date_default_timezone_set('UTC');
449
		if ($lat != '') {
450
			if (!is_numeric($lat)) {
451
				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...
452
			}
453
		}
454
        if ($lng != '')
455
                {
456
                        if (!is_numeric($lng))
457
                        {
458
                                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...
459
                        }
460
                }
461
462
                if ($radius != '')
463
                {
464
                        if (!is_numeric($radius))
465
                        {
466
                                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...
467
                        }
468
                }
469
		$additional_query = '';
470
        if ($interval != '')
471
                {
472
                        if (!is_string($interval))
473
                        {
474
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
475
			        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...
476
                        } else {
477
                if ($interval == '1m')
478
                {
479
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';
480
                } else if ($interval == '15m'){
481
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= spotter_live.date ';
482
                } 
483
            }
484
                } else {
485
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= spotter_live.date ';   
486
        }
487
488
                $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 
489
                   WHERE spotter_live.latitude <> '' 
490
                                   AND spotter_live.longitude <> '' 
491
                   ".$additional_query."
492
                   HAVING distance < :radius  
493
                                   ORDER BY distance";
494
495
                $spotter_array = $Spotter->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
496
497
                return $spotter_array;
498
        }
499
500
    
501
        /**
502
	* Gets all the spotter information based on a particular callsign
503
	*
504
	* @return Array the spotter information
505
	*
506
	*/
507
	public function getLastLiveSpotterDataByIdent($ident)
508
	{
509
		$Spotter = new Spotter($this->db);
510
		date_default_timezone_set('UTC');
511
512
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
513
                $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';
514
515
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident),'',true);
516
517
		return $spotter_array;
518
	}
519
520
        /**
521
	* Gets all the spotter information based on a particular callsign
522
	*
523
	* @return Array the spotter information
524
	*
525
	*/
526
	public function getDateLiveSpotterDataByIdent($ident,$date)
527
	{
528
		$Spotter = new Spotter($this->db);
529
		date_default_timezone_set('UTC');
530
531
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
532
                $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';
533
534
                $date = date('c',$date);
535
		$spotter_array = $Spotter->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
536
537
		return $spotter_array;
538
	}
539
540
        /**
541
	* Gets last spotter information based on a particular callsign
542
	*
543
	* @return Array the spotter information
544
	*
545
	*/
546
	public function getLastLiveSpotterDataById($id)
547
	{
548
		$Spotter = new Spotter($this->db);
549
		date_default_timezone_set('UTC');
550
		$id = filter_var($id, FILTER_SANITIZE_STRING);
551
		$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';
552
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id),'',true);
553
		return $spotter_array;
554
	}
555
556
        /**
557
	* Gets last spotter information based on a particular callsign
558
	*
559
	* @return Array the spotter information
560
	*
561
	*/
562
	public function getDateLiveSpotterDataById($id,$date)
563
	{
564
		$Spotter = new Spotter($this->db);
565
		date_default_timezone_set('UTC');
566
567
		$id = filter_var($id, FILTER_SANITIZE_STRING);
568
		$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';
569
		$date = date('c',$date);
570
		$spotter_array = $Spotter->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
571
		return $spotter_array;
572
	}
573
574
        /**
575
	* Gets altitude information based on a particular callsign
576
	*
577
	* @return Array the spotter information
578
	*
579
	*/
580
	public function getAltitudeLiveSpotterDataByIdent($ident)
581
	{
582
583
		date_default_timezone_set('UTC');
584
585
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
586
                $query  = 'SELECT spotter_live.altitude, spotter_live.date FROM spotter_live WHERE spotter_live.ident = :ident';
587
588
    		try {
589
			
590
			$sth = $this->db->prepare($query);
591
			$sth->execute(array(':ident' => $ident));
592
		} catch(PDOException $e) {
593
			echo $e->getMessage();
594
			die;
595
		}
596
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
597
598
		return $spotter_array;
599
	}
600
601
        /**
602
	* Gets all the spotter information based on a particular id
603
	*
604
	* @return Array the spotter information
605
	*
606
	*/
607
	public function getAllLiveSpotterDataById($id,$liveinterval = false)
608
	{
609
		global $globalDBdriver, $globalLiveInterval;
610
		date_default_timezone_set('UTC');
611
		$id = filter_var($id, FILTER_SANITIZE_STRING);
612
		//$query  = self::$global_query.' WHERE spotter_live.flightaware_id = :id ORDER BY date';
613
		if ($globalDBdriver == 'mysql') {
614
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
615
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
616
			$query .= ' ORDER BY date';
617
		} else {
618
			$query = 'SELECT spotter_live.* FROM spotter_live WHERE spotter_live.flightaware_id = :id';
619
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
620
			$query .= ' ORDER BY date';
621
		}
622
623
		try {
624
			$sth = $this->db->prepare($query);
625
			$sth->execute(array(':id' => $id));
626
		} catch(PDOException $e) {
627
			echo $e->getMessage();
628
			die;
629
		}
630
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
631
		return $spotter_array;
632
	}
633
634
        /**
635
	* Gets all the spotter information based on a particular ident
636
	*
637
	* @return Array the spotter information
638
	*
639
	*/
640
	public function getAllLiveSpotterDataByIdent($ident)
641
	{
642
		date_default_timezone_set('UTC');
643
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
644
		$query  = self::$global_query.' WHERE spotter_live.ident = :ident';
645
    		try {
646
			
647
			$sth = $this->db->prepare($query);
648
			$sth->execute(array(':ident' => $ident));
649
		} catch(PDOException $e) {
650
			echo $e->getMessage();
651
			die;
652
		}
653
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
654
		return $spotter_array;
655
	}
656
657
658
	/**
659
	* Deletes all info in the table
660
	*
661
	* @return String success or false
662
	*
663
	*/
664
	public function deleteLiveSpotterData()
665
	{
666
		global $globalDBdriver;
667
		if ($globalDBdriver == 'mysql') {
668
			//$query  = "DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= spotter_live.date";
669
			$query  = 'DELETE FROM spotter_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= spotter_live.date';
670
            		//$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)";
671
		} else {
672
			$query  = "DELETE FROM spotter_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= spotter_live.date";
673
		}
674
        
675
    		try {
676
			
677
			$sth = $this->db->prepare($query);
678
			$sth->execute();
679
		} catch(PDOException $e) {
680
			return "error";
681
		}
682
683
		return "success";
684
	}
685
686
	/**
687
	* Deletes all info in the table for aircraft not seen since 2 HOUR
688
	*
689
	* @return String success or false
690
	*
691
	*/
692
	public function deleteLiveSpotterDataNotUpdated()
693
	{
694
		global $globalDBdriver, $globalDebug;
695
		if ($globalDBdriver == 'mysql') {
696
			//$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';
697
    			$query = "SELECT spotter_live.flightaware_id FROM spotter_live INNER JOIN (SELECT flightaware_id,MAX(date) as max_date FROM spotter_live GROUP BY flightaware_id) s ON s.flightaware_id = spotter_live.flightaware_id AND DATE_SUB(UTC_TIMESTAMP(), INTERVAL 2 HOUR) >= 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 == 30) {
714
					if ($globalDebug) echo ".";
715
				    	try {
716
						
717
						$sth = $this->db->prepare(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->prepare(substr($query_delete,0,-1).")");
731
					$sth->execute();
732
				} catch(PDOException $e) {
733
					return "error";
734
				}
735
			}
736
			return "success";
737
		} elseif ($globalDBdriver == 'pgsql') {
738
			//$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";
739
    			//$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";
740
    			$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)";
741
    			try {
742
				
743
				$sth = $this->db->prepare($query);
744
				$sth->execute();
745
			} catch(PDOException $e) {
746
				return "error";
747
			}
748
/*			$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
749
                        $i = 0;
750
                        $j =0;
751
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
752
			foreach($all as $row)
753
			{
754
				$i++;
755
				$j++;
756
				if ($j == 100) {
757
					if ($globalDebug) echo ".";
758
				    	try {
759
						
760
						$sth = $this->db->query(substr($query_delete,0,-1).")");
761
						//$sth->execute();
762
					} catch(PDOException $e) {
763
						return "error";
764
					}
765
                                	$query_delete = "DELETE FROM spotter_live WHERE flightaware_id IN (";
766
                                	$j = 0;
767
				}
768
				$query_delete .= "'".$row['flightaware_id']."',";
769
			}
770
			if ($i > 0) {
771
    				try {
772
					
773
					$sth = $this->db->query(substr($query_delete,0,-1).")");
774
					//$sth->execute();
775
				} catch(PDOException $e) {
776
					return "error";
777
				}
778
			}
779
*/
780
			return "success";
781
		}
782
	}
783
784
	/**
785
	* Deletes all info in the table for an ident
786
	*
787
	* @return String success or false
788
	*
789
	*/
790
	public function deleteLiveSpotterDataByIdent($ident)
791
	{
792
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
793
		$query  = 'DELETE FROM spotter_live WHERE ident = :ident';
794
        
795
    		try {
796
			
797
			$sth = $this->db->prepare($query);
798
			$sth->execute(array(':ident' => $ident));
799
		} catch(PDOException $e) {
800
			return "error";
801
		}
802
803
		return "success";
804
	}
805
806
	/**
807
	* Deletes all info in the table for an id
808
	*
809
	* @return String success or false
810
	*
811
	*/
812
	public function deleteLiveSpotterDataById($id)
813
	{
814
		$id = filter_var($id, FILTER_SANITIZE_STRING);
815
		$query  = 'DELETE FROM spotter_live WHERE flightaware_id = :id';
816
        
817
    		try {
818
			
819
			$sth = $this->db->prepare($query);
820
			$sth->execute(array(':id' => $id));
821
		} catch(PDOException $e) {
822
			return "error";
823
		}
824
825
		return "success";
826
	}
827
828
829
	/**
830
	* Gets the aircraft ident within the last hour
831
	*
832
	* @return String the ident
833
	*
834
	*/
835
	public function getIdentFromLastHour($ident)
836
	{
837
		global $globalDBdriver, $globalTimezone;
838
		if ($globalDBdriver == 'mysql') {
839
			$query  = 'SELECT spotter_live.ident FROM spotter_live 
840
				WHERE spotter_live.ident = :ident 
841
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
842
				AND spotter_live.date < UTC_TIMESTAMP()';
843
			$query_data = array(':ident' => $ident);
844
		} else {
845
			$query  = "SELECT spotter_live.ident FROM spotter_live 
846
				WHERE spotter_live.ident = :ident 
847
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
848
				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
849
			$query_data = array(':ident' => $ident);
850
		}
851
		
852
		$sth = $this->db->prepare($query);
853
		$sth->execute($query_data);
854
		$ident_result='';
855
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
856
		{
857
			$ident_result = $row['ident'];
858
		}
859
		return $ident_result;
860
        }
861
862
	/**
863
	* Check recent aircraft
864
	*
865
	* @return String the ident
866
	*
867
	*/
868
	public function checkIdentRecent($ident)
869
	{
870
		global $globalDBdriver, $globalTimezone;
871
		if ($globalDBdriver == 'mysql') {
872
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
873
				WHERE spotter_live.ident = :ident 
874
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
875
//				AND spotter_live.date < UTC_TIMESTAMP()";
876
			$query_data = array(':ident' => $ident);
877
		} else {
878
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
879
				WHERE spotter_live.ident = :ident 
880
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
881
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
882
			$query_data = array(':ident' => $ident);
883
		}
884
		
885
		$sth = $this->db->prepare($query);
886
		$sth->execute($query_data);
887
		$ident_result='';
888
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
889
		{
890
			$ident_result = $row['flightaware_id'];
891
		}
892
		return $ident_result;
893
        }
894
895
	/**
896
	* Check recent aircraft by id
897
	*
898
	* @return String the ident
899
	*
900
	*/
901
	public function checkIdRecent($id)
902
	{
903
		global $globalDBdriver, $globalTimezone;
904
		if ($globalDBdriver == 'mysql') {
905
			$query  = 'SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
906
				WHERE spotter_live.flightaware_id = :id 
907
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
908
//				AND spotter_live.date < UTC_TIMESTAMP()";
909
			$query_data = array(':id' => $id);
910
		} else {
911
			$query  = "SELECT spotter_live.ident, spotter_live.flightaware_id FROM spotter_live 
912
				WHERE spotter_live.flightaware_id = :id 
913
				AND spotter_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
914
//				AND spotter_live.date < now() AT TIME ZONE 'UTC'";
915
			$query_data = array(':id' => $id);
916
		}
917
		
918
		$sth = $this->db->prepare($query);
919
		$sth->execute($query_data);
920
		$ident_result='';
921
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
922
		{
923
			$ident_result = $row['flightaware_id'];
924
		}
925
		return $ident_result;
926
        }
927
928
	/**
929
	* Check recent aircraft by ModeS
930
	*
931
	* @return String the ModeS
932
	*
933
	*/
934
	public function checkModeSRecent($modes)
935
	{
936
		global $globalDBdriver, $globalTimezone;
937
		if ($globalDBdriver == 'mysql') {
938
			$query  = 'SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
939
				WHERE spotter_live.ModeS = :modes 
940
				AND spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
941
//				AND spotter_live.date < UTC_TIMESTAMP()";
942
			$query_data = array(':modes' => $modes);
943
		} else {
944
			$query  = "SELECT spotter_live.ModeS, spotter_live.flightaware_id FROM spotter_live 
945
				WHERE spotter_live.ModeS = :modes 
946
				AND spotter_live.date >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 MINUTE'";
947
//			//	AND spotter_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
948
			$query_data = array(':modes' => $modes);
949
		}
950
		
951
		$sth = $this->db->prepare($query);
952
		$sth->execute($query_data);
953
		$ident_result='';
954
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
955
		{
956
			//$ident_result = $row['spotter_live_id'];
957
			$ident_result = $row['flightaware_id'];
958
		}
959
		return $ident_result;
960
	}
961
962
	/**
963
	* Gets the aircraft data from the last 20 seconds
964
	*
965
	* @return Array the spotter data
966
	*
967
	*/
968
	public function getRealTimeData($q = '')
969
	{
970
		global $globalDBdriver;
971
		$additional_query = '';
972
		if ($q != "")
973
		{
974
			if (!is_string($q))
975
			{
976
				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::getRealTimeData 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...
977
			} else {
978
				$q_array = explode(" ", $q);
979
				foreach ($q_array as $q_item){
980
					$q_item = filter_var($q_item,FILTER_SANITIZE_STRING);
981
					$additional_query .= " AND (";
982
					$additional_query .= "(spotter_live.aircraft_icao like '%".$q_item."%') OR ";
983
					$additional_query .= "(spotter_live.aircraft_name like '%".$q_item."%') OR ";
984
					$additional_query .= "(spotter_live.aircraft_manufacturer like '%".$q_item."%') OR ";
985
					$additional_query .= "(spotter_live.airline_icao like '%".$q_item."%') OR ";
986
					$additional_query .= "(spotter_live.departure_airport_icao like '%".$q_item."%') OR ";
987
					$additional_query .= "(spotter_live.arrival_airport_icao like '%".$q_item."%') OR ";
988
					$additional_query .= "(spotter_live.registration like '%".$q_item."%') OR ";
989
					$additional_query .= "(spotter_live.ident like '%".$q_item."%')";
990
					$additional_query .= ")";
991
				}
992
			}
993
		}
994
		if ($globalDBdriver == 'mysql') {
995
			$query  = "SELECT spotter_live.* FROM spotter_live 
996
			    WHERE spotter_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 20 SECOND) ".$additional_query." 
997
			    AND spotter_live.date < UTC_TIMESTAMP()";
998
		} else {
999
			$query  = "SELECT spotter_live.* FROM spotter_live 
1000
			    WHERE spotter_live.date::timestamp >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '20 SECONDS' ".$additional_query." 
1001
			    AND spotter_live.date::timestamp < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
1002
		}
1003
		$Spotter = new Spotter();
1004
		$spotter_array = $Spotter->getDataFromDB($query, array());
1005
		return $spotter_array;
1006
	}
1007
1008
	/**
1009
	* Adds a new spotter data
1010
	*
1011
	* @param String $flightaware_id the ID from flightaware
1012
	* @param String $ident the flight ident
1013
	* @param String $aircraft_icao the aircraft type
1014
	* @param String $departure_airport_icao the departure airport
1015
	* @param String $arrival_airport_icao the arrival airport
1016
	* @return String success or false
1017
	*
1018
	*/
1019
	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 = '')
1020
	{
1021
		global $globalURL, $globalArchive, $globalDebug;
1022
		$Common = new Common();
1023
		date_default_timezone_set('UTC');
1024
1025
		//getting the airline information
1026
		if ($ident != '')
1027
		{
1028
			if (!is_string($ident))
1029
			{
1030
				return false;
1031
			} 
1032
		}
1033
1034
		//getting the aircraft information
1035
		if ($aircraft_icao != '')
1036
		{
1037
			if (!is_string($aircraft_icao))
1038
			{
1039
				return false;
1040
			} 
1041
		} 
1042
		//getting the departure airport information
1043
		if ($departure_airport_icao != '')
1044
		{
1045
			if (!is_string($departure_airport_icao))
1046
			{
1047
				return false;
1048
			} 
1049
		}
1050
1051
		//getting the arrival airport information
1052
		if ($arrival_airport_icao != '')
1053
		{
1054
			if (!is_string($arrival_airport_icao))
1055
			{
1056
				return false;
1057
			}
1058
		}
1059
1060
1061
		if ($latitude != '')
1062
		{
1063
			if (!is_numeric($latitude))
1064
			{
1065
				return false;
1066
			}
1067
		} else return '';
1068
1069
		if ($longitude != '')
1070
		{
1071
			if (!is_numeric($longitude))
1072
			{
1073
				return false;
1074
			}
1075
		} else return '';
1076
1077
		if ($waypoints != '')
1078
		{
1079
			if (!is_string($waypoints))
1080
			{
1081
				return false;
1082
			}
1083
		}
1084
1085
		if ($altitude != '')
1086
		{
1087
			if (!is_numeric($altitude))
1088
			{
1089
				return false;
1090
			}
1091
		} else $altitude = 0;
1092
		if ($altitude_real != '')
1093
		{
1094
			if (!is_numeric($altitude_real))
1095
			{
1096
				return false;
1097
			}
1098
		} else $altitude_real = 0;
1099
1100
		if ($heading != '')
1101
		{
1102
			if (!is_numeric($heading))
1103
			{
1104
				return false;
1105
			}
1106
		} else $heading = 0;
1107
1108
		if ($groundspeed != '')
1109
		{
1110
			if (!is_numeric($groundspeed))
1111
			{
1112
				return false;
1113
			}
1114
		} else $groundspeed = 0;
1115
		date_default_timezone_set('UTC');
1116
		if ($date == '') $date = date("Y-m-d H:i:s", time());
1117
1118
        
1119
		$flightaware_id = filter_var($flightaware_id,FILTER_SANITIZE_STRING);
1120
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1121
		$aircraft_icao = filter_var($aircraft_icao,FILTER_SANITIZE_STRING);
1122
		$departure_airport_icao = filter_var($departure_airport_icao,FILTER_SANITIZE_STRING);
1123
		$arrival_airport_icao = filter_var($arrival_airport_icao,FILTER_SANITIZE_STRING);
1124
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1125
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1126
		$waypoints = filter_var($waypoints,FILTER_SANITIZE_STRING);
1127
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1128
		$altitude_real = filter_var($altitude_real,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1129
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
1130
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1131
		$squawk = filter_var($squawk,FILTER_SANITIZE_NUMBER_INT);
1132
		$route_stop = filter_var($route_stop,FILTER_SANITIZE_STRING);
1133
		$ModeS = filter_var($ModeS,FILTER_SANITIZE_STRING);
1134
		$pilot_id = filter_var($pilot_id,FILTER_SANITIZE_STRING);
1135
		$pilot_name = filter_var($pilot_name,FILTER_SANITIZE_STRING);
1136
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
1137
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
1138
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
1139
		$verticalrate = filter_var($verticalrate,FILTER_SANITIZE_NUMBER_INT);
1140
1141
		$airline_name = '';
1142
		$airline_icao = '';
1143
		$airline_country = '';
1144
		$airline_type = '';
1145
		$aircraft_shadow = '';
1146
		$aircraft_type = '';
1147
		$aircraft_manufacturer = '';
1148
1149
1150
1151
		$aircraft_name = '';
1152
		$departure_airport_name = '';
1153
		$departure_airport_city = '';
1154
		$departure_airport_country = '';
1155
		
1156
		$arrival_airport_name = '';
1157
		$arrival_airport_city = '';
1158
		$arrival_airport_country = '';
1159
		
1160
            	
1161
            	if ($squawk == '' || $Common->isInteger($squawk) === false ) $squawk = NULL;
1162
            	if ($verticalrate == '' || $Common->isInteger($verticalrate) === false ) $verticalrate = NULL;
1163
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
1164
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
1165
		
1166
		$query = '';
1167
		if ($globalArchive) {
1168
			if ($globalDebug) echo '-- Delete previous data -- ';
1169
			$query .= 'DELETE FROM spotter_live WHERE flightaware_id = :flightaware_id;';
1170
		}
1171
1172
		$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) 
1173
		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)';
1174
1175
		$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);
1176
		try {
1177
			
1178
			$sth = $this->db->prepare($query);
1179
			$sth->execute($query_values);
1180
			$sth->closeCursor();
1181
		} catch(PDOException $e) {
1182
			return "error : ".$e->getMessage();
1183
		}
1184
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
1185
		    if ($globalDebug) echo '(Add to SBS archive : ';
1186
		    $SpotterArchive = new SpotterArchive($this->db);
1187
		    $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);
1188
		    if ($globalDebug) echo $result.')';
1189
		} elseif ($globalDebug && $putinarchive !== true) {
1190
			echo '(Not adding to archive)';
1191
		} elseif ($globalDebug && $noarchive === true) {
1192
			echo '(No archive)';
1193
		}
1194
		return "success";
1195
1196
	}
1197
1198
	public function getOrderBy()
1199
	{
1200
		$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"));
1201
		return $orderby;
1202
	}
1203
1204
}
1205
1206
1207
?>
1208