Completed
Push — master ( f1954e...8053db )
by Yannick
07:25
created

Marine::updateStatusMarineData()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 3
nop 3
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
require_once(dirname(__FILE__).'/class.Image.php');
3
$global_query = "SELECT marine_output.* FROM marine_output";
4
5
class Marine{
6
	public $db;
7
	
8
	public function __construct($dbc = null) {
9
		$Connection = new Connection($dbc);
10
		$this->db = $Connection->db();
11
	}
12
13
	/**
14
	* Get SQL query part for filter used
15
	* @param Array $filter the filter
16
	* @return Array the SQL part
17
	*/
18
	
19
	public function getFilter($filter = array(),$where = false,$and = false) {
20
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
21
		$filters = array();
22
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
23
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
24
				$filters = $globalStatsFilters[$globalFilterName];
25
			} else {
26
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
27
			}
28
		}
29
		if (isset($filter[0]['source'])) {
30
			$filters = array_merge($filters,$filter);
31
		}
32
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
33
		$filter_query_join = '';
34
		$filter_query_where = '';
35
		foreach($filters as $flt) {
36
			if (isset($flt['idents']) && !empty($flt['idents'])) {
37
				if (isset($flt['source'])) {
38
					$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output WHERE marine_output.ident IN ('".implode("','",$flt['idents'])."') AND spotter_output.format_source IN ('".implode("','",$flt['source'])."')) spfi ON spfi.fammarine_id = marine_output.fammarine_id";
39
				} else {
40
					$filter_query_join .= " INNER JOIN (SELECT fammarine_id FROM marine_output WHERE marine_output.ident IN ('".implode("','",$flt['idents'])."')) spfi ON spfi.fammarine_id = marine_output.fammarine_id";
41
				}
42
			}
43
		}
44
		if (isset($filter['source']) && !empty($filter['source'])) {
45
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
46
		}
47
		if (isset($filter['ident']) && !empty($filter['ident'])) {
48
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
49
		}
50
		if (isset($filter['year']) && $filter['year'] != '') {
51
			if ($globalDBdriver == 'mysql') {
52
				$filter_query_where .= " AND YEAR(marine_output.date) = '".$filter['year']."'";
53
			} else {
54
				$filter_query_where .= " AND EXTRACT(YEAR FROM marine_output.date) = '".$filter['year']."'";
55
			}
56
		}
57
		if (isset($filter['month']) && $filter['month'] != '') {
58
			if ($globalDBdriver == 'mysql') {
59
				$filter_query_where .= " AND MONTH(marine_output.date) = '".$filter['month']."'";
60
			} else {
61
				$filter_query_where .= " AND EXTRACT(MONTH FROM marine_output.date) = '".$filter['month']."'";
62
			}
63
		}
64
		if (isset($filter['day']) && $filter['day'] != '') {
65
			if ($globalDBdriver == 'mysql') {
66
				$filter_query_where .= " AND DAY(marine_output.date) = '".$filter['day']."'";
67
			} else {
68
				$filter_query_where .= " AND EXTRACT(DAY FROM marine_output.date) = '".$filter['day']."'";
69
			}
70
		}
71
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
72
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
73
		if ($filter_query_where != '') {
74
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
75
		}
76
		$filter_query = $filter_query_join.$filter_query_where;
77
		return $filter_query;
78
	}
79
80
	/**
81
	* Executes the SQL statements to get the spotter information
82
	*
83
	* @param String $query the SQL query
84
	* @param Array $params parameter of the query
85
	* @param String $limitQuery the limit query
86
	* @return Array the spotter information
87
	*
88
	*/
89
	public function getDataFromDB($query, $params = array(), $limitQuery = '',$schedules = false)
