Completed
Push — master ( 919fdf...02daa8 )
by Yannick
06:48
created

update_db::update_ModeS_fam()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 15
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 30
nop 0
dl 0
loc 15
rs 8.2222
c 0
b 0
f 0
1
<?php
2
//require_once('libs/simple_html_dom.php');
3
require(dirname(__FILE__).'/../require/settings.php');
4
require_once(dirname(__FILE__).'/../require/class.Common.php');
5
require_once(dirname(__FILE__).'/../require/class.Connection.php');
6
7
$tmp_dir = dirname(__FILE__).'/tmp/';
8
//$globalDebug = true;
9
//$globalTransaction = true;
10
class update_db {
11
	public static $db_sqlite;
12
13
	public static function download($url, $file, $referer = '') {
14
		$fp = fopen($file, 'w+');
15
		$ch = curl_init();
16
		curl_setopt($ch, CURLOPT_URL, $url);
17
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
18
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
19
		if ($referer != '') curl_setopt($ch, CURLOPT_REFERER, $referer);
20
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
21
		curl_setopt($ch, CURLOPT_FILE, $fp);
22
		curl_exec($ch);
23
		curl_close($ch);
24
		fclose($fp);
25
	}
26
27
	public static function gunzip($in_file,$out_file_name = '') {
28
		//echo $in_file.' -> '.$out_file_name."\n";
29
		$buffer_size = 4096; // read 4kb at a time
30
		if ($out_file_name == '') $out_file_name = str_replace('.gz', '', $in_file); 
31
		if ($in_file != '' && file_exists($in_file)) {
32
			// PHP version of Ubuntu use gzopen64 instead of gzopen
33
			if (function_exists('gzopen')) $file = gzopen($in_file,'rb');
34
			elseif (function_exists('gzopen64')) $file = gzopen64($in_file,'rb');
35
			else {
36
				echo 'gzopen not available';
37
				die;
38
			}
39
			$out_file = fopen($out_file_name, 'wb'); 
40
			while(!gzeof($file)) {
41
				fwrite($out_file, gzread($file, $buffer_size));
42
			}  
43
			fclose($out_file);
44
			gzclose($file);
45
		}
46
	}
47
48
	public static function unzip($in_file) {
49
		if ($in_file != '' && file_exists($in_file)) {
50
			$path = pathinfo(realpath($in_file), PATHINFO_DIRNAME);
51
			$zip = new ZipArchive;
52
			$res = $zip->open($in_file);
53
			if ($res === TRUE) {
54
				$zip->extractTo($path);
55
				$zip->close();
56
			} else return false;
57
		} else return false;
58
	}
59
	
60
	public static function connect_sqlite($database) {
61
		try {
62
			self::$db_sqlite = new PDO('sqlite:'.$database);
63
			self::$db_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
64
		} catch(PDOException $e) {
65
			return "error : ".$e->getMessage();
66
		}
67
	}
68
	
69
	public static function retrieve_route_sqlite_to_dest($database_file) {
70
		global $globalDebug, $globalTransaction;
71
		//$query = 'TRUNCATE TABLE routes';
72
		if ($globalDebug) echo " - Delete previous routes from DB -";
73
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
74
		$Connection = new Connection();
75
		try {
76
			//$Connection = new Connection();
77
			$sth = $Connection->db->prepare($query);
78
                        $sth->execute(array(':source' => $database_file));
79
                } catch(PDOException $e) {
80
                        return "error : ".$e->getMessage();
81
                }
82
83
    		if ($globalDebug) echo " - Add routes to DB -";
84
    		update_db::connect_sqlite($database_file);
85
		//$query = 'select Route.RouteID, Route.callsign, operator.Icao AS operator_icao, FromAir.Icao AS FromAirportIcao, ToAir.Icao AS ToAirportIcao from Route inner join operator ON Route.operatorId = operator.operatorId LEFT JOIN Airport AS FromAir ON route.FromAirportId = FromAir.AirportId LEFT JOIN Airport AS ToAir ON ToAir.AirportID = route.ToAirportID';
86
		$query = "select Route.RouteID, Route.callsign, operator.Icao AS operator_icao, FromAir.Icao AS FromAirportIcao, ToAir.Icao AS ToAirportIcao, rstp.allstop AS AllStop from Route inner join operator ON Route.operatorId = operator.operatorId LEFT JOIN Airport AS FromAir ON route.FromAirportId = FromAir.AirportId LEFT JOIN Airport AS ToAir ON ToAir.AirportID = route.ToAirportID LEFT JOIN (select RouteId,GROUP_CONCAT(icao,' ') as allstop from routestop left join Airport as air ON routestop.AirportId = air.AirportID group by RouteID) AS rstp ON Route.RouteID = rstp.RouteID";
87
		try {
88
                        $sth = update_db::$db_sqlite->prepare($query);
89
                        $sth->execute();
90
                } catch(PDOException $e) {
91
                        return "error : ".$e->getMessage();
92
                }
93
		//$query_dest = 'INSERT INTO routes (`RouteID`,`CallSign`,`Operator_ICAO`,`FromAirport_ICAO`,`ToAirport_ICAO`,`RouteStop`,`Source`) VALUES (:RouteID, :CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
94
		$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,ToAirport_ICAO,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO, :ToAirport_ICAO, :routestop, :source)';
95
		$Connection = new Connection();
96
		$sth_dest = $Connection->db->prepare($query_dest);
97
		try {
98
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
99
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
100
				//$query_dest_values = array(':RouteID' => $values['RouteId'],':CallSign' => $values['Callsign'],':Operator_ICAO' => $values['operator_icao'],':FromAirport_ICAO' => $values['FromAirportIcao'],':ToAirport_ICAO' => $values['ToAirportIcao'],':routestop' => $values['AllStop'],':source' => $database_file);
101
				$query_dest_values = array(':CallSign' => $values['Callsign'],':Operator_ICAO' => $values['operator_icao'],':FromAirport_ICAO' => $values['FromAirportIcao'],':ToAirport_ICAO' => $values['ToAirportIcao'],':routestop' => $values['AllStop'],':source' => $database_file);
102
				$sth_dest->execute($query_dest_values);
103
            		}
104
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
105
		} catch(PDOException $e) {
106
			if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
107
			return "error : ".$e->getMessage();
108
		}
109
                return '';
110
	}
111
	public static function retrieve_route_oneworld($database_file) {
112
		global $globalDebug, $globalTransaction;
113
		//$query = 'TRUNCATE TABLE routes';
114
		if ($globalDebug) echo " - Delete previous routes from DB -";
115
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
116
		$Connection = new Connection();
117
		try {
118
			//$Connection = new Connection();
119
			$sth = $Connection->db->prepare($query);
120
                        $sth->execute(array(':source' => 'oneworld'));
121
                } catch(PDOException $e) {
122
                        return "error : ".$e->getMessage();
123
                }
124
125
    		if ($globalDebug) echo " - Add routes to DB -";
126
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
127
		$Spotter = new Spotter();
128
		if ($fh = fopen($database_file,"r")) {
129
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
130
			$Connection = new Connection();
131
			$sth_dest = $Connection->db->prepare($query_dest);
132
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
133
			while (!feof($fh)) {
134
				$line = fgetcsv($fh,9999,',');
135
				if ($line[0] != '') {
136
					if (($line[2] == '-' || ($line[2] != '-' && (strtotime($line[2]) > time()))) && ($line[3] == '-' || ($line[3] != '-' && (strtotime($line[3]) < time())))) {
137
						try {
138
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[7]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[5],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[6],':routestop' => '',':source' => 'oneworld');
139
							$sth_dest->execute($query_dest_values);
140
						} catch(PDOException $e) {
141
							if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
142
							return "error : ".$e->getMessage();
143
						}
144
					}
145
				}
146
			}
147
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
148
		}
149
                return '';
150
	}
151
	
152
	public static function retrieve_route_skyteam($database_file) {
153
		global $globalDebug, $globalTransaction;
154
		//$query = 'TRUNCATE TABLE routes';
155
		if ($globalDebug) echo " - Delete previous routes from DB -";
156
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
157
		$Connection = new Connection();
158
		try {
159
			//$Connection = new Connection();
160
			$sth = $Connection->db->prepare($query);
161
                        $sth->execute(array(':source' => 'skyteam'));
162
                } catch(PDOException $e) {
163
                        return "error : ".$e->getMessage();
164
                }
165
166
    		if ($globalDebug) echo " - Add routes to DB -";
167
168
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
169
		$Spotter = new Spotter();
170
		if ($fh = fopen($database_file,"r")) {
171
			$query_dest = 'INSERT INTO routes (CallSign,Operator_ICAO,FromAirport_ICAO,FromAirport_Time,ToAirport_ICAO,ToAirport_Time,RouteStop,Source) VALUES (:CallSign, :Operator_ICAO, :FromAirport_ICAO,:FromAirport_Time, :ToAirport_ICAO, :ToAirport_Time,:routestop, :source)';
172
			$Connection = new Connection();
173
			$sth_dest = $Connection->db->prepare($query_dest);
174
			try {
175
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
176
				while (!feof($fh)) {
177
					$line = fgetcsv($fh,9999,',');
178
					if ($line[0] != '') {
179
						$datebe = explode('  -  ',$line[2]);
180
						if (strtotime($datebe[0]) > time() && strtotime($datebe[1]) < time()) {
181
							$query_dest_values = array(':CallSign' => str_replace('*','',$line[6]),':Operator_ICAO' => '',':FromAirport_ICAO' => $Spotter->getAirportICAO($line[0]),':FromAirport_Time' => $line[4],':ToAirport_ICAO' => $Spotter->getAirportICAO($line[1]),':ToAirport_Time' => $line[5],':routestop' => '',':source' => 'skyteam');
182
							$sth_dest->execute($query_dest_values);
183
						}
184
					}
185
				}
186
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
187
			} catch(PDOException $e) {
188
				if ($globalTransaction) $Connection->db->rollBack(); 
0 ignored issues
show
Bug introduced by
The method rollBack cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
189
				return "error : ".$e->getMessage();
190
			}
191
		}
192
                return '';
193
	}
