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

TrackerLive::getOrderBy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
//$global_query = "SELECT tracker_live.* FROM tracker_live";
3
4
class TrackerLive {
5
	public $db;
6
	static $global_query = "SELECT tracker_live.* FROM tracker_live";
7
8
	public function __construct($dbc = null) {
9
		$Connection = new Connection($dbc);
10
		$this->db = $Connection->db();
11
	}
12
13
14
	/**
15
	* Get SQL query part for filter used
16
	* @param Array $filter the filter
17
	* @return Array the SQL part
18
	*/
19
	public function getFilter($filter = array(),$where = false,$and = false) {
20
		global $globalFilter, $globalStatsFilters, $globalFilterName, $globalDBdriver;
21
		$filters = array();
22
		if (is_array($globalStatsFilters) && isset($globalStatsFilters[$globalFilterName])) {
23
			if (isset($globalStatsFilters[$globalFilterName][0]['source'])) {
24
				$filters = $globalStatsFilters[$globalFilterName];
25
			} else {
26
				$filter = array_merge($filter,$globalStatsFilters[$globalFilterName]);
27
			}
28
		}
29
		if (isset($filter[0]['source'])) {
30
			$filters = array_merge($filters,$filter);
31
		}
32
		if (is_array($globalFilter)) $filter = array_merge($filter,$globalFilter);
33
		$filter_query_join = '';
34
		$filter_query_where = '';
35
		foreach($filters as $flt) {
36
			if (isset($flt['idents']) && !empty($flt['idents'])) {
37
				if (isset($flt['source'])) {
38
					$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output WHERE tracker_output.ident IN ('".implode("','",$flt['idents'])."') AND tracker_output.format_source IN ('".implode("','",$flt['source'])."')) spid ON spid.famtrackid = tracker_live.famtrackid";
39
				} else {
40
					$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output WHERE tracker_output.ident IN ('".implode("','",$flt['idents'])."')) spid ON spid.famtrackid = tracker_live.famtrackid";
41
				}
42
			}
43
		}
44
		if (isset($filter['source']) && !empty($filter['source'])) {
45
			$filter_query_where .= " AND format_source IN ('".implode("','",$filter['source'])."')";
46
		}
47
		if (isset($filter['ident']) && !empty($filter['ident'])) {
48
			$filter_query_where .= " AND ident = '".$filter['ident']."'";
49
		}
50
		if ((isset($filter['year']) && $filter['year'] != '') || (isset($filter['month']) && $filter['month'] != '') || (isset($filter['day']) && $filter['day'] != '')) {
51
			$filter_query_date = '';
52
			
53
			if (isset($filter['year']) && $filter['year'] != '') {
54
				if ($globalDBdriver == 'mysql') {
55
					$filter_query_date .= " AND YEAR(tracker_output.date) = '".$filter['year']."'";
56
				} else {
57
					$filter_query_date .= " 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_date .= " AND MONTH(tracker_output.date) = '".$filter['month']."'";
63
				} else {
64
					$filter_query_date .= " 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_date .= " AND DAY(tracker_output.date) = '".$filter['day']."'";
70
				} else {
71
					$filter_query_date .= " AND EXTRACT(DAY FROM tracker_output.date) = '".$filter['day']."'";
72
				}
73
			}
74
			$filter_query_join .= " INNER JOIN (SELECT famtrackid FROM tracker_output".preg_replace('/^ AND/',' WHERE',$filter_query_date).") sd ON sd.famtrackid = tracker_live.famtrackid";
75
		}
76
		if (isset($filter['source_aprs']) && !empty($filter['source_aprs'])) {
77
			$filter_query_where .= " AND format_source = 'aprs' AND source_name IN ('".implode("','",$filter['source_aprs'])."')";
78
		}
79
		if ($filter_query_where == '' && $where) $filter_query_where = ' WHERE';
80
		elseif ($filter_query_where != '' && $and) $filter_query_where .= ' AND';
81
		if ($filter_query_where != '') {
82
			$filter_query_where = preg_replace('/^ AND/',' WHERE',$filter_query_where);
83
		}
84
		$filter_query = $filter_query_join.$filter_query_where;
85
		return $filter_query;
86
	}
87
88
	/**
89
	* Gets all the spotter information based on the latest data entry
90
	*
91
	* @return Array the spotter information
92
	*
93
	*/
94
	public function getLiveTrackerData($limit = '', $sort = '', $filter = array())
