Completed
Push — master ( 5e27ff...ea1d88 )
by Yannick
06:20
created

update_db::modes_fam()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 27
nc 16
nop 0
dl 0
loc 40
rs 4.909
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
		// Remove data already in DB from ACARS
249
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
250
		try {
251
			$Connection = new Connection();
252
			$sth = $Connection->db->prepare($query);
253
                        $sth->execute(array(':source' => $database_file));
254
                } catch(PDOException $e) {
255
                        return "error : ".$e->getMessage();
256
                }
257
		return '';
258
	}
259
260
	public static function retrieve_modes_flarmnet($database_file) {
261
		global $globalTransaction;
262
		$Common = new Common();
263
		//$query = 'TRUNCATE TABLE aircraft_modes';
264
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
265
		try {
266
			$Connection = new Connection();
267
			$sth = $Connection->db->prepare($query);
268
                        $sth->execute(array(':source' => $database_file));
269
                } catch(PDOException $e) {
270
                        return "error : ".$e->getMessage();
271
                }
272
		
273
		if ($fh = fopen($database_file,"r")) {
274
			//$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)';
275
			$query_dest = 'INSERT INTO aircraft_modes (ModeS,Registration,ICAOTypeCode,Source) VALUES (:ModeS,:Registration,:ICAOTypeCode,:source)';
276
		
277
			$Connection = new Connection();
278
			$sth_dest = $Connection->db->prepare($query_dest);
279
			try {
280
				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...
281
            			while (!feof($fh)) {
282
            				$values = array();
283
            				$line = $Common->hex2str(fgets($fh,9999));
284
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
285
            				$values['ModeS'] = substr($line,0,6);
286
            				$values['Registration'] = trim(substr($line,69,6));
287
            				$aircraft_name = trim(substr($line,48,6));
288
            				// Check if we can find ICAO, else set it to GLID
289
            				$aircraft_name_split = explode(' ',$aircraft_name);
290
            				$search_more = '';
291
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
292
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
293
            				$sth_search = $Connection->db->prepare($query_search);
294
					try {
295
                                    		$sth_search->execute();
296
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
297
	            				//if (count($result) > 0) {
298
	            				if (isset($result['icao']) && $result['icao'] != '') {
299
	            				    $values['ICAOTypeCode'] = $result['icao'];
300
	            				} 
301
					} catch(PDOException $e) {
302
						return "error : ".$e->getMessage();
303
					}
304
					if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
305
					// Add data to db
306
					if ($values['Registration'] != '' && $values['Registration'] != '0000') {
307
						//$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']);
308
						$query_dest_values = array(':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
309
						//print_r($query_dest_values);
310
						$sth_dest->execute($query_dest_values);
311
					}
312
				}
313
				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...
314
			} catch(PDOException $e) {
315
				return "error : ".$e->getMessage();
316
			}
317
		}
318
319
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
320
		try {
321
			$Connection = new Connection();
322
			$sth = $Connection->db->prepare($query);
323
                        $sth->execute(array(':source' => $database_file));
324
                } catch(PDOException $e) {
325
                        return "error : ".$e->getMessage();
326
                }
327
		return '';
328
	}
329
330
	public static function retrieve_modes_ogn($database_file) {
331
		global $globalTransaction;
332
		//$query = 'TRUNCATE TABLE aircraft_modes';
333
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source IS NULL OR Source = :source";
334
		try {
335
			$Connection = new Connection();
336
			$sth = $Connection->db->prepare($query);
337
                        $sth->execute(array(':source' => $database_file));
338
                } catch(PDOException $e) {
339
                        return "error : ".$e->getMessage();
340
                }
341
		
342
		if ($fh = fopen($database_file,"r")) {
343
			//$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)';
344
			$query_dest = 'INSERT INTO aircraft_modes (LastModified,ModeS,Registration,ICAOTypeCode,Source) VALUES (:lastmodified,:ModeS,:Registration,:ICAOTypeCode,:source)';
345
		
346
			$Connection = new Connection();
347
			$sth_dest = $Connection->db->prepare($query_dest);
348
			try {
349
				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...
350
				$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...
351
            			while (!feof($fh)) {
352
            				$line = fgetcsv($fh,9999,',',"'");
353
            				
354
					//FFFFFF                     RIDEAU VALLEY SOARINGASW-20               C-FBKN MZ 123.400
355
					//print_r($line);
356
            				$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...
357
            				$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...
358
            				$aircraft_name = $line[2];
359
            				// Check if we can find ICAO, else set it to GLID
360
            				$aircraft_name_split = explode(' ',$aircraft_name);
361
            				$search_more = '';
362
            				if (count($aircraft_name) > 1 && strlen($aircraft_name_split[1]) > 3) $search_more .= " AND LIKE '%".$aircraft_name_split[0]."%'";
363
            				$query_search = "SELECT * FROM aircraft WHERE type LIKE '%".$aircraft_name."%'".$search_more;
364
            				$sth_search = $Connection->db->prepare($query_search);
365
					try {
366
                                    		$sth_search->execute();
367
	            				$result = $sth_search->fetch(PDO::FETCH_ASSOC);
368
	            				if (isset($result['icao']) && $result['icao'] != '') $values['ICAOTypeCode'] = $result['icao'];
369
					} catch(PDOException $e) {
370
						return "error : ".$e->getMessage();
371
					}
372
					//if (!isset($values['ICAOTypeCode'])) $values['ICAOTypeCode'] = 'GLID';
373
					// Add data to db
374
					if ($values['Registration'] != '' && $values['Registration'] != '0000' && $values['ICAOTypeCode'] != '') {
375
						//$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']);
376
						$query_dest_values = array(':lastmodified' => date('Y-m-d H:m:s'),':ModeS' => $values['ModeS'],':Registration' => $values['Registration'],':ICAOTypeCode' => $values['ICAOTypeCode'],':source' => $database_file);
377
						//print_r($query_dest_values);
378
						$sth_dest->execute($query_dest_values);
379
					}
380
				}
381
				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...
382
			} catch(PDOException $e) {
383
				return "error : ".$e->getMessage();
384
			}
385
		}
386
387
		$query = "DELETE FROM aircraft_modes WHERE Source = :source AND ModeS IN (SELECT * FROM (SELECT ModeS FROM aircraft_modes WHERE Source = 'ACARS') _alias)";
388
		try {
389
			$Connection = new Connection();
390
			$sth = $Connection->db->prepare($query);
391
                        $sth->execute(array(':source' => $database_file));
392
                } catch(PDOException $e) {
393
                        return "error : ".$e->getMessage();
394
                }
395
		return '';
396
	}
397
398
	public static function retrieve_owner($database_file,$country = 'F') {
399
		global $globalTransaction;
400
		//$query = 'TRUNCATE TABLE aircraft_modes';
401
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source IS NULL OR Source = :source";
402
		try {
403
			$Connection = new Connection();
404
			$sth = $Connection->db->prepare($query);
405
                        $sth->execute(array(':source' => $database_file));
406
                } catch(PDOException $e) {
407
                        return "error : ".$e->getMessage();
408
                }
409
		
410
		if ($fh = fopen($database_file,"r")) {
411
			//$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)';
412
			$query_dest = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
413
		
414
			$Connection = new Connection();
415
			$sth_dest = $Connection->db->prepare($query_dest);
416
			try {
417
				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...
418
				$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...
419
            			while (!feof($fh)) {
420
            				$line = fgetcsv($fh,9999,',','"');
421
            				$values = array();
422
            				//print_r($line);
423
            				if ($country == 'F') {
424
            				    $values['registration'] = $line[0];
425
            				    $values['base'] = $line[4];
426
            				    $values['owner'] = $line[5];
427
            				    if ($line[6] == '') $values['date_first_reg'] = null;
428
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
429
					    $values['cancel'] = $line[7];
430
					} elseif ($country == 'EI') {
431
					    // TODO : add modeS & reg to aircraft_modes
432
            				    $values['registration'] = $line[0];
433
            				    $values['base'] = $line[3];
434
            				    $values['owner'] = $line[2];
435
            				    if ($line[1] == '') $values['date_first_reg'] = null;
436
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[1]));
437
					    $values['cancel'] = '';
438
					} elseif ($country == 'HB') {
439
					    // TODO : add modeS & reg to aircraft_modes
440
            				    $values['registration'] = $line[0];
441
            				    $values['base'] = null;
442
            				    $values['owner'] = $line[5];
443
            				    $values['date_first_reg'] = null;
444
					    $values['cancel'] = '';
445
					} elseif ($country == 'OK') {
446
					    // TODO : add modeS & reg to aircraft_modes
447
            				    $values['registration'] = $line[3];
448
            				    $values['base'] = null;
449
            				    $values['owner'] = $line[5];
450
            				    if ($line[18] == '') $values['date_first_reg'] = null;
451
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[18]));
452
					    $values['cancel'] = '';
453
					} elseif ($country == 'VH') {
454
					    // TODO : add modeS & reg to aircraft_modes
455
            				    $values['registration'] = $line[0];
456
            				    $values['base'] = null;
457
            				    $values['owner'] = $line[12];
458
            				    if ($line[28] == '') $values['date_first_reg'] = null;
459
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[28]));
460
461
					    $values['cancel'] = $line[39];
462
					} elseif ($country == 'OE' || $country == '9A' || $country == 'VP' || $country == 'LX' || $country == 'P2' || $country == 'HC') {
463
            				    $values['registration'] = $line[0];
464
            				    $values['base'] = null;
465
            				    $values['owner'] = $line[4];
466
            				    $values['date_first_reg'] = null;
467
					    $values['cancel'] = '';
468
					} elseif ($country == 'CC') {
469
            				    $values['registration'] = $line[0];
470
            				    $values['base'] = null;
471
            				    $values['owner'] = $line[6];
472
            				    $values['date_first_reg'] = null;
473
					    $values['cancel'] = '';
474
					} elseif ($country == 'HJ') {
475
            				    $values['registration'] = $line[0];
476
            				    $values['base'] = null;
477
            				    $values['owner'] = $line[8];
478
            				    if ($line[7] == '') $values['date_first_reg'] = null;
479
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
480
					    $values['cancel'] = '';
481
					} elseif ($country == 'PP') {
482
            				    $values['registration'] = $line[0];
483
            				    $values['base'] = null;
484
            				    $values['owner'] = $line[4];
485
            				    if ($line[6] == '') $values['date_first_reg'] = null;
486
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[6]));
487
					    $values['cancel'] = $line[7];
