Completed
Push — master ( 118bb3...d652ce )
by Yannick
29:38
created

Marine::countOverallTracked()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 31
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 24
nc 18
nop 3
dl 0
loc 31
rs 8.439
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 flightaware_id,over_country FROM marine_live".$filter_query.") l ON c.iso2 = l.over_country ";
837
		} else {
838
			$MarineArchive = new MarineArchive();
0 ignored issues
show
Unused Code introduced by
$MarineArchive 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...
839
			$filter_query = $MarineLive->getFilter($filters,true,true);
0 ignored issues
show
Bug introduced by
The variable $MarineLive seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
840
			$filter_query .= ' over_country IS NOT NULL';
841
			if ($olderthanmonths > 0) {
842
				if ($globalDBdriver == 'mysql') {
843
					$filter_query .= ' AND marine_archive.date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH) ';
844
				} else {
845
					$filter_query .= " AND marine_archive.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
846
				}
847
			}
848
			if ($sincedate != '') {
849
				if ($globalDBdriver == 'mysql') {
850
					$filter_query .= " AND marine_archive.date > '".$sincedate."' ";
851
				} else {
852
					$filter_query .= " AND marine_archive.date > CAST('".$sincedate."' AS TIMESTAMP)";
853
				}
854
			}
855
			$query = "SELECT c.name, c.iso3, c.iso2, count(c.name) as nb FROM countries c INNER JOIN (SELECT DISTINCT flightaware_id,over_country FROM marine_archive".$filter_query.") l ON c.iso2 = l.over_country ";
856
		}
857
		$query .= "GROUP BY c.name,c.iso3,c.iso2 ORDER BY nb DESC";
858
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
859
      
860
		
861
		$sth = $this->db->prepare($query);
862
		$sth->execute();
863
 
864
		$flight_array = array();
865
		$temp_array = array();
866
        
867
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
868
		{
869
			$temp_array['flight_count'] = $row['nb'];
870
			$temp_array['flight_country'] = $row['name'];
871
			$temp_array['flight_country_iso3'] = $row['iso3'];
872
			$temp_array['flight_country_iso2'] = $row['iso2'];
873
			$flight_array[] = $temp_array;
874
		}
875
		return $flight_array;
876
	}
877
	
878
	
879
	
880
	/**
881
	* Gets all callsigns that have flown over
882
	*
883
	* @return Array the callsign list
884
	*
885
	*/
886
	public function countAllCallsigns($limit = true, $olderthanmonths = 0, $sincedate = '',$filters = array(),$year = '', $month = '', $day = '')
887
	{
888
		global $globalDBdriver;
889
		$filter_query = $this->getFilter($filters,true,true);
890
		$query  = "SELECT DISTINCT marine_output.ident, COUNT(marine_output.ident) AS callsign_icao_count 
891
                    FROM marine_output".$filter_query." marine_output.ident <> ''";
892
		 if ($olderthanmonths > 0) {
893
			if ($globalDBdriver == 'mysql') $query .= ' AND date < DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$olderthanmonths.' MONTH)';
894
			else $query .= " AND marine_output.date < CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$olderthanmonths." MONTHS'";
895
		}
896
		if ($sincedate != '') {
897
			if ($globalDBdriver == 'mysql') $query .= " AND marine_output.date > '".$sincedate."'";
898
			else $query .= " AND marine_output.date > CAST('".$sincedate."' AS TIMESTAMP)";
899
		}
900
		$query_values = array();
901
		if ($year != '') {
902
			if ($globalDBdriver == 'mysql') {
903
				$query .= " AND YEAR(marine_output.date) = :year";
904
				$query_values = array_merge($query_values,array(':year' => $year));
905
			} else {
906
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
907
				$query_values = array_merge($query_values,array(':year' => $year));
908
			}
909
		}
910
		if ($month != '') {
911
			if ($globalDBdriver == 'mysql') {
912
				$query .= " AND MONTH(marine_output.date) = :month";
913
				$query_values = array_merge($query_values,array(':month' => $month));
914
			} else {
915
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
916
				$query_values = array_merge($query_values,array(':month' => $month));
917
			}
918
		}