95
	{
96
		global $globalDBdriver, $globalLiveInterval;
97
		$Tracker = new Tracker($this->db);
98
		date_default_timezone_set('UTC');
99
100
		$filter_query = $this->getFilter($filter);
101
		$limit_query = '';
102
		if ($limit != '')
103
		{
104
			$limit_array = explode(',', $limit);
105
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
106
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
107
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
108
			{
109
				$limit_query = ' LIMIT '.$limit_array[1].' OFFSET '.$limit_array[0];
110
			}
111
		}
112
		$orderby_query = '';
113
		if ($sort != '')
114
		{
115
			$search_orderby_array = $this->getOrderBy();
116
			if (isset($search_orderby_array[$sort]['sql'])) 
117
			{
118
				$orderby_query = ' '.$search_orderby_array[$sort]['sql'];
119
			}
120
		}
121
122
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
123
		if ($globalDBdriver == 'mysql') {
124
			//$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate";
125
			$query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate'.$filter_query.$orderby_query;
126
		} else {
127
			$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate".$filter_query.$orderby_query;
128
		}
129
		$spotter_array = $Tracker->getDataFromDB($query.$limit_query,array(),'',true);
130
131
		return $spotter_array;
132
	}
133
134
	/**
135
	* Gets Minimal Live Spotter data
136
	*
137
	* @return Array the spotter information
138
	*
139
	*/
140
	public function getMinLiveTrackerData($filter = array())
141
	{
142
		global $globalDBdriver, $globalLiveInterval;
143
		date_default_timezone_set('UTC');
144
145
		$filter_query = $this->getFilter($filter,true,true);
146
147
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
148
		if ($globalDBdriver == 'mysql') {
149
			$query  = 'SELECT tracker_live.ident, tracker_live.type,tracker_live.famtrackid, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
150
			FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate'.$filter_query." tracker_live.latitude <> 0 AND tracker_live.longitude <> 0";
151
		} else {
152
			$query  = "SELECT tracker_live.ident, tracker_live.type,tracker_live.famtrackid, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
153
			FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate".$filter_query." tracker_live.latitude <> '0' AND tracker_live.longitude <> '0'";
154
155
156
		}
157
//		$spotter_array = Spotter->getDataFromDB($query.$limit_query);
158
//		echo $query;
159
160
		try {
161
			$sth = $this->db->prepare($query);
162
			$sth->execute();
163
		} catch(PDOException $e) {
164
			echo $e->getMessage();
165
			die;
166
		}
167
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
168
169
		return $spotter_array;
170
	}
171
172
	/**
173
	* Gets Minimal Live Spotter data since xx seconds
174
	*
175
	* @return Array the spotter information
176
	*
177
	*/
178
	public function getMinLastLiveTrackerData($filter = array())
179
	{
180
		global $globalDBdriver, $globalLiveInterval;
181
		date_default_timezone_set('UTC');
182
183
		$filter_query = $this->getFilter($filter,true,true);
184
185
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
186
		if ($globalDBdriver == 'mysql') {
187
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid,tracker_live.type, tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
188
			FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval." SECOND) <= tracker_live.date AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' 
189
			ORDER BY tracker_live.famtrackid, tracker_live.date";
190
                } else {
191
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid, tracker_live.type,tracker_live.latitude, tracker_live.longitude, tracker_live.altitude, tracker_live.heading, tracker_live.ground_speed, tracker_live.date, tracker_live.format_source 
192
			FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= tracker_live.date AND tracker_live.latitude <> '0' AND tracker_live.longitude <> '0' 
193
			ORDER BY tracker_live.famtrackid, tracker_live.date";
194
		}
195
196
    		try {
197
			$sth = $this->db->prepare($query);
198
			$sth->execute();
199
		} catch(PDOException $e) {
200
			echo $e->getMessage();
201
			die;
202
		}
203
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
204
		return $spotter_array;
205
	}
206
207
	/**
208
	* Gets number of latest data entry
209
	*
210
	* @return String number of entry
211
	*
212
	*/
213
	public function getLiveTrackerCount($filter = array())