488
					} elseif ($country == 'E7') {
489
            				    $values['registration'] = $line[0];
490
            				    $values['base'] = null;
491
            				    $values['owner'] = $line[4];
492
            				    if ($line[5] == '') $values['date_first_reg'] = null;
493
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[5]));
494
					    $values['cancel'] = '';
495
					} elseif ($country == '8Q') {
496
            				    $values['registration'] = $line[0];
497
            				    $values['base'] = null;
498
            				    $values['owner'] = $line[3];
499
            				    if ($line[7] == '') $values['date_first_reg'] = null;
500
					    else $values['date_first_reg'] = date("Y-m-d",strtotime($line[7]));
501
					    $values['cancel'] = '';
502
					} elseif ($country == 'ZK' || $country == 'OM' || $country == 'TF') {
503
            				    $values['registration'] = $line[0];
504
            				    $values['base'] = null;
505
            				    $values['owner'] = $line[3];
506
            				    $values['date_first_reg'] = null;
507
					    $values['cancel'] = '';
508
					}
509
					if ($values['cancel'] == '' && $values['registration'] != null) {
510
						$query_dest_values = array(':registration' => $values['registration'],':base' => $values['base'],':date_first_reg' => $values['date_first_reg'],':owner' => $values['owner'],':source' => $database_file);
511
						$sth_dest->execute($query_dest_values);
512
					}
513
				}
514
				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...
515
			} catch(PDOException $e) {
516
				return "error : ".$e->getMessage();
517
			}
518
		}
519
		return '';
520
	}
521
522
	/*
523
	* This function is used to create a list of airports. Sources : Wikipedia, ourairports.com ans partow.net
524
	*/
525
	public static function update_airports() {
526
		global $tmp_dir, $globalTransaction, $globalDebug;
527
528
		require_once(dirname(__FILE__).'/libs/sparqllib.php');
529
		$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...
530
		$query = '
531
		    PREFIX dbo: <http://dbpedia.org/ontology/>
532
		    PREFIX dbp: <http://dbpedia.org/property/>
533
		    PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
534
		    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
535
		    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
536
		    SELECT ?name ?icao ?iata ?faa ?lid ?latitude ?longitude ?airport ?homepage ?type ?country ?country_bis ?altitude ?image
537
		    FROM <http://dbpedia.org>
538
		    WHERE {
539
			?airport rdf:type <http://dbpedia.org/ontology/Airport> .
540
541
			OPTIONAL {
542
			    ?airport dbo:icaoLocationIdentifier ?icao .
543
			    FILTER regex(?icao, "^[A-Z0-9]{4}$")
544
			}
545
546
			OPTIONAL {
547
			    ?airport dbo:iataLocationIdentifier ?iata .
548
			    FILTER regex(?iata, "^[A-Z0-9]{3}$")
549
			}
550
551
			OPTIONAL {
552
			    ?airport dbo:locationIdentifier ?lid .
553
			    FILTER regex(?lid, "^[A-Z0-9]{4}$")
554
			    FILTER (!bound(?icao) || (bound(?icao) && (?icao != ?lid)))
555
			    OPTIONAL {
556
				?airport_y rdf:type <http://dbpedia.org/ontology/Airport> .
557
				?airport_y dbo:icaoLocationIdentifier ?other_icao .
558
				FILTER (bound(?lid) && (?airport_y != ?airport && ?lid = ?other_icao))
559
			    }
560
			    FILTER (!bound(?other_icao))
561
			}
562
563
			OPTIONAL {
564
			    ?airport dbo:faaLocationIdentifier ?faa .
565
			    FILTER regex(?faa, "^[A-Z0-9]{3}$")
566
			    FILTER (!bound(?iata) || (bound(?iata) && (?iata != ?faa)))
567
			    OPTIONAL {
568
				?airport_x rdf:type <http://dbpedia.org/ontology/Airport> .
569
				?airport_x dbo:iataLocationIdentifier ?other_iata .
570
				FILTER (bound(?faa) && (?airport_x != ?airport && ?faa = ?other_iata))
571
			    }
572
			    FILTER (!bound(?other_iata))
573
			}
574
575
			FILTER (bound(?icao) || bound(?iata) || bound(?faa) || bound(?lid))
576
	
577
			OPTIONAL {
578
			    ?airport rdfs:label ?name
579
			    FILTER (lang(?name) = "en")
580
			}
581
    
582
			OPTIONAL {
583
			    ?airport foaf:homepage ?homepage
584
			}
585
		    
586
			OPTIONAL {
587
			    ?airport dbp:coordinatesRegion ?country
588
			}
589
    
590
			OPTIONAL {
591
			    ?airport dbp:type ?type
592
			}
593
			
594
			OPTIONAL {
595
			    ?airport dbo:elevation ?altitude
596
			}
597
			OPTIONAL {
598
			    ?airport dbp:image ?image
599
			}
600
601
			{
602
			    ?airport geo:lat ?latitude .
603
			    ?airport geo:long ?longitude .
604
			    FILTER (datatype(?latitude) = xsd:float)
605
			    FILTER (datatype(?longitude) = xsd:float)
606
			} UNION {
607
			    ?airport geo:lat ?latitude .
608
			    ?airport geo:long ?longitude .
609
			    FILTER (datatype(?latitude) = xsd:double)
610
			    FILTER (datatype(?longitude) = xsd:double)
611
			    OPTIONAL {
612
				?airport geo:lat ?lat_f .
613
				?airport geo:long ?long_f .
614
				FILTER (datatype(?lat_f) = xsd:float)
615
				FILTER (datatype(?long_f) = xsd:float)
616
			    }
617
			    FILTER (!bound(?lat_f) && !bound(?long_f))
618
			}
619
620
		    }
621
		    ORDER BY ?airport
622
		';
623
		$result = sparql_query($query);
624
  
625
		$query = 'TRUNCATE TABLE airport';
626
		try {
627
			$Connection = new Connection();
628
			$sth = $Connection->db->prepare($query);
629
                        $sth->execute();
630
                } catch(PDOException $e) {
631
                        return "error : ".$e->getMessage();
632
                }
633
634
635
		$query = 'ALTER TABLE airport DROP INDEX icaoidx';
636
		try {
637
			$Connection = new Connection();
638
			$sth = $Connection->db->prepare($query);
639
                        $sth->execute();
640
                } catch(PDOException $e) {
641
                        return "error : ".$e->getMessage();
642
                }
643
644
		$query_dest = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image_thumb`,`image`)
645
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image_thumb, :image)";
646
		$Connection = new Connection();
647
		$sth_dest = $Connection->db->prepare($query_dest);
648
		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...
649
  
650
		$i = 0;
651
		while($row = sparql_fetch_array($result))
652
		{
653
			if ($i >= 1) {
654
			//print_r($row);
655
			if (!isset($row['iata'])) $row['iata'] = '';
656
			if (!isset($row['icao'])) $row['icao'] = '';
657
			if (!isset($row['type'])) $row['type'] = '';
658
			if (!isset($row['altitude'])) $row['altitude'] = '';
659
			if (isset($row['city_bis'])) {
660
				$row['city'] = $row['city_bis'];
661
			}
662
			if (!isset($row['city'])) $row['city'] = '';
663
			if (!isset($row['country'])) $row['country'] = '';
664
			if (!isset($row['homepage'])) $row['homepage'] = '';
665
			if (!isset($row['wikipedia_page'])) $row['wikipedia_page'] = '';
666
			if (!isset($row['name'])) continue;
667
			if (!isset($row['image'])) {
668
				$row['image'] = '';
669
				$row['image_thumb'] = '';
670
			} else {
671
				$image = str_replace(' ','_',$row['image']);
672
				$digest = md5($image);
673
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image . '/220px-' . $image;
674
				$row['image_thumb'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/' . $folder;
675
				$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' . $image;
676
				$row['image'] = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
677
			}
678
			
679
			$country = explode('-',$row['country']);
680
			$row['country'] = $country[0];
681
			
682
			$row['type'] = trim($row['type']);
683
			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'])) {
684
				$row['type'] = 'Military';
685
			} 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') {
686
				$row['type'] = 'small_airport';
687
			}
688
			
689
			$row['city'] = urldecode(str_replace('_',' ',str_replace('http://dbpedia.org/resource/','',$row['city'])));
690
			$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']);
691
			//print_r($query_dest_values);
692
			
693
			try {
694
				$sth_dest->execute($query_dest_values);
695
			} catch(PDOException $e) {
696
				return "error : ".$e->getMessage();
697
			}
698
			}
699
700
			$i++;
701
		}
702
		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...
703
		echo "Delete duplicate rows...\n";
704
		$query = 'ALTER IGNORE TABLE airport ADD UNIQUE INDEX icaoidx (icao)';
705
		try {
706
			$Connection = new Connection();
707
			$sth = $Connection->db->prepare($query);
708
                        $sth->execute();
709
                } catch(PDOException $e) {
710
                        return "error : ".$e->getMessage();
711
                }
712
713
714
		if ($globalDebug) echo "Insert Not available Airport...\n";
715
		$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`,`image`,`image_thumb`)
716
		    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link, :image, :image_thumb)";
717
		$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' => '');
718
		try {
719
			$Connection = new Connection();
720
			$sth = $Connection->db->prepare($query);
721
                        $sth->execute($query_values);
722
                } catch(PDOException $e) {
723
                        return "error : ".$e->getMessage();
724
                }
