Completed
Push — master ( f32ba6...d43b85 )
by Yannick
30:30
created

MarineLive::getAllRaces()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 8
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['id']) && !empty($filter['id'])) {
52
			$filter_query_where .= " AND fammarine_id = '".$filter['id']."'";
53
		}
54
		if (isset($filter['mmsi']) && !empty($filter['mmsi'])) {
55
			$filter_query_where .= " AND mmsi = '".$filter['mmsi']."'";
56
		}
57
		if (isset($filter['race']) && !empty($filter['race'])) {
58
			$filter_query_where .= " AND race_id = '".$filter['race']."'";
59
		}
60
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
61
			$filter_query_date = '';
62
			
63
			if (isset($filter['year']) && $filter['year'] != '') {
64
				if ($globalDBdriver == 'mysql') {
65
					$filter_query_date .= " AND YEAR(marine_output.date) = '".$filter['year']."'";
66
				} else {
67
					$filter_query_date .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
68
				}
69
			}
70
			if (isset($filter['month']) && $filter['month'] != '') {
71
				if ($globalDBdriver == 'mysql') {
72
					$filter_query_date .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
73
				} else {
74
					$filter_query_date .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
75
				}
76
			}
77
			if (isset($filter['day']) && $filter['day'] != '') {
78
				if ($globalDBdriver == 'mysql') {
79
					$filter_query_date .= " AND DAY(marine_output.date) = '".$filter['day']."'";
80
				} else {
81
					$filter_query_date .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
82
				}
83
			}
84
			$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";
85
		}
86
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
87
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
88
		}
89
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
90
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
91
		if ($filter_query_where != '') {
92
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
93
		}
94
		$filter_query = $filter_query_join.$filter_query_where;
95
		return $filter_query;
96
	}
97
98
	/**
99
	* Gets all the spotter information based on the latest data entry
100
	*
101
	* @return Array the spotter information
102
	*
103
	*/
104
	public function getLiveMarineData($limit = '', $sort = '', $filter = array())
105
	{
106
		global $globalDBdriver, $globalLiveInterval;
107
		$Marine = new Marine($this->db);
108
		date_default_timezone_set('UTC');
109
110
		$filter_query = $this->getFilter($filter);
111
		$limit_query = '';
112
		if ($limit != '')
113
		{
114
			$limit_array = explode(',', $limit);
115
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
116
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
117
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
118
			{
119
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
120
			}
121
		}
122
		$orderby_query = '';
123
		if ($sort != '')
124
		{
125
			$search_orderby_array = $this->getOrderBy();
126
			if (isset($search_orderby_array[$sort]['sql'])) 
127
			{
128
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
129
			}
130
		}
131
		if ($orderby_query == '') $orderby_query= ' ORDER BY date DESC';
132
133
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
134
		if ($globalDBdriver == 'mysql') {
135
			//$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";
136
			$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;
137
		} else {
138
			$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;
139
		}
140
		$spotter_array = $Marine->getDataFromDB($query.$limit_query,array(),'',true);
141
142
		return $spotter_array;
143
	}
144
145
	/**
146
	* Gets Minimal Live Spotter data
147
	*
148
	* @return Array the spotter information
149
	*
150
	*/
151
	public function getMinLiveMarineData($filter = array())
152
	{
153
		global $globalDBdriver, $globalLiveInterval;
154
		date_default_timezone_set('UTC');
155
156
		$filter_query = $this->getFilter($filter,true,true);
157
158
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
159
		if ($globalDBdriver == 'mysql') {
160
			$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, marine_live.captain_name 
161
			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";
162
		} else {
163
			$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, marine_live.captain_name 
164
			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'";
165
		}
166
167
		try {
168
			$sth = $this->db->prepare($query);
169
			$sth->execute();
170
		} catch(PDOException $e) {
171
			echo $e->getMessage();
172
			die;
173
		}
174
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
175
176
		return $spotter_array;
177
	}
