Completed
Push — master ( 994417...89e41e )
by Yannick
34:04 queued 01:34
created

MarineLive::getDateLiveMarineDataByMMSI()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 2
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
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. (MarineLive)');
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['mmsi']) && !empty($filter['mmsi'])) {
52
			$filter_query_where .= " AND mmsi = '".$filter['mmsi']."'";
53
		}
54
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
55
			$filter_query_date = '';
56
			
57
			if (isset($filter['year']) && $filter['year'] != '') {
58
				if ($globalDBdriver == 'mysql') {
59
					$filter_query_date .= " AND YEAR(marine_output.date) = '".$filter['year']."'";
60
				} else {
61
					$filter_query_date .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
62
				}
63
			}
64
			if (isset($filter['month']) && $filter['month'] != '') {
65
				if ($globalDBdriver == 'mysql') {
66
					$filter_query_date .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
67
				} else {
68
					$filter_query_date .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
69
				}
70
			}
71
			if (isset($filter['day']) && $filter['day'] != '') {
72
				if ($globalDBdriver == 'mysql') {
73
					$filter_query_date .= " AND DAY(marine_output.date) = '".$filter['day']."'";
74
				} else {
75
					$filter_query_date .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
76
				}
77
			}
78
			$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";
79
		}
80
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
81
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
82
		}
83
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
84
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
85
		if ($filter_query_where != '') {
86
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
87
		}
88
		$filter_query = $filter_query_join.$filter_query_where;
89
		return $filter_query;
90
	}
91
92
	/**
93
	* Gets all the spotter information based on the latest data entry
94
	*
95
	* @return Array the spotter information
96
	*
97
	*/
98
	public function getLiveMarineData($limit = '', $sort = '', $filter = array())
99
	{
100
		global $globalDBdriver, $globalLiveInterval;
101
		$Marine = new Marine($this->db);
102
		date_default_timezone_set('UTC');
103
104
		$filter_query = $this->getFilter($filter);
105
		$limit_query = '';
106
		if ($limit != '')
107
		{
108
			$limit_array = explode(',', $limit);
109
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
110
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
111
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
112
			{
113
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
114
			}
115
		}
116
		$orderby_query = '';
117
		if ($sort != '')
118
		{
119
			$search_orderby_array = $this->getOrderBy();
120
			if (isset($search_orderby_array[$sort]['sql'])) 
121
			{
122
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
123
			}
124
		}
125
		if ($orderby_query == '') $orderby_query= ' ORDER BY date DESC';
126
127
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
128
		if ($globalDBdriver == 'mysql') {
129
			//$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";
130
			$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;
131
		} else {
132
			$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;
133
		}
134
		$spotter_array = $Marine->getDataFromDB($query.$limit_query,array(),'',true);
135
136
		return $spotter_array;
137
	}
138
139
	/**
140
	* Gets Minimal Live Spotter data
141
	*
142
	* @return Array the spotter information
143
	*
144
	*/
145
	public function getMinLiveMarineData($filter = array())
146
	{
147
		global $globalDBdriver, $globalLiveInterval;
148
		date_default_timezone_set('UTC');
149
150
		$filter_query = $this->getFilter($filter,true,true);
151
152
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
153
		if ($globalDBdriver == 'mysql') {
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 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";
156
		} else {
157
			$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 
158
			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'";
159
		}
160
161
		try {
162
			$sth = $this->db->prepare($query);
163
			$sth->execute();
164
		} catch(PDOException $e) {
165
			echo $e->getMessage();
166
			die;
167
		}
168
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
169
170
		return $spotter_array;
171
	}
172
173
	/**
174
	* Gets Minimal Live Spotter data since xx seconds
175
	*
176
	* @return Array the spotter information
177
	*
178
	*/
179
	public function getMinLastLiveMarineData($coord = array(),$filter = array(), $limit = false)
