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

MarineLive   D

Complexity

Total Complexity 164

Size/Duplication

Total Lines 944
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

25 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
F getFilter() 0 68 36
D getLiveMarineData() 0 40 9
B getMinLiveMarineData() 0 27 4
F getMinLastLiveMarineData() 0 66 22
B getLiveMarineCount() 0 22 4
A getLiveMarineDatabyCoord() 0 21 4
B getMinLiveMarineDatabyCoord() 0 25 4
C getLatestMarineForLayar() 0 54 11
A getLastLiveMarineDataByIdent() 0 12 1
A getDateLiveMarineDataByIdent() 0 13 1
A getLastLiveMarineDataById() 0 12 1
A getDateLiveMarineDataById() 0 12 1
B getAllLiveMarineDataById() 0 26 5
A getAllLiveMarineDataByIdent() 0 16 2
A deleteLiveMarineData() 0 21 3
C deleteLiveMarineDataNotUpdated() 0 91 11
A deleteLiveMarineDataByIdent() 0 15 2
A deleteLiveMarineDataById() 0 15 2
B getIdentFromLastHour() 0 26 3
B checkIdentRecent() 0 26 3
B checkIdRecent() 0 26 3
B checkMMSIRecent() 0 26 3
F addLiveMarineData() 0 97 26
A getOrderBy() 0 5 1

How to fix   Complexity   

Complex Class

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

1
<?php
2
//$global_query = "SELECT marine_live.* FROM marine_live";
3
4
class MarineLive {
5
	public $db;
6
	static $global_query = "SELECT marine_live.* FROM marine_live";
7
8
	public function __construct($dbc = null) {
9
		$Connection = new Connection($dbc);
10
		$this->db = $Connection->db();
11
		if ($this->db === null) die('Error: No DB connection.');
12
	}
13
14
15
	/**
16
	* Get SQL query part for filter used
17
	* @param Array $filter the filter
18
	* @return Array the SQL part
19
	*/
20
	public function getFilter($filter = array(),$where = false,$and = false) {
21
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
22
		$filters = array();
23
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
24
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
25
				$filters = $globalStatsFilters[$globalFilterName];
26
			} else {
27
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
28
			}
29
		}
30
		if (isset($filter[0]['source'])) {
31
			$filters = array_merge($filters,$filter);
32
		}
33
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
34
		$filter_query_join = '';
35
		$filter_query_where = '';
36
		foreach($filters as $flt) {
37
			if (isset($flt['idents']) && !empty($flt['idents'])) {
38
				if (isset($flt['source'])) {
39
					$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output WHERE marine_output.ident IN ('".implode("','",$flt['idents'])."') AND marine_output.format_source IN ('".implode("','",$flt['source'])."')) spid ON spid.fammarine_id = marine_live.fammarine_id";
40
				} else {
41
					$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output WHERE marine_output.ident IN ('".implode("','",$flt['idents'])."')) spid ON spid.fammarine_id = marine_live.fammarine_id";
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(marine_output.date) = '".$filter['year']."'";
57
				} else {
58
					$filter_query_date .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
59
				}
60
			}
61
			if (isset($filter['month']) && $filter['month'] != '') {
62
				if ($globalDBdriver == 'mysql') {
63
					$filter_query_date .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
64
				} else {
65
					$filter_query_date .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
66
				}
67
			}
68
			if (isset($filter['day']) && $filter['day'] != '') {
69
				if ($globalDBdriver == 'mysql') {
70
					$filter_query_date .= " AND DAY(marine_output.date) = '".$filter['day']."'";
71
				} else {
72
					$filter_query_date .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
73
				}
74
			}