725
		$i++;
726
/*
727
		$query = 'DELETE FROM airport WHERE airport_id IN (SELECT * FROM (SELECT min(a.airport_id) FROM airport a GROUP BY a.icao) x)';
728
		try {
729
			$Connection = new Connection();
730
			$sth = $Connection->db->prepare($query);
731
                        $sth->execute();
732
                } catch(PDOException $e) {
733
                        return "error : ".$e->getMessage();
734
                }
735
*/
736
737
		echo "Download data from ourairports.com...\n";
738
		$delimiter = ',';
739
		$out_file = $tmp_dir.'airports.csv';
740
		update_db::download('http://ourairports.com/data/airports.csv',$out_file);
741
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
742
		echo "Add data from ourairports.com...\n";
743
744
		$header = NULL;
745
		if (($handle = fopen($out_file, 'r')) !== FALSE)
746
		{
747
			$Connection = new Connection();
748
			//$Connection->db->beginTransaction();
749
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
750
			{
751
				if(!$header) $header = $row;
752
				else {
753
					$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...
754
					$data = array_combine($header, $row);
755
					try {
756
						$sth = $Connection->db->prepare('SELECT COUNT(*) FROM airport WHERE `icao` = :icao');
757
						$sth->execute(array(':icao' => $data['gps_code']));
758
					} catch(PDOException $e) {
759
						return "error : ".$e->getMessage();
760
					}
761
					if ($sth->fetchColumn() > 0) {
762
						$query = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
763
						try {
764
							$sth = $Connection->db->prepare($query);
765
							$sth->execute(array(':icao' => $data['gps_code'],':type' => $data['type']));
766
						} catch(PDOException $e) {
767
							return "error : ".$e->getMessage();
768
						}
769
					} else {
770
						$query = "INSERT INTO airport (`airport_id`,`name`,`city`,`country`,`iata`,`icao`,`latitude`,`longitude`,`altitude`,`type`,`home_link`,`wikipedia_link`)
771
						    VALUES (:airport_id, :name, :city, :country, :iata, :icao, :latitude, :longitude, :altitude, :type, :home_link, :wikipedia_link)";
772
						$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']);
773
						try {
774
							$sth = $Connection->db->prepare($query);
775
							$sth->execute($query_values);
776
						} catch(PDOException $e) {
777
							return "error : ".$e->getMessage();
778
						}
779
						$i++;
780
					}
781
				}
782
			}
783
			fclose($handle);
784
			//$Connection->db->commit();
785
		}
786
787
		echo "Download data from another free database...\n";
788
		$out_file = $tmp_dir.'GlobalAirportDatabase.zip';
789
		update_db::download('http://www.partow.net/downloads/GlobalAirportDatabase.zip',$out_file);
790
		if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
791
		update_db::unzip($out_file);
792
		$header = NULL;
793
		echo "Add data from another free database...\n";
794
		$delimiter = ':';
795
		$Connection = new Connection();
796
		if (($handle = fopen($tmp_dir.'GlobalAirportDatabase.txt', 'r')) !== FALSE)
797
		{
798
			//$Connection->db->beginTransaction();
799
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
800
			{
801
				if(!$header) $header = $row;
802
				else {
803
					$data = $row;
804
805
					$query = 'UPDATE airport SET `city` = :city, `country` = :country WHERE icao = :icao';
806
					try {
807
						$sth = $Connection->db->prepare($query);
808
						$sth->execute(array(':icao' => $data[0],':city' => ucwords(strtolower($data[3])),':country' => ucwords(strtolower($data[4]))));
809
					} catch(PDOException $e) {
810
						return "error : ".$e->getMessage();
811
					}
812
				}
813
			}
814
			fclose($handle);
815
			//$Connection->db->commit();
816
		}
817
818
		echo "Put type military for all air base";
819
		$Connection = new Connection();
820
		try {
821
			$sth = $Connection->db->prepare("SELECT icao FROM airport WHERE `name` LIKE '%Air Base%'");
822
			$sth->execute();
823
		} catch(PDOException $e) {
824
			return "error : ".$e->getMessage();
825
		}
826
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
827
			$query2 = 'UPDATE airport SET `type` = :type WHERE icao = :icao';
828
			try {
829
				$sth2 = $Connection->db->prepare($query2);
830
				$sth2->execute(array(':icao' => $row['icao'],':type' => 'military'));
831
			} catch(PDOException $e) {
832
				return "error : ".$e->getMessage();
833
			}
834
		}
835
836
837
838
                return "success";
839
	}
840
	
841
	public static function translation() {
842
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
843
		global $tmp_dir, $globalTransaction;
844
		$Spotter = new Spotter();
845
		//$out_file = $tmp_dir.'translation.zip';
846
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
847
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
848
		
849
		//$query = 'TRUNCATE TABLE translation';
850
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
851
		try {
852
			$Connection = new Connection();
853
			$sth = $Connection->db->prepare($query);
854
                        $sth->execute(array(':source' => 'translation.csv'));
855
                } catch(PDOException $e) {
856
                        return "error : ".$e->getMessage();
857
                }
858
859
		
860
		//update_db::unzip($out_file);
861
		$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...
862
		$delimiter = ';';
863
		$Connection = new Connection();
864
		if (($handle = fopen($tmp_dir.'translation.csv', 'r')) !== FALSE)
865
		{
866
			$i = 0;
867
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
868
			//$Connection->db->beginTransaction();
869
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
870
			{
871
				$i++;
872
				if($i > 12) {
873
					$data = $row;
874
					$operator = $data[2];
875
					if ($operator != '' && is_numeric(substr(substr($operator, 0, 3), -1, 1))) {
876
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator, 0, 2));
877
                                                //echo substr($operator, 0, 2)."\n";;
878
                                                if (count($airline_array) > 0) {
879
							//print_r($airline_array);
880
							$operator = $airline_array[0]['icao'].substr($operator,2);
881
                                                }
882
                                        }
883
					
884
					$operator_correct = $data[3];
885
					if ($operator_correct != '' && is_numeric(substr(substr($operator_correct, 0, 3), -1, 1))) {
886
                                                $airline_array = $Spotter->getAllAirlineInfo(substr($operator_correct, 0, 2));
887
                                                if (count($airline_array) > 0) {
888
                                            		$operator_correct = $airline_array[0]['icao'].substr($operator_correct,2);
889
                                            	}
890
                                        }
891
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
892
					try {
893
						$sth = $Connection->db->prepare($query);
894
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $operator,':Operator_correct' => $operator_correct, ':source' => 'translation.csv'));
895
					} catch(PDOException $e) {
896
						return "error : ".$e->getMessage();
897
					}
898
				}
899
			}
900
			fclose($handle);
901
			//$Connection->db->commit();
902
		}
903
		return '';
904
        }
905
	
906
	public static function translation_fam() {
907
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
908
		global $tmp_dir, $globalTransaction;
909
		$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...
910
		$query = "DELETE FROM translation WHERE Source = '' OR Source = :source";
911
		try {
912
			$Connection = new Connection();
913
			$sth = $Connection->db->prepare($query);
914
                        $sth->execute(array(':source' => 'website_fam'));
915
                } catch(PDOException $e) {
916
                        return "error : ".$e->getMessage();
917
                }
918
919
		
920
		//update_db::unzip($out_file);
921
		$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...
922
		$delimiter = "\t";
923
		$Connection = new Connection();
924
		if (($handle = fopen($tmp_dir.'translation.tsv', 'r')) !== FALSE)
925
		{
926
			$i = 0;
927
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
928
			//$Connection->db->beginTransaction();
929
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
930
			{
931
				if ($i > 0) {
932
					$query = 'INSERT INTO translation (Reg,Reg_correct,Operator,Operator_correct,Source) VALUES (:Reg, :Reg_correct, :Operator, :Operator_correct, :source)';
933
					try {
934
						$sth = $Connection->db->prepare($query);
935
						$sth->execute(array(':Reg' => $data[0],':Reg_correct' => $data[1],':Operator' => $data[2],':Operator_correct' => $data[3], ':source' => 'website_fam'));
936
					} catch(PDOException $e) {
937
						return "error : ".$e->getMessage();
938
					}
939
				}
940
				$i++;
941
			}
942
			fclose($handle);
943
			//$Connection->db->commit();
944
		}
945
		return '';
946
        }
947
948
	/*
949
	* This function use FAA public data.
950
	* With the help of data from other source, Mfr id is added to manufacturer table. Then ModeS with ICAO are added based on that.
951
	*/
