Completed
Push — master ( cc50d0...0f8c33 )
by Yannick
09:46
created

MarineLive   D

Complexity

Total Complexity 131

Size/Duplication

Total Lines 865
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

24 Methods

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

How to fix   Complexity   

Complex Class

Complex classes like MarineLive often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MarineLive, and based on these observations, apply Extract Interface, too.

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