75
			$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output".preg_replace('/^ AND/',' WHERE',$filter_query_date).") sd ON sd.fammarine_id = marine_live.fammarine_id";
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 getLiveMarineData($limit = '', $sort = '', $filter = array())
96
	{
97
		global $globalDBdriver, $globalLiveInterval;
98
		$Marine = new Marine($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
		if ($orderby_query == '') $orderby_query= ' ORDER BY date DESC';
123
124
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
125
		if ($globalDBdriver == 'mysql') {
126
			//$query  = "SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND) <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate";
127
			$query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate'.$filter_query.$orderby_query;
128
		} else {
129
			$query  = "SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate".$filter_query.$orderby_query;
130
		}
131
		$spotter_array = $Marine->getDataFromDB($query.$limit_query,array(),'',true);
132
133
		return $spotter_array;
134
	}
135
136
	/**
137
	* Gets Minimal Live Spotter data
138
	*
139
	* @return Array the spotter information
140
	*
141
	*/
142
	public function getMinLiveMarineData($filter = array())
143
	{
144
		global $globalDBdriver, $globalLiveInterval;
145
		date_default_timezone_set('UTC');
146
147
		$filter_query = $this->getFilter($filter,true,true);
148
149
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
150
		if ($globalDBdriver == 'mysql') {
151
			$query  = 'SELECT marine_live.mmsi, marine_live.ident, marine_live.type,marine_live.fammarine_id, marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
152
			FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate'.$filter_query." marine_live.latitude <> 0 AND marine_live.longitude <> 0";
153
		} else {
154
			$query  = "SELECT marine_live.mmsi, marine_live.ident, marine_live.type,marine_live.fammarine_id, marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
155
			FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate".$filter_query." marine_live.latitude <> '0' AND marine_live.longitude <> '0'";
156
		}
157
158
		try {
159
			$sth = $this->db->prepare($query);
160
			$sth->execute();
161
		} catch(PDOException $e) {
162
			echo $e->getMessage();
163
			die;
164
		}
165
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
166
167
		return $spotter_array;
168
	}
169
170
	/**
171
	* Gets Minimal Live Spotter data since xx seconds
172
	*
173
	* @return Array the spotter information
174
	*
175
	*/
176
	public function getMinLastLiveMarineData($coord = array(),$filter = array(), $limit = false)
177
	{
178
		global $globalDBdriver, $globalLiveInterval, $globalMap3DMarinesLimit;
179
		date_default_timezone_set('UTC');
180
		if (is_array($coord) && !empty($coord)) {
181
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
182
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
183
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
184
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
185
		}
186
		$filter_query = $this->getFilter($filter,true,true);
187
188
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
189
		if (!isset($globalMap3DMarinesLimit) || $globalMap3DMarinesLimit == '') $globalMap3DMarinesLimit = '300';
190
		if ($globalDBdriver == 'mysql') {
191
			if (isset($globalArchive) && $globalArchive === TRUE) {
0 ignored issues
show
Bug introduced by
The variable $globalArchive seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
192
				$query  = 'SELECT * FROM (SELECT marine_archive.ident, marine_archive.fammarine_id,marine_archive.type, marine_archive.latitude, marine_archive.longitude, marine_archive.heading, marine_archive.ground_speed, marine_archive.date, marine_archive.format_source 
193
				    FROM marine_archive INNER JOIN (SELECT fammarine_id FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date) l ON l.flightaware_id = marine_archive.flightaware_id ";
194
				if (isset($maxlat)) $query .= "AND marine_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
0 ignored issues
show
Bug introduced by
The variable $minlat does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
195
				$query .= "UNION
196
				    SELECT marine_live.ident, marine_live.fammarine_id,marine_live.type, marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
197
				    FROM marine_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date";
198
				if (isset($maxlat)) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
199
				$query .= ") AS marine 
200
				    WHERE latitude <> '0' AND longitude <> '0' 
201
				    ORDER BY fammarine_id, date";
202
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
203
			} else {
204
				$query  = 'SELECT marine_live.ident, marine_live.fammarine_id,marine_live.type, marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
205
				    FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date ";
206
				if (isset($maxlat)) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
207
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
208
				ORDER BY marine_live.fammarine_id, marine_live.date";
209
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
210
			}
211
		} else {
212
			if (isset($globalArchive) && $globalArchive === TRUE) {
213
				$query  = "SELECT * FROM (SELECT marine_archive.ident, marine_archive.fammarine_id, marine_archive.type,marine_archive.latitude, marine_archive.longitude, marine_archive.heading, marine_archive.ground_speed, marine_archive.date, marine_archive.format_source 
214
				    FROM marine_archive INNER JOIN (SELECT flightaware_id FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date) l ON l.flightaware_id = marine_archive.flightaware_id ";
215
				if (isset($maxlat)) $query .= "AND marine_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
216
				$query .= "UNION
217
				    SELECT marine_live.ident, marine_live.fammarine_id, marine_live.type,marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
218
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date";
219
				if (isset($maxlat)) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
220
				$query .= ") AS marine WHERE latitude <> '0' AND longitude <> '0' ";
221
				$query .= "ORDER BY fammarine_id, date";
222
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
223
			} else {
224
				$query  = "SELECT marine_live.ident, marine_live.fammarine_id, marine_live.type,marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
225
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date ";
226
				if (isset($maxlat)) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
227
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
228
				ORDER BY marine_live.fammarine_id, marine_live.date";
229
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
230
			}
231
		}
232
		try {
233
			$sth = $this->db->prepare($query);
234
			$sth->execute();
235
		} catch(PDOException $e) {
236
			echo $e->getMessage();
237
			die;
238
		}
239
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
240
		return $spotter_array;
241
	}
242
243
	/**
244
	* Gets number of latest data entry
245
	*
246
	* @return String number of entry
247
	*
248
	*/
249
	public function getLiveMarineCount($filter = array())
250
	{
251
		global $globalDBdriver, $globalLiveInterval;
252
		$filter_query = $this->getFilter($filter,true,true);
253
254
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
255
		if ($globalDBdriver == 'mysql') {
256
			$query = 'SELECT COUNT(DISTINCT marine_live.fammarine_id) as nb FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
257
		} else {
258
			$query = "SELECT COUNT(DISTINCT marine_live.fammarine_id) as nb FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
259
		}
260
		try {
261
			$sth = $this->db->prepare($query);
262
			$sth->execute();
263
		} catch(PDOException $e) {
264
			echo $e->getMessage();
265
			die;
266
		}
267
		$result = $sth->fetch(PDO::FETCH_ASSOC);
268
		$sth->closeCursor();
269
		return $result['nb'];
270
	}
271
272
	/**
273
	* Gets all the spotter information based on the latest data entry and coord
274
	*
275
	* @return Array the spotter information
276
	*
277
	*/
278
	public function getLiveMarineDatabyCoord($coord, $filter = array())
279
	{
280
		global $globalDBdriver, $globalLiveInterval;
281
		$Spotter = new Spotter($this->db);
282
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
283
		$filter_query = $this->getFilter($filter);
284
285
		if (is_array($coord)) {
286
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
287
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
288
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
289
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
290
		} else return array();
291
		if ($globalDBdriver == 'mysql') {
292
			$query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate AND marine_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND marine_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.' GROUP BY marine_live.fammarine_id'.$filter_query;
293
		} else {
294
			$query  = "SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE NOW() at time zone 'UTC'  - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." GROUP BY marine_live.fammarine_id".$filter_query;
295
		}
296
		$spotter_array = $Spotter->getDataFromDB($query);
297
		return $spotter_array;
298
	}
299
300
	/**
301
	* Gets all the spotter information based on the latest data entry and coord
302
	*
303
	* @return Array the spotter information
304
	*
305
	*/
306
	public function getMinLiveMarineDatabyCoord($coord, $filter = array())
307
	{
308
		global $globalDBdriver, $globalLiveInterval;
309
		$Spotter = new Spotter($this->db);
310
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
311
		$filter_query = $this->getFilter($filter);
312
313
		if (is_array($coord)) {
314
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
315
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
316
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
317
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
318
		} else return array();
319
		if ($globalDBdriver == 'mysql') {
320
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id,marine_live.type, marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
321
			FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' AND marine_live.latitude BETWEEN ".$minlat.' AND '.$maxlat.' AND marine_live.longitude BETWEEN '.$minlong.' AND '.$maxlong."
322
			ORDER BY marine_live.fammarine_id, marine_live.date";
323
		} else {
324
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id, marine_live.type,marine_live.latitude, marine_live.longitude, marine_live.heading, marine_live.ground_speed, marine_live.date, marine_live.format_source 
325
			FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong."
326
			ORDER BY marine_live.fammarine_id, marine_live.date";
327
		}
328
		$spotter_array = $Spotter->getDataFromDB($query);
329
		return $spotter_array;
330
	}
331
332
	/**
333
	* Gets all the spotter information based on a user's latitude and longitude
334
	*
335
	* @return Array the spotter information
336
	*
337
	*/
338
	public function getLatestMarineForLayar($lat, $lng, $radius, $interval)
339
	{
340
		$Marine = new Marine($this->db);
341
		date_default_timezone_set('UTC');
342
		if ($lat != '') {
343
			if (!is_numeric($lat)) {
344
				return false;
345
			}
346
		}
347
		if ($lng != '')
348
		{
349
			if (!is_numeric($lng))
350
                        {
351
                                return false;
352
                        }
353
                }
354
355
                if ($radius != '')
356
                {
357
                        if (!is_numeric($radius))
358
                        {
359
                                return false;
360
                        }
361
                }
362
		$additional_query = '';
363
		if ($interval != '')
364
                {
365
                        if (!is_string($interval))
366
                        {
367
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
368
			        return false;
369
                        } else {
370
                if ($interval == '1m')
371
                {
372
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
373
                } else if ($interval == '15m'){
374
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= marine_live.date ';
375
                } 
376
            }
377
                } else {
378
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';   
379
        }
380
381
                $query  = "SELECT marine_live.*, ( 6371 * acos( cos( radians(:lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:lng) ) + sin( radians(:lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM marine_live 
382
                   WHERE marine_live.latitude <> '' 
383
                                   AND marine_live.longitude <> '' 
384
                   ".$additional_query."
385
                   HAVING distance < :radius  
386
                                   ORDER BY distance";
387
388
                $spotter_array = $Marine->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
389
390
                return $spotter_array;
391
        }
392
393
    
394
        /**
395
	* Gets all the spotter information based on a particular callsign
396
	*
397
	* @return Array the spotter information
398
	*
399
	*/
400
	public function getLastLiveMarineDataByIdent($ident)
401
	{
402
		$Marine = new Marine($this->db);
403
		date_default_timezone_set('UTC');
404
405
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
406
                $query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE l.ident = :ident GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate ORDER BY marine_live.date DESC';
407
408
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident),'',true);
409
410
		return $spotter_array;