194
	public static function retrieve_modes_sqlite_to_dest($database_file) {
195
		global $globalTransaction;
196
		//$query = 'TRUNCATE TABLE aircraft_modes';
197
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
198
		try {
199
			$Connection = new Connection();
200
			$sth = $Connection->db->prepare($query);
201
                        $sth->execute(array(':source' => $database_file));
202
                } catch(PDOException $e) {
203
                        return "error : ".$e->getMessage();
204
                }
205
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
206
		try {
207
			$Connection = new Connection();
208
			$sth = $Connection->db->prepare($query);
209
                        $sth->execute(array(':source' => $database_file));
210
                } catch(PDOException $e) {
211
                        return "error : ".$e->getMessage();
212
                }
213
214
    		update_db::connect_sqlite($database_file);
215
		$query = 'select * from Aircraft';
216
		try {
217
                        $sth = update_db::$db_sqlite->prepare($query);
218
                        $sth->execute();
219
                } catch(PDOException $e) {
220
                        return "error : ".$e->getMessage();
221
                }
222
		//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
223
		$query_dest = 'INSERT INTO aircraft_modes (LastModified, ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type,:source)';
224
		
225
		$query_dest_owner = 'INSERT INTO aircraft_owner (registration,owner,Source) VALUES (:registration,:owner,:source)';
226
		
227
		$Connection = new Connection();
228
		$sth_dest = $Connection->db->prepare($query_dest);
229
		$sth_dest_owner = $Connection->db->prepare($query_dest_owner);
230
		try {
231
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
232
            		while ($values = $sth->fetch(PDO::FETCH_ASSOC)) {
233
			//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
234
				if ($values['UserString4'] == 'M') $type = 'military';
235
				else $type = null;
236
				$query_dest_values = array(':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file,':type' => $type);
237
				$sth_dest->execute($query_dest_values);
238
				if ($values['RegisteredOwners'] != '' && $values['RegisteredOwners'] != NULL && $values['RegisteredOwners'] != 'Private') {
239
				    $query_dest_owner_values = array(':registration' => $values['Registration'],':source' => $database_file,':owner' => $values['RegisteredOwners']);
240
				    $sth_dest_owner->execute($query_dest_owner_values);
241
				}
242
            		}
243
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
244
		} catch(PDOException $e) {
245
			return "error : ".$e->getMessage();
246
		}
247
248
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
249
		try {
250
			$Connection = new Connection();
251
			$sth = $Connection->db->prepare($query);
252
                        $sth->execute(array(':source' => $database_file));
253
                } catch(PDOException $e) {
254
                        return "error : ".$e->getMessage();
255
                }
256
		return '';
257
	}
258
259
	public static function retrieve_modes_flarmnet($database_file) {
260
		global $globalTransaction;
261
		$Common = new Common();
262
		//$query = 'TRUNCATE TABLE aircraft_modes';
263
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
264
		try {
265
			$Connection = new Connection();
266
			$sth = $Connection->db->prepare($query);
267
                        $sth->execute(array(':source' => $database_file));
268
                } catch(PDOException $e) {
269
                        return "error : ".$e->getMessage();
270
                }
271
		
272
		if ($fh = fopen($database_file,"r")) {
273
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
274
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
275
		
276
			$Connection = new Connection();
277
			$sth_dest = $Connection->db->prepare($query_dest);
278
			try {
279
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
280
            			while (!feof($fh)) {
281
            				$values = array();
282
            				$line = $Common->hex2str(fgets($fh,9999));
283
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
284
            				$values['ModeS'] = substr($line,0,6);
285
            				$values['Registration'] = trim(substr($line,69,6));
286
            				$aircraft_name = trim(substr($line,48,6));
287
            				// Check if we can find ICAO, else set it to GLID
288
            				$aircraft_name_split = explode(' ',$aircraft_name);
289
            				$search_more = '';
290
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
291
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
292
            				$sth_search = $Connection->db->prepare($query_search);
293
					try {
294
                                    		$sth_search->execute();
295
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
296
	            				//if (count($result) > 0) {
297
	            				if (isset($result['icao']) && $result['icao'] != '') {
298
	            				    $values['ICAOTypeCode'] = $result['icao'];
299
	            				} 
300
					} catch(PDOException $e) {
301
						return "error : ".$e->getMessage();
302
					}
303
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
304
					// Add data to db
305
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000') {
306
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
307
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
308
						//print_r($query_dest_values);
309
						$sth_dest->execute($query_dest_values);
310
					}
311
				}
312
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
313
			} catch(PDOException $e) {
314
				return "error : ".$e->getMessage();
315
			}
316
		}
317
318
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
319
		try {
320
			$Connection = new Connection();
321
			$sth = $Connection->db->prepare($query);
322
                        $sth->execute(array(':source' => $database_file));
323
                } catch(PDOException $e) {
324
                        return "error : ".$e->getMessage();
325
                }
326
		return '';
327
	}
328
329
	public static function retrieve_modes_ogn($database_file) {
330
		global $globalTransaction;
331
		//$query = 'TRUNCATE TABLE aircraft_modes';
332
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
333
		try {
334
			$Connection = new Connection();
335
			$sth = $Connection->db->prepare($query);
336
                        $sth->execute(array(':source' => $database_file));
337
                } catch(PDOException $e) {
338
                        return "error : ".$e->getMessage();
339
                }
340
		
341
		if ($fh = fopen($database_file,"r")) {
342
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
343
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
344
		
345
			$Connection = new Connection();
346
			$sth_dest = $Connection->db->prepare($query_dest);
347
			try {
348
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
349
				$tmp = fgetcsv($fh,9999,',',"'");
0 ignored issues
show
Unused Code introduced by
$tmp 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...
350
            			while (!feof($fh)) {
351
            				$line = fgetcsv($fh,9999,',',"'");
352
            				
353
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
354
					//print_r($line);
355
            				$values['ModeS'] = $line[1];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$values was never initialized. Although not strictly required by PHP, it is generally a good practice to add $values = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
356
            				$values['Registration'] = $line[3];
0 ignored issues
show
Bug introduced by
The variable $values does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
357
            				$aircraft_name = $line[2];
358
            				// Check if we can find ICAO, else set it to GLID
359
            				$aircraft_name_split = explode(' ',$aircraft_name);
360
            				$search_more = '';
361
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
362
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
363
            				$sth_search = $Connection->db->prepare($query_search);
364
					try {
365
                                    		$sth_search->execute();
366
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
367
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
368
					} catch(PDOException $e) {
369
						return "error : ".$e->getMessage();
370
					}
371
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
372
					// Add data to db
373
					if ($values['ModeS'] != '' && $values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
374
						//$query_dest_values = array(':AircraftID' => $values['AircraftID'],':FirstCreated' => $values['FirstCreated'],':LastModified' => $values['LastModified'],':ModeS' => $values['ModeS'],':ModeSCountry' => $values['ModeSCountry'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':SerialNo' => $values['SerialNo'], ':OperatorFlagCode' => $values['OperatorFlagCode'], ':Manufacturer' => $values['Manufacturer'], ':Type' => $values['Type'], ':FirstRegDate' => $values['FirstRegDate'], ':CurrentRegDate' => $values['CurrentRegDate'], ':Country' => $values['Country'], ':PreviousID' => $values['PreviousID'], ':DeRegDate' => $values['DeRegDate'], ':Status' => $values['Status'], ':PopularName' => $values['PopularName'],':GenericName' => $values['GenericName'],':AircraftClass' => $values['AircraftClass'], ':Engines' => $values['Engines'], ':OwnershipStatus' => $values['OwnershipStatus'],':RegisteredOwners' => $values['RegisteredOwners'],':MTOW' => $values['MTOW'], ':TotalHours' => $values['TotalHours'],':YearBuilt' => $values['YearBuilt'], ':CofACategory' => $values['CofACategory'], ':CofAExpiry' => $values['CofAExpiry'], ':UserNotes' => $values['UserNotes'], ':Interested' => $values['Interested'], ':UserTag' => $values['UserTag'], ':InfoUrl' => $values['InfoURL'], ':PictureUrl1' => $values['PictureURL1'], ':PictureUrl2' => $values['PictureURL2'], ':PictureUrl3' => $values['PictureURL3'], ':UserBool1' => $values['UserBool1'], ':UserBool2' => $values['UserBool2'], ':UserBool3' => $values['UserBool3'], ':UserBool4' => $values['UserBool4'], ':UserBool5' => $values['UserBool5'], ':UserString1' => $values['UserString1'], ':UserString2' => $values['UserString2'], ':UserString3' => $values['UserString3'], ':UserString4' => $values['UserString4'], ':UserString5' => $values['UserString5'], ':UserInt1' => $values['UserInt1'], ':UserInt2' => $values['UserInt2'], ':UserInt3' => $values['UserInt3'], ':UserInt4' => $values['UserInt4'], ':UserInt5' => $values['UserInt5']);
375
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
376
						//print_r($query_dest_values);
377
						$sth_dest->execute($query_dest_values);
378
					}
379
				}
380
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
381
			} catch(PDOException $e) {
382
				return "error : ".$e->getMessage();
383
			}
384
		}
385
386
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
387
		try {
388
			$Connection = new Connection();
389
			$sth = $Connection->db->prepare($query);
390
                        $sth->execute(array(':source' => $database_file));
391
                } catch(PDOException $e) {
392
                        return "error : ".$e->getMessage();
393
                }
394
		return '';
395
	}
