Completed
Push — master ( 6c4f55...213543 )
by Yannick
10:31
created

Marine::addMarineData()   F

Complexity

Conditions 28
Paths > 20000

Size

Total Lines 119
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 63
nc 36991
nop 17
dl 0
loc 119
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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