919
		if ($day != '') {
920
			if ($globalDBdriver == 'mysql') {
921
				$query .= " AND DAY(marine_output.date) = :day";
922
				$query_values = array_merge($query_values,array(':day' => $day));
923
			} else {
924
				$query .= " AND EXTRACT(DAY FROM marine_output.date) = :day";
925
				$query_values = array_merge($query_values,array(':day' => $day));
926
			}
927
		}
928
		$query .= " GROUP BY marine_output.ident ORDER BY callsign_icao_count DESC";
929
		if ($limit) $query .= " LIMIT 10 OFFSET 0";
930
      		
931
		$sth = $this->db->prepare($query);
932
		$sth->execute($query_values);
933
      
934
		$callsign_array = array();
935
		$temp_array = array();
936
        
937
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
938
		{
939
			$temp_array['callsign_icao'] = $row['ident'];
940
			$temp_array['airline_name'] = $row['airline_name'];
941
			$temp_array['airline_icao'] = $row['airline_icao'];
942
			$temp_array['callsign_icao_count'] = $row['callsign_icao_count'];
943
          
944
			$callsign_array[] = $temp_array;
945
		}
946
947
		return $callsign_array;
948
	}
949
950
951
	/**
952
	* Counts all dates
953
	*
954
	* @return Array the date list
955
	*
956
	*/
957
	public function countAllDates($filters = array())
958
	{
959
		global $globalTimezone, $globalDBdriver;
960
		if ($globalTimezone != '') {
961
			date_default_timezone_set($globalTimezone);
962
			$datetime = new DateTime();
963
			$offset = $datetime->format('P');
964
		} else $offset = '+00:00';
965
966
		if ($globalDBdriver == 'mysql') {
967
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
968
								FROM marine_output";
969
			$query .= $this->getFilter($filters);
970
			$query .= " GROUP BY date_name 
971
								ORDER BY date_count DESC
972
								LIMIT 10 OFFSET 0";
973
		} else {
974
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
975
								FROM marine_output";
976
			$query .= $this->getFilter($filters);
977
			$query .= " GROUP BY date_name 
978
								ORDER BY date_count DESC
979
								LIMIT 10 OFFSET 0";
980
		}
981
      
982
		
983
		$sth = $this->db->prepare($query);
984
		$sth->execute(array(':offset' => $offset));
985
      
986
		$date_array = array();
987
		$temp_array = array();
988
        
989
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
990
		{
991
			$temp_array['date_name'] = $row['date_name'];
992
			$temp_array['date_count'] = $row['date_count'];
993
994
			$date_array[] = $temp_array;
995
		}
996
997
		return $date_array;
998
	}
999
	
1000
	
1001
	/**
1002
	* Counts all dates during the last 7 days
1003
	*
1004
	* @return Array the date list
1005
	*
1006
	*/
1007
	public function countAllDatesLast7Days($filters = array())
1008
	{
1009
		global $globalTimezone, $globalDBdriver;
1010
		if ($globalTimezone != '') {
1011
			date_default_timezone_set($globalTimezone);
1012
			$datetime = new DateTime();
1013
			$offset = $datetime->format('P');
1014
		} else $offset = '+00:00';
1015
		$filter_query = $this->getFilter($filters,true,true);
1016
		if ($globalDBdriver == 'mysql') {
1017
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1018
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 7 DAY)";
1019
			$query .= " GROUP BY date_name 
1020
								ORDER BY marine_output.date ASC";
1021
			$query_data = array(':offset' => $offset);
1022
		} else {
1023
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1024
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '7 DAYS'";
1025
			$query .= " GROUP BY date_name 
1026
								ORDER BY date_name ASC";
1027
			$query_data = array(':offset' => $offset);
1028
    		}
1029
		
1030
		$sth = $this->db->prepare($query);
1031
		$sth->execute($query_data);
1032
      
1033
		$date_array = array();
1034
		$temp_array = array();
1035
        
1036
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1037
		{
1038
			$temp_array['date_name'] = $row['date_name'];
1039
			$temp_array['date_count'] = $row['date_count'];
1040
          
1041
			$date_array[] = $temp_array;
1042
		}
1043
1044
		return $date_array;
