Issues (843)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

require/class.TrackerLive.php (4 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * This class is part of FlightAirmap. It's used for trackers live data
4
 *
5
 * Copyright (c) Ycarus (Yannick Chabanois) <[email protected]>
6
 * Licensed under AGPL license.
7
 * For more information see: https://www.flightairmap.com/
8
*/
9
//$global_query = "SELECT tracker_live.* FROM tracker_live";
10
11
class TrackerLive {
12
	public $db;
13
	static $global_query = "SELECT tracker_live.* FROM tracker_live";
14
15
	public function __construct($dbc = null) {
16
		$Connection = new Connection($dbc);
17
		$this->db = $Connection->db();
18
		if ($this->db === null) die('Error: No DB connection. (TrackerLive)');
19
	}
20
21
22
    /**
23
     * Get SQL query part for filter used
24
     * @param array $filter the filter
25
     * @param bool $where
26
     * @param bool $and
27
     * @return string the SQL part
28
     */
29
	public function getFilter($filter = array(),$where = false,$and = false) {
30
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
31
		$filters = array();
32
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
33
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
34
				$filters = $globalStatsFilters[$globalFilterName];
35
			} else {
36
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
37
			}
38
		}
39
		if (isset($filter[0]['source'])) {
40
			$filters = array_merge($filters,$filter);
41
		}
42
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
43
		$filter_query_join = '';
44
		$filter_query_where = '';
45
		foreach($filters as $flt) {
46
			if (isset($flt['idents']) && !empty($flt['idents'])) {
47
				if (isset($flt['source'])) {
48
					$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";
49
				} else {
50
					$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";
51
				}
52
			}
53
		}
54
		if (isset($filter['source']) && !empty($filter['source'])) {
55
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
56
		}
57
		if (isset($filter['ident']) && !empty($filter['ident'])) {
58
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
59
		}
60
		if (isset($filter['id']) && !empty($filter['id'])) {
61
			$filter_query_where .= " AND famtrackid = '".$filter['id']."'";
62
		}
63
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
64
			$filter_query_date = '';
65
			
66
			if (isset($filter['year']) && $filter['year'] != '') {
67
				if ($globalDBdriver == 'mysql') {
68
					$filter_query_date .= " AND YEAR(tracker_output.date) = '".$filter['year']."'";
69
				} else {
70
					$filter_query_date .= " AND EXTRACT(YEAR FROM tracker_output.date) = '".$filter['year']."'";
71
				}
72
			}
73
			if (isset($filter['month']) && $filter['month'] != '') {
74
				if ($globalDBdriver == 'mysql') {
75
					$filter_query_date .= " AND MONTH(tracker_output.date) = '".$filter['month']."'";
76
				} else {
77
					$filter_query_date .= " AND EXTRACT(MONTH FROM tracker_output.date) = '".$filter['month']."'";
78
				}
79
			}
80
			if (isset($filter['day']) && $filter['day'] != '') {
81
				if ($globalDBdriver == 'mysql') {
82
					$filter_query_date .= " AND DAY(tracker_output.date) = '".$filter['day']."'";
83
				} else {
84
					$filter_query_date .= " AND EXTRACT(DAY FROM tracker_output.date) = '".$filter['day']."'";
85
				}
86
			}
87
			$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output".preg_replace('/^ AND/',' WHERE',$filter_query_date).") sd ON sd.famtrackid = tracker_live.famtrackid";
88
		}
89
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
90
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
91
		}
92
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
93
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
94
		if ($filter_query_where != '') {
95
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
96
		}
97
		$filter_query = $filter_query_join.$filter_query_where;
98
		return $filter_query;
99
	}
100
101
    /**
102
     * Gets all the spotter information based on the latest data entry
103
     *
104
     * @param string $limit
105
     * @param string $sort
106
     * @param array $filter
107
     * @return array the spotter information
108
     */
109
	public function getLiveTrackerData($limit = '', $sort = '', $filter = array())