0 ignored issues
show
Unused Code introduced by
The parameter $schedules is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
90
	{
91
		date_default_timezone_set('UTC');
92
		if (!is_string($query))
93
		{
94
			return false;
95
		}
96
		
97
		if ($limitQuery != "")
98
		{
99
			if (!is_string($limitQuery))
100
			{
101
				return false;
102
			}
103
		}
104
105
		try {
106
			$sth = $this->db->prepare($query.$limitQuery);
107
			$sth->execute($params);
108
		} catch (PDOException $e) {
109
			printf("Invalid query : %s\nWhole query: %s\n",$e->getMessage(), $query.$limitQuery);
110
			exit();
111
		}
112
		
113
		$num_rows = 0;
114
		$spotter_array = array();
115
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
116
		{
117
			$num_rows++;
118
			$temp_array = array();
119
			if (isset($row['marine_live_id'])) {
120
				$temp_array['marine_id'] = $this->getMarineIDBasedOnFamMarineID($row['fammarine_id']);
121
			/*
122
			} elseif (isset($row['spotter_archive_id'])) {
123
				$temp_array['spotter_id'] = $row['spotter_archive_id'];
124
			} elseif (isset($row['spotter_archive_output_id'])) {
125
				$temp_array['spotter_id'] = $row['spotter_archive_output_id'];
126
			*/} 
127
			elseif (isset($row['marineid'])) {
128
				$temp_array['marine_id'] = $row['marineid'];
129
			} else {
130
				$temp_array['marine_id'] = '';
131
			}
132
			if (isset($row['fammarine_id'])) $temp_array['fammarine_id'] = $row['fammarine_id'];
133
			if (isset($row['mmsi'])) $temp_array['mmsi'] = $row['mmsi'];
134
			if (isset($row['type'])) $temp_array['type'] = $row['type'];
135
			if (isset($row['type_id'])) $temp_array['type_id'] = $row['type_id'];
136
			if (isset($row['ident'])) $temp_array['ident'] = $row['ident'];
137
			if (isset($row['latitude'])) $temp_array['latitude'] = $row['latitude'];
138
			if (isset($row['longitude'])) $temp_array['longitude'] = $row['longitude'];
139
			if (isset($row['format_source'])) $temp_array['format_source'] = $row['format_source'];
140
			if (isset($row['heading'])) {
141
				$temp_array['heading'] = $row['heading'];
142
				$heading_direction = $this->parseDirection($row['heading']);
143
				if (isset($heading_direction[0]['direction_fullname'])) $temp_array['heading_name'] = $heading_direction[0]['direction_fullname'];
144
			}
145
			if (isset($row['ground_speed'])) $temp_array['ground_speed'] = $row['ground_speed'];
146
147
			if($temp_array['mmsi'] != "")
148
			{
149
				$Image = new Image($this->db);
150
				if (isset($temp_array['ident']) && $temp_array['ident'] != '') $image_array = $Image->getMarineImage($temp_array['mmsi'],'',$temp_array['ident']);
151
				else $image_array = $Image->getMarineImage($temp_array['mmsi']);
152
				unset($Image);
153
				if (count($image_array) > 0) {
154
					$temp_array['image'] = $image_array[0]['image'];
155
					$temp_array['image_thumbnail'] = $image_array[0]['image_thumbnail'];
156
					$temp_array['image_source'] = $image_array[0]['image_source'];
157
					$temp_array['image_source_website'] = $image_array[0]['image_source_website'];
158
					$temp_array['image_copyright'] = $image_array[0]['image_copyright'];
159
				}
160
			}
161
			
162
			if (isset($row['date'])) {
163
				$dateArray = $this->parseDateString($row['date']);
164
				if ($dateArray['seconds'] < 10)
165
				{
166
					$temp_array['date'] = "a few seconds ago";
167
				} elseif ($dateArray['seconds'] >= 5 && $dateArray['seconds'] < 30)
168
				{
169
					$temp_array['date'] = "half a minute ago";
170
				} elseif ($dateArray['seconds'] >= 30 && $dateArray['seconds'] < 60)
171
				{
172
					$temp_array['date'] = "about a minute ago";
173
				} elseif ($dateArray['minutes'] < 5)
174
				{
175
					$temp_array['date'] = "a few minutes ago";
176
				} elseif ($dateArray['minutes'] >= 5 && $dateArray['minutes'] < 60)
177
				{
178
					$temp_array['date'] = "about ".$dateArray['minutes']." minutes ago";
179
				} elseif ($dateArray['hours'] < 2)
180
				{
181
					$temp_array['date'] = "about an hour ago";
182
				} elseif ($dateArray['hours'] >= 2 && $dateArray['hours'] < 24)
183
				{
184
					$temp_array['date'] = "about ".$dateArray['hours']." hours ago";
185
				} else {
186
					$temp_array['date'] = date("M j Y, g:i a",strtotime($row['date']." UTC"));
187
				}
188
				$temp_array['date_minutes_past'] = $dateArray['minutes'];
189
				$temp_array['date_iso_8601'] = date("c",strtotime($row['date']." UTC"));
190
				$temp_array['date_rfc_2822'] = date("r",strtotime($row['date']." UTC"));
191
				$temp_array['date_unix'] = strtotime($row['date']." UTC");
192
				if (isset($row['last_seen']) && $row['last_seen'] != '') {
193
					if (strtotime($row['last_seen']) > strtotime($row['date'])) {
194
						$temp_array['duration'] = strtotime($row['last_seen']) - strtotime($row['date']);
195
						$temp_array['last_seen_date_iso_8601'] = date("c",strtotime($row['last_seen']." UTC"));
196
						$temp_array['last_seen_date_rfc_2822'] = date("r",strtotime($row['last_seen']." UTC"));
197
						$temp_array['last_seen_date_unix'] = strtotime($row['last_seen']." UTC");
198
					}
199
				}
200
			}
201
			
202
			$fromsource = NULL;
0 ignored issues
show
Unused Code introduced by
$fromsource is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
203
			if (isset($row['source_name']) && $row['source_name'] != '') $temp_array['source_name'] = $row['source_name'];
204
			if (isset($row['over_country']) && $row['over_country'] != '') $temp_array['over_country'] = $row['over_country'];
205
			if (isset($row['distance']) && $row['distance'] != '') $temp_array['distance'] = $row['distance'];
206
			$temp_array['query_number_rows'] = $num_rows;
207
			$spotter_array[] = $temp_array;
208
		}
209
		if ($num_rows == 0) return array();
210
		$spotter_array[0]['query_number_rows'] = $num_rows;
211
		return $spotter_array;
212
	}	
