Completed
Push — master ( b49092...cf2135 )
by Yannick
30:03
created

Marine::countAllHours()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 58
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 33
nc 32
nop 2
dl 0
loc 58
rs 8.7274
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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['year']) && $filter['year'] != '') {
52
			if ($globalDBdriver == 'mysql') {
53
				$filter_query_where .= " AND YEAR(marine_output.date) = '".$filter['year']."'";
54
			} else {
55
				$filter_query_where .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
56
			}
57
		}
58
		if (isset($filter['month']) && $filter['month'] != '') {
59
			if ($globalDBdriver == 'mysql') {
60
				$filter_query_where .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
61
			} else {
62
				$filter_query_where .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
63
			}
64
		}
65
		if (isset($filter['day']) && $filter['day'] != '') {
66
			if ($globalDBdriver == 'mysql') {
67
				$filter_query_where .= " AND DAY(marine_output.date) = '".$filter['day']."'";
68
			} else {
69
				$filter_query_where .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
70
			}
71
		}
72
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
73
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
74
		if ($filter_query_where != '') {
75
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
76
		}
77
		$filter_query = $filter_query_join.$filter_query_where;
78
		return $filter_query;
79
	}
80
81
	/**
82
	* Executes the SQL statements to get the spotter information
83
	*
84
	* @param String $query the SQL query
85
	* @param Array $params parameter of the query
86
	* @param String $limitQuery the limit query
87
	* @return Array the spotter information
88
	*
89
	*/
90
	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...
91
	{
92
		date_default_timezone_set('UTC');
93
		if (!is_string($query))
94
		{
95
			return false;
96
		}
97
		
98
		if ($limitQuery != "")
99
		{
100
			if (!is_string($limitQuery))
101
			{
102
				return false;
103
			}
104
		}
105
106
		try {
107
			$sth = $this->db->prepare($query.$limitQuery);
108
			$sth->execute($params);
109
		} catch (PDOException $e) {
110
			printf("Invalid query : %s\nWhole query: %s\n",$e->getMessage(), $query.$limitQuery);
111
			exit();
112
		}
113
		
114
		$num_rows = 0;
115
		$spotter_array = array();
116
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
117
		{
118
			$num_rows++;
119
			$temp_array = array();
120
			if (isset($row['marine_live_id'])) {
121
				$temp_array['marine_id'] = $this->getMarineIDBasedOnFamMarineID($row['fammarine_id']);
122
			/*
123
			} elseif (isset($row['spotter_archive_id'])) {
124
				$temp_array['spotter_id'] = $row['spotter_archive_id'];
125
			} elseif (isset($row['spotter_archive_output_id'])) {
126
				$temp_array['spotter_id'] = $row['spotter_archive_output_id'];
127
			*/} 
128
			elseif (isset($row['marineid'])) {
129
				$temp_array['marine_id'] = $row['marineid'];
130
			} else {
131
				$temp_array['marine_id'] = '';
132
			}
133
			if (isset($row['fammarine_id'])) $temp_array['fammarine_id'] = $row['fammarine_id'];
134
			if (isset($row['mmsi'])) $temp_array['mmsi'] = $row['mmsi'];
135
			if (isset($row['type'])) $temp_array['type'] = $row['type'];
136
			if (isset($row['type_id'])) $temp_array['type_id'] = $row['type_id'];
137
			if (isset($row['ident'])) $temp_array['ident'] = $row['ident'];
138
			if (isset($row['latitude'])) $temp_array['latitude'] = $row['latitude'];
139
			if (isset($row['longitude'])) $temp_array['longitude'] = $row['longitude'];
140
			if (isset($row['format_source'])) $temp_array['format_source'] = $row['format_source'];
141
			if (isset($row['heading'])) {
142
				$temp_array['heading'] = $row['heading'];
143
				$heading_direction = $this->parseDirection($row['heading']);
144
				if (isset($heading_direction[0]['direction_fullname'])) $temp_array['heading_name'] = $heading_direction[0]['direction_fullname'];
145
			}
146
			if (isset($row['ground_speed'])) $temp_array['ground_speed'] = $row['ground_speed'];
147
148
			if($temp_array['mmsi'] != "")
149
			{
150
				$Image = new Image($this->db);
151
				if (isset($temp_array['ident']) && $temp_array['ident'] != '') $image_array = $Image->getMarineImage($temp_array['mmsi'],'',$temp_array['ident']);
152
				else $image_array = $Image->getMarineImage($temp_array['mmsi']);
153
				unset($Image);
154
				if (count($image_array) > 0) {
155
					$temp_array['image'] = $image_array[0]['image'];
156
					$temp_array['image_thumbnail'] = $image_array[0]['image_thumbnail'];
157
					$temp_array['image_source'] = $image_array[0]['image_source'];
158
					$temp_array['image_source_website'] = $image_array[0]['image_source_website'];
159
					$temp_array['image_copyright'] = $image_array[0]['image_copyright'];
160
				}
161
			}
162
			
163
			if (isset($row['date'])) {
164
				$dateArray = $this->parseDateString($row['date']);
165
				if ($dateArray['seconds'] < 10)
166
				{
167
					$temp_array['date'] = "a few seconds ago";
168
				} elseif ($dateArray['seconds'] >= 5 && $dateArray['seconds'] < 30)
169
				{
170
					$temp_array['date'] = "half a minute ago";
171
				} elseif ($dateArray['seconds'] >= 30 && $dateArray['seconds'] < 60)
172
				{
173
					$temp_array['date'] = "about a minute ago";
174
				} elseif ($dateArray['minutes'] < 5)
175
				{
176
					$temp_array['date'] = "a few minutes ago";
177
				} elseif ($dateArray['minutes'] >= 5 && $dateArray['minutes'] < 60)
178
				{
179
					$temp_array['date'] = "about ".$dateArray['minutes']." minutes ago";
180
				} elseif ($dateArray['hours'] < 2)
181
				{
182
					$temp_array['date'] = "about an hour ago";
183
				} elseif ($dateArray['hours'] >= 2 && $dateArray['hours'] < 24)
184
				{
185
					$temp_array['date'] = "about ".$dateArray['hours']." hours ago";
186
				} else {
187
					$temp_array['date'] = date("M j Y, g:i a",strtotime($row['date']." UTC"));
188
				}
189
				$temp_array['date_minutes_past'] = $dateArray['minutes'];
190
				$temp_array['date_iso_8601'] = date("c",strtotime($row['date']." UTC"));
191
				$temp_array['date_rfc_2822'] = date("r",strtotime($row['date']." UTC"));
192
				$temp_array['date_unix'] = strtotime($row['date']." UTC");
193
				if (isset($row['last_seen']) && $row['last_seen'] != '') {
194
					if (strtotime($row['last_seen']) > strtotime($row['date'])) {
195
						$temp_array['duration'] = strtotime($row['last_seen']) - strtotime($row['date']);
196
						$temp_array['last_seen_date_iso_8601'] = date("c",strtotime($row['last_seen']." UTC"));
197
						$temp_array['last_seen_date_rfc_2822'] = date("r",strtotime($row['last_seen']." UTC"));
198
						$temp_array['last_seen_date_unix'] = strtotime($row['last_seen']." UTC");
199
					}
200
				}
201
			}
202
			
203
			$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...
204
			if (isset($row['source_name']) && $row['source_name'] != '') $temp_array['source_name'] = $row['source_name'];
205
			if (isset($row['over_country']) && $row['over_country'] != '') $temp_array['over_country'] = $row['over_country'];
206
			if (isset($row['distance']) && $row['distance'] != '') $temp_array['distance'] = $row['distance'];
207
			$temp_array['query_number_rows'] = $num_rows;
208
			$spotter_array[] = $temp_array;
209
		}
210
		if ($num_rows == 0) return array();
211
		$spotter_array[0]['query_number_rows'] = $num_rows;
212
		return $spotter_array;
213
	}	
214
	
215
	
216
	/**
217
	* Gets all the spotter information based on the latest data entry
218
	*
219
	* @return Array the spotter information
220
	*
221
	*/
222
	public function getLatestMarineData($limit = '', $sort = '', $filter = array())