110
	{
111
		global $globalDBdriver, $globalLiveInterval;
112
		$Tracker = new Tracker($this->db);
113
		date_default_timezone_set('UTC');
114
115
		$filter_query = $this->getFilter($filter);
116
		$limit_query = '';
117
		if ($limit != '')
118
		{
119
			$limit_array = explode(',', $limit);
120
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
121
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
122
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
123
			{
124
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
125
			}
126
		}
127
		$orderby_query = '';
128
		if ($sort != '')
129
		{
130
			$search_orderby_array = $this->getOrderBy();
131
			if (isset($search_orderby_array[$sort]['sql'])) 
132
			{
133
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
134
			}
135
		}
136
137
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
138
		if ($globalDBdriver == 'mysql') {
139
			//$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";
140
			$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;
141
		} else {
142
			$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;
143
		}
144
		$spotter_array = $Tracker->getDataFromDB($query.$limit_query,array(),'',true);
145
146
		return $spotter_array;
147
	}
148
149
    /**
150
     * Gets Minimal Live Spotter data
151
     *
152
     * @param array $filter
153
     * @return array the spotter information
154
     */
155
	public function getMinLiveTrackerData($filter = array())
156
	{
157
		global $globalDBdriver, $globalLiveInterval;
158
		date_default_timezone_set('UTC');
159
160
		$filter_query = $this->getFilter($filter,true,true);
161
162
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
163
		if ($globalDBdriver == 'mysql') {
164
			$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 
165
			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";
166
		} else {
167
			$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 
168
			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'";
169
170
171
		}
172
//		$spotter_array = Spotter->getDataFromDB($query.$limit_query);
173
//		echo $query;
174
175
		try {
176
			$sth = $this->db->prepare($query);
177
			$sth->execute();
178
		} catch(PDOException $e) {
179
			echo $e->getMessage();
180
			die;
181
		}
182
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
183
184
		return $spotter_array;
185
	}
186
187
    /**
188
     * Gets Minimal Live Spotter data since xx seconds
189
     *
190
     * @param $coord
191
     * @param array $filter
192
     * @param bool $limit
193
     * @return array the spotter information
194
     */
195
	public function getMinLastLiveTrackerData($coord,$filter = array(),$limit = false)
196
	{
197
		global $globalDBdriver, $globalLiveInterval, $globalArchive, $globalMap3DTrackersLimit;
198
		date_default_timezone_set('UTC');
199
		$usecoord = false;
200
		if (is_array($coord) && !empty($coord)) {
201
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
202
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
203
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
204
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
205
			$usecoord = true;
206
		}
207
		$filter_query = $this->getFilter($filter,true,true);
208
209
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
210
		if (!isset($globalMap3DTrackersLimit) || $globalMap3DTrackersLimit == '') $globalMap3DTrackersLimit = '300';
211
		if ($globalDBdriver == 'mysql') {
212
			if (isset($globalArchive) && $globalArchive) {
213
				$query  = "SELECT * FROM (
214
					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 
215
					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 ";
216
				if ($usecoord) $query .= "AND tracker_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
0 ignored issues
show
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...
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...
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...
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...
217
				$query .= "UNION
218
					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 
219
					FROM tracker_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date ";
220
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
221
				$query .= ") AS tracker
222
				    WHERE latitude <> '0' AND longitude <> '0' 
223
				    ORDER BY famtrackid, date";
224
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
225
			} else {
226
				$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 
227
				    FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date ";
228
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
229
				$query .= "AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' 
230
				    ORDER BY tracker_live.famtrackid, tracker_live.date";
231
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
232
			}
233
		} else {
234
			if (isset($globalArchive) && $globalArchive) {
235
				$query  = "SELECT * FROM (
236
					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 
237
					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 ";
238
				if ($usecoord) $query .= "AND tracker_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
239
				$query .= "UNION
240
					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 
241
					FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date";
242
				if ($usecoord) $query .= " AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
243
				$query .= ") AS tracker
244
				    WHERE latitude <> '0' AND longitude <> '0' 
245
				    ORDER BY famtrackid, date";
246
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
247
			} else {
248
				$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 
249
				    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' ";
250
				if ($usecoord) $query .= "AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
251
				$query .= "ORDER BY tracker_live.famtrackid, tracker_live.date";
252
				if ($limit) $query .= " LIMIT ".$globalMap3DTrackersLimit;
253
			}
254
		}
255
256
		try {
257
			$sth = $this->db->prepare($query);
258
			$sth->execute();
259
		} catch(PDOException $e) {
260
			echo $e->getMessage();
261
			die;
262
		}
263
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
264
		return $spotter_array;
265
	}
266
267
    /**
268
     * Gets number of latest data entry
269
     *
270
     * @param array $filter
271
     * @return String number of entry
272
     */