396
397
	public static function retrieve_owner($database_file,$country = 'F') {
398
		global $globalTransaction;
399
		//$query = 'TRUNCATE TABLE aircraft_modes';
400
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
401
		try {
402
			$Connection = new Connection();
403
			$sth = $Connection->db->prepare($query);
404
                        $sth->execute(array(':source' => $database_file));
405
                } catch(PDOException $e) {
406
                        return "error : ".$e->getMessage();
407
                }
408
		
409
		if ($fh = fopen($database_file,"r")) {
410
			//$query_dest = 'INSERT INTO aircraft_modes (`AircraftID`,`FirstCreated`,`LastModified`, `ModeS`,`ModeSCountry`,`Registration`,`ICAOTypeCode`,`SerialNo`, `OperatorFlagCode`, `Manufacturer`, `Type`, `FirstRegDate`, `CurrentRegDate`, `Country`, `PreviousID`, `DeRegDate`, `Status`, `PopularName`,`GenericName`,`AircraftClass`, `Engines`, `OwnershipStatus`,`RegisteredOwners`,`MTOW`, `TotalHours`, `YearBuilt`, `CofACategory`, `CofAExpiry`, `UserNotes`, `Interested`, `UserTag`, `InfoUrl`, `PictureUrl1`, `PictureUrl2`, `PictureUrl3`, `UserBool1`, `UserBool2`, `UserBool3`, `UserBool4`, `UserBool5`, `UserString1`, `UserString2`, `UserString3`, `UserString4`, `UserString5`, `UserInt1`, `UserInt2`, `UserInt3`, `UserInt4`, `UserInt5`) VALUES (:AircraftID,:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:SerialNo, :OperatorFlagCode, :Manufacturer, :Type, :FirstRegDate, :CurrentRegDate, :Country, :PreviousID, :DeRegDate, :Status, :PopularName,:GenericName,:AircraftClass, :Engines, :OwnershipStatus,:RegisteredOwners,:MTOW, :TotalHours,:YearBuilt, :CofACategory, :CofAExpiry, :UserNotes, :Interested, :UserTag, :InfoUrl, :PictureUrl1, :PictureUrl2, :PictureUrl3, :UserBool1, :UserBool2, :UserBool3, :UserBool4, :UserBool5, :UserString1, :UserString2, :UserString3, :UserString4, :UserString5, :UserInt1, :UserInt2, :UserInt3, :UserInt4, :UserInt5)';
411
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
412
		
413
			$Connection = new Connection();
414
			$sth_dest = $Connection->db->prepare($query_dest);
415
			try {
416
				if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
417
				$tmp = fgetcsv($fh,9999,',','"');
0 ignored issues
show
Unused Code introduced by
$tmp 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...
418
            			while (!feof($fh)) {
419
            				$line = fgetcsv($fh,9999,',','"');
420
            				$values = array();
421
            				//print_r($line);
422
            				if ($country == 'F') {
423
            				    $values['registration'] = $line[0];
424
            				    $values['base'] = $line[4];
425
            				    $values['owner'] = $line[5];
426
            				    if ($line[6] == '') $values['date_first_reg'] = null;
427
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
428
					    $values['cancel'] = $line[7];
429
					} elseif ($country == 'EI') {
430
					    // TODO : add modeS & reg to aircraft_modes
431
            				    $values['registration'] = $line[0];
432
            				    $values['base'] = $line[3];
433
            				    $values['owner'] = $line[2];
434
            				    if ($line[1] == '') $values['date_first_reg'] = null;
435
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
436
					    $values['cancel'] = '';
437
					} elseif ($country == 'HB') {
438
					    // TODO : add modeS & reg to aircraft_modes
439
            				    $values['registration'] = $line[0];
440
            				    $values['base'] = null;
441
            				    $values['owner'] = $line[5];
442
            				    $values['date_first_reg'] = null;
443
					    $values['cancel'] = '';
444
					} elseif ($country == 'OK') {
445
					    // TODO : add modeS & reg to aircraft_modes
446
            				    $values['registration'] = $line[3];
447
            				    $values['base'] = null;
448
            				    $values['owner'] = $line[5];
449
            				    if ($line[18] == '') $values['date_first_reg'] = null;
450
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
451
					    $values['cancel'] = '';
452
					} elseif ($country == 'VH') {
453
					    // TODO : add modeS & reg to aircraft_modes
454
            				    $values['registration'] = $line[0];
455
            				    $values['base'] = null;
456
            				    $values['owner'] = $line[12];
457
            				    if ($line[28] == '') $values['date_first_reg'] = null;
458
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
459
460
					    $values['cancel'] = $line[39];
461
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
462
            				    $values['registration'] = $line[0];
463
            				    $values['base'] = null;
464
            				    $values['owner'] = $line[4];
465
            				    $values['date_first_reg'] = null;
466
					    $values['cancel'] = '';
467
					} elseif ($country == 'CC') {
468
            				    $values['registration'] = $line[0];
469
            				    $values['base'] = null;
470
            				    $values['owner'] = $line[6];
471
            				    $values['date_first_reg'] = null;
472
					    $values['cancel'] = '';
473
					} elseif ($country == 'HJ') {
474
            				    $values['registration'] = $line[0];
475
            				    $values['base'] = null;
476
            				    $values['owner'] = $line[8];
477
            				    if ($line[7] == '') $values['date_first_reg'] = null;
478
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
479
					    $values['cancel'] = '';
480
					} elseif ($country == 'PP') {
481
            				    $values['registration'] = $line[0];
482
            				    $values['base'] = null;
483
            				    $values['owner'] = $line[4];
484
            				    if ($line[6] == '') $values['date_first_reg'] = null;
485
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
486
					    $values['cancel'] = $line[7];
487
					} elseif ($country == 'E7') {
488
            				    $values['registration'] = $line[0];
489
            				    $values['base'] = null;
490
            				    $values['owner'] = $line[4];
491
            				    if ($line[5] == '') $values['date_first_reg'] = null;
492
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
493
					    $values['cancel'] = '';
494
					} elseif ($country == '8Q') {
495
            				    $values['registration'] = $line[0];
496
            				    $values['base'] = null;
497
            				    $values['owner'] = $line[3];
498
            				    if ($line[7] == '') $values['date_first_reg'] = null;
499
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
500
					    $values['cancel'] = '';
501
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
502
            				    $values['registration'] = $line[0];
503
            				    $values['base'] = null;
504
            				    $values['owner'] = $line[3];
505
            				    $values['date_first_reg'] = null;
506
					    $values['cancel'] = '';
507
					}
508
					if ($values['cancel'] == '' && $values['registration'] != null) {
509
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
510
						$sth_dest->execute($query_dest_values);
511
					}
512
				}
513
				if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
514
			} catch(PDOException $e) {
515
				return "error : ".$e->getMessage();
516
			}
517
		}
518
		return '';
519
	}
520
521
	/*
522
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
523
	*/