223
	{
224
		global $global_query;
225
		date_default_timezone_set('UTC');
226
		$filter_query = $this->getFilter($filter);
227
		if ($limit != "")
228
		{
229
			$limit_array = explode(",", $limit);
230
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
231
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
232
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
233
			{
234
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
235
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
236
			} else $limit_query = "";
237
		} else $limit_query = "";
238
		if ($sort != "")
239
		{
240
			$search_orderby_array = $this->getOrderBy();
241
			$orderby_query = $search_orderby_array[$sort]['sql'];
242
		} else {
243
			$orderby_query = " ORDER BY marine_output.date DESC";
244
		}
245
		$query  = $global_query.$filter_query." ".$orderby_query;
246
		$spotter_array = $this->getDataFromDB($query, array(),$limit_query,true);
247
		return $spotter_array;
248
	}
249
    
250
	/*
251
	* Gets all the spotter information based on the spotter id
252
	*
253
	* @return Array the spotter information
254
	*
255
	*/
256
	public function getMarineDataByID($id = '')
257
	{
258
		global $global_query;
259
		
260
		date_default_timezone_set('UTC');
261
		if ($id == '') return array();
262
		$additional_query = "marine_output.fammarine_id = :id";
263
		$query_values = array(':id' => $id);
264
		$query  = $global_query." WHERE ".$additional_query." ";
265
		$spotter_array = $this->getDataFromDB($query,$query_values);
266
		return $spotter_array;
267
	}
268
269
	/**
270
	* Gets all the spotter information based on the callsign
271
	*
272
	* @return Array the spotter information
273
	*
274
	*/
275
	public function getMarineDataByIdent($ident = '', $limit = '', $sort = '', $filter = array())
276
	{
277
		global $global_query;
278
		
279
		date_default_timezone_set('UTC');
280
		
281
		$query_values = array();
282
		$limit_query = '';
283
		$additional_query = '';
284
		$filter_query = $this->getFilter($filter,true,true);
285
		if ($ident != "")
286
		{
287
			if (!is_string($ident))
288
			{
289
				return false;
290
			} else {
291
				$additional_query = " AND (marine_output.ident = :ident)";
292
				$query_values = array(':ident' => $ident);
293
			}
294
		}
295
		
296
		if ($limit != "")
297
		{
298
			$limit_array = explode(",", $limit);
299
			
300
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
301
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
302
			
303
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
304
			{
305
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
306
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
307
			}
308
		}
309
310
		if ($sort != "")
311
		{
312
			$search_orderby_array = $this->getOrderBy();
313
			$orderby_query = $search_orderby_array[$sort]['sql'];
314
		} else {
315
			$orderby_query = " ORDER BY marine_output.date DESC";
316
		}
317
318
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query." ".$orderby_query;
319
		//echo $query."\n";
320
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
321
322
		return $spotter_array;
323
	}
324
	
325
	public function getMarineDataByDate($date = '', $limit = '', $sort = '',$filter = array())
326
	{
327
		global $global_query, $globalTimezone, $globalDBdriver;
328
		
329
		$query_values = array();
330
		$limit_query = '';
331
		$additional_query = '';
332
333
		$filter_query = $this->getFilter($filter,true,true);
334
		
335
		if ($date != "")
336
		{
337
			if ($globalTimezone != '') {
338
				date_default_timezone_set($globalTimezone);
339
				$datetime = new DateTime($date);
340
				$offset = $datetime->format('P');
341
			} else {
342
				date_default_timezone_set('UTC');
343
				$datetime = new DateTime($date);
344
				$offset = '+00:00';
345
			}
346
			if ($globalDBdriver == 'mysql') {
347
				$additional_query = " AND DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date ";
348
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':offset' => $offset);
349
			} elseif ($globalDBdriver == 'pgsql') {
350
				$additional_query = " AND to_char(marine_output.date AT TIME ZONE :timezone,'YYYY-mm-dd') = :date ";
351
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':timezone' => $globalTimezone);
352
			}
353
		}
354
		
355
		if ($limit != "")
356
		{
357
			$limit_array = explode(",", $limit);
358
			
359
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
360
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
361
			
362
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
363
			{
364
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
365
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
366
			}
367
		}
368
369
		if ($sort != "")
370
		{
371
			$search_orderby_array = $this->getOrderBy();
372
			$orderby_query = $search_orderby_array[$sort]['sql'];
373
		} else {
374
			$orderby_query = " ORDER BY marine_output.date DESC";
375
		}
376
377
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query.$orderby_query;
378
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
379
		return $spotter_array;
380
	}
381
382
383
384
	/**
385
	* Gets all source name
386
	*
387
	* @param String type format of source
388
	* @return Array list of source name
389
	*
390
	*/
391
	public function getAllSourceName($type = '',$filters = array())
392
	{
393
		$filter_query = $this->getFilter($filters,true,true);
394
		$query_values = array();
395
		$query  = "SELECT DISTINCT marine_output.source_name 
396
				FROM marine_output".$filter_query." marine_output.source_name <> ''";
397
		if ($type != '') {
398
			$query_values = array(':type' => $type);
399
			$query .= " AND format_source = :type";
400
		}
401
		$query .= " ORDER BY marine_output.source_name ASC";
402
403
		$sth = $this->db->prepare($query);
404
		if (!empty($query_values)) $sth->execute($query_values);
405
		else $sth->execute();
406
407
		$source_array = array();
408
		$temp_array = array();
409
		
410
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
411
		{
412
			$temp_array['source_name'] = $row['source_name'];
413
			$source_array[] = $temp_array;
414
		}
415
		return $source_array;
416
	}
417
418
419
	/**
420
	* Gets a list of all idents/callsigns
421
	*
422
	* @return Array list of ident/callsign names
423
	*
424
	*/
425
	public function getAllIdents($filters = array())
426
	{
427
		$filter_query = $this->getFilter($filters,true,true);
428
		$query  = "SELECT DISTINCT marine_output.ident
429
								FROM marine_output".$filter_query." marine_output.ident <> '' 
430
								ORDER BY marine_output.date ASC LIMIT 700 OFFSET 0";
431
432
		$sth = $this->db->prepare($query);
433
		$sth->execute();
434
    
435
		$ident_array = array();
436
		$temp_array = array();
437
		
438
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
439
		{
440
			$temp_array['ident'] = $row['ident'];
441
			$ident_array[] = $temp_array;
442
		}
443
444
		return $ident_array;
445
	}
446
447
	/**
448
	* Gets all info from a mmsi
449
	*
450
	* @return Array list of mmsi info
451
	*
452
	*/
453
	public function getIdentity($mmsi)
454
	{
455
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
456
		$query  = "SELECT * FROM marine_identity WHERE mmsi = :mmsi LIMIT 1";
457
		$sth = $this->db->prepare($query);
458
		$sth->execute(array(':mmsi' => $mmsi));
459
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
460
		if (isset($result[0])) return $result[0];
461
		else return array();
462
	}
463
464
	/*
465
	* Gets a list of all dates
466
	*
467
	* @return Array list of date names
468
	*
469
	*/
470
	public function getAllDates()
471
	{
472
		global $globalTimezone, $globalDBdriver;
473
		if ($globalTimezone != '') {
474
			date_default_timezone_set($globalTimezone);
475
			$datetime = new DateTime();
476
			$offset = $datetime->format('P');
477
		} else $offset = '+00:00';
478
479
		if ($globalDBdriver == 'mysql') {
480
			$query  = "SELECT DISTINCT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) as date
481
								FROM marine_output
482
								WHERE marine_output.date <> '' 
483
								ORDER BY marine_output.date ASC LIMIT 0,100";
484
		} else {
485
			$query  = "SELECT DISTINCT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') as date
486
								FROM marine_output
487
								WHERE marine_output.date <> '' 
488
								ORDER BY marine_output.date ASC LIMIT 0,100";
489
		}
490
		
491
		$sth = $this->db->prepare($query);
492
		$sth->execute(array(':offset' => $offset));
493
    
494
		$date_array = array();
495
		$temp_array = array();
496
		
497
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
498
		{
499
			$temp_array['date'] = $row['date'];
500
501
			$date_array[] = $temp_array;
502
		}
503
504
		return $date_array;
505
	}
506
	
507
	
508
	/**
509
	* Update ident tracker data
510
	*
511
	* @param String $fammarine_id the ID
512
	* @param String $ident the marine ident
513
	* @return String success or false
514
	*
515
	*/	
516
	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...
517
	{
518
519
		$query = 'UPDATE marine_output SET ident = :ident WHERE fammarine_id = :fammarine_id';
520
                $query_values = array(':fammarine_id' => $fammarine_id,':ident' => $ident);
521
522
		try {
523
			$sth = $this->db->prepare($query);
524
			$sth->execute($query_values);
525
		} catch (PDOException $e) {
526
			return "error : ".$e->getMessage();
527
		}
528
		
529
		return "success";
530
531
	}