178
179
	/**
180
	* Gets Minimal Live Spotter data since xx seconds
181
	*
182
	* @return Array the spotter information
183
	*
184
	*/
185
	public function getMinLastLiveMarineData($coord = array(),$filter = array(), $limit = false)
186
	{
187
		global $globalDBdriver, $globalLiveInterval, $globalMap3DMarinesLimit, $globalArchive;
188
		date_default_timezone_set('UTC');
189
		$usecoord = false;
190
		if (is_array($coord) && !empty($coord)) {
191
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
192
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
193
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
194
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
195
			$usecoord = true;
196
		}
197
		$filter_query = $this->getFilter($filter,true,true);
198
199
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
200
		if (!isset($globalMap3DMarinesLimit) || $globalMap3DMarinesLimit == '') $globalMap3DMarinesLimit = '300';
201
		if ($globalDBdriver == 'mysql') {
202
			if (isset($globalArchive) && $globalArchive === TRUE) {
203
				$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, marine_live.captain_name 
204
				    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 ";
205
				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...
206
				$query .= "UNION
207
				    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, marine_live.captain_name 
208
				    FROM marine_live".$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date";
209
				if ($usecoord) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
210
				$query .= ") AS marine 
211
				    WHERE latitude <> '0' AND longitude <> '0' 
212
				    ORDER BY fammarine_id, date";
213
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
214
			} else {
215
				$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, marine_live.captain_name 
216
				    FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= marine_live.date ";
217
				if ($usecoord) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
218
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
219
				ORDER BY marine_live.fammarine_id, marine_live.date";
220
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
221
			}
222
		} else {
223
			if (isset($globalArchive) && $globalArchive === TRUE) {
224
				$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, marine_live.captain_name 
225
				    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 ";
226
				if ($usecoord) $query .= "AND marine_archive.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_archive.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
227
				$query .= "UNION
228
				    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, marine_live.captain_name 
229
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date";
230
				if ($usecoord) $query .= " AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong;
231
				$query .= ") AS marine WHERE latitude <> '0' AND longitude <> '0' ";
232
				$query .= "ORDER BY fammarine_id, date";
233
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
234
			} else {
235
				$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, marine_live.captain_name 
236
				    FROM marine_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date ";
237
				if ($usecoord) $query .= "AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." ";
238
				$query .= "AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' 
239
				ORDER BY marine_live.fammarine_id, marine_live.date";
240
				if ($limit) $query .= " LIMIT ".$globalMap3DMarinesLimit;
241
			}
242
		}
243
		try {
244
			$sth = $this->db->prepare($query);
245
			$sth->execute();
246
		} catch(PDOException $e) {
247
			echo $e->getMessage();
248
			die;
249
		}
250
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
251
		return $spotter_array;
252
	}
253
254
	/**
255
	* Gets number of latest data entry
256
	*
257
	* @return String number of entry
258
	*
259
	*/
260
	public function getLiveMarineCount($filter = array())
261
	{
262
		global $globalDBdriver, $globalLiveInterval;
263
		$filter_query = $this->getFilter($filter,true,true);
264
265
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
266
		if ($globalDBdriver == 'mysql') {
267
			$query = 'SELECT COUNT(DISTINCT marine_live.fammarine_id) as nb FROM marine_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
268
		} else {
269
			$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";
270
		}
271
		try {
272
			$sth = $this->db->prepare($query);
273
			$sth->execute();
274
		} catch(PDOException $e) {
275
			echo $e->getMessage();
276
			die;
277
		}
278
		$result = $sth->fetch(PDO::FETCH_ASSOC);
279
		$sth->closeCursor();
280
		return $result['nb'];
281
	}
282
283
	/**
284
	* Gets all the spotter information based on the latest data entry and coord
285
	*
286
	* @return Array the spotter information
287
	*
288
	*/
289
	public function getLiveMarineDatabyCoord($coord, $filter = array())