524
	public static function update_airports() {
525
		global $tmp_dir, $globalTransaction, $globalDebug;
526
527
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
528
		$db = sparql_connect('http://dbpedia.org/sparql');
0 ignored issues
show
Unused Code introduced by
$db 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...
529
		$query = '
530
		    PREFIX dbo: <http://dbpedia.org/ontology/>
531
		    PREFIX dbp: <http://dbpedia.org/property/>
532
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
533
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
534
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
535
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
536
		    FROM <http://dbpedia.org>
537
		    WHERE {
538
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
539
540
			OPTIONAL {
541
			    ?airport dbo:icaoLocationIdentifier ?icao .
542
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
543
			}
544
545
			OPTIONAL {
546
			    ?airport dbo:iataLocationIdentifier ?iata .
547
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
548
			}
549
550
			OPTIONAL {
551
			    ?airport dbo:locationIdentifier ?lid .
552
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
553
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
554
			    OPTIONAL {
555
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
556
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
557
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
558
			    }
559
			    FILTER (!bound(?other_icao))
560
			}
561
562
			OPTIONAL {
563
			    ?airport dbo:faaLocationIdentifier ?faa .
564
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
565
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
566
			    OPTIONAL {
567
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
568
				?airport_x dbo:iataLocationIdentifier ?other_iata .
569
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
570
			    }
571
			    FILTER (!bound(?other_iata))
572
			}
573
574
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
575
	
576
			OPTIONAL {
577
			    ?airport rdfs:label ?name
578
			    FILTER (lang(?name) = "en")
579
			}
580
    
581
			OPTIONAL {
582
			    ?airport foaf:homepage ?homepage
583
			}
584
		    
585
			OPTIONAL {
586
			    ?airport dbp:coordinatesRegion ?country
587
			}
588
    
589
			OPTIONAL {
590
			    ?airport dbp:type ?type
591
			}
592
			
593
			OPTIONAL {
594
			    ?airport dbo:elevation ?altitude
595
			}
596
			OPTIONAL {
597
			    ?airport dbp:image ?image
598
			}
599
600
			{
601
			    ?airport geo:lat ?latitude .
602
			    ?airport geo:long ?longitude .
603
			    FILTER (datatype(?latitude) = xsd:float)
604
			    FILTER (datatype(?longitude) = xsd:float)
605
			} UNION {
606
			    ?airport geo:lat ?latitude .
607
			    ?airport geo:long ?longitude .
608
			    FILTER (datatype(?latitude) = xsd:double)
609
			    FILTER (datatype(?longitude) = xsd:double)
610
			    OPTIONAL {
611
				?airport geo:lat ?lat_f .
612
				?airport geo:long ?long_f .
613
				FILTER (datatype(?lat_f) = xsd:float)
614
				FILTER (datatype(?long_f) = xsd:float)
615
			    }
616
			    FILTER (!bound(?lat_f) && !bound(?long_f))
617
			}
618
619
		    }
620
		    ORDER BY ?airport
621
		';
622
		$result = sparql_query($query);
623
  
624
		$query = 'TRUNCATE TABLE airport';
625
		try {
626
			$Connection = new Connection();
627
			$sth = $Connection->db->prepare($query);
628
                        $sth->execute();
629
                } catch(PDOException $e) {
630
                        return "error : ".$e->getMessage();
631
                }
632
633
634
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
635
		try {
636
			$Connection = new Connection();
637
			$sth = $Connection->db->prepare($query);
638
                        $sth->execute();
639
                } catch(PDOException $e) {
640
                        return "error : ".$e->getMessage();
641
                }
642
643
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
644
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
645
		$Connection = new Connection();
646
		$sth_dest = $Connection->db->prepare($query_dest);
647
		if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
648
  
649
		$i = 0;
650
		while($row = sparql_fetch_array($result))
651
		{
652
			if ($i >= 1) {
653
			//print_r($row);
654
			if (!isset($row['iata'])) $row['iata'] = '';
655
			if (!isset($row['icao'])) $row['icao'] = '';
656
			if (!isset($row['type'])) $row['type'] = '';
657
			if (!isset($row['altitude'])) $row['altitude'] = '';
658
			if (isset($row['city_bis'])) {
659
				$row['city'] = $row['city_bis'];
660
			}
661
			if (!isset($row['city'])) $row['city'] = '';
662
			if (!isset($row['country'])) $row['country'] = '';
663
			if (!isset($row['homepage'])) $row['homepage'] = '';
664
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
665
			if (!isset($row['name'])) continue;
666
			if (!isset($row['image'])) {
667
				$row['image'] = '';
668
				$row['image_thumb'] = '';
669
			} else {
670
				$image = str_replace(' ','_',$row['image']);
671
				$digest = md5($image);
672
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
673
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
674
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
675
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
676
			}
677
			
678
			$country = explode('-',$row['country']);
679
			$row['country'] = $country[0];
680
			
681
			$row['type'] = trim($row['type']);
682
			if ($row['type'] == 'Military: Naval Auxiliary Air Station' || $row['type'] == 'http://dbpedia.org/resource/Naval_air_station' || $row['type'] == 'Military: Naval Air Station' || $row['type'] == 'Military Northern Fleet' || $row['type'] == 'Military and industrial' || $row['type'] == 'Military: Royal Air Force station' || $row['type'] == 'http://dbpedia.org/resource/Military_airbase' || $row['type'] == 'Military: Naval air station' || preg_match('/air base/i',$row['name'])) {
683
				$row['type'] = 'Military';
684
			} elseif ($row['type'] == 'http://dbpedia.org/resource/Airport' || $row['type'] == 'Civil' || $row['type'] == 'Public use' || $row['type'] == 'Public' || $row['type'] == 'http://dbpedia.org/resource/Civilian' || $row['type'] == 'Public, Civilian' || $row['type'] == 'Public / Military' || $row['type'] == 'Private & Civilian' || $row['type'] == 'Civilian and Military' || $row['type'] == 'Public/military' || $row['type'] == 'Active With Few Facilities' || $row['type'] == '?ivilian' || $row['type'] == 'Civil/Military' || $row['type'] == 'NA' || $row['type'] == 'Public/Military') {
685
				$row['type'] = 'small_airport';
686
			}
687
			
688
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
689
			$query_dest_values = array(':airport_id' => $i, ':name' => $row['name'],':iata' => $row['iata'],':icao' => $row['icao'],':latitude' => $row['latitude'],':longitude' => $row['longitude'],':altitude' => $row['altitude'],':type' => $row['type'],':city' => $row['city'],':country' => $row['country'],':home_link' => $row['homepage'],':wikipedia_link' => $row['wikipedia_page'],':image' => $row['image'],':image_thumb' => $row['image_thumb']);
690
			//print_r($query_dest_values);
691
			
692
			try {
693
				$sth_dest->execute($query_dest_values);
694
			} catch(PDOException $e) {
695
				return "error : ".$e->getMessage();
696
			}
697
			}
698
699
			$i++;
700
		}
701
		if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
702
		echo "Delete duplicate rows...\n";
703
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
704
		try {
705
			$Connection = new Connection();
706
			$sth = $Connection->db->prepare($query);
707
                        $sth->execute();
708
                } catch(PDOException $e) {
709
                        return "error : ".$e->getMessage();
710
                }
711
712
713
		if ($globalDebug) echo "Insert Not available Airport...\n";
714
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
715
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
716
		$query_values = array(':airport_id' => $i, ':name' => 'Not available',':iata' => 'NA',':icao' => 'NA',':latitude' => '0',':longitude' => '0',':altitude' => '0',':type' => 'NA',':city' => 'N/A',':country' => 'N/A',':home_link' => '',':wikipedia_link' => '',':image' => '',':image_thumb' => '');
717
		try {
718
			$Connection = new Connection();
719
			$sth = $Connection->db->prepare($query);
720
                        $sth->execute($query_values);
721
                } catch(PDOException $e) {
722
                        return "error : ".$e->getMessage();
723
                }
724
		$i++;
725
/*
726
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
727
		try {
728
			$Connection = new Connection();
729
			$sth = $Connection->db->prepare($query);
730
                        $sth->execute();
731
                } catch(PDOException $e) {
732
                        return "error : ".$e->getMessage();
733
                }
734
*/
735
736
		echo "Download data from ourairports.com...\n";
737
		$delimiter = ',';
738
		$out_file = $tmp_dir.'airports.csv';
739
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
740
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
741
		echo "Add data from ourairports.com...\n";
742
743
		$header = NULL;
744
		if (($handle = fopen($out_file, 'r')) !== FALSE)
745
		{
746
			$Connection = new Connection();
747
			//$Connection->db->beginTransaction();
748
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
749
			{
750
				if(!$header) $header = $row;
751
				else {
752
					$data = array();
0 ignored issues
show
Unused Code introduced by
$data 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...
753
					$data = array_combine($header, $row);
754
					try {
755
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
756
						$sth->execute(array(':icao' => $data['gps_code']));
757
					} catch(PDOException $e) {
758
						return "error : ".$e->getMessage();
759
					}
760
					if ($sth->fetchColumn() > 0) {
761
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
762
						try {
763
							$sth = $Connection->db->prepare($query);
764
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
765
						} catch(PDOException $e) {
766
							return "error : ".$e->getMessage();
767
						}
768
					} else {
769
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
770
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
771
						$query_values = array(':airport_id' => $i, ':name' => $data['name'],':iata' => $data['iata_code'],':icao' => $data['gps_code'],':latitude' => $data['latitude_deg'],':longitude' => $data['longitude_deg'],':altitude' => $data['elevation_ft'],':type' => $data['type'],':city' => $data['municipality'],':country' => $data['iso_country'],':home_link' => $data['home_link'],':wikipedia_link' => $data['wikipedia_link']);
772
						try {
773
							$sth = $Connection->db->prepare($query);
774
							$sth->execute($query_values);
775
						} catch(PDOException $e) {
776
							return "error : ".$e->getMessage();
777
						}
778
						$i++;
779
					}
780
				}
781
			}
782
			fclose($handle);
783
			//$Connection->db->commit();
784
		}
785
786
		echo "Download data from another free database...\n";
787
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
788
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
789
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
790
		update_db::unzip($out_file);
791
		$header = NULL;
792
		echo "Add data from another free database...\n";
793
		$delimiter = ':';
794
		$Connection = new Connection();
795
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
796
		{
797
			//$Connection->db->beginTransaction();
798
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
799
			{
800
				if(!$header) $header = $row;
801
				else {
802
					$data = $row;
803
804
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
805
					try {
806
						$sth = $Connection->db->prepare($query);
807
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
808
					} catch(PDOException $e) {
809
						return "error : ".$e->getMessage();
810
					}
811
				}
812
			}
813
			fclose($handle);
814
			//$Connection->db->commit();
815
		}
816
817
		echo "Put type military for all air base";
818
		$Connection = new Connection();
819
		try {
820
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
821
			$sth->execute();
822
		} catch(PDOException $e) {
823
			return "error : ".$e->getMessage();
824
		}
825
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
826
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
827
			try {
828
				$sth2 = $Connection->db->prepare($query2);
829
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
830
			} catch(PDOException $e) {
831
				return "error : ".$e->getMessage();
832
			}
833
		}
834
835
836
837
                return "success";
838
	}
839
	
840
	public static function translation() {
841
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
842
		global $tmp_dir, $globalTransaction;
843
		$Spotter = new Spotter();
844
		//$out_file = $tmp_dir.'translation.zip';
845
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
846
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
847
		
848
		//$query = 'TRUNCATE TABLE translation';
849
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
850
		try {
851
			$Connection = new Connection();
852
			$sth = $Connection->db->prepare($query);
853
                        $sth->execute(array(':source' => 'translation.csv'));
854
                } catch(PDOException $e) {
855
                        return "error : ".$e->getMessage();
856
                }
857
858
		
859
		//update_db::unzip($out_file);
860
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header 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...
861
		$delimiter = ';';
862
		$Connection = new Connection();
863
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
864
		{
865
			$i = 0;
866
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
867
			//$Connection->db->beginTransaction();
868
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
869
			{
870
				$i++;
871
				if($i > 12) {
872
					$data = $row;
873
					$operator = $data[2];
874
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
875
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
876
                                                //echo substr($operator, 0, 2)."\n";;
877
                                                if (count($airline_array) > 0) {
878
							//print_r($airline_array);
879
							$operator = $airline_array[0]['icao'].substr($operator,2);
880
                                                }
881
                                        }
882
					
883
					$operator_correct = $data[3];
884
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
885
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
886
                                                if (count($airline_array) > 0) {
887
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
888
                                            	}
889
                                        }
890
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
891
					try {
892
						$sth = $Connection->db->prepare($query);
893
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
894
					} catch(PDOException $e) {
895
						return "error : ".$e->getMessage();
896
					}
897
				}
898
			}
899
			fclose($handle);
900
			//$Connection->db->commit();
901
		}
902
		return '';
903
        }
904
	
905
	public static function translation_fam() {
906
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
907
		global $tmp_dir, $globalTransaction;
908
		$Spotter = new Spotter();
0 ignored issues
show
Unused Code introduced by
$Spotter 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...
909
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
910
		try {
911
			$Connection = new Connection();
912
			$sth = $Connection->db->prepare($query);
913
                        $sth->execute(array(':source' => 'website_fam'));
914
                } catch(PDOException $e) {
915
                        return "error : ".$e->getMessage();
916
                }
917
918
		
919
		//update_db::unzip($out_file);
920
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header 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...
921
		$delimiter = "\t";
922
		$Connection = new Connection();
923
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
924
		{
925
			$i = 0;
926
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
927
			//$Connection->db->beginTransaction();
928
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
929
			{
930
				if ($i > 0) {
931
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
932
					try {
933
						$sth = $Connection->db->prepare($query);
934
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
935
					} catch(PDOException $e) {
936
						return "error : ".$e->getMessage();
937
					}
938
				}
939
				$i++;
940
			}
941
			fclose($handle);
942
			//$Connection->db->commit();
943
		}
944
		return '';
945
        }