180
	{
181
		global $globalDBdriver, $globalLiveInterval, $globalMap3DMarinesLimit, $globalArchive;
182
		date_default_timezone_set('UTC');
183
		$usecoord = false;
184
		if (is_array($coord) && !empty($coord)) {
185
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
186
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
187
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
188
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
189
			$usecoord = true;
190
		}
191
		$filter_query = $this->getFilter($filter,true,true);
192
193
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
194
		if (!isset($globalMap3DMarinesLimit) || $globalMap3DMarinesLimit == '') $globalMap3DMarinesLimit = '300';
195
		if ($globalDBdriver == 'mysql') {
196
			if (isset($globalArchive) && $globalArchive === TRUE) {
197
				$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 
198
				    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.fammarine_id = marine_archive.fammarine_id ";
199
				if ($usecoord) $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 $maxlat does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
200
				$query .= "UNION
201
				    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 
202
				    FROM marine_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date";
203
				if ($usecoord) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
204
				$query .= ") AS marine 
205
				    WHERE latitude <> '0' AND longitude <> '0' 
206
				    ORDER BY fammarine_id, date";
207
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
208
			} else {
209
				$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 
210
				    FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date ";
211
				if ($usecoord) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
212
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
213
				ORDER BY marine_live.fammarine_id, marine_live.date";
214
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
215
			}
216
		} else {
217
			if (isset($globalArchive) && $globalArchive === TRUE) {
218
				$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 
219
				    FROM marine_archive INNER JOIN (SELECT fammarine_id FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date) l ON l.fammarine_id = marine_archive.fammarine_id ";
220
				if ($usecoord) $query .= "AND marine_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
221
				$query .= "UNION
222
				    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 
223
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date";
224
				if ($usecoord) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
225
				$query .= ") AS marine WHERE latitude <> '0' AND longitude <> '0' ";
226
				$query .= "ORDER BY fammarine_id, date";
227
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
228
			} else {
229
				$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 
230
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date ";
231
				if ($usecoord) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
232
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
233
				ORDER BY marine_live.fammarine_id, marine_live.date";
234
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
235
			}
236
		}
237
		try {
238
			$sth = $this->db->prepare($query);
239
			$sth->execute();
240
		} catch(PDOException $e) {
241
			echo $e->getMessage();
242
			die;
243
		}
244
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
245
		return $spotter_array;
246
	}
247
248
	/**
249
	* Gets number of latest data entry
250
	*
251
	* @return String number of entry
252
	*
253
	*/
254
	public function getLiveMarineCount($filter = array())
255
	{
256
		global $globalDBdriver, $globalLiveInterval;
257
		$filter_query = $this->getFilter($filter,true,true);
258
259
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
260
		if ($globalDBdriver == 'mysql') {
261
			$query = 'SELECT COUNT(DISTINCT marine_live.fammarine_id) as nb FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
262
		} else {
263
			$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";
264
		}
265
		try {
266
			$sth = $this->db->prepare($query);
267
			$sth->execute();
268
		} catch(PDOException $e) {
269
			echo $e->getMessage();
270
			die;
271
		}
272
		$result = $sth->fetch(PDO::FETCH_ASSOC);
273
		$sth->closeCursor();
274
		return $result['nb'];
275
	}
276
277
	/**
278
	* Gets all the spotter information based on the latest data entry and coord
279
	*
280
	* @return Array the spotter information
281
	*
282
	*/
283
	public function getLiveMarineDatabyCoord($coord, $filter = array())
284
	{
285
		global $globalDBdriver, $globalLiveInterval;
286
		$Marine = new Marine($this->db);
287
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
288
		$filter_query = $this->getFilter($filter);
289
290
		if (is_array($coord)) {
291
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
292
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
293
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
294
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
295
		} else return array();
296
		if ($globalDBdriver == 'mysql') {
297
			$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;
298
		} else {
299
			$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;
300
		}
301
		$spotter_array = $Marine->getDataFromDB($query);
302
		return $spotter_array;
303
	}