290
	{
291
		global $globalDBdriver, $globalLiveInterval;
292
		$Marine = new Marine($this->db);
293
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
294
		$filter_query = $this->getFilter($filter);
295
296
		if (is_array($coord)) {
297
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
298
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
299
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
300
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
301
		} else return array();
302
		if ($globalDBdriver == 'mysql') {
303
			$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 ORDER BY date DESC'.$filter_query;
304
		} else {
305
			$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 ORDEr BY date DESC".$filter_query;
306
		}
307
		$spotter_array = $Marine->getDataFromDB($query);
308
		return $spotter_array;
309
	}
310
311
	/**
312
	* Gets all the spotter information based on the latest data entry and coord
313
	*
314
	* @return Array the spotter information
315
	*
316
	*/
317
	public function getMinLiveMarineDatabyCoord($coord, $filter = array())
318
	{
319
		global $globalDBdriver, $globalLiveInterval, $globalArchive;
320
		$Marine = new Marine($this->db);
321
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
322
		$filter_query = $this->getFilter($filter,true,true);
323
324
		if (is_array($coord)) {
325
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
326
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
327
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
328
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
329
		} else return array();
330
		/*
331
		if ($globalDBdriver == 'mysql') {
332
			$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 
333
			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."
334
			ORDER BY marine_live.fammarine_id, marine_live.date";
335
		} else {
336
			$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 
337
			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."
338
			ORDER BY marine_live.fammarine_id, marine_live.date";
339
		}
340
		*/
341
		if ($globalDBdriver == 'mysql') {
342
			if (isset($globalArchive) && $globalArchive === TRUE) {
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, marine_live.captain_name 
344
				    FROM marine_live 
345
				    '.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= marine_live.date 
346
				    AND marine_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND marine_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
347
				    AND marine_live.latitude <> 0 AND marine_live.longitude <> 0 ORDER BY date DESC';
348
			} else {
349
				$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, marine_live.captain_name 
350
				    FROM marine_live 
351
				    INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate 
352
				    FROM marine_live l 
353
				    WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date 
354
				    AND l.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND l.longitude BETWEEN '.$minlong.' AND '.$maxlong.'
355
				    GROUP BY l.fammarine_id
356
				    ) s on marine_live.fammarine_id = s.fammarine_id 
357
				    AND marine_live.date = s.maxdate'.$filter_query.' marine_live.latitude <> 0 AND marine_live.longitude <> 0 ORDER BY date DESC';
358
			}
359
		} else {
360
			if (isset($globalArchive) && $globalArchive === TRUE) {
361
				$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, marine_live.captain_name 
362
				    FROM marine_live 
363
				    ".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= marine_live.date 
364
				    AND marine_live.latitude BETWEEN ".$minlat." AND ".$maxlat." 
365
				    AND marine_live.longitude BETWEEN ".$minlong." AND ".$maxlong." 
366
				    AND marine_live.latitude <> '0' AND marine_live.longitude <> '0' ORDER BY date DESC";
367
			} else {
368
				$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, marine_live.captain_name 
369
				    FROM marine_live 
370
				    INNER JOIN (SELECT l.fammarine_id, max(l.date) as maxdate 
371
				    FROM marine_live l 
372
				    WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date 
373
				    AND l.latitude BETWEEN ".$minlat." AND ".$maxlat." 
374
				    AND l.longitude BETWEEN ".$minlong." AND ".$maxlong." 
375
				    GROUP BY l.fammarine_id
376
				    ) s on marine_live.fammarine_id = s.fammarine_id 
377
				    AND marine_live.date = s.maxdate".$filter_query." marine_live.latitude <> '0' AND marine_live.longitude <> '0' ORDER BY date DESC";
378
			}
379
		}
380
		$spotter_array = $Marine->getDataFromDB($query);
381
		return $spotter_array;
382
	}
383
384
	/**
385
	* Gets all the spotter information based on a user's latitude and longitude
386
	*
387
	* @return Array the spotter information
388
	*
389
	*/
390
	public function getLatestMarineForLayar($lat, $lng, $radius, $interval)