952
	public static function modes_faa() {
953
		global $tmp_dir, $globalTransaction, $globalDebug;
954
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
955
		try {
956
			$Connection = new Connection();
957
			$sth = $Connection->db->prepare($query);
958
                        $sth->execute(array(':source' => 'website_faa'));
959
                } catch(PDOException $e) {
960
                        return "error : ".$e->getMessage();
961
                }
962
963
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
964
		try {
965
			$Connection = new Connection();
966
			$sth = $Connection->db->prepare($query);
967
                        $sth->execute(array(':source' => 'website_faa'));
968
                } catch(PDOException $e) {
969
                        return "error : ".$e->getMessage();
970
                }
971
972
		$delimiter = ",";
973
		$mfr = array();
974
		$Connection = new Connection();
975
		if (($handle = fopen($tmp_dir.'MASTER.txt', 'r')) !== FALSE)
976
		{
977
			$i = 0;
978
			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...
979
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
980
			{
981
				if ($i > 0) {
982
					$query_search = 'SELECT icaotypecode FROM aircraft_modes WHERE registration = :registration AND Source <> :source LIMIT 1';
983
					try {
984
						$sths = $Connection->db->prepare($query_search);
985
						$sths->execute(array(':registration' => 'N'.$data[0],':source' => 'website_faa'));
986
					} catch(PDOException $e) {
987
						return "error s : ".$e->getMessage();
988
					}
989
					$result_search = $sths->fetchAll(PDO::FETCH_ASSOC);
990
					if (!empty($result_search)) {
991
						if ($globalDebug) echo '.';
992
							//if ($globalDBdriver == 'mysql') {
993
							//	$queryi = 'INSERT INTO faamfr (mfr,icao) VALUES (:mfr,:icao) ON DUPLICATE KEY UPDATE icao = :icao';
994
							//} else {
995
								$queryi = "INSERT INTO faamfr (mfr,icao) SELECT :mfr,:icao WHERE NOT EXISTS (SELECT 1 FROM faamfr WHERE mfr = :mfr);"; 
996
							//}
997
						try {
998
							$sthi = $Connection->db->prepare($queryi);
999
							$sthi->execute(array(':mfr' => $data[2],':icao' => $result_search[0]['icaotypecode']));
1000
						} catch(PDOException $e) {
1001
							return "error u : ".$e->getMessage();
1002
						}
1003
					} else {
1004
						$query_search_mfr = 'SELECT icao FROM faamfr WHERE mfr = :mfr';
1005
						try {
1006
							$sthsm = $Connection->db->prepare($query_search_mfr);
1007
							$sthsm->execute(array(':mfr' => $data[2]));
1008
						} catch(PDOException $e) {
1009
							return "error mfr : ".$e->getMessage();
1010
						}
1011
						$result_search_mfr = $sthsm->fetchAll(PDO::FETCH_ASSOC);
1012
						if (!empty($result_search_mfr)) {
1013
							if (trim($data[16]) == '' && trim($data[23]) != '') $data[16] = $data[23];
1014
							if (trim($data[16]) == '' && trim($data[15]) != '') $data[16] = $data[15];
1015
							$queryf = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:source)';
1016
							try {
1017
								$sthf = $Connection->db->prepare($queryf);
1018
								$sthf->execute(array(':FirstCreated' => $data[16],':LastModified' => $data[15],':ModeS' => $data[33],':ModeSCountry' => $data[14], ':Registration' => 'N'.$data[0],':ICAOTypeCode' => $result_search_mfr[0]['icao'],':source' => 'website_faa'));
1019
							} catch(PDOException $e) {
1020
								return "error f : ".$e->getMessage();
1021
							}
1022
						}
1023
					}
1024
					if (strtotime($data[29]) > time()) {
1025
						if ($globalDebug) echo 'i';
1026
						$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,:date_first_reg,:source)';
1027
						try {
1028
							$sth = $Connection->db->prepare($query);
1029
							$sth->execute(array(':registration' => 'N'.$data[0],':base' => $data[9],':owner' => ucwords(strtolower($data[6])),':date_first_reg' => date('Y-m-d',strtotime($data[23])), ':source' => 'website_faa'));
1030
						} catch(PDOException $e) {
1031
							return "error i : ".$e->getMessage();
1032
						}
1033
					}
1034
				}
1035
				if ($i % 90 == 0) {
1036
					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...
1037
					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...
1038
				}
1039
				$i++;
1040
			}
1041
			fclose($handle);
1042
			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...
1043
		}
1044
		print_r($mfr);
1045
		return '';
1046
        }
1047
	public static function modes_fam() {
1048
		global $tmp_dir, $globalTransaction;
1049
		$query = "DELETE FROM aircraft_modes WHERE Source = '' OR Source = :source";
1050
		try {
1051
			$Connection = new Connection();
1052
			$sth = $Connection->db->prepare($query);
1053
                        $sth->execute(array(':source' => 'website_fam'));
1054
                } catch(PDOException $e) {
1055
                        return "error : ".$e->getMessage();
1056
                }
1057
1058
		
1059
		//update_db::unzip($out_file);
1060
		$delimiter = "\t";
1061
		$Connection = new Connection();
1062
		if (($handle = fopen($tmp_dir.'modes.tsv', 'r')) !== FALSE)
1063
		{
1064
			$i = 0;
1065
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1066
			//$Connection->db->beginTransaction();
1067
			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...
1068
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1069
			{
1070
				if ($i > 0) {
1071
					if ($data[1] == 'NULL') $data[1] = $data[0];
1072
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1073
					try {
1074
						$sth = $Connection->db->prepare($query);
1075
						$sth->execute(array(':FirstCreated' => $data[0],':LastModified' => $data[1],':ModeS' => $data[2],':ModeSCountry' => $data[3], ':Registration' => $data[4],':ICAOTypeCode' => $data[5],':type_flight' => $data[6],':source' => 'website_fam'));
1076
					} catch(PDOException $e) {
1077
						return "error : ".$e->getMessage();
1078
					}
1079
				}
1080
				$i++;
1081
			}
1082
			fclose($handle);
1083
			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...
1084
		}
1085
		return '';
1086
        }
1087
        
1088
	public static function owner_fam() {
1089
		global $tmp_dir, $globalTransaction;
1090
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1091
		try {
1092
			$Connection = new Connection();
1093
			$sth = $Connection->db->prepare($query);
1094
                        $sth->execute(array(':source' => 'website_fam'));
1095
                } catch(PDOException $e) {
1096
                        return "error : ".$e->getMessage();
1097
                }
1098
1099
		$delimiter = "\t";
1100
		$Connection = new Connection();
1101
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1102
		{
1103
			$i = 0;
1104
			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...
1105
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1106
			{
1107
				if ($i > 0) {
1108
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1109
					try {
1110
						$sth = $Connection->db->prepare($query);
1111
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1112
					} catch(PDOException $e) {
1113
						print_r($data);
1114
						return "error : ".$e->getMessage();
1115
					}
1116
				}
1117
				$i++;
1118
			}
1119
			fclose($handle);
1120
			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...
1121
		}
1122
		return '';
1123
        }
1124
1125
	public static function routes_fam() {
1126
		global $tmp_dir, $globalTransaction;
1127
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1128
		try {
1129
			$Connection = new Connection();
1130
			$sth = $Connection->db->prepare($query);
1131
                        $sth->execute(array(':source' => 'website_fam'));
1132
                } catch(PDOException $e) {
1133
                        return "error : ".$e->getMessage();
1134
                }
1135
1136
		
1137
		//update_db::unzip($out_file);
1138
		$delimiter = "\t";
1139
		$Connection = new Connection();
1140
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1141
		{
1142
			$i = 0;
1143
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1144
			//$Connection->db->beginTransaction();
1145
			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...
1146
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1147
			{
1148
				if ($i > 0) {
1149
					$query = '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)';
1150
					try {
1151
						$sth = $Connection->db->prepare($query);
1152
						$sth->execute(array(':CallSign' => $data[0],':Operator_ICAO' => $data[1],':FromAirport_ICAO' => $data[2],':FromAirport_Time' => $data[3], ':ToAirport_ICAO' => $data[4],':ToAirport_Time' => $data[5],':RouteStop' => $data[6],':source' => 'website_fam'));
1153
					} catch(PDOException $e) {
1154
						return "error : ".$e->getMessage();
1155
					}
1156
				}
1157
				$i++;
1158
			}
1159
			fclose($handle);
1160
			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...
1161
		}
1162
		return '';
1163
        }
1164
1165
	public static function banned_fam() {
1166
		global $tmp_dir, $globalTransaction;
1167
		$query = "UPDATE airlines SET ban_eu = 0";
1168
		try {
1169
			$Connection = new Connection();
1170
			$sth = $Connection->db->prepare($query);
1171
			$sth->execute();
1172
		} catch(PDOException $e) {
1173
			return "error : ".$e->getMessage();
1174
		}
1175
1176
		$Connection = new Connection();
1177
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1178
		{
1179
			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...
1180
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1181
			{
1182
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1183
				if ($data[0] != '') {
1184
					$icao = $data[0];
1185
					try {
1186
						$sth = $Connection->db->prepare($query);
1187
						$sth->execute(array(':icao' => $icao));
1188
					} catch(PDOException $e) {
1189
						return "error : ".$e->getMessage();
1190
					}
1191
				}
1192
			}
1193
			fclose($handle);
1194
			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...
1195
		}
1196
		return '';
1197
        }
1198
1199
	public static function tle($filename,$tletype) {
1200
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1201
		global $tmp_dir, $globalTransaction;
1202
		//$Spotter = new Spotter();
1203
		
1204
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1205
		try {
1206
			$Connection = new Connection();
1207
			$sth = $Connection->db->prepare($query);
1208
                        $sth->execute(array(':source' => $filename));
1209
                } catch(PDOException $e) {
1210
                        return "error : ".$e->getMessage();
1211
                }
1212
		
1213
		$Connection = new Connection();
1214
		if (($handle = fopen($filename, 'r')) !== FALSE)
1215
		{
1216
			$i = 0;
1217
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1218
			//$Connection->db->beginTransaction();
1219
			$dbdata = array();
1220
			while (($data = fgets($handle, 1000)) !== FALSE)
1221
			{
1222
				if ($i == 0) {
1223
					$dbdata['name'] = trim($data);
1224
					$i++;
1225
				} elseif ($i == 1) {
1226
					$dbdata['tle1'] = trim($data);
1227
					$i++;
1228
				} elseif ($i == 2) {
1229
					$dbdata['tle2'] = trim($data);
1230
					//print_r($dbdata);
1231
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1232
					try {
1233
						$sth = $Connection->db->prepare($query);
1234
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1235
					} catch(PDOException $e) {
1236
						return "error : ".$e->getMessage();
1237
					}
1238
1239
					$i = 0;
1240
				}
1241
			}
1242
			fclose($handle);
1243
			//$Connection->db->commit();
1244
		}
1245
		return '';
1246
        }
1247
1248
	/**
1249
        * Convert a HTML table to an array
1250
        * @param String $data HTML page
1251
        * @return Array array of the tables in HTML page
1252
        */