213
	
214
	
215
	/**
216
	* Gets all the spotter information based on the latest data entry
217
	*
218
	* @return Array the spotter information
219
	*
220
	*/
221
	public function getLatestMarineData($limit = '', $sort = '', $filter = array())
222
	{
223
		global $global_query;
224
		date_default_timezone_set('UTC');
225
		$filter_query = $this->getFilter($filter);
226
		if ($limit != "")
227
		{
228
			$limit_array = explode(",", $limit);
229
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
230
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
231
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
232
			{
233
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
234
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
235
			} else $limit_query = "";
236
		} else $limit_query = "";
237
		if ($sort != "")
238
		{
239
			$search_orderby_array = $this->getOrderBy();
240
			$orderby_query = $search_orderby_array[$sort]['sql'];
241
		} else {
242
			$orderby_query = " ORDER BY marine_output.date DESC";
243
		}
244
		$query  = $global_query.$filter_query." ".$orderby_query;
245
		$spotter_array = $this->getDataFromDB($query, array(),$limit_query,true);
246
		return $spotter_array;
247
	}
248
    
249
	/*
250
	* Gets all the spotter information based on the spotter id
251
	*
252
	* @return Array the spotter information
253
	*
254
	*/
255
	public function getMarineDataByID($id = '')
256
	{
257
		global $global_query;
258
		
259
		date_default_timezone_set('UTC');
260
		if ($id == '') return array();
261
		$additional_query = "marine_output.fammarine_id = :id";
262
		$query_values = array(':id' => $id);
263
		$query  = $global_query." WHERE ".$additional_query." ";
264
		$spotter_array = $this->getDataFromDB($query,$query_values);
265
		return $spotter_array;
266
	}
267
268
	/**
269
	* Gets all the spotter information based on the callsign
270
	*
271
	* @return Array the spotter information
272
	*
273
	*/
274
	public function getMarineDataByIdent($ident = '', $limit = '', $sort = '', $filter = array())
275
	{
276
		global $global_query;
277
		
278
		date_default_timezone_set('UTC');
279
		
280
		$query_values = array();
281
		$limit_query = '';
282
		$additional_query = '';
283
		$filter_query = $this->getFilter($filter,true,true);
284
		if ($ident != "")
285
		{
286
			if (!is_string($ident))
287
			{
288
				return false;
289
			} else {
290
				$additional_query = " AND (marine_output.ident = :ident)";
291
				$query_values = array(':ident' => $ident);
292
			}
293
		}
294
		
295
		if ($limit != "")
296
		{
297
			$limit_array = explode(",", $limit);
298
			
299
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
300
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
301
			
302
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
303
			{
304
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
305
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
306
			}
307
		}
308
309
		if ($sort != "")
310
		{
311
			$search_orderby_array = $this->getOrderBy();
312
			$orderby_query = $search_orderby_array[$sort]['sql'];
313
		} else {
314
			$orderby_query = " ORDER BY marine_output.date DESC";
315
		}
316
317
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query." ".$orderby_query;
318
		//echo $query."\n";
319
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
320
321
		return $spotter_array;
322
	}
