Completed
Push — master ( 3326da...2a1f3f )
by Yannick
30:39
created

Marine   D

Complexity

Total Complexity 336

Size/Duplication

Total Lines 1984
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 0
loc 1984
rs 4.4102
c 0
b 0
f 0
wmc 336
lcom 1
cbo 5

41 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
F getFilter() 0 63 30
F getDataFromDB() 0 124 46
B getLatestMarineData() 0 27 5
A getMarineDataByID() 0 12 2
C getMarineDataByIdent() 0 49 7
B getMarineDataByDate() 0 56 9
B getAllSourceName() 0 26 4
A getAllIdents() 0 21 2
A getIdentity() 0 10 2
B getAllDates() 0 36 4
A updateIdentMarineData() 0 12 2
B addIdentity() 0 20 5
A updateArrivalPortNameMarineData() 0 12 2
A updateStatusMarineData() 0 16 2
A updateLatestMarineData() 0 15 2
F addMarineData() 0 116 28
B getIdentFromLastHour() 0 27 3
B getRealTimeData() 0 32 5
C countAllMarineOverCountries() 0 67 14
F countAllCallsigns() 0 63 13
B countAllDates() 0 42 4
B countAllDatesLast7Days() 0 39 4
B countAllDatesLastMonth() 0 39 4
B countAllMonths() 0 39 4
B countAllMonthsLastYear() 0 40 4
B countAllHours() 0 58 6
B countAllHoursByDate() 0 39 4
B countAllHoursByIdent() 0 40 4
B countOverallMarine() 0 32 6
B countOverallMarineTypes() 0 31 6
B countAllHoursFromToday() 0 37 4
A getMarineIDBasedOnFamMarineID() 0 17 2
B parseDateString() 0 30 2
C parseDirection() 0 75 35
B getCountryFromLatitudeLongitude() 0 34 6
B getCountryFromISO2() 0 25 6
A getBitlyURL() 0 23 3
F countAllMarineTypes() 0 62 13
F searchMarineData() 0 126 29
A getOrderBy() 0 7 1

How to fix   Complexity   

Complex Class

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

1
<?php
2
require_once(dirname(__FILE__).'/class.Image.php');
3
$global_query = "SELECT marine_output.* FROM marine_output";
4
5
class Marine{
6
	public $db;
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. (Marine)');
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
	
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 spotter_output.format_source IN ('".implode("','",$flt['source'])."')) spfi ON spfi.fammarine_id = marine_output.fammarine_id";
40
				} else {
41
					$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output WHERE marine_output.ident IN ('".implode("','",$flt['idents'])."')) spfi ON spfi.fammarine_id = marine_output.fammarine_id";
42
				}
43
			}
44
		}
45
		if (isset($filter['source']) && !empty($filter['source'])) {
46
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
47
		}
48
		if (isset($filter['ident']) && !empty($filter['ident'])) {
49
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
50
		}
51
		if (isset($filter['mmsi']) && !empty($filter['mmsi'])) {
52
			$filter_query_where .= " AND mmsi = '".$filter['mmsi']."'";
53
		}
54
		if (isset($filter['year']) && $filter['year'] != '') {
55
			if ($globalDBdriver == 'mysql') {
56
				$filter_query_where .= " AND YEAR(marine_output.date) = '".$filter['year']."'";
57
			} else {
58
				$filter_query_where .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
59
			}
60
		}
61
		if (isset($filter['month']) && $filter['month'] != '') {
62
			if ($globalDBdriver == 'mysql') {
63
				$filter_query_where .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
64
			} else {
65
				$filter_query_where .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
66
			}
67
		}
68
		if (isset($filter['day']) && $filter['day'] != '') {
69
			if ($globalDBdriver == 'mysql') {
70
				$filter_query_where .= " AND DAY(marine_output.date) = '".$filter['day']."'";
71
			} else {
72
				$filter_query_where .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
73
			}
74
		}
75
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
76
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
77
		if ($filter_query_where != '') {
78
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
79
		}
80
		$filter_query = $filter_query_join.$filter_query_where;
81
		return $filter_query;
82
	}
83
84
	/**
85
	* Executes the SQL statements to get the spotter information
86
	*
87
	* @param String $query the SQL query
88
	* @param Array $params parameter of the query
89
	* @param String $limitQuery the limit query
90
	* @return Array the spotter information
91
	*
92
	*/
93
	public function getDataFromDB($query, $params = array(), $limitQuery = '',$schedules = false)
0 ignored issues
show
Unused Code introduced by
The parameter $schedules 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...
94
	{
95
		date_default_timezone_set('UTC');
96
		if (!is_string($query))
97
		{
98
			return false;
99
		}
100
		
101
		if ($limitQuery != "")
102
		{
103
			if (!is_string($limitQuery))
104
			{
105
				return false;
106
			}
107
		}
108
109
		try {
110
			$sth = $this->db->prepare($query.$limitQuery);
111
			$sth->execute($params);
112
		} catch (PDOException $e) {
113
			printf("Invalid query : %s\nWhole query: %s\n",$e->getMessage(), $query.$limitQuery);
114
			exit();
115
		}
116
		
117
		$num_rows = 0;
118
		$spotter_array = array();
119
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
120
		{
121
			$num_rows++;
122
			$temp_array = array();
123
			if (isset($row['marine_live_id'])) {
124
				$temp_array['marine_id'] = $this->getMarineIDBasedOnFamMarineID($row['fammarine_id']);
125
			/*
126
			} elseif (isset($row['spotter_archive_id'])) {
127
				$temp_array['spotter_id'] = $row['spotter_archive_id'];
128
			} elseif (isset($row['spotter_archive_output_id'])) {
129
				$temp_array['spotter_id'] = $row['spotter_archive_output_id'];
130
			*/} 
131
			elseif (isset($row['marineid'])) {
132
				$temp_array['marine_id'] = $row['marineid'];
133
			} else {
134
				$temp_array['marine_id'] = '';
135
			}
136
			if (isset($row['fammarine_id'])) $temp_array['fammarine_id'] = $row['fammarine_id'];
137
			if (isset($row['mmsi'])) $temp_array['mmsi'] = $row['mmsi'];
138
			if (isset($row['type'])) $temp_array['type'] = $row['type'];
139
			if (isset($row['type_id'])) $temp_array['type_id'] = $row['type_id'];
140
			if (isset($row['ident'])) $temp_array['ident'] = $row['ident'];
141
			if (isset($row['latitude'])) $temp_array['latitude'] = $row['latitude'];
142
			if (isset($row['longitude'])) $temp_array['longitude'] = $row['longitude'];
143
			if (isset($row['format_source'])) $temp_array['format_source'] = $row['format_source'];
144
			if (isset($row['heading'])) {
145
				$temp_array['heading'] = $row['heading'];
146
				$heading_direction = $this->parseDirection($row['heading']);
147
				if (isset($heading_direction[0]['direction_fullname'])) $temp_array['heading_name'] = $heading_direction[0]['direction_fullname'];
148
			}
149
			if (isset($row['ground_speed'])) $temp_array['ground_speed'] = $row['ground_speed'];
150
151
			if(isset($temp_array['mmsi']) && $temp_array['mmsi'] != "")
152
			{
153
				$Image = new Image($this->db);
154
				if (isset($temp_array['ident']) && $temp_array['ident'] != '') $image_array = $Image->getMarineImage($temp_array['mmsi'],'',$temp_array['ident']);
155
				else $image_array = $Image->getMarineImage($temp_array['mmsi']);
156
				unset($Image);
157
				if (count($image_array) > 0) {
158
					$temp_array['image'] = $image_array[0]['image'];
159
					$temp_array['image_thumbnail'] = $image_array[0]['image_thumbnail'];
160
					$temp_array['image_source'] = $image_array[0]['image_source'];
161
					$temp_array['image_source_website'] = $image_array[0]['image_source_website'];
162
					$temp_array['image_copyright'] = $image_array[0]['image_copyright'];
163
				}
164
			}
165
			
166
			if (isset($row['date'])) {
167
				$dateArray = $this->parseDateString($row['date']);
168
				if ($dateArray['seconds'] < 10)
169
				{
170
					$temp_array['date'] = "a few seconds ago";
171
				} elseif ($dateArray['seconds'] >= 5 && $dateArray['seconds'] < 30)
172
				{
173
					$temp_array['date'] = "half a minute ago";
174
				} elseif ($dateArray['seconds'] >= 30 && $dateArray['seconds'] < 60)
175
				{
176
					$temp_array['date'] = "about a minute ago";
177
				} elseif ($dateArray['minutes'] < 5)
178
				{
179
					$temp_array['date'] = "a few minutes ago";
180
				} elseif ($dateArray['minutes'] >= 5 && $dateArray['minutes'] < 60)
181
				{
182
					$temp_array['date'] = "about ".$dateArray['minutes']." minutes ago";
183
				} elseif ($dateArray['hours'] < 2)
184
				{
185
					$temp_array['date'] = "about an hour ago";
186
				} elseif ($dateArray['hours'] >= 2 && $dateArray['hours'] < 24)
187
				{
188
					$temp_array['date'] = "about ".$dateArray['hours']." hours ago";
189
				} else {
190
					$temp_array['date'] = date("M j Y, g:i a",strtotime($row['date']." UTC"));
191
				}
192
				$temp_array['date_minutes_past'] = $dateArray['minutes'];
193
				$temp_array['date_iso_8601'] = date("c",strtotime($row['date']." UTC"));
194
				$temp_array['date_rfc_2822'] = date("r",strtotime($row['date']." UTC"));
195
				$temp_array['date_unix'] = strtotime($row['date']." UTC");
196
				if (isset($row['last_seen']) && $row['last_seen'] != '') {
197
					if (strtotime($row['last_seen']) > strtotime($row['date'])) {
198
						$temp_array['duration'] = strtotime($row['last_seen']) - strtotime($row['date']);
199
						$temp_array['last_seen_date_iso_8601'] = date("c",strtotime($row['last_seen']." UTC"));
200
						$temp_array['last_seen_date_rfc_2822'] = date("r",strtotime($row['last_seen']." UTC"));
201
						$temp_array['last_seen_date_unix'] = strtotime($row['last_seen']." UTC");
202
					}
203
				}
204
			}
205
			
206
			$fromsource = NULL;
0 ignored issues
show
Unused Code introduced by
$fromsource 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...
207
			if (isset($row['source_name']) && $row['source_name'] != '') $temp_array['source_name'] = $row['source_name'];
208
			if (isset($row['over_country']) && $row['over_country'] != '') $temp_array['over_country'] = $row['over_country'];
209
			if (isset($row['distance']) && $row['distance'] != '') $temp_array['distance'] = $row['distance'];
210
			$temp_array['query_number_rows'] = $num_rows;
211
			$spotter_array[] = $temp_array;
212
		}
213
		if ($num_rows == 0) return array();
214
		$spotter_array[0]['query_number_rows'] = $num_rows;
215
		return $spotter_array;
216
	}	