411
	}
412
413
        /**
414
	* Gets all the spotter information based on a particular callsign
415
	*
416
	* @return Array the spotter information
417
	*
418
	*/
419
	public function getDateLiveMarineDataByIdent($ident,$date)
420
	{
421
		$Marine = new Marine($this->db);
422
		date_default_timezone_set('UTC');
423
424
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
425
                $query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE l.ident = :ident AND l.date <= :date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate ORDER BY marine_live.date DESC';
426
427
                $date = date('c',$date);
428
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
429
430
		return $spotter_array;
431
	}
432
433
        /**
434
	* Gets last spotter information based on a particular callsign
435
	*
436
	* @return Array the spotter information
437
	*
438
	*/
439
	public function getLastLiveMarineDataById($id)
440
	{
441
		$Marine = new Marine($this->db);
442
		date_default_timezone_set('UTC');
443
444
		$id = filter_var($id, FILTER_SANITIZE_STRING);
445
                $query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE l.fammarine_id = :id GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate ORDER BY marine_live.date DESC';
446
447
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id),'',true);
448
449
		return $spotter_array;
450
	}
451
452
        /**
453
	* Gets last spotter information based on a particular callsign
454
	*
455
	* @return Array the spotter information
456
	*
457
	*/
458
	public function getDateLiveMarineDataById($id,$date)