1045
	}
1046
1047
	/**
1048
	* Counts all dates during the last month
1049
	*
1050
	* @return Array the date list
1051
	*
1052
	*/
1053
	public function countAllDatesLastMonth($filters = array())
1054
	{
1055
		global $globalTimezone, $globalDBdriver;
1056
		if ($globalTimezone != '') {
1057
			date_default_timezone_set($globalTimezone);
1058
			$datetime = new DateTime();
1059
			$offset = $datetime->format('P');
1060
		} else $offset = '+00:00';
1061
		$filter_query = $this->getFilter($filters,true,true);
1062
		if ($globalDBdriver == 'mysql') {
1063
			$query  = "SELECT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS date_name, count(*) as date_count
1064
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MONTH)";
1065
			$query .= " GROUP BY date_name 
1066
								ORDER BY marine_output.date ASC";
1067
			$query_data = array(':offset' => $offset);
1068
		} else {
1069
			$query  = "SELECT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') AS date_name, count(*) as date_count
1070
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 MONTHS'";
1071
			$query .= " GROUP BY date_name 
1072
								ORDER BY date_name ASC";
1073
			$query_data = array(':offset' => $offset);
1074
    		}
1075
		
1076
		$sth = $this->db->prepare($query);
1077
		$sth->execute($query_data);
1078
      
1079
		$date_array = array();
1080
		$temp_array = array();
1081
        
1082
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1083
		{
1084
			$temp_array['date_name'] = $row['date_name'];
1085
			$temp_array['date_count'] = $row['date_count'];
1086
          
1087
			$date_array[] = $temp_array;
1088
		}
1089
1090
		return $date_array;
1091
	}
1092
1093
1094
1095
	/**
1096
	* Counts all month
1097
	*
1098
	* @return Array the month list
1099
	*
1100
	*/
1101
	public function countAllMonths($filters = array())
1102
	{
1103
		global $globalTimezone, $globalDBdriver;
1104
		if ($globalTimezone != '') {
1105
			date_default_timezone_set($globalTimezone);
1106
			$datetime = new DateTime();
1107
			$offset = $datetime->format('P');
1108
		} else $offset = '+00:00';
1109
1110
		if ($globalDBdriver == 'mysql') {
1111
			$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
1112
								FROM marine_output";
1113
			$query .= $this->getFilter($filters);
1114
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1115
		} else {
1116
			$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
1117
								FROM marine_output";
1118
			$query .= $this->getFilter($filters);
1119
			$query .= " GROUP BY year_name, month_name ORDER BY date_count DESC";
1120
		}
1121
      
1122
		
1123
		$sth = $this->db->prepare($query);
1124
		$sth->execute(array(':offset' => $offset));
1125
      
1126
		$date_array = array();
1127
		$temp_array = array();
1128
        
1129
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1130
		{
1131
			$temp_array['month_name'] = $row['month_name'];
1132
			$temp_array['year_name'] = $row['year_name'];
1133
			$temp_array['date_count'] = $row['date_count'];
1134
1135
			$date_array[] = $temp_array;
1136
		}
1137
1138
		return $date_array;
1139
	}
1140
1141
	
1142
	
1143
1144
	/**
1145
	* Counts all dates during the last year
1146
	*
1147
	* @return Array the date list
1148
	*
1149
	*/
1150
	public function countAllMonthsLastYear($filters)
1151
	{
1152
		global $globalTimezone, $globalDBdriver;
1153
		if ($globalTimezone != '') {
1154
			date_default_timezone_set($globalTimezone);
1155
			$datetime = new DateTime();
1156
			$offset = $datetime->format('P');
1157
		} else $offset = '+00:00';
1158
		$filter_query = $this->getFilter($filters,true,true);
1159
		if ($globalDBdriver == 'mysql') {
1160
			$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
1161
								FROM marine_output".$filter_query." marine_output.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 YEAR)";
1162
			$query .= " GROUP BY year_name, month_name
1163
								ORDER BY year_name, month_name ASC";
1164
			$query_data = array(':offset' => $offset);
1165
		} else {
1166
			$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
1167
								FROM marine_output".$filter_query." marine_output.date >= CURRENT_TIMESTAMP AT TIME ZONE INTERVAL :offset - INTERVAL '1 YEARS'";
1168
			$query .= " GROUP BY year_name, month_name
1169
								ORDER BY year_name, month_name ASC";
1170
			$query_data = array(':offset' => $offset);
1171
    		}