217
	
218
	
219
	/**
220
	* Gets all the spotter information based on the latest data entry
221
	*
222
	* @return Array the spotter information
223
	*
224
	*/
225
	public function getLatestMarineData($limit = '', $sort = '', $filter = array())
226
	{
227
		global $global_query;
228
		date_default_timezone_set('UTC');
229
		$filter_query = $this->getFilter($filter);
230
		if ($limit != "")
231
		{
232
			$limit_array = explode(",", $limit);
233
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
234
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
235
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
236
			{
237
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
238
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
239
			} else $limit_query = "";
240
		} else $limit_query = "";
241
		if ($sort != "")
242
		{
243
			$search_orderby_array = $this->getOrderBy();
244
			$orderby_query = $search_orderby_array[$sort]['sql'];
245
		} else {
246
			$orderby_query = " ORDER BY marine_output.date DESC";
247
		}
248
		$query  = $global_query.$filter_query." ".$orderby_query;
249
		$spotter_array = $this->getDataFromDB($query, array(),$limit_query,true);
250
		return $spotter_array;
251
	}
252
    
253
	/*
254
	* Gets all the spotter information based on the spotter id
255
	*
256
	* @return Array the spotter information
257
	*
258
	*/
259
	public function getMarineDataByID($id = '')
260
	{
261
		global $global_query;
262
		
263
		date_default_timezone_set('UTC');
264
		if ($id == '') return array();
265
		$additional_query = "marine_output.fammarine_id = :id";
266
		$query_values = array(':id' => $id);
267
		$query  = $global_query." WHERE ".$additional_query." ";
268
		$spotter_array = $this->getDataFromDB($query,$query_values);
269
		return $spotter_array;
270
	}
271
272
	/**
273
	* Gets all the spotter information based on the callsign
274
	*
275
	* @return Array the spotter information
276
	*
277
	*/
278
	public function getMarineDataByIdent($ident = '', $limit = '', $sort = '', $filter = array())
279
	{
280
		global $global_query;
281
		
282
		date_default_timezone_set('UTC');
283
		
284
		$query_values = array();
285
		$limit_query = '';
286
		$additional_query = '';
287
		$filter_query = $this->getFilter($filter,true,true);
288
		if ($ident != "")
289
		{
290
			if (!is_string($ident))
291
			{
292
				return false;
293
			} else {
294
				$additional_query = " AND (marine_output.ident = :ident)";
295
				$query_values = array(':ident' => $ident);
296
			}
297
		}
298
		
299
		if ($limit != "")
300
		{
301
			$limit_array = explode(",", $limit);
302
			
303
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
304
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
305
			
306
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
307
			{
308
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
309
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
310
			}
311
		}
312
313
		if ($sort != "")
314
		{
315
			$search_orderby_array = $this->getOrderBy();
316
			$orderby_query = $search_orderby_array[$sort]['sql'];
317
		} else {
318
			$orderby_query = " ORDER BY marine_output.date DESC";
319
		}
320
321
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query." ".$orderby_query;
322
		//echo $query."\n";
323
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
324
325
		return $spotter_array;
326
	}
327
	
328
	public function getMarineDataByDate($date = '', $limit = '', $sort = '',$filter = array())
329
	{
330
		global $global_query, $globalTimezone, $globalDBdriver;
331
		
332
		$query_values = array();
333
		$limit_query = '';
334
		$additional_query = '';
335
336
		$filter_query = $this->getFilter($filter,true,true);
337
		
338
		if ($date != "")
339
		{
340
			if ($globalTimezone != '') {
341
				date_default_timezone_set($globalTimezone);
342
				$datetime = new DateTime($date);
343
				$offset = $datetime->format('P');
344
			} else {
345
				date_default_timezone_set('UTC');
346
				$datetime = new DateTime($date);
347
				$offset = '+00:00';
348
			}
349
			if ($globalDBdriver == 'mysql') {
350
				$additional_query = " AND DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date ";
351
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':offset' => $offset);
352
			} elseif ($globalDBdriver == 'pgsql') {
353
				$additional_query = " AND to_char(marine_output.date AT TIME ZONE :timezone,'YYYY-mm-dd') = :date ";
354
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':timezone' => $globalTimezone);
355
			}
356
		}
357
		
358
		if ($limit != "")
359
		{
360
			$limit_array = explode(",", $limit);
361
			
362
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
363
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
364
			
365
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
366
			{
367
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
368
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
369
			}
370
		}
371
372
		if ($sort != "")
373
		{
374
			$search_orderby_array = $this->getOrderBy();
375
			$orderby_query = $search_orderby_array[$sort]['sql'];
376
		} else {
377
			$orderby_query = " ORDER BY marine_output.date DESC";
378
		}
379
380
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query.$orderby_query;
381
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
382
		return $spotter_array;
383
	}
384
385
386
387
	/**
388
	* Gets all source name
389
	*
390
	* @param String type format of source
391
	* @return Array list of source name
392
	*
393
	*/
394
	public function getAllSourceName($type = '',$filters = array())
395
	{
396
		$filter_query = $this->getFilter($filters,true,true);
397
		$query_values = array();
398
		$query  = "SELECT DISTINCT marine_output.source_name 
399
				FROM marine_output".$filter_query." marine_output.source_name <> ''";
400
		if ($type != '') {
401
			$query_values = array(':type' => $type);
402
			$query .= " AND format_source = :type";
403
		}
404
		$query .= " ORDER BY marine_output.source_name ASC";
405
406
		$sth = $this->db->prepare($query);
407
		if (!empty($query_values)) $sth->execute($query_values);
408
		else $sth->execute();
409
410
		$source_array = array();
411
		$temp_array = array();
412
		
413
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
414
		{
415
			$temp_array['source_name'] = $row['source_name'];
416
			$source_array[] = $temp_array;
417
		}
418
		return $source_array;
419
	}
420
421
422
	/**
423
	* Gets a list of all idents/callsigns
424
	*
425
	* @return Array list of ident/callsign names
426
	*
427
	*/
428
	public function getAllIdents($filters = array())
429
	{
430
		$filter_query = $this->getFilter($filters,true,true);
431
		$query  = "SELECT DISTINCT marine_output.ident
432
								FROM marine_output".$filter_query." marine_output.ident <> '' 
433
								ORDER BY marine_output.date ASC LIMIT 700 OFFSET 0";
434
435
		$sth = $this->db->prepare($query);
436
		$sth->execute();
437
    
438
		$ident_array = array();
439
		$temp_array = array();
440
		
441
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
442
		{
443
			$temp_array['ident'] = $row['ident'];
444
			$ident_array[] = $temp_array;
445
		}
446
447
		return $ident_array;
448
	}
449
450
	/**
451
	* Gets all info from a mmsi
452
	*
453
	* @return Array ident
454
	*
455
	*/
456
	public function getIdentity($mmsi)
457
	{
458
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
459
		$query  = "SELECT * FROM marine_identity WHERE mmsi = :mmsi LIMIT 1";
460
		$sth = $this->db->prepare($query);
461
		$sth->execute(array(':mmsi' => $mmsi));
462
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
463
		if (isset($result[0])) return $result[0];
464
		else return array();
465
	}
466
467
	/**
468
	* Add identity
469
	*
470
	*/
471
	public function addIdentity($mmsi,$imo,$ident,$callsign,$type)
472
	{
473
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
474
		if ($mmsi != '') {
475
			$imo = filter_var($imo,FILTER_SANITIZE_NUMBER_INT);
476
			$ident = filter_var($ident,FILTER_SANITIZE_STRING);
477
			$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
478
			$type = filter_var($type,FILTER_SANITIZE_STRING);
479
			$identinfo = $this->getIdentity($mmsi);
480
			if (empty($identinfo)) {
481
				$query  = "INSERT INTO marine_identity (mmsi,imo,call_sign,ship_name,type) VALUES (:mmsi,:imo,:call_sign,:ship_name,:type)";
482
				$sth = $this->db->prepare($query);
483
				$sth->execute(array(':mmsi' => $mmsi,':imo' => $imo,':call_sign' => $callsign,':ship_name' => $ident,':type' => $type));
484
			} elseif ($ident != '' && $identinfo['ship_name'] != $ident) {
485
				$query  = "UPDATE marine_identity SET ship_name = :ship_name,type = :type WHERE mmsi = :mmsi";
486
				$sth = $this->db->prepare($query);
487
				$sth->execute(array(':mmsi' => $mmsi,':ship_name' => $ident,':type' => $type));
488
			}
489
		}
490
	}
491
492
	/*
493
	* Gets a list of all dates
494
	*
495
	* @return Array list of date names
496
	*
497
	*/
498
	public function getAllDates()
499
	{
500
		global $globalTimezone, $globalDBdriver;
501
		if ($globalTimezone != '') {
502
			date_default_timezone_set($globalTimezone);
503
			$datetime = new DateTime();
504
			$offset = $datetime->format('P');
505
		} else $offset = '+00:00';
506
507
		if ($globalDBdriver == 'mysql') {
508
			$query  = "SELECT DISTINCT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) as date
509
								FROM marine_output
510
								WHERE marine_output.date <> '' 
511
								ORDER BY marine_output.date ASC LIMIT 0,100";
512
		} else {
513
			$query  = "SELECT DISTINCT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') as date
514
								FROM marine_output
515
								WHERE marine_output.date <> '' 
516
								ORDER BY marine_output.date ASC LIMIT 0,100";
517
		}
518
		
519
		$sth = $this->db->prepare($query);
520
		$sth->execute(array(':offset' => $offset));
521
    
522
		$date_array = array();
523
		$temp_array = array();
524
		
525
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
526
		{
527
			$temp_array['date'] = $row['date'];
528
529
			$date_array[] = $temp_array;
530
		}
531
532
		return $date_array;
533
	}
