Completed
Push — master ( 492b3e...b38f26 )
by Yannick
29:43
created

TrackerLive   D

Complexity

Total Complexity 169

Size/Duplication

Total Lines 995
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 995
rs 4.4444
c 0
b 0
f 0
wmc 169
lcom 1
cbo 4

25 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
F getFilter() 0 68 36
C getLiveTrackerData() 0 39 8
B getMinLiveTrackerData() 0 31 4
F getMinLastLiveTrackerData() 0 71 22
B getLiveTrackerCount() 0 22 4
A getLiveTrackerDatabyCoord() 0 21 4
C getMinLiveTrackerDatabyCoord() 0 65 8
C getLatestTrackerForLayar() 0 54 11
A getLastLiveTrackerDataByIdent() 0 12 1
A getDateLiveTrackerDataByIdent() 0 13 1
A getLastLiveTrackerDataById() 0 12 1
A getDateLiveTrackerDataById() 0 12 1
A getAltitudeLiveTrackerDataByIdent() 0 20 2
C getAllLiveTrackerDataById() 0 28 7
A getAllLiveTrackerDataByIdent() 0 16 2
A deleteLiveTrackerData() 0 21 3
C deleteLiveTrackerDataNotUpdated() 0 91 11
A deleteLiveTrackerDataByIdent() 0 15 2
A deleteLiveTrackerDataById() 0 15 2
B getIdentFromLastHour() 0 26 3
B checkIdentRecent() 0 26 3
B checkIdRecent() 0 26 3
F addLiveTrackerData() 0 105 27
A getOrderBy() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like TrackerLive 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 TrackerLive, and based on these observations, apply Extract Interface, too.

1
<?php
2
//$global_query = "SELECT tracker_live.* FROM tracker_live";
3
4
class TrackerLive {
5
	public $db;
6
	static $global_query = "SELECT tracker_live.* FROM tracker_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. (TrackerLive)');
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['idents']) && !empty($flt['idents'])) {
38
				if (isset($flt['source'])) {
39
					$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output WHERE tracker_output.ident IN ('".implode("','",$flt['idents'])."') AND tracker_output.format_source IN ('".implode("','",$flt['source'])."')) spid ON spid.famtrackid = tracker_live.famtrackid";
40
				} else {
41
					$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output WHERE tracker_output.ident IN ('".implode("','",$flt['idents'])."')) spid ON spid.famtrackid = tracker_live.famtrackid";
42
				}
43
			}
44
		}
45
		if (isset($filter['source']) && !empty($filter['source'])) {
46
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
47
		}
48
		if (isset($filter['ident']) && !empty($filter['ident'])) {
49
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
50
		}
51
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
52
			$filter_query_date = '';
53
			
54
			if (isset($filter['year']) && $filter['year'] != '') {
55
				if ($globalDBdriver == 'mysql') {
56
					$filter_query_date .= " AND YEAR(tracker_output.date) = '".$filter['year']."'";
57
				} else {
58
					$filter_query_date .= " AND EXTRACT(YEAR FROM tracker_output.date) = '".$filter['year']."'";
59
				}
60
			}
61
			if (isset($filter['month']) && $filter['month'] != '') {
62
				if ($globalDBdriver == 'mysql') {
63
					$filter_query_date .= " AND MONTH(tracker_output.date) = '".$filter['month']."'";
64
				} else {
65
					$filter_query_date .= " AND EXTRACT(MONTH FROM tracker_output.date) = '".$filter['month']."'";
66
				}
67
			}
68
			if (isset($filter['day']) && $filter['day'] != '') {
69
				if ($globalDBdriver == 'mysql') {
70
					$filter_query_date .= " AND DAY(tracker_output.date) = '".$filter['day']."'";
71
				} else {
72
					$filter_query_date .= " AND EXTRACT(DAY FROM tracker_output.date) = '".$filter['day']."'";
73
				}
74
			}
75
			$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output".preg_replace('/^ AND/',' WHERE',$filter_query_date).") sd ON sd.famtrackid = tracker_live.famtrackid";
76
		}
77
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
78
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
79
		}
80
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
81
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
82
		if ($filter_query_where != '') {
83
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
84
		}
85
		$filter_query = $filter_query_join.$filter_query_where;
86
		return $filter_query;
87
	}
88
89
	/**
90
	* Gets all the spotter information based on the latest data entry
91
	*
92
	* @return Array the spotter information
93
	*
94
	*/
95
	public function getLiveTrackerData($limit = '', $sort = '', $filter = array())