304
305
	/**
306
	* Gets all the spotter information based on the latest data entry and coord
307
	*
308
	* @return Array the spotter information
309
	*
310
	*/
311
	public function getMinLiveMarineDatabyCoord($coord, $filter = array())
312
	{
313
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
314
		$Marine = new Marine($this->db);
315
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
316
		$filter_query = $this->getFilter($filter,true,true);
317
318
		if (is_array($coord)) {
319
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
320
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
321
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
322
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
323
		} else return array();
324
		/*
325
		if ($globalDBdriver == 'mysql') {
326
			$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 
327
			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."
328
			ORDER BY marine_live.fammarine_id, marine_live.date";
329
		} else {
330
			$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 
331
			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."
332
			ORDER BY marine_live.fammarine_id, marine_live.date";
333
		}
334
		*/
335
		if ($globalDBdriver == 'mysql') {
336
			if (isset($globalArchive) && $globalArchive === TRUE) {
337
				$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 
338
				    FROM marine_live 
339
				    '.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= marine_live.date 
340
				    AND marine_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND marine_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
341
				    AND marine_live.latitude <> 0 AND marine_live.longitude <> 0';
342
			} else {
343
				$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 
344
				    FROM marine_live 
345
				    INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate 
346
				    FROM marine_live l 
347
				    WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
348
				    AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
349
				    GROUP BY l.fammarine_id
350
				    ) s on marine_live.fammarine_id = s.fammarine_id 
351
				    AND marine_live.date = s.maxdate'.$filter_query.' marine_live.latitude <> 0 AND marine_live.longitude <> 0';
352
			}
353
		} else {
354
			if (isset($globalArchive) && $globalArchive === TRUE) {
355
				$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 
356
				    FROM marine_live 
357
				    ".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date 
358
				    AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
359
				    AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
360
				    AND marine_live.latitude <> '0' AND marine_live.longitude <> '0'";
361
			} else {
362
				$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 
363
				    FROM marine_live 
364
				    INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate 
365
				    FROM marine_live l 
366
				    WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
367
				    AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
368
				    AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
369
				    GROUP BY l.fammarine_id
370
				    ) s on marine_live.fammarine_id = s.fammarine_id 
371
				    AND marine_live.date = s.maxdate".$filter_query." marine_live.latitude <> '0' AND marine_live.longitude <> '0'";
372
			}
373
		}
374
		$spotter_array = $Marine->getDataFromDB($query);
375
		return $spotter_array;
376
	}
377
378
	/**
379
	* Gets all the spotter information based on a user's latitude and longitude
380
	*
381
	* @return Array the spotter information
382
	*
383
	*/
384
	public function getLatestMarineForLayar($lat, $lng, $radius, $interval)
385
	{
386
		$Marine = new Marine($this->db);
387
		date_default_timezone_set('UTC');
388
		if ($lat != '') {
389
			if (!is_numeric($lat)) {
390
				return false;
391
			}
392
		}
393
		if ($lng != '')
394
		{
395
			if (!is_numeric($lng))
396
                        {
397
                                return false;
398
                        }
399
                }
400
401
                if ($radius != '')
402
                {
403
                        if (!is_numeric($radius))
404
                        {
405
                                return false;
406
                        }
407
                }
408
		$additional_query = '';
409
		if ($interval != '')
410
                {
411
                        if (!is_string($interval))
412
                        {
413
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
414
			        return false;
415
                        } else {
416
                if ($interval == '1m')
417
                {
418
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
419
                } else if ($interval == '15m'){
420
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= marine_live.date ';
421
                } 
422
            }
423
                } else {
424
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';   
425
        }
426
427
                $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 
428
                   WHERE marine_live.latitude <> '' 
429
                                   AND marine_live.longitude <> '' 
430
                   ".$additional_query."
431
                   HAVING distance < :radius  
432
                                   ORDER BY distance";
433
434
                $spotter_array = $Marine->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
435
436
                return $spotter_array;
437
        }