946
947
	public static function modes_fam() {
948
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
949
		global $tmp_dir, $globalTransaction;
950
		$Spotter = new Spotter();
0 ignored issues
show
Unused Code introduced by
$Spotter 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...
951
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
952
		try {
953
			$Connection = new Connection();
954
			$sth = $Connection->db->prepare($query);
955
                        $sth->execute(array(':source' => 'website_fam'));
956
                } catch(PDOException $e) {
957
                        return "error : ".$e->getMessage();
958
                }
959
960
		
961
		//update_db::unzip($out_file);
962
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header 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...
963
		$delimiter = "\t";
964
		$Connection = new Connection();
965
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
966
		{
967
			$i = 0;
968
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
969
			//$Connection->db->beginTransaction();
970
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
971
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
972
			{
973
				if ($i > 0) {
974
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
975
					try {
976
						$sth = $Connection->db->prepare($query);
977
						$sth->execute(array(':FirstCreated' => $data[0],':LastModified' => $data[1],':ModeS' => $data[2],':ModeSCountry' => $data[3], ':Registration' => $data[4],':ICAOTypeCode' => $data[5],':type_flight' => $data[6],':source' => 'website_fam'));
978
					} catch(PDOException $e) {
979
						return "error : ".$e->getMessage();
980
					}
981
				}
982
				$i++;
983
			}
984
			fclose($handle);
985
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
986
		}
987
		return '';
988
        }
989
990
	public static function tle($filename,$tletype) {
991
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
992
		global $tmp_dir, $globalTransaction;
993
		//$Spotter = new Spotter();
994
		
995
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
996
		try {
997
			$Connection = new Connection();
998
			$sth = $Connection->db->prepare($query);
999
                        $sth->execute(array(':source' => $filename));
1000
                } catch(PDOException $e) {
1001
                        return "error : ".$e->getMessage();
1002
                }
1003
		
1004
		$Connection = new Connection();
1005
		if (($handle = fopen($filename, 'r')) !== FALSE)
1006
		{
1007
			$i = 0;
1008
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1009
			//$Connection->db->beginTransaction();
1010
			$dbdata = array();
1011
			while (($data = fgets($handle, 1000)) !== FALSE)
1012
			{
1013
				if ($i == 0) {
1014
					$dbdata['name'] = trim($data);
1015
					$i++;
1016
				} elseif ($i == 1) {
1017
					$dbdata['tle1'] = trim($data);
1018
					$i++;
1019
				} elseif ($i == 2) {
1020
					$dbdata['tle2'] = trim($data);
1021
					//print_r($dbdata);
1022
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1023
					try {
1024
						$sth = $Connection->db->prepare($query);
1025
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1026
					} catch(PDOException $e) {
1027
						return "error : ".$e->getMessage();
1028
					}
1029
1030
					$i = 0;
1031
				}
1032
			}
1033
			fclose($handle);
1034
			//$Connection->db->commit();
1035
		}
1036
		return '';
1037
        }
1038
1039
	/**
1040
        * Convert a HTML table to an array
1041
        * @param String $data HTML page
1042
        * @return Array array of the tables in HTML page
1043
        */
1044
        private static function table2array($data) {
1045
                $html = str_get_html($data);
1046
                $tabledata=array();
1047
                foreach($html->find('tr') as $element)
1048
                {
1049
                        $td = array();
1050
                        foreach( $element->find('th') as $row)
1051
                        {
1052
                                $td [] = trim($row->plaintext);
1053
                        }
1054
                        $td=array_filter($td);
1055
                        $tabledata[] = $td;
1056
1057
                        $td = array();
1058
                        $tdi = array();
1059
                        foreach( $element->find('td') as $row)
1060
                        {
1061
                                $td [] = trim($row->plaintext);
1062
                                $tdi [] = trim($row->innertext);
1063
                        }
1064
                        $td=array_filter($td);
1065
                        $tdi=array_filter($tdi);
0 ignored issues
show
Unused Code introduced by
$tdi 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...
1066
                    //    $tabledata[]=array_merge($td,$tdi);
1067
                        $tabledata[]=$td;
1068
                }
1069
                return(array_filter($tabledata));
1070
        }
1071
1072
       /**
1073
        * Get data from form result
1074
        * @param String $url form URL
1075
        * @return String the result
1076
        */
1077
        private static function getData($url) {
1078
                $ch = curl_init();
1079
                curl_setopt($ch, CURLOPT_URL, $url);
1080
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1081
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1082
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
1083
                return curl_exec($ch);
1084
        }
1085
/*
1086
	public static function waypoints() {
1087
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1088
		$table = update_db::table2array($data);
1089
//		print_r($table);
1090
		$query = 'TRUNCATE TABLE waypoints';
1091
		try {
1092
			$Connection = new Connection();
1093
			$sth = $Connection->db->prepare($query);
1094
                        $sth->execute();
1095
                } catch(PDOException $e) {
1096
                        return "error : ".$e->getMessage();
1097
                }
1098
1099
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1100
		$Connection = new Connection();
1101
		$sth_dest = $Connection->db->prepare($query_dest);
1102
		$Connection->db->beginTransaction();
1103
                foreach ($table as $row) {
1104
            		if ($row[0] != 'Ident') {
1105
				$ident = $row[0];
1106
				$latitude = $row[2];
1107
				$longitude = $row[3];
1108
				$control = $row[4];
1109
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1110
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1111
				try {
1112
					$sth_dest->execute($query_dest_values);
1113
				} catch(PDOException $e) {
1114
					return "error : ".$e->getMessage();
1115
				}
1116
			}
1117
                }
1118
		$Connection->db->commit();
1119
1120
	}
1121
*/
1122
	public static function waypoints($filename) {
1123
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1124
		global $tmp_dir, $globalTransaction;
1125
		//$Spotter = new Spotter();
1126
		//$out_file = $tmp_dir.'translation.zip';
1127
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1128
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1129
		$Connection = new Connection();
1130
		//update_db::unzip($out_file);
1131
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header 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...
1132
		$delimiter = ' ';
1133
		if (($handle = fopen($filename, 'r')) !== FALSE)
1134
		{
1135
			$i = 0;
1136
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1137
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1138
			{
1139
				$i++;
1140
				if($i > 3 && count($row) > 2) {
1141
					$data = array_values(array_filter($row));
1142
					$cntdata = count($data);
1143
					if ($cntdata > 10) {
1144
						$value = $data[9];
1145
						
1146
						for ($i =10;$i < $cntdata;$i++) {
1147
							$value .= ' '.$data[$i];
1148
						}
1149
						$data[9] = $value;
1150
					}
1151
					//print_r($data);
1152
					if (count($data) > 9) {
1153
						$query = 'INSERT INTO waypoints (name_begin,latitude_begin,longitude_begin,name_end,latitude_end,longitude_end,high,base,top,segment_name) VALUES (:name_begin, :latitude_begin, :longitude_begin, :name_end, :latitude_end, :longitude_end, :high, :base, :top, :segment_name)';
1154
						try {
1155
							$sth = $Connection->db->prepare($query);
1156
							$sth->execute(array(':name_begin' => $data[0],':latitude_begin' => $data[1],':longitude_begin' => $data[2],':name_end' => $data[3], ':latitude_end' => $data[4], ':longitude_end' => $data[5], ':high' => $data[6], ':base' => $data[7], ':top' => $data[8], ':segment_name' => $data[9]));
1157
						} catch(PDOException $e) {
1158
							return "error : ".$e->getMessage();
1159
						}
1160
					}
1161
				}
1162
			}
1163
			fclose($handle);
1164
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1165
		}
1166
		return '';
1167
        }
1168
1169
	public static function ivao_airlines($filename) {
1170
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1171
		global $tmp_dir, $globalTransaction;
1172
		//$query = 'TRUNCATE TABLE airlines';
1173
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1174
		try {
1175
			$Connection = new Connection();
1176
			$sth = $Connection->db->prepare($query);
1177
                        $sth->execute();
1178
                } catch(PDOException $e) {
1179
                        return "error : ".$e->getMessage();
1180
                }
1181
1182
		$header = NULL;
0 ignored issues
show
Unused Code introduced by
$header 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...
1183
		$delimiter = ':';
1184
		$Connection = new Connection();
1185
		if (($handle = fopen($filename, 'r')) !== FALSE)
1186
		{
1187
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1188
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1189
			{
1190
				if(count($row) > 1) {
1191
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1192
					try {
1193
						$sth = $Connection->db->prepare($query);
1194
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1195
					} catch(PDOException $e) {
1196
						return "error : ".$e->getMessage();
1197
					}
1198
				}
1199
			}
1200
			fclose($handle);
1201
			if ($globalTransaction) $Connection->db->commit();
1 ignored issue
show
Bug introduced by
The method commit cannot be called on $Connection->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1202
		}
1203
		return '';
1204
        }
1205
	
1206
	public static function update_airspace() {
1207
		global $tmp_dir, $globalDBdriver;
1208
		include_once('class.create_db.php');
1209
		$Connection = new Connection();
1210
		if ($Connection->tableExists('airspace')) {
1211
			$query = 'DROP TABLE airspace';
1212
			try {
1213
				$sth = $Connection->db->prepare($query);
1214
                    		$sth->execute();
1215
	                } catch(PDOException $e) {
1216
				return "error : ".$e->getMessage();
1217
	                }
1218
	        }
1219
1220
1221
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1222
		else {
1223
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1224
			$query = "CREATE EXTENSION postgis";
1225
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1226
			try {
1227
				$sth = $Connection->db->prepare($query);
1228
				$sth->execute();
1229
			} catch(PDOException $e) {
1230
				return "error : ".$e->getMessage();
1231
			}
1232
		}
1233
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1234
		return $error;
1235
	}
1236
1237
	public static function update_notam_fam() {
1238
		global $tmp_dir, $globalDebug;
1239
		include_once('class.create_db.php');
1240
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1241
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1242
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1243
		$error = '';
1244
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1245
			if ($globalDebug) echo "Gunzip...";
1246
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1247
			if ($globalDebug) echo "Add to DB...";
1248
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1249
			$NOTAM = new NOTAM();
1250
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1251
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1252
		if ($error != '') {
1253
			return $error;
1254
		} elseif ($globalDebug) echo "Done\n";
1255
		return '';
1256
	}
1257
1258
	public static function update_vatsim() {
1259
		global $tmp_dir;
1260
		include_once('class.create_db.php');
1261
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1262
		return $error;
1263
	}
1264
	
