Completed
Push — master ( a729dc...acd68c )
by Yannick
08:59
created

update_db::check_airspace_version()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 5
nop 1
dl 0
loc 13
rs 9.4285
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 tle($filename,$tletype) {
948
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
949
		global $tmp_dir, $globalTransaction;
950
		//$Spotter = new Spotter();
951
		
952
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
953
		try {
954
			$Connection = new Connection();
955
			$sth = $Connection->db->prepare($query);
956
                        $sth->execute(array(':source' => $filename));
957
                } catch(PDOException $e) {
958
                        return "error : ".$e->getMessage();
959
                }
960
		
961
		$Connection = new Connection();
962
		if (($handle = fopen($filename, 'r')) !== FALSE)
963
		{
964
			$i = 0;
965
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
966
			//$Connection->db->beginTransaction();
967
			$dbdata = array();
968
			while (($data = fgets($handle, 1000)) !== FALSE)
969
			{
970
				if ($i == 0) {
971
					$dbdata['name'] = trim($data);
972
					$i++;
973
				} elseif ($i == 1) {
974
					$dbdata['tle1'] = trim($data);
975
					$i++;
976
				} elseif ($i == 2) {
977
					$dbdata['tle2'] = trim($data);
978
					//print_r($dbdata);
979
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
980
					try {
981
						$sth = $Connection->db->prepare($query);
982
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
983
					} catch(PDOException $e) {
984
						return "error : ".$e->getMessage();
985
					}
986
987
					$i = 0;
988
				}
989
			}
990
			fclose($handle);
991
			//$Connection->db->commit();
992
		}
993
		return '';
994
        }
995
996
	/**
997
        * Convert a HTML table to an array
998
        * @param String $data HTML page
999
        * @return Array array of the tables in HTML page
1000
        */
1001
        private static function table2array($data) {
1002
                $html = str_get_html($data);
1003
                $tabledata=array();
1004
                foreach($html->find('tr') as $element)
1005
                {
1006
                        $td = array();
1007
                        foreach( $element->find('th') as $row)
1008
                        {
1009
                                $td [] = trim($row->plaintext);
1010
                        }
1011
                        $td=array_filter($td);
1012
                        $tabledata[] = $td;
1013
1014
                        $td = array();
1015
                        $tdi = array();
1016
                        foreach( $element->find('td') as $row)
1017
                        {
1018
                                $td [] = trim($row->plaintext);
1019
                                $tdi [] = trim($row->innertext);
1020
                        }
1021
                        $td=array_filter($td);
1022
                        $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...
1023
                    //    $tabledata[]=array_merge($td,$tdi);
1024
                        $tabledata[]=$td;
1025
                }
1026
                return(array_filter($tabledata));
1027
        }
1028
1029
       /**
1030
        * Get data from form result
1031
        * @param String $url form URL
1032
        * @return String the result
1033
        */
1034
        private static function getData($url) {
1035
                $ch = curl_init();
1036
                curl_setopt($ch, CURLOPT_URL, $url);
1037
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1038
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1039
                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');
1040
                return curl_exec($ch);
1041
        }
1042
/*
1043
	public static function waypoints() {
1044
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1045
		$table = update_db::table2array($data);
1046
//		print_r($table);
1047
		$query = 'TRUNCATE TABLE waypoints';
1048
		try {
1049
			$Connection = new Connection();
1050
			$sth = $Connection->db->prepare($query);
1051
                        $sth->execute();
1052
                } catch(PDOException $e) {
1053
                        return "error : ".$e->getMessage();
1054
                }
1055
1056
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1057
		$Connection = new Connection();
1058
		$sth_dest = $Connection->db->prepare($query_dest);
1059
		$Connection->db->beginTransaction();
1060
                foreach ($table as $row) {
1061
            		if ($row[0] != 'Ident') {
1062
				$ident = $row[0];
1063
				$latitude = $row[2];
1064
				$longitude = $row[3];
1065
				$control = $row[4];
1066
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1067
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1068
				try {
1069
					$sth_dest->execute($query_dest_values);
1070
				} catch(PDOException $e) {
1071
					return "error : ".$e->getMessage();
1072
				}
1073
			}
1074
                }
1075
		$Connection->db->commit();
1076
1077
	}
1078
*/
1079
	public static function waypoints($filename) {
1080
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1081
		global $tmp_dir, $globalTransaction;
1082
		//$Spotter = new Spotter();
1083
		//$out_file = $tmp_dir.'translation.zip';
1084
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1085
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1086
		$Connection = new Connection();
1087
		//update_db::unzip($out_file);
1088
		$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...
1089
		$delimiter = ' ';
1090
		if (($handle = fopen($filename, 'r')) !== FALSE)
1091
		{
1092
			$i = 0;
1093
			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...
1094
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1095
			{
1096
				$i++;
1097
				if($i > 3 && count($row) > 2) {
1098
					$data = array_values(array_filter($row));
1099
					$cntdata = count($data);
1100
					if ($cntdata > 10) {
1101
						$value = $data[9];
1102
						
1103
						for ($i =10;$i < $cntdata;$i++) {
1104
							$value .= ' '.$data[$i];
1105
						}
1106
						$data[9] = $value;
1107
					}
1108
					//print_r($data);
1109
					if (count($data) > 9) {
1110
						$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)';
1111
						try {
1112
							$sth = $Connection->db->prepare($query);
1113
							$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]));
1114
						} catch(PDOException $e) {
1115
							return "error : ".$e->getMessage();
1116
						}
1117
					}