391
	{
392
		$Marine = new Marine($this->db);
393
		date_default_timezone_set('UTC');
394
		if ($lat != '') {
395
			if (!is_numeric($lat)) {
396
				return false;
397
			}
398
		}
399
		if ($lng != '')
400
		{
401
			if (!is_numeric($lng))
402
                        {
403
                                return false;
404
                        }
405
                }
406
407
                if ($radius != '')
408
                {
409
                        if (!is_numeric($radius))
410
                        {
411
                                return false;
412
                        }
413
                }
414
		$additional_query = '';
415
		if ($interval != '')
416
                {
417
                        if (!is_string($interval))
418
                        {
419
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
420
			        return false;
421
                        } else {
422
                if ($interval == '1m')
423
                {
424
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';
425
                } else if ($interval == '15m'){
426
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= marine_live.date ';
427
                } 
428
            }
429
                } else {
430
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= marine_live.date ';   
431
        }
432
433
                $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 
434
                   WHERE marine_live.latitude <> '' 
435
                                   AND marine_live.longitude <> '' 
436
                   ".$additional_query."
437
                   HAVING distance < :radius  
438
                                   ORDER BY distance";
439
440
                $spotter_array = $Marine->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
441
442
                return $spotter_array;
443
        }
444
445
    
446
        /**
447
	* Gets all the spotter information based on a particular callsign
448
	*
449
	* @return Array the spotter information
450
	*
451
	*/
452
	public function getLastLiveMarineDataByIdent($ident)
453
	{
454
		$Marine = new Marine($this->db);
455
		date_default_timezone_set('UTC');
456
457
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
458
                $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';
459
460
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident),'',true);
461
462
		return $spotter_array;
463
	}
464
465
        /**
466
	* Gets all the spotter information based on a particular callsign
467
	*
468
	* @return Array the spotter information
469
	*
470
	*/
471
	public function getDateLiveMarineDataByIdent($ident,$date)
472
	{
473
		$Marine = new Marine($this->db);
474
		date_default_timezone_set('UTC');
475
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
476
		$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';
477
		$date = date('c',$date);
478
		$spotter_array = $Marine->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
479
		return $spotter_array;
480
	}
481
482
	/**
483
	* Gets all the spotter information based on a particular MMSI
484
	*
485
	* @return Array the spotter information
486
	*
487
	*/
488
	public function getDateLiveMarineDataByMMSI($mmsi,$date)
489
	{
490
		$Marine = new Marine($this->db);
491
		date_default_timezone_set('UTC');
492
		$mmsi = filter_var($mmsi, FILTER_SANITIZE_NUMBER_INT);
493
		$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';
494
		$date = date('c',$date);
495
		$spotter_array = $Marine->getDataFromDB($query,array(':mmsi' => $mmsi,':date' => $date));
496
		return $spotter_array;
497
	}
498
499
        /**
500
	* Gets last spotter information based on a particular callsign
501
	*
502
	* @return Array the spotter information
503
	*
504
	*/
505
	public function getLastLiveMarineDataById($id)
506
	{
507
		$Marine = new Marine($this->db);
508
		date_default_timezone_set('UTC');
509
510
		$id = filter_var($id, FILTER_SANITIZE_STRING);
511
                $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';
512
513
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id),'',true);
514
515
		return $spotter_array;
516
	}
517
518
        /**
519
	* Gets last spotter information based on a particular callsign
520
	*
521
	* @return Array the spotter information
522
	*
523
	*/
524
	public function getDateLiveMarineDataById($id,$date)
525
	{
526
		$Marine = new Marine($this->db);
527
		date_default_timezone_set('UTC');
528
529
		$id = filter_var($id, FILTER_SANITIZE_STRING);
530
                $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';
531
                $date = date('c',$date);
532
		$spotter_array = $Marine->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
533
534
		return $spotter_array;
535
	}
536
537
538
        /**
539
	* Gets all the spotter information based on a particular id
540
	*
541
	* @return Array the spotter information
542
	*
543
	*/
544
	public function getAllLiveMarineDataById($id,$liveinterval = false)