459
	{
460
		$Marine = new Marine($this->db);
461
		date_default_timezone_set('UTC');
462
463
		$id = filter_var($id, FILTER_SANITIZE_STRING);
464
                $query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE l.fammarine_id = :id AND l.date <= :date GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate ORDER BY marine_live.date DESC';
465
                $date = date('c',$date);
466
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
467
468
		return $spotter_array;
469
	}
470
471
472
        /**
473
	* Gets all the spotter information based on a particular id
474
	*
475
	* @return Array the spotter information
476
	*
477
	*/
478
	public function getAllLiveMarineDataById($id,$liveinterval = false)
479
	{
480
		global $globalDBdriver, $globalLiveInterval;
481
		date_default_timezone_set('UTC');
482
		$id = filter_var($id, FILTER_SANITIZE_STRING);
483
		//$query  = self::$global_query.' WHERE marine_live.fammarine_id = :id ORDER BY date';
484
		if ($globalDBdriver == 'mysql') {
485
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
486
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
487
			$query .= ' ORDER BY date';
488
		} else {
489
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
490
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
491
			$query .= ' ORDER BY date';
492
		}
493
494
		try {
495
			$sth = $this->db->prepare($query);
496
			$sth->execute(array(':id' => $id));
497
		} catch(PDOException $e) {
498
			echo $e->getMessage();
499
			die;
500
		}
501
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
502
		return $spotter_array;
503
	}