1172
		
1173
		$sth = $this->db->prepare($query);
1174
		$sth->execute($query_data);
1175
      
1176
		$date_array = array();
1177
		$temp_array = array();
1178
        
1179
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1180
		{
1181
			$temp_array['year_name'] = $row['year_name'];
1182
			$temp_array['month_name'] = $row['month_name'];
1183
			$temp_array['date_count'] = $row['date_count'];
1184
          
1185
			$date_array[] = $temp_array;
1186
		}
1187
1188
		return $date_array;
1189
	}
1190
	
1191
	
1192
	
1193
	/**
1194
	* Counts all hours
1195
	*
1196
	* @return Array the hour list
1197
	*
1198
	*/
1199
	public function countAllHours($orderby,$filters = array())
1200
	{
1201
		global $globalTimezone, $globalDBdriver;
1202
		if ($globalTimezone != '') {
1203
			date_default_timezone_set($globalTimezone);
1204
			$datetime = new DateTime();
1205
			$offset = $datetime->format('P');
1206
		} else $offset = '+00:00';
1207
1208
		$orderby_sql = '';
1209
		if ($orderby == "hour")
1210
		{
1211
			$orderby_sql = "ORDER BY hour_name ASC";
1212
		}
1213
		if ($orderby == "count")
1214
		{
1215
			$orderby_sql = "ORDER BY hour_count DESC";
1216
		}
1217
		
1218
		if ($globalDBdriver == 'mysql') {
1219
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1220
								FROM marine_output";
1221
			$query .= $this->getFilter($filters);
1222
			$query .= " GROUP BY hour_name 
1223
								".$orderby_sql;
1224
1225
/*		$query  = "SELECT HOUR(marine_output.date) AS hour_name, count(*) as hour_count
1226
								FROM marine_output 
1227
								GROUP BY hour_name 
1228
								".$orderby_sql."
1229
								LIMIT 10 OFFSET 00";
1230
  */    
1231
		$query_data = array(':offset' => $offset);
1232
		} else {
1233
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1234
								FROM marine_output";
1235
			$query .= $this->getFilter($filters);
1236
			$query .= " GROUP BY hour_name 
1237
								".$orderby_sql;
1238
			$query_data = array(':offset' => $offset);
1239
		}
1240
		
1241
		$sth = $this->db->prepare($query);
1242
		$sth->execute($query_data);
1243
      
1244
		$hour_array = array();
1245
		$temp_array = array();
1246
        
1247
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1248
		{
1249
			$temp_array['hour_name'] = $row['hour_name'];
1250
			$temp_array['hour_count'] = $row['hour_count'];
1251
          
1252
			$hour_array[] = $temp_array;
1253
		}
1254
1255
		return $hour_array;
1256
	}
1257
	
1258
	
1259
	
1260
	/**
1261
	* Counts all hours by date
1262
	*
1263
	* @return Array the hour list
1264
	*
1265
	*/
1266
	public function countAllHoursByDate($date, $filters = array())
1267
	{
1268
		global $globalTimezone, $globalDBdriver;
1269
		$filter_query = $this->getFilter($filters,true,true);
1270
		$date = filter_var($date,FILTER_SANITIZE_STRING);
1271
		if ($globalTimezone != '') {
1272
			date_default_timezone_set($globalTimezone);
1273
			$datetime = new DateTime($date);
1274
			$offset = $datetime->format('P');
1275
		} else $offset = '+00:00';
1276
1277
		if ($globalDBdriver == 'mysql') {
1278
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1279
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date
1280
								GROUP BY hour_name 
1281
								ORDER BY hour_name ASC";
1282
		} else {
1283
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1284
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset, 'YYYY-mm-dd') = :date
1285
								GROUP BY hour_name 
1286
								ORDER BY hour_name ASC";
1287
		}
1288
		
1289
		$sth = $this->db->prepare($query);