545
	{
546
		global $globalDBdriver, $globalLiveInterval;
547
		date_default_timezone_set('UTC');
548
		$id = filter_var($id, FILTER_SANITIZE_STRING);
549
		//$query  = self::$global_query.' WHERE marine_live.fammarine_id = :id ORDER BY date';
550
		if ($globalDBdriver == 'mysql') {
551
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
552
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
553
			$query .= ' ORDER BY date';
554
		} else {
555
			$query = 'SELECT marine_live.* FROM marine_live WHERE marine_live.fammarine_id = :id';
556
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
557
			$query .= ' ORDER BY date';
558
		}
559
560
		try {
561
			$sth = $this->db->prepare($query);
562
			$sth->execute(array(':id' => $id));
563
		} catch(PDOException $e) {
564
			echo $e->getMessage();
565
			die;
566
		}
567
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
568
		return $spotter_array;
569
	}
570
571
        /**
572
	* Gets all the spotter information based on a particular ident
573
	*
574
	* @return Array the spotter information
575
	*
576
	*/
577
	public function getAllLiveMarineDataByIdent($ident)
578
	{
579
		date_default_timezone_set('UTC');
580
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
581
		$query  = self::$global_query.' WHERE marine_live.ident = :ident';
582
    		try {
583
			
584
			$sth = $this->db->prepare($query);
585
			$sth->execute(array(':ident' => $ident));
586
		} catch(PDOException $e) {
587
			echo $e->getMessage();
588
			die;
589
		}
590
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
591
		return $spotter_array;
592
	}
593
594
595
	/**
596
	* Deletes all info in the table
597
	*
598
	* @return String success or false
599
	*
600
	*/
601
	public function deleteLiveMarineData()
602
	{
603
		global $globalDBdriver;
604
		if ($globalDBdriver == 'mysql') {
605
			//$query  = "DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= marine_live.date";
606
			$query  = 'DELETE FROM marine_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= marine_live.date';
607
            		//$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)";
608
		} else {
609
			$query  = "DELETE FROM marine_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= marine_live.date";
610
		}
611
        
612
    		try {
613
			
614
			$sth = $this->db->prepare($query);
615
			$sth->execute();
616
		} catch(PDOException $e) {
617
			return "error";
618
		}
619
620
		return "success";
621
	}
622
623
	/**
624
	* Deletes all info in the table for aircraft not seen since 2 HOUR
625
	*
626
	* @return String success or false
627
	*
628
	*/
629
	public function deleteLiveMarineDataNotUpdated()
630
	{
631
		global $globalDBdriver, $globalDebug;
632
		if ($globalDBdriver == 'mysql') {
633
			//$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';
634
    			$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";
635
    			try {
636
				
637
				$sth = $this->db->prepare($query);
638
				$sth->execute();
639
			} catch(PDOException $e) {
640
				return "error";
641
			}
642
			$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
643
                        $i = 0;
644
                        $j =0;
645
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
646
			foreach($all as $row)
647
			{
648
				$i++;
649
				$j++;
650
				if ($j == 30) {
651
					if ($globalDebug) echo ".";
652
				    	try {
653
						
654
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
655
						$sth->execute();
656
					} catch(PDOException $e) {
657
						return "error";
658
					}
659
                                	$query_delete = 'DELETE FROM marine_live WHERE fammarine_id IN (';
660
                                	$j = 0;
661
				}
662
				$query_delete .= "'".$row['fammarine_id']."',";
663
			}
664
			if ($i > 0) {
665
    				try {
666
					
667
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
668
					$sth->execute();
669
				} catch(PDOException $e) {
670
					return "error";
671
				}
672
			}
673
			return "success";
674
		} elseif ($globalDBdriver == 'pgsql') {
675
			//$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";
676
    			//$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";
677
    			$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)";
678
    			try {
679
				
680
				$sth = $this->db->prepare($query);
681
				$sth->execute();
682
			} catch(PDOException $e) {
683
				return "error";
684
			}
685
/*			$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
686
                        $i = 0;
687
                        $j =0;
688
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
689
			foreach($all as $row)
690
			{
691
				$i++;
692
				$j++;
693
				if ($j == 100) {
694
					if ($globalDebug) echo ".";
695
				    	try {
696
						
697
						$sth = $this->db->query(substr($query_delete,0,-1).")");
698
						//$sth->execute();
699
					} catch(PDOException $e) {
700
						return "error";
701
					}
702
                                	$query_delete = "DELETE FROM marine_live WHERE fammarine_id IN (";
703
                                	$j = 0;
704
				}
705
				$query_delete .= "'".$row['fammarine_id']."',";
706
			}
707
			if ($i > 0) {
708
    				try {
709
					
710
					$sth = $this->db->query(substr($query_delete,0,-1).")");
711
					//$sth->execute();
712
				} catch(PDOException $e) {
713
					return "error";
714
				}
715
			}
716
*/
717
			return "success";
718
		}