438
439
    
440
        /**
441
	* Gets all the spotter information based on a particular callsign
442
	*
443
	* @return Array the spotter information
444
	*
445
	*/
446
	public function getLastLiveMarineDataByIdent($ident)
447
	{
448
		$Marine = new Marine($this->db);
449
		date_default_timezone_set('UTC');
450
451
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
452
                $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';
453
454
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident),'',true);
455
456
		return $spotter_array;
457
	}
458
459
        /**
460
	* Gets all the spotter information based on a particular callsign
461
	*
462
	* @return Array the spotter information
463
	*
464
	*/
465
	public function getDateLiveMarineDataByIdent($ident,$date)
466
	{
467
		$Marine = new Marine($this->db);
468
		date_default_timezone_set('UTC');
469
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
470
		$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';
471
		$date = date('c',$date);
472
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
473
		return $spotter_array;
474
	}
475
476
	/**
477
	* Gets all the spotter information based on a particular MMSI
478
	*
479
	* @return Array the spotter information
480
	*
481
	*/
482
	public function getDateLiveMarineDataByMMSI($mmsi,$date)
483
	{
484
		$Marine = new Marine($this->db);
485
		date_default_timezone_set('UTC');
486
		$mmsi = filter_var($mmsi, FILTER_SANITIZE_NUMBER_INT);
487
		$query  = 'SELECT marine_live.* FROM marine_live INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate FROM marine_live l WHERE l.mmsi = :mmsi 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';
488
		$date = date('c',$date);
489
		$spotter_array = $Marine->getDataFromDB($query,array(':mmsi' => $mmsi,':date' => $date));
490
		return $spotter_array;
491
	}
492
493
        /**
494
	* Gets last spotter information based on a particular callsign
495
	*
496
	* @return Array the spotter information
497
	*
498
	*/
499
	public function getLastLiveMarineDataById($id)
500
	{
501
		$Marine = new Marine($this->db);
502
		date_default_timezone_set('UTC');
503
504
		$id = filter_var($id, FILTER_SANITIZE_STRING);
505
                $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';
506
507
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id),'',true);
508
509
		return $spotter_array;
510
	}
511
512
        /**
513
	* Gets last spotter information based on a particular callsign
514
	*
515
	* @return Array the spotter information
516
	*
517
	*/
518
	public function getDateLiveMarineDataById($id,$date)
519
	{
520
		$Marine = new Marine($this->db);
521
		date_default_timezone_set('UTC');
522
523
		$id = filter_var($id, FILTER_SANITIZE_STRING);
524
                $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';
525
                $date = date('c',$date);
526
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
527
528
		return $spotter_array;
529
	}
530
531
532
        /**
533
	* Gets all the spotter information based on a particular id
534
	*
535
	* @return Array the spotter information
536
	*
537
	*/
538
	public function getAllLiveMarineDataById($id,$liveinterval = false)
539
	{
540
		global $globalDBdriver, $globalLiveInterval;
541
		date_default_timezone_set('UTC');
542
		$id = filter_var($id, FILTER_SANITIZE_STRING);
543
		//$query  = self::$global_query.' WHERE marine_live.fammarine_id = :id ORDER BY date';
544
		if ($globalDBdriver == 'mysql') {
545
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
546
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
547
			$query .= ' ORDER BY date';
548
		} else {
549
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
550
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
551
			$query .= ' ORDER BY date';
552
		}
553
554
		try {
555
			$sth = $this->db->prepare($query);
556
			$sth->execute(array(':id' => $id));
557
		} catch(PDOException $e) {
558
			echo $e->getMessage();
559
			die;
560
		}
561
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
562
		return $spotter_array;
563
	}
564
565
        /**
566
	* Gets all the spotter information based on a particular ident
567
	*
568
	* @return Array the spotter information
569
	*
570
	*/
571
	public function getAllLiveMarineDataByIdent($ident)