273
	public function getLiveTrackerCount($filter = array())
274
	{
275
		global $globalDBdriver, $globalLiveInterval;
276
		$filter_query = $this->getFilter($filter,true,true);
277
278
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
279
		if ($globalDBdriver == 'mysql') {
280
			$query = 'SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
281
		} else {
282
			$query = "SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
283
		}
284
		try {
285
			$sth = $this->db->prepare($query);
286
			$sth->execute();
287
		} catch(PDOException $e) {
288
			echo $e->getMessage();
289
			die;
290
		}
291
		$result = $sth->fetch(PDO::FETCH_ASSOC);
292
		$sth->closeCursor();
293
		return $result['nb'];
294
	}
295
296
    /**
297
     * Gets all the spotter information based on the latest data entry and coord
298
     *
299
     * @param $coord
300
     * @param array $filter
301
     * @return array the spotter information
302
     */
303
	public function getLiveTrackerDatabyCoord($coord, $filter = array())
304
	{
305
		global $globalDBdriver, $globalLiveInterval;
306
		$Tracker = new Tracker($this->db);
307
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
308
		$filter_query = $this->getFilter($filter);
309
310
		if (is_array($coord)) {
311
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
312
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
313
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
314
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
315
		} else return array();
316
		if ($globalDBdriver == 'mysql') {
317
			$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;
318
		} else {
319
			$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;
320
		}
321
		$spotter_array = $Tracker->getDataFromDB($query);
322
		return $spotter_array;
323
	}
324
325
    /**
326
     * Gets all the spotter information based on the latest data entry and coord
327
     *
328
     * @param $coord
329
     * @param array $filter
330
     * @return array the spotter information
331
     */
332
	public function getMinLiveTrackerDatabyCoord($coord, $filter = array())
333
	{
334
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
335
		$Tracker = new Tracker($this->db);
336
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
337
		$filter_query = $this->getFilter($filter,true,true);
338
339
		if (is_array($coord)) {
340
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
341
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
342
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
343
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
344
		} else return array();
345
		/*
346
		if ($globalDBdriver == 'mysql') {
347
			$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 
348
			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."
349
			ORDER BY tracker_live.famtrackid, tracker_live.date";
350
		} else {
351
			$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 
352
			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'";
353
		}
354
		*/
355
		if ($globalDBdriver == 'mysql') {
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.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= tracker_live.date 
360
				    AND tracker_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND tracker_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
361
				    AND tracker_live.latitude <> 0 AND tracker_live.longitude <> 0 ORDER BY date DESC';
362
			} else {
363
				$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 
364
				    FROM tracker_live 
365
				    INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate 
366
					FROM tracker_live l 
367
					WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
368
					AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
369
					GROUP BY l.famtrackid
370
				    ) s on tracker_live.famtrackid = s.famtrackid 
371
				    AND tracker_live.date = s.maxdate'.$filter_query.' tracker_live.latitude <> 0 AND tracker_live.longitude <> 0 ORDER BY date DESC';
372
			}
373
		} else {
374
			if (isset($globalArchive) && $globalArchive === TRUE) {
375
				$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 
376
				    FROM tracker_live 
377
				    ".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date 
378
				    AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
379
				    AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
380
				    AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' ORDER BY date DESC";
381
			} else {
382
				$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 
383
				    FROM tracker_live 
384
				    INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate 
385
					FROM tracker_live l 
386
					WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
387
					AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
388
					AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
389
					GROUP BY l.famtrackid
390
				    ) s on tracker_live.famtrackid = s.famtrackid 
391
				    AND tracker_live.date = s.maxdate".$filter_query." tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' ORDER BY date DESC";
392
			}
393
		}
394
		$spotter_array = $Tracker->getDataFromDB($query);
395
		return $spotter_array;
396
	}
397
398
    /**
399
     * Gets all the spotter information based on a user's latitude and longitude
400
     *
401
     * @param $lat
402
     * @param $lng
403
     * @param $radius
404
     * @param $interval
405
     * @return array the spotter information
406
     */
407
	public function getLatestTrackerForLayar($lat, $lng, $radius, $interval)