719
	}
720
721
	/**
722
	* Deletes all info in the table for an ident
723
	*
724
	* @return String success or false
725
	*
726
	*/
727
	public function deleteLiveMarineDataByIdent($ident)
728
	{
729
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
730
		$query  = 'DELETE FROM marine_live WHERE ident = :ident';
731
        
732
    		try {
733
			
734
			$sth = $this->db->prepare($query);
735
			$sth->execute(array(':ident' => $ident));
736
		} catch(PDOException $e) {
737
			return "error";
738
		}
739
740
		return "success";
741
	}
742
743
	/**
744
	* Deletes all info in the table for an id
745
	*
746
	* @return String success or false
747
	*
748
	*/
749
	public function deleteLiveMarineDataById($id)
750
	{
751
		$id = filter_var($id, FILTER_SANITIZE_STRING);
752
		$query  = 'DELETE FROM marine_live WHERE fammarine_id = :id';
753
        
754
    		try {
755
			
756
			$sth = $this->db->prepare($query);
757
			$sth->execute(array(':id' => $id));
758
		} catch(PDOException $e) {
759
			return "error";
760
		}
761
762
		return "success";
763
	}
764
765
766
	/**
767
	* Gets the marine race
768
	*
769
	* @return String the ident
770
	*
771
	*/
772
	public function getAllRaces()
773
	{
774
		$query  = 'SELECT DISTINCT marine_live.race_id, marine_live.race_name FROM marine_live ORDER BY marine_live.race_name';
775
		$sth = $this->db->prepare($query);
776
		$sth->execute();
777
		$ident_result='';
0 ignored issues
show
Unused Code introduced by
$ident_result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
778
		return $sth->fetchAll(PDO::FETCH_ASSOC);
779
	}
780
781
	/**
782
	* Gets the aircraft ident within the last hour
783
	*
784
	* @return String the ident
785
	*
786
	*/
787
	public function getIdentFromLastHour($ident)
788
	{
789
		global $globalDBdriver, $globalTimezone;
790
		if ($globalDBdriver == 'mysql') {
791
			$query  = 'SELECT marine_live.ident FROM marine_live 
792
				WHERE marine_live.ident = :ident 
793
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
794
				AND marine_live.date < UTC_TIMESTAMP()';
795
			$query_data = array(':ident' => $ident);
796
		} else {
797
			$query  = "SELECT marine_live.ident FROM marine_live 
798
				WHERE marine_live.ident = :ident 
799
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
800
				AND marine_live.date < now() AT TIME ZONE 'UTC'";
801
			$query_data = array(':ident' => $ident);
802
		}
803
		
804
		$sth = $this->db->prepare($query);
805
		$sth->execute($query_data);
806
		$ident_result='';
807
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
808
		{
809
			$ident_result = $row['ident'];
810
		}
811
		return $ident_result;
812
        }
813
814
	/**
815
	* Check recent aircraft
816
	*
817
	* @return String the ident
818
	*
819
	*/
820
	public function checkIdentRecent($ident)