532
533
	/**
534
	* Update Status data
535
	*
536
	* @param String $fammarine_id the ID
537
	* @param String $status_id the marine status id
538
	* @param String $status the marine status
539
	* @return String success or false
540
	*
541
	*/	
542
	public function updateStatusMarineData($fammarine_id = '', $status_id = '',$status = '')
543
	{
544
545
		$query = 'UPDATE marine_output SET status = :status, status_id = :status_id WHERE fammarine_id = :fammarine_id';
546
                $query_values = array(':fammarine_id' => $fammarine_id,':status' => $status,':status_id' => $status_id);
547
548
		try {
549
			$sth = $this->db->prepare($query);
550
			$sth->execute($query_values);
551
		} catch (PDOException $e) {
552
			return "error : ".$e->getMessage();
553
		}
554
		
555
		return "success";
556
557
	}
558
	/**
559
	* Update latest marine data
560
	*
561
	* @param String $fammarine_id the ID
562
	* @param String $ident the marine ident
563
	* @return String success or false
564
	*
565
	*/	
566
	public function updateLatestMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $groundspeed = NULL, $date = '')
567
	{
568
		$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';
569
                $query_values = array(':fammarine_id' => $fammarine_id,':last_latitude' => $latitude,':last_longitude' => $longitude, ':last_ground_speed' => $groundspeed,':last_seen' => $date,':ident' => $ident);
570
571
		try {
572
			$sth = $this->db->prepare($query);
573
			$sth->execute($query_values);
574
		} catch (PDOException $e) {
575
			return "error : ".$e->getMessage();
576
		}
577
		
578
		return "success";
579
580
	}
581
582
	/**
583
	* Adds a new spotter data
584
	*
585
	* @param String $fammarine_id the ID
586
	* @param String $ident the marine ident
587
	* @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...
588
	* @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...
589
	* @param String $latitude latitude of flight
590
	* @param String $longitude latitude of flight
591
	* @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...
592
	* @param String $heading heading of flight
593
	* @param String $groundspeed speed of flight
594
	* @param String $date date of flight
595
	* @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...
596
	* @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...
597
	* @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...
598
	* @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...
599
	* @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...
600
	* @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...
601
	* @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...
602
	* @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...
603
	* @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...
604
	* @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...
605
	* @return String success or false
606
	*/
607
	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...
608
	{
609
		global $globalURL, $globalMarineImageFetch;
610
		
611
		//$Image = new Image($this->db);
612
		$Common = new Common();
613
		
614
		date_default_timezone_set('UTC');
615
		
616
		//getting the registration
617
		if ($fammarine_id != "")
618
		{
619
			if (!is_string($fammarine_id))
620
			{
621
				return false;
622
			}
623
		}
624
		$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...
625
		//getting the airline information
626
		if ($ident != "")
627
		{
628
			if (!is_string($ident))
629
			{
630
				return false;
631
			}
632
		}
633
634
		if ($latitude != "")
635
		{
636
			if (!is_numeric($latitude))
637
			{
638
				return false;
639
			}
640
		}
641
		
642
		if ($longitude != "")
643
		{
644
			if (!is_numeric($longitude))
645
			{
646
				return false;
647
			}
648
		}
649
		
650
		if ($heading != "")
651
		{
652
			if (!is_numeric($heading))
653
			{
654
				return false;
655
			}
656
		}
657
		if ($mmsi != "")
658
		{
659
			if (!is_numeric($mmsi))
660
			{
661
				return false;
662
			}
663
		}
664
		
665
		if ($groundspeed != "")
666
		{
667
			if (!is_numeric($groundspeed))
668
			{
669
				return false;
670
			}
671
		}
672
673
    
674
		if ($date == "" || strtotime($date) < time()-20*60)
675
		{
676
			$date = date("Y-m-d H:i:s", time());
677
		}
678
679
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
680
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
681
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
682
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
683
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
684
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
685
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
686
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
687
		$type = filter_var($type,FILTER_SANITIZE_STRING);
688
		$status = filter_var($status,FILTER_SANITIZE_STRING);
689
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
690
		$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...
691
		$arrival_code = filter_var($arrival_code,FILTER_SANITIZE_STRING);
692
		$arrival_date = filter_var($arrival_date,FILTER_SANITIZE_STRING);
693
	
694
		if (isset($globalMarineImageFetch) && $globalMarineImageFetch === TRUE) {
695
			$Image = new Image($this->db);
696
			$image_array = $Image->getMarineImage($mmsi,$imo,$ident);
697
			if (!isset($image_array[0]['mmsi'])) {
698
				$Image->addMarineImage($mmsi,$imo,$ident);
699
			}
700
			unset($Image);
701
		}
702
		
703
                if ($latitude == '' && $longitude == '') {
704
            		$latitude = 0;
705
            		$longitude = 0;
706
            	}
707
                if ($heading == '' || $Common->isInteger($heading) === false) $heading = 0;
708
                if ($groundspeed == '' || $Common->isInteger($groundspeed) === false) $groundspeed = 0;
709
                if ($arrival_date == '') $arrival_date = NULL;
710
		$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) 
711
		    VALUES (:fammarine_id,:ident,:latitude,:longitude,:heading,:speed,:date,:format_source, :source_name,:mmsi,:type,:status,:imo,:arrival_port_name,:arrival_port_date)";
712
713
		$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);
714
		try {
715
		        
716
			$sth = $this->db->prepare($query);
717
			$sth->execute($query_values);
718
			$this->db = null;
719
		} catch (PDOException $e) {
720
		    return "error : ".$e->getMessage();
721
		}
722
		
723
		return "success";
724
725
	}
726
	
727
  
728
	/**
729
	* Gets the aircraft ident within the last hour
730
	*
731
	* @return String the ident
732
	*
733
	*/
734
	public function getIdentFromLastHour($ident)
735
	{
736
		global $globalDBdriver, $globalTimezone;
737
		if ($globalDBdriver == 'mysql') {
738
			$query  = "SELECT marine_output.ident FROM marine_output 
739
								WHERE marine_output.ident = :ident 
740
								AND marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
741
								AND marine_output.date < UTC_TIMESTAMP()";
742
			$query_data = array(':ident' => $ident);
743
		} else {
744
			$query  = "SELECT marine_output.ident FROM marine_output 
745
								WHERE marine_output.ident = :ident 
746
								AND marine_output.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
747
								AND marine_output.date < now() AT TIME ZONE 'UTC'";
748
			$query_data = array(':ident' => $ident);
749
    		}
750
		
751
		$sth = $this->db->prepare($query);
752
		$sth->execute($query_data);
753
    		$ident_result='';
754
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
755
		{
756
			$ident_result = $row['ident'];
757
		}
758
759
		return $ident_result;
760
	}
761
	
762
	
763
	/**
764
	* Gets the aircraft data from the last 20 seconds
765
	*
766
	* @return Array the spotter data
767
	*
768
	*/
769
	public function getRealTimeData($q = '')
770
	{
771
		global $globalDBdriver;
772
		$additional_query = '';
773
		if ($q != "")
774
		{
775
			if (!is_string($q))
776
			{
777
				return false;
778
			} else {
779
				$q_array = explode(" ", $q);
780
				foreach ($q_array as $q_item){
781
					$q_item = filter_var($q_item,FILTER_SANITIZE_STRING);
782
					$additional_query .= " AND (";
783
					$additional_query .= "(marine_output.ident like '%".$q_item."%')";
784
					$additional_query .= ")";
785
				}
786
			}
787
		}
788
		if ($globalDBdriver == 'mysql') {
789
			$query  = "SELECT marine_output.* FROM marine_output 
790
				WHERE marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 20 SECOND) ".$additional_query." 
791
				AND marine_output.date < UTC_TIMESTAMP()";
792
		} else {
793
			$query  = "SELECT marine_output.* FROM marine_output 
794
				WHERE marine_output.date::timestamp >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '20 SECONDS' ".$additional_query." 
795
				AND marine_output.date::timestamp < CURRENT_TIMESTAMP AT TIME ZONE 'UTC'";
796
		}
797
		$spotter_array = $this->getDataFromDB($query, array());
798
799
		return $spotter_array;
800
	}
801
	
802
	
803
	
804
805
	/**
806
	* Gets all number of flight over countries
807
	*
808
	* @return Array the airline country list
809
	*
810
	*/