1118
				}
1119
			}
1120
			fclose($handle);
1121
			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...
1122
		}
1123
		return '';
1124
        }
1125
1126
	public static function ivao_airlines($filename) {
1127
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1128
		global $tmp_dir, $globalTransaction;
1129
		//$query = 'TRUNCATE TABLE airlines';
1130
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1131
		try {
1132
			$Connection = new Connection();
1133
			$sth = $Connection->db->prepare($query);
1134
                        $sth->execute();
1135
                } catch(PDOException $e) {
1136
                        return "error : ".$e->getMessage();
1137
                }
1138
1139
		$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...
1140
		$delimiter = ':';
1141
		$Connection = new Connection();
1142
		if (($handle = fopen($filename, 'r')) !== FALSE)
1143
		{
1144
			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...
1145
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1146
			{
1147
				if(count($row) > 1) {
1148
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1149
					try {
1150
						$sth = $Connection->db->prepare($query);
1151
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1152
					} catch(PDOException $e) {
1153
						return "error : ".$e->getMessage();
1154
					}
1155
				}
1156
			}
1157
			fclose($handle);
1158
			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...
1159
		}
1160
		return '';
1161
        }
1162
	
1163
	public static function update_airspace() {
1164
		global $tmp_dir, $globalDBdriver;
1165
		include_once('class.create_db.php');
1166
		$Connection = new Connection();
1167
		if ($Connection->tableExists('airspace')) {
1168
			$query = 'DROP TABLE airspace';
1169
			try {
1170
				$sth = $Connection->db->prepare($query);
1171
                    		$sth->execute();
1172
	                } catch(PDOException $e) {
1173
				return "error : ".$e->getMessage();
1174
	                }
1175
	        }
1176
1177
1178
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1179
		else {
1180
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1181
			$query = "CREATE EXTENSION postgis";
1182
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1183
			try {
1184
				$sth = $Connection->db->prepare($query);
1185
				$sth->execute();
1186
			} catch(PDOException $e) {
1187
				return "error : ".$e->getMessage();
1188
			}
1189
		}
1190
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1191
		return $error;
1192
	}
1193
1194
	public static function update_notam_fam() {
1195
		global $tmp_dir, $globalDebug;
1196
		include_once('class.create_db.php');
1197
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1198
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1199
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1200
		$error = '';
1201
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1202
			if ($globalDebug) echo "Gunzip...";
1203
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1204
			if ($globalDebug) echo "Add to DB...";
1205
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1206
			$NOTAM = new NOTAM();
1207
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1208
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1209
		if ($error != '') {
1210
			return $error;
1211
		} elseif ($globalDebug) echo "Done\n";
1212
		return '';
1213
	}
1214
1215
	public static function update_vatsim() {
1216
		global $tmp_dir;
1217
		include_once('class.create_db.php');
1218
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1219
		return $error;
1220
	}
1221
	
1222
	public static function update_countries() {
1223
		global $tmp_dir, $globalDBdriver;
1224
		include_once('class.create_db.php');
1225
		$Connection = new Connection();
1226
		if ($Connection->tableExists('countries')) {
1227
			$query = 'DROP TABLE countries';
1228
			try {
1229
				$sth = $Connection->db->prepare($query);
1230
            	        	$sth->execute();
1231
	                } catch(PDOException $e) {
1232
    	                	echo "error : ".$e->getMessage();
1233
	                }
1234
		}
1235
		if ($globalDBdriver == 'mysql') {
1236
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1237
		} else {
1238
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1239
		}
1240
		$error = create_db::import_file($tmp_dir.'countries.sql');
1241
		return $error;
1242
	}