572
	{
573
		date_default_timezone_set('UTC');
574
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
575
		$query  = self::$global_query.' WHERE marine_live.ident = :ident';
576
    		try {
577
			
578
			$sth = $this->db->prepare($query);
579
			$sth->execute(array(':ident' => $ident));
580
		} catch(PDOException $e) {
581
			echo $e->getMessage();
582
			die;
583
		}
584
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
585
		return $spotter_array;
586
	}
587
588
589
	/**
590
	* Deletes all info in the table
591
	*
592
	* @return String success or false
593
	*
594
	*/
595
	public function deleteLiveMarineData()
596
	{
597
		global $globalDBdriver;
598
		if ($globalDBdriver == 'mysql') {
599
			//$query  = "DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= marine_live.date";
600
			$query  = 'DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= marine_live.date';
601
            		//$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)";
602
		} else {
603
			$query  = "DELETE FROM marine_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= marine_live.date";
604
		}
605
        
606
    		try {
607
			
608
			$sth = $this->db->prepare($query);
609
			$sth->execute();
610
		} catch(PDOException $e) {
611
			return "error";
612
		}
613
614
		return "success";
615
	}
616
617
	/**
618
	* Deletes all info in the table for aircraft not seen since 2 HOUR
619
	*
620
	* @return String success or false
621
	*
622
	*/
623
	public function deleteLiveMarineDataNotUpdated()
624
	{
625
		global $globalDBdriver, $globalDebug;
626
		if ($globalDBdriver == 'mysql') {
627
			//$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';
628
    			$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";
629
    			try {
630
				
631
				$sth = $this->db->prepare($query);
632
				$sth->execute();
633
			} catch(PDOException $e) {
634
				return "error";
635
			}
636
			$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
637
                        $i = 0;
638
                        $j =0;
639
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
640
			foreach($all as $row)
641
			{
642
				$i++;
643
				$j++;
644
				if ($j == 30) {
645
					if ($globalDebug) echo ".";
646
				    	try {
647
						
648
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
649
						$sth->execute();
650
					} catch(PDOException $e) {
651
						return "error";
652
					}
653
                                	$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
654
                                	$j = 0;
655
				}
656
				$query_delete .= "'".$row['fammarine_id']."',";
657
			}
658
			if ($i > 0) {
659
    				try {
660
					
661
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
662
					$sth->execute();
663
				} catch(PDOException $e) {
664
					return "error";
665
				}
666
			}
667
			return "success";
668
		} elseif ($globalDBdriver == 'pgsql') {
669
			//$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";
670
    			//$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";
671
    			$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)";
672
    			try {
673
				
674
				$sth = $this->db->prepare($query);
675
				$sth->execute();
676
			} catch(PDOException $e) {
677
				return "error";
678
			}
679
/*			$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
680
                        $i = 0;
681
                        $j =0;
682
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
683
			foreach($all as $row)
684
			{
685
				$i++;
686
				$j++;
687
				if ($j == 100) {
688
					if ($globalDebug) echo ".";
689
				    	try {
690
						
691
						$sth = $this->db->query(substr($query_delete,0,-1).")");
692
						//$sth->execute();
693
					} catch(PDOException $e) {
694
						return "error";
695
					}
696
                                	$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
697
                                	$j = 0;
698
				}
699
				$query_delete .= "'".$row['fammarine_id']."',";
700
			}
701
			if ($i > 0) {
702
    				try {
703
					
704
					$sth = $this->db->query(substr($query_delete,0,-1).")");
705
					//$sth->execute();
706
				} catch(PDOException $e) {
707
					return "error";
708
				}
709
			}
710
*/
711
			return "success";
712
		}
713
	}
714
715
	/**
716
	* Deletes all info in the table for an ident
717
	*
718
	* @return String success or false
719
	*
720
	*/
721
	public function deleteLiveMarineDataByIdent($ident)