214
	{
215
		global $globalDBdriver, $globalLiveInterval;
216
		$filter_query = $this->getFilter($filter,true,true);
217
218
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
219
		if ($globalDBdriver == 'mysql') {
220
			$query = 'SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live'.$filter_query.' DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
221
		} else {
222
			$query = "SELECT COUNT(DISTINCT tracker_live.famtrackid) as nb FROM tracker_live".$filter_query." CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
223
		}
224
		try {
225
			$sth = $this->db->prepare($query);
226
			$sth->execute();
227
		} catch(PDOException $e) {
228
			echo $e->getMessage();
229
			die;
230
		}
231
		$result = $sth->fetch(PDO::FETCH_ASSOC);
232
		$sth->closeCursor();
233
		return $result['nb'];
234
	}
235
236
	/**
237
	* Gets all the spotter information based on the latest data entry and coord
238
	*
239
	* @return Array the spotter information
240
	*
241
	*/
242
	public function getLiveTrackerDatabyCoord($coord, $filter = array())
243
	{
244
		global $globalDBdriver, $globalLiveInterval;
245
		$Spotter = new Spotter($this->db);
246
		if (!isset($globalLiveInterval)) $globalLiveInterval = '200';
247
		$filter_query = $this->getFilter($filter);
248
249
		if (is_array($coord)) {
250
			$minlong = filter_var($coord[0],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
251
			$minlat = filter_var($coord[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
252
			$maxlong = filter_var($coord[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
253
			$maxlat = filter_var($coord[3],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
254
		} else return array();
255
		if ($globalDBdriver == 'mysql') {
256
			$query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND tracker_live.latitude BETWEEN '.$minlat.' AND '.$maxlat.' AND tracker_live.longitude BETWEEN '.$minlong.' AND '.$maxlong.' GROUP BY tracker_live.famtrackid'.$filter_query;
257
		} else {
258
			$query  = "SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE NOW() at time zone 'UTC'  - INTERVAL '".$globalLiveInterval." SECONDS' <= l.date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND tracker_live.latitude BETWEEN ".$minlat." AND ".$maxlat." AND tracker_live.longitude BETWEEN ".$minlong." AND ".$maxlong." GROUP BY tracker_live.famtrackid".$filter_query;
259
		}
260
		$spotter_array = $Spotter->getDataFromDB($query);
261
		return $spotter_array;
262
	}
263
264
	/**
265
	* Gets all the spotter information based on a user's latitude and longitude
266
	*
267
	* @return Array the spotter information
268
	*
269
	*/
270
	public function getLatestTrackerForLayar($lat, $lng, $radius, $interval)
271
	{
272
		$Tracker = new Tracker($this->db);
273
		date_default_timezone_set('UTC');
274
		if ($lat != '') {
275
			if (!is_numeric($lat)) {
276
				return false;
277
			}
278
		}
279
		if ($lng != '')
280
		{
281
			if (!is_numeric($lng))
282
                        {
283
                                return false;
284
                        }
285
                }
286
287
                if ($radius != '')
288
                {
289
                        if (!is_numeric($radius))
290
                        {
291
                                return false;
292
                        }
293
                }
294
		$additional_query = '';
295
		if ($interval != '')
296
                {
297
                        if (!is_string($interval))
298
                        {
299
                                //$additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
300
			        return false;
301
                        } else {
302
                if ($interval == '1m')
303
                {
304
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';
305
                } else if ($interval == '15m'){
306
                    $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 15 MINUTE) <= tracker_live.date ';
307
                } 
308
            }
309
                } else {
310
         $additional_query = ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 MINUTE) <= tracker_live.date ';   
311
        }
312
313
                $query  = "SELECT tracker_live.*, ( 6371 * acos( cos( radians(:lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:lng) ) + sin( radians(:lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM tracker_live 
314
                   WHERE tracker_live.latitude <> '' 
315
                                   AND tracker_live.longitude <> '' 
316
                   ".$additional_query."
317
                   HAVING distance < :radius  
318
                                   ORDER BY distance";
319
320
                $spotter_array = $Tracker->getDataFromDB($query, array(':lat' => $lat, ':lng' => $lng,':radius' => $radius));
321
322
                return $spotter_array;
323
        }
324
325
    
326
        /**
327
	* Gets all the spotter information based on a particular callsign
328
	*
329
	* @return Array the spotter information
330
	*
331
	*/
332
	public function getLastLiveTrackerDataByIdent($ident)
333
	{
334
		$Tracker = new Tracker($this->db);
335
		date_default_timezone_set('UTC');
336
337
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
338
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.ident = :ident GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
339
340
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident),'',true);
341
342
		return $spotter_array;
343
	}
344
345
        /**
346
	* Gets all the spotter information based on a particular callsign
347
	*
348
	* @return Array the spotter information
349
	*
350
	*/
351
	public function getDateLiveTrackerDataByIdent($ident,$date)
352
	{
353
		$Tracker = new Tracker($this->db);
354
		date_default_timezone_set('UTC');
355
356
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
357
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.ident = :ident AND l.date <= :date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
358
359
                $date = date('c',$date);
360
		$spotter_array = $Tracker->getDataFromDB($query,array(':ident' => $ident,':date' => $date));
361
362
		return $spotter_array;
363
	}
364
365
        /**
366
	* Gets last spotter information based on a particular callsign
367
	*
368
	* @return Array the spotter information
369
	*
370
	*/
371
	public function getLastLiveTrackerDataById($id)
372
	{
373
		$Tracker = new Tracker($this->db);
374
		date_default_timezone_set('UTC');
375
376
		$id = filter_var($id, FILTER_SANITIZE_STRING);
377
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.famtrackid = :id GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
378
379
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id),'',true);
380
381
		return $spotter_array;
382
	}