504
505
        /**
506
	* Gets all the spotter information based on a particular ident
507
	*
508
	* @return Array the spotter information
509
	*
510
	*/
511
	public function getAllLiveMarineDataByIdent($ident)
512
	{
513
		date_default_timezone_set('UTC');
514
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
515
		$query  = self::$global_query.' WHERE marine_live.ident = :ident';
516
    		try {
517
			
518
			$sth = $this->db->prepare($query);
519
			$sth->execute(array(':ident' => $ident));
520
		} catch(PDOException $e) {
521
			echo $e->getMessage();
522
			die;
523
		}
524
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
525
		return $spotter_array;
526
	}
527
528
529
	/**
530
	* Deletes all info in the table
531
	*
532
	* @return String success or false
533
	*
534
	*/
535
	public function deleteLiveMarineData()
536
	{
537
		global $globalDBdriver;
538
		if ($globalDBdriver == 'mysql') {
539
			//$query  = "DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= marine_live.date";
540
			$query  = 'DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= marine_live.date';
541
            		//$query  = "DELETE FROM marine_live WHERE marine_live.id IN (SELECT marine_live.id FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l GROUP BY l.fammarine_id) s on marine_live.fammarine_id = s.fammarine_id AND marine_live.date = s.maxdate AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) >= marine_live.date)";
542
		} else {
543
			$query  = "DELETE FROM marine_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= marine_live.date";
544
		}
545
        
546
    		try {
547
			
548
			$sth = $this->db->prepare($query);
549
			$sth->execute();
550
		} catch(PDOException $e) {
551
			return "error";
552
		}
553
554
		return "success";
555
	}
556
557
	/**
558
	* Deletes all info in the table for aircraft not seen since 2 HOUR
559
	*
560
	* @return String success or false
561
	*
562
	*/
563
	public function deleteLiveMarineDataNotUpdated()
564
	{
565
		global $globalDBdriver, $globalDebug;
566
		if ($globalDBdriver == 'mysql') {
567
			//$query = 'SELECT fammarine_id FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) >= marine_live.date AND marine_live.fammarine_id NOT IN (SELECT fammarine_id FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) < marine_live.date) LIMIT 800 OFFSET 0';
568
    			$query = "SELECT marine_live.fammarine_id FROM marine_live INNER JOIN (SELECT fammarine_id,MAX(date) as max_date FROM marine_live GROUP BY fammarine_id) s ON s.fammarine_id = marine_live.fammarine_id AND DATE_SUB(UTC_TIMESTAMP(), INTERVAL 2 HOUR) >= s.max_date LIMIT 1200 OFFSET 0";
569
    			try {
570
				
571
				$sth = $this->db->prepare($query);
572
				$sth->execute();
573
			} catch(PDOException $e) {
574
				return "error";
575
			}
576
			$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
577
                        $i = 0;
578
                        $j =0;
579
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
580
			foreach($all as $row)
581
			{
582
				$i++;
583
				$j++;
584
				if ($j == 30) {
585
					if ($globalDebug) echo ".";
586
				    	try {
587
						
588
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
589
						$sth->execute();
590
					} catch(PDOException $e) {
591
						return "error";
592
					}
593
                                	$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
594
                                	$j = 0;
595
				}
596
				$query_delete .= "'".$row['fammarine_id']."',";
597
			}
598
			if ($i > 0) {
599
    				try {
600
					
601
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
602
					$sth->execute();
603
				} catch(PDOException $e) {
604
					return "error";
605
				}
606
			}
607
			return "success";
608
		} elseif ($globalDBdriver == 'pgsql') {
609
			//$query = "SELECT fammarine_id FROM marine_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= marine_live.date AND marine_live.fammarine_id NOT IN (SELECT fammarine_id FROM marine_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' < marine_live.date) LIMIT 800 OFFSET 0";
610
    			//$query = "SELECT marine_live.fammarine_id FROM marine_live INNER JOIN (SELECT fammarine_id,MAX(date) as max_date FROM marine_live GROUP BY fammarine_id) s ON s.fammarine_id = marine_live.fammarine_id AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0";
611
    			$query = "DELETE FROM marine_live WHERE fammarine_id IN (SELECT marine_live.fammarine_id FROM marine_live INNER JOIN (SELECT fammarine_id,MAX(date) as max_date FROM marine_live GROUP BY fammarine_id) s ON s.fammarine_id = marine_live.fammarine_id AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0)";
612
    			try {
613
				
614
				$sth = $this->db->prepare($query);
615
				$sth->execute();
616
			} catch(PDOException $e) {
617
				return "error";
618
			}
619
/*			$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
620
                        $i = 0;
621
                        $j =0;
622
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
623
			foreach($all as $row)
624
			{
625
				$i++;
626
				$j++;
627
				if ($j == 100) {
628
					if ($globalDebug) echo ".";
629
				    	try {
630
						
631
						$sth = $this->db->query(substr($query_delete,0,-1).")");
632
						//$sth->execute();
633
					} catch(PDOException $e) {
634
						return "error";
635
					}
636
                                	$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
637
                                	$j = 0;
638
				}
639
				$query_delete .= "'".$row['fammarine_id']."',";
640
			}
641
			if ($i > 0) {
642
    				try {
643
					
644
					$sth = $this->db->query(substr($query_delete,0,-1).")");
645
					//$sth->execute();
646
				} catch(PDOException $e) {
647
					return "error";
648
				}
649
			}
650
*/
651
			return "success";
652
		}
653
	}