323
	
324
	public function getMarineDataByDate($date = '', $limit = '', $sort = '',$filter = array())
325
	{
326
		global $global_query, $globalTimezone, $globalDBdriver;
327
		
328
		$query_values = array();
329
		$limit_query = '';
330
		$additional_query = '';
331
332
		$filter_query = $this->getFilter($filter,true,true);
333
		
334
		if ($date != "")
335
		{
336
			if ($globalTimezone != '') {
337
				date_default_timezone_set($globalTimezone);
338
				$datetime = new DateTime($date);
339
				$offset = $datetime->format('P');
340
			} else {
341
				date_default_timezone_set('UTC');
342
				$datetime = new DateTime($date);
343
				$offset = '+00:00';
344
			}
345
			if ($globalDBdriver == 'mysql') {
346
				$additional_query = " AND DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) = :date ";
347
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':offset' => $offset);
348
			} elseif ($globalDBdriver == 'pgsql') {
349
				$additional_query = " AND to_char(marine_output.date AT TIME ZONE :timezone,'YYYY-mm-dd') = :date ";
350
				$query_values = array(':date' => $datetime->format('Y-m-d'), ':timezone' => $globalTimezone);
351
			}
352
		}
353
		
354
		if ($limit != "")
355
		{
356
			$limit_array = explode(",", $limit);
357
			
358
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
359
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
360
			
361
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
362
			{
363
				//$limit_query = " LIMIT ".$limit_array[0].",".$limit_array[1];
364
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
365
			}
366
		}
367
368
		if ($sort != "")
369
		{
370
			$search_orderby_array = $this->getOrderBy();
371
			$orderby_query = $search_orderby_array[$sort]['sql'];
372
		} else {
373
			$orderby_query = " ORDER BY marine_output.date DESC";
374
		}
375
376
		$query = $global_query.$filter_query." marine_output.ident <> '' ".$additional_query.$orderby_query;
377
		$spotter_array = $this->getDataFromDB($query, $query_values, $limit_query);
378
		return $spotter_array;
379
	}
380
381
382
383
	/**
384
	* Gets all source name
385
	*
386
	* @param String type format of source
387
	* @return Array list of source name
388
	*
389
	*/
390
	public function getAllSourceName($type = '',$filters = array())
391
	{
392
		$filter_query = $this->getFilter($filters,true,true);
393
		$query_values = array();
394
		$query  = "SELECT DISTINCT marine_output.source_name 
395
				FROM marine_output".$filter_query." marine_output.source_name <> ''";
396
		if ($type != '') {
397
			$query_values = array(':type' => $type);
398
			$query .= " AND format_source = :type";
399
		}
400
		$query .= " ORDER BY marine_output.source_name ASC";
401
402
		$sth = $this->db->prepare($query);
403
		if (!empty($query_values)) $sth->execute($query_values);
404
		else $sth->execute();
405
406
		$source_array = array();
407
		$temp_array = array();
408
		
409
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
410
		{
411
			$temp_array['source_name'] = $row['source_name'];
412
			$source_array[] = $temp_array;
413
		}
414
		return $source_array;
415
	}
416
417
418
	/**
419
	* Gets a list of all idents/callsigns
420
	*
421
	* @return Array list of ident/callsign names
422
	*
423
	*/
424
	public function getAllIdents($filters = array())
425
	{
426
		$filter_query = $this->getFilter($filters,true,true);
427
		$query  = "SELECT DISTINCT marine_output.ident
428
								FROM marine_output".$filter_query." marine_output.ident <> '' 
429
								ORDER BY marine_output.date ASC LIMIT 700 OFFSET 0";
430
431
		$sth = $this->db->prepare($query);
432
		$sth->execute();
433
    
434
		$ident_array = array();
435
		$temp_array = array();
436
		
437
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
438
		{
439
			$temp_array['ident'] = $row['ident'];
440
			$ident_array[] = $temp_array;
441
		}
442
443
		return $ident_array;
444
	}
445
446
	/**
447
	* Gets all info from a mmsi
448
	*
449
	* @return Array list of mmsi info
450
	*
451
	*/
452
	public function getIdentity($mmsi)