383
384
        /**
385
	* Gets last spotter information based on a particular callsign
386
	*
387
	* @return Array the spotter information
388
	*
389
	*/
390
	public function getDateLiveTrackerDataById($id,$date)
391
	{
392
		$Tracker = new Tracker($this->db);
393
		date_default_timezone_set('UTC');
394
395
		$id = filter_var($id, FILTER_SANITIZE_STRING);
396
                $query  = 'SELECT tracker_live.* FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l WHERE l.famtrackid = :id AND l.date <= :date GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate ORDER BY tracker_live.date DESC';
397
                $date = date('c',$date);
398
		$spotter_array = $Tracker->getDataFromDB($query,array(':id' => $id,':date' => $date),'',true);
399
400
		return $spotter_array;
401
	}
402
403
        /**
404
	* Gets altitude information based on a particular callsign
405
	*
406
	* @return Array the spotter information
407
	*
408
	*/
409
	public function getAltitudeLiveTrackerDataByIdent($ident)
410
	{
411
412
		date_default_timezone_set('UTC');
413
414
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
415
                $query  = 'SELECT tracker_live.altitude, tracker_live.date FROM tracker_live WHERE tracker_live.ident = :ident';
416
417
    		try {
418
			
419
			$sth = $this->db->prepare($query);
420
			$sth->execute(array(':ident' => $ident));
421
		} catch(PDOException $e) {
422
			echo $e->getMessage();
423
			die;
424
		}
425
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
426
427
		return $spotter_array;
428
	}
429
430
        /**
431
	* Gets all the spotter information based on a particular id
432
	*
433
	* @return Array the spotter information
434
	*
435
	*/
436
	public function getAllLiveTrackerDataById($id,$liveinterval = false)
437
	{
438
		global $globalDBdriver, $globalLiveInterval;
439
		date_default_timezone_set('UTC');
440
		$id = filter_var($id, FILTER_SANITIZE_STRING);
441
		//$query  = self::$global_query.' WHERE tracker_live.famtrackid = :id ORDER BY date';
442
		if ($globalDBdriver == 'mysql') {
443
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
444
			if ($liveinterval) $query .= ' AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL '.$globalLiveInterval.' SECOND) <= date';
445
			$query .= ' ORDER BY date';
446
		} else {
447
			$query = 'SELECT tracker_live.* FROM tracker_live WHERE tracker_live.famtrackid = :id';
448
			if ($liveinterval) $query .= " AND CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '".$globalLiveInterval." SECONDS' <= date";
449
			$query .= ' ORDER BY date';
450
		}
451
452
		try {
453
			$sth = $this->db->prepare($query);
454
			$sth->execute(array(':id' => $id));
455
		} catch(PDOException $e) {
456
			echo $e->getMessage();
457
			die;
458
		}
459
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
460
		return $spotter_array;
461
	}
462
463
        /**
464
	* Gets all the spotter information based on a particular ident
465
	*
466
	* @return Array the spotter information
467
	*
468
	*/
469
	public function getAllLiveTrackerDataByIdent($ident)
470
	{
471
		date_default_timezone_set('UTC');
472
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
473
		$query  = self::$global_query.' WHERE tracker_live.ident = :ident';
474
    		try {
475
			
476
			$sth = $this->db->prepare($query);
477
			$sth->execute(array(':ident' => $ident));
478
		} catch(PDOException $e) {
479
			echo $e->getMessage();
480
			die;
481
		}
482
		$spotter_array = $sth->fetchAll(PDO::FETCH_ASSOC);
483
		return $spotter_array;
484
	}