534
535
	/**
536
	* Update ident tracker data
537
	*
538
	* @param String $fammarine_id the ID
539
	* @param String $ident the marine ident
540
	* @return String success or false
541
	*
542
	*/
543
	public function updateIdentMarineData($fammarine_id = '', $ident = '',$fromsource = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $fromsource 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...
544
	{
545
		$query = 'UPDATE marine_output SET ident = :ident WHERE fammarine_id = :fammarine_id';
546
		$query_values = array(':fammarine_id' => $fammarine_id,':ident' => $ident);
547
		try {
548
			$sth = $this->db->prepare($query);
549
			$sth->execute($query_values);
550
		} catch (PDOException $e) {
551
			return "error : ".$e->getMessage();
552
		}
553
		return "success";
554
	}
555
556
	/**
557
	* Update arrival marine data
558
	*
559
	* @param String $fammarine_id the ID
560
	* @param String $ident the marine ident
0 ignored issues
show
Bug introduced by
There is no parameter named $ident. 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...
561
	* @return String success or false
562
	*
563
	*/
564
	public function updateArrivalPortNameMarineData($fammarine_id = '', $arrival_code = '',$fromsource = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $fromsource 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...
565
	{
566
		$query = 'UPDATE marine_output SET arrival_port_name = :arrival_code WHERE fammarine_id = :fammarine_id';
567
		$query_values = array(':fammarine_id' => $fammarine_id,':arrival_code' => $arrival_code);
568
		try {
569
			$sth = $this->db->prepare($query);
570
			$sth->execute($query_values);
571
		} catch (PDOException $e) {
572
			return "error : ".$e->getMessage();
573
		}
574
		return "success";
575
	}
576
577
	/**
578
	* Update Status data
579
	*
580
	* @param String $fammarine_id the ID
581
	* @param String $status_id the marine status id
582
	* @param String $status the marine status
583
	* @return String success or false
584
	*
585
	*/
586
	public function updateStatusMarineData($fammarine_id = '', $status_id = '',$status = '')
587
	{
588
589
		$query = 'UPDATE marine_output SET status = :status, status_id = :status_id WHERE fammarine_id = :fammarine_id';
590
                $query_values = array(':fammarine_id' => $fammarine_id,':status' => $status,':status_id' => $status_id);
591
592
		try {
593
			$sth = $this->db->prepare($query);
594
			$sth->execute($query_values);
595
		} catch (PDOException $e) {
596
			return "error : ".$e->getMessage();
597
		}
598
		
599
		return "success";
600
601
	}
602
	/**
603
	* Update latest marine data
604
	*
605
	* @param String $fammarine_id the ID
606
	* @param String $ident the marine ident
607
	* @return String success or false
608
	*
609
	*/	
610
	public function updateLatestMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $groundspeed = NULL, $date = '')
611
	{
612
		$query = 'UPDATE marine_output SET ident = :ident, last_latitude = :last_latitude, last_longitude = :last_longitude, last_seen = :last_seen, last_ground_speed = :last_ground_speed WHERE fammarine_id = :fammarine_id';
613
                $query_values = array(':fammarine_id' => $fammarine_id,':last_latitude' => $latitude,':last_longitude' => $longitude, ':last_ground_speed' => $groundspeed,':last_seen' => $date,':ident' => $ident);
614
615
		try {
616
			$sth = $this->db->prepare($query);
617
			$sth->execute($query_values);
618
		} catch (PDOException $e) {
619
			return "error : ".$e->getMessage();
620
		}
621
		
622
		return "success";
623
624
	}
625
626
	/**
627
	* Adds a new spotter data
628
	*
629
	* @param String $fammarine_id the ID
630
	* @param String $ident the marine ident
631
	* @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...
632
	* @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...
633
	* @param String $latitude latitude of flight
634
	* @param String $longitude latitude of flight
635
	* @param String $waypoints waypoints of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $waypoints. 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...
636
	* @param String $heading heading of flight
637
	* @param String $groundspeed speed of flight
638
	* @param String $date date of flight
639
	* @param String $departure_airport_time departure time of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $departure_airport_time. 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...
640
	* @param String $arrival_airport_time arrival time of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $arrival_airport_time. 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...
641
	* @param String $squawk squawk code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $squawk. 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...
642
	* @param String $route_stop route stop of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $route_stop. 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...
643
	* @param String $highlight highlight or not
0 ignored issues
show
Bug introduced by
There is no parameter named $highlight. 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...
644
	* @param String $ModeS ModesS code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $ModeS. 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...
645
	* @param String $registration registration code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $registration. 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...
646
	* @param String $pilot_id pilot id of flight (for virtual airlines)
0 ignored issues
show
Bug introduced by
There is no parameter named $pilot_id. 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...
647
	* @param String $pilot_name pilot name of flight (for virtual airlines)
0 ignored issues
show
Bug introduced by
There is no parameter named $pilot_name. 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...
648
	* @param String $verticalrate vertival rate of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $verticalrate. 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...
649
	* @return String success or false
650
	*/
651
	public function addMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $heading = '', $groundspeed = '', $date = '', $mmsi = '',$type = '',$typeid = '',$imo = '',$callsign = '',$arrival_code = '',$arrival_date = '',$status = '',$statusid = '',$format_source = '', $source_name = '')
0 ignored issues
show
Unused Code introduced by
The parameter $typeid 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 $statusid is not used and could be removed.

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

Loading history...
652
	{
653
		global $globalURL, $globalMarineImageFetch;
654
		
655
		//$Image = new Image($this->db);
656
		$Common = new Common();
657
		
658
		date_default_timezone_set('UTC');
659
		
660
		//getting the registration
661
		if ($fammarine_id != "")
662
		{
663
			if (!is_string($fammarine_id))
664
			{
665
				return false;
666
			}
667
		}
668
		$fromsource = NULL;
0 ignored issues
show
Unused Code introduced by
$fromsource 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...
669
		//getting the airline information
670
		if ($ident != "")
671
		{
672
			if (!is_string($ident))
673
			{
674
				return false;
675
			}
676
		}
677
678
		if ($latitude != "")
679
		{
680
			if (!is_numeric($latitude))
681
			{
682
				return false;
683
			}
684
		}
685
		
686
		if ($longitude != "")
687
		{
688
			if (!is_numeric($longitude))
689
			{
690
				return false;
691
			}
692
		}
693
		
694
		if ($heading != "")
695
		{
696
			if (!is_numeric($heading))
697
			{
698
				return false;
699
			}
700
		}
701
		if ($mmsi != "")
702
		{
703
			if (!is_numeric($mmsi))
704
			{
705
				return false;
706
			}
707
		}
708
		
709
		if ($groundspeed != "")
710
		{
711
			if (!is_numeric($groundspeed))
712
			{
713
				return false;
714
			}
715
		}
716
717
    
718
		if ($date == "" || strtotime($date) < time()-20*60)
719
		{
720
			$date = date("Y-m-d H:i:s", time());
721
		}
722
723
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
724
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
725
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
726
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
727
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
728
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
729
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
730
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
731
		$type = filter_var($type,FILTER_SANITIZE_STRING);
732
		$status = filter_var($status,FILTER_SANITIZE_STRING);
733
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
734
		$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
0 ignored issues
show
Unused Code introduced by
$callsign 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...
735
		$arrival_code = filter_var($arrival_code,FILTER_SANITIZE_STRING);
736
		$arrival_date = filter_var($arrival_date,FILTER_SANITIZE_STRING);
737
		if (isset($globalMarineImageFetch) && $globalMarineImageFetch === TRUE) {
738
			$Image = new Image($this->db);
739
			$image_array = $Image->getMarineImage($mmsi,$imo,$ident);
740
			if (!isset($image_array[0]['mmsi'])) {
741
				$Image->addMarineImage($mmsi,$imo,$ident);
742
			}
743
			unset($Image);
744
		}
745
		if ($latitude == '' && $longitude == '') {
746
			$latitude = 0;
747
			$longitude = 0;
748
		}
749
		if ($heading == '' || $Common->isInteger($heading) === false) $heading = 0;
750
		if ($groundspeed == '' || $Common->isInteger($groundspeed) === false) $groundspeed = 0;
751
		if ($arrival_date == '') $arrival_date = NULL;
752
		$query  = "INSERT INTO marine_output (fammarine_id, ident, latitude, longitude, heading, ground_speed, date, format_source, source_name, mmsi, type, status,imo,arrival_port_name,arrival_port_date) 
753
		    VALUES (:fammarine_id,:ident,:latitude,:longitude,:heading,:speed,:date,:format_source, :source_name,:mmsi,:type,:status,:imo,:arrival_port_name,:arrival_port_date)";
754
755
		$query_values = array(':fammarine_id' => $fammarine_id,':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':heading' => $heading,':speed' => $groundspeed,':date' => $date,':format_source' => $format_source, ':source_name' => $source_name,':mmsi' => $mmsi,':type' => $type,':status' => $status,':imo' => $imo,':arrival_port_name' => $arrival_code,':arrival_port_date' => $arrival_date);
756
		try {
757
			$sth = $this->db->prepare($query);
758
			$sth->execute($query_values);
759
			$this->db = null;
760
		} catch (PDOException $e) {
761
		    return "error : ".$e->getMessage();
762
		}
763
		
764
		return "success";
765
766
	}
767
	
768
  
769
	/**
770
	* Gets the aircraft ident within the last hour
771
	*
772
	* @return String the ident
773
	*
774
	*/
775
	public function getIdentFromLastHour($ident)
776
	{
777
		global $globalDBdriver, $globalTimezone;
778
		if ($globalDBdriver == 'mysql') {
779
			$query  = "SELECT marine_output.ident FROM marine_output 
780
								WHERE marine_output.ident = :ident 
781
								AND marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
782
								AND marine_output.date < UTC_TIMESTAMP()";
783
			$query_data = array(':ident' => $ident);
784
		} else {
785
			$query  = "SELECT marine_output.ident FROM marine_output 
786
								WHERE marine_output.ident = :ident 
787
								AND marine_output.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
788
								AND marine_output.date < now() AT TIME ZONE 'UTC'";
789
			$query_data = array(':ident' => $ident);
790
    		}
791
		
792
		$sth = $this->db->prepare($query);
793
		$sth->execute($query_data);
794
    		$ident_result='';
795
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
796
		{
797
			$ident_result = $row['ident'];
798
		}
799
800
		return $ident_result;
801
	}
802
	
803
	
804
	/**
805
	* Gets the aircraft data from the last 20 seconds
806
	*
807
	* @return Array the spotter data
808
	*
809
	*/
810
	public function getRealTimeData($q = '')
811
	{
812
		global $globalDBdriver;
813
		$additional_query = '';
814
		if ($q != "")
815
		{
816
			if (!is_string($q))
817
			{
818
				return false;
819
			} else {
820
				$q_array = explode(" ", $q);
821
				foreach ($q_array as $q_item){
822
					$q_item = filter_var($q_item,FILTER_SANITIZE_STRING);
823
					$additional_query .= " AND (";
824
					$additional_query .= "(marine_output.ident like '%".$q_item."%')";
825
					$additional_query .= ")";
826
				}
827
			}
828
		}
829
		if ($globalDBdriver == 'mysql') {
830
			$query  = "SELECT marine_output.* FROM marine_output 
831
				WHERE marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 20 SECOND) ".$additional_query." 
832
				AND marine_output.date < UTC_TIMESTAMP()";
833
		} else {
834
			$query  = "SELECT marine_output.* FROM marine_output 
835
				WHERE marine_output.date::timestamp >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '20 SECONDS' ".$additional_query." 
836
				AND marine_output.date::timestamp < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
837
		}
838
		$spotter_array = $this->getDataFromDB($query, array());
839
840
		return $spotter_array;
841
	}