96
	{
97
		global $globalDBdriver, $globalLiveInterval;
98
		$Tracker = new Tracker($this->db);
99
		date_default_timezone_set('UTC');
100
101
		$filter_query = $this->getFilter($filter);
102
		$limit_query = '';
103
		if ($limit != '')
104
		{
105
			$limit_array = explode(',', $limit);
106
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
107
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
108
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
109
			{
110
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
111
			}
112
		}
113
		$orderby_query = '';
114
		if ($sort != '')
115
		{
116
			$search_orderby_array = $this->getOrderBy();
117
			if (isset($search_orderby_array[$sort]['sql'])) 
118
			{
119
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
120
			}
121
		}
122
123
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
124
		if ($globalDBdriver == 'mysql') {
125
			//$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate";
126
			$query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate'.$filter_query.$orderby_query;
127
		} else {
128
			$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate".$filter_query.$orderby_query;
129
		}
130
		$spotter_array = $Tracker->getDataFromDB($query.$limit_query,array(),'',true);
131
132
		return $spotter_array;
133
	}
134
135
	/**
136
	* Gets Minimal Live Spotter data
137
	*
138
	* @return Array the spotter information
139
	*
140
	*/
141
	public function getMinLiveTrackerData($filter = array())
142
	{
143
		global $globalDBdriver, $globalLiveInterval;
144
		date_default_timezone_set('UTC');
145
146
		$filter_query = $this->getFilter($filter,true,true);
147
148
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
149
		if ($globalDBdriver == 'mysql') {
150
			$query  = 'SELECT tracker_live.ident, tracker_live.type,tracker_live.famtrackid, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
151
			FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate'.$filter_query." tracker_live.latitude <> 0 AND tracker_live.longitude <> 0";
152
		} else {
153
			$query  = "SELECT tracker_live.ident, tracker_live.type,tracker_live.famtrackid, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
154
			FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate".$filter_query." tracker_live.latitude <> '0' AND tracker_live.longitude <> '0'";
155
156
157
		}
158
//		$spotter_array = Spotter->getDataFromDB($query.$limit_query);
159
//		echo $query;
160
161
		try {
162
			$sth = $this->db->prepare($query);
163
			$sth->execute();
164
		} catch(PDOException $e) {
165
			echo $e->getMessage();
166
			die;
167
		}
168
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
169
170
		return $spotter_array;
171
	}
172
173
	/**
174
	* Gets Minimal Live Spotter data since xx seconds
175
	*
176
	* @return Array the spotter information
177
	*
178
	*/
179
	public function getMinLastLiveTrackerData($coord,$filter = array(),$limit = false)
180
	{
181
		global $globalDBdriver, $globalLiveInterval, $globalArchive, $globalMap3DTrackersLimit;
182
		date_default_timezone_set('UTC');
183
		$usecoord = false;
184
		if (is_array($coord) && !empty($coord)) {
185
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
186
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
187
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
188
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
189
			$usecoord = true;
190
		}
191
		$filter_query = $this->getFilter($filter,true,true);
192
193
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
194
		if (!isset($globalMap3DTrackersLimit) || $globalMap3DTrackersLimit == '') $globalMap3DTrackersLimit = '300';
195
		if ($globalDBdriver == 'mysql') {
196
			if (isset($globalArchive) && $globalArchive) {
197
				$query  = "SELECT * FROM (
198
					SELECT tracker_archive.ident, tracker_archive.famtrackid,tracker_archive.type,tracker_archive.latitude, tracker_archive.longitude, tracker_archive.altitude, tracker_archive.heading, tracker_archive.ground_speed, tracker_archive.date, tracker_archive.format_source 
199
					FROM tracker_archive INNER JOIN (SELECT famtrackid FROM tracker_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date) l ON l.famtrackid = tracker_archive.famtrackid ";
200
				if ($usecoord) $query .= "AND tracker_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_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...
201
				$query .= "UNION
202
					SELECT tracker_live.ident, tracker_live.famtrackid, tracker_live.type,tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
203
					FROM tracker_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date ";
204
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
205
				$query .= ") AS tracker
206
				    WHERE latitude <> '0' AND longitude <> '0' 
207
				    ORDER BY famtrackid, date";
208
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
209
			} else {
210
				$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
211
				    FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date ";
212
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
213
				$query .= "AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' 
214
				    ORDER BY tracker_live.famtrackid, tracker_live.date";
215
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
216
			}
217
		} else {
218
			if (isset($globalArchive) && $globalArchive) {
219
				$query  = "SELECT * FROM (
220
					SELECT tracker_archive.ident, tracker_archive.famtrackid,tracker_archive.type,tracker_archive.latitude, tracker_archive.longitude, tracker_archive.altitude, tracker_archive.heading, tracker_archive.ground_speed, tracker_archive.date, tracker_archive.format_source 
221
					FROM tracker_archive INNER JOIN (SELECT famtrackid FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date) l ON l.famtrackid = tracker_archive.famtrackid ";
222
				if ($usecoord) $query .= "AND tracker_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
223
				$query .= "UNION
224
					SELECT tracker_live.ident, tracker_live.famtrackid, tracker_live.type,tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
225
					FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date";
226
				if ($usecoord) $query .= " AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
227
				$query .= ") AS tracker
228
				    WHERE latitude <> '0' AND longitude <> '0' 
229
				    ORDER BY famtrackid, date";
230
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
231
			} else {
232
				$query  = "SELECT tracker_live.ident, tracker_live.famtrackid, tracker_live.type,tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
233
				    FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' ";
234
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
235
				$query .= "ORDER BY tracker_live.famtrackid, tracker_live.date";
236
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
237
			}
238
		}
239
240
		try {
241
			$sth = $this->db->prepare($query);
242
			$sth->execute();
243
		} catch(PDOException $e) {
244
			echo $e->getMessage();
245
			die;
246
		}
247
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
248
		return $spotter_array;
249
	}