1290
		$sth->execute(array(':date' => $date, ':offset' => $offset));
1291
      
1292
		$hour_array = array();
1293
		$temp_array = array();
1294
        
1295
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1296
		{
1297
			$temp_array['hour_name'] = $row['hour_name'];
1298
			$temp_array['hour_count'] = $row['hour_count'];
1299
          
1300
			$hour_array[] = $temp_array;
1301
		}
1302
1303
		return $hour_array;
1304
	}
1305
	
1306
	
1307
	
1308
	/**
1309
	* Counts all hours by a ident/callsign
1310
	*
1311
	* @return Array the hour list
1312
	*
1313
	*/
1314
	public function countAllHoursByIdent($ident, $filters = array())
1315
	{
1316
		global $globalTimezone, $globalDBdriver;
1317
		$filter_query = $this->getFilter($filters,true,true);
1318
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
1319
		if ($globalTimezone != '') {
1320
			date_default_timezone_set($globalTimezone);
1321
			$datetime = new DateTime();
1322
			$offset = $datetime->format('P');
1323
		} else $offset = '+00:00';
1324
1325
		if ($globalDBdriver == 'mysql') {
1326
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1327
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1328
								GROUP BY hour_name 
1329
								ORDER BY hour_name ASC";
1330
		} else {
1331
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1332
								FROM marine_output".$filter_query." marine_output.ident = :ident 
1333
								GROUP BY hour_name 
1334
								ORDER BY hour_name ASC";
1335
		}
1336
      
1337
		
1338
		$sth = $this->db->prepare($query);
1339
		$sth->execute(array(':ident' => $ident,':offset' => $offset));
1340
      
1341
		$hour_array = array();
1342
		$temp_array = array();
1343
        
1344
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1345
		{
1346
			$temp_array['hour_name'] = $row['hour_name'];
1347
			$temp_array['hour_count'] = $row['hour_count'];
1348
          
1349
			$hour_array[] = $temp_array;
1350
		}
1351
1352
		return $hour_array;
1353
	}
1354
	
1355
	
1356
	
1357
	/**
1358
	* Counts all flights that have flown over
1359
	*
1360
	* @return Integer the number of flights
1361
	*
1362
	*/
1363
	public function countOverallMarine($filters = array(),$year = '',$month = '')
1364
	{
1365
		global $globalDBdriver;
1366
		//$queryi  = "SELECT COUNT(marine_output.marine_id) AS flight_count FROM marine_output";
1367
		$queryi  = "SELECT COUNT(DISTINCT marine_output.mmsi) AS flight_count FROM marine_output";
1368
		$query_values = array();
1369
		$query = '';
1370
		if ($year != '') {
1371
			if ($globalDBdriver == 'mysql') {
1372
				$query .= " AND YEAR(marine_output.date) = :year";
1373
				$query_values = array_merge($query_values,array(':year' => $year));
1374
			} else {
1375
				$query .= " AND EXTRACT(YEAR FROM marine_output.date) = :year";
1376
				$query_values = array_merge($query_values,array(':year' => $year));
1377
			}
1378
		}
1379
		if ($month != '') {
1380
			if ($globalDBdriver == 'mysql') {
1381
				$query .= " AND MONTH(marine_output.date) = :month";
1382
				$query_values = array_merge($query_values,array(':month' => $month));
1383
			} else {
1384
				$query .= " AND EXTRACT(MONTH FROM marine_output.date) = :month";
1385
				$query_values = array_merge($query_values,array(':month' => $month));
1386
			}
1387
		}
1388
		if (empty($query_values)) $queryi .= $this->getFilter($filters);
1389
		else $queryi .= $this->getFilter($filters,true,true).substr($query,4);
1390
		
1391
		$sth = $this->db->prepare($queryi);
1392
		$sth->execute($query_values);
1393
		return $sth->fetchColumn();
1394
	}
1395
	
1396
  
1397
	/**
1398
	* Counts all hours of today
1399
	*
1400
	* @return Array the hour list
1401
	*
1402
	*/
1403
	public function countAllHoursFromToday($filters = array())