811
812
	public function countAllMarineOverCountries($limit = true,$olderthanmonths = 0,$sincedate = '',$filters = array())
813
	{
814
		global $globalDBdriver, $globalArchive;
815
		//$filter_query = $this->getFilter($filters,true,true);
816
		$Connection= new Connection($this->db);
817
		if (!$Connection->tableExists('countries')) return array();
818
		require_once('class.SpotterLive.php');
819
		if (!isset($globalArchive) || $globalArchive !== TRUE) {
820
			$MarineLive = new MarineLive($this->db);
821
			$filter_query = $MarineLive->getFilter($filters,true,true);
822
			$filter_query .= " over_country IS NOT NULL AND over_country <> ''";
823
			if ($olderthanmonths > 0) {
824
				if ($globalDBdriver == 'mysql') {
825
					$filter_query .= ' AND marine_live.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH) ';
826
				} else {
827
					$filter_query .= " AND marine_live.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
828
				}
829
			}
830
			if ($sincedate != '') {
831
				if ($globalDBdriver == 'mysql') {
832
					$filter_query .= " AND marine_live.date > '".$sincedate."' ";
833
				} else {
834
					$filter_query .= " AND marine_live.date > CAST('".$sincedate."' AS TIMESTAMP)";
835
				}
836
			}
837
			$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 ";
838
		} else {
839
			require_once(dirname(__FILE__)."/class.MarineArchive.php");
840
			$MarineArchive = new MarineArchive($this->db);
841
			$filter_query = $MarineArchive->getFilter($filters,true,true);
842
			$filter_query .= " over_country <> ''";
843
			if ($olderthanmonths > 0) {
844
				if ($globalDBdriver == 'mysql') {
845
					$filter_query .= ' AND marine_archive.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH) ';
846
				} else {
847
					$filter_query .= " AND marine_archive.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
848
				}
849
			}
850
			if ($sincedate != '') {
851
				if ($globalDBdriver == 'mysql') {
852
					$filter_query .= " AND marine_archive.date > '".$sincedate."' ";
853
				} else {
854
					$filter_query .= " AND marine_archive.date > CAST('".$sincedate."' AS TIMESTAMP)";
855
				}
856
			}
857
			$filter_query .= " LIMIT 100 OFFSET 0";
858
			$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 ";
859
		}
860
		$query .= "GROUP BY c.name,c.iso3,c.iso2 ORDER BY nb DESC";
861
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
862
863
		$sth = $this->db->prepare($query);
864
		$sth->execute();
865
 
866
		$flight_array = array();
867
		$temp_array = array();
868
        
869
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
870
		{
871
			$temp_array['marine_count'] = $row['nb'];
872
			$temp_array['marine_country'] = $row['name'];
873
			$temp_array['marine_country_iso3'] = $row['iso3'];
874
			$temp_array['marine_country_iso2'] = $row['iso2'];
875
			$flight_array[] = $temp_array;
876
		}
877
		return $flight_array;
878
	}
879
	
880
	
881
	
882
	/**
883
	* Gets all callsigns that have flown over
884
	*
885
	* @return Array the callsign list
886
	*
887
	*/
888
	public function countAllCallsigns($limit = true, $olderthanmonths = 0, $sincedate = '',$filters = array(),$year = '', $month = '', $day = '')
889
	{
890
		global $globalDBdriver;
891
		$filter_query = $this->getFilter($filters,true,true);
892
		$query  = "SELECT DISTINCT marine_output.ident, COUNT(marine_output.ident) AS callsign_icao_count 
893
                    FROM marine_output".$filter_query." marine_output.ident <> ''";
894
		 if ($olderthanmonths > 0) {
895
			if ($globalDBdriver == 'mysql') $query .= ' AND date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH)';
896
			else $query .= " AND marine_output.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
897
		}
898
		if ($sincedate != '') {
899
			if ($globalDBdriver == 'mysql') $query .= " AND marine_output.date > '".$sincedate."'";
900
			else $query .= " AND marine_output.date > CAST('".$sincedate."' AS TIMESTAMP)";
901
		}
902
		$query_values = array();
903
		if ($year != '') {
904
			if ($globalDBdriver == 'mysql') {
905
				$query .= " AND YEAR(marine_output.date) = :year";
906
				$query_values = array_merge($query_values,array(':year' => $year));
907
			} else {
908
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
909
				$query_values = array_merge($query_values,array(':year' => $year));
910
			}
911
		}
912
		if ($month != '') {
913
			if ($globalDBdriver == 'mysql') {
914
				$query .= " AND MONTH(marine_output.date) = :month";
915
				$query_values = array_merge($query_values,array(':month' => $month));
916
			} else {
917
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
918
				$query_values = array_merge($query_values,array(':month' => $month));
919
			}
920
		}
921
		if ($day != '') {
922
			if ($globalDBdriver == 'mysql') {
923
				$query .= " AND DAY(marine_output.date) = :day";
924
				$query_values = array_merge($query_values,array(':day' => $day));
925
			} else {
926
				$query .= " AND EXTRACT(DAY FROM marine_output.date) = :day";
927
				$query_values = array_merge($query_values,array(':day' => $day));
928
			}
929
		}
930
		$query .= " GROUP BY marine_output.ident ORDER BY callsign_icao_count DESC";
931
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
932
      		
933
		$sth = $this->db->prepare($query);
934
		$sth->execute($query_values);
935
      
936
		$callsign_array = array();
937
		$temp_array = array();
938
        
939
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
940
		{
941
			$temp_array['callsign_icao'] = $row['ident'];
942
			$temp_array['airline_name'] = $row['airline_name'];
943
			$temp_array['airline_icao'] = $row['airline_icao'];
944
			$temp_array['callsign_icao_count'] = $row['callsign_icao_count'];
945
          
946
			$callsign_array[] = $temp_array;
947
		}
948
949
		return $callsign_array;
950
	}
951
952
953
	/**
954
	* Counts all dates
955
	*
956
	* @return Array the date list
957
	*
958
	*/
959
	public function countAllDates($filters = array())
960
	{
961
		global $globalTimezone, $globalDBdriver;
962
		if ($globalTimezone != '') {
963
			date_default_timezone_set($globalTimezone);
964
			$datetime = new DateTime();
965
			$offset = $datetime->format('P');
966
		} else $offset = '+00:00';
967
968
		if ($globalDBdriver == 'mysql') {
969
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
970
								FROM marine_output";
971
			$query .= $this->getFilter($filters);
972
			$query .= " GROUP BY date_name 
973
								ORDER BY date_count DESC
974
								LIMIT 10 OFFSET 0";
975
		} else {
976
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
977
								FROM marine_output";
978
			$query .= $this->getFilter($filters);
979
			$query .= " GROUP BY date_name 
980
								ORDER BY date_count DESC
981
								LIMIT 10 OFFSET 0";
982
		}
983
      
984
		
985
		$sth = $this->db->prepare($query);
986
		$sth->execute(array(':offset' => $offset));
987
      
988
		$date_array = array();
989
		$temp_array = array();
990
        
991
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
992
		{
993
			$temp_array['date_name'] = $row['date_name'];
994
			$temp_array['date_count'] = $row['date_count'];
995
996
			$date_array[] = $temp_array;
997
		}
998
999
		return $date_array;
1000
	}
1001
	
1002
	
1003
	/**
1004
	* Counts all dates during the last 7 days
1005
	*
1006
	* @return Array the date list
1007
	*
1008
	*/
1009
	public function countAllDatesLast7Days($filters = array())
1010
	{
1011
		global $globalTimezone, $globalDBdriver;
1012
		if ($globalTimezone != '') {
1013
			date_default_timezone_set($globalTimezone);
1014
			$datetime = new DateTime();
1015
			$offset = $datetime->format('P');
1016
		} else $offset = '+00:00';
1017
		$filter_query = $this->getFilter($filters,true,true);
1018
		if ($globalDBdriver == 'mysql') {
1019
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1020
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 7 DAY)";
1021
			$query .= " GROUP BY date_name 
1022
								ORDER BY marine_output.date ASC";
1023
			$query_data = array(':offset' => $offset);
1024
		} else {
1025
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1026
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '7 DAYS'";
1027
			$query .= " GROUP BY date_name 
1028
								ORDER BY date_name ASC";
1029
			$query_data = array(':offset' => $offset);
1030
    		}
1031
		
1032
		$sth = $this->db->prepare($query);
1033
		$sth->execute($query_data);
1034
      