1265
	public static function update_countries() {
1266
		global $tmp_dir, $globalDBdriver;
1267
		include_once('class.create_db.php');
1268
		$Connection = new Connection();
1269
		if ($Connection->tableExists('countries')) {
1270
			$query = 'DROP TABLE countries';
1271
			try {
1272
				$sth = $Connection->db->prepare($query);
1273
            	        	$sth->execute();
1274
	                } catch(PDOException $e) {
1275
    	                	echo "error : ".$e->getMessage();
1276
	                }
1277
		}
1278
		if ($globalDBdriver == 'mysql') {
1279
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1280
		} else {
1281
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1282
		}
1283
		$error = create_db::import_file($tmp_dir.'countries.sql');
1284
		return $error;
1285
	}
1286
1287
	
1288
	public static function update_waypoints() {
1289
		global $tmp_dir;
1290
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1291
//		update_db::unzip($tmp_dir.'AptNav.zip');
1292
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1293
//		update_db::download('http://sourceforge.net/p/flightgear/fgdata/ci/next/tree/Navaids/awy.dat.gz?format=raw',$tmp_dir.'awy.dat.gz','http://sourceforge.net');
1294
		update_db::download('http://pkgs.fedoraproject.org/repo/extras/FlightGear-Atlas/awy.dat.gz/f530c9d1c4b31a288ba88dcc8224268b/awy.dat.gz',$tmp_dir.'awy.dat.gz','http://sourceforge.net');
1295
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1296
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1297
		return $error;
1298
	}
1299
1300
	public static function update_ivao() {
1301
		global $tmp_dir, $globalDebug;
1302
		$Common = new Common();
1303
		$error = '';
1304
		//Direct download forbidden
1305
		//if ($globalDebug) echo "IVAO : Download...";
1306
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1307
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1308
			if ($globalDebug) echo "Unzip...";
1309
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1310
			if ($globalDebug) echo "Add to DB...";
1311
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1312
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1313
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1314
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1315
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1316
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1317
		if ($error != '') {
1318
			return $error;
1319
		} elseif ($globalDebug) echo "Done\n";
1320
		return '';
1321
	}
1322
1323
	public static function update_routes() {
1324
		global $tmp_dir, $globalDebug;
1325
		$error = '';
0 ignored issues
show
Unused Code introduced by
$error 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...
1326
		if ($globalDebug) echo "Routes : Download...";
1327
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1328
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1329
			if ($globalDebug) echo "Gunzip...";
1330
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1331
			if ($globalDebug) echo "Add to DB...";
1332
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1333
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1334
		if ($error != '') {
1335
			return $error;
1336
		} elseif ($globalDebug) echo "Done\n";
1337
		return '';
1338
	}
1339
	public static function update_oneworld() {
1340
		global $tmp_dir, $globalDebug;
1341
		$error = '';
0 ignored issues
show
Unused Code introduced by
$error 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...
1342
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1343
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1344
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1345
			if ($globalDebug) echo "Gunzip...";
1346
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1347
			if ($globalDebug) echo "Add to DB...";
1348
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1349
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1350
		if ($error != '') {
1351
			return $error;
1352
		} elseif ($globalDebug) echo "Done\n";
1353
		return '';
1354
	}
1355
	public static function update_skyteam() {
1356
		global $tmp_dir, $globalDebug;
1357
		$error = '';
0 ignored issues
show
Unused Code introduced by
$error 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...
1358
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1359
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1360
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1361
			if ($globalDebug) echo "Gunzip...";
1362
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1363
			if ($globalDebug) echo "Add to DB...";
1364
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1365
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1366
		if ($error != '') {
1367
			return $error;
1368
		} elseif ($globalDebug) echo "Done\n";
1369
		return '';
1370
	}
1371
	public static function update_ModeS() {
1372
		global $tmp_dir, $globalDebug;
1373
/*
1374
		if ($globalDebug) echo "Modes : Download...";
1375
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1376
		if ($globalDebug) echo "Unzip...";
1377
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1378
		if ($globalDebug) echo "Add to DB...";
1379
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1380
		if ($error != true) {
1381
			echo $error;
1382
			exit;
1383
		} elseif ($globalDebug) echo "Done\n";
1384
*/
1385
		if ($globalDebug) echo "Modes : Download...";
1386
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1387
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1388
1389
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1390
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1391
			if ($globalDebug) echo "Unzip...";
1392
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1393
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1394
			if ($globalDebug) echo "Add to DB...";
1395
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1396
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1397
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1398
		if ($error != '') {
1399
			return $error;
1400
		} elseif ($globalDebug) echo "Done\n";
1401
		return '';
1402
	}