250
251
	/**
252
	* Gets number of latest data entry
253
	*
254
	* @return String number of entry
255
	*
256
	*/
257
	public function getLiveTrackerCount($filter = array())
258
	{
259
		global $globalDBdriver, $globalLiveInterval;
260
		$filter_query = $this->getFilter($filter,true,true);
261
262
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
263
		if ($globalDBdriver == 'mysql') {
264
			$query = 'SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
265
		} else {
266
			$query = "SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
267
		}
268
		try {
269
			$sth = $this->db->prepare($query);
270
			$sth->execute();
271
		} catch(PDOException $e) {
272
			echo $e->getMessage();
273
			die;
274
		}
275
		$result = $sth->fetch(PDO::FETCH_ASSOC);
276
		$sth->closeCursor();
277
		return $result['nb'];
278
	}
279
280
	/**
281
	* Gets all the spotter information based on the latest data entry and coord
282
	*
283
	* @return Array the spotter information
284
	*
285
	*/
286
	public function getLiveTrackerDatabyCoord($coord, $filter = array())
287
	{
288
		global $globalDBdriver, $globalLiveInterval;
289
		$Tracker = new Tracker($this->db);
290
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
291
		$filter_query = $this->getFilter($filter);
292
293
		if (is_array($coord)) {
294
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
295
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
296
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
297
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
298
		} else return array();
299
		if ($globalDBdriver == 'mysql') {
300
			$query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND tracker_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND tracker_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.' GROUP BY tracker_live.famtrackid'.$filter_query;
301
		} else {
302
			$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE NOW() at time zone 'UTC'  - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." GROUP BY tracker_live.famtrackid".$filter_query;
303
		}
304
		$spotter_array = $Tracker->getDataFromDB($query);
305
		return $spotter_array;
306
	}
307
308
	/**
309
	* Gets all the spotter information based on the latest data entry and coord
310
	*
311
	* @return Array the spotter information
312
	*
313
	*/
314
	public function getMinLiveTrackerDatabyCoord($coord, $filter = array())