842
	
843
	
844
	
845
846
	/**
847
	* Gets all number of flight over countries
848
	*
849
	* @return Array the airline country list
850
	*
851
	*/
852
853
	public function countAllMarineOverCountries($limit = true,$olderthanmonths = 0,$sincedate = '',$filters = array())
854
	{
855
		global $globalDBdriver, $globalArchive;
856
		//$filter_query = $this->getFilter($filters,true,true);
857
		$Connection= new Connection($this->db);
858
		if (!$Connection->tableExists('countries')) return array();
859
		require_once('class.SpotterLive.php');
860
		if (!isset($globalArchive) || $globalArchive !== TRUE) {
861
			$MarineLive = new MarineLive($this->db);
862
			$filter_query = $MarineLive->getFilter($filters,true,true);
863
			$filter_query .= " over_country IS NOT NULL AND over_country <> ''";
864
			if ($olderthanmonths > 0) {
865
				if ($globalDBdriver == 'mysql') {
866
					$filter_query .= ' AND marine_live.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH) ';
867
				} else {
868
					$filter_query .= " AND marine_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
869
				}
870
			}
871
			if ($sincedate != '') {
872
				if ($globalDBdriver == 'mysql') {
873
					$filter_query .= " AND marine_live.date > '".$sincedate."' ";
874
				} else {
875
					$filter_query .= " AND marine_live.date > CAST('".$sincedate."' AS TIMESTAMP)";
876
				}
877
			}
878
			$query = "SELECT c.name, c.iso3, c.iso2, count(c.name) as nb FROM countries c INNER JOIN (SELECT DISTINCT fammarine_id,over_country FROM marine_live".$filter_query.") l ON c.iso2 = l.over_country ";
879
		} else {
880
			require_once(dirname(__FILE__)."/class.MarineArchive.php");
881
			$MarineArchive = new MarineArchive($this->db);
882
			$filter_query = $MarineArchive->getFilter($filters,true,true);
883
			$filter_query .= " over_country <> ''";
884
			if ($olderthanmonths > 0) {
885
				if ($globalDBdriver == 'mysql') {
886
					$filter_query .= ' AND marine_archive.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH) ';
887
				} else {
888
					$filter_query .= " AND marine_archive.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
889
				}
890
			}
891
			if ($sincedate != '') {
892
				if ($globalDBdriver == 'mysql') {
893
					$filter_query .= " AND marine_archive.date > '".$sincedate."' ";
894
				} else {
895
					$filter_query .= " AND marine_archive.date > CAST('".$sincedate."' AS TIMESTAMP)";
896
				}
897
			}
898
			$filter_query .= " LIMIT 100 OFFSET 0";
899
			$query = "SELECT c.name, c.iso3, c.iso2, count(c.name) as nb FROM countries c INNER JOIN (SELECT DISTINCT fammarine_id,over_country FROM marine_archive".$filter_query.") l ON c.iso2 = l.over_country ";
900
		}
901
		$query .= "GROUP BY c.name,c.iso3,c.iso2 ORDER BY nb DESC";
902
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
903
904
		$sth = $this->db->prepare($query);
905
		$sth->execute();
906
 
907
		$flight_array = array();
908
		$temp_array = array();
909
        
910
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
911
		{
912
			$temp_array['marine_count'] = $row['nb'];
913
			$temp_array['marine_country'] = $row['name'];
914
			$temp_array['marine_country_iso3'] = $row['iso3'];
915
			$temp_array['marine_country_iso2'] = $row['iso2'];
916
			$flight_array[] = $temp_array;
917
		}
918
		return $flight_array;
919
	}
920
	
921
	
922
	
923
	/**
924
	* Gets all callsigns that have flown over
925
	*
926
	* @return Array the callsign list
927
	*
928
	*/
929
	public function countAllCallsigns($limit = true, $olderthanmonths = 0, $sincedate = '',$filters = array(),$year = '', $month = '', $day = '')
930
	{
931
		global $globalDBdriver;
932
		$filter_query = $this->getFilter($filters,true,true);
933
		$query  = "SELECT DISTINCT marine_output.ident, COUNT(marine_output.ident) AS callsign_icao_count 
934
                    FROM marine_output".$filter_query." marine_output.ident <> ''";
935
		 if ($olderthanmonths > 0) {
936
			if ($globalDBdriver == 'mysql') $query .= ' AND date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH)';
937
			else $query .= " AND marine_output.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
938
		}
939
		if ($sincedate != '') {
940
			if ($globalDBdriver == 'mysql') $query .= " AND marine_output.date > '".$sincedate."'";
941
			else $query .= " AND marine_output.date > CAST('".$sincedate."' AS TIMESTAMP)";
942
		}
943
		$query_values = array();
944
		if ($year != '') {
945
			if ($globalDBdriver == 'mysql') {
946
				$query .= " AND YEAR(marine_output.date) = :year";
947
				$query_values = array_merge($query_values,array(':year' => $year));
948
			} else {
949
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
950
				$query_values = array_merge($query_values,array(':year' => $year));
951
			}
952
		}
953
		if ($month != '') {
954
			if ($globalDBdriver == 'mysql') {
955
				$query .= " AND MONTH(marine_output.date) = :month";
956
				$query_values = array_merge($query_values,array(':month' => $month));
957
			} else {
958
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
959
				$query_values = array_merge($query_values,array(':month' => $month));
960
			}
961
		}
962
		if ($day != '') {
963
			if ($globalDBdriver == 'mysql') {
964
				$query .= " AND DAY(marine_output.date) = :day";
965
				$query_values = array_merge($query_values,array(':day' => $day));
966
			} else {
967
				$query .= " AND EXTRACT(DAY FROM marine_output.date) = :day";
968
				$query_values = array_merge($query_values,array(':day' => $day));
969
			}
970
		}
971
		$query .= " GROUP BY marine_output.ident ORDER BY callsign_icao_count DESC";
972
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
973
      		
974
		$sth = $this->db->prepare($query);
975
		$sth->execute($query_values);
976
      
977
		$callsign_array = array();
978
		$temp_array = array();
979
        
980
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
981
		{
982
			$temp_array['callsign_icao'] = $row['ident'];
983
			$temp_array['airline_name'] = $row['airline_name'];
984
			$temp_array['airline_icao'] = $row['airline_icao'];
985
			$temp_array['callsign_icao_count'] = $row['callsign_icao_count'];
986
          
987
			$callsign_array[] = $temp_array;
988
		}
989
990
		return $callsign_array;
991
	}
992
993
994
	/**
995
	* Counts all dates
996
	*
997
	* @return Array the date list
998
	*
999
	*/
1000
	public function countAllDates($filters = array())
1001
	{
1002
		global $globalTimezone, $globalDBdriver;
1003
		if ($globalTimezone != '') {
1004
			date_default_timezone_set($globalTimezone);
1005
			$datetime = new DateTime();
1006
			$offset = $datetime->format('P');
1007
		} else $offset = '+00:00';
1008
1009
		if ($globalDBdriver == 'mysql') {
1010
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1011
								FROM marine_output";
1012
			$query .= $this->getFilter($filters);
1013
			$query .= " GROUP BY date_name 
1014
								ORDER BY date_count DESC
1015
								LIMIT 10 OFFSET 0";
1016
		} else {
1017
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1018
								FROM marine_output";
1019
			$query .= $this->getFilter($filters);
1020
			$query .= " GROUP BY date_name 
1021
								ORDER BY date_count DESC
1022
								LIMIT 10 OFFSET 0";
1023
		}
1024
      
1025
		
1026
		$sth = $this->db->prepare($query);
1027
		$sth->execute(array(':offset' => $offset));
1028
      
1029
		$date_array = array();
1030
		$temp_array = array();
1031
        
1032
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1033
		{
1034
			$temp_array['date_name'] = $row['date_name'];
1035
			$temp_array['date_count'] = $row['date_count'];
1036
1037
			$date_array[] = $temp_array;
1038
		}
1039
1040
		return $date_array;
1041
	}
1042
	
1043
	
1044
	/**
1045
	* Counts all dates during the last 7 days
1046
	*
1047
	* @return Array the date list
1048
	*
1049
	*/