1243
1244
	
1245
	public static function update_waypoints() {
1246
		global $tmp_dir;
1247
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1248
//		update_db::unzip($tmp_dir.'AptNav.zip');
1249
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1250
//		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');
1251
		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');
1252
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1253
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1254
		return $error;
1255
	}
1256
1257
	public static function update_ivao() {
1258
		global $tmp_dir, $globalDebug;
1259
		$Common = new Common();
1260
		$error = '';
1261
		//Direct download forbidden
1262
		//if ($globalDebug) echo "IVAO : Download...";
1263
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1264
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1265
			if ($globalDebug) echo "Unzip...";
1266
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1267
			if ($globalDebug) echo "Add to DB...";
1268
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1269
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1270
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1271
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1272
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1273
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1274
		if ($error != '') {
1275
			return $error;
1276
		} elseif ($globalDebug) echo "Done\n";
1277
		return '';
1278
	}
1279
1280
	public static function update_routes() {
1281
		global $tmp_dir, $globalDebug;
1282
		$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...
1283
		if ($globalDebug) echo "Routes : Download...";
1284
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1285
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1286
			if ($globalDebug) echo "Gunzip...";
1287
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1288
			if ($globalDebug) echo "Add to DB...";
1289
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1290
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1291
		if ($error != '') {
1292
			return $error;
1293
		} elseif ($globalDebug) echo "Done\n";
1294
		return '';
1295
	}
1296
	public static function update_oneworld() {
1297
		global $tmp_dir, $globalDebug;
1298
		$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...
1299
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1300
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1301
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1302
			if ($globalDebug) echo "Gunzip...";
1303
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1304
			if ($globalDebug) echo "Add to DB...";
1305
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1306
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1307
		if ($error != '') {
1308
			return $error;
1309
		} elseif ($globalDebug) echo "Done\n";
1310
		return '';
1311
	}
1312
	public static function update_skyteam() {
1313
		global $tmp_dir, $globalDebug;
1314
		$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...
1315
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1316
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1317
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1318
			if ($globalDebug) echo "Gunzip...";
1319
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1320
			if ($globalDebug) echo "Add to DB...";
1321
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1322
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1323
		if ($error != '') {
1324
			return $error;
1325
		} elseif ($globalDebug) echo "Done\n";
1326
		return '';
1327
	}
1328
	public static function update_ModeS() {
1329
		global $tmp_dir, $globalDebug;
1330
/*
1331
		if ($globalDebug) echo "Modes : Download...";
1332
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1333
		if ($globalDebug) echo "Unzip...";
1334
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1335
		if ($globalDebug) echo "Add to DB...";
1336
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1337
		if ($error != true) {
1338
			echo $error;
1339
			exit;
1340
		} elseif ($globalDebug) echo "Done\n";
1341
*/
1342
		if ($globalDebug) echo "Modes : Download...";
1343
		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1344
		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1345
			if ($globalDebug) echo "Unzip...";
1346
			update_db::unzip($tmp_dir.'basestation_latest.zip');
1347
			if ($globalDebug) echo "Add to DB...";
1348
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1349
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1350
		if ($error != '') {
1351
			return $error;
1352
		} elseif ($globalDebug) echo "Done\n";
1353
		return '';
1354
	}