485
486
487
	/**
488
	* Deletes all info in the table
489
	*
490
	* @return String success or false
491
	*
492
	*/
493
	public function deleteLiveTrackerData()
494
	{
495
		global $globalDBdriver;
496
		if ($globalDBdriver == 'mysql') {
497
			//$query  = "DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE) >= tracker_live.date";
498
			$query  = 'DELETE FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(),INTERVAL 9 HOUR) >= tracker_live.date';
499
            		//$query  = "DELETE FROM tracker_live WHERE tracker_live.id IN (SELECT tracker_live.id FROM tracker_live INNER JOIN (SELECT l.famtrackid, max(l.date) as maxdate FROM tracker_live l GROUP BY l.famtrackid) s on tracker_live.famtrackid = s.famtrackid AND tracker_live.date = s.maxdate AND DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) >= tracker_live.date)";
500
		} else {
501
			$query  = "DELETE FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= tracker_live.date";
502
		}
503
        
504
    		try {
505
			
506
			$sth = $this->db->prepare($query);
507
			$sth->execute();
508
		} catch(PDOException $e) {
509
			return "error";
510
		}
511
512
		return "success";
513
	}
514
515
	/**
516
	* Deletes all info in the table for aircraft not seen since 2 HOUR
517
	*
518
	* @return String success or false
519
	*
520
	*/
521
	public function deleteLiveTrackerDataNotUpdated()
522
	{
523
		global $globalDBdriver, $globalDebug;
524
		if ($globalDBdriver == 'mysql') {
525
			//$query = 'SELECT famtrackid FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) >= tracker_live.date AND tracker_live.famtrackid NOT IN (SELECT famtrackid FROM tracker_live WHERE DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR) < tracker_live.date) LIMIT 800 OFFSET 0';
526
    			$query = "SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND DATE_SUB(UTC_TIMESTAMP(), INTERVAL 2 HOUR) >= s.max_date LIMIT 1200 OFFSET 0";
527
    			try {
528
				
529
				$sth = $this->db->prepare($query);
530
				$sth->execute();
531
			} catch(PDOException $e) {
532
				return "error";
533
			}
534
			$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
535
                        $i = 0;
536
                        $j =0;
537
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
538
			foreach($all as $row)
539
			{
540
				$i++;
541
				$j++;
542
				if ($j == 30) {
543
					if ($globalDebug) echo ".";
544
				    	try {
545
						
546
						$sth = $this->db->prepare(substr($query_delete,0,-1).")");
547
						$sth->execute();
548
					} catch(PDOException $e) {
549
						return "error";
550
					}
551
                                	$query_delete = 'DELETE FROM tracker_live WHERE famtrackid IN (';
552
                                	$j = 0;
553
				}
554
				$query_delete .= "'".$row['famtrackid']."',";
555
			}
556
			if ($i > 0) {
557
    				try {
558
					
559
					$sth = $this->db->prepare(substr($query_delete,0,-1).")");
560
					$sth->execute();
561
				} catch(PDOException $e) {
562
					return "error";
563
				}
564
			}
565
			return "success";
566
		} elseif ($globalDBdriver == 'pgsql') {
567
			//$query = "SELECT famtrackid FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' >= tracker_live.date AND tracker_live.famtrackid NOT IN (SELECT famtrackid FROM tracker_live WHERE NOW() AT TIME ZONE 'UTC' - INTERVAL '9 HOURS' < tracker_live.date) LIMIT 800 OFFSET 0";
568
    			//$query = "SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0";
569
    			$query = "DELETE FROM tracker_live WHERE famtrackid IN (SELECT tracker_live.famtrackid FROM tracker_live INNER JOIN (SELECT famtrackid,MAX(date) as max_date FROM tracker_live GROUP BY famtrackid) s ON s.famtrackid = tracker_live.famtrackid AND NOW() AT TIME ZONE 'UTC' - INTERVAL '2 HOURS' >= s.max_date LIMIT 800 OFFSET 0)";
570
    			try {
571
				
572
				$sth = $this->db->prepare($query);
573
				$sth->execute();
574
			} catch(PDOException $e) {
575
				return "error";
576
			}
577
/*			$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
578
                        $i = 0;
579
                        $j =0;
580
			$all = $sth->fetchAll(PDO::FETCH_ASSOC);
581
			foreach($all as $row)
582
			{
583
				$i++;
584
				$j++;
585
				if ($j == 100) {
586
					if ($globalDebug) echo ".";
587
				    	try {
588
						
589
						$sth = $this->db->query(substr($query_delete,0,-1).")");
590
						//$sth->execute();
591
					} catch(PDOException $e) {
592
						return "error";
593
					}
594
                                	$query_delete = "DELETE FROM tracker_live WHERE famtrackid IN (";
595
                                	$j = 0;
596
				}
597
				$query_delete .= "'".$row['famtrackid']."',";
598
			}
599
			if ($i > 0) {
600
    				try {
601
					
602
					$sth = $this->db->query(substr($query_delete,0,-1).")");
603
					//$sth->execute();
604
				} catch(PDOException $e) {
605
					return "error";
606
				}
607
			}
608
*/
609
			return "success";
610
		}
611
	}