1050
	public function countAllDatesLast7Days($filters = array())
1051
	{
1052
		global $globalTimezone, $globalDBdriver;
1053
		if ($globalTimezone != '') {
1054
			date_default_timezone_set($globalTimezone);
1055
			$datetime = new DateTime();
1056
			$offset = $datetime->format('P');
1057
		} else $offset = '+00:00';
1058
		$filter_query = $this->getFilter($filters,true,true);
1059
		if ($globalDBdriver == 'mysql') {
1060
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1061
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 7 DAY)";
1062
			$query .= " GROUP BY date_name 
1063
								ORDER BY marine_output.date ASC";
1064
			$query_data = array(':offset' => $offset);
1065
		} else {
1066
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1067
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '7 DAYS'";
1068
			$query .= " GROUP BY date_name 
1069
								ORDER BY date_name ASC";
1070
			$query_data = array(':offset' => $offset);
1071
    		}
1072
		
1073
		$sth = $this->db->prepare($query);
1074
		$sth->execute($query_data);
1075
      
1076
		$date_array = array();
1077
		$temp_array = array();
1078
        
1079
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1080
		{
1081
			$temp_array['date_name'] = $row['date_name'];
1082
			$temp_array['date_count'] = $row['date_count'];
1083
          
1084
			$date_array[] = $temp_array;
1085
		}
1086
1087
		return $date_array;
1088
	}
1089
1090
	/**
1091
	* Counts all dates during the last month
1092
	*
1093
	* @return Array the date list
1094
	*
1095
	*/
1096
	public function countAllDatesLastMonth($filters = array())
1097
	{
1098
		global $globalTimezone, $globalDBdriver;
1099
		if ($globalTimezone != '') {
1100
			date_default_timezone_set($globalTimezone);
1101
			$datetime = new DateTime();
1102
			$offset = $datetime->format('P');
1103
		} else $offset = '+00:00';
1104
		$filter_query = $this->getFilter($filters,true,true);
1105
		if ($globalDBdriver == 'mysql') {
1106
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1107
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MONTH)";
1108
			$query .= " GROUP BY date_name 
1109
								ORDER BY marine_output.date ASC";
1110
			$query_data = array(':offset' => $offset);
1111
		} else {
1112
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1113
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 MONTHS'";
1114
			$query .= " GROUP BY date_name 
1115
								ORDER BY date_name ASC";
1116
			$query_data = array(':offset' => $offset);
1117
    		}
1118
		
1119
		$sth = $this->db->prepare($query);
1120
		$sth->execute($query_data);
1121
      
1122
		$date_array = array();
1123
		$temp_array = array();
1124
        
1125
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1126
		{
1127
			$temp_array['date_name'] = $row['date_name'];
1128
			$temp_array['date_count'] = $row['date_count'];
1129
          
1130
			$date_array[] = $temp_array;
1131
		}
1132
1133
		return $date_array;
1134
	}
1135
1136
1137
1138
	/**
1139
	* Counts all month
1140
	*
1141
	* @return Array the month list
1142
	*
1143
	*/
1144
	public function countAllMonths($filters = array())
1145
	{
1146
		global $globalTimezone, $globalDBdriver;
1147
		if ($globalTimezone != '') {
1148
			date_default_timezone_set($globalTimezone);
1149
			$datetime = new DateTime();
1150
			$offset = $datetime->format('P');
1151
		} else $offset = '+00:00';
1152
1153
		if ($globalDBdriver == 'mysql') {
1154
			$query  = "SELECT YEAR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS year_name,MONTH(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS month_name, count(*) as date_count
1155
								FROM marine_output";
1156
			$query .= $this->getFilter($filters);
1157
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1158
		} else {
1159
			$query  = "SELECT EXTRACT(YEAR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS year_name,EXTRACT(MONTH FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS month_name, count(*) as date_count
1160
								FROM marine_output";
1161
			$query .= $this->getFilter($filters);
1162
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1163
		}
1164
      
1165
		
1166
		$sth = $this->db->prepare($query);
1167
		$sth->execute(array(':offset' => $offset));
1168
      
1169
		$date_array = array();
1170
		$temp_array = array();
1171
        
1172
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1173
		{
1174
			$temp_array['month_name'] = $row['month_name'];
1175
			$temp_array['year_name'] = $row['year_name'];
1176
			$temp_array['date_count'] = $row['date_count'];
1177
1178
			$date_array[] = $temp_array;
1179
		}
1180
1181
		return $date_array;
1182
	}
1183
1184
	
1185
	
1186
1187
	/**
1188
	* Counts all dates during the last year
1189
	*
1190
	* @return Array the date list
1191
	*
1192
	*/
1193
	public function countAllMonthsLastYear($filters)
1194
	{
1195
		global $globalTimezone, $globalDBdriver;
1196
		if ($globalTimezone != '') {
1197
			date_default_timezone_set($globalTimezone);
1198
			$datetime = new DateTime();
1199
			$offset = $datetime->format('P');
1200
		} else $offset = '+00:00';
1201
		$filter_query = $this->getFilter($filters,true,true);
1202
		if ($globalDBdriver == 'mysql') {
1203
			$query  = "SELECT MONTH(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS month_name, YEAR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS year_name, count(*) as date_count
1204
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 YEAR)";
1205
			$query .= " GROUP BY year_name, month_name
1206
								ORDER BY year_name, month_name ASC";
1207
			$query_data = array(':offset' => $offset);
1208
		} else {
1209
			$query  = "SELECT EXTRACT(MONTH FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS month_name, EXTRACT(YEAR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS year_name, count(*) as date_count
1210
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 YEARS'";
1211
			$query .= " GROUP BY year_name, month_name
1212
								ORDER BY year_name, month_name ASC";
1213
			$query_data = array(':offset' => $offset);
1214
    		}
1215
		
1216
		$sth = $this->db->prepare($query);
1217
		$sth->execute($query_data);
1218
      
1219
		$date_array = array();
1220
		$temp_array = array();
1221
        
1222
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1223
		{
1224
			$temp_array['year_name'] = $row['year_name'];
1225
			$temp_array['month_name'] = $row['month_name'];
1226
			$temp_array['date_count'] = $row['date_count'];
1227
          
1228
			$date_array[] = $temp_array;
1229
		}
1230
1231
		return $date_array;
1232
	}
1233
	
1234
	
1235
	
1236
	/**
1237
	* Counts all hours
1238
	*
1239
	* @return Array the hour list
1240
	*
1241
	*/
1242
	public function countAllHours($orderby,$filters = array())
1243
	{
1244
		global $globalTimezone, $globalDBdriver;
1245
		if ($globalTimezone != '') {
1246
			date_default_timezone_set($globalTimezone);
1247
			$datetime = new DateTime();
1248
			$offset = $datetime->format('P');
1249
		} else $offset = '+00:00';
1250
1251
		$orderby_sql = '';
1252
		if ($orderby == "hour")
1253
		{
1254
			$orderby_sql = "ORDER BY hour_name ASC";
1255
		}
1256
		if ($orderby == "count")
1257
		{
1258
			$orderby_sql = "ORDER BY hour_count DESC";
1259
		}
1260
		
1261
		if ($globalDBdriver == 'mysql') {
1262
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1263
								FROM marine_output";
1264
			$query .= $this->getFilter($filters);
1265
			$query .= " GROUP BY hour_name 
1266
								".$orderby_sql;
1267
1268
/*		$query  = "SELECT HOUR(marine_output.date) AS hour_name, count(*) as hour_count
1269
								FROM marine_output 
1270
								GROUP BY hour_name 
1271
								".$orderby_sql."
1272
								LIMIT 10 OFFSET 00";
1273
  */    
1274
		$query_data = array(':offset' => $offset);
1275
		} else {
1276
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1277
								FROM marine_output";
1278
			$query .= $this->getFilter($filters);
1279
			$query .= " GROUP BY hour_name 
1280
								".$orderby_sql;
1281
			$query_data = array(':offset' => $offset);
1282
		}
1283
		
1284
		$sth = $this->db->prepare($query);
1285
		$sth->execute($query_data);
1286
      
1287
		$hour_array = array();
1288
		$temp_array = array();
1289
        
1290
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1291
		{
1292
			$temp_array['hour_name'] = $row['hour_name'];
1293
			$temp_array['hour_count'] = $row['hour_count'];
1294
          
1295
			$hour_array[] = $temp_array;
1296
		}
1297
1298
		return $hour_array;
1299
	}
1300
	
1301
	
1302
	
1303
	/**
1304
	* Counts all hours by date
1305
	*
1306
	* @return Array the hour list
1307
	*
1308
	*/
1309
	public function countAllHoursByDate($date, $filters = array())
1310
	{
1311
		global $globalTimezone, $globalDBdriver;
1312
		$filter_query = $this->getFilter($filters,true,true);
1313
		$date = filter_var($date,FILTER_SANITIZE_STRING);
1314
		if ($globalTimezone != '') {
1315
			date_default_timezone_set($globalTimezone);
1316
			$datetime = new DateTime($date);
1317
			$offset = $datetime->format('P');
1318
		} else $offset = '+00:00';
1319
1320
		if ($globalDBdriver == 'mysql') {
1321
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1322
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date
1323
								GROUP BY hour_name 
1324
								ORDER BY hour_name ASC";
1325
		} else {
1326
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1327
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset, 'YYYY-mm-dd') = :date
1328
								GROUP BY hour_name 
1329
								ORDER BY hour_name ASC";
1330
		}
1331
		
1332
		$sth = $this->db->prepare($query);
1333
		$sth->execute(array(':date' => $date, ':offset' => $offset));
1334
      
1335
		$hour_array = array();
1336
		$temp_array = array();
1337
        
1338
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1339
		{
1340
			$temp_array['hour_name'] = $row['hour_name'];
1341
			$temp_array['hour_count'] = $row['hour_count'];
1342
          
1343
			$hour_array[] = $temp_array;
1344
		}
1345
1346
		return $hour_array;
1347
	}
1348
	
1349
	
1350
	
1351
	/**
1352
	* Counts all hours by a ident/callsign
1353
	*
1354
	* @return Array the hour list
1355
	*
1356
	*/