1404
	{
1405
		global $globalTimezone, $globalDBdriver;
1406
		$filter_query = $this->getFilter($filters,true,true);
1407
		if ($globalTimezone != '') {
1408
			date_default_timezone_set($globalTimezone);
1409
			$datetime = new DateTime();
1410
			$offset = $datetime->format('P');
1411
		} else $offset = '+00:00';
1412
1413
		if ($globalDBdriver == 'mysql') {
1414
			$query  = "SELECT HOUR(CONVERT_TZ(marine_output.date,'+00:00', :offset)) AS hour_name, count(*) as hour_count
1415
								FROM marine_output".$filter_query." DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = CURDATE()
1416
								GROUP BY hour_name 
1417
								ORDER BY hour_name ASC";
1418
		} else {
1419
			$query  = "SELECT EXTRACT(HOUR FROM marine_output.date AT TIME ZONE INTERVAL :offset) AS hour_name, count(*) as hour_count
1420
								FROM marine_output".$filter_query." to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') = CAST(NOW() AS date)
1421
								GROUP BY hour_name 
1422
								ORDER BY hour_name ASC";
1423
		}
1424
		
1425
		$sth = $this->db->prepare($query);
1426
		$sth->execute(array(':offset' => $offset));
1427
      
1428
		$hour_array = array();
1429
		$temp_array = array();
1430
        
1431
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1432
		{
1433
			$temp_array['hour_name'] = $row['hour_name'];
1434
			$temp_array['hour_count'] = $row['hour_count'];
1435
			$hour_array[] = $temp_array;
1436
		}
1437
1438
		return $hour_array;
1439
	}
1440
    
1441
    
1442
     /**
1443
	* Gets the Barrie Spotter ID based on the FlightAware ID
1444
	*
1445
	* @return Integer the Barrie Spotter ID
1446
q	*
1447
	*/
1448
	public function getMarineIDBasedOnFamMarineID($fammarine_id)
1449
	{
1450
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
1451
1452
		$query  = "SELECT marine_output.marine_id
1453
				FROM marine_output 
1454
				WHERE marine_output.fammarine_id = '".$fammarine_id."'";
1455
        
1456
		
1457
		$sth = $this->db->prepare($query);
1458
		$sth->execute();
1459
1460
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
1461
		{
1462
			return $row['marine_id'];
1463
		}
1464
	}
1465
  
1466
 
1467
	/**
1468
	* Parses a date string
1469
	*
1470
	* @param String $dateString the date string
1471
	* @param String $timezone the timezone of a user
1472
	* @return Array the time information
1473
	*
1474
	*/
1475
	public function parseDateString($dateString, $timezone = '')