315
	{
316
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
317
		$Tracker = new Tracker($this->db);
318
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
319
		$filter_query = $this->getFilter($filter,true,true);
320
321
		if (is_array($coord)) {
322
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
323
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
324
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
325
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
326
		} else return array();
327
		/*
328
		if ($globalDBdriver == 'mysql') {
329
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
330
			FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' AND tracker_live.latitude BETWEEN ".$minlat.' AND '.$maxlat.' AND tracker_live.longitude BETWEEN '.$minlong.' AND '.$maxlong."
331
			ORDER BY tracker_live.famtrackid, tracker_live.date";
332
		} else {
333
			$query  = "SELECT tracker_live.ident, tracker_live.type,tracker_live.famtrackid, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
334
			FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date l.latitude BETWEEN ".$minlat." AND ".$maxlat." AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate".$filter_query." tracker_live.latitude <> '0' AND tracker_live.longitude <> '0'";
335
		}
336
		*/
337
		if ($globalDBdriver == 'mysql') {
338
			if (isset($globalArchive) && $globalArchive === TRUE) {
339
				$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
340
				    FROM tracker_live 
341
				    '.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= tracker_live.date 
342
				    AND tracker_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND tracker_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
343
				    AND tracker_live.latitude <> 0 AND tracker_live.longitude <> 0';
344
			} else {
345
				$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
346
				    FROM tracker_live 
347
				    INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate 
348
					FROM tracker_live l 
349
					WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
350
					AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
351
					GROUP BY l.famtrackid
352
				    ) s on tracker_live.famtrackid = s.famtrackid 
353
				    AND tracker_live.date = s.maxdate'.$filter_query.' tracker_live.latitude <> 0 AND tracker_live.longitude <> 0';
354
			}
355
		} else {
356
			if (isset($globalArchive) && $globalArchive === TRUE) {
357
				$query  = "SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
358
				    FROM tracker_live 
359
				    ".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date 
360
				    AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
361
				    AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
362
				    AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0'";
363
			} else {
364
				$query  = "SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
365
				    FROM tracker_live 
366
				    INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate 
367
					FROM tracker_live l 
368
					WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
369
					AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
370
					AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
371
					GROUP BY l.famtrackid
372
				    ) s on tracker_live.famtrackid = s.famtrackid 
373
				    AND tracker_live.date = s.maxdate".$filter_query." tracker_live.latitude <> '0' AND tracker_live.longitude <> '0'";
374
			}
375
		}
376
		$spotter_array = $Tracker->getDataFromDB($query);
377
		return $spotter_array;
378
	}
379
380
	/**
381
	* Gets all the spotter information based on a user's latitude and longitude
382
	*
383
	* @return Array the spotter information
384
	*
385
	*/
386
	public function getLatestTrackerForLayar($lat, $lng, $radius, $interval)
387
	{
388
		$Tracker = new Tracker($this->db);
389
		date_default_timezone_set('UTC');
390
		if ($lat != '') {
391
			if (!is_numeric($lat)) {
392
				return false;
393
			}
394
		}
395
		if ($lng != '')
396
		{
397
			if (!is_numeric($lng))
398
                        {
399
                                return false;
400
                        }
401
                }
402
403
                if ($radius != '')
404
                {
405
                        if (!is_numeric($radius))
406
                        {
407
                                return false;
408
                        }
409
                }
410
		$additional_query = '';
411
		if ($interval != '')
412
                {
413
                        if (!is_string($interval))
414
                        {
415
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
416
			        return false;
417
                        } else {
418
                if ($interval == '1m')
419
                {
420
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
421
                } else if ($interval == '15m'){
422
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= tracker_live.date ';
423
                } 
424
            }
425
                } else {
426
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';   
427
        }
428
429
                $query  = "SELECT tracker_live.*, ( 6371 * acos( cos( radians(:lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:lng) ) + sin( radians(:lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM tracker_live 
430
                   WHERE tracker_live.latitude <> '' 
431
                                   AND tracker_live.longitude <> '' 
432
                   ".$additional_query."
433
                   HAVING distance < :radius  
434
                                   ORDER BY distance";
435
436
                $spotter_array = $Tracker->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
437
438
                return $spotter_array;
439
        }
440
441
    
442
        /**
443
	* Gets all the spotter information based on a particular callsign
444
	*
445
	* @return Array the spotter information
446
	*
447
	*/
448
	public function getLastLiveTrackerDataByIdent($ident)
449
	{
450
		$Tracker = new Tracker($this->db);
451
		date_default_timezone_set('UTC');
452
453
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
454
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.ident = :ident GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
455
456
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident),'',true);
457
458
		return $spotter_array;
459
	}
460
461
        /**
462
	* Gets all the spotter information based on a particular callsign
463
	*
464
	* @return Array the spotter information
465
	*
466
	*/
467
	public function getDateLiveTrackerDataByIdent($ident,$date)
468
	{
469
		$Tracker = new Tracker($this->db);
470
		date_default_timezone_set('UTC');
471
472
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
473
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.ident = :ident AND l.date <= :date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
474
475
                $date = date('c',$date);
476
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
477
478
		return $spotter_array;
479
	}
480
481
        /**
482
	* Gets last spotter information based on a particular callsign
483
	*
484
	* @return Array the spotter information
485
	*
486
	*/
487
	public function getLastLiveTrackerDataById($id)
488
	{
489
		$Tracker = new Tracker($this->db);
490
		date_default_timezone_set('UTC');
491
492
		$id = filter_var($id, FILTER_SANITIZE_STRING);
493
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.famtrackid = :id GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
494
495
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id),'',true);
496
497
		return $spotter_array;
498
	}