1403
1404
	public static function update_ModeS_flarm() {
1405
		global $tmp_dir, $globalDebug;
1406
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1407
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1408
		if (file_exists($tmp_dir.'data.fln')) {
1409
			if ($globalDebug) echo "Add to DB...";
1410
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1411
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1412
		if ($error != '') {
1413
			return $error;
1414
		} elseif ($globalDebug) echo "Done\n";
1415
		return '';
1416
	}
1417
1418
	public static function update_ModeS_ogn() {
1419
		global $tmp_dir, $globalDebug;
1420
		if ($globalDebug) echo "Modes OGN: Download...";
1421
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1422
		if (file_exists($tmp_dir.'ogn.csv')) {
1423
			if ($globalDebug) echo "Add to DB...";
1424
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1425
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1426
		if ($error != '') {
1427
			return $error;
1428
		} elseif ($globalDebug) echo "Done\n";
1429
		return '';
1430
	}
1431
1432
	public static function update_owner() {
1433
		global $tmp_dir, $globalDebug;
1434
		
1435
		if ($globalDebug) echo "Owner France: Download...";
1436
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1437
		if (file_exists($tmp_dir.'owner_f.csv')) {
1438
			if ($globalDebug) echo "Add to DB...";
1439
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1440
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1441
		if ($error != '') {
1442
			return $error;
1443
		} elseif ($globalDebug) echo "Done\n";
1444
		
1445
		if ($globalDebug) echo "Owner Ireland: Download...";
1446
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1447
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1448
			if ($globalDebug) echo "Add to DB...";
1449
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1450
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1451
		if ($error != '') {
1452
			return $error;
1453
		} elseif ($globalDebug) echo "Done\n";
1454
		if ($globalDebug) echo "Owner Switzerland: Download...";
1455
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1456
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1457
			if ($globalDebug) echo "Add to DB...";
1458
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1459
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1460
		if ($error != '') {
1461
			return $error;
1462
		} elseif ($globalDebug) echo "Done\n";
1463
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1464
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1465
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1466
			if ($globalDebug) echo "Add to DB...";
1467
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1468
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1469
		if ($error != '') {
1470
			return $error;
1471
		} elseif ($globalDebug) echo "Done\n";
1472
		if ($globalDebug) echo "Owner Australia: Download...";
1473
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1474
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1475
			if ($globalDebug) echo "Add to DB...";
1476
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1477
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1478
		if ($error != '') {
1479
			return $error;
1480
		} elseif ($globalDebug) echo "Done\n";
1481
		if ($globalDebug) echo "Owner Austria: Download...";
1482
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1483
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1484
			if ($globalDebug) echo "Add to DB...";
1485
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1486
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1487
		if ($error != '') {
1488
			return $error;
1489
		} elseif ($globalDebug) echo "Done\n";
1490
		if ($globalDebug) echo "Owner Chile: Download...";
1491
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1492
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1493
			if ($globalDebug) echo "Add to DB...";
1494
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1495
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1496
		if ($error != '') {
1497
			return $error;
1498
		} elseif ($globalDebug) echo "Done\n";
1499
		if ($globalDebug) echo "Owner Colombia: Download...";
1500
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1501
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1502
			if ($globalDebug) echo "Add to DB...";
1503
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1504
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1505
		if ($error != '') {
1506
			return $error;
1507
		} elseif ($globalDebug) echo "Done\n";
1508
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1509
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1510
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1511
			if ($globalDebug) echo "Add to DB...";
1512
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1513
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1514
		if ($error != '') {
1515
			return $error;
1516
		} elseif ($globalDebug) echo "Done\n";
1517
		if ($globalDebug) echo "Owner Brazil: Download...";
1518
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1519
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1520
			if ($globalDebug) echo "Add to DB...";
1521
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1522
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1523
		if ($error != '') {
1524
			return $error;
1525
		} elseif ($globalDebug) echo "Done\n";
1526
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1527
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1528
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1529
			if ($globalDebug) echo "Add to DB...";
1530
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1531
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1532
		if ($error != '') {
1533
			return $error;
1534
		} elseif ($globalDebug) echo "Done\n";
1535
		if ($globalDebug) echo "Owner Croatia: Download...";
1536
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1537
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1538
			if ($globalDebug) echo "Add to DB...";
1539
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1540
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1541
		if ($error != '') {
1542
			return $error;
1543
		} elseif ($globalDebug) echo "Done\n";
1544
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1545
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1546
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1547
			if ($globalDebug) echo "Add to DB...";
1548
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1549
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1550
		if ($error != '') {
1551
			return $error;
1552
		} elseif ($globalDebug) echo "Done\n";
1553
		if ($globalDebug) echo "Owner Maldives: Download...";
1554
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1555
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1556
			if ($globalDebug) echo "Add to DB...";
1557
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1558
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1559
		if ($error != '') {
1560
			return $error;
1561
		} elseif ($globalDebug) echo "Done\n";
1562
		if ($globalDebug) echo "Owner New Zealand: Download...";
1563
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1564
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1565
			if ($globalDebug) echo "Add to DB...";
1566
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1567
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1568
		if ($error != '') {
1569
			return $error;
1570
		} elseif ($globalDebug) echo "Done\n";
1571
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1572
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1573
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1574
			if ($globalDebug) echo "Add to DB...";
1575
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1576
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1577
		if ($error != '') {
1578
			return $error;
1579
		} elseif ($globalDebug) echo "Done\n";
1580
		if ($globalDebug) echo "Owner Slovakia: Download...";
1581
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1582
		if (file_exists($tmp_dir.'owner_om.csv')) {
1583
			if ($globalDebug) echo "Add to DB...";
1584
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1585
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1586
		if ($error != '') {
1587
			return $error;
1588
		} elseif ($globalDebug) echo "Done\n";
1589
		if ($globalDebug) echo "Owner Ecuador: Download...";
1590
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1591
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1592
			if ($globalDebug) echo "Add to DB...";
1593
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1594
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1595
		if ($error != '') {
1596
			return $error;
1597
		} elseif ($globalDebug) echo "Done\n";
1598
		if ($globalDebug) echo "Owner Iceland: Download...";
1599
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1600
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1601
			if ($globalDebug) echo "Add to DB...";
1602
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1603
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1604
		if ($error != '') {
1605
			return $error;
1606
		} elseif ($globalDebug) echo "Done\n";
1607
		return '';
1608
	}
1609
1610
	public static function update_translation() {
1611
		global $tmp_dir, $globalDebug;
1612
		$error = '';
0 ignored issues
show
Unused Code introduced by
$error 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...
1613
		if ($globalDebug) echo "Translation : Download...";
1614
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1615
		if (file_exists($tmp_dir.'translation.zip')) {
1616
			if ($globalDebug) echo "Unzip...";
1617
			update_db::unzip($tmp_dir.'translation.zip');
1618
			if ($globalDebug) echo "Add to DB...";
1619
			$error = update_db::translation();
1620
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1621
		if ($error != '') {
1622
			return $error;
1623
		} elseif ($globalDebug) echo "Done\n";
1624
		return '';
1625
	}
1626
1627
	public static function update_translation_fam() {
1628
		global $tmp_dir, $globalDebug;
1629
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1630
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1631
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1632
			if ($globalDebug) echo "Gunzip...";
1633
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1634
			if ($globalDebug) echo "Add to DB...";
1635
			$error = update_db::translation_fam();
1636
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1637
		if ($error != '') {
1638
			return $error;
1639
		} elseif ($globalDebug) echo "Done\n";
1640
		return '';
1641
	}
1642
	public static function update_ModeS_fam() {
1643
		global $tmp_dir, $globalDebug;
1644
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1645
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1646
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1647
			if ($globalDebug) echo "Gunzip...";
1648
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1649
			if ($globalDebug) echo "Add to DB...";
1650
			$error = update_db::modes_fam();
1651
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1652
		if ($error != '') {
1653
			return $error;
1654
		} elseif ($globalDebug) echo "Done\n";
1655
		return '';
1656
	}
1657
1658
	public static function update_airspace_fam() {
1659
		global $tmp_dir, $globalDebug, $globalDBdriver;
1660
		include_once('class.create_db.php');
1661
		$error = '';
1662
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1663
		if ($globalDBdriver == 'mysql') {
1664
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1665
		} else {
1666
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1667
		}
1668
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1669
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1670
			$airspace_md5 = $airspace_md5_file[0];
1671
			if (!update_db::check_airspace_version($airspace_md5)) {
1672
				if ($globalDBdriver == 'mysql') {
1673
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1674
				} else {
1675
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1676
				}
1677
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1678
					if ($globalDebug) echo "Gunzip...";
1679
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1680
					if ($globalDebug) echo "Add to DB...";
1681
					$Connection = new Connection();
1682
					if ($Connection->tableExists('airspace')) {
1683
						$query = 'DROP TABLE airspace';
1684
						try {
1685
							$sth = $Connection->db->prepare($query);
1686
    	    	    					$sth->execute();
1687
			            		} catch(PDOException $e) {
1688
							return "error : ".$e->getMessage();
1689
		            			}
1690
		    			}
1691
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1692
					update_db::insert_airspace_version($airspace_md5);
1693
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1694
			}
1695
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1696
		if ($error != '') {
1697
			return $error;
1698
		} elseif ($globalDebug) echo "Done\n";
1699
		return '';
1700
	}
1701
1702
	public static function update_tle() {
1703
		global $tmp_dir, $globalDebug;
1704
		if ($globalDebug) echo "Download TLE : Download...";
1705
		$alltle = array('stations.txt','gps-ops.txt','glo-ops.txt','galileo.txt','weather.txt','noaa.txt','goes.txt','resource.txt','dmc.txt','tdrss.txt','geo.txt','intelsat.txt','gorizont.txt',
1706
		'raduga.txt','molniya.txt','iridium.txt','orbcomm.txt','globalstar.txt','amateur.txt','x-comm.txt','other-comm.txt','sbas.txt','nnss.txt','musson.txt','science.txt','geodetic.txt',
1707
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1708
		foreach ($alltle as $filename) {
1709
			if ($globalDebug) echo "downloading ".$filename.'...';
1710
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1711
			if (file_exists($tmp_dir.$filename)) {
1712
				if ($globalDebug) echo "Add to DB ".$filename."...";
1713
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1714
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1715
			if ($error != '') {
1716
				echo $error."\n";
1717
			} elseif ($globalDebug) echo "Done\n";
1718
		}
1719
		return '';
1720
	}
1721
1722
	public static function update_models() {
1723
		global $tmp_dir, $globalDebug;
1724
		$error = '';
1725
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1726
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1727
		if (file_exists($tmp_dir.'models.md5sum')) {
1728
			if ($globalDebug) echo "Check files...\n";
1729
			$newmodelsdb = array();
1730
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1731
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1732
					$model = trim($row[2]);
1733
					$newmodelsdb[$model] = trim($row[0]);
1734
				}
1735
			}
1736
			$modelsdb = array();
1737
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1738
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1739
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1740
						$model = trim($row[2]);
1741
						$modelsdb[$model] = trim($row[0]);
1742
					}
1743
				}
1744
			}
1745
			$diff = array_diff($newmodelsdb,$modelsdb);
1746
			foreach ($diff as $key => $value) {
1747
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1748
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1749
				
1750
			}
1751
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1752
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1753
		if ($error != '') {
1754
			return $error;
1755
		} elseif ($globalDebug) echo "Done\n";
1756
		return '';
1757
	}
1758
1759
	public static function update_space_models() {
1760
		global $tmp_dir, $globalDebug;
1761
		$error = '';
1762
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1763
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1764
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1765
			if ($globalDebug) echo "Check files...\n";
1766
			$newmodelsdb = array();
1767
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1768
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1769
					$model = trim($row[2]);
1770
					$newmodelsdb[$model] = trim($row[0]);
1771
				}
1772
			}
1773
			$modelsdb = array();
1774
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1775
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1776
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1777
						$model = trim($row[2]);
1778
						$modelsdb[$model] = trim($row[0]);
1779
					}
1780
				}
1781
			}
1782
			$diff = array_diff($newmodelsdb,$modelsdb);
1783
			foreach ($diff as $key => $value) {
1784
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1785
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1786
				
1787
			}
1788
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1789
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1790
		if ($error != '') {
1791
			return $error;
1792
		} elseif ($globalDebug) echo "Done\n";
1793
		return '';
1794
	}
1795
1796
	public static function update_aircraft() {
1797
		global $tmp_dir, $globalDebug;
1798
		date_default_timezone_set('UTC');
1799
		//$error = '';
1800
		/*
1801
		if ($globalDebug) echo "Aircrafts : Download...";
1802
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1803
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1804
		//$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,array('Content-Type: application/x-www-form-urlencoded','Host: cfapp.icao.int','Origin: http://cfapp.icao.int','Pragma: no-cache','Upgrade-Insecure-Requests: 1','Content-Length: '.strlen($data_req)),'','http://cfapp.icao.int/Doc8643/search.cfm',20);
1805
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1806
//		echo strlen($data_req);
1807
		echo $data;
1808
		*/
1809
		if (file_exists($tmp_dir.'aircrafts.html')) {
1810
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1811
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1812
		    $result = fread($fh,100000000);
0 ignored issues
show
Unused Code introduced by
$result 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...
1813
		    //echo $result;
1814
		    //var_dump(str_get_html($result));
1815
		    //print_r(self::table2array($result));
1816
		}
1817
1818
	}
1819
	