1355
1356
	public static function update_ModeS_flarm() {
1357
		global $tmp_dir, $globalDebug;
1358
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1359
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1360
		if (file_exists($tmp_dir.'data.fln')) {
1361
			if ($globalDebug) echo "Add to DB...";
1362
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1363
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1364
		if ($error != '') {
1365
			return $error;
1366
		} elseif ($globalDebug) echo "Done\n";
1367
		return '';
1368
	}
1369
1370
	public static function update_ModeS_ogn() {
1371
		global $tmp_dir, $globalDebug;
1372
		if ($globalDebug) echo "Modes OGN: Download...";
1373
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1374
		if (file_exists($tmp_dir.'ogn.csv')) {
1375
			if ($globalDebug) echo "Add to DB...";
1376
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1377
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1378
		if ($error != '') {
1379
			return $error;
1380
		} elseif ($globalDebug) echo "Done\n";
1381
		return '';
1382
	}
1383
1384
	public static function update_owner() {
1385
		global $tmp_dir, $globalDebug;
1386
		
1387
		if ($globalDebug) echo "Owner France: Download...";
1388
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1389
		if (file_exists($tmp_dir.'owner_f.csv')) {
1390
			if ($globalDebug) echo "Add to DB...";
1391
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1392
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1393
		if ($error != '') {
1394
			return $error;
1395
		} elseif ($globalDebug) echo "Done\n";
1396
		
1397
		if ($globalDebug) echo "Owner Ireland: Download...";
1398
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1399
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1400
			if ($globalDebug) echo "Add to DB...";
1401
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1402
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1403
		if ($error != '') {
1404
			return $error;
1405
		} elseif ($globalDebug) echo "Done\n";
1406
		if ($globalDebug) echo "Owner Switzerland: Download...";
1407
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1408
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1409
			if ($globalDebug) echo "Add to DB...";
1410
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1411
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1412
		if ($error != '') {
1413
			return $error;
1414
		} elseif ($globalDebug) echo "Done\n";
1415
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1416
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1417
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1418
			if ($globalDebug) echo "Add to DB...";
1419
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1420
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1421
		if ($error != '') {
1422
			return $error;
1423
		} elseif ($globalDebug) echo "Done\n";
1424
		if ($globalDebug) echo "Owner Australia: Download...";
1425
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1426
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1427
			if ($globalDebug) echo "Add to DB...";
1428
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1429
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1430
		if ($error != '') {
1431
			return $error;
1432
		} elseif ($globalDebug) echo "Done\n";
1433
		if ($globalDebug) echo "Owner Austria: Download...";
1434
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1435
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1436
			if ($globalDebug) echo "Add to DB...";
1437
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1438
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1439
		if ($error != '') {
1440
			return $error;
1441
		} elseif ($globalDebug) echo "Done\n";
1442
		if ($globalDebug) echo "Owner Chile: Download...";
1443
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1444
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1445
			if ($globalDebug) echo "Add to DB...";
1446
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1447
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1448
		if ($error != '') {
1449
			return $error;
1450
		} elseif ($globalDebug) echo "Done\n";
1451
		if ($globalDebug) echo "Owner Colombia: Download...";
1452
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1453
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1454
			if ($globalDebug) echo "Add to DB...";
1455
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1456
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1457
		if ($error != '') {
1458
			return $error;
1459
		} elseif ($globalDebug) echo "Done\n";
1460
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1461
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1462
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1463
			if ($globalDebug) echo "Add to DB...";
1464
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1465
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1466
		if ($error != '') {
1467
			return $error;
1468
		} elseif ($globalDebug) echo "Done\n";
1469
		if ($globalDebug) echo "Owner Brazil: Download...";
1470
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1471
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1472
			if ($globalDebug) echo "Add to DB...";
1473
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1474
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1475
		if ($error != '') {
1476
			return $error;
1477
		} elseif ($globalDebug) echo "Done\n";
1478
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1479
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1480
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1481
			if ($globalDebug) echo "Add to DB...";
1482
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1483
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1484
		if ($error != '') {
1485
			return $error;
1486
		} elseif ($globalDebug) echo "Done\n";
1487
		if ($globalDebug) echo "Owner Croatia: Download...";
1488
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1489
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1490
			if ($globalDebug) echo "Add to DB...";
1491
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1492
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1493
		if ($error != '') {
1494
			return $error;
1495
		} elseif ($globalDebug) echo "Done\n";
1496
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1497
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1498
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1499
			if ($globalDebug) echo "Add to DB...";
1500
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1501
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1502
		if ($error != '') {
1503
			return $error;
1504
		} elseif ($globalDebug) echo "Done\n";
1505
		if ($globalDebug) echo "Owner Maldives: Download...";
1506
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1507
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1508
			if ($globalDebug) echo "Add to DB...";
1509
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1510
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1511
		if ($error != '') {
1512
			return $error;
1513
		} elseif ($globalDebug) echo "Done\n";
1514
		if ($globalDebug) echo "Owner New Zealand: Download...";
1515
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1516
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1517
			if ($globalDebug) echo "Add to DB...";
1518
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1519
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1520
		if ($error != '') {
1521
			return $error;
1522
		} elseif ($globalDebug) echo "Done\n";
1523
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1524
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1525
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1526
			if ($globalDebug) echo "Add to DB...";
1527
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1528
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1529
		if ($error != '') {
1530
			return $error;
1531
		} elseif ($globalDebug) echo "Done\n";
1532
		if ($globalDebug) echo "Owner Slovakia: Download...";
1533
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1534
		if (file_exists($tmp_dir.'owner_om.csv')) {
1535
			if ($globalDebug) echo "Add to DB...";
1536
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1537
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1538
		if ($error != '') {
1539
			return $error;
1540
		} elseif ($globalDebug) echo "Done\n";
1541
		if ($globalDebug) echo "Owner Ecuador: Download...";
1542
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1543
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1544
			if ($globalDebug) echo "Add to DB...";
1545
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1546
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1547
		if ($error != '') {
1548
			return $error;
1549
		} elseif ($globalDebug) echo "Done\n";
1550
		if ($globalDebug) echo "Owner Iceland: Download...";
1551
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1552
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1553
			if ($globalDebug) echo "Add to DB...";
1554
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1555
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1556
		if ($error != '') {
1557
			return $error;
1558
		} elseif ($globalDebug) echo "Done\n";
1559
		return '';
1560
	}
1561
1562
	public static function update_translation() {
1563
		global $tmp_dir, $globalDebug;
1564
		$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...
1565
		if ($globalDebug) echo "Translation : Download...";
1566
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1567
		if (file_exists($tmp_dir.'translation.zip')) {
1568
			if ($globalDebug) echo "Unzip...";
1569
			update_db::unzip($tmp_dir.'translation.zip');
1570
			if ($globalDebug) echo "Add to DB...";
1571
			$error = update_db::translation();
1572
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1573
		if ($error != '') {
1574
			return $error;
1575
		} elseif ($globalDebug) echo "Done\n";
1576
		return '';
1577
	}
1578
1579
	public static function update_translation_fam() {
1580
		global $tmp_dir, $globalDebug;
1581
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1582
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1583
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1584
			if ($globalDebug) echo "Gunzip...";
1585
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1586
			if ($globalDebug) echo "Add to DB...";
1587
			$error = update_db::translation_fam();
1588
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1589
		if ($error != '') {
1590
			return $error;
1591
		} elseif ($globalDebug) echo "Done\n";
1592
		return '';
1593
	}
1594
1595
	public static function update_airspace_fam() {
1596
		global $tmp_dir, $globalDebug, $globalDBdriver;
1597
		include_once('class.create_db.php');
1598
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1599
		if ($globalDBdriver == 'mysql') {
1600
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1601
		} else {
1602
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1603
		}
1604
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1605
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1606
			$airspace_md5 = $airspace_md5_file[0];
1607
			if (!update_db::check_airspace_version($airspace_md5)) {
1608
				if ($globalDBdriver == 'mysql') {
1609
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1610
				} else {
1611
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1612
				}
1613
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1614
					if ($globalDebug) echo "Gunzip...";
1615
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1616
					if ($globalDebug) echo "Add to DB...";
1617
					$Connection = new Connection();
1618
					if ($Connection->tableExists('airspace')) {
1619
						$query = 'DROP TABLE airspace';
1620
						try {
1621
							$sth = $Connection->db->prepare($query);
1622
    	    	    					$sth->execute();
1623
			            		} catch(PDOException $e) {
1624
							return "error : ".$e->getMessage();
1625
		            			}
1626
		    			}
1627
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1628
					update_db::insert_airspace_version($airspace_md5);
1629
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1630
			}
1631
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1632
		if ($error != '') {
1633
			return $error;
0 ignored issues
show
Bug introduced by
The variable $error 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...
1634
		} elseif ($globalDebug) echo "Done\n";
1635
		return '';
1636
	}
1637
1638
	public static function update_tle() {
1639
		global $tmp_dir, $globalDebug;
1640
		if ($globalDebug) echo "Download TLE : Download...";
1641
		$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',
1642
		'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',
1643
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1644
		foreach ($alltle as $filename) {
1645
			if ($globalDebug) echo "downloading ".$filename.'...';
1646
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1647
			if (file_exists($tmp_dir.$filename)) {
1648
				if ($globalDebug) echo "Add to DB ".$filename."...";
1649
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1650
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1651
			if ($error != '') {
1652
				echo $error."\n";
1653
			} elseif ($globalDebug) echo "Done\n";
1654
		}
1655
		return '';
1656
	}
1657
1658
	public static function update_models() {
1659
		global $tmp_dir, $globalDebug;
1660
		$error = '';
1661
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1662
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
1663
		if (file_exists($tmp_dir.'models.md5sum')) {
1664
			if ($globalDebug) echo "Check files...\n";
1665
			$newmodelsdb = array();
1666
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
1667
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1668
					$model = trim($row[2]);
1669
					$newmodelsdb[$model] = trim($row[0]);
1670
				}
1671
			}
1672
			$modelsdb = array();
1673
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
1674
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
1675
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1676
						$model = trim($row[2]);
1677
						$modelsdb[$model] = trim($row[0]);
1678
					}
1679
				}
1680
			}
1681
			$diff = array_diff($newmodelsdb,$modelsdb);
1682
			foreach ($diff as $key => $value) {
1683
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
1684
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
1685
				
1686
			}
1687
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
1688
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1689
		if ($error != '') {
1690
			return $error;
1691
		} elseif ($globalDebug) echo "Done\n";
1692
		return '';
1693
	}
1694
1695
	public static function update_space_models() {
1696
		global $tmp_dir, $globalDebug;
1697
		$error = '';
1698
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
1699
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
1700
		if (file_exists($tmp_dir.'space_models.md5sum')) {
1701
			if ($globalDebug) echo "Check files...\n";
1702
			$newmodelsdb = array();
1703
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
1704
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1705
					$model = trim($row[2]);
1706
					$newmodelsdb[$model] = trim($row[0]);
1707
				}
1708
			}
1709
			$modelsdb = array();
1710
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
1711
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
1712
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
1713
						$model = trim($row[2]);
1714
						$modelsdb[$model] = trim($row[0]);
1715
					}
1716
				}