1035
		$date_array = array();
1036
		$temp_array = array();
1037
        
1038
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1039
		{
1040
			$temp_array['date_name'] = $row['date_name'];
1041
			$temp_array['date_count'] = $row['date_count'];
1042
          
1043
			$date_array[] = $temp_array;
1044
		}
1045
1046
		return $date_array;
1047
	}
1048
1049
	/**
1050
	* Counts all dates during the last month
1051
	*
1052
	* @return Array the date list
1053
	*
1054
	*/
1055
	public function countAllDatesLastMonth($filters = array())
1056
	{
1057
		global $globalTimezone, $globalDBdriver;
1058
		if ($globalTimezone != '') {
1059
			date_default_timezone_set($globalTimezone);
1060
			$datetime = new DateTime();
1061
			$offset = $datetime->format('P');
1062
		} else $offset = '+00:00';
1063
		$filter_query = $this->getFilter($filters,true,true);
1064
		if ($globalDBdriver == 'mysql') {
1065
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1066
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MONTH)";
1067
			$query .= " GROUP BY date_name 
1068
								ORDER BY marine_output.date ASC";
1069
			$query_data = array(':offset' => $offset);
1070
		} else {
1071
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1072
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 MONTHS'";
1073
			$query .= " GROUP BY date_name 
1074
								ORDER BY date_name ASC";
1075
			$query_data = array(':offset' => $offset);
1076
    		}
1077
		
1078
		$sth = $this->db->prepare($query);
1079
		$sth->execute($query_data);
1080
      
1081
		$date_array = array();
1082
		$temp_array = array();
1083
        
1084
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1085
		{
1086
			$temp_array['date_name'] = $row['date_name'];
1087
			$temp_array['date_count'] = $row['date_count'];
1088
          
1089
			$date_array[] = $temp_array;
1090
		}
1091
1092
		return $date_array;
1093
	}
1094
1095
1096
1097
	/**
1098
	* Counts all month
1099
	*
1100
	* @return Array the month list
1101
	*
1102
	*/
1103
	public function countAllMonths($filters = array())
1104
	{
1105
		global $globalTimezone, $globalDBdriver;
1106
		if ($globalTimezone != '') {
1107
			date_default_timezone_set($globalTimezone);
1108
			$datetime = new DateTime();
1109
			$offset = $datetime->format('P');
1110
		} else $offset = '+00:00';
1111
1112
		if ($globalDBdriver == 'mysql') {
1113
			$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
1114
								FROM marine_output";
1115
			$query .= $this->getFilter($filters);
1116
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1117
		} else {
1118
			$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
1119
								FROM marine_output";
1120
			$query .= $this->getFilter($filters);
1121
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1122
		}
1123
      
1124
		
1125
		$sth = $this->db->prepare($query);
1126
		$sth->execute(array(':offset' => $offset));
1127
      
1128
		$date_array = array();
1129
		$temp_array = array();
1130
        
1131
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1132
		{
1133
			$temp_array['month_name'] = $row['month_name'];
1134
			$temp_array['year_name'] = $row['year_name'];
1135
			$temp_array['date_count'] = $row['date_count'];
1136
1137
			$date_array[] = $temp_array;
1138
		}
1139
1140
		return $date_array;
1141
	}
1142
1143
	
1144
	
1145
1146
	/**
1147
	* Counts all dates during the last year
1148
	*
1149
	* @return Array the date list
1150
	*
1151
	*/
1152
	public function countAllMonthsLastYear($filters)
1153
	{
1154
		global $globalTimezone, $globalDBdriver;
1155
		if ($globalTimezone != '') {
1156
			date_default_timezone_set($globalTimezone);
1157
			$datetime = new DateTime();
1158
			$offset = $datetime->format('P');
1159
		} else $offset = '+00:00';
1160
		$filter_query = $this->getFilter($filters,true,true);
1161
		if ($globalDBdriver == 'mysql') {
1162
			$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
1163
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 YEAR)";
1164
			$query .= " GROUP BY year_name, month_name
1165
								ORDER BY year_name, month_name ASC";
1166
			$query_data = array(':offset' => $offset);
1167
		} else {
1168
			$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
1169
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 YEARS'";
1170
			$query .= " GROUP BY year_name, month_name
1171
								ORDER BY year_name, month_name ASC";
1172
			$query_data = array(':offset' => $offset);
1173
    		}
1174
		
1175
		$sth = $this->db->prepare($query);
1176
		$sth->execute($query_data);
1177
      
1178
		$date_array = array();
1179
		$temp_array = array();
1180
        
1181
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1182
		{
1183
			$temp_array['year_name'] = $row['year_name'];
1184
			$temp_array['month_name'] = $row['month_name'];
1185
			$temp_array['date_count'] = $row['date_count'];
1186
          
1187
			$date_array[] = $temp_array;
1188
		}
1189
1190
		return $date_array;
1191
	}
1192
	
1193
	
1194
	
1195
	/**
1196
	* Counts all hours
1197
	*
1198
	* @return Array the hour list
1199
	*
1200
	*/
1201
	public function countAllHours($orderby,$filters = array())
1202
	{
1203
		global $globalTimezone, $globalDBdriver;
1204
		if ($globalTimezone != '') {
1205
			date_default_timezone_set($globalTimezone);
1206
			$datetime = new DateTime();
1207
			$offset = $datetime->format('P');
1208
		} else $offset = '+00:00';
1209
1210
		$orderby_sql = '';
1211
		if ($orderby == "hour")
1212
		{
1213
			$orderby_sql = "ORDER BY hour_name ASC";
1214
		}
1215
		if ($orderby == "count")
1216
		{
1217
			$orderby_sql = "ORDER BY hour_count DESC";
1218
		}
1219
		
1220
		if ($globalDBdriver == 'mysql') {
1221
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1222
								FROM marine_output";
1223
			$query .= $this->getFilter($filters);
1224
			$query .= " GROUP BY hour_name 
1225
								".$orderby_sql;
1226
1227
/*		$query  = "SELECT HOUR(marine_output.date) AS hour_name, count(*) as hour_count
1228
								FROM marine_output 
1229
								GROUP BY hour_name 
1230
								".$orderby_sql."
1231
								LIMIT 10 OFFSET 00";
1232
  */    
1233
		$query_data = array(':offset' => $offset);
1234
		} else {
1235
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1236
								FROM marine_output";
1237
			$query .= $this->getFilter($filters);
1238
			$query .= " GROUP BY hour_name 
1239
								".$orderby_sql;
1240
			$query_data = array(':offset' => $offset);
1241
		}
1242
		
1243
		$sth = $this->db->prepare($query);
1244
		$sth->execute($query_data);
1245
      
1246
		$hour_array = array();
1247
		$temp_array = array();
1248
        
1249
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1250
		{
1251
			$temp_array['hour_name'] = $row['hour_name'];
1252
			$temp_array['hour_count'] = $row['hour_count'];
1253
          
1254
			$hour_array[] = $temp_array;
1255
		}
1256
1257
		return $hour_array;
1258
	}
1259
	
1260
	
1261
	
1262
	/**
1263
	* Counts all hours by date
1264
	*
1265
	* @return Array the hour list
1266
	*
1267
	*/
1268
	public function countAllHoursByDate($date, $filters = array())
1269
	{
1270
		global $globalTimezone, $globalDBdriver;
1271
		$filter_query = $this->getFilter($filters,true,true);
1272
		$date = filter_var($date,FILTER_SANITIZE_STRING);
1273
		if ($globalTimezone != '') {
1274
			date_default_timezone_set($globalTimezone);
1275
			$datetime = new DateTime($date);
1276
			$offset = $datetime->format('P');
1277
		} else $offset = '+00:00';
1278
1279
		if ($globalDBdriver == 'mysql') {
1280
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1281
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date
1282
								GROUP BY hour_name 
1283
								ORDER BY hour_name ASC";
1284
		} else {
1285
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1286
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset, 'YYYY-mm-dd') = :date
1287
								GROUP BY hour_name 
1288
								ORDER BY hour_name ASC";
1289
		}
1290
		
1291
		$sth = $this->db->prepare($query);
1292
		$sth->execute(array(':date' => $date, ':offset' => $offset));
1293
      
1294
		$hour_array = array();
1295
		$temp_array = array();
1296
        
1297
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1298
		{
1299
			$temp_array['hour_name'] = $row['hour_name'];
1300
			$temp_array['hour_count'] = $row['hour_count'];
1301
          
1302
			$hour_array[] = $temp_array;
1303
		}