499
500
        /**
501
	* Gets last spotter information based on a particular callsign
502
	*
503
	* @return Array the spotter information
504
	*
505
	*/
506
	public function getDateLiveTrackerDataById($id,$date)
507
	{
508
		$Tracker = new Tracker($this->db);
509
		date_default_timezone_set('UTC');
510
511
		$id = filter_var($id, FILTER_SANITIZE_STRING);
512
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.famtrackid = :id AND l.date <= :date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
513
                $date = date('c',$date);
514
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
515
516
		return $spotter_array;
517
	}
518
519
        /**
520
	* Gets altitude information based on a particular callsign
521
	*
522
	* @return Array the spotter information
523
	*
524
	*/
525
	public function getAltitudeLiveTrackerDataByIdent($ident)
526
	{
527
528
		date_default_timezone_set('UTC');
529
530
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
531
                $query  = 'SELECT tracker_live.altitude, tracker_live.date FROM tracker_live WHERE tracker_live.ident = :ident';
532
533
    		try {
534
			
535
			$sth = $this->db->prepare($query);
536
			$sth->execute(array(':ident' => $ident));
537
		} catch(PDOException $e) {
538
			echo $e->getMessage();
539
			die;
540
		}
541
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
542
543
		return $spotter_array;
544
	}
545
546
        /**
547
	* Gets all the spotter information based on a particular id
548
	*
549
	* @return Array the spotter information
550
	*
551
	*/
552
	public function getAllLiveTrackerDataById($id,$liveinterval = false)
553
	{
554
		global $globalDBdriver, $globalLiveInterval;
555
		date_default_timezone_set('UTC');
556
		$id = filter_var($id, FILTER_SANITIZE_STRING);
557
		//$query  = self::$global_query.' WHERE tracker_live.famtrackid = :id ORDER BY date';
558
		if ($globalDBdriver == 'mysql') {
559
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
560
			if ($liveinterval === true) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
561
			elseif ($liveinterval !== false) $query .= " AND date <= '".date('c',$liveinterval)."'";
562
			$query .= ' ORDER BY date';
563
		} else {
564
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
565
			if ($liveinterval === true) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
566
			elseif ($liveinterval !== false) $query .= " AND date <= '".date('c',$liveinterval)."'";
567
			$query .= ' ORDER BY date';
568
		}
569
570
		try {
571
			$sth = $this->db->prepare($query);
572
			$sth->execute(array(':id' => $id));
573
		} catch(PDOException $e) {
574
			echo $e->getMessage();
575
			die;
576
		}
577
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
578
		return $spotter_array;
579
	}
580
581
        /**
582
	* Gets all the spotter information based on a particular ident
583
	*
584
	* @return Array the spotter information
585
	*
586
	*/
587
	public function getAllLiveTrackerDataByIdent($ident)
588
	{
589
		date_default_timezone_set('UTC');
590
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
591
		$query  = self::$global_query.' WHERE tracker_live.ident = :ident';
592
    		try {
593
			
594
			$sth = $this->db->prepare($query);
595
			$sth->execute(array(':ident' => $ident));
596
		} catch(PDOException $e) {
597
			echo $e->getMessage();
598
			die;
599
		}
600
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
601
		return $spotter_array;
602
	}
603
604
605
	/**
606
	* Deletes all info in the table
607
	*
608
	* @return String success or false
609
	*
610
	*/
611
	public function deleteLiveTrackerData()
612
	{
613
		global $globalDBdriver;
614
		if ($globalDBdriver == 'mysql') {
615
			//$query  = "DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= tracker_live.date";
616
			$query  = 'DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= tracker_live.date';
617
            		//$query  = "DELETE FROM tracker_live WHERE tracker_live.id IN (SELECT tracker_live.id FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) >= tracker_live.date)";
618
		} else {
619
			$query  = "DELETE FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= tracker_live.date";
620
		}
621
        
622
    		try {
623
			
624
			$sth = $this->db->prepare($query);
625
			$sth->execute();
626
		} catch(PDOException $e) {
627
			return "error";
628
		}
629
630
		return "success";
631
	}
632
633
	/**
634
	* Deletes all info in the table for aircraft not seen since 2 HOUR
635
	*
636
	* @return String success or false
637
	*
638
	*/
639
	public function deleteLiveTrackerDataNotUpdated()