1357
	public function countAllHoursByIdent($ident, $filters = array())
1358
	{
1359
		global $globalTimezone, $globalDBdriver;
1360
		$filter_query = $this->getFilter($filters,true,true);
1361
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1362
		if ($globalTimezone != '') {
1363
			date_default_timezone_set($globalTimezone);
1364
			$datetime = new DateTime();
1365
			$offset = $datetime->format('P');
1366
		} else $offset = '+00:00';
1367
1368
		if ($globalDBdriver == 'mysql') {
1369
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1370
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1371
								GROUP BY hour_name 
1372
								ORDER BY hour_name ASC";
1373
		} else {
1374
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1375
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1376
								GROUP BY hour_name 
1377
								ORDER BY hour_name ASC";
1378
		}
1379
      
1380
		
1381
		$sth = $this->db->prepare($query);
1382
		$sth->execute(array(':ident' => $ident,':offset' => $offset));
1383
      
1384
		$hour_array = array();
1385
		$temp_array = array();
1386
        
1387
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1388
		{
1389
			$temp_array['hour_name'] = $row['hour_name'];
1390
			$temp_array['hour_count'] = $row['hour_count'];
1391
          
1392
			$hour_array[] = $temp_array;
1393
		}
1394
1395
		return $hour_array;
1396
	}
1397
	
1398
	
1399
	
1400
	/**
1401
	* Counts all vessels
1402
	*
1403
	* @return Integer the number of vessels
1404
	*
1405
	*/
1406
	public function countOverallMarine($filters = array(),$year = '',$month = '')
1407
	{
1408
		global $globalDBdriver;
1409
		//$queryi  = "SELECT COUNT(marine_output.marine_id) AS flight_count FROM marine_output";
1410
		$queryi  = "SELECT COUNT(DISTINCT marine_output.mmsi) AS flight_count FROM marine_output";
1411
		$query_values = array();
1412
		$query = '';
1413
		if ($year != '') {
1414
			if ($globalDBdriver == 'mysql') {
1415
				$query .= " AND YEAR(marine_output.date) = :year";
1416
				$query_values = array_merge($query_values,array(':year' => $year));
1417
			} else {
1418
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1419
				$query_values = array_merge($query_values,array(':year' => $year));
1420
			}
1421
		}
1422
		if ($month != '') {
1423
			if ($globalDBdriver == 'mysql') {
1424
				$query .= " AND MONTH(marine_output.date) = :month";
1425
				$query_values = array_merge($query_values,array(':month' => $month));
1426
			} else {
1427
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1428
				$query_values = array_merge($query_values,array(':month' => $month));
1429
			}
1430
		}
1431
		if (empty($query_values)) $queryi .= $this->getFilter($filters);
1432
		else $queryi .= $this->getFilter($filters,true,true).substr($query,4);
1433
		
1434
		$sth = $this->db->prepare($queryi);
1435
		$sth->execute($query_values);
1436
		return $sth->fetchColumn();
1437
	}
1438
	
1439
	/**
1440
	* Counts all vessel type
1441
	*
1442
	* @return Integer the number of vessels
1443
	*
1444
	*/
1445
	public function countOverallMarineTypes($filters = array(),$year = '',$month = '')
1446
	{
1447
		global $globalDBdriver;
1448
		$queryi  = "SELECT COUNT(DISTINCT marine_output.type) AS marine_count FROM marine_output";
1449
		$query_values = array();
1450
		$query = '';
1451
		if ($year != '') {
1452
			if ($globalDBdriver == 'mysql') {
1453
				$query .= " AND YEAR(marine_output.date) = :year";
1454
				$query_values = array_merge($query_values,array(':year' => $year));
1455
			} else {
1456
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1457
				$query_values = array_merge($query_values,array(':year' => $year));
1458
			}
1459
		}
1460
		if ($month != '') {
1461
			if ($globalDBdriver == 'mysql') {
1462
				$query .= " AND MONTH(marine_output.date) = :month";
1463
				$query_values = array_merge($query_values,array(':month' => $month));
1464
			} else {
1465
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1466
				$query_values = array_merge($query_values,array(':month' => $month));
1467
			}
1468
		}
1469
		if (empty($query_values)) $queryi .= $this->getFilter($filters);
1470
		else $queryi .= $this->getFilter($filters,true,true).substr($query,4);
1471
		
1472
		$sth = $this->db->prepare($queryi);
1473
		$sth->execute($query_values);
1474
		return $sth->fetchColumn();
1475
	}
1476
	
1477
  
1478
	/**
1479
	* Counts all hours of today
1480
	*
1481
	* @return Array the hour list
1482
	*
1483
	*/
1484
	public function countAllHoursFromToday($filters = array())
1485
	{
1486
		global $globalTimezone, $globalDBdriver;
1487
		$filter_query = $this->getFilter($filters,true,true);
1488
		if ($globalTimezone != '') {
1489
			date_default_timezone_set($globalTimezone);
1490
			$datetime = new DateTime();
1491
			$offset = $datetime->format('P');
1492
		} else $offset = '+00:00';
1493
1494
		if ($globalDBdriver == 'mysql') {
1495
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1496
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = CURDATE()
1497
								GROUP BY hour_name 
1498
								ORDER BY hour_name ASC";
1499
		} else {
1500
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1501
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') = CAST(NOW() AS date)
1502
								GROUP BY hour_name 
1503
								ORDER BY hour_name ASC";
1504
		}
1505
		
1506
		$sth = $this->db->prepare($query);
1507
		$sth->execute(array(':offset' => $offset));
1508
      
1509
		$hour_array = array();
1510
		$temp_array = array();
1511
        
1512
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1513
		{
1514
			$temp_array['hour_name'] = $row['hour_name'];
1515
			$temp_array['hour_count'] = $row['hour_count'];
1516
			$hour_array[] = $temp_array;
1517
		}
1518
1519
		return $hour_array;
1520
	}
1521
    
1522
    
1523
     /**
1524
	* Gets the Barrie Spotter ID based on the FlightAware ID
1525
	*
1526
	* @return Integer the Barrie Spotter ID
1527
q	*
1528
	*/
1529
	public function getMarineIDBasedOnFamMarineID($fammarine_id)
1530
	{
1531
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
1532
1533
		$query  = "SELECT marine_output.marine_id
1534
				FROM marine_output 
1535
				WHERE marine_output.fammarine_id = '".$fammarine_id."'";
1536
        
1537
		
1538
		$sth = $this->db->prepare($query);
1539
		$sth->execute();
1540
1541
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1542
		{
1543
			return $row['marine_id'];
1544
		}
1545
	}
1546
  
1547
 
1548
	/**
1549
	* Parses a date string
1550
	*
1551
	* @param String $dateString the date string
1552
	* @param String $timezone the timezone of a user
1553
	* @return Array the time information
1554
	*
1555
	*/
1556
	public function parseDateString($dateString, $timezone = '')
