Completed
Push — master ( 7bb360...c01d59 )
by Yannick
22:07
created

Marine::updateIdentMarineData()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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