408
	{
409
		$Tracker = new Tracker($this->db);
410
		date_default_timezone_set('UTC');
411
		if ($lat != '') {
412
			if (!is_numeric($lat)) {
413
				return array();
414
			}
415
		}
416
		if ($lng != '')
417
		{
418
			if (!is_numeric($lng))
419
			{
420
				return array();
421
			}
422
		}
423
424
		if ($radius != '')
425
		{
426
			if (!is_numeric($radius))
427
			{
428
				return array();
429
			}
430
		}
431
		$additional_query = '';
432
		if ($interval != '')
433
		{
434
			if (!is_string($interval))
435
			{
436
				//$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
437
				return array();
438
			} else {
439
				if ($interval == '1m')
440
				{
441
					$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
442
				} else if ($interval == '15m'){
443
					$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= tracker_live.date ';
444
				}
445
			}
446
		} else {
447
			$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
448
		}
449
450
		$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 
451
                   WHERE tracker_live.latitude <> '' 
452
                                   AND tracker_live.longitude <> '' 
453
                   ".$additional_query."
454
                   HAVING distance < :radius  
455
                                   ORDER BY distance";
456
457
		$spotter_array = $Tracker->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
458
459
		return $spotter_array;
460
	}
461
462
463
    /**
464
     * Gets all the spotter information based on a particular callsign
465
     *
466
     * @param $ident
467
     * @return array the spotter information
468
     */
469
	public function getLastLiveTrackerDataByIdent($ident)
470
	{
471
		$Tracker = new Tracker($this->db);
472
		date_default_timezone_set('UTC');
473
474
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
475
                $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';
476
477
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident),'',true);
478
479
		return $spotter_array;
480
	}
481
482
    /**
483
     * Gets all the spotter information based on a particular callsign
484
     *
485
     * @param $ident
486
     * @param $date
487
     * @return array the spotter information
488
     */
489
	public function getDateLiveTrackerDataByIdent($ident,$date)
490
	{
491
		$Tracker = new Tracker($this->db);
492
		date_default_timezone_set('UTC');
493
494
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
495
                $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';
496
497
                $date = date('c',$date);
498
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
499
500
		return $spotter_array;
501
	}
502
503
    /**
504
     * Gets last spotter information based on a particular callsign
505
     *
506
     * @param $id
507
     * @return array the spotter information
508
     */
509
	public function getLastLiveTrackerDataById($id)
510
	{
511
		$Tracker = new Tracker($this->db);
512
		date_default_timezone_set('UTC');
513
514
		$id = filter_var($id, FILTER_SANITIZE_STRING);
515
                $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';
516
517
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id),'',true);
518
519
		return $spotter_array;
520
	}
521
522
    /**
523
     * Gets last spotter information based on a particular callsign
524
     *
525
     * @param $id
526
     * @param $date
527
     * @return array the spotter information
528
     */
529
	public function getDateLiveTrackerDataById($id,$date)
530
	{
531
		$Tracker = new Tracker($this->db);
532
		date_default_timezone_set('UTC');
533
534
		$id = filter_var($id, FILTER_SANITIZE_STRING);
535
                $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';
536
                $date = date('c',$date);
537
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
538
539
		return $spotter_array;
540
	}
541
542
    /**
543
     * Gets altitude information based on a particular callsign
544
     *
545
     * @param $ident
546
     * @return array the spotter information
547
     */
548
	public function getAltitudeLiveTrackerDataByIdent($ident)
549
	{
550
551
		date_default_timezone_set('UTC');
552
553
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
554
                $query  = 'SELECT tracker_live.altitude, tracker_live.date FROM tracker_live WHERE tracker_live.ident = :ident';
555
556
    		try {
557
			
558
			$sth = $this->db->prepare($query);
559
			$sth->execute(array(':ident' => $ident));
560
		} catch(PDOException $e) {
561
			echo $e->getMessage();
562
			die;
563
		}
564
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
565
566
		return $spotter_array;
567
	}
568
569
    /**
570
     * Gets all the spotter information based on a particular id
571
     *
572
     * @param $id
573
     * @param bool $liveinterval
574
     * @return array the spotter information
575
     */
576
	public function getAllLiveTrackerDataById($id,$liveinterval = false)