654
655
	/**
656
	* Deletes all info in the table for an ident
657
	*
658
	* @return String success or false
659
	*
660
	*/
661
	public function deleteLiveMarineDataByIdent($ident)
662
	{
663
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
664
		$query  = 'DELETE FROM marine_live WHERE ident = :ident';
665
        
666
    		try {
667
			
668
			$sth = $this->db->prepare($query);
669
			$sth->execute(array(':ident' => $ident));
670
		} catch(PDOException $e) {
671
			return "error";
672
		}
673
674
		return "success";
675
	}
676
677
	/**
678
	* Deletes all info in the table for an id
679
	*
680
	* @return String success or false
681
	*
682
	*/
683
	public function deleteLiveMarineDataById($id)
684
	{
685
		$id = filter_var($id, FILTER_SANITIZE_STRING);
686
		$query  = 'DELETE FROM marine_live WHERE fammarine_id = :id';
687
        
688
    		try {
689
			
690
			$sth = $this->db->prepare($query);
691
			$sth->execute(array(':id' => $id));
692
		} catch(PDOException $e) {
693
			return "error";
694
		}
695
696
		return "success";
697
	}
698
699
700
	/**
701
	* Gets the aircraft ident within the last hour
702
	*
703
	* @return String the ident
704
	*
705
	*/
706
	public function getIdentFromLastHour($ident)
707
	{
708
		global $globalDBdriver, $globalTimezone;
709
		if ($globalDBdriver == 'mysql') {
710
			$query  = 'SELECT marine_live.ident FROM marine_live 
711
				WHERE marine_live.ident = :ident 
712
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
713
				AND marine_live.date < UTC_TIMESTAMP()';
714
			$query_data = array(':ident' => $ident);
715
		} else {
716
			$query  = "SELECT marine_live.ident FROM marine_live 
717
				WHERE marine_live.ident = :ident 
718
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
719
				AND marine_live.date < now() AT TIME ZONE 'UTC'";
720
			$query_data = array(':ident' => $ident);
721
		}
722
		
723
		$sth = $this->db->prepare($query);
724
		$sth->execute($query_data);
725
		$ident_result='';
726
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
727
		{
728
			$ident_result = $row['ident'];
729
		}
730
		return $ident_result;
731
        }
732
733
	/**
734
	* Check recent aircraft
735
	*
736
	* @return String the ident
737
	*
738
	*/
739
	public function checkIdentRecent($ident)
740
	{
741
		global $globalDBdriver, $globalTimezone;
742
		if ($globalDBdriver == 'mysql') {
743
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
744
				WHERE marine_live.ident = :ident 
745
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
746
//				AND marine_live.date < UTC_TIMESTAMP()";
747
			$query_data = array(':ident' => $ident);
748
		} else {
749
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
750
				WHERE marine_live.ident = :ident 
751
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
752
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
753
			$query_data = array(':ident' => $ident);
754
		}
755
		
756
		$sth = $this->db->prepare($query);
757
		$sth->execute($query_data);
758
		$ident_result='';
759
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
760
		{
761
			$ident_result = $row['fammarine_id'];
762
		}
763
		return $ident_result;
764
        }
765
766
	/**
767
	* Check recent aircraft by id
768
	*
769
	* @return String the ident
770
	*
771
	*/