821
	{
822
		global $globalDBdriver, $globalTimezone;
823
		if ($globalDBdriver == 'mysql') {
824
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
825
				WHERE marine_live.ident = :ident 
826
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
827
//				AND marine_live.date < UTC_TIMESTAMP()";
828
			$query_data = array(':ident' => $ident);
829
		} else {
830
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
831
				WHERE marine_live.ident = :ident 
832
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
833
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
834
			$query_data = array(':ident' => $ident);
835
		}
836
		
837
		$sth = $this->db->prepare($query);
838
		$sth->execute($query_data);
839
		$ident_result='';
840
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
841
		{
842
			$ident_result = $row['fammarine_id'];
843
		}
844
		return $ident_result;
845
        }
846
847
	/**
848
	* Check recent aircraft by id
849
	*
850
	* @return String the ident
851
	*
852
	*/
853
	public function checkIdRecent($id)
854
	{
855
		global $globalDBdriver, $globalTimezone;
856
		if ($globalDBdriver == 'mysql') {
857
			$query  = 'SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
858
				WHERE marine_live.fammarine_id = :id 
859
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
860
//				AND marine_live.date < UTC_TIMESTAMP()";
861
			$query_data = array(':id' => $id);
862
		} else {
863
			$query  = "SELECT marine_live.ident, marine_live.fammarine_id FROM marine_live 
864
				WHERE marine_live.fammarine_id = :id 
865
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
866
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
867
			$query_data = array(':id' => $id);
868
		}
869
		
870
		$sth = $this->db->prepare($query);
871
		$sth->execute($query_data);
872
		$ident_result='';
873
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
874
		{
875
			$ident_result = $row['fammarine_id'];
876
		}
877
		return $ident_result;
878
        }
879
880
	/**
881
	* Check recent aircraft by mmsi
882
	*
883
	* @return String the ident
884
	*
885
	*/
886
	public function checkMMSIRecent($mmsi)
887
	{
888
		global $globalDBdriver, $globalTimezone;
889
		if ($globalDBdriver == 'mysql') {
890
			$query  = 'SELECT marine_live.fammarine_id FROM marine_live 
891
				WHERE marine_live.mmsi = :mmsi 
892
				AND marine_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
893
//				AND marine_live.date < UTC_TIMESTAMP()";
894
			$query_data = array(':mmsi' => $mmsi);
895
		} else {
896
			$query  = "SELECT marine_live.fammarine_id FROM marine_live 
897
				WHERE marine_live.mmsi = :mmsi 
898
				AND marine_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
899
//				AND marine_live.date < now() AT TIME ZONE 'UTC'";
900
			$query_data = array(':mmsi' => $mmsi);
901
		}
902
		
903
		$sth = $this->db->prepare($query);
904
		$sth->execute($query_data);
905
		$ident_result='';
906
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
907
		{
908
			$ident_result = $row['fammarine_id'];
909
		}
910
		return $ident_result;
911
        }
912
913
	/**
914
	* Adds a new spotter data
915
	*
916
	* @param String $fammarine_id the ID from flightaware
917
	* @param String $ident the flight ident
918
	* @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...
919
	* @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...
920
	* @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...
921
	* @return String success or false
922
	*
923
	*/
924
	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 = '',$captain_id = '',$captain_name = '',$race_id = '', $race_name = '')