640
	{
641
		global $globalDBdriver, $globalDebug;
642
		if ($globalDBdriver == 'mysql') {
643
			//$query = 'SELECT famtrackid FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) >= tracker_live.date AND tracker_live.famtrackid NOT IN (SELECT famtrackid FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) < tracker_live.date) LIMIT 800 OFFSET 0';
644
    			$query = "SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND DATE_SUB(UTC_TIMESTAMP(), INTERVAL 2 HOUR) >= s.max_date LIMIT 1200 OFFSET 0";
645
    			try {
646
				
647
				$sth = $this->db->prepare($query);
648
				$sth->execute();
649
			} catch(PDOException $e) {
650
				return "error";
651
			}
652
			$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
653
                        $i = 0;
654
                        $j =0;
655
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
656
			foreach($all as $row)
657
			{
658
				$i++;
659
				$j++;
660
				if ($j == 30) {
661
					if ($globalDebug) echo ".";
662
				    	try {
663
						
664
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
665
						$sth->execute();
666
					} catch(PDOException $e) {
667
						return "error";
668
					}
669
                                	$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
670
                                	$j = 0;
671
				}
672
				$query_delete .= "'".$row['famtrackid']."',";
673
			}
674
			if ($i > 0) {
675
    				try {
676
					
677
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
678
					$sth->execute();
679
				} catch(PDOException $e) {
680
					return "error";
681
				}
682
			}
683
			return "success";
684
		} elseif ($globalDBdriver == 'pgsql') {
685
			//$query = "SELECT famtrackid FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= tracker_live.date AND tracker_live.famtrackid NOT IN (SELECT famtrackid FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' < tracker_live.date) LIMIT 800 OFFSET 0";
686
    			//$query = "SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0";
687
    			$query = "DELETE FROM tracker_live WHERE famtrackid IN (SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0)";
688
    			try {
689
				
690
				$sth = $this->db->prepare($query);
691
				$sth->execute();
692
			} catch(PDOException $e) {
693
				return "error";
694
			}
695
/*			$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
696
                        $i = 0;
697
                        $j =0;
698
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
699
			foreach($all as $row)
700
			{
701
				$i++;
702
				$j++;
703
				if ($j == 100) {
704
					if ($globalDebug) echo ".";
705
				    	try {
706
						
707
						$sth = $this->db->query(substr($query_delete,0,-1).")");
708
						//$sth->execute();
709
					} catch(PDOException $e) {
710
						return "error";
711
					}
712
                                	$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
713
                                	$j = 0;
714
				}
715
				$query_delete .= "'".$row['famtrackid']."',";
716
			}
717
			if ($i > 0) {
718
    				try {
719
					
720
					$sth = $this->db->query(substr($query_delete,0,-1).")");
721
					//$sth->execute();
722
				} catch(PDOException $e) {
723
					return "error";
724
				}
725
			}
726
*/
727
			return "success";
728
		}
729
	}
730
731
	/**
732
	* Deletes all info in the table for an ident
733
	*
734
	* @return String success or false
735
	*
736
	*/
737
	public function deleteLiveTrackerDataByIdent($ident)
738
	{
739
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
740
		$query  = 'DELETE FROM tracker_live WHERE ident = :ident';
741
        
742
    		try {
743
			
744
			$sth = $this->db->prepare($query);
745
			$sth->execute(array(':ident' => $ident));
746
		} catch(PDOException $e) {
747
			return "error";
748
		}
749
750
		return "success";
751
	}
752
753
	/**
754
	* Deletes all info in the table for an id
755
	*
756
	* @return String success or false
757
	*
758
	*/
759
	public function deleteLiveTrackerDataById($id)
760
	{
761
		$id = filter_var($id, FILTER_SANITIZE_STRING);
762
		$query  = 'DELETE FROM tracker_live WHERE famtrackid = :id';
763
        
764
    		try {
765
			
766
			$sth = $this->db->prepare($query);
767
			$sth->execute(array(':id' => $id));
768
		} catch(PDOException $e) {
769
			return "error";
770
		}
771
772
		return "success";
773
	}
774
775
776
	/**
777
	* Gets the aircraft ident within the last hour
778
	*
779
	* @return String the ident
780
	*
781
	*/
782
	public function getIdentFromLastHour($ident)
783
	{
784
		global $globalDBdriver, $globalTimezone;
785
		if ($globalDBdriver == 'mysql') {
786
			$query  = 'SELECT tracker_live.ident FROM tracker_live 
787
				WHERE tracker_live.ident = :ident 
788
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
789
				AND tracker_live.date < UTC_TIMESTAMP()';
790
			$query_data = array(':ident' => $ident);
791
		} else {
792
			$query  = "SELECT tracker_live.ident FROM tracker_live 
793
				WHERE tracker_live.ident = :ident 
794
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
795
				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
796
			$query_data = array(':ident' => $ident);
797
		}
798
		
799
		$sth = $this->db->prepare($query);
800
		$sth->execute($query_data);
801
		$ident_result='';
802
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
803
		{
804
			$ident_result = $row['ident'];
805
		}
806
		return $ident_result;
807
        }