1304
1305
		return $hour_array;
1306
	}
1307
	
1308
	
1309
	
1310
	/**
1311
	* Counts all hours by a ident/callsign
1312
	*
1313
	* @return Array the hour list
1314
	*
1315
	*/
1316
	public function countAllHoursByIdent($ident, $filters = array())
1317
	{
1318
		global $globalTimezone, $globalDBdriver;
1319
		$filter_query = $this->getFilter($filters,true,true);
1320
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1321
		if ($globalTimezone != '') {
1322
			date_default_timezone_set($globalTimezone);
1323
			$datetime = new DateTime();
1324
			$offset = $datetime->format('P');
1325
		} else $offset = '+00:00';
1326
1327
		if ($globalDBdriver == 'mysql') {
1328
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1329
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1330
								GROUP BY hour_name 
1331
								ORDER BY hour_name ASC";
1332
		} else {
1333
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1334
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1335
								GROUP BY hour_name 
1336
								ORDER BY hour_name ASC";
1337
		}
1338
      
1339
		
1340
		$sth = $this->db->prepare($query);
1341
		$sth->execute(array(':ident' => $ident,':offset' => $offset));
1342
      
1343
		$hour_array = array();
1344
		$temp_array = array();
1345
        
1346
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1347
		{
1348
			$temp_array['hour_name'] = $row['hour_name'];
1349
			$temp_array['hour_count'] = $row['hour_count'];
1350
          
1351
			$hour_array[] = $temp_array;
1352
		}
1353
1354
		return $hour_array;
1355
	}
1356
	
1357
	
1358
	
1359
	/**
1360
	* Counts all vessels
1361
	*
1362
	* @return Integer the number of vessels
1363
	*
1364
	*/
1365
	public function countOverallMarine($filters = array(),$year = '',$month = '')
1366
	{
1367
		global $globalDBdriver;
1368
		//$queryi  = "SELECT COUNT(marine_output.marine_id) AS flight_count FROM marine_output";
1369
		$queryi  = "SELECT COUNT(DISTINCT marine_output.mmsi) AS flight_count FROM marine_output";
1370
		$query_values = array();
1371
		$query = '';
1372
		if ($year != '') {
1373
			if ($globalDBdriver == 'mysql') {
1374
				$query .= " AND YEAR(marine_output.date) = :year";
1375
				$query_values = array_merge($query_values,array(':year' => $year));
1376
			} else {
1377
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1378
				$query_values = array_merge($query_values,array(':year' => $year));
1379
			}
1380
		}
1381
		if ($month != '') {
1382
			if ($globalDBdriver == 'mysql') {
1383
				$query .= " AND MONTH(marine_output.date) = :month";
1384
				$query_values = array_merge($query_values,array(':month' => $month));
1385
			} else {
1386
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1387
				$query_values = array_merge($query_values,array(':month' => $month));
1388
			}
1389
		}
1390
		if (empty($query_values)) $queryi .= $this->getFilter($filters);
1391
		else $queryi .= $this->getFilter($filters,true,true).substr($query,4);
1392
		
1393
		$sth = $this->db->prepare($queryi);
1394
		$sth->execute($query_values);
1395
		return $sth->fetchColumn();
1396
	}
1397
	
1398
	/**
1399
	* Counts all vessel type
1400
	*
1401
	* @return Integer the number of vessels
1402
	*
1403
	*/
1404
	public function countOverallMarineTypes($filters = array(),$year = '',$month = '')
1405
	{
1406
		global $globalDBdriver;
1407
		$queryi  = "SELECT COUNT(DISTINCT marine_output.type) AS marine_count FROM marine_output";
1408
		$query_values = array();
1409
		$query = '';
1410
		if ($year != '') {
1411
			if ($globalDBdriver == 'mysql') {
1412
				$query .= " AND YEAR(marine_output.date) = :year";
1413
				$query_values = array_merge($query_values,array(':year' => $year));
1414
			} else {
1415
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1416
				$query_values = array_merge($query_values,array(':year' => $year));
1417
			}
1418
		}
1419
		if ($month != '') {
1420
			if ($globalDBdriver == 'mysql') {
1421
				$query .= " AND MONTH(marine_output.date) = :month";
1422
				$query_values = array_merge($query_values,array(':month' => $month));
1423
			} else {
1424
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1425
				$query_values = array_merge($query_values,array(':month' => $month));
1426
			}
1427
		}
1428
		if (empty($query_values)) $queryi .= $this->getFilter($filters);
1429
		else $queryi .= $this->getFilter($filters,true,true).substr($query,4);
1430
		
1431
		$sth = $this->db->prepare($queryi);
1432
		$sth->execute($query_values);
1433
		return $sth->fetchColumn();
1434
	}
1435
	
1436
  
1437
	/**
1438
	* Counts all hours of today
1439
	*
1440
	* @return Array the hour list
1441
	*
1442
	*/
1443
	public function countAllHoursFromToday($filters = array())
1444
	{
1445
		global $globalTimezone, $globalDBdriver;
1446
		$filter_query = $this->getFilter($filters,true,true);
1447
		if ($globalTimezone != '') {
1448
			date_default_timezone_set($globalTimezone);
1449
			$datetime = new DateTime();
1450
			$offset = $datetime->format('P');
1451
		} else $offset = '+00:00';
1452
1453
		if ($globalDBdriver == 'mysql') {
1454
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1455
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = CURDATE()
1456
								GROUP BY hour_name 
1457
								ORDER BY hour_name ASC";
1458
		} else {
1459
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1460
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') = CAST(NOW() AS date)
1461
								GROUP BY hour_name 
1462
								ORDER BY hour_name ASC";
1463
		}
1464
		
1465
		$sth = $this->db->prepare($query);
1466
		$sth->execute(array(':offset' => $offset));
1467
      
1468
		$hour_array = array();
1469
		$temp_array = array();
1470
        
1471
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1472
		{
1473
			$temp_array['hour_name'] = $row['hour_name'];
1474
			$temp_array['hour_count'] = $row['hour_count'];
1475
			$hour_array[] = $temp_array;
1476
		}
1477
1478
		return $hour_array;
1479
	}
1480
    
1481
    
1482
     /**
1483
	* Gets the Barrie Spotter ID based on the FlightAware ID
1484
	*
1485
	* @return Integer the Barrie Spotter ID
1486
q	*
1487
	*/
1488
	public function getMarineIDBasedOnFamMarineID($fammarine_id)
1489
	{
1490
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
1491
1492
		$query  = "SELECT marine_output.marine_id
1493
				FROM marine_output 
1494
				WHERE marine_output.fammarine_id = '".$fammarine_id."'";
1495
        
1496
		
1497
		$sth = $this->db->prepare($query);
1498
		$sth->execute();
1499
1500
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1501
		{
1502
			return $row['marine_id'];
1503
		}
1504
	}
1505
  
1506
 
1507
	/**
1508
	* Parses a date string
1509
	*
1510
	* @param String $dateString the date string
1511
	* @param String $timezone the timezone of a user
1512
	* @return Array the time information
1513
	*
1514
	*/
1515
	public function parseDateString($dateString, $timezone = '')