1557
	{
1558
		$time_array = array();
1559
	
1560
		if ($timezone != "")
1561
		{
1562
			date_default_timezone_set($timezone);
1563
		}
1564
		
1565
		$current_date = date("Y-m-d H:i:s");
1566
		$date = date("Y-m-d H:i:s",strtotime($dateString." UTC"));
1567
		
1568
		$diff = abs(strtotime($current_date) - strtotime($date));
1569
1570
		$time_array['years'] = floor($diff / (365*60*60*24)); 
1571
		$years = $time_array['years'];
1572
		
1573
		$time_array['months'] = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
1574
		$months = $time_array['months'];
1575
		
1576
		$time_array['days'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
1577
		$days = $time_array['days'];
1578
		$time_array['hours'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
1579
		$hours = $time_array['hours'];
1580
		$time_array['minutes'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
1581
		$minutes = $time_array['minutes'];
1582
		$time_array['seconds'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60));  
1583
		
1584
		return $time_array;
1585
	}
1586
	
1587
	/**
1588
	* Parses the direction degrees to working
1589
	*
1590
	* @param Float $direction the direction in degrees
1591
	* @return Array the direction information
1592
	*
1593
	*/
1594
	public function parseDirection($direction = 0)
1595
	{
1596
		if ($direction == '') $direction = 0;
1597
		$direction_array = array();
1598
		$temp_array = array();
1599
1600
		if ($direction == 360 || ($direction >= 0 && $direction < 22.5))
1601
		{
1602
			$temp_array['direction_degree'] = $direction;
1603
			$temp_array['direction_shortname'] = "N";
1604
			$temp_array['direction_fullname'] = "North";
1605
		} elseif ($direction >= 22.5 && $direction < 45){
1606
			$temp_array['direction_degree'] = $direction;
1607
			$temp_array['direction_shortname'] = "NNE";
1608
			$temp_array['direction_fullname'] = "North-Northeast";
1609
		} elseif ($direction >= 45 && $direction < 67.5){
1610
			$temp_array['direction_degree'] = $direction;
1611
			$temp_array['direction_shortname'] = "NE";
1612
			$temp_array['direction_fullname'] = "Northeast";
1613
		} elseif ($direction >= 67.5 && $direction < 90){
1614
			$temp_array['direction_degree'] = $direction;
1615
			$temp_array['direction_shortname'] = "ENE";
1616
			$temp_array['direction_fullname'] = "East-Northeast";
1617
		} elseif ($direction >= 90 && $direction < 112.5){
1618
			$temp_array['direction_degree'] = $direction;
1619
			$temp_array['direction_shortname'] = "E";
1620
			$temp_array['direction_fullname'] = "East";
1621
		} elseif ($direction >= 112.5 && $direction < 135){
1622
			$temp_array['direction_degree'] = $direction;
1623
			$temp_array['direction_shortname'] = "ESE";
1624
			$temp_array['direction_fullname'] = "East-Southeast";
1625
		} elseif ($direction >= 135 && $direction < 157.5){
1626
			$temp_array['direction_degree'] = $direction;
1627
			$temp_array['direction_shortname'] = "SE";
1628
			$temp_array['direction_fullname'] = "Southeast";
1629
		} elseif ($direction >= 157.5 && $direction < 180){
1630
			$temp_array['direction_degree'] = $direction;
1631
			$temp_array['direction_shortname'] = "SSE";
1632
			$temp_array['direction_fullname'] = "South-Southeast";
1633
		} elseif ($direction >= 180 && $direction < 202.5){
1634
			$temp_array['direction_degree'] = $direction;
1635
			$temp_array['direction_shortname'] = "S";
1636
			$temp_array['direction_fullname'] = "South";
1637
		} elseif ($direction >= 202.5 && $direction < 225){
1638
			$temp_array['direction_degree'] = $direction;
1639
			$temp_array['direction_shortname'] = "SSW";
1640
			$temp_array['direction_fullname'] = "South-Southwest";
1641
		} elseif ($direction >= 225 && $direction < 247.5){
1642
			$temp_array['direction_degree'] = $direction;
1643
			$temp_array['direction_shortname'] = "SW";
1644
			$temp_array['direction_fullname'] = "Southwest";
1645
		} elseif ($direction >= 247.5 && $direction < 270){
1646
			$temp_array['direction_degree'] = $direction;
1647
			$temp_array['direction_shortname'] = "WSW";
1648
			$temp_array['direction_fullname'] = "West-Southwest";
1649
		} elseif ($direction >= 270 && $direction < 292.5){
1650
			$temp_array['direction_degree'] = $direction;
1651
			$temp_array['direction_shortname'] = "W";
1652
			$temp_array['direction_fullname'] = "West";
1653
		} elseif ($direction >= 292.5 && $direction < 315){
1654
			$temp_array['direction_degree'] = $direction;
1655
			$temp_array['direction_shortname'] = "WNW";
1656
			$temp_array['direction_fullname'] = "West-Northwest";
1657
		} elseif ($direction >= 315 && $direction < 337.5){
1658
			$temp_array['direction_degree'] = $direction;
1659
			$temp_array['direction_shortname'] = "NW";
1660
			$temp_array['direction_fullname'] = "Northwest";
1661
		} elseif ($direction >= 337.5 && $direction < 360){
1662
			$temp_array['direction_degree'] = $direction;
1663
			$temp_array['direction_shortname'] = "NNW";
1664
			$temp_array['direction_fullname'] = "North-Northwest";
1665
		}
1666
		$direction_array[] = $temp_array;
1667
		return $direction_array;
1668
	}
1669
	
1670
	
1671
	/**
1672
	* Gets Country from latitude/longitude
1673
	*
1674
	* @param Float $latitude latitute of the flight
1675
	* @param Float $longitude longitute of the flight
1676
	* @return String the countrie
1677
	*/
1678
	public function getCountryFromLatitudeLongitude($latitude,$longitude)
1679
	{
1680
		global $globalDBdriver, $globalDebug;
1681
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1682
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1683
	
1684
		$Connection = new Connection($this->db);
1685
		if (!$Connection->tableExists('countries')) return '';
1686
	
1687
		try {
1688
			/*
1689
			if ($globalDBdriver == 'mysql') {
1690
				//$query  = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(:latitude :longitude)'), ogc_geom) LIMIT 1";
1691
				$query = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(".$longitude.' '.$latitude.")'), ogc_geom) LIMIT 1";
1692
			}
1693
			*/
1694
			// This query seems to work both for MariaDB and PostgreSQL
1695
			$query = "SELECT name,iso2,iso3 FROM countries WHERE ST_Within(ST_GeomFromText('POINT(".$longitude." ".$latitude.")',4326), ogc_geom) LIMIT 1";
1696
		
1697
			$sth = $this->db->prepare($query);
1698
			//$sth->execute(array(':latitude' => $latitude,':longitude' => $longitude));
1699
			$sth->execute();
1700
    
1701
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1702
			$sth->closeCursor();
1703
			if (count($row) > 0) {
1704
				return $row;
1705
			} else return '';
1706
		} catch (PDOException $e) {
1707
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1708
			return '';
1709
		}
1710
	
1711
	}
1712
1713
	/**
1714
	* Gets Country from iso2
1715
	*
1716
	* @param String $iso2 ISO2 country code
1717
	* @return String the countrie
1718
	*/
1719
	public function getCountryFromISO2($iso2)
1720
	{
1721
		global $globalDBdriver, $globalDebug;
1722
		$iso2 = filter_var($iso2,FILTER_SANITIZE_STRING);
1723
	
1724
		$Connection = new Connection($this->db);
1725
		if (!$Connection->tableExists('countries')) return '';
1726
	
1727
		try {
1728
			$query = "SELECT name,iso2,iso3 FROM countries WHERE iso2 = :iso2 LIMIT 1";
1729
		
1730
			$sth = $this->db->prepare($query);
1731
			$sth->execute(array(':iso2' => $iso2));
1732
    
1733
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1734
			$sth->closeCursor();
1735
			if (count($row) > 0) {
1736
				return $row;
1737
			} else return '';
1738
		} catch (PDOException $e) {
1739
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1740
			return '';
1741
		}
1742
	
1743
	}
1744
1745
	
1746
	/**
1747
	* Gets the short url from bit.ly
1748
	*
1749
	* @param String $url the full url
1750
	* @return String the bit.ly url
1751
	*
1752
	*/
1753
	public function getBitlyURL($url)
1754
	{
1755
		global $globalBitlyAccessToken;
1756
		
1757
		if ($globalBitlyAccessToken == '') return $url;
1758
        
1759
		$google_url = 'https://api-ssl.bitly.com/v3/shorten?access_token='.$globalBitlyAccessToken.'&longUrl='.$url;
1760
		
1761
		$ch = curl_init();
1762
		curl_setopt($ch, CURLOPT_HEADER, 0);
1763
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1764
		curl_setopt($ch, CURLOPT_URL, $google_url);
1765
		$bitly_data = curl_exec($ch);
1766
		curl_close($ch);
1767
		
1768
		$bitly_data = json_decode($bitly_data);
1769
		$bitly_url = '';
1770
		if ($bitly_data->status_txt = "OK"){
1771
			$bitly_url = $bitly_data->data->url;
1772
		}
1773
1774
		return $bitly_url;
1775
	}
1776
1777
	
1778
	/**
1779
	* Gets all vessels types that have flown over
1780
	*
1781
	* @return Array the vessel type list
1782
	*
1783
	*/
1784
	public function countAllMarineTypes($limit = true,$olderthanmonths = 0,$sincedate = '',$filters = array(),$year = '',$month = '',$day = '')
1785
	{
1786
		global $globalDBdriver;
1787
		$filter_query = $this->getFilter($filters,true,true);
1788
		$query  = "SELECT marine_output.type AS marine_type, COUNT(marine_output.type) AS marine_type_count 
1789
		    FROM marine_output ".$filter_query." marine_output.type  <> ''";
1790
		if ($olderthanmonths > 0) {
1791
			if ($globalDBdriver == 'mysql') {
1792
				$query .= ' AND marine_output.date < DATE_SUB(UTC_TIMESTAMP(), INTERVAL '.$olderthanmonths.' MONTH)';
1793
			} else {
1794
				$query .= " AND marine_output.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
1795
			}
1796
		}
1797
		if ($sincedate != '') {
1798
			if ($globalDBdriver == 'mysql') {
1799
				$query .= " AND marine_output.date > '".$sincedate."'";
1800
			} else {
1801
				$query .= " AND marine_output.date > CAST('".$sincedate."' AS TIMESTAMP)";
1802
			}
1803
		}
1804
		$query_values = array();
1805
		if ($year != '') {
1806
			if ($globalDBdriver == 'mysql') {
1807
				$query .= " AND YEAR(marine_output.date) = :year";
1808
				$query_values = array_merge($query_values,array(':year' => $year));
1809
			} else {
1810
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1811
				$query_values = array_merge($query_values,array(':year' => $year));
1812
			}
1813
		}
1814
		if ($month != '') {
1815
			if ($globalDBdriver == 'mysql') {
1816
				$query .= " AND MONTH(marine_output.date) = :month";
1817
				$query_values = array_merge($query_values,array(':month' => $month));
1818
			} else {
1819
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1820
				$query_values = array_merge($query_values,array(':month' => $month));
1821
			}
1822
		}
1823
		if ($day != '') {
1824
			if ($globalDBdriver == 'mysql') {
1825
				$query .= " AND DAY(marine_output.date) = :day";
1826
				$query_values = array_merge($query_values,array(':day' => $day));
1827
			} else {
1828
				$query .= " AND EXTRACT(DAY FROM marine_output.date) = :day";
1829
				$query_values = array_merge($query_values,array(':day' => $day));
1830
			}
1831
		}
1832
		$query .= " GROUP BY marine_output.type ORDER BY marine_type_count DESC";
1833
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
1834
		$sth = $this->db->prepare($query);
1835
		$sth->execute($query_values);
1836
		$marine_array = array();
1837
		$temp_array = array();
1838
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1839
		{
1840
			$temp_array['marine_type'] = $row['marine_type'];
1841
			$temp_array['marine_type_count'] = $row['marine_type_count'];
1842
			$marine_array[] = $temp_array;
1843
		}
1844
		return $marine_array;
1845
	}
1846
1847
	/**
1848
	* Gets all the tracker information
1849
	*
1850
	* @return Array the tracker information
1851
	*
1852
	*/
1853
	public function searchMarineData($q = '', $callsign = '',$mmsi = '', $imo = '', $date_posted = '', $limit = '', $sort = '', $includegeodata = '',$origLat = '',$origLon = '',$dist = '',$filters = array())
0 ignored issues
show
Unused Code introduced by
The parameter $includegeodata 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...
1854
	{
1855
		global $globalTimezone, $globalDBdriver;
1856
		date_default_timezone_set('UTC');
1857
		$query_values = array();
1858
		$additional_query = '';
1859
		$filter_query = $this->getFilter($filters,true,true);
1860
		if ($q != "")
1861
		{
1862
			if (!is_string($q))
1863
			{
1864
				return false;
1865
			} else {
1866
				$q_array = explode(" ", $q);
1867
				foreach ($q_array as $q_item){
1868
					$q_item = filter_var($q_item,FILTER_SANITIZE_STRING);
1869
					$additional_query .= " AND (";
1870
					if (is_int($q_item)) $additional_query .= "(marine_output.marine_id = '".$q_item."') OR ";
1871
					if (is_int($q_item)) $additional_query .= "(marine_output.mmsi = '".$q_item."') OR ";
1872
					if (is_int($q_item)) $additional_query .= "(marine_output.imo = '".$q_item."') OR ";
1873
					$additional_query .= "(marine_output.ident like '%".$q_item."%') OR ";
1874
					$additional_query .= ")";
1875
				}
1876
			}
1877
		}
1878
		if ($callsign != "")
1879
		{
1880
			$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
1881
			if (!is_string($callsign))
1882
			{
1883
				return false;
1884
			} else {
1885
				$additional_query .= " AND marine_output.ident = :callsign";
1886
				$query_values = array_merge($query_values,array(':callsign' => $callsign));
1887
			}
1888
		}
1889
		if ($mmsi != "")
1890
		{
1891
			$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
1892
			if (!is_numeric($mmsi))
1893
			{
1894
				return false;
1895
			} else {
1896
				$additional_query .= " AND marine_output.mmsi = :mmsi";
1897
				$query_values = array_merge($query_values,array(':mmsi' => $mmsi));
1898
			}
1899
		}
1900
		if ($imo != "")
1901
		{
1902
			$imo = filter_var($imo,FILTER_SANITIZE_STRING);
1903
			if (!is_numeric($imo))
1904
			{
1905
				return false;
1906
			} else {
1907
				$additional_query .= " AND marine_output.imo = :imo";
1908
				$query_values = array_merge($query_values,array(':imo' => $imo));
1909
			}
1910
		}
1911
		if ($date_posted != "")
1912
		{
1913
			$date_array = explode(",", $date_posted);
1914
			$date_array[0] = filter_var($date_array[0],FILTER_SANITIZE_STRING);
1915
			$date_array[1] = filter_var($date_array[1],FILTER_SANITIZE_STRING);
1916
			if ($globalTimezone != '') {
1917
				date_default_timezone_set($globalTimezone);
1918
				$datetime = new DateTime();
1919
				$offset = $datetime->format('P');
1920
			} else $offset = '+00:00';
1921
			if ($date_array[1] != "")
1922
			{
1923
				$date_array[0] = date("Y-m-d H:i:s", strtotime($date_array[0]));
1924
				$date_array[1] = date("Y-m-d H:i:s", strtotime($date_array[1]));
1925
				if ($globalDBdriver == 'mysql') {
1926
					$additional_query .= " AND TIMESTAMP(CONVERT_TZ(marine_output.date,'+00:00', '".$offset."')) >= '".$date_array[0]."' AND TIMESTAMP(CONVERT_TZ(marine_output.date,'+00:00', '".$offset."')) <= '".$date_array[1]."' ";
1927
				} else {
1928
					$additional_query .= " AND CAST(marine_output.date AT TIME ZONE INTERVAL ".$offset." AS TIMESTAMP) >= '".$date_array[0]."' AND CAST(marine_output.date AT TIME ZONE INTERVAL ".$offset." AS TIMESTAMP) <= '".$date_array[1]."' ";
1929
				}
1930
			} else {
1931
				$date_array[0] = date("Y-m-d H:i:s", strtotime($date_array[0]));
1932
				if ($globalDBdriver == 'mysql') {
1933
					$additional_query .= " AND TIMESTAMP(CONVERT_TZ(marine_output.date,'+00:00', '".$offset."')) >= '".$date_array[0]."' ";
1934
				} else {
1935
					$additional_query .= " AND CAST(marine_output.date AT TIME ZONE INTERVAL ".$offset." AS TIMESTAMP) >= '".$date_array[0]."' ";
1936
				}
1937
			}
1938
		}
1939
		if ($limit != "")
1940
		{
1941
			$limit_array = explode(",", $limit);
1942
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
1943
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
1944
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
1945
			{
1946
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
1947
			} else $limit_query = "";
1948
		} else $limit_query = "";
1949
		if ($sort != "")
1950
		{
1951
			$search_orderby_array = $this->getOrderBy();
1952
			$orderby_query = $search_orderby_array[$sort]['sql'];
1953
		} else {
1954
			if ($origLat != "" && $origLon != "" && $dist != "") {
1955
				$orderby_query = " ORDER BY distance ASC";
1956
			} else {
1957
				$orderby_query = " ORDER BY marine_output.date DESC";
1958
			}
1959
		}
1960
		if ($origLat != "" && $origLon != "" && $dist != "") {
1961
			$dist = number_format($dist*0.621371,2,'.',''); // convert km to mile
1962
			if ($globalDBdriver == 'mysql') {
1963
				$query="SELECT marine_output.*, 1.60935*3956 * 2 * ASIN(SQRT( POWER(SIN(($origLat - marine_archive.latitude)*pi()/180/2),2)+COS( $origLat *pi()/180)*COS(marine_archive.latitude*pi()/180)*POWER(SIN(($origLon-marine_archive.longitude)*pi()/180/2),2))) as distance 
1964
				    FROM marine_archive,marine_output".$filter_query." marine_output.fammarine_id = marine_archive.fammarine_id AND marine_output.ident <> '' ".$additional_query."AND marine_archive.longitude between ($origLon-$dist/cos(radians($origLat))*69) and ($origLon+$dist/cos(radians($origLat)*69)) and marine_archive.latitude between ($origLat-($dist/69)) and ($origLat+($dist/69)) 
1965
				    AND (3956 * 2 * ASIN(SQRT( POWER(SIN(($origLat - marine_archive.latitude)*pi()/180/2),2)+COS( $origLat *pi()/180)*COS(marine_archive.latitude*pi()/180)*POWER(SIN(($origLon-marine_archive.longitude)*pi()/180/2),2)))) < $dist".$orderby_query;
1966
			} else {
1967
				$query="SELECT marine_output.*, 1.60935 * 3956 * 2 * ASIN(SQRT( POWER(SIN(($origLat - CAST(marine_archive.latitude as double precision))*pi()/180/2),2)+COS( $origLat *pi()/180)*COS(CAST(marine_archive.latitude as double precision)*pi()/180)*POWER(SIN(($origLon-CAST(marine_archive.longitude as double precision))*pi()/180/2),2))) as distance 
1968
				    FROM marine_archive,marine_output".$filter_query." marine_output.fammarine_id = marine_archive.fammarine_id AND marine_output.ident <> '' ".$additional_query."AND CAST(marine_archive.longitude as double precision) between ($origLon-$dist/cos(radians($origLat))*69) and ($origLon+$dist/cos(radians($origLat))*69) and CAST(marine_archive.latitude as double precision) between ($origLat-($dist/69)) and ($origLat+($dist/69)) 
1969
				    AND (3956 * 2 * ASIN(SQRT( POWER(SIN(($origLat - CAST(marine_archive.latitude as double precision))*pi()/180/2),2)+COS( $origLat *pi()/180)*COS(CAST(marine_archive.latitude as double precision)*pi()/180)*POWER(SIN(($origLon-CAST(marine_archive.longitude as double precision))*pi()/180/2),2)))) < $dist".$filter_query.$orderby_query;
1970
			}
1971
		} else {
1972
			$query  = "SELECT marine_output.* FROM marine_output".$filter_query." marine_output.ident <> '' 
1973
			    ".$additional_query."
1974
			    ".$orderby_query;
1975
		}
1976
		$marine_array = $this->getDataFromDB($query, $query_values,$limit_query);
1977
		return $marine_array;
1978
	}
1979
1980
	public function getOrderBy()
1981
	{
1982
		$orderby = array("type_asc" => array("key" => "type_asc", "value" => "Type - ASC", "sql" => "ORDER BY marine_output.type ASC"), "type_desc" => array("key" => "type_desc", "value" => "Type - DESC", "sql" => "ORDER BY marine_output.type DESC"),"manufacturer_asc" => array("key" => "manufacturer_asc", "value" => "Aircraft Manufacturer - ASC", "sql" => "ORDER BY marine_output.aircraft_manufacturer ASC"), "manufacturer_desc" => array("key" => "manufacturer_desc", "value" => "Aircraft Manufacturer - DESC", "sql" => "ORDER BY marine_output.aircraft_manufacturer DESC"),"airline_name_asc" => array("key" => "airline_name_asc", "value" => "Airline Name - ASC", "sql" => "ORDER BY marine_output.airline_name ASC"), "airline_name_desc" => array("key" => "airline_name_desc", "value" => "Airline Name - DESC", "sql" => "ORDER BY marine_output.airline_name DESC"), "ident_asc" => array("key" => "ident_asc", "value" => "Ident - ASC", "sql" => "ORDER BY marine_output.ident ASC"), "ident_desc" => array("key" => "ident_desc", "value" => "Ident - DESC", "sql" => "ORDER BY marine_output.ident DESC"), "airport_departure_asc" => array("key" => "airport_departure_asc", "value" => "Departure Airport - ASC", "sql" => "ORDER BY marine_output.departure_airport_city ASC"), "airport_departure_desc" => array("key" => "airport_departure_desc", "value" => "Departure Airport - DESC", "sql" => "ORDER BY marine_output.departure_airport_city DESC"), "airport_arrival_asc" => array("key" => "airport_arrival_asc", "value" => "Arrival Airport - ASC", "sql" => "ORDER BY marine_output.arrival_airport_city ASC"), "airport_arrival_desc" => array("key" => "airport_arrival_desc", "value" => "Arrival Airport - DESC", "sql" => "ORDER BY marine_output.arrival_airport_city DESC"), "date_asc" => array("key" => "date_asc", "value" => "Date - ASC", "sql" => "ORDER BY marine_output.date ASC"), "date_desc" => array("key" => "date_desc", "value" => "Date - DESC", "sql" => "ORDER BY marine_output.date DESC"),"distance_asc" => array("key" => "distance_asc","value" => "Distance - ASC","sql" => "ORDER BY distance ASC"),"distance_desc" => array("key" => "distance_desc","value" => "Distance - DESC","sql" => "ORDER BY distance DESC"));
1983
		
1984
		return $orderby;
1985
		
1986
	}
1987
    
1988
}
1989
?>