772
	public function checkIdRecent($id)
773
	{
774
		global $globalDBdriver, $globalTimezone;
775
		if ($globalDBdriver == 'mysql') {
776
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
777
				WHERE marine_live.fammarine_id = :id 
778
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
779
//				AND marine_live.date < UTC_TIMESTAMP()";
780
			$query_data = array(':id' => $id);
781
		} else {
782
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
783
				WHERE marine_live.fammarine_id = :id 
784
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
785
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
786
			$query_data = array(':id' => $id);
787
		}
788
		
789
		$sth = $this->db->prepare($query);
790
		$sth->execute($query_data);
791
		$ident_result='';
792
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
793
		{
794
			$ident_result = $row['fammarine_id'];
795
		}
796
		return $ident_result;
797
        }
798
799
	/**
800
	* Check recent aircraft by mmsi
801
	*
802
	* @return String the ident
803
	*
804
	*/
805
	public function checkMMSIRecent($mmsi)
806
	{
807
		global $globalDBdriver, $globalTimezone;
808
		if ($globalDBdriver == 'mysql') {
809
			$query  = 'SELECT marine_live.fammarine_id FROM marine_live 
810
				WHERE marine_live.mmsi = :mmsi 
811
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
812
//				AND marine_live.date < UTC_TIMESTAMP()";
813
			$query_data = array(':mmsi' => $mmsi);
814
		} else {
815
			$query  = "SELECT marine_live.fammarine_id FROM marine_live 
816
				WHERE marine_live.mmsi = :mmsi 
817
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
818
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
819
			$query_data = array(':mmsi' => $mmsi);
820
		}
821
		
822
		$sth = $this->db->prepare($query);
823
		$sth->execute($query_data);
824
		$ident_result='';
825
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
826
		{
827
			$ident_result = $row['fammarine_id'];
828
		}
829
		return $ident_result;
830
        }
831
832
	/**
833
	* Adds a new spotter data
834
	*
835
	* @param String $fammarine_id the ID from flightaware
836
	* @param String $ident the flight ident
837
	* @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...
838
	* @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...
839
	* @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...
840
	* @return String success or false
841
	*
842
	*/
843
	public function addLiveMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $heading = '', $groundspeed = '', $date = '', $putinarchive = false, $mmsi = '',$type = '',$typeid = '',$imo = '', $callsign = '',$arrival_code = '',$arrival_date = '',$status = '',$statusid = '',$noarchive = false,$format_source = '', $source_name = '', $over_country = '')
0 ignored issues
show
Unused Code introduced by
The parameter $statusid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
844
	{
845
		global $globalURL, $globalArchive, $globalDebug;
846
		$Common = new Common();
847
		date_default_timezone_set('UTC');
848
849
		//getting the airline information
850
		if ($ident != '')
851
		{
852
			if (!is_string($ident))
853
			{
854
				return false;
855
			} 
856
		}
857
858
859
		if ($latitude != '')
860
		{
861
			if (!is_numeric($latitude))
862
			{
863
				return false;
864
			}
865
		} else return '';
866
867
		if ($longitude != '')
868
		{
869
			if (!is_numeric($longitude))
870
			{
871
				return false;
872
			}
873
		} else return '';
874
875
876
		if ($heading != '')
877
		{
878
			if (!is_numeric($heading))
879
			{
880
				return false;
881
			}
882
		} else $heading = 0;
883
884
		if ($groundspeed != '')
885
		{
886
			if (!is_numeric($groundspeed))
887
			{
888
				return false;
889
			}
890
		} else $groundspeed = 0;
891
		date_default_timezone_set('UTC');
892
		if ($date == '') $date = date("Y-m-d H:i:s", time());
893
894
        
895
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
896
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
897
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
898
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
899
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
900
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
901
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
902
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
903
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
904
		$type = filter_var($type,FILTER_SANITIZE_STRING);
905
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
906
		$status = filter_var($status,FILTER_SANITIZE_STRING);
907
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
908
		$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
909
		$arrival_code = filter_var($arrival_code,FILTER_SANITIZE_STRING);
910
		$arrival_date = filter_var($arrival_date,FILTER_SANITIZE_STRING);
911
		
912
913
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
914
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
915
            	if ($arrival_date == '') $arrival_date = NULL;
916
            	$query = '';
917
		if ($globalArchive) {
918
			if ($globalDebug) echo '-- Delete previous data -- ';
919
			$query .= 'DELETE FROM marine_live WHERE fammarine_id = :fammarine_id;';
920
		}
921
		$query .= 'INSERT INTO marine_live (fammarine_id, ident, latitude, longitude, heading, ground_speed, date, format_source, source_name, over_country, mmsi, type,status,imo,arrival_port_name,arrival_port_date) 
922
		    VALUES (:fammarine_id,:ident,:latitude,:longitude,:heading,:groundspeed,:date,:format_source, :source_name, :over_country,:mmsi,:type,:status,:imo,:arrival_port_name,:arrival_port_date)';
923
924
		$query_values = array(':fammarine_id' => $fammarine_id,':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':heading' => $heading,':groundspeed' => $groundspeed,':date' => $date, ':format_source' => $format_source, ':source_name' => $source_name, ':over_country' => $over_country,':mmsi' => $mmsi,':type' => $type,':status' => $status,':imo' => $imo,':arrival_port_name' => $arrival_code,':arrival_port_date' => $arrival_date);
925
		try {
926
			$sth = $this->db->prepare($query);
927
			$sth->execute($query_values);
928
		} catch(PDOException $e) {
929
			return "error : ".$e->getMessage();
930
		}
931
		
932
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
933
			if ($globalDebug) echo '(Add to Marine archive : ';
934
			$MarineArchive = new MarineArchive($this->db);
935
			$result =  $MarineArchive->addMarineArchiveData($fammarine_id, $ident, $latitude, $longitude, $heading, $groundspeed, $date, $putinarchive, $mmsi,$type,$typeid,$imo, $callsign,$arrival_code,$arrival_date,$status,$noarchive,$format_source, $source_name, $over_country);
0 ignored issues
show
Documentation introduced by
$noarchive is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
936
			if ($globalDebug) echo $result.')';
937
		}
938
		return "success";
939
	}