1253
        private static function table2array($data) {
1254
                $html = str_get_html($data);
1255
                $tabledata=array();
1256
                foreach($html->find('tr') as $element)
1257
                {
1258
                        $td = array();
1259
                        foreach( $element->find('th') as $row)
1260
                        {
1261
                                $td [] = trim($row->plaintext);
1262
                        }
1263
                        $td=array_filter($td);
1264
                        $tabledata[] = $td;
1265
1266
                        $td = array();
1267
                        $tdi = array();
1268
                        foreach( $element->find('td') as $row)
1269
                        {
1270
                                $td [] = trim($row->plaintext);
1271
                                $tdi [] = trim($row->innertext);
1272
                        }
1273
                        $td=array_filter($td);
1274
                        $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...
1275
                    //    $tabledata[]=array_merge($td,$tdi);
1276
                        $tabledata[]=$td;
1277
                }
1278
                return(array_filter($tabledata));
1279
        }
1280
1281
       /**
1282
        * Get data from form result
1283
        * @param String $url form URL
1284
        * @return String the result
1285
        */
1286
        private static function getData($url) {
1287
                $ch = curl_init();
1288
                curl_setopt($ch, CURLOPT_URL, $url);
1289
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1290
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1291
                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');
1292
                return curl_exec($ch);
1293
        }
1294
/*
1295
	public static function waypoints() {
1296
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1297
		$table = update_db::table2array($data);
1298
//		print_r($table);
1299
		$query = 'TRUNCATE TABLE waypoints';
1300
		try {
1301
			$Connection = new Connection();
1302
			$sth = $Connection->db->prepare($query);
1303
                        $sth->execute();
1304
                } catch(PDOException $e) {
1305
                        return "error : ".$e->getMessage();
1306
                }
1307
1308
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1309
		$Connection = new Connection();
1310
		$sth_dest = $Connection->db->prepare($query_dest);
1311
		$Connection->db->beginTransaction();
1312
                foreach ($table as $row) {
1313
            		if ($row[0] != 'Ident') {
1314
				$ident = $row[0];
1315
				$latitude = $row[2];
1316
				$longitude = $row[3];
1317
				$control = $row[4];
1318
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1319
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1320
				try {
1321
					$sth_dest->execute($query_dest_values);
1322
				} catch(PDOException $e) {
1323
					return "error : ".$e->getMessage();
1324
				}
1325
			}
1326
                }
1327
		$Connection->db->commit();
1328
1329
	}
1330
*/
1331
	public static function waypoints($filename) {
1332
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1333
		global $tmp_dir, $globalTransaction;
1334
		//$Spotter = new Spotter();
1335
		//$out_file = $tmp_dir.'translation.zip';
1336
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1337
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1338
		$Connection = new Connection();
1339
		//update_db::unzip($out_file);
1340
		$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...
1341
		$delimiter = ' ';
1342
		if (($handle = fopen($filename, 'r')) !== FALSE)
1343
		{
1344
			$i = 0;
1345
			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...
1346
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1347
			{
1348
				$i++;
1349
				if($i > 3 && count($row) > 2) {
1350
					$data = array_values(array_filter($row));
1351
					$cntdata = count($data);
1352
					if ($cntdata > 10) {
1353
						$value = $data[9];
1354
						
1355
						for ($i =10;$i < $cntdata;$i++) {
1356
							$value .= ' '.$data[$i];
1357
						}
1358
						$data[9] = $value;
1359
					}
1360
					//print_r($data);
1361
					if (count($data) > 9) {
1362
						$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)';
1363
						try {
1364
							$sth = $Connection->db->prepare($query);
1365
							$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]));
1366
						} catch(PDOException $e) {
1367
							return "error : ".$e->getMessage();
1368
						}
1369
					}
1370
				}
1371
			}
1372
			fclose($handle);
1373
			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...
1374
		}
1375
		return '';
1376
        }
1377
1378
	public static function ivao_airlines($filename) {
1379
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1380
		global $tmp_dir, $globalTransaction;
1381
		//$query = 'TRUNCATE TABLE airlines';
1382
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1383
		try {
1384
			$Connection = new Connection();
1385
			$sth = $Connection->db->prepare($query);
1386
                        $sth->execute();
1387
                } catch(PDOException $e) {
1388
                        return "error : ".$e->getMessage();
1389
                }
1390
1391
		$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...
1392
		$delimiter = ':';
1393
		$Connection = new Connection();
1394
		if (($handle = fopen($filename, 'r')) !== FALSE)
1395
		{
1396
			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...
1397
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1398
			{
1399
				if(count($row) > 1) {
1400
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1401
					try {
1402
						$sth = $Connection->db->prepare($query);
1403
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1404
					} catch(PDOException $e) {
1405
						return "error : ".$e->getMessage();
1406
					}
1407
				}
1408
			}
1409
			fclose($handle);
1410
			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...
1411
		}
1412
		return '';
1413
        }
1414
	
1415
	public static function update_airspace() {
1416
		global $tmp_dir, $globalDBdriver;
1417
		include_once('class.create_db.php');
1418
		$Connection = new Connection();
1419
		if ($Connection->tableExists('airspace')) {
1420
			$query = 'DROP TABLE airspace';
1421
			try {
1422
				$sth = $Connection->db->prepare($query);
1423
                    		$sth->execute();
1424
	                } catch(PDOException $e) {
1425
				return "error : ".$e->getMessage();
1426
	                }
1427
	        }
1428
1429
1430
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1431
		else {
1432
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1433
			$query = "CREATE EXTENSION postgis";
1434
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1435
			try {
1436
				$sth = $Connection->db->prepare($query);
1437
				$sth->execute();
1438
			} catch(PDOException $e) {
1439
				return "error : ".$e->getMessage();
1440
			}
1441
		}
1442
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1443
		return $error;
1444
	}
1445
1446
	public static function update_notam_fam() {
1447
		global $tmp_dir, $globalDebug;
1448
		include_once('class.create_db.php');
1449
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1450
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1451
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1452
		$error = '';
1453
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1454
			if ($globalDebug) echo "Gunzip...";
1455
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1456
			if ($globalDebug) echo "Add to DB...";
1457
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1458
			$NOTAM = new NOTAM();
1459
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1460
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1461
		if ($error != '') {
1462
			return $error;
1463
		} elseif ($globalDebug) echo "Done\n";
1464
		return '';
1465
	}
1466
1467
	public static function update_vatsim() {
1468
		global $tmp_dir;
1469
		include_once('class.create_db.php');
1470
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1471
		return $error;
1472
	}
1473
	
1474
	public static function update_countries() {
1475
		global $tmp_dir, $globalDBdriver;
1476
		include_once('class.create_db.php');
1477
		$Connection = new Connection();
1478
		if ($Connection->tableExists('countries')) {
1479
			$query = 'DROP TABLE countries';
1480
			try {
1481
				$sth = $Connection->db->prepare($query);
1482
            	        	$sth->execute();
1483
	                } catch(PDOException $e) {
1484
    	                	echo "error : ".$e->getMessage();
1485
	                }
1486
		}
1487
		if ($globalDBdriver == 'mysql') {
1488
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1489
		} else {
1490
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1491
		}
1492
		$error = create_db::import_file($tmp_dir.'countries.sql');
1493
		return $error;
1494
	}
1495
1496
	
1497
	public static function update_waypoints() {
1498
		global $tmp_dir;
1499
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1500
//		update_db::unzip($tmp_dir.'AptNav.zip');
1501
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1502
//		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');
1503
		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');
1504
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1505
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1506
		return $error;
1507
	}
1508
1509
	public static function update_ivao() {
1510
		global $tmp_dir, $globalDebug;
1511
		$Common = new Common();
1512
		$error = '';
1513
		//Direct download forbidden
1514
		//if ($globalDebug) echo "IVAO : Download...";
1515
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1516
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1517
			if ($globalDebug) echo "Unzip...";
1518
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1519
			if ($globalDebug) echo "Add to DB...";
1520
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1521
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1522
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1523
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1524
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1525
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1526
		if ($error != '') {
1527
			return $error;
1528
		} elseif ($globalDebug) echo "Done\n";
1529
		return '';
1530
	}
1531
1532
	public static function update_routes() {
1533
		global $tmp_dir, $globalDebug;
1534
		$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...
1535
		if ($globalDebug) echo "Routes : Download...";
1536
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1537
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1538
			if ($globalDebug) echo "Gunzip...";
1539
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1540
			if ($globalDebug) echo "Add to DB...";
1541
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1542
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1543
		if ($error != '') {
1544
			return $error;
1545
		} elseif ($globalDebug) echo "Done\n";
1546
		return '';
1547
	}
1548
	public static function update_oneworld() {
1549
		global $tmp_dir, $globalDebug;
1550
		$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...
1551
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1552
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1553
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1554
			if ($globalDebug) echo "Gunzip...";
1555
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1556
			if ($globalDebug) echo "Add to DB...";
1557
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1558
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1559
		if ($error != '') {
1560
			return $error;
1561
		} elseif ($globalDebug) echo "Done\n";
1562
		return '';
1563
	}
1564
	public static function update_skyteam() {
1565
		global $tmp_dir, $globalDebug;
1566
		$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...
1567
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1568
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1569
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1570
			if ($globalDebug) echo "Gunzip...";
1571
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1572
			if ($globalDebug) echo "Add to DB...";
1573
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1574
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1575
		if ($error != '') {
1576
			return $error;
1577
		} elseif ($globalDebug) echo "Done\n";
1578
		return '';
1579
	}
1580
	public static function update_ModeS() {
1581
		global $tmp_dir, $globalDebug;
1582
/*
1583
		if ($globalDebug) echo "Modes : Download...";
1584
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1585
		if ($globalDebug) echo "Unzip...";
1586
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1587
		if ($globalDebug) echo "Add to DB...";
1588
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1589
		if ($error != true) {
1590
			echo $error;
1591
			exit;
1592
		} elseif ($globalDebug) echo "Done\n";
1593
*/
1594
		if ($globalDebug) echo "Modes : Download...";
1595
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1596
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1597
1598
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1599
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1600
			if ($globalDebug) echo "Unzip...";
1601
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1602
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1603
			if ($globalDebug) echo "Add to DB...";
1604
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1605
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1606
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1607
		if ($error != '') {
1608
			return $error;
1609
		} elseif ($globalDebug) echo "Done\n";
1610
		return '';
1611
	}