1820
	public static function update_notam() {
1821
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1822
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1823
		$Common = new Common();
1824
		date_default_timezone_set('UTC');
1825
		$query = 'TRUNCATE TABLE notam';
1826
		try {
1827
			$Connection = new Connection();
1828
			$sth = $Connection->db->prepare($query);
1829
                        $sth->execute();
1830
                } catch(PDOException $e) {
1831
                        return "error : ".$e->getMessage();
1832
                }
1833
1834
		$error = '';
1835
		if ($globalDebug) echo "Notam : Download...";
1836
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1837
		if (file_exists($tmp_dir.'notam.rss')) {
1838
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1839
			foreach ($notams['channel']['item'] as $notam) {
1840
				$title = explode(':',$notam['title']);
1841
				$data['ref'] = trim($title[0]);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1842
				unset($title[0]);
1843
				$data['title'] = trim(implode(':',$title));
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1844
				$description = strip_tags($notam['description'],'<pre>');
1845
				preg_match(':^(.*?)<pre>:',$description,$match);
1846
				$q = explode('/',$match[1]);
1847
				$data['fir'] = $q[0];
1848
				$data['code'] = $q[1];
1849
				$ifrvfr = $q[2];
1850
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1851
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1852
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1853
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1854
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1855
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1856
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1857
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1858
				//$data['scope'] = $q[4];
1859
				$data['lower_limit'] = $q[5];
1860
				$data['upper_limit'] = $q[6];
1861
				$latlonrad = $q[7];
1862
				sscanf($latlonrad,'%4c%c%5c%c%3d',$las,$lac,$lns,$lnc,$radius);
0 ignored issues
show
Bug introduced by
The variable $lac does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $lns does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $lnc does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $radius does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1863
				$latitude = $Common->convertDec($las,'latitude');
1864
				$longitude = $Common->convertDec($lns,'longitude');
1865
				if ($lac == 'S') $latitude = '-'.$latitude;
1866
				if ($lnc == 'W') $longitude = '-'.$longitude;
1867
				$data['center_latitude'] = $latitude;
1868
				$data['center_longitude'] = $longitude;
1869
				$data['radius'] = intval($radius);
1870
				
1871
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1872
				$data['text'] = $match[1];
1873
				preg_match(':</pre>(.*?)$:',$description,$match);
1874
				$fromto = $match[1];
1875
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1876
				$fromall = trim($match[1]);
1877
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1878
				$from = trim($match[1]);
1879
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1880
				preg_match('#TO:(.*?)$#',$fromto,$match);
1881
				$toall = trim($match[1]);
1882
				if (!preg_match(':Permanent:',$toall)) {
1883
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1884
					$to = trim($match[1]);
1885
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1886
					$data['permanent'] = 0;
1887
				} else {
1888
				    $data['date_end'] = NULL;
1889
				    $data['permanent'] = 1;
1890
				}
1891
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1892
				$NOTAM = new NOTAM();
1893
				$NOTAM->addNOTAM($data['ref'],$data['title'],'',$data['fir'],$data['code'],'',$data['scope'],$data['lower_limit'],$data['upper_limit'],$data['center_latitude'],$data['center_longitude'],$data['radius'],$data['date_begin'],$data['date_end'],$data['permanent'],$data['text'],$data['full_notam']);
1894
				unset($data);
1895
			} 
1896
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1897
		if ($error != '') {
1898
			return $error;
1899
		} elseif ($globalDebug) echo "Done\n";
1900
		return '';
1901
	}
1902
	
1903
	public static function create_airspace() {
1904
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
1905
		$Connection = new Connection();
1906
		if ($Connection->tableExists('airspace')) {
1907
			if ($globalDBdriver == 'mysql') {
1908
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
1909
			} else {
1910
				$query = 'DROP TABLE airspace';
1911
			}
1912
			try {
1913
				$Connection = new Connection();
1914
				$sth = $Connection->db->prepare($query);
1915
				$sth->execute();
1916
			} catch(PDOException $e) {
1917
				return "error : ".$e->getMessage();
1918
			}
1919
		}
1920
		$Common = new Common();
1921
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
1922
		$airspace_json = json_decode($airspace_lst,true);
1923
		foreach ($airspace_json['records'] as $airspace) {
1924
			if ($globalDebug) echo $airspace['name']."...\n";
1925
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
1926
			if (file_exists($tmp_dir.$airspace['name'])) {
1927
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
1928
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
1929
				if ($globalDBdriver == 'mysql') {
1930
					system('ogr2ogr -update -append -f "MySQL" MySQL:"'.$globalDBname.',host='.$globalDBhost.',user='.$globalDBuser.',password='.$globalDBpass.',port='.$globalDBport.'" -nln airspace -nlt POLYGON -skipfailures -lco ENGINE=MyISAM "'.$tmp_dir.$airspace['name'].'"');
1931
				} else {
1932
					system('ogr2ogr -append -f "PostgreSQL" PG:"host='.$globalDBhost.' user='.$globalDBuser.' dbname='.$globalDBname.' password='.$globalDBpass.' port='.$globalDBport.'" -nln airspace -nlt POLYGON -skipfailures "'.$tmp_dir.$airspace['name'].'"');
1933
				}
1934
			}
1935
		}
1936
	}
1937
	
1938
	public static function check_last_update() {
1939
		global $globalDBdriver;
1940
		if ($globalDBdriver == 'mysql') {
1941
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
1942
		} else {
1943
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1944
		}
1945
		try {
1946
			$Connection = new Connection();
1947
			$sth = $Connection->db->prepare($query);
1948
                        $sth->execute();
1949
                } catch(PDOException $e) {
1950
                        return "error : ".$e->getMessage();
1951
                }
1952
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1953
                if ($row['nb'] > 0) return false;
1954
                else return true;
1955
	}
1956
1957
	public static function insert_last_update() {
1958
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1959
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1960
		try {
1961
			$Connection = new Connection();
1962
			$sth = $Connection->db->prepare($query);
1963
                        $sth->execute();
1964
                } catch(PDOException $e) {
1965
                        return "error : ".$e->getMessage();
1966
                }
1967
	}
1968
1969
	public static function check_airspace_version($version) {
1970
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
1971
		try {
1972
			$Connection = new Connection();
1973
			$sth = $Connection->db->prepare($query);
1974
                        $sth->execute(array(':version' => $version));
1975
                } catch(PDOException $e) {
1976
                        return "error : ".$e->getMessage();
1977
                }
1978
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1979
                if ($row['nb'] > 0) return true;
1980
                else return false;
1981
	}
1982
1983
1984
	public static function insert_airspace_version($version) {
1985
		$query = "DELETE FROM config WHERE name = 'airspace_version';
1986
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
1987
		try {
1988
			$Connection = new Connection();
1989
			$sth = $Connection->db->prepare($query);
1990
                        $sth->execute(array(':version' => $version));
1991
                } catch(PDOException $e) {
1992
                        return "error : ".$e->getMessage();
1993
                }
1994
	}
1995
1996
	public static function check_last_notam_update() {
1997
		global $globalDBdriver;
1998
		if ($globalDBdriver == 'mysql') {
1999
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2000
		} else {
2001
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2002
		}
2003
		try {
2004
			$Connection = new Connection();
2005
			$sth = $Connection->db->prepare($query);
2006
                        $sth->execute();
2007
                } catch(PDOException $e) {
2008
                        return "error : ".$e->getMessage();
2009
                }
2010
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2011
                if ($row['nb'] > 0) return false;
2012
                else return true;
2013
	}
2014
2015
	public static function insert_last_notam_update() {
2016
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2017
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2018
		try {
2019
			$Connection = new Connection();
2020
			$sth = $Connection->db->prepare($query);
2021
                        $sth->execute();
2022
                } catch(PDOException $e) {
2023
                        return "error : ".$e->getMessage();
2024
                }
2025
	}
2026
	public static function check_last_airspace_update() {
2027
		global $globalDBdriver;
2028
		if ($globalDBdriver == 'mysql') {
2029
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2030
		} else {
2031
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2032
		}
2033
		try {
2034
			$Connection = new Connection();
2035
			$sth = $Connection->db->prepare($query);
2036
                        $sth->execute();
2037
                } catch(PDOException $e) {
2038
                        return "error : ".$e->getMessage();
2039
                }
2040
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2041
                if ($row['nb'] > 0) return false;
2042
                else return true;
2043
	}
2044
2045
	public static function insert_last_airspace_update() {
2046
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2047
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2048
		try {
2049
			$Connection = new Connection();
2050
			$sth = $Connection->db->prepare($query);
2051
                        $sth->execute();
2052
                } catch(PDOException $e) {
2053
                        return "error : ".$e->getMessage();
2054
                }
2055
	}
2056
2057
	public static function check_last_owner_update() {
2058
		global $globalDBdriver;
2059
		if ($globalDBdriver == 'mysql') {
2060
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2061
		} else {
2062
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2063
		}
2064
		try {
2065
			$Connection = new Connection();
2066
			$sth = $Connection->db->prepare($query);
2067
                        $sth->execute();
2068
                } catch(PDOException $e) {
2069
                        return "error : ".$e->getMessage();
2070
                }
2071
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2072
                if ($row['nb'] > 0) return false;
2073
                else return true;
2074
	}
2075
2076
	public static function insert_last_owner_update() {
2077
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2078
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2079
		try {
2080
			$Connection = new Connection();
2081
			$sth = $Connection->db->prepare($query);
2082
                        $sth->execute();
2083
                } catch(PDOException $e) {
2084
                        return "error : ".$e->getMessage();
2085
                }
2086
	}
2087
	public static function check_last_schedules_update() {
2088
		global $globalDBdriver;
2089
		if ($globalDBdriver == 'mysql') {
2090
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2091
		} else {
2092
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2093
		}
2094
		try {
2095
			$Connection = new Connection();
2096
			$sth = $Connection->db->prepare($query);
2097
                        $sth->execute();
2098
                } catch(PDOException $e) {
2099
                        return "error : ".$e->getMessage();
2100
                }
2101
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2102
                if ($row['nb'] > 0) return false;
2103
                else return true;
2104
	}
2105
2106
	public static function insert_last_schedules_update() {
2107
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2108
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2109
		try {
2110
			$Connection = new Connection();
2111
			$sth = $Connection->db->prepare($query);
2112
                        $sth->execute();
2113
                } catch(PDOException $e) {
2114
                        return "error : ".$e->getMessage();
2115
                }
2116
	}
2117
	public static function check_last_tle_update() {
2118
		global $globalDBdriver;
2119
		if ($globalDBdriver == 'mysql') {
2120
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2121
		} else {
2122
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2123
		}
2124
		try {
2125
			$Connection = new Connection();
2126
			$sth = $Connection->db->prepare($query);
2127
                        $sth->execute();
2128
                } catch(PDOException $e) {
2129
                        return "error : ".$e->getMessage();
2130
                }
2131
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2132
                if ($row['nb'] > 0) return false;
2133
                else return true;
2134
	}
2135
2136
	public static function insert_last_tle_update() {
2137
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2138
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2139
		try {
2140
			$Connection = new Connection();
2141
			$sth = $Connection->db->prepare($query);
2142
                        $sth->execute();
2143
                } catch(PDOException $e) {
2144
                        return "error : ".$e->getMessage();
2145
                }
2146
	}
2147
	
2148
	public static function update_all() {
2149
		global $globalMasterServer;
2150
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2151
			echo update_db::update_routes();
2152
			echo update_db::update_translation();
2153
			echo update_db::update_translation_fam();
2154
			echo update_db::update_notam_fam();
2155
			//echo update_db::update_ModeS();
2156
			echo update_db::update_ModeS_fam();
2157
		}
2158
		echo update_db::update_ModeS_flarm();
2159
		echo update_db::update_ModeS_ogn();
2160
	}
2161
}
2162
2163
//echo update_db::update_airports();
2164
//echo update_db::translation();
2165
//echo update_db::update_waypoints();
2166
//echo update_db::update_airspace();
2167
//echo update_db::update_notam();
2168
//echo update_db::update_ivao();
2169
//echo update_db::update_ModeS_flarm();
2170
//echo update_db::update_ModeS_ogn();
2171
//echo update_db::update_aircraft();
2172
//$update_db = new update_db();
2173
//echo $update_db->update_owner();
2174
//update_db::update_translation_fam();
2175
//echo update_db::update_routes();
2176
//update_db::update_models();
2177
//echo $update_db::update_skyteam();
2178
//echo $update_db::update_tle();
2179
//echo update_db::update_notam_fam();
2180
//echo update_db::create_airspace();
2181
//echo update_db::update_ModeS();
2182
//echo update_db::update_ModeS_fam();
2183
?>
2184