925
	{
926
		global $globalURL, $globalArchive, $globalDebug;
927
		$Common = new Common();
928
		date_default_timezone_set('UTC');
929
930
		//getting the airline information
931
		if ($ident != '')
932
		{
933
			if (!is_string($ident))
934
			{
935
				return false;
936
			} 
937
		}
938
939
940
		if ($latitude != '')
941
		{
942
			if (!is_numeric($latitude))
943
			{
944
				return false;
945
			}
946
		} else return '';
947
948
		if ($longitude != '')
949
		{
950
			if (!is_numeric($longitude))
951
			{
952
				return false;
953
			}
954
		} else return '';
955
956
957
		if ($heading != '')
958
		{
959
			if (!is_numeric($heading))
960
			{
961
				return false;
962
			}
963
		} else $heading = 0;
964
965
		if ($groundspeed != '')
966
		{
967
			if (!is_numeric($groundspeed))
968
			{
969
				return false;
970
			}
971
		} else $groundspeed = 0;
972
		date_default_timezone_set('UTC');
973
		if ($date == '') $date = date("Y-m-d H:i:s", time());
974
975
        
976
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
977
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
978
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
979
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
980
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
981
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
982
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
983
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
984
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
985
		$type = filter_var($type,FILTER_SANITIZE_STRING);
986
		$typeid = filter_var($typeid,FILTER_SANITIZE_NUMBER_INT);
987
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
988
		$status = filter_var($status,FILTER_SANITIZE_STRING);
989
		$statusid = filter_var($statusid,FILTER_SANITIZE_NUMBER_INT);
990
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
991
		$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
992
		$arrival_code = filter_var($arrival_code,FILTER_SANITIZE_STRING);
993
		$arrival_date = filter_var($arrival_date,FILTER_SANITIZE_STRING);
994
		$captain_id = filter_var($captain_id,FILTER_SANITIZE_STRING);
995
		$captain_name = filter_var($captain_name,FILTER_SANITIZE_STRING);
996
		$race_id = filter_var($race_id,FILTER_SANITIZE_STRING);
997
		$race_name = filter_var($race_name,FILTER_SANITIZE_STRING);
998
		if ($typeid == '') $typeid = NULL;
999
		if ($statusid == '') $statusid = NULL;
1000
1001
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
1002
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
1003
            	if ($arrival_date == '') $arrival_date = NULL;
1004
            	$query = '';
1005
		if ($globalArchive) {
1006
			if ($globalDebug) echo '-- Delete previous data -- ';
1007
			$query .= 'DELETE FROM marine_live WHERE fammarine_id = :fammarine_id;';
1008
		}
1009
		$query .= 'INSERT INTO marine_live (fammarine_id, ident, latitude, longitude, heading, ground_speed, date, format_source, source_name, over_country, mmsi, type,type_id,status,status_id,imo,arrival_port_name,arrival_port_date,captain_id,captain_name,race_id,race_name) 
1010
		    VALUES (:fammarine_id,:ident,:latitude,:longitude,:heading,:groundspeed,:date,:format_source, :source_name, :over_country,:mmsi,:type,:typeid,:status,:statusid,:imo,:arrival_port_name,:arrival_port_date,:captain_id,:captain_name,:race_id,:race_name)';
1011
		$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,':typeid' => $typeid,':status' => $status,':statusid' => $statusid,':imo' => $imo,':arrival_port_name' => $arrival_code,':arrival_port_date' => $arrival_date,':captain_id' => $captain_id,':captain_name' => $captain_name,':race_id' => $race_id,':race_name' => $race_name);
1012
		try {
1013
			$sth = $this->db->prepare($query);
1014
			$sth->execute($query_values);
1015
			$sth->closeCursor();
1016
		} catch(PDOException $e) {
1017
			return "error : ".$e->getMessage();
1018
		}
1019
		
1020
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
1021
			if ($globalDebug) echo '(Add to Marine archive : ';
1022
			$MarineArchive = new MarineArchive($this->db);
1023
			$result =  $MarineArchive->addMarineArchiveData($fammarine_id, $ident, $latitude, $longitude, $heading, $groundspeed, $date, $putinarchive, $mmsi,$type,$typeid,$imo, $callsign,$arrival_code,$arrival_date,$status,$statusid,$noarchive,$format_source, $source_name, $over_country,$captain_id,$captain_name,$race_id,$race_name);
1024
			if ($globalDebug) echo $result.')';
1025
		}
1026
		return "success";
1027
	}
1028
1029
	public function getOrderBy()
1030
	{
1031
		$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"));
1032
		return $orderby;
1033
	}
1034
1035
}
1036
1037
1038
?>
1039