612
613
	/**
614
	* Deletes all info in the table for an ident
615
	*
616
	* @return String success or false
617
	*
618
	*/
619
	public function deleteLiveTrackerDataByIdent($ident)
620
	{
621
		$ident = filter_var($ident, FILTER_SANITIZE_STRING);
622
		$query  = 'DELETE FROM tracker_live WHERE ident = :ident';
623
        
624
    		try {
625
			
626
			$sth = $this->db->prepare($query);
627
			$sth->execute(array(':ident' => $ident));
628
		} catch(PDOException $e) {
629
			return "error";
630
		}
631
632
		return "success";
633
	}
634
635
	/**
636
	* Deletes all info in the table for an id
637
	*
638
	* @return String success or false
639
	*
640
	*/
641
	public function deleteLiveTrackerDataById($id)
642
	{
643
		$id = filter_var($id, FILTER_SANITIZE_STRING);
644
		$query  = 'DELETE FROM tracker_live WHERE famtrackid = :id';
645
        
646
    		try {
647
			
648
			$sth = $this->db->prepare($query);
649
			$sth->execute(array(':id' => $id));
650
		} catch(PDOException $e) {
651
			return "error";
652
		}
653
654
		return "success";
655
	}
656
657
658
	/**
659
	* Gets the aircraft ident within the last hour
660
	*
661
	* @return String the ident
662
	*
663
	*/
664
	public function getIdentFromLastHour($ident)
665
	{
666
		global $globalDBdriver, $globalTimezone;
667
		if ($globalDBdriver == 'mysql') {
668
			$query  = 'SELECT tracker_live.ident FROM tracker_live 
669
				WHERE tracker_live.ident = :ident 
670
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 HOUR) 
671
				AND tracker_live.date < UTC_TIMESTAMP()';
672
			$query_data = array(':ident' => $ident);
673
		} else {
674
			$query  = "SELECT tracker_live.ident FROM tracker_live 
675
				WHERE tracker_live.ident = :ident 
676
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '1 HOURS'
677
				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
678
			$query_data = array(':ident' => $ident);
679
		}
680
		
681
		$sth = $this->db->prepare($query);
682
		$sth->execute($query_data);
683
		$ident_result='';
684
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
685
		{
686
			$ident_result = $row['ident'];
687
		}
688
		return $ident_result;
689
        }
690
691
	/**
692
	* Check recent aircraft
693
	*
694
	* @return String the ident
695
	*
696
	*/
697
	public function checkIdentRecent($ident)
698
	{
699
		global $globalDBdriver, $globalTimezone;
700
		if ($globalDBdriver == 'mysql') {
701
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
702
				WHERE tracker_live.ident = :ident 
703
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 MINUTE)'; 
704
//				AND tracker_live.date < UTC_TIMESTAMP()";
705
			$query_data = array(':ident' => $ident);
706
		} else {
707
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
708
				WHERE tracker_live.ident = :ident 
709
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '30 MINUTES'";
710
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
711
			$query_data = array(':ident' => $ident);
712
		}
713
		
714
		$sth = $this->db->prepare($query);
715
		$sth->execute($query_data);
716
		$ident_result='';
717
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
718
		{
719
			$ident_result = $row['famtrackid'];
720
		}
721
		return $ident_result;
722
        }
723
724
	/**
725
	* Check recent aircraft by id
726
	*
727
	* @return String the ident
728
	*
729
	*/
730
	public function checkIdRecent($id)