1717
			}
1718
			$diff = array_diff($newmodelsdb,$modelsdb);
1719
			foreach ($diff as $key => $value) {
1720
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
1721
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
1722
				
1723
			}
1724
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
1725
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
1726
		if ($error != '') {
1727
			return $error;
1728
		} elseif ($globalDebug) echo "Done\n";
1729
		return '';
1730
	}
1731
1732
	public static function update_aircraft() {
1733
		global $tmp_dir, $globalDebug;
1734
		date_default_timezone_set('UTC');
1735
		//$error = '';
1736
		/*
1737
		if ($globalDebug) echo "Aircrafts : Download...";
1738
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
1739
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
1740
		//$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);
1741
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
1742
//		echo strlen($data_req);
1743
		echo $data;
1744
		*/
1745
		if (file_exists($tmp_dir.'aircrafts.html')) {
1746
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
1747
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
1748
		    $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...
1749
		    //echo $result;
1750
		    //var_dump(str_get_html($result));
1751
		    //print_r(self::table2array($result));
1752
		}
1753
1754
	}
1755
	
1756
	public static function update_notam() {
1757
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
1758
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
1759
		$Common = new Common();
1760
		date_default_timezone_set('UTC');
1761
		$query = 'TRUNCATE TABLE notam';
1762
		try {
1763
			$Connection = new Connection();
1764
			$sth = $Connection->db->prepare($query);
1765
                        $sth->execute();
1766
                } catch(PDOException $e) {
1767
                        return "error : ".$e->getMessage();
1768
                }
1769
1770
		$error = '';
1771
		if ($globalDebug) echo "Notam : Download...";
1772
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
1773
		if (file_exists($tmp_dir.'notam.rss')) {
1774
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
1775
			foreach ($notams['channel']['item'] as $notam) {
1776
				$title = explode(':',$notam['title']);
1777
				$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...
1778
				unset($title[0]);
1779
				$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...
1780
				$description = strip_tags($notam['description'],'<pre>');
1781
				preg_match(':^(.*?)<pre>:',$description,$match);
1782
				$q = explode('/',$match[1]);
1783
				$data['fir'] = $q[0];
1784
				$data['code'] = $q[1];
1785
				$ifrvfr = $q[2];
1786
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
1787
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
1788
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
1789
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
1790
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
1791
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
1792
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
1793
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
1794
				//$data['scope'] = $q[4];
1795
				$data['lower_limit'] = $q[5];
1796
				$data['upper_limit'] = $q[6];
1797
				$latlonrad = $q[7];
1798
				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...
1799
				$latitude = $Common->convertDec($las,'latitude');
1800
				$longitude = $Common->convertDec($lns,'longitude');
1801
				if ($lac == 'S') $latitude = '-'.$latitude;
1802
				if ($lnc == 'W') $longitude = '-'.$longitude;
1803
				$data['center_latitude'] = $latitude;
1804
				$data['center_longitude'] = $longitude;
1805
				$data['radius'] = intval($radius);
1806
				
1807
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
1808
				$data['text'] = $match[1];
1809
				preg_match(':</pre>(.*?)$:',$description,$match);
1810
				$fromto = $match[1];
1811
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
1812
				$fromall = trim($match[1]);
1813
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
1814
				$from = trim($match[1]);
1815
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
1816
				preg_match('#TO:(.*?)$#',$fromto,$match);
1817
				$toall = trim($match[1]);
1818
				if (!preg_match(':Permanent:',$toall)) {
1819
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
1820
					$to = trim($match[1]);
1821
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
1822
					$data['permanent'] = 0;
1823
				} else {
1824
				    $data['date_end'] = NULL;
1825
				    $data['permanent'] = 1;
1826
				}
1827
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
1828
				$NOTAM = new NOTAM();
1829
				$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']);
1830
				unset($data);
1831
			} 
1832
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
1833
		if ($error != '') {
1834
			return $error;
1835
		} elseif ($globalDebug) echo "Done\n";
1836
		return '';
1837
	}
1838
	
1839
	public static function create_airspace() {
1840
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
1841
		$Connection = new Connection();
1842
		if ($Connection->tableExists('airspace')) {
1843
			if ($globalDBdriver == 'mysql') {
1844
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
1845
			} else {
1846
				$query = 'DROP TABLE airspace';
1847
			}
1848
			try {
1849
				$Connection = new Connection();
1850
				$sth = $Connection->db->prepare($query);
1851
				$sth->execute();
1852
			} catch(PDOException $e) {
1853
				return "error : ".$e->getMessage();
1854
			}
1855
		}
1856
		$Common = new Common();
1857
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
1858
		$airspace_json = json_decode($airspace_lst,true);
1859
		foreach ($airspace_json['records'] as $airspace) {
1860
			if ($globalDebug) echo $airspace['name']."...\n";
1861
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
1862
			if (file_exists($tmp_dir.$airspace['name'])) {
1863
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
1864
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
1865
				if ($globalDBdriver == 'mysql') {
1866
					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'].'"');
1867
				} else {
1868
					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'].'"');
1869
				}
1870
			}
1871
		}
1872
	}
1873
	
1874
	public static function check_last_update() {
1875
		global $globalDBdriver;
1876
		if ($globalDBdriver == 'mysql') {
1877
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
1878
		} else {
1879
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1880
		}
1881
		try {
1882
			$Connection = new Connection();
1883
			$sth = $Connection->db->prepare($query);
1884
                        $sth->execute();
1885
                } catch(PDOException $e) {
1886
                        return "error : ".$e->getMessage();
1887
                }
1888
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1889
                if ($row['nb'] > 0) return false;
1890
                else return true;
1891
	}
1892
1893
	public static function insert_last_update() {
1894
		$query = "DELETE FROM config WHERE name = 'last_update_db';
1895
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
1896
		try {
1897
			$Connection = new Connection();
1898
			$sth = $Connection->db->prepare($query);
1899
                        $sth->execute();
1900
                } catch(PDOException $e) {
1901
                        return "error : ".$e->getMessage();
1902
                }
1903
	}
1904
1905
	public static function check_airspace_version($version) {
1906
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
1907
		try {
1908
			$Connection = new Connection();
1909
			$sth = $Connection->db->prepare($query);
1910
                        $sth->execute(array(':version' => $version));
1911
                } catch(PDOException $e) {
1912
                        return "error : ".$e->getMessage();
1913
                }
1914
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1915
                if ($row['nb'] > 0) return true;
1916
                else return false;
1917
	}
1918
1919
1920
	public static function insert_airspace_version($version) {
1921
		$query = "DELETE FROM config WHERE name = 'airspace_version';
1922
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
1923
		try {
1924
			$Connection = new Connection();
1925
			$sth = $Connection->db->prepare($query);
1926
                        $sth->execute(array(':version' => $version));
1927
                } catch(PDOException $e) {
1928
                        return "error : ".$e->getMessage();
1929
                }
1930
	}
1931
1932
	public static function check_last_notam_update() {
1933
		global $globalDBdriver;
1934
		if ($globalDBdriver == 'mysql') {
1935
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
1936
		} else {
1937
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
1938
		}
1939
		try {
1940
			$Connection = new Connection();
1941
			$sth = $Connection->db->prepare($query);
1942
                        $sth->execute();
1943
                } catch(PDOException $e) {
1944
                        return "error : ".$e->getMessage();
1945
                }
1946
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1947
                if ($row['nb'] > 0) return false;
1948
                else return true;
1949
	}
1950
1951
	public static function insert_last_notam_update() {
1952
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
1953
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
1954
		try {
1955
			$Connection = new Connection();
1956
			$sth = $Connection->db->prepare($query);
1957
                        $sth->execute();
1958
                } catch(PDOException $e) {
1959
                        return "error : ".$e->getMessage();
1960
                }
1961
	}
1962
	public static function check_last_airspace_update() {
1963
		global $globalDBdriver;
1964
		if ($globalDBdriver == 'mysql') {
1965
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
1966
		} else {
1967
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
1968
		}
1969
		try {
1970
			$Connection = new Connection();
1971
			$sth = $Connection->db->prepare($query);
1972
                        $sth->execute();
1973
                } catch(PDOException $e) {
1974
                        return "error : ".$e->getMessage();
1975
                }
1976
                $row = $sth->fetch(PDO::FETCH_ASSOC);
1977
                if ($row['nb'] > 0) return false;
1978
                else return true;
1979
	}
1980
1981
	public static function insert_last_airspace_update() {
1982
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
1983
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
1984
		try {
1985
			$Connection = new Connection();
1986
			$sth = $Connection->db->prepare($query);
1987
                        $sth->execute();
1988
                } catch(PDOException $e) {
1989
                        return "error : ".$e->getMessage();
1990
                }
1991
	}
1992
1993
	public static function check_last_owner_update() {
1994
		global $globalDBdriver;
1995
		if ($globalDBdriver == 'mysql') {
1996
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
1997
		} else {
1998
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
1999
		}
2000
		try {
2001
			$Connection = new Connection();
2002
			$sth = $Connection->db->prepare($query);
2003
                        $sth->execute();
2004
                } catch(PDOException $e) {
2005
                        return "error : ".$e->getMessage();
2006
                }
2007
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2008
                if ($row['nb'] > 0) return false;
2009
                else return true;
2010
	}
2011
2012
	public static function insert_last_owner_update() {
2013
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2014
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2015
		try {
2016
			$Connection = new Connection();
2017
			$sth = $Connection->db->prepare($query);
2018
                        $sth->execute();
2019
                } catch(PDOException $e) {
2020
                        return "error : ".$e->getMessage();
2021
                }
2022
	}
2023
	public static function check_last_schedules_update() {
2024
		global $globalDBdriver;
2025
		if ($globalDBdriver == 'mysql') {
2026
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2027
		} else {
2028
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2029
		}
2030
		try {
2031
			$Connection = new Connection();
2032
			$sth = $Connection->db->prepare($query);
2033
                        $sth->execute();
2034
                } catch(PDOException $e) {
2035
                        return "error : ".$e->getMessage();
2036
                }
2037
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2038
                if ($row['nb'] > 0) return false;
2039
                else return true;
2040
	}
2041
2042
	public static function insert_last_schedules_update() {
2043
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2044
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2045
		try {
2046
			$Connection = new Connection();
2047
			$sth = $Connection->db->prepare($query);
2048
                        $sth->execute();
2049
                } catch(PDOException $e) {
2050
                        return "error : ".$e->getMessage();
2051
                }
2052
	}
2053
	public static function check_last_tle_update() {
2054
		global $globalDBdriver;
2055
		if ($globalDBdriver == 'mysql') {
2056
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2057
		} else {
2058
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2059
		}
2060
		try {
2061
			$Connection = new Connection();
2062
			$sth = $Connection->db->prepare($query);
2063
                        $sth->execute();
2064
                } catch(PDOException $e) {
2065
                        return "error : ".$e->getMessage();
2066
                }
2067
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2068
                if ($row['nb'] > 0) return false;
2069
                else return true;
2070
	}
2071
2072
	public static function insert_last_tle_update() {
2073
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2074
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2075
		try {
2076
			$Connection = new Connection();
2077
			$sth = $Connection->db->prepare($query);
2078
                        $sth->execute();
2079
                } catch(PDOException $e) {
2080
                        return "error : ".$e->getMessage();
2081
                }
2082
	}
2083
	
2084
	public static function update_all() {
2085
		global $globalMasterServer;
2086
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2087
			echo update_db::update_routes();
2088
			echo update_db::update_translation();
2089
			echo update_db::update_translation_fam();
2090
			echo update_db::update_notam_fam();
2091
		}
2092
		echo update_db::update_ModeS();
2093
		echo update_db::update_ModeS_flarm();
2094
		echo update_db::update_ModeS_ogn();
2095
	}
2096
}
2097
2098
//echo update_db::update_airports();
2099
//echo update_db::translation();
2100
//echo update_db::update_waypoints();
2101
//echo update_db::update_airspace();
2102
//echo update_db::update_notam();
2103
//echo update_db::update_ivao();
2104
//echo update_db::update_ModeS_flarm();
2105
//echo update_db::update_ModeS_ogn();
2106
//echo update_db::update_aircraft();
2107
//$update_db = new update_db();
2108
//echo $update_db->update_owner();
2109
//update_db::update_translation_fam();
2110
//echo update_db::update_routes();
2111
//update_db::update_models();
2112
//echo $update_db::update_skyteam();
2113
//echo $update_db::update_tle();
2114
//echo update_db::update_notam_fam();
2115
//echo update_db::create_airspace();
2116
?>
2117