Tracker::countAllMonthsLastYear()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

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