731
	{
732
		global $globalDBdriver, $globalTimezone;
733
		if ($globalDBdriver == 'mysql') {
734
			$query  = 'SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
735
				WHERE tracker_live.famtrackid = :id 
736
				AND tracker_live.date >= DATE_SUB(UTC_TIMESTAMP(),INTERVAL 10 HOUR)'; 
737
//				AND tracker_live.date < UTC_TIMESTAMP()";
738
			$query_data = array(':id' => $id);
739
		} else {
740
			$query  = "SELECT tracker_live.ident, tracker_live.famtrackid FROM tracker_live 
741
				WHERE tracker_live.famtrackid = :id 
742
				AND tracker_live.date >= now() AT TIME ZONE 'UTC' - INTERVAL '10 HOUR'";
743
//				AND tracker_live.date < now() AT TIME ZONE 'UTC'";
744
			$query_data = array(':id' => $id);
745
		}
746
		
747
		$sth = $this->db->prepare($query);
748
		$sth->execute($query_data);
749
		$ident_result='';
750
		while($row = $sth->fetch(PDO::FETCH_ASSOC))
751
		{
752
			$ident_result = $row['famtrackid'];
753
		}
754
		return $ident_result;
755
        }
756
757
	/**
758
	* Adds a new spotter data
759
	*
760
	* @param String $famtrackid the ID from flightaware
761
	* @param String $ident the flight ident
762
	* @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...
763
	* @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...
764
	* @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...
765
	* @return String success or false
766
	*
767
	*/
768
	public function addLiveTrackerData($famtrackid = '', $ident = '', $latitude = '', $longitude = '', $altitude = '', $heading = '', $groundspeed = '', $date = '', $putinarchive = false, $comment = '', $type = '',$noarchive = false,$format_source = '', $source_name = '', $over_country = '')