1476
	{
1477
		$time_array = array();
1478
	
1479
		if ($timezone != "")
1480
		{
1481
			date_default_timezone_set($timezone);
1482
		}
1483
		
1484
		$current_date = date("Y-m-d H:i:s");
1485
		$date = date("Y-m-d H:i:s",strtotime($dateString." UTC"));
1486
		
1487
		$diff = abs(strtotime($current_date) - strtotime($date));
1488
1489
		$time_array['years'] = floor($diff / (365*60*60*24)); 
1490
		$years = $time_array['years'];
1491
		
1492
		$time_array['months'] = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
1493
		$months = $time_array['months'];
1494
		
1495
		$time_array['days'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
1496
		$days = $time_array['days'];
1497
		$time_array['hours'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
1498
		$hours = $time_array['hours'];
1499
		$time_array['minutes'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
1500
		$minutes = $time_array['minutes'];
1501
		$time_array['seconds'] = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60));  
1502
		
1503
		return $time_array;
1504
	}
1505
	
1506
	/**
1507
	* Parses the direction degrees to working
1508
	*
1509
	* @param Float $direction the direction in degrees
1510
	* @return Array the direction information
1511
	*
1512
	*/
1513
	public function parseDirection($direction = 0)
1514
	{
1515
		if ($direction == '') $direction = 0;
1516
		$direction_array = array();
1517
		$temp_array = array();
1518
1519
		if ($direction == 360 || ($direction >= 0 && $direction < 22.5))
1520
		{
1521
			$temp_array['direction_degree'] = $direction;
1522
			$temp_array['direction_shortname'] = "N";
1523
			$temp_array['direction_fullname'] = "North";
1524
		} elseif ($direction >= 22.5 && $direction < 45){
1525
			$temp_array['direction_degree'] = $direction;
1526
			$temp_array['direction_shortname'] = "NNE";
1527
			$temp_array['direction_fullname'] = "North-Northeast";
1528
		} elseif ($direction >= 45 && $direction < 67.5){
1529
			$temp_array['direction_degree'] = $direction;
1530
			$temp_array['direction_shortname'] = "NE";
1531
			$temp_array['direction_fullname'] = "Northeast";
1532
		} elseif ($direction >= 67.5 && $direction < 90){
1533
			$temp_array['direction_degree'] = $direction;
1534
			$temp_array['direction_shortname'] = "ENE";
1535
			$temp_array['direction_fullname'] = "East-Northeast";
1536
		} elseif ($direction >= 90 && $direction < 112.5){
1537
			$temp_array['direction_degree'] = $direction;
1538
			$temp_array['direction_shortname'] = "E";
1539
			$temp_array['direction_fullname'] = "East";
1540
		} elseif ($direction >= 112.5 && $direction < 135){
1541
			$temp_array['direction_degree'] = $direction;
1542
			$temp_array['direction_shortname'] = "ESE";
1543
			$temp_array['direction_fullname'] = "East-Southeast";
1544
		} elseif ($direction >= 135 && $direction < 157.5){
1545
			$temp_array['direction_degree'] = $direction;
1546
			$temp_array['direction_shortname'] = "SE";
1547
			$temp_array['direction_fullname'] = "Southeast";
1548
		} elseif ($direction >= 157.5 && $direction < 180){
1549
			$temp_array['direction_degree'] = $direction;
1550
			$temp_array['direction_shortname'] = "SSE";
1551
			$temp_array['direction_fullname'] = "South-Southeast";
1552
		} elseif ($direction >= 180 && $direction < 202.5){
1553
			$temp_array['direction_degree'] = $direction;
1554
			$temp_array['direction_shortname'] = "S";
1555
			$temp_array['direction_fullname'] = "South";
1556
		} elseif ($direction >= 202.5 && $direction < 225){
1557
			$temp_array['direction_degree'] = $direction;
1558
			$temp_array['direction_shortname'] = "SSW";
1559
			$temp_array['direction_fullname'] = "South-Southwest";
1560
		} elseif ($direction >= 225 && $direction < 247.5){
1561
			$temp_array['direction_degree'] = $direction;
1562
			$temp_array['direction_shortname'] = "SW";
1563
			$temp_array['direction_fullname'] = "Southwest";
1564
		} elseif ($direction >= 247.5 && $direction < 270){
1565
			$temp_array['direction_degree'] = $direction;
1566
			$temp_array['direction_shortname'] = "WSW";
1567
			$temp_array['direction_fullname'] = "West-Southwest";
1568
		} elseif ($direction >= 270 && $direction < 292.5){
1569
			$temp_array['direction_degree'] = $direction;
1570
			$temp_array['direction_shortname'] = "W";
1571
			$temp_array['direction_fullname'] = "West";
1572
		} elseif ($direction >= 292.5 && $direction < 315){
1573
			$temp_array['direction_degree'] = $direction;
1574
			$temp_array['direction_shortname'] = "WNW";
1575
			$temp_array['direction_fullname'] = "West-Northwest";
1576
		} elseif ($direction >= 315 && $direction < 337.5){
1577
			$temp_array['direction_degree'] = $direction;
1578
			$temp_array['direction_shortname'] = "NW";
1579
			$temp_array['direction_fullname'] = "Northwest";
1580
		} elseif ($direction >= 337.5 && $direction < 360){
1581
			$temp_array['direction_degree'] = $direction;
1582
			$temp_array['direction_shortname'] = "NNW";
1583
			$temp_array['direction_fullname'] = "North-Northwest";
1584
		}
1585
		$direction_array[] = $temp_array;
1586
		return $direction_array;
1587
	}
1588
	
1589
	
1590
	/**
1591
	* Gets Country from latitude/longitude
1592
	*
1593
	* @param Float $latitude latitute of the flight
1594
	* @param Float $longitude longitute of the flight
1595
	* @return String the countrie
1596
	*/
1597
	public function getCountryFromLatitudeLongitude($latitude,$longitude)
1598
	{
1599
		global $globalDBdriver, $globalDebug;
1600
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1601
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
1602
	
1603
		$Connection = new Connection($this->db);
1604
		if (!$Connection->tableExists('countries')) return '';
1605
	
1606
		try {
1607
			/*
1608
			if ($globalDBdriver == 'mysql') {
1609
				//$query  = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(:latitude :longitude)'), ogc_geom) LIMIT 1";
1610
				$query = "SELECT name, iso2, iso3 FROM countries WHERE Within(GeomFromText('POINT(".$longitude.' '.$latitude.")'), ogc_geom) LIMIT 1";
1611
			}
1612
			*/
1613
			// This query seems to work both for MariaDB and PostgreSQL
1614
			$query = "SELECT name,iso2,iso3 FROM countries WHERE ST_Within(ST_GeomFromText('POINT(".$longitude." ".$latitude.")',4326), ogc_geom) LIMIT 1";
1615
		
1616
			$sth = $this->db->prepare($query);
1617
			//$sth->execute(array(':latitude' => $latitude,':longitude' => $longitude));
1618
			$sth->execute();
1619
    
1620
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1621
			$sth->closeCursor();
1622
			if (count($row) > 0) {
1623
				return $row;
1624
			} else return '';
1625
		} catch (PDOException $e) {
1626
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1627
			return '';
1628
		}
1629
	
1630
	}
1631
1632
	/**
1633
	* Gets Country from iso2
1634
	*
1635
	* @param String $iso2 ISO2 country code
1636
	* @return String the countrie
1637
	*/
1638
	public function getCountryFromISO2($iso2)
1639
	{
1640
		global $globalDBdriver, $globalDebug;
1641
		$iso2 = filter_var($iso2,FILTER_SANITIZE_STRING);
1642
	
1643
		$Connection = new Connection($this->db);
1644
		if (!$Connection->tableExists('countries')) return '';
1645
	
1646
		try {
1647
			$query = "SELECT name,iso2,iso3 FROM countries WHERE iso2 = :iso2 LIMIT 1";
1648
		
1649
			$sth = $this->db->prepare($query);
1650
			$sth->execute(array(':iso2' => $iso2));
1651
    
1652
			$row = $sth->fetch(PDO::FETCH_ASSOC);
1653
			$sth->closeCursor();
1654
			if (count($row) > 0) {
1655
				return $row;
1656
			} else return '';
1657
		} catch (PDOException $e) {
1658
			if (isset($globalDebug) && $globalDebug) echo 'Error : '.$e->getMessage()."\n";
1659
			return '';
1660
		}
1661
	
1662
	}
1663
1664
	
1665
	/**
1666
	* Gets the short url from bit.ly
1667
	*
1668
	* @param String $url the full url
1669
	* @return String the bit.ly url
1670
	*
1671
	*/
1672
	public function getBitlyURL($url)
1673
	{
1674
		global $globalBitlyAccessToken;
1675
		
1676
		if ($globalBitlyAccessToken == '') return $url;
1677
        
1678
		$google_url = 'https://api-ssl.bitly.com/v3/shorten?access_token='.$globalBitlyAccessToken.'&longUrl='.$url;
1679
		
1680
		$ch = curl_init();
1681
		curl_setopt($ch, CURLOPT_HEADER, 0);
1682
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1683
		curl_setopt($ch, CURLOPT_URL, $google_url);
1684
		$bitly_data = curl_exec($ch);
1685
		curl_close($ch);
1686
		
1687
		$bitly_data = json_decode($bitly_data);
1688
		$bitly_url = '';
1689
		if ($bitly_data->status_txt = "OK"){
1690
			$bitly_url = $bitly_data->data->url;
1691
		}
1692
1693
		return $bitly_url;
1694
	}
1695
1696
1697
	public function getOrderBy()
1698
	{
1699
		$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"));
1700
		
1701
		return $orderby;
1702
		
1703
	}
1704
    
1705
}
1706
?>