577
	{
578
		global $globalDBdriver, $globalLiveInterval;
579
		date_default_timezone_set('UTC');
580
		$id = filter_var($id, FILTER_SANITIZE_STRING);
581
		//$query  = self::$global_query.' WHERE tracker_live.famtrackid = :id ORDER BY date';
582
		if ($globalDBdriver == 'mysql') {
583
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
584
			if ($liveinterval === true) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
585
			elseif ($liveinterval !== false) $query .= " AND date <= '".date('c',$liveinterval)."'";
586
			$query .= ' ORDER BY date';
587
		} else {
588
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
589
			if ($liveinterval === true) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
590
			elseif ($liveinterval !== false) $query .= " AND date <= '".date('c',$liveinterval)."'";
591
			$query .= ' ORDER BY date';
592
		}
593
594
		try {
595
			$sth = $this->db->prepare($query);
596
			$sth->execute(array(':id' => $id));
597
		} catch(PDOException $e) {
598
			echo $e->getMessage();
599
			die;
600
		}
601
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
602
		return $spotter_array;
603
	}
604
605
    /**
606
     * Gets all the spotter information based on a particular ident
607
     *
608
     * @param $ident
609
     * @return array the spotter information
610
     */
611
	public function getAllLiveTrackerDataByIdent($ident)