453
	{
454
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_NUMBER_INT);
455
		$query  = "SELECT * FROM marine_identity WHERE mmsi = :mmsi LIMIT 1";
456
		$sth = $this->db->prepare($query);
457
		$sth->execute(array(':mmsi' => $mmsi));
458
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
459
		if (isset($result[0])) return $result[0];
460
		else return array();
461
	}
462
463
	/*
464
	* Gets a list of all dates
465
	*
466
	* @return Array list of date names
467
	*
468
	*/
469
	public function getAllDates()
470
	{
471
		global $globalTimezone, $globalDBdriver;
472
		if ($globalTimezone != '') {
473
			date_default_timezone_set($globalTimezone);
474
			$datetime = new DateTime();
475
			$offset = $datetime->format('P');
476
		} else $offset = '+00:00';
477
478
		if ($globalDBdriver == 'mysql') {
479
			$query  = "SELECT DISTINCT DATE(CONVERT_TZ(marine_output.date,'+00:00', :offset)) as date
480
								FROM marine_output
481
								WHERE marine_output.date <> '' 
482
								ORDER BY marine_output.date ASC LIMIT 0,200";
483
		} else {
484
			$query  = "SELECT DISTINCT to_char(marine_output.date AT TIME ZONE INTERVAL :offset,'YYYY-mm-dd') as date
485
								FROM marine_output
486
								WHERE marine_output.date <> '' 
487
								ORDER BY marine_output.date ASC LIMIT 0,200";
488
		}
489
		
490
		$sth = $this->db->prepare($query);
491
		$sth->execute(array(':offset' => $offset));
492
    
493
		$date_array = array();
494
		$temp_array = array();
495
		
496
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
497
		{
498
			$temp_array['date'] = $row['date'];
499
500
			$date_array[] = $temp_array;
501
		}
502
503
		return $date_array;
504
	}
505
	
506
	
507
	/**
508
	* Update ident tracker data
509
	*
510
	* @param String $fammarine_id the ID
511
	* @param String $ident the marine ident
512
	* @return String success or false
513
	*
514
	*/	
515
	public function updateIdentMarineData($fammarine_id = '', $ident = '',$fromsource = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $fromsource is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
516
	{
517
518
		$query = 'UPDATE marine_output SET ident = :ident WHERE fammarine_id = :fammarine_id';
519
                $query_values = array(':fammarine_id' => $fammarine_id,':ident' => $ident);
520
521
		try {
522
			$sth = $this->db->prepare($query);
523
			$sth->execute($query_values);
524
		} catch (PDOException $e) {
525
			return "error : ".$e->getMessage();
526
		}
527
		
528
		return "success";
529
530
	}
531
532
	/**
533
	* Update Status data
534
	*
535
	* @param String $fammarine_id the ID
536
	* @param String $status_id the marine status id
537
	* @param String $status the marine status
538
	* @return String success or false
539
	*
540
	*/	
541
	public function updateStatusMarineData($fammarine_id = '', $status_id = '',$status = '')
542
	{
543
544
		$query = 'UPDATE marine_output SET status = :status, status_id = :status_id WHERE fammarine_id = :fammarine_id';
545
                $query_values = array(':fammarine_id' => $fammarine_id,':status' => $status,':status_id' => $status_id);
546
547
		try {
548
			$sth = $this->db->prepare($query);
549
			$sth->execute($query_values);
550
		} catch (PDOException $e) {
551
			return "error : ".$e->getMessage();
552
		}
553
		
554
		return "success";
555
556
	}
557
	/**
558
	* Update latest marine data
559
	*
560
	* @param String $fammarine_id the ID
561
	* @param String $ident the marine ident
562
	* @return String success or false
563
	*
564
	*/	
565
	public function updateLatestMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $groundspeed = NULL, $date = '')
566
	{
567
		$query = 'UPDATE marine_output SET ident = :ident, last_latitude = :last_latitude, last_longitude = :last_longitude, last_seen = :last_seen, last_ground_speed = :last_ground_speed WHERE fammarine_id = :fammarine_id';
568
                $query_values = array(':fammarine_id' => $fammarine_id,':last_latitude' => $latitude,':last_longitude' => $longitude, ':last_ground_speed' => $groundspeed,':last_seen' => $date,':ident' => $ident);
569
570
		try {
571
			$sth = $this->db->prepare($query);
572
			$sth->execute($query_values);
573
		} catch (PDOException $e) {
574
			return "error : ".$e->getMessage();
575
		}
576
		
577
		return "success";
578
579
	}
