Completed
Push — master ( cc50d0...0f8c33 )
by Yannick
09:46
created

Marine::getFilter()   F

Complexity

Conditions 28
Paths > 20000

Size

Total Lines 60
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 44
nc 31104
nop 3
dl 0
loc 60
rs 3.2266
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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