0 ignored issues
show
Unused Code introduced by
The parameter $putinarchive is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $noarchive 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...
769
	{
770
		global $globalURL, $globalArchive, $globalDebug;
771
		$Common = new Common();
772
		date_default_timezone_set('UTC');
773
774
		//getting the airline information
775
		if ($ident != '')
776
		{
777
			if (!is_string($ident))
778
			{
779
				return false;
780
			} 
781
		}
782
783
784
		if ($latitude != '')
785
		{
786
			if (!is_numeric($latitude))
787
			{
788
				return false;
789
			}
790
		} else return '';
791
792
		if ($longitude != '')
793
		{
794
			if (!is_numeric($longitude))
795
			{
796
				return false;
797
			}
798
		} else return '';
799
800
		if ($altitude != '')
801
		{
802
			if (!is_numeric($altitude))
803
			{
804
				return false;
805
			}
806
		} else $altitude = 0;
807
808
		if ($heading != '')
809
		{
810
			if (!is_numeric($heading))
811
			{
812
				return false;
813
			}
814
		} else $heading = 0;
815
816
		if ($groundspeed != '')
817
		{
818
			if (!is_numeric($groundspeed))
819
			{
820
				return false;
821
			}
822
		} else $groundspeed = 0;
823
		date_default_timezone_set('UTC');
824
		if ($date == '') $date = date("Y-m-d H:i:s", time());
825
826
        
827
		$famtrackid = filter_var($famtrackid,FILTER_SANITIZE_STRING);
828
		$ident = filter_var($ident,FILTER_SANITIZE_STRING);
829
		$latitude = filter_var($latitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
830
		$longitude = filter_var($longitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
831
		$altitude = filter_var($altitude,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
832
		$heading = filter_var($heading,FILTER_SANITIZE_NUMBER_INT);
833
		$groundspeed = filter_var($groundspeed,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
834
		$format_source = filter_var($format_source,FILTER_SANITIZE_STRING);
835
		$source_name = filter_var($source_name,FILTER_SANITIZE_STRING);
836
		$over_country = filter_var($over_country,FILTER_SANITIZE_STRING);
837
		$comment = filter_var($comment,FILTER_SANITIZE_STRING);
838
		$type = filter_var($type,FILTER_SANITIZE_STRING);
839
840
            	if ($groundspeed == '' || $Common->isInteger($groundspeed) === false ) $groundspeed = 0;
841
            	if ($heading == '' || $Common->isInteger($heading) === false ) $heading = 0;
842
            	
843
		$query  = 'INSERT INTO tracker_live (famtrackid, ident, latitude, longitude, altitude, heading, ground_speed, date, format_source, source_name, over_country, comment, type) 
844
		VALUES (:famtrackid,:ident,:latitude,:longitude,:altitude,:heading,:groundspeed,:date,:format_source, :source_name, :over_country,:comment,:type)';
845
846
		$query_values = array(':famtrackid' => $famtrackid,':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':altitude' => $altitude,':heading' => $heading,':groundspeed' => $groundspeed,':date' => $date, ':format_source' => $format_source, ':source_name' => $source_name, ':over_country' => $over_country,':comment' => $comment,':type' => $type);
847
		try {
848
			
849
			$sth = $this->db->prepare($query);
850
			$sth->execute($query_values);
851
                } catch(PDOException $e) {
852
                	return "error : ".$e->getMessage();
853
                }
854
		/*
855
		if (isset($globalArchive) && $globalArchive && $putinarchive && $noarchive !== true) {
856
		    if ($globalDebug) echo '(Add to SBS archive : ';
857
		    $TrackerArchive = new TrackerArchive($this->db);
858
		    $result =  $TrackerArchive->addTrackerArchiveData($famtrackid, $ident, $registration, $airline_name, $airline_icao, $airline_country, $airline_type, $aircraft_icao, $aircraft_shadow, $aircraft_name, $aircraft_manufacturer, $departure_airport_icao, $departure_airport_name, $departure_airport_city, $departure_airport_country, $departure_airport_time,$arrival_airport_icao, $arrival_airport_name, $arrival_airport_city, $arrival_airport_country, $arrival_airport_time, $route_stop, $date,$latitude, $longitude, $waypoints, $altitude, $heading, $groundspeed, $squawk, $ModeS, $pilot_id, $pilot_name,$verticalrate,$format_source,$source_name, $over_country);
859
		    if ($globalDebug) echo $result.')';
860
		}
861
		*/
862
		return "success";
863
864
	}
865
866
	public function getOrderBy()
867
	{
868
		$orderby = array("aircraft_asc" => array("key" => "aircraft_asc", "value" => "Aircraft Type - ASC", "sql" => "ORDER BY tracker_live.aircraft_icao ASC"), "aircraft_desc" => array("key" => "aircraft_desc", "value" => "Aircraft Type - DESC", "sql" => "ORDER BY tracker_live.aircraft_icao DESC"),"manufacturer_asc" => array("key" => "manufacturer_asc", "value" => "Aircraft Manufacturer - ASC", "sql" => "ORDER BY tracker_live.aircraft_manufacturer ASC"), "manufacturer_desc" => array("key" => "manufacturer_desc", "value" => "Aircraft Manufacturer - DESC", "sql" => "ORDER BY tracker_live.aircraft_manufacturer DESC"),"airline_name_asc" => array("key" => "airline_name_asc", "value" => "Airline Name - ASC", "sql" => "ORDER BY tracker_live.airline_name ASC"), "airline_name_desc" => array("key" => "airline_name_desc", "value" => "Airline Name - DESC", "sql" => "ORDER BY tracker_live.airline_name DESC"), "ident_asc" => array("key" => "ident_asc", "value" => "Ident - ASC", "sql" => "ORDER BY tracker_live.ident ASC"), "ident_desc" => array("key" => "ident_desc", "value" => "Ident - DESC", "sql" => "ORDER BY tracker_live.ident DESC"), "airport_departure_asc" => array("key" => "airport_departure_asc", "value" => "Departure Airport - ASC", "sql" => "ORDER BY tracker_live.departure_airport_city ASC"), "airport_departure_desc" => array("key" => "airport_departure_desc", "value" => "Departure Airport - DESC", "sql" => "ORDER BY tracker_live.departure_airport_city DESC"), "airport_arrival_asc" => array("key" => "airport_arrival_asc", "value" => "Arrival Airport - ASC", "sql" => "ORDER BY tracker_live.arrival_airport_city ASC"), "airport_arrival_desc" => array("key" => "airport_arrival_desc", "value" => "Arrival Airport - DESC", "sql" => "ORDER BY tracker_live.arrival_airport_city DESC"), "date_asc" => array("key" => "date_asc", "value" => "Date - ASC", "sql" => "ORDER BY tracker_live.date ASC"), "date_desc" => array("key" => "date_desc", "value" => "Date - DESC", "sql" => "ORDER BY tracker_live.date DESC"));
869
		return $orderby;
870
	}
871
872
}
873
874
875
?>
876