Completed
Push — master ( b49092...cf2135 )
by Yannick
30:03
created

Tracker::searchTrackerData()   F

Complexity

Conditions 23
Paths 975

Size

Total Lines 102
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 78
nc 975
nop 10
dl 0
loc 102
rs 2.2656
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

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

There are several approaches to avoid long parameter lists:

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