808
809
	/**
810
	* Check recent aircraft
811
	*
812
	* @return String the ident
813
	*
814
	*/
815
	public function checkIdentRecent($ident)
816
	{
817
		global $globalDBdriver, $globalTimezone;
818
		if ($globalDBdriver == 'mysql') {
819
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
820
				WHERE tracker_live.ident = :ident 
821
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
822
//				AND tracker_live.date < UTC_TIMESTAMP()";
823
			$query_data = array(':ident' => $ident);
824
		} else {
825
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
826
				WHERE tracker_live.ident = :ident 
827
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
828
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
829
			$query_data = array(':ident' => $ident);
830
		}
831
		
832
		$sth = $this->db->prepare($query);
833
		$sth->execute($query_data);
834
		$ident_result='';
835
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
836
		{
837
			$ident_result = $row['famtrackid'];
838
		}
839
		return $ident_result;
840
        }
841
842
	/**
843
	* Check recent aircraft by id
844
	*
845
	* @return String the ident
846
	*
847
	*/
848
	public function checkIdRecent($id)
849
	{
850
		global $globalDBdriver, $globalTimezone;
851
		if ($globalDBdriver == 'mysql') {
852
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
853
				WHERE tracker_live.famtrackid = :id 
854
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
855
//				AND tracker_live.date < UTC_TIMESTAMP()";
856
			$query_data = array(':id' => $id);
857
		} else {
858
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
859
				WHERE tracker_live.famtrackid = :id 
860
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
861
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
862
			$query_data = array(':id' => $id);
863
		}
864
		
865
		$sth = $this->db->prepare($query);
866
		$sth->execute($query_data);
867
		$ident_result='';
868
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
869
		{
870
			$ident_result = $row['famtrackid'];
871
		}
872
		return $ident_result;
873
        }
874
875
	/**
876
	* Adds a new spotter data
877
	*
878
	* @param String $famtrackid the ID from flightaware
879
	* @param String $ident the flight ident
880
	* @param String $aircraft_icao the aircraft type
0 ignored issues
show
Bug introduced by
There is no parameter named $aircraft_icao. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
881
	* @param String $departure_airport_icao the departure airport
0 ignored issues
show
Bug introduced by
There is no parameter named $departure_airport_icao. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
882
	* @param String $arrival_airport_icao the arrival airport
0 ignored issues
show
Bug introduced by
There is no parameter named $arrival_airport_icao. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
883
	* @return String success or false
884
	*
885
	*/
886
	public function addLiveTrackerData($famtrackid = '', $ident = '', $latitude = '', $longitude = '', $altitude = '', $heading = '', $groundspeed = '', $date = '', $putinarchive = false, $comment = '', $type = '',$noarchive = false,$format_source = '', $source_name = '', $over_country = '')