580
581
	/**
582
	* Adds a new spotter data
583
	*
584
	* @param String $fammarine_id the ID
585
	* @param String $ident the marine ident
586
	* @param String $departure_airport_icao the departure airport
0 ignored issues
show
Bug introduced by
There is no parameter named $departure_airport_icao. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
587
	* @param String $arrival_airport_icao the arrival airport
0 ignored issues
show
Bug introduced by
There is no parameter named $arrival_airport_icao. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
588
	* @param String $latitude latitude of flight
589
	* @param String $longitude latitude of flight
590
	* @param String $waypoints waypoints of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $waypoints. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
591
	* @param String $heading heading of flight
592
	* @param String $groundspeed speed of flight
593
	* @param String $date date of flight
594
	* @param String $departure_airport_time departure time of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $departure_airport_time. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
595
	* @param String $arrival_airport_time arrival time of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $arrival_airport_time. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
596
	* @param String $squawk squawk code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $squawk. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
597
	* @param String $route_stop route stop of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $route_stop. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
598
	* @param String $highlight highlight or not
0 ignored issues
show
Bug introduced by
There is no parameter named $highlight. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
599
	* @param String $ModeS ModesS code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $ModeS. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
600
	* @param String $registration registration code of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $registration. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
601
	* @param String $pilot_id pilot id of flight (for virtual airlines)
0 ignored issues
show
Bug introduced by
There is no parameter named $pilot_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
602
	* @param String $pilot_name pilot name of flight (for virtual airlines)
0 ignored issues
show
Bug introduced by
There is no parameter named $pilot_name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
603
	* @param String $verticalrate vertival rate of flight
0 ignored issues
show
Bug introduced by
There is no parameter named $verticalrate. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
604
	* @return String success or false
605
	*/
606
	public function addMarineData($fammarine_id = '', $ident = '', $latitude = '', $longitude = '', $heading = '', $groundspeed = '', $date = '', $mmsi = '',$type = '',$typeid = '',$imo = '',$callsign = '',$arrival_code = '',$arrival_date = '',$status = '',$statusid = '',$format_source = '', $source_name = '')
0 ignored issues
show
Unused Code introduced by
The parameter $typeid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $statusid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
607
	{
608
		global $globalURL, $globalMarineImageFetch;
609
		
610
		//$Image = new Image($this->db);
611
		$Common = new Common();
612
		
613
		date_default_timezone_set('UTC');
614
		
615
		//getting the registration
616
		if ($fammarine_id != "")
617
		{
618
			if (!is_string($fammarine_id))
619
			{
620
				return false;
621
			}
622
		}
623
		$fromsource = NULL;
0 ignored issues
show
Unused Code introduced by
$fromsource is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
624
		//getting the airline information
625
		if ($ident != "")
626
		{
627
			if (!is_string($ident))
628
			{
629
				return false;
630
			}
631
		}
632
633
		if ($latitude != "")
634
		{
635
			if (!is_numeric($latitude))
636
			{
637
				return false;
638
			}
639
		}
640
		
641
		if ($longitude != "")
642
		{
643
			if (!is_numeric($longitude))
644
			{
645
				return false;
646
			}
647
		}
648
		
649
		if ($heading != "")
650
		{
651
			if (!is_numeric($heading))
652
			{
653
				return false;
654
			}
655
		}
656
		if ($mmsi != "")
657
		{
658
			if (!is_numeric($mmsi))
659
			{
660
				return false;
661
			}
662
		}
663
		
664
		if ($groundspeed != "")
665
		{
666
			if (!is_numeric($groundspeed))
667
			{
668
				return false;
669
			}
670
		}
671
672
    
673
		if ($date == "" || strtotime($date) < time()-20*60)
674
		{
675
			$date = date("Y-m-d H:i:s", time());
676
		}
677
678
		$fammarine_id = filter_var($fammarine_id,FILTER_SANITIZE_STRING);
679
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
680
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
681
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
682
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
683
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
684
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
685
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
686
		$type = filter_var($type,FILTER_SANITIZE_STRING);
687
		$status = filter_var($status,FILTER_SANITIZE_STRING);
688
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
689
		$callsign = filter_var($callsign,FILTER_SANITIZE_STRING);
0 ignored issues
show
Unused Code introduced by
$callsign is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

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