722
	{
723
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
724
		$query  = 'DELETE FROM marine_live WHERE ident = :ident';
725
        
726
    		try {
727
			
728
			$sth = $this->db->prepare($query);
729
			$sth->execute(array(':ident' => $ident));
730
		} catch(PDOException $e) {
731
			return "error";
732
		}
733
734
		return "success";
735
	}
736
737
	/**
738
	* Deletes all info in the table for an id
739
	*
740
	* @return String success or false
741
	*
742
	*/
743
	public function deleteLiveMarineDataById($id)
744
	{
745
		$id = filter_var($id, FILTER_SANITIZE_STRING);
746
		$query  = 'DELETE FROM marine_live WHERE fammarine_id = :id';
747
        
748
    		try {
749
			
750
			$sth = $this->db->prepare($query);
751
			$sth->execute(array(':id' => $id));
752
		} catch(PDOException $e) {
753
			return "error";
754
		}
755
756
		return "success";
757
	}
758
759
760
	/**
761
	* Gets the aircraft ident within the last hour
762
	*
763
	* @return String the ident
764
	*
765
	*/
766
	public function getIdentFromLastHour($ident)
767
	{
768
		global $globalDBdriver, $globalTimezone;
769
		if ($globalDBdriver == 'mysql') {
770
			$query  = 'SELECT marine_live.ident FROM marine_live 
771
				WHERE marine_live.ident = :ident 
772
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
773
				AND marine_live.date < UTC_TIMESTAMP()';
774
			$query_data = array(':ident' => $ident);
775
		} else {
776
			$query  = "SELECT marine_live.ident FROM marine_live 
777
				WHERE marine_live.ident = :ident 
778
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
779
				AND marine_live.date < now() AT TIME ZONE 'UTC'";
780
			$query_data = array(':ident' => $ident);
781
		}
782
		
783
		$sth = $this->db->prepare($query);
784
		$sth->execute($query_data);
785
		$ident_result='';
786
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
787
		{
788
			$ident_result = $row['ident'];
789
		}
790
		return $ident_result;
791
        }
792
793
	/**
794
	* Check recent aircraft
795
	*
796
	* @return String the ident
797
	*
798
	*/
799
	public function checkIdentRecent($ident)
800
	{
801
		global $globalDBdriver, $globalTimezone;
802
		if ($globalDBdriver == 'mysql') {
803
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
804
				WHERE marine_live.ident = :ident 
805
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
806
//				AND marine_live.date < UTC_TIMESTAMP()";
807
			$query_data = array(':ident' => $ident);
808
		} else {
809
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
810
				WHERE marine_live.ident = :ident 
811
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
812
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
813
			$query_data = array(':ident' => $ident);
814
		}
815
		
816
		$sth = $this->db->prepare($query);
817
		$sth->execute($query_data);
818
		$ident_result='';
819
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
820
		{
821
			$ident_result = $row['fammarine_id'];
822
		}
823
		return $ident_result;
824
        }
825
826
	/**
827
	* Check recent aircraft by id
828
	*
829
	* @return String the ident
830
	*
831
	*/
832
	public function checkIdRecent($id)
833
	{
834
		global $globalDBdriver, $globalTimezone;
835
		if ($globalDBdriver == 'mysql') {
836
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
837
				WHERE marine_live.fammarine_id = :id 
838
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
839
//				AND marine_live.date < UTC_TIMESTAMP()";
840
			$query_data = array(':id' => $id);
841
		} else {
842
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
843
				WHERE marine_live.fammarine_id = :id 
844
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
845
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
846
			$query_data = array(':id' => $id);
847
		}
848
		
849
		$sth = $this->db->prepare($query);
850
		$sth->execute($query_data);
851
		$ident_result='';
852
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
853
		{
854
			$ident_result = $row['fammarine_id'];
855
		}
856
		return $ident_result;
857
        }
858
859
	/**
860
	* Check recent aircraft by mmsi
861
	*
862
	* @return String the ident
863
	*
864
	*/
865
	public function checkMMSIRecent($mmsi)
