Completed
Push — master ( 0a71c8...58eab4 )
by Yannick
38:44
created

SpotterLive   D

Complexity

Total Complexity 225

Size/Duplication

Total Lines 1149
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 1149
rs 4.4102
c 0
b 0
f 0
wmc 225
lcom 1
cbo 3

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
F getFilter() 0 110 66
D getLiveSpotterData() 0 40 9
C getMinLiveSpotterData() 0 34 8
F getMinLastLiveSpotterData() 0 78 23
B getLiveSpotterCount() 0 24 4
B getLiveSpotterDatabyCoord() 0 22 4
C getMinLiveSpotterDatabyCoord() 0 62 9
C getLatestSpotterForLayar() 0 54 11
A getLastLiveSpotterDataByIdent() 0 12 1
A getDateLiveSpotterDataByIdent() 0 13 1
A getLastLiveSpotterDataById() 0 9 1
A getDateLiveSpotterDataById() 0 11 1
A getAltitudeLiveSpotterDataByIdent() 0 20 2
B getAllLiveSpotterDataById() 0 26 5
A getAllLiveSpotterDataByIdent() 0 16 2
A deleteLiveSpotterData() 0 21 3
C deleteLiveSpotterDataNotUpdated() 0 91 11
A deleteLiveSpotterDataByIdent() 0 15 2
A deleteLiveSpotterDataById() 0 15 2
B getIdentFromLastHour() 0 26 3
B checkIdentRecent() 0 26 3
B checkIdRecent() 0 26 3
B checkModeSRecent() 0 27 3
F addLiveSpotterData() 0 178 45
A getOrderBy() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like SpotterLive often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SpotterLive, and based on these observations, apply Extract Interface, too.

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.');
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
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
89
		}
90
		if (isset($filter['ident']) && !empty($filter['ident'])) {
91
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
92
		}
93
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
94
			$filter_query_date = '';
95
			
96
			if (isset($filter['year']) && $filter['year'] != '') {
97
				if ($globalDBdriver == 'mysql') {
98
					$filter_query_date .= " AND YEAR(spotter_output.date) = '".$filter['year']."'";
99
				} else {
100
					$filter_query_date .= " AND EXTRACT(YEAR FROM spotter_output.date) = '".$filter['year']."'";
101
				}
102
			}
103
			if (isset($filter['month']) && $filter['month'] != '') {
104
				if ($globalDBdriver == 'mysql') {
105
					$filter_query_date .= " AND MONTH(spotter_output.date) = '".$filter['month']."'";
106
				} else {
107
					$filter_query_date .= " AND EXTRACT(MONTH FROM spotter_output.date) = '".$filter['month']."'";
108
				}
109
			}
110
			if (isset($filter['day']) && $filter['day'] != '') {
111
				if ($globalDBdriver == 'mysql') {
112
					$filter_query_date .= " AND DAY(spotter_output.date) = '".$filter['day']."'";
113
				} else {
114
					$filter_query_date .= " AND EXTRACT(DAY FROM spotter_output.date) = '".$filter['day']."'";
115
				}
116
			}
117
			$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";
118
		}
119
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
120
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
121
		}
122
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
123
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
124
		if ($filter_query_where != '') {
125
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
126
		}
127
		$filter_query = $filter_query_join.$filter_query_where;
128
		return $filter_query;
129
	}
130
131
	/**
132
	* Gets all the spotter information based on the latest data entry
133
	*
134
	* @return Array the spotter information
135
	*
136
	*/
137
	public function getLiveSpotterData($limit = '', $sort = '', $filter = array())
138
	{
139
		global $globalDBdriver, $globalLiveInterval;
140
		$Spotter = new Spotter($this->db);
141
		date_default_timezone_set('UTC');
142
143
		$filter_query = $this->getFilter($filter);
144
		$limit_query = '';
145
		if ($limit != '')
146
		{
147
			$limit_array = explode(',', $limit);
148
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
149
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
150
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
151
			{
152
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
153
			}
154
		}
155
		$orderby_query = '';
156
		if ($sort != '')
157
		{
158
			$search_orderby_array = $this->getOrderBy();
159
			if (isset($search_orderby_array[$sort]['sql'])) 
160
			{
161
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
162
			}
163
		}
164
		if ($orderby_query == '') $orderby_query = ' ORDER BY date DESC';
165
166
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
167
		if ($globalDBdriver == 'mysql') {
168
			//$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";
169
			$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;
170
		} else {
171
			$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;
172
		}
173
		$spotter_array = $Spotter->getDataFromDB($query.$limit_query,array(),'',true);
174
175
		return $spotter_array;
176
	}
177
178
	/**
179
	* Gets Minimal Live Spotter data
180
	*
181
	* @return Array the spotter information
182
	*
183
	*/
184
	public function getMinLiveSpotterData($filter = array())
185
	{
186
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
187
		date_default_timezone_set('UTC');
188
		$filter_query = $this->getFilter($filter,true,true);
189
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
190
		if ($globalDBdriver == 'mysql') {
191
			if (isset($globalArchive) && $globalArchive === TRUE) {
192
				$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 
193
				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";
194
			} else {
195
				$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 
196
				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";
197
			}
198
		} else {
199
			if (isset($globalArchive) && $globalArchive === TRUE) {
200
				$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 
201
				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'";
202
			} else {
203
				$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 
204
				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'";
205
			}
206
		}
207
208
		try {
209
			$sth = $this->db->prepare($query);
210
			$sth->execute();
211
		} catch(PDOException $e) {
212
			echo $e->getMessage();
213
			die;
214
		}
215
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
216
		return $spotter_array;
217
	}
218
219
	/**
220
	* Gets Minimal Live Spotter data since xx seconds
221
	*
222
	* @return Array the spotter information
223
	*
224
	*/
225
	public function getMinLastLiveSpotterData($coord = array(),$filter = array(), $limit = false)
226
	{
227
		global $globalDBdriver, $globalLiveInterval, $globalArchive, $globalMap3DAircraftsLimit;
228
		date_default_timezone_set('UTC');
229
		if (is_array($coord) && !empty($coord)) {
230
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
231
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
232
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
233
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
234
		}
235
		$filter_query = $this->getFilter($filter,true,true);
236
237
		if (!isset($globalLiveInterval) || $globalLiveInterval == '') $globalLiveInterval = '200';
238
		if (!isset($globalMap3DAircraftsLimit) || $globalMap3DAicraftsLimit == '') $globalMap3DAircraftsLimit = '300';
0 ignored issues
show
Bug introduced by
The variable $globalMap3DAicraftsLimit does not exist. Did you mean $globalMap3DAircraftsLimit?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

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