612
	{
613
		date_default_timezone_set('UTC');
614
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
615
		$query  = self::$global_query.' WHERE tracker_live.ident = :ident';
616
    		try {
617
			
618
			$sth = $this->db->prepare($query);
619
			$sth->execute(array(':ident' => $ident));
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
	/**
630
	* Deletes all info in the table
631
	*
632
	* @return String success or false
633
	*
634
	*/
635
	public function deleteLiveTrackerData()
636
	{
637
		global $globalDBdriver;
638
		if ($globalDBdriver == 'mysql') {
639
			//$query  = "DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= tracker_live.date";
640
			$query  = 'DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= tracker_live.date';
641
            		//$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)";
642
		} else {
643
			$query  = "DELETE FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= tracker_live.date";
644
		}
645
        
646
    		try {
647
			
648
			$sth = $this->db->prepare($query);
649
			$sth->execute();
650
		} catch(PDOException $e) {
651
			return "error";
652
		}
653
654
		return "success";
655
	}
656
657
	/**
658
	* Deletes all info in the table for aircraft not seen since 2 HOUR
659
	*
660
	* @return String success or false
661
	*
662
	*/
663
	public function deleteLiveTrackerDataNotUpdated()
664
	{
665
		global $globalDBdriver, $globalDebug;
666
		if ($globalDBdriver == 'mysql') {
667
			//$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';
668
    			$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";
669
    			try {
670
				
671
				$sth = $this->db->prepare($query);
672
				$sth->execute();
673
			} catch(PDOException $e) {
674
				return "error";
675
			}
676
			$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
677
                        $i = 0;
678
                        $j =0;
679
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
680
			foreach($all as $row)
681
			{
682
				$i++;
683
				$j++;
684
				if ($j == 30) {
685
					if ($globalDebug) echo ".";
686
				    	try {
687
						
688
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
689
						$sth->execute();
690
					} catch(PDOException $e) {
691
						return "error";
692
					}
693
                                	$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
694
                                	$j = 0;
695
				}
696
				$query_delete .= "'".$row['famtrackid']."',";
697
			}
698
			if ($i > 0) {
699
    				try {
700
					
701
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
702
					$sth->execute();
703
				} catch(PDOException $e) {
704
					return "error";
705
				}
706
			}
707
			return "success";
708
		} elseif ($globalDBdriver == 'pgsql') {
709
			//$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";
710
    			//$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";
711
    			$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)";
712
    			try {
713
				
714
				$sth = $this->db->prepare($query);
715
				$sth->execute();
716
			} catch(PDOException $e) {
717
				return "error";
718
			}
719
/*			$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
720
                        $i = 0;
721
                        $j =0;
722
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
723
			foreach($all as $row)
724
			{
725
				$i++;
726
				$j++;
727
				if ($j == 100) {
728
					if ($globalDebug) echo ".";
729
				    	try {
730
						
731
						$sth = $this->db->query(substr($query_delete,0,-1).")");
732
						//$sth->execute();
733
					} catch(PDOException $e) {
734
						return "error";
735
					}
736
                                	$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
737
                                	$j = 0;
738
				}
739
				$query_delete .= "'".$row['famtrackid']."',";
740
			}
741
			if ($i > 0) {
742
    				try {
743
					
744
					$sth = $this->db->query(substr($query_delete,0,-1).")");
745
					//$sth->execute();
746
				} catch(PDOException $e) {
747
					return "error";
748
				}
749
			}
750
*/
751
			return "success";
752
		}
753
	}
754
755
    /**
756
     * Deletes all info in the table for an ident
757
     *
758
     * @param $ident
759
     * @return String success or false
760
     */
761
	public function deleteLiveTrackerDataByIdent($ident)
762
	{
763
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
764
		$query  = 'DELETE FROM tracker_live WHERE ident = :ident';
765
        
766
    		try {
767
			
768
			$sth = $this->db->prepare($query);
769
			$sth->execute(array(':ident' => $ident));
770
		} catch(PDOException $e) {
771
			return "error";
772
		}
773
774
		return "success";
775
	}
776
777
    /**
778
     * Deletes all info in the table for an id
779
     *
780
     * @param $id
781
     * @return String success or false
782
     */
783
	public function deleteLiveTrackerDataById($id)
784
	{
785
		$id = filter_var($id, FILTER_SANITIZE_STRING);
786
		$query  = 'DELETE FROM tracker_live WHERE famtrackid = :id';
787
        
788
    		try {
789
			
790
			$sth = $this->db->prepare($query);
791
			$sth->execute(array(':id' => $id));
792
		} catch(PDOException $e) {
793
			return "error";
794
		}
795
796
		return "success";
797
	}
798
799
800
    /**
801
     * Gets the aircraft ident within the last hour
802
     *
803
     * @param $ident
804
     * @return String the ident
805
     */
806
	public function getIdentFromLastHour($ident)
807
	{
808
		global $globalDBdriver, $globalTimezone;
809
		if ($globalDBdriver == 'mysql') {
810
			$query  = 'SELECT tracker_live.ident FROM tracker_live 
811
				WHERE tracker_live.ident = :ident 
812
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
813
				AND tracker_live.date < UTC_TIMESTAMP()';
814
			$query_data = array(':ident' => $ident);
815
		} else {
816
			$query  = "SELECT tracker_live.ident FROM tracker_live 
817
				WHERE tracker_live.ident = :ident 
818
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
819
				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
820
			$query_data = array(':ident' => $ident);
821
		}
822
		
823
		$sth = $this->db->prepare($query);
824
		$sth->execute($query_data);
825
		$ident_result='';
826
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
827
		{
828
			$ident_result = $row['ident'];
829
		}
830
		return $ident_result;
831
        }
832
833
    /**
834
     * Check recent aircraft
835
     *
836
     * @param $ident
837
     * @return String the ident
838
     */
839
	public function checkIdentRecent($ident)
840
	{
841
		global $globalDBdriver, $globalTimezone;
842
		if ($globalDBdriver == 'mysql') {
843
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
844
				WHERE tracker_live.ident = :ident 
845
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
846
//				AND tracker_live.date < UTC_TIMESTAMP()";
847
			$query_data = array(':ident' => $ident);
848
		} else {
849
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
850
				WHERE tracker_live.ident = :ident 
851
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
852
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
853
			$query_data = array(':ident' => $ident);
854
		}
855
		
856
		$sth = $this->db->prepare($query);
857
		$sth->execute($query_data);
858
		$ident_result='';
859
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
860
		{
861
			$ident_result = $row['famtrackid'];
862
		}
863
		return $ident_result;
864
        }
865
866
    /**
867
     * Check recent aircraft by id
868
     *
869
     * @param $id
870
     * @return String the ident
871
     */
872
	public function checkIdRecent($id)
873
	{
874
		global $globalDBdriver, $globalTimezone;
875
		if ($globalDBdriver == 'mysql') {
876
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
877
				WHERE tracker_live.famtrackid = :id 
878
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
879
//				AND tracker_live.date < UTC_TIMESTAMP()";
880
			$query_data = array(':id' => $id);
881
		} else {
882
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
883
				WHERE tracker_live.famtrackid = :id 
884
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
885
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
886
			$query_data = array(':id' => $id);
887
		}
888
		
889
		$sth = $this->db->prepare($query);
890
		$sth->execute($query_data);
891
		$ident_result='';
892
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
893
		{
894
			$ident_result = $row['famtrackid'];
895
		}
896
		return $ident_result;
897
        }
898
899
    /**
900
     * Adds a new spotter data
901
     *
902
     * @param String $famtrackid the ID from flightaware
903
     * @param String $ident the flight ident
904
     * @param string $latitude
905
     * @param string $longitude
906
     * @param string $altitude
907
     * @param string $heading
908
     * @param string $groundspeed
909
     * @param string $date
910
     * @param bool $putinarchive
911
     * @param string $comment
912
     * @param string $type
913
     * @param bool $noarchive
914
     * @param string $format_source
915
     * @param string $source_name
916
     * @param string $over_country
917
     * @return String success or false
918
     */
919
	public function addLiveTrackerData($famtrackid = '', $ident = '', $latitude = '', $longitude = '', $altitude = '', $heading = '', $groundspeed = '', $date = '', $putinarchive = false, $comment = '', $type = '',$noarchive = false,$format_source = '', $source_name = '', $over_country = '')
920
	{
921
		global $globalURL, $globalArchive, $globalDebug;
922
		$Common = new Common();
923
		date_default_timezone_set('UTC');
924
925
		//getting the airline information
926
		if ($ident != '')
927
		{
928
			if (!is_string($ident))
929
			{
930
				return false;
931
			} 
932
		}
933
934
935
		if ($latitude != '')
936
		{
937
			if (!is_numeric($latitude))
938
			{
939
				return false;
940
			}
941
		} else return '';
942
943
		if ($longitude != '')
944
		{
945
			if (!is_numeric($longitude))
946
			{
947
				return false;
948
			}
949
		} else return '';
950
951
		if ($altitude != '')
952
		{
953
			if (!is_numeric($altitude))
954
			{
955
				return false;
956
			}
957
		} else $altitude = 0;
958
959
		if ($heading != '')
960
		{
961
			if (!is_numeric($heading))
962
			{
963
				return false;
964
			}
965
		} else $heading = 0;
966
967
		if ($groundspeed != '')
968
		{
969
			if (!is_numeric($groundspeed))
970
			{
971
				return false;
972
			}
973
		} else $groundspeed = 0;
974
		date_default_timezone_set('UTC');
975
		if ($date == '') $date = date("Y-m-d H:i:s", time());
976
977
        
978
		$famtrackid = filter_var($famtrackid,FILTER_SANITIZE_STRING);
979
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
980
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
981
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
982
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
983
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
984
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
985
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
986
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
987
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
988
		$comment = filter_var($comment,FILTER_SANITIZE_STRING);
989
		$type = filter_var($type,FILTER_SANITIZE_STRING);
990
991
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
992
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
993
            	
994
		$query = '';
995
		if ($globalArchive) {
996
			if ($globalDebug) echo '-- Delete previous data -- ';
997
			$query .= 'DELETE FROM tracker_live WHERE famtrackid = :famtrackid;';
998
		}
999
		$query  .= 'INSERT INTO tracker_live (famtrackid, ident, latitude, longitude, altitude, heading, ground_speed, date, format_source, source_name, over_country, comment, type) 
1000
		VALUES (:famtrackid,:ident,:latitude,:longitude,:altitude,:heading,:groundspeed,:date,:format_source, :source_name, :over_country,:comment,:type)';
1001
1002
		$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);
1003
		try {
1004
			$sth = $this->db->prepare($query);
1005
			$sth->execute($query_values);
1006
			$sth->closeCursor();
1007
		} catch(PDOException $e) {
1008
			return "error : ".$e->getMessage();
1009
		}
1010
                /*
1011
                echo 'putinarchive : '.$putinarchive."\n";
1012
                echo 'noarchive : '.$noarchive."\n";
1013
                */
1014
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
1015
		    if ($globalDebug) echo '(Add to Tracker archive '.$famtrackid.' : ';
1016
		    $TrackerArchive = new TrackerArchive($this->db);
1017
		    $result =  $TrackerArchive->addTrackerArchiveData($famtrackid, $ident,$latitude, $longitude, $altitude, $heading, $groundspeed, $date, $putinarchive, $comment, $type,$noarchive,$format_source, $source_name, $over_country);
1018
		    if ($globalDebug) echo $result.')';
1019
		}
1020
1021
		return "success";
1022
1023
	}
1024
1025
	public function getOrderBy()
1026
	{
1027
		$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"));
1028
		return $orderby;
1029
	}
1030
1031
}
1032
1033
1034
?>
1035