1516
	{
1517
		$time_array = array();
1518
	
1519
		if ($timezone != "")
1520
		{
1521
			date_default_timezone_set($timezone);
1522
		}
1523
		
1524
		$current_date = date("Y-m-d H:i:s");
1525
		$date = date("Y-m-d H:i:s",strtotime($dateString." UTC"));
1526
		
1527
		$diff = abs(strtotime($current_date) - strtotime($date));
1528
1529
		$time_array['years'] = floor($diff / (365*60*60*24)); 
1530
		$years = $time_array['years'];
1531
		
1532
		$time_array['months'] = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
1533
		$months = $time_array['months'];
1534
		
1535
		$time_array['days'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
1536
		$days = $time_array['days'];
1537
		$time_array['hours'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
1538
		$hours = $time_array['hours'];
1539
		$time_array['minutes'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
1540
		$minutes = $time_array['minutes'];
1541
		$time_array['seconds'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60));  
1542
		
1543
		return $time_array;
1544
	}
1545
	
1546
	/**
1547
	* Parses the direction degrees to working
1548
	*
1549
	* @param Float $direction the direction in degrees
1550
	* @return Array the direction information
1551
	*
1552
	*/
1553
	public function parseDirection($direction = 0)
1554
	{
1555
		if ($direction == '') $direction = 0;
1556
		$direction_array = array();
1557
		$temp_array = array();
1558
1559
		if ($direction == 360 || ($direction >= 0 && $direction < 22.5))
1560
		{
1561
			$temp_array['direction_degree'] = $direction;
1562
			$temp_array['direction_shortname'] = "N";
1563
			$temp_array['direction_fullname'] = "North";
1564
		} elseif ($direction >= 22.5 && $direction < 45){
1565
			$temp_array['direction_degree'] = $direction;
1566
			$temp_array['direction_shortname'] = "NNE";
1567
			$temp_array['direction_fullname'] = "North-Northeast";
1568
		} elseif ($direction >= 45 && $direction < 67.5){
1569
			$temp_array['direction_degree'] = $direction;
1570
			$temp_array['direction_shortname'] = "NE";
1571
			$temp_array['direction_fullname'] = "Northeast";
1572
		} elseif ($direction >= 67.5 && $direction < 90){
1573
			$temp_array['direction_degree'] = $direction;
1574
			$temp_array['direction_shortname'] = "ENE";
1575
			$temp_array['direction_fullname'] = "East-Northeast";
1576
		} elseif ($direction >= 90 && $direction < 112.5){
1577
			$temp_array['direction_degree'] = $direction;
1578
			$temp_array['direction_shortname'] = "E";
1579
			$temp_array['direction_fullname'] = "East";
1580
		} elseif ($direction >= 112.5 && $direction < 135){
1581
			$temp_array['direction_degree'] = $direction;
1582
			$temp_array['direction_shortname'] = "ESE";
1583
			$temp_array['direction_fullname'] = "East-Southeast";
1584
		} elseif ($direction >= 135 && $direction < 157.5){
1585
			$temp_array['direction_degree'] = $direction;
1586
			$temp_array['direction_shortname'] = "SE";
1587
			$temp_array['direction_fullname'] = "Southeast";
1588
		} elseif ($direction >= 157.5 && $direction < 180){
1589
			$temp_array['direction_degree'] = $direction;
1590
			$temp_array['direction_shortname'] = "SSE";
1591
			$temp_array['direction_fullname'] = "South-Southeast";
1592
		} elseif ($direction >= 180 && $direction < 202.5){
1593
			$temp_array['direction_degree'] = $direction;
1594
			$temp_array['direction_shortname'] = "S";
1595
			$temp_array['direction_fullname'] = "South";
1596
		} elseif ($direction >= 202.5 && $direction < 225){
1597
			$temp_array['direction_degree'] = $direction;
1598
			$temp_array['direction_shortname'] = "SSW";
1599
			$temp_array['direction_fullname'] = "South-Southwest";
1600
		} elseif ($direction >= 225 && $direction < 247.5){
1601
			$temp_array['direction_degree'] = $direction;
1602
			$temp_array['direction_shortname'] = "SW";
1603
			$temp_array['direction_fullname'] = "Southwest";
1604
		} elseif ($direction >= 247.5 && $direction < 270){
1605
			$temp_array['direction_degree'] = $direction;
1606
			$temp_array['direction_shortname'] = "WSW";
1607
			$temp_array['direction_fullname'] = "West-Southwest";
1608
		} elseif ($direction >= 270 && $direction < 292.5){
1609
			$temp_array['direction_degree'] = $direction;
1610
			$temp_array['direction_shortname'] = "W";
1611
			$temp_array['direction_fullname'] = "West";
1612
		} elseif ($direction >= 292.5 && $direction < 315){
1613
			$temp_array['direction_degree'] = $direction;
1614
			$temp_array['direction_shortname'] = "WNW";
1615
			$temp_array['direction_fullname'] = "West-Northwest";
1616
		} elseif ($direction >= 315 && $direction < 337.5){
1617
			$temp_array['direction_degree'] = $direction;
1618
			$temp_array['direction_shortname'] = "NW";
1619
			$temp_array['direction_fullname'] = "Northwest";
1620
		} elseif ($direction >= 337.5 && $direction < 360){
1621
			$temp_array['direction_degree'] = $direction;
1622
			$temp_array['direction_shortname'] = "NNW";
1623
			$temp_array['direction_fullname'] = "North-Northwest";
1624
		}
1625
		$direction_array[] = $temp_array;
1626
		return $direction_array;
1627
	}
1628
	
1629
	
1630
	/**
1631
	* Gets Country from latitude/longitude
1632
	*
1633
	* @param Float $latitude latitute of the flight
1634
	* @param Float $longitude longitute of the flight
1635
	* @return String the countrie
1636
	*/
1637
	public function getCountryFromLatitudeLongitude($latitude,$longitude)
1638
	{
1639
		global $globalDBdriver, $globalDebug;
1640
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1641
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1642
	
1643
		$Connection = new Connection($this->db);
1644
		if (!$Connection->tableExists('countries')) return '';
1645
	
1646
		try {
1647
			/*
1648
			if ($globalDBdriver == 'mysql') {
1649
				//$query  = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(:latitude :longitude)'), ogc_geom) LIMIT 1";
1650
				$query = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(".$longitude.' '.$latitude.")'), ogc_geom) LIMIT 1";
1651
			}
1652
			*/
1653
			// This query seems to work both for MariaDB and PostgreSQL
1654
			$query = "SELECT name,iso2,iso3 FROM countries WHERE ST_Within(ST_GeomFromText('POINT(".$longitude." ".$latitude.")',4326), ogc_geom) LIMIT 1";
1655
		
1656
			$sth = $this->db->prepare($query);
1657
			//$sth->execute(array(':latitude' => $latitude,':longitude' => $longitude));
1658
			$sth->execute();
1659
    
1660
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1661
			$sth->closeCursor();
1662
			if (count($row) > 0) {
1663
				return $row;
1664
			} else return '';
1665
		} catch (PDOException $e) {
1666
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1667
			return '';
1668
		}
1669
	
1670
	}
1671
1672
	/**
1673
	* Gets Country from iso2
1674
	*
1675
	* @param String $iso2 ISO2 country code
1676
	* @return String the countrie
1677
	*/
1678
	public function getCountryFromISO2($iso2)
1679
	{
1680
		global $globalDBdriver, $globalDebug;
1681
		$iso2 = filter_var($iso2,FILTER_SANITIZE_STRING);
1682
	
1683
		$Connection = new Connection($this->db);
1684
		if (!$Connection->tableExists('countries')) return '';
1685
	
1686
		try {
1687
			$query = "SELECT name,iso2,iso3 FROM countries WHERE iso2 = :iso2 LIMIT 1";
1688
		
1689
			$sth = $this->db->prepare($query);
1690
			$sth->execute(array(':iso2' => $iso2));
1691
    
1692
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1693
			$sth->closeCursor();
1694
			if (count($row) > 0) {
1695
				return $row;
1696
			} else return '';
1697
		} catch (PDOException $e) {
1698
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1699
			return '';
1700
		}
1701
	
1702
	}
1703
1704
	
1705
	/**
1706
	* Gets the short url from bit.ly
1707
	*
1708
	* @param String $url the full url
1709
	* @return String the bit.ly url
1710
	*
1711
	*/
1712
	public function getBitlyURL($url)
1713
	{
1714
		global $globalBitlyAccessToken;
1715
		
1716
		if ($globalBitlyAccessToken == '') return $url;
1717
        
1718
		$google_url = 'https://api-ssl.bitly.com/v3/shorten?access_token='.$globalBitlyAccessToken.'&longUrl='.$url;
1719
		
1720
		$ch = curl_init();
1721
		curl_setopt($ch, CURLOPT_HEADER, 0);
1722
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1723
		curl_setopt($ch, CURLOPT_URL, $google_url);
1724
		$bitly_data = curl_exec($ch);
1725
		curl_close($ch);
1726
		
1727
		$bitly_data = json_decode($bitly_data);
1728
		$bitly_url = '';
1729
		if ($bitly_data->status_txt = "OK"){
1730
			$bitly_url = $bitly_data->data->url;
1731
		}
1732
1733
		return $bitly_url;
1734
	}
1735
1736
	
1737
	/**
1738
	* Gets all vessels types that have flown over
1739
	*
1740
	* @return Array the vessel type list
1741
	*
1742
	*/
1743
	public function countAllMarineTypes($limit = true,$olderthanmonths = 0,$sincedate = '',$filters = array(),$year = '',$month = '',$day = '')
1744
	{
1745
		global $globalDBdriver;
1746
		$filter_query = $this->getFilter($filters,true,true);
1747
		$query  = "SELECT marine_output.type AS marine_type, COUNT(marine_output.type) AS marine_type_count 
1748
		    FROM marine_output ".$filter_query." marine_output.type  <> ''";
1749
		if ($olderthanmonths > 0) {
1750
			if ($globalDBdriver == 'mysql') {
1751
				$query .= ' AND marine_output.date < DATE_SUB(UTC_TIMESTAMP(), INTERVAL '.$olderthanmonths.' MONTH)';
1752
			} else {
1753
				$query .= " AND marine_output.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
1754
			}
1755
		}
1756
		if ($sincedate != '') {
1757
			if ($globalDBdriver == 'mysql') {
1758
				$query .= " AND marine_output.date > '".$sincedate."'";
1759
			} else {
1760
				$query .= " AND marine_output.date > CAST('".$sincedate."' AS TIMESTAMP)";
1761
			}
1762
		}
1763
		$query_values = array();
1764
		if ($year != '') {
1765
			if ($globalDBdriver == 'mysql') {
1766
				$query .= " AND YEAR(marine_output.date) = :year";
1767
				$query_values = array_merge($query_values,array(':year' => $year));
1768
			} else {
1769
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1770
				$query_values = array_merge($query_values,array(':year' => $year));
1771
			}
1772
		}
1773
		if ($month != '') {
1774
			if ($globalDBdriver == 'mysql') {
1775
				$query .= " AND MONTH(marine_output.date) = :month";
1776
				$query_values = array_merge($query_values,array(':month' => $month));
1777
			} else {
1778
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1779
				$query_values = array_merge($query_values,array(':month' => $month));
1780
			}
1781
		}
1782
		if ($day != '') {
1783
			if ($globalDBdriver == 'mysql') {
1784
				$query .= " AND DAY(marine_output.date) = :day";
1785
				$query_values = array_merge($query_values,array(':day' => $day));
1786
			} else {
1787
				$query .= " AND EXTRACT(DAY FROM marine_output.date) = :day";
1788
				$query_values = array_merge($query_values,array(':day' => $day));
1789
			}
1790
		}
1791
		$query .= " GROUP BY marine_output.type ORDER BY marine_type_count DESC";
1792
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
1793
		$sth = $this->db->prepare($query);
1794
		$sth->execute($query_values);
1795
		$marine_array = array();
1796
		$temp_array = array();
1797
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1798
		{
1799
			$temp_array['marine_type'] = $row['marine_type'];
1800
			$temp_array['marine_type_count'] = $row['marine_type_count'];
1801
			$marine_array[] = $temp_array;
1802
		}
1803
		return $marine_array;
1804
	}
1805
1806
	/**
1807
	* Gets all the tracker information
1808
	*
1809
	* @return Array the tracker information
1810
	*
1811
	*/
1812
	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...
1813
	{
1814
		global $globalTimezone, $globalDBdriver;
1815
		date_default_timezone_set('UTC');
1816
		$query_values = array();
1817
		$additional_query = '';
1818
		$filter_query = $this->getFilter($filters,true,true);
1819
		if ($q != "")
1820
		{
1821
			if (!is_string($q))
1822
			{
1823
				return false;
1824
			} else {
1825
				$q_array = explode(" ", $q);
1826
				foreach ($q_array as $q_item){
1827
					$q_item = filter_var($q_item,FILTER_SANITIZE_STRING);
1828
					$additional_query .= " AND (";
1829
					if (is_int($q_item)) $additional_query .= "(marine_output.marine_id = '".$q_item."') OR ";
1830
					if (is_int($q_item)) $additional_query .= "(marine_output.mmsi = '".$q_item."') OR ";
1831
					if (is_int($q_item)) $additional_query .= "(marine_output.imo = '".$q_item."') OR ";
1832
					$additional_query .= "(marine_output.ident like '%".$q_item."%') OR ";
1833
					$additional_query .= ")";
1834
				}
1835
			}
1836
		}
1837
		if ($callsign != "")
1838
		{
1839
			$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
1840
			if (!is_string($callsign))
1841
			{
1842
				return false;
1843
			} else {
1844
				$additional_query .= " AND marine_output.ident = :callsign";
1845
				$query_values = array_merge($query_values,array(':callsign' => $callsign));
1846
			}
1847
		}
1848
		if ($mmsi != "")
1849
		{
1850
			$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
1851
			if (!is_numeric($mmsi))
1852
			{
1853
				return false;
1854
			} else {
1855
				$additional_query .= " AND marine_output.mmsi = :mmsi";
1856
				$query_values = array_merge($query_values,array(':mmsi' => $mmsi));
1857
			}
1858
		}
1859
		if ($imo != "")
1860
		{
1861
			$imo = filter_var($imo,FILTER_SANITIZE_STRING);
1862
			if (!is_numeric($imo))
1863
			{
1864
				return false;
1865
			} else {
1866
				$additional_query .= " AND marine_output.imo = :imo";
1867
				$query_values = array_merge($query_values,array(':imo' => $imo));
1868
			}
1869
		}
1870
		if ($date_posted != "")
1871
		{
1872
			$date_array = explode(",", $date_posted);
1873
			$date_array[0] = filter_var($date_array[0],FILTER_SANITIZE_STRING);
1874
			$date_array[1] = filter_var($date_array[1],FILTER_SANITIZE_STRING);
1875
			if ($globalTimezone != '') {
1876
				date_default_timezone_set($globalTimezone);
1877
				$datetime = new DateTime();
1878
				$offset = $datetime->format('P');
1879
			} else $offset = '+00:00';
1880
			if ($date_array[1] != "")
1881
			{
1882
				$date_array[0] = date("Y-m-d H:i:s", strtotime($date_array[0]));
1883
				$date_array[1] = date("Y-m-d H:i:s", strtotime($date_array[1]));
1884
				if ($globalDBdriver == 'mysql') {
1885
					$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]."' ";
1886
				} else {
1887
					$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]."' ";
1888
				}
1889
			} else {
1890
				$date_array[0] = date("Y-m-d H:i:s", strtotime($date_array[0]));
1891
				if ($globalDBdriver == 'mysql') {
1892
					$additional_query .= " AND TIMESTAMP(CONVERT_TZ(marine_output.date,'+00:00', '".$offset."')) >= '".$date_array[0]."' ";
1893
				} else {
1894
					$additional_query .= " AND CAST(marine_output.date AT TIME ZONE INTERVAL ".$offset." AS TIMESTAMP) >= '".$date_array[0]."' ";
1895
				}
1896
			}
1897
		}
1898
		if ($limit != "")
1899
		{
1900
			$limit_array = explode(",", $limit);
1901
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
1902
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
1903
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
1904
			{
1905
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
1906
			} else $limit_query = "";
1907
		} else $limit_query = "";
1908
		if ($sort != "")
1909
		{
1910
			$search_orderby_array = $this->getOrderBy();
1911
			$orderby_query = $search_orderby_array[$sort]['sql'];
1912
		} else {
1913
			if ($origLat != "" && $origLon != "" && $dist != "") {
1914
				$orderby_query = " ORDER BY distance ASC";
1915
			} else {
1916
				$orderby_query = " ORDER BY marine_output.date DESC";
1917
			}
1918
		}
1919
		if ($origLat != "" && $origLon != "" && $dist != "") {
1920
			$dist = number_format($dist*0.621371,2,'.',''); // convert km to mile
1921
			if ($globalDBdriver == 'mysql') {
1922
				$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 
1923
				    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)) 
1924
				    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;
1925
			} else {
1926
				$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 
1927
				    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)) 
1928
				    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;
1929
			}
1930
		} else {
1931
			$query  = "SELECT marine_output.* FROM marine_output".$filter_query." marine_output.ident <> '' 
1932
			    ".$additional_query."
1933
			    ".$orderby_query;
1934
		}
1935
		$marine_array = $this->getDataFromDB($query, $query_values,$limit_query);
1936
		return $marine_array;
1937
	}
1938
1939
	public function getOrderBy()
1940
	{
1941
		$orderby = array("aircraft_asc" => array("key" => "aircraft_asc", "value" => "Aircraft Type - ASC", "sql" => "ORDER BY marine_output.aircraft_icao ASC"), "aircraft_desc" => array("key" => "aircraft_desc", "value" => "Aircraft Type - DESC", "sql" => "ORDER BY marine_output.aircraft_icao 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"));
1942
		
1943
		return $orderby;
1944
		
1945
	}
1946
    
1947
}
1948
?>