940
941
	public function getOrderBy()
942
	{
943
		$orderby = array("aircraft_asc" => array("key" => "aircraft_asc", "value" => "Aircraft Type - ASC", "sql" => "ORDER BY marine_live.aircraft_icao ASC"), "aircraft_desc" => array("key" => "aircraft_desc", "value" => "Aircraft Type - DESC", "sql" => "ORDER BY marine_live.aircraft_icao DESC"),"manufacturer_asc" => array("key" => "manufacturer_asc", "value" => "Aircraft Manufacturer - ASC", "sql" => "ORDER BY marine_live.aircraft_manufacturer ASC"), "manufacturer_desc" => array("key" => "manufacturer_desc", "value" => "Aircraft Manufacturer - DESC", "sql" => "ORDER BY marine_live.aircraft_manufacturer DESC"),"airline_name_asc" => array("key" => "airline_name_asc", "value" => "Airline Name - ASC", "sql" => "ORDER BY marine_live.airline_name ASC"), "airline_name_desc" => array("key" => "airline_name_desc", "value" => "Airline Name - DESC", "sql" => "ORDER BY marine_live.airline_name DESC"), "ident_asc" => array("key" => "ident_asc", "value" => "Ident - ASC", "sql" => "ORDER BY marine_live.ident ASC"), "ident_desc" => array("key" => "ident_desc", "value" => "Ident - DESC", "sql" => "ORDER BY marine_live.ident DESC"), "airport_departure_asc" => array("key" => "airport_departure_asc", "value" => "Departure Airport - ASC", "sql" => "ORDER BY marine_live.departure_airport_city ASC"), "airport_departure_desc" => array("key" => "airport_departure_desc", "value" => "Departure Airport - DESC", "sql" => "ORDER BY marine_live.departure_airport_city DESC"), "airport_arrival_asc" => array("key" => "airport_arrival_asc", "value" => "Arrival Airport - ASC", "sql" => "ORDER BY marine_live.arrival_airport_city ASC"), "airport_arrival_desc" => array("key" => "airport_arrival_desc", "value" => "Arrival Airport - DESC", "sql" => "ORDER BY marine_live.arrival_airport_city DESC"), "date_asc" => array("key" => "date_asc", "value" => "Date - ASC", "sql" => "ORDER BY marine_live.date ASC"), "date_desc" => array("key" => "date_desc", "value" => "Date - DESC", "sql" => "ORDER BY marine_live.date DESC"));
944
		return $orderby;
945
	}
946
947
}
948
949
950
?>
951