1612
1613
	public static function update_ModeS_faa() {
1614
		global $tmp_dir, $globalDebug;
1615
		if ($globalDebug) echo "Modes FAA: Download...";
1616
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
1617
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
1618
			if ($globalDebug) echo "Unzip...";
1619
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
1620
			if ($globalDebug) echo "Add to DB...";
1621
			$error = update_db::modes_faa();
1622
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
1623
		if ($error != '') {
1624
			return $error;
1625
		} elseif ($globalDebug) echo "Done\n";
1626
		return '';
1627
	}
1628
1629
	public static function update_ModeS_flarm() {
1630
		global $tmp_dir, $globalDebug;
1631
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1632
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1633
		if (file_exists($tmp_dir.'data.fln')) {
1634
			if ($globalDebug) echo "Add to DB...";
1635
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1636
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1637
		if ($error != '') {
1638
			return $error;
1639
		} elseif ($globalDebug) echo "Done\n";
1640
		return '';
1641
	}
1642
1643
	public static function update_ModeS_ogn() {
1644
		global $tmp_dir, $globalDebug;
1645
		if ($globalDebug) echo "Modes OGN: Download...";
1646
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1647
		if (file_exists($tmp_dir.'ogn.csv')) {
1648
			if ($globalDebug) echo "Add to DB...";
1649
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1650
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1651
		if ($error != '') {
1652
			return $error;
1653
		} elseif ($globalDebug) echo "Done\n";
1654
		return '';
1655
	}
1656
1657
	public static function update_owner() {
1658
		global $tmp_dir, $globalDebug;
1659
		
1660
		if ($globalDebug) echo "Owner France: Download...";
1661
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1662
		if (file_exists($tmp_dir.'owner_f.csv')) {
1663
			if ($globalDebug) echo "Add to DB...";
1664
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1665
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1666
		if ($error != '') {
1667
			return $error;
1668
		} elseif ($globalDebug) echo "Done\n";
1669
		
1670
		if ($globalDebug) echo "Owner Ireland: Download...";
1671
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1672
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1673
			if ($globalDebug) echo "Add to DB...";
1674
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1675
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1676
		if ($error != '') {
1677
			return $error;
1678
		} elseif ($globalDebug) echo "Done\n";
1679
		if ($globalDebug) echo "Owner Switzerland: Download...";
1680
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1681
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1682
			if ($globalDebug) echo "Add to DB...";
1683
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1684
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1685
		if ($error != '') {
1686
			return $error;
1687
		} elseif ($globalDebug) echo "Done\n";
1688
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1689
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1690
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1691
			if ($globalDebug) echo "Add to DB...";
1692
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1693
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1694
		if ($error != '') {
1695
			return $error;
1696
		} elseif ($globalDebug) echo "Done\n";
1697
		if ($globalDebug) echo "Owner Australia: Download...";
1698
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1699
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1700
			if ($globalDebug) echo "Add to DB...";
1701
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1702
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1703
		if ($error != '') {
1704
			return $error;
1705
		} elseif ($globalDebug) echo "Done\n";
1706
		if ($globalDebug) echo "Owner Austria: Download...";
1707
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1708
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1709
			if ($globalDebug) echo "Add to DB...";
1710
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1711
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1712
		if ($error != '') {
1713
			return $error;
1714
		} elseif ($globalDebug) echo "Done\n";
1715
		if ($globalDebug) echo "Owner Chile: Download...";
1716
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1717
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1718
			if ($globalDebug) echo "Add to DB...";
1719
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1720
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1721
		if ($error != '') {
1722
			return $error;
1723
		} elseif ($globalDebug) echo "Done\n";
1724
		if ($globalDebug) echo "Owner Colombia: Download...";
1725
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1726
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1727
			if ($globalDebug) echo "Add to DB...";
1728
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1729
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1730
		if ($error != '') {
1731
			return $error;
1732
		} elseif ($globalDebug) echo "Done\n";
1733
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1734
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1735
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1736
			if ($globalDebug) echo "Add to DB...";
1737
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1738
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1739
		if ($error != '') {
1740
			return $error;
1741
		} elseif ($globalDebug) echo "Done\n";
1742
		if ($globalDebug) echo "Owner Brazil: Download...";
1743
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1744
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1745
			if ($globalDebug) echo "Add to DB...";
1746
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1747
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1748
		if ($error != '') {
1749
			return $error;
1750
		} elseif ($globalDebug) echo "Done\n";
1751
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1752
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1753
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1754
			if ($globalDebug) echo "Add to DB...";
1755
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1756
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1757
		if ($error != '') {
1758
			return $error;
1759
		} elseif ($globalDebug) echo "Done\n";
1760
		if ($globalDebug) echo "Owner Croatia: Download...";
1761
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1762
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1763
			if ($globalDebug) echo "Add to DB...";
1764
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1765
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1766
		if ($error != '') {
1767
			return $error;
1768
		} elseif ($globalDebug) echo "Done\n";
1769
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1770
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1771
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1772
			if ($globalDebug) echo "Add to DB...";
1773
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1774
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1775
		if ($error != '') {
1776
			return $error;
1777
		} elseif ($globalDebug) echo "Done\n";
1778
		if ($globalDebug) echo "Owner Maldives: Download...";
1779
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1780
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1781
			if ($globalDebug) echo "Add to DB...";
1782
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1783
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1784
		if ($error != '') {
1785
			return $error;
1786
		} elseif ($globalDebug) echo "Done\n";
1787
		if ($globalDebug) echo "Owner New Zealand: Download...";
1788
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1789
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1790
			if ($globalDebug) echo "Add to DB...";
1791
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1792
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1793
		if ($error != '') {
1794
			return $error;
1795
		} elseif ($globalDebug) echo "Done\n";
1796
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1797
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1798
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1799
			if ($globalDebug) echo "Add to DB...";
1800
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1801
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1802
		if ($error != '') {
1803
			return $error;
1804
		} elseif ($globalDebug) echo "Done\n";
1805
		if ($globalDebug) echo "Owner Slovakia: Download...";
1806
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1807
		if (file_exists($tmp_dir.'owner_om.csv')) {
1808
			if ($globalDebug) echo "Add to DB...";
1809
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1810
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1811
		if ($error != '') {
1812
			return $error;
1813
		} elseif ($globalDebug) echo "Done\n";
1814
		if ($globalDebug) echo "Owner Ecuador: Download...";
1815
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1816
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1817
			if ($globalDebug) echo "Add to DB...";
1818
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1819
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1820
		if ($error != '') {
1821
			return $error;
1822
		} elseif ($globalDebug) echo "Done\n";
1823
		if ($globalDebug) echo "Owner Iceland: Download...";
1824
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1825
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1826
			if ($globalDebug) echo "Add to DB...";
1827
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1828
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1829
		if ($error != '') {
1830
			return $error;
1831
		} elseif ($globalDebug) echo "Done\n";
1832
		return '';
1833
	}
1834
1835
	public static function update_translation() {
1836
		global $tmp_dir, $globalDebug;
1837
		$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...
1838
		if ($globalDebug) echo "Translation : Download...";
1839
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1840
		if (file_exists($tmp_dir.'translation.zip')) {
1841
			if ($globalDebug) echo "Unzip...";
1842
			update_db::unzip($tmp_dir.'translation.zip');
1843
			if ($globalDebug) echo "Add to DB...";
1844
			$error = update_db::translation();
1845
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1846
		if ($error != '') {
1847
			return $error;
1848
		} elseif ($globalDebug) echo "Done\n";
1849
		return '';
1850
	}
1851
1852
	public static function update_translation_fam() {
1853
		global $tmp_dir, $globalDebug;
1854
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1855
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1856
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1857
			if ($globalDebug) echo "Gunzip...";
1858
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1859
			if ($globalDebug) echo "Add to DB...";
1860
			$error = update_db::translation_fam();
1861
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1862
		if ($error != '') {
1863
			return $error;
1864
		} elseif ($globalDebug) echo "Done\n";
1865
		return '';
1866
	}
1867
	public static function update_ModeS_fam() {
1868
		global $tmp_dir, $globalDebug;
1869
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1870
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1871
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1872
			if ($globalDebug) echo "Gunzip...";
1873
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1874
			if ($globalDebug) echo "Add to DB...";
1875
			$error = update_db::modes_fam();
1876
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1877
		if ($error != '') {
1878
			return $error;
1879
		} elseif ($globalDebug) echo "Done\n";
1880
		return '';
1881
	}
1882
	public static function update_owner_fam() {
1883
		global $tmp_dir, $globalDebug, $globalOwner;
1884
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
1885
		if ($globalOwner === TRUE) {
1886
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
1887
		} else {
1888
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
1889
		}
1890
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
1891
			if ($globalDebug) echo "Gunzip...";
1892
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
1893
			if ($globalDebug) echo "Add to DB...";
1894
			$error = update_db::owner_fam();
1895
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
1896
		if ($error != '') {
1897
			return $error;
1898
		} elseif ($globalDebug) echo "Done\n";
1899
		return '';
1900
	}
1901
	public static function update_routes_fam() {
1902
		global $tmp_dir, $globalDebug;
1903
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
1904
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
1905
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
1906
			if ($globalDebug) echo "Gunzip...";
1907
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
1908
			if ($globalDebug) echo "Add to DB...";
1909
			$error = update_db::routes_fam();
1910
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
1911
		if ($error != '') {
1912
			return $error;
1913
		} elseif ($globalDebug) echo "Done\n";
1914
		return '';
1915
	}
1916
	public static function update_banned_fam() {
1917
		global $tmp_dir, $globalDebug;
1918
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
1919
		update_db::download('http://data.flightairmap.fr/data/ban_eu.csv',$tmp_dir.'ban_eu.csv');
1920
		if (file_exists($tmp_dir.'ban_eu.csv')) {
1921
			//if ($globalDebug) echo "Gunzip...";
1922
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
1923
			if ($globalDebug) echo "Add to DB...";
1924
			$error = update_db::banned_fam();
1925
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
1926
		if ($error != '') {
1927
			return $error;
1928
		} elseif ($globalDebug) echo "Done\n";
1929
		return '';
1930
	}
1931
1932
	public static function update_airspace_fam() {
1933
		global $tmp_dir, $globalDebug, $globalDBdriver;
1934
		include_once('class.create_db.php');
1935
		$error = '';
1936
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1937
		if ($globalDBdriver == 'mysql') {
1938
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1939
		} else {
1940
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1941
		}
1942
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1943
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1944
			$airspace_md5 = $airspace_md5_file[0];
1945
			if (!update_db::check_airspace_version($airspace_md5)) {
1946
				if ($globalDBdriver == 'mysql') {
1947
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1948
				} else {
1949
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1950
				}
1951
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1952
					if ($globalDebug) echo "Gunzip...";
1953
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1954
					if ($globalDebug) echo "Add to DB...";
1955
					$Connection = new Connection();
1956
					if ($Connection->tableExists('airspace')) {
1957
						$query = 'DROP TABLE airspace';
1958
						try {
1959
							$sth = $Connection->db->prepare($query);
1960
    	    	    					$sth->execute();
1961
			            		} catch(PDOException $e) {
1962
							return "error : ".$e->getMessage();
1963
		            			}
1964
		    			}
1965
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1966
					update_db::insert_airspace_version($airspace_md5);
1967
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1968
			}
1969
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1970
		if ($error != '') {
1971
			return $error;
1972
		} elseif ($globalDebug) echo "Done\n";
1973
		return '';
1974
	}
1975
1976
	public static function update_tle() {
1977
		global $tmp_dir, $globalDebug;
1978
		if ($globalDebug) echo "Download TLE : Download...";
1979
		$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',
1980
		'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',
1981
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1982
		foreach ($alltle as $filename) {
1983
			if ($globalDebug) echo "downloading ".$filename.'...';
1984
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1985
			if (file_exists($tmp_dir.$filename)) {
1986
				if ($globalDebug) echo "Add to DB ".$filename."...";
1987
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1988
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1989
			if ($error != '') {
1990
				echo $error."\n";
1991
			} elseif ($globalDebug) echo "Done\n";
1992
		}
1993
		return '';
1994
	}
1995
1996
	public static function update_models() {
1997
		global $tmp_dir, $globalDebug;
1998
		$error = '';
1999
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
2000
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2001
		if (file_exists($tmp_dir.'models.md5sum')) {
2002
			if ($globalDebug) echo "Check files...\n";
2003
			$newmodelsdb = array();
2004
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2005
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2006
					$model = trim($row[2]);
2007
					$newmodelsdb[$model] = trim($row[0]);
2008
				}
2009
			}
2010
			$modelsdb = array();
2011
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2012
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2013
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2014
						$model = trim($row[2]);
2015
						$modelsdb[$model] = trim($row[0]);
2016
					}
2017
				}
2018
			}
2019
			$diff = array_diff($newmodelsdb,$modelsdb);
2020
			foreach ($diff as $key => $value) {
2021
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2022
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2023
				
2024
			}
2025
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2026
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2027
		if ($error != '') {
2028
			return $error;
2029
		} elseif ($globalDebug) echo "Done\n";
2030
		return '';
2031
	}
2032
2033
	public static function update_space_models() {
2034
		global $tmp_dir, $globalDebug;
2035
		$error = '';
2036
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2037
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2038
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2039
			if ($globalDebug) echo "Check files...\n";
2040
			$newmodelsdb = array();
2041
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2042
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2043
					$model = trim($row[2]);
2044
					$newmodelsdb[$model] = trim($row[0]);
2045
				}
2046
			}
2047
			$modelsdb = array();
2048
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2049
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2050
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2051
						$model = trim($row[2]);
2052
						$modelsdb[$model] = trim($row[0]);
2053
					}
2054
				}