866
	{
867
		global $globalDBdriver, $globalTimezone;
868
		if ($globalDBdriver == 'mysql') {
869
			$query  = 'SELECT marine_live.fammarine_id FROM marine_live 
870
				WHERE marine_live.mmsi = :mmsi 
871
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
872
//				AND marine_live.date < UTC_TIMESTAMP()";
873
			$query_data = array(':mmsi' => $mmsi);
874
		} else {
875
			$query  = "SELECT marine_live.fammarine_id FROM marine_live 
876
				WHERE marine_live.mmsi = :mmsi 
877
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
878
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
879
			$query_data = array(':mmsi' => $mmsi);
880
		}
881
		
882
		$sth = $this->db->prepare($query);
883
		$sth->execute($query_data);
884
		$ident_result='';
885
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
886
		{
887
			$ident_result = $row['fammarine_id'];
888
		}
889
		return $ident_result;
890
        }
891
892
	/**
893
	* Adds a new spotter data
894
	*
895
	* @param String $fammarine_id the ID from flightaware
896
	* @param String $ident the flight ident
897
	* @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...
898
	* @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...
899
	* @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...
900
	* @return String success or false
901
	*
902
	*/
903
	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...
904
	{
905
		global $globalURL, $globalArchive, $globalDebug;
906
		$Common = new Common();
907
		date_default_timezone_set('UTC');
908
909
		//getting the airline information
910
		if ($ident != '')
911
		{
912
			if (!is_string($ident))
913
			{
914
				return false;
915
			} 
916
		}
917
918
919
		if ($latitude != '')
920
		{
921
			if (!is_numeric($latitude))
922
			{
923
				return false;
924
			}
925
		} else return '';
926
927
		if ($longitude != '')
928
		{
929
			if (!is_numeric($longitude))
930
			{
931
				return false;
932
			}
933
		} else return '';
934
935
936
		if ($heading != '')
937
		{
938
			if (!is_numeric($heading))
939
			{
940
				return false;
941
			}
942
		} else $heading = 0;
943
944
		if ($groundspeed != '')
945
		{
946
			if (!is_numeric($groundspeed))
947
			{
948
				return false;
949
			}
950
		} else $groundspeed = 0;
951
		date_default_timezone_set('UTC');
952
		if ($date == '') $date = date("Y-m-d H:i:s", time());
953
954
        
955
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
956
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
957
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
958
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
959
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
960
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
961
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
962
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
963
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
964
		$type = filter_var($type,FILTER_SANITIZE_STRING);
965
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
966
		$status = filter_var($status,FILTER_SANITIZE_STRING);
967
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
968
		$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
969
		$arrival_code = filter_var($arrival_code,FILTER_SANITIZE_STRING);
970
		$arrival_date = filter_var($arrival_date,FILTER_SANITIZE_STRING);
971
		
972
973
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
974
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
975
            	if ($arrival_date == '') $arrival_date = NULL;
976
            	$query = '';
977
		if ($globalArchive) {
978
			if ($globalDebug) echo '-- Delete previous data -- ';
979
			$query .= 'DELETE FROM marine_live WHERE fammarine_id = :fammarine_id;';
980
		}
981
		$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) 
982
		    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)';
983
984
		$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);
985
		try {
986
			$sth = $this->db->prepare($query);
987
			$sth->execute($query_values);
988
			$sth->closeCursor();
989
		} catch(PDOException $e) {
990
			return "error : ".$e->getMessage();
991
		}
992
		
993
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
994
			if ($globalDebug) echo '(Add to Marine archive : ';
995
			$MarineArchive = new MarineArchive($this->db);
996
			$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...
997
			if ($globalDebug) echo $result.')';
998
		}
999
		return "success";
1000
	}
1001
1002
	public function getOrderBy()
1003
	{
1004
		$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"));
1005
		return $orderby;
1006
	}
1007
1008
}
1009
1010
1011
?>
1012