887
	{
888
		global $globalURL, $globalArchive, $globalDebug;
889
		$Common = new Common();
890
		date_default_timezone_set('UTC');
891
892
		//getting the airline information
893
		if ($ident != '')
894
		{
895
			if (!is_string($ident))
896
			{
897
				return false;
898
			} 
899
		}
900
901
902
		if ($latitude != '')
903
		{
904
			if (!is_numeric($latitude))
905
			{
906
				return false;
907
			}
908
		} else return '';
909
910
		if ($longitude != '')
911
		{
912
			if (!is_numeric($longitude))
913
			{
914
				return false;
915
			}
916
		} else return '';
917
918
		if ($altitude != '')
919
		{
920
			if (!is_numeric($altitude))
921
			{
922
				return false;
923
			}
924
		} else $altitude = 0;
925
926
		if ($heading != '')
927
		{
928
			if (!is_numeric($heading))
929
			{
930
				return false;
931
			}
932
		} else $heading = 0;
933
934
		if ($groundspeed != '')
935
		{
936
			if (!is_numeric($groundspeed))
937
			{
938
				return false;
939
			}
940
		} else $groundspeed = 0;
941
		date_default_timezone_set('UTC');
942
		if ($date == '') $date = date("Y-m-d H:i:s", time());
943
944
        
945
		$famtrackid = filter_var($famtrackid,FILTER_SANITIZE_STRING);
946
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
947
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
948
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
949
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
950
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
951
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
952
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
953
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
954
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
955
		$comment = filter_var($comment,FILTER_SANITIZE_STRING);
956
		$type = filter_var($type,FILTER_SANITIZE_STRING);
957
958
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
959
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
960
            	
961
		$query = '';
962
		if ($globalArchive) {
963
			if ($globalDebug) echo '-- Delete previous data -- ';
964
			$query .= 'DELETE FROM tracker_live WHERE famtrackid = :famtrackid;';
965
		}
966
		$query  .= 'INSERT INTO tracker_live (famtrackid, ident, latitude, longitude, altitude, heading, ground_speed, date, format_source, source_name, over_country, comment, type) 
967
		VALUES (:famtrackid,:ident,:latitude,:longitude,:altitude,:heading,:groundspeed,:date,:format_source, :source_name, :over_country,:comment,:type)';
968
969
		$query_values = array(':famtrackid' => $famtrackid,':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':altitude' => $altitude,':heading' => $heading,':groundspeed' => $groundspeed,':date' => $date, ':format_source' => $format_source, ':source_name' => $source_name, ':over_country' => $over_country,':comment' => $comment,':type' => $type);
970
		try {
971
			$sth = $this->db->prepare($query);
972
			$sth->execute($query_values);
973
			$sth->closeCursor();
974
		} catch(PDOException $e) {
975
			return "error : ".$e->getMessage();
976
		}
977
                /*
978
                echo 'putinarchive : '.$putinarchive."\n";
979
                echo 'noarchive : '.$noarchive."\n";
980
                */
981
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
982
		    if ($globalDebug) echo '(Add to Tracker archive '.$famtrackid.' : ';
983
		    $TrackerArchive = new TrackerArchive($this->db);
984
		    $result =  $TrackerArchive->addTrackerArchiveData($famtrackid, $ident,$latitude, $longitude, $altitude, $heading, $groundspeed, $date, $putinarchive, $comment, $type,$noarchive,$format_source, $source_name, $over_country);
985
		    if ($globalDebug) echo $result.')';
986
		}
987
988
		return "success";
989
990
	}
991
992
	public function getOrderBy()
993
	{
994
		$orderby = array("aircraft_asc" => array("key" => "aircraft_asc", "value" => "Aircraft Type - ASC", "sql" => "ORDER BY tracker_live.aircraft_icao ASC"), "aircraft_desc" => array("key" => "aircraft_desc", "value" => "Aircraft Type - DESC", "sql" => "ORDER BY tracker_live.aircraft_icao DESC"),"manufacturer_asc" => array("key" => "manufacturer_asc", "value" => "Aircraft Manufacturer - ASC", "sql" => "ORDER BY tracker_live.aircraft_manufacturer ASC"), "manufacturer_desc" => array("key" => "manufacturer_desc", "value" => "Aircraft Manufacturer - DESC", "sql" => "ORDER BY tracker_live.aircraft_manufacturer DESC"),"airline_name_asc" => array("key" => "airline_name_asc", "value" => "Airline Name - ASC", "sql" => "ORDER BY tracker_live.airline_name ASC"), "airline_name_desc" => array("key" => "airline_name_desc", "value" => "Airline Name - DESC", "sql" => "ORDER BY tracker_live.airline_name DESC"), "ident_asc" => array("key" => "ident_asc", "value" => "Ident - ASC", "sql" => "ORDER BY tracker_live.ident ASC"), "ident_desc" => array("key" => "ident_desc", "value" => "Ident - DESC", "sql" => "ORDER BY tracker_live.ident DESC"), "airport_departure_asc" => array("key" => "airport_departure_asc", "value" => "Departure Airport - ASC", "sql" => "ORDER BY tracker_live.departure_airport_city ASC"), "airport_departure_desc" => array("key" => "airport_departure_desc", "value" => "Departure Airport - DESC", "sql" => "ORDER BY tracker_live.departure_airport_city DESC"), "airport_arrival_asc" => array("key" => "airport_arrival_asc", "value" => "Arrival Airport - ASC", "sql" => "ORDER BY tracker_live.arrival_airport_city ASC"), "airport_arrival_desc" => array("key" => "airport_arrival_desc", "value" => "Arrival Airport - DESC", "sql" => "ORDER BY tracker_live.arrival_airport_city DESC"), "date_asc" => array("key" => "date_asc", "value" => "Date - ASC", "sql" => "ORDER BY tracker_live.date ASC"), "date_desc" => array("key" => "date_desc", "value" => "Date - DESC", "sql" => "ORDER BY tracker_live.date DESC"));
995
		return $orderby;
996
	}
997
998
}
999
1000
1001
?>
1002