2055
			}
2056
			$diff = array_diff($newmodelsdb,$modelsdb);
2057
			foreach ($diff as $key => $value) {
2058
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2059
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2060
				
2061
			}
2062
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2063
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2064
		if ($error != '') {
2065
			return $error;
2066
		} elseif ($globalDebug) echo "Done\n";
2067
		return '';
2068
	}
2069
2070
	public static function update_aircraft() {
2071
		global $tmp_dir, $globalDebug;
2072
		date_default_timezone_set('UTC');
2073
		//$error = '';
2074
		/*
2075
		if ($globalDebug) echo "Aircrafts : Download...";
2076
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2077
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2078
		//$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);
2079
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2080
//		echo strlen($data_req);
2081
		echo $data;
2082
		*/
2083
		if (file_exists($tmp_dir.'aircrafts.html')) {
2084
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2085
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2086
		    $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...
2087
		    //echo $result;
2088
		    //var_dump(str_get_html($result));
2089
		    //print_r(self::table2array($result));
2090
		}
2091
2092
	}
2093
	
2094
	public static function update_notam() {
2095
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2096
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2097
		$Common = new Common();
2098
		date_default_timezone_set('UTC');
2099
		$query = 'TRUNCATE TABLE notam';
2100
		try {
2101
			$Connection = new Connection();
2102
			$sth = $Connection->db->prepare($query);
2103
                        $sth->execute();
2104
                } catch(PDOException $e) {
2105
                        return "error : ".$e->getMessage();
2106
                }
2107
2108
		$error = '';
2109
		if ($globalDebug) echo "Notam : Download...";
2110
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2111
		if (file_exists($tmp_dir.'notam.rss')) {
2112
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2113
			foreach ($notams['channel']['item'] as $notam) {
2114
				$title = explode(':',$notam['title']);
2115
				$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...
2116
				unset($title[0]);
2117
				$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...
2118
				$description = strip_tags($notam['description'],'<pre>');
2119
				preg_match(':^(.*?)<pre>:',$description,$match);
2120
				$q = explode('/',$match[1]);
2121
				$data['fir'] = $q[0];
2122
				$data['code'] = $q[1];
2123
				$ifrvfr = $q[2];
2124
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2125
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2126
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2127
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2128
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2129
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2130
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2131
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2132
				//$data['scope'] = $q[4];
2133
				$data['lower_limit'] = $q[5];
2134
				$data['upper_limit'] = $q[6];
2135
				$latlonrad = $q[7];
2136
				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...
2137
				$latitude = $Common->convertDec($las,'latitude');
2138
				$longitude = $Common->convertDec($lns,'longitude');
2139
				if ($lac == 'S') $latitude = '-'.$latitude;
2140
				if ($lnc == 'W') $longitude = '-'.$longitude;
2141
				$data['center_latitude'] = $latitude;
2142
				$data['center_longitude'] = $longitude;
2143
				$data['radius'] = intval($radius);
2144
				
2145
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2146
				$data['text'] = $match[1];
2147
				preg_match(':</pre>(.*?)$:',$description,$match);
2148
				$fromto = $match[1];
2149
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2150
				$fromall = trim($match[1]);
2151
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2152
				$from = trim($match[1]);
2153
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2154
				preg_match('#TO:(.*?)$#',$fromto,$match);
2155
				$toall = trim($match[1]);
2156
				if (!preg_match(':Permanent:',$toall)) {
2157
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2158
					$to = trim($match[1]);
2159
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2160
					$data['permanent'] = 0;
2161
				} else {
2162
				    $data['date_end'] = NULL;
2163
				    $data['permanent'] = 1;
2164
				}
2165
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2166
				$NOTAM = new NOTAM();
2167
				$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']);
2168
				unset($data);
2169
			} 
2170
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2171
		if ($error != '') {
2172
			return $error;
2173
		} elseif ($globalDebug) echo "Done\n";
2174
		return '';
2175
	}
2176
	
2177
	public static function create_airspace() {
2178
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2179
		$Connection = new Connection();
2180
		if ($Connection->tableExists('airspace')) {
2181
			if ($globalDBdriver == 'mysql') {
2182
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2183
			} else {
2184
				$query = 'DROP TABLE airspace';
2185
			}
2186
			try {
2187
				$Connection = new Connection();
2188
				$sth = $Connection->db->prepare($query);
2189
				$sth->execute();
2190
			} catch(PDOException $e) {
2191
				return "error : ".$e->getMessage();
2192
			}
2193
		}
2194
		$Common = new Common();
2195
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2196
		$airspace_json = json_decode($airspace_lst,true);
2197
		foreach ($airspace_json['records'] as $airspace) {
2198
			if ($globalDebug) echo $airspace['name']."...\n";
2199
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2200
			if (file_exists($tmp_dir.$airspace['name'])) {
2201
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2202
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2203
				if ($globalDBdriver == 'mysql') {
2204
					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'].'"');
2205
				} else {
2206
					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'].'"');
2207
				}
2208
			}
2209
		}
2210
	}
2211
	
2212
	public static function fix_icaotype() {
2213
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
2214
		$Spotter = new Spotter();
2215
		foreach ($Spotter->aircraft_correct_icaotype as $old => $new) {
2216
			$query = 'UPDATE aircraft_modes SET ICAOTypeCode = :new WHERE ICAOTypeCode = :old';
2217
			try {
2218
				$Connection = new Connection();
2219
				$sth = $Connection->db->prepare($query);
2220
				$sth->execute(array(':new' => $new, ':old' => $old));
2221
			} catch(PDOException $e) {
2222
				return "error : ".$e->getMessage();
2223
			}
2224
		}
2225
	}
2226
2227
	public static function check_last_update() {
2228
		global $globalDBdriver;
2229
		if ($globalDBdriver == 'mysql') {
2230
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2231
		} else {
2232
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2233
		}
2234
		try {
2235
			$Connection = new Connection();
2236
			$sth = $Connection->db->prepare($query);
2237
                        $sth->execute();
2238
                } catch(PDOException $e) {
2239
                        return "error : ".$e->getMessage();
2240
                }
2241
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2242
                if ($row['nb'] > 0) return false;
2243
                else return true;
2244
	}
2245
2246
	public static function insert_last_update() {
2247
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2248
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2249
		try {
2250
			$Connection = new Connection();
2251
			$sth = $Connection->db->prepare($query);
2252
                        $sth->execute();
2253
                } catch(PDOException $e) {
2254
                        return "error : ".$e->getMessage();
2255
                }
2256
	}
2257
2258
	public static function check_airspace_version($version) {
2259
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2260
		try {
2261
			$Connection = new Connection();
2262
			$sth = $Connection->db->prepare($query);
2263
                        $sth->execute(array(':version' => $version));
2264
                } catch(PDOException $e) {
2265
                        return "error : ".$e->getMessage();
2266
                }
2267
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2268
                if ($row['nb'] > 0) return true;
2269
                else return false;
2270
	}
2271
2272
2273
	public static function insert_airspace_version($version) {
2274
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2275
			INSERT INTO config (name,value) VALUES ('airspace_version',:version);";
2276
		try {
2277
			$Connection = new Connection();
2278
			$sth = $Connection->db->prepare($query);
2279
                        $sth->execute(array(':version' => $version));
2280
                } catch(PDOException $e) {
2281
                        return "error : ".$e->getMessage();
2282
                }
2283
	}
2284
2285
	public static function check_last_notam_update() {
2286
		global $globalDBdriver;
2287
		if ($globalDBdriver == 'mysql') {
2288
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2289
		} else {
2290
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2291
		}
2292
		try {
2293
			$Connection = new Connection();
2294
			$sth = $Connection->db->prepare($query);
2295
                        $sth->execute();
2296
                } catch(PDOException $e) {
2297
                        return "error : ".$e->getMessage();
2298
                }
2299
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2300
                if ($row['nb'] > 0) return false;
2301
                else return true;
2302
	}
2303
2304
	public static function insert_last_notam_update() {
2305
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2306
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2307
		try {
2308
			$Connection = new Connection();
2309
			$sth = $Connection->db->prepare($query);
2310
                        $sth->execute();
2311
                } catch(PDOException $e) {
2312
                        return "error : ".$e->getMessage();
2313
                }
2314
	}
2315
	public static function check_last_airspace_update() {
2316
		global $globalDBdriver;
2317
		if ($globalDBdriver == 'mysql') {
2318
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2319
		} else {
2320
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2321
		}
2322
		try {
2323
			$Connection = new Connection();
2324
			$sth = $Connection->db->prepare($query);
2325
                        $sth->execute();
2326
                } catch(PDOException $e) {
2327
                        return "error : ".$e->getMessage();
2328
                }
2329
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2330
                if ($row['nb'] > 0) return false;
2331
                else return true;
2332
	}
2333
2334
	public static function insert_last_airspace_update() {
2335
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2336
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2337
		try {
2338
			$Connection = new Connection();
2339
			$sth = $Connection->db->prepare($query);
2340
                        $sth->execute();
2341
                } catch(PDOException $e) {
2342
                        return "error : ".$e->getMessage();
2343
                }
2344
	}
2345
2346
	public static function check_last_owner_update() {
2347
		global $globalDBdriver;
2348
		if ($globalDBdriver == 'mysql') {
2349
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2350
		} else {
2351
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2352
		}
2353
		try {
2354
			$Connection = new Connection();
2355
			$sth = $Connection->db->prepare($query);
2356
                        $sth->execute();
2357
                } catch(PDOException $e) {
2358
                        return "error : ".$e->getMessage();
2359
                }
2360
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2361
                if ($row['nb'] > 0) return false;
2362
                else return true;
2363
	}
2364
2365
	public static function insert_last_owner_update() {
2366
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2367
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2368
		try {
2369
			$Connection = new Connection();
2370
			$sth = $Connection->db->prepare($query);
2371
                        $sth->execute();
2372
                } catch(PDOException $e) {
2373
                        return "error : ".$e->getMessage();
2374
                }
2375
	}
2376
	public static function check_last_schedules_update() {
2377
		global $globalDBdriver;
2378
		if ($globalDBdriver == 'mysql') {
2379
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2380
		} else {
2381
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2382
		}
2383
		try {
2384
			$Connection = new Connection();
2385
			$sth = $Connection->db->prepare($query);
2386
                        $sth->execute();
2387
                } catch(PDOException $e) {
2388
                        return "error : ".$e->getMessage();
2389
                }
2390
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2391
                if ($row['nb'] > 0) return false;
2392
                else return true;
2393
	}
2394
2395
	public static function insert_last_schedules_update() {
2396
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2397
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2398
		try {
2399
			$Connection = new Connection();
2400
			$sth = $Connection->db->prepare($query);
2401
                        $sth->execute();
2402
                } catch(PDOException $e) {
2403
                        return "error : ".$e->getMessage();
2404
                }
2405
	}
2406
	public static function check_last_tle_update() {
2407
		global $globalDBdriver;
2408
		if ($globalDBdriver == 'mysql') {
2409
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2410
		} else {
2411
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2412
		}
2413
		try {
2414
			$Connection = new Connection();
2415
			$sth = $Connection->db->prepare($query);
2416
                        $sth->execute();
2417
                } catch(PDOException $e) {
2418
                        return "error : ".$e->getMessage();
2419
                }
2420
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2421
                if ($row['nb'] > 0) return false;
2422
                else return true;
2423
	}
2424
2425
	public static function insert_last_tle_update() {
2426
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2427
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2428
		try {
2429
			$Connection = new Connection();
2430
			$sth = $Connection->db->prepare($query);
2431
                        $sth->execute();
2432
                } catch(PDOException $e) {
2433
                        return "error : ".$e->getMessage();
2434
                }
2435
	}
2436
	public static function delete_duplicatemodes() {
2437
		global $globalDBdriver;
2438
		if ($globalDBdriver == 'mysql') {
2439
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
2440
		} else {
2441
			$query = "DELETE FROM aircraft_modes WHERE AircraftID IN (SELECT AircraftID FROM (SELECT AircraftID, ROW_NUMBER() OVER (partition BY ModeS ORDER BY FirstCreated) AS rnum FROM aircraft_modes) t WHERE t.rnum > 1) AND Source != 'ACARS'";
2442
		}
2443
		try {
2444
			$Connection = new Connection();
2445
			$sth = $Connection->db->prepare($query);
2446
                        $sth->execute();
2447
                } catch(PDOException $e) {
2448
                        return "error : ".$e->getMessage();
2449
                }
2450
	}
2451
	public static function delete_duplicateowner() {
2452
		global $globalDBdriver;
2453
		if ($globalDBdriver == 'mysql') {
2454
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
2455
		} else {
2456
			$query = "DELETE FROM aircraft_owner WHERE owner_id IN (SELECT owner_id FROM (SELECT owner_id, ROW_NUMBER() OVER (partition BY registration ORDER BY owner_id) AS rnum FROM aircraft_owner) t WHERE t.rnum > 1)";
2457
		}
2458
		try {
2459
			$Connection = new Connection();
2460
			$sth = $Connection->db->prepare($query);
2461
                        $sth->execute();
2462
                } catch(PDOException $e) {
2463
                        return "error : ".$e->getMessage();
2464
                }
2465
	}
2466
	
2467
	public static function update_all() {
2468
		global $globalMasterServer, $globalMasterSource;
2469
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2470
			if (isset($globalMasterSource) && $globalMasterSource) {
2471
				echo update_db::update_routes();
2472
				echo update_db::update_translation();
2473
				//echo update_db::update_notam_fam();
2474
				echo update_db::update_ModeS();
2475
				echo update_db::update_ModeS_flarm();
2476
				echo update_db::update_ModeS_ogn();
2477
				echo update_db::update_ModeS_faa();
2478
				echo update_db::fix_icaotype();
2479
				echo update_db::update_banned_fam();
2480
				//echo update_db::delete_duplicatemodes();
2481
			} else {
2482
				//echo update_db::update_routes();
2483
				echo update_db::update_routes_fam();
2484
				echo update_db::update_translation();
2485
				echo update_db::update_translation_fam();
2486
				//echo update_db::update_notam_fam();
2487
				//echo update_db::update_ModeS();
2488
				echo update_db::update_ModeS_fam();
2489
				echo update_db::update_ModeS_flarm();
2490
				echo update_db::update_ModeS_ogn();
2491
				echo update_db::delete_duplicatemodes();
2492
				echo update_db::update_banned_fam();
2493
			}
2494
		}
2495
	}
2496
}
2497
2498
//echo update_db::update_airports();
2499
//echo update_db::translation();
2500
//echo update_db::update_waypoints();
2501
//echo update_db::update_airspace();
2502
//echo update_db::update_notam();
2503
//echo update_db::update_ivao();
2504
//echo update_db::update_ModeS_flarm();
2505
//echo update_db::update_ModeS_ogn();
2506
//echo update_db::update_aircraft();
2507
//$update_db = new update_db();
2508
//echo $update_db->update_owner();
2509
//update_db::update_translation_fam();
2510
//echo update_db::update_routes();
2511
//update_db::update_models();
2512
//echo $update_db::update_skyteam();
2513
//echo $update_db::update_tle();
2514
//echo update_db::update_notam_fam();
2515
//echo update_db::create_airspace();
2516
//echo update_db::update_ModeS();
2517
//echo update_db::update_ModeS_fam();
2518
//echo update_db::update_routes_fam();
2519
//echo update_db::update_ModeS_faa();
2520
//echo update_db::update_banned_fam();
2521
//echo update_db::modes_faa();
2522
//echo update_db::update_owner_fam();
2523
//echo update_db::delete_duplicateowner();
2524
//echo update_db::fix_icaotype();
2525
?>
2526