Completed
Push — master ( d44f1f...2285a7 )
by Yannick
09:57
created

update_db::insert_last_banned_update()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
244
		} catch(PDOException $e) {
245
			return "error : ".$e->getMessage();
246
		}
247
248
		// 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
					$query = 'INSERT INTO aircraft_modes (FirstCreated,LastModified,ModeS,ModeSCountry,Registration,ICAOTypeCode,type_flight,Source) VALUES (:FirstCreated,:LastModified,:ModeS,:ModeSCountry,:Registration,:ICAOTypeCode,:type_flight,:source)';
1072
					try {
1073
						$sth = $Connection->db->prepare($query);
1074
						$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'));
1075
					} catch(PDOException $e) {
1076
						return "error : ".$e->getMessage();
1077
					}
1078
				}
1079
				$i++;
1080
			}
1081
			fclose($handle);
1082
			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...
1083
		}
1084
		return '';
1085
        }
1086
        
1087
	public static function owner_fam() {
1088
		global $tmp_dir, $globalTransaction;
1089
		$query = "DELETE FROM aircraft_owner WHERE Source = '' OR Source = :source";
1090
		try {
1091
			$Connection = new Connection();
1092
			$sth = $Connection->db->prepare($query);
1093
                        $sth->execute(array(':source' => 'website_fam'));
1094
                } catch(PDOException $e) {
1095
                        return "error : ".$e->getMessage();
1096
                }
1097
1098
		$delimiter = "\t";
1099
		$Connection = new Connection();
1100
		if (($handle = fopen($tmp_dir.'owners.tsv', 'r')) !== FALSE)
1101
		{
1102
			$i = 0;
1103
			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...
1104
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1105
			{
1106
				if ($i > 0) {
1107
					$query = 'INSERT INTO aircraft_owner (registration,base,owner,date_first_reg,Source) VALUES (:registration,:base,:owner,NULL,:source)';
1108
					try {
1109
						$sth = $Connection->db->prepare($query);
1110
						$sth->execute(array(':registration' => $data[0],':base' => $data[1],':owner' => $data[2], ':source' => 'website_fam'));
1111
					} catch(PDOException $e) {
1112
						print_r($data);
1113
						return "error : ".$e->getMessage();
1114
					}
1115
				}
1116
				$i++;
1117
			}
1118
			fclose($handle);
1119
			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...
1120
		}
1121
		return '';
1122
        }
1123
1124
	public static function routes_fam() {
1125
		global $tmp_dir, $globalTransaction;
1126
		$query = "DELETE FROM routes WHERE Source = '' OR Source = :source";
1127
		try {
1128
			$Connection = new Connection();
1129
			$sth = $Connection->db->prepare($query);
1130
                        $sth->execute(array(':source' => 'website_fam'));
1131
                } catch(PDOException $e) {
1132
                        return "error : ".$e->getMessage();
1133
                }
1134
1135
		
1136
		//update_db::unzip($out_file);
1137
		$delimiter = "\t";
1138
		$Connection = new Connection();
1139
		if (($handle = fopen($tmp_dir.'routes.tsv', 'r')) !== FALSE)
1140
		{
1141
			$i = 0;
1142
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1143
			//$Connection->db->beginTransaction();
1144
			if ($globalTransaction) $Connection->db->beginTransaction();
1 ignored issue
show
Bug introduced by
The method beginTransaction cannot be called on $Connection->db (of type null).

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

Loading history...
1145
			while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1146
			{
1147
				if ($i > 0) {
1148
					$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)';
1149
					try {
1150
						$sth = $Connection->db->prepare($query);
1151
						$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'));
1152
					} catch(PDOException $e) {
1153
						return "error : ".$e->getMessage();
1154
					}
1155
				}
1156
				$i++;
1157
			}
1158
			fclose($handle);
1159
			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...
1160
		}
1161
		return '';
1162
        }
1163
1164
	public static function banned_fam() {
1165
		global $tmp_dir, $globalTransaction;
1166
		$query = "UPDATE airlines SET ban_eu = 0";
1167
		try {
1168
			$Connection = new Connection();
1169
			$sth = $Connection->db->prepare($query);
1170
			$sth->execute();
1171
		} catch(PDOException $e) {
1172
			return "error : ".$e->getMessage();
1173
		}
1174
1175
		$Connection = new Connection();
1176
		if (($handle = fopen($tmp_dir.'ban_eu.csv', 'r')) !== FALSE)
1177
		{
1178
			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...
1179
			while (($data = fgetcsv($handle, 1000)) !== FALSE)
1180
			{
1181
				$query = 'UPDATE airlines SET ban_eu = 1 WHERE icao = :icao AND forsource IS NULL';
1182
				if ($data[0] != '') {
1183
					$icao = $data[0];
1184
					try {
1185
						$sth = $Connection->db->prepare($query);
1186
						$sth->execute(array(':icao' => $icao));
1187
					} catch(PDOException $e) {
1188
						return "error : ".$e->getMessage();
1189
					}
1190
				}
1191
			}
1192
			fclose($handle);
1193
			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...
1194
		}
1195
		return '';
1196
        }
1197
1198
	public static function tle($filename,$tletype) {
1199
		require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1200
		global $tmp_dir, $globalTransaction;
1201
		//$Spotter = new Spotter();
1202
		
1203
		$query = "DELETE FROM tle WHERE tle_source = '' OR tle_source = :source";
1204
		try {
1205
			$Connection = new Connection();
1206
			$sth = $Connection->db->prepare($query);
1207
                        $sth->execute(array(':source' => $filename));
1208
                } catch(PDOException $e) {
1209
                        return "error : ".$e->getMessage();
1210
                }
1211
		
1212
		$Connection = new Connection();
1213
		if (($handle = fopen($filename, 'r')) !== FALSE)
1214
		{
1215
			$i = 0;
1216
			//$Connection->db->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
1217
			//$Connection->db->beginTransaction();
1218
			$dbdata = array();
1219
			while (($data = fgets($handle, 1000)) !== FALSE)
1220
			{
1221
				if ($i == 0) {
1222
					$dbdata['name'] = trim($data);
1223
					$i++;
1224
				} elseif ($i == 1) {
1225
					$dbdata['tle1'] = trim($data);
1226
					$i++;
1227
				} elseif ($i == 2) {
1228
					$dbdata['tle2'] = trim($data);
1229
					//print_r($dbdata);
1230
					$query = 'INSERT INTO tle (tle_name,tle_tle1,tle_tle2,tle_type,tle_source) VALUES (:name, :tle1, :tle2, :type, :source)';
1231
					try {
1232
						$sth = $Connection->db->prepare($query);
1233
						$sth->execute(array(':name' => $dbdata['name'],':tle1' => $dbdata['tle1'],':tle2' => $dbdata['tle2'], ':type' => $tletype,':source' => $filename));
1234
					} catch(PDOException $e) {
1235
						return "error : ".$e->getMessage();
1236
					}
1237
1238
					$i = 0;
1239
				}
1240
			}
1241
			fclose($handle);
1242
			//$Connection->db->commit();
1243
		}
1244
		return '';
1245
        }
1246
1247
	/**
1248
        * Convert a HTML table to an array
1249
        * @param String $data HTML page
1250
        * @return Array array of the tables in HTML page
1251
        */
1252
        private static function table2array($data) {
1253
                $html = str_get_html($data);
1254
                $tabledata=array();
1255
                foreach($html->find('tr') as $element)
1256
                {
1257
                        $td = array();
1258
                        foreach( $element->find('th') as $row)
1259
                        {
1260
                                $td [] = trim($row->plaintext);
1261
                        }
1262
                        $td=array_filter($td);
1263
                        $tabledata[] = $td;
1264
1265
                        $td = array();
1266
                        $tdi = array();
1267
                        foreach( $element->find('td') as $row)
1268
                        {
1269
                                $td [] = trim($row->plaintext);
1270
                                $tdi [] = trim($row->innertext);
1271
                        }
1272
                        $td=array_filter($td);
1273
                        $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...
1274
                    //    $tabledata[]=array_merge($td,$tdi);
1275
                        $tabledata[]=$td;
1276
                }
1277
                return(array_filter($tabledata));
1278
        }
1279
1280
       /**
1281
        * Get data from form result
1282
        * @param String $url form URL
1283
        * @return String the result
1284
        */
1285
        private static function getData($url) {
1286
                $ch = curl_init();
1287
                curl_setopt($ch, CURLOPT_URL, $url);
1288
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1289
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1290
                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');
1291
                return curl_exec($ch);
1292
        }
1293
/*
1294
	public static function waypoints() {
1295
		$data = update_db::getData('http://www.fallingrain.com/world/FR/waypoints.html');
1296
		$table = update_db::table2array($data);
1297
//		print_r($table);
1298
		$query = 'TRUNCATE TABLE waypoints';
1299
		try {
1300
			$Connection = new Connection();
1301
			$sth = $Connection->db->prepare($query);
1302
                        $sth->execute();
1303
                } catch(PDOException $e) {
1304
                        return "error : ".$e->getMessage();
1305
                }
1306
1307
		$query_dest = 'INSERT INTO waypoints (`ident`,`latitude`,`longitude`,`control`,`usage`) VALUES (:ident, :latitude, :longitude, :control, :usage)';
1308
		$Connection = new Connection();
1309
		$sth_dest = $Connection->db->prepare($query_dest);
1310
		$Connection->db->beginTransaction();
1311
                foreach ($table as $row) {
1312
            		if ($row[0] != 'Ident') {
1313
				$ident = $row[0];
1314
				$latitude = $row[2];
1315
				$longitude = $row[3];
1316
				$control = $row[4];
1317
				if (isset($row[5])) $usage = $row[5]; else $usage = '';
1318
				$query_dest_values = array(':ident' => $ident,':latitude' => $latitude,':longitude' => $longitude,':control' => $control,':usage' => $usage);
1319
				try {
1320
					$sth_dest->execute($query_dest_values);
1321
				} catch(PDOException $e) {
1322
					return "error : ".$e->getMessage();
1323
				}
1324
			}
1325
                }
1326
		$Connection->db->commit();
1327
1328
	}
1329
*/
1330
	public static function waypoints($filename) {
1331
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1332
		global $tmp_dir, $globalTransaction;
1333
		//$Spotter = new Spotter();
1334
		//$out_file = $tmp_dir.'translation.zip';
1335
		//update_db::download('http://www.acarsd.org/download/translation.php',$out_file);
1336
		//if (!file_exists($out_file) || !is_readable($out_file)) return FALSE;
1337
		$Connection = new Connection();
1338
		//update_db::unzip($out_file);
1339
		$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...
1340
		$delimiter = ' ';
1341
		if (($handle = fopen($filename, 'r')) !== FALSE)
1342
		{
1343
			$i = 0;
1344
			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...
1345
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1346
			{
1347
				$i++;
1348
				if($i > 3 && count($row) > 2) {
1349
					$data = array_values(array_filter($row));
1350
					$cntdata = count($data);
1351
					if ($cntdata > 10) {
1352
						$value = $data[9];
1353
						
1354
						for ($i =10;$i < $cntdata;$i++) {
1355
							$value .= ' '.$data[$i];
1356
						}
1357
						$data[9] = $value;
1358
					}
1359
					//print_r($data);
1360
					if (count($data) > 9) {
1361
						$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)';
1362
						try {
1363
							$sth = $Connection->db->prepare($query);
1364
							$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]));
1365
						} catch(PDOException $e) {
1366
							return "error : ".$e->getMessage();
1367
						}
1368
					}
1369
				}
1370
			}
1371
			fclose($handle);
1372
			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...
1373
		}
1374
		return '';
1375
        }
1376
1377
	public static function ivao_airlines($filename) {
1378
		//require_once(dirname(__FILE__).'/../require/class.Spotter.php');
1379
		global $tmp_dir, $globalTransaction;
1380
		//$query = 'TRUNCATE TABLE airlines';
1381
		$query = "DELETE FROM airlines WHERE forsource = 'ivao'";
1382
		try {
1383
			$Connection = new Connection();
1384
			$sth = $Connection->db->prepare($query);
1385
                        $sth->execute();
1386
                } catch(PDOException $e) {
1387
                        return "error : ".$e->getMessage();
1388
                }
1389
1390
		$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...
1391
		$delimiter = ':';
1392
		$Connection = new Connection();
1393
		if (($handle = fopen($filename, 'r')) !== FALSE)
1394
		{
1395
			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...
1396
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
1397
			{
1398
				if(count($row) > 1) {
1399
					$query = "INSERT INTO airlines (name,icao,active,forsource) VALUES (:name, :icao, 'Y','ivao')";
1400
					try {
1401
						$sth = $Connection->db->prepare($query);
1402
						$sth->execute(array(':name' => $row[1],':icao' => $row[0]));
1403
					} catch(PDOException $e) {
1404
						return "error : ".$e->getMessage();
1405
					}
1406
				}
1407
			}
1408
			fclose($handle);
1409
			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...
1410
		}
1411
		return '';
1412
        }
1413
	
1414
	public static function update_airspace() {
1415
		global $tmp_dir, $globalDBdriver;
1416
		include_once('class.create_db.php');
1417
		$Connection = new Connection();
1418
		if ($Connection->tableExists('airspace')) {
1419
			$query = 'DROP TABLE airspace';
1420
			try {
1421
				$sth = $Connection->db->prepare($query);
1422
                    		$sth->execute();
1423
	                } catch(PDOException $e) {
1424
				return "error : ".$e->getMessage();
1425
	                }
1426
	        }
1427
1428
1429
		if ($globalDBdriver == 'mysql') update_db::gunzip('../db/airspace.sql.gz',$tmp_dir.'airspace.sql');
1430
		else {
1431
			update_db::gunzip('../db/pgsql/airspace.sql.gz',$tmp_dir.'airspace.sql');
1432
			$query = "CREATE EXTENSION postgis";
1433
			$Connection = new Connection(null,null,$_SESSION['database_root'],$_SESSION['database_rootpass']);
1434
			try {
1435
				$sth = $Connection->db->prepare($query);
1436
				$sth->execute();
1437
			} catch(PDOException $e) {
1438
				return "error : ".$e->getMessage();
1439
			}
1440
		}
1441
		$error = create_db::import_file($tmp_dir.'airspace.sql');
1442
		return $error;
1443
	}
1444
1445
	public static function update_notam_fam() {
1446
		global $tmp_dir, $globalDebug;
1447
		include_once('class.create_db.php');
1448
		require_once(dirname(__FILE__).'/../require/class.NOTAM.php');
1449
		if ($globalDebug) echo "NOTAM from FlightAirMap website : Download...";
1450
		update_db::download('http://data.flightairmap.fr/data/notam.txt.gz',$tmp_dir.'notam.txt.gz');
1451
		$error = '';
1452
		if (file_exists($tmp_dir.'notam.txt.gz')) {
1453
			if ($globalDebug) echo "Gunzip...";
1454
			update_db::gunzip($tmp_dir.'notam.txt.gz');
1455
			if ($globalDebug) echo "Add to DB...";
1456
			//$error = create_db::import_file($tmp_dir.'notam.sql');
1457
			$NOTAM = new NOTAM();
1458
			$NOTAM->updateNOTAMfromTextFile($tmp_dir.'notam.txt');
1459
		} else $error = "File ".$tmp_dir.'notam.txt.gz'." doesn't exist. Download failed.";
1460
		if ($error != '') {
1461
			return $error;
1462
		} elseif ($globalDebug) echo "Done\n";
1463
		return '';
1464
	}
1465
1466
	public static function update_vatsim() {
1467
		global $tmp_dir;
1468
		include_once('class.create_db.php');
1469
		$error = create_db::import_file('../db/vatsim/airlines.sql');
1470
		return $error;
1471
	}
1472
	
1473
	public static function update_countries() {
1474
		global $tmp_dir, $globalDBdriver;
1475
		include_once('class.create_db.php');
1476
		$Connection = new Connection();
1477
		if ($Connection->tableExists('countries')) {
1478
			$query = 'DROP TABLE countries';
1479
			try {
1480
				$sth = $Connection->db->prepare($query);
1481
            	        	$sth->execute();
1482
	                } catch(PDOException $e) {
1483
    	                	echo "error : ".$e->getMessage();
1484
	                }
1485
		}
1486
		if ($globalDBdriver == 'mysql') {
1487
			update_db::gunzip('../db/countries.sql.gz',$tmp_dir.'countries.sql');
1488
		} else {
1489
			update_db::gunzip('../db/pgsql/countries.sql.gz',$tmp_dir.'countries.sql');
1490
		}
1491
		$error = create_db::import_file($tmp_dir.'countries.sql');
1492
		return $error;
1493
	}
1494
1495
	
1496
	public static function update_waypoints() {
1497
		global $tmp_dir;
1498
//		update_db::download('http://dev.x-plane.com/update/data/AptNav201310XP1000.zip',$tmp_dir.'AptNav.zip');
1499
//		update_db::unzip($tmp_dir.'AptNav.zip');
1500
//		update_db::download('https://gitorious.org/fg/fgdata/raw/e81f8a15424a175a7b715f8f7eb8f4147b802a27:Navaids/awy.dat.gz',$tmp_dir.'awy.dat.gz');
1501
//		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');
1502
		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');
1503
		update_db::gunzip($tmp_dir.'awy.dat.gz');
1504
		$error = update_db::waypoints($tmp_dir.'awy.dat');
1505
		return $error;
1506
	}
1507
1508
	public static function update_ivao() {
1509
		global $tmp_dir, $globalDebug;
1510
		$Common = new Common();
1511
		$error = '';
1512
		//Direct download forbidden
1513
		//if ($globalDebug) echo "IVAO : Download...";
1514
		//update_db::download('http://fr.mirror.ivao.aero/software/ivae_feb2013.zip',$tmp_dir.'ivae_feb2013.zip');
1515
		if (file_exists($tmp_dir.'ivae_feb2013.zip')) {
1516
			if ($globalDebug) echo "Unzip...";
1517
			update_db::unzip($tmp_dir.'ivae_feb2013.zip');
1518
			if ($globalDebug) echo "Add to DB...";
1519
			update_db::ivao_airlines($tmp_dir.'data/airlines.dat');
1520
			if ($globalDebug) echo "Copy airlines logos to airlines images directory...";
1521
			if (is_writable(dirname(__FILE__).'/../images/airlines')) {
1522
				if (!$Common->xcopy($tmp_dir.'logos/',dirname(__FILE__).'/../images/airlines/')) $error = "Failed to copy airlines logo.";
1523
			} else $error = "The directory ".dirname(__FILE__).'/../images/airlines'." must be writable";
1524
		} else $error = "File ".$tmp_dir.'ivao.zip'." doesn't exist. Download failed.";
1525
		if ($error != '') {
1526
			return $error;
1527
		} elseif ($globalDebug) echo "Done\n";
1528
		return '';
1529
	}
1530
1531
	public static function update_routes() {
1532
		global $tmp_dir, $globalDebug;
1533
		$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...
1534
		if ($globalDebug) echo "Routes : Download...";
1535
		update_db::download('http://www.virtualradarserver.co.uk/Files/StandingData.sqb.gz',$tmp_dir.'StandingData.sqb.gz');
1536
		if (file_exists($tmp_dir.'StandingData.sqb.gz')) {
1537
			if ($globalDebug) echo "Gunzip...";
1538
			update_db::gunzip($tmp_dir.'StandingData.sqb.gz');
1539
			if ($globalDebug) echo "Add to DB...";
1540
			$error = update_db::retrieve_route_sqlite_to_dest($tmp_dir.'StandingData.sqb');
1541
		} else $error = "File ".$tmp_dir.'StandingData.sqb.gz'." doesn't exist. Download failed.";
1542
		if ($error != '') {
1543
			return $error;
1544
		} elseif ($globalDebug) echo "Done\n";
1545
		return '';
1546
	}
1547
	public static function update_oneworld() {
1548
		global $tmp_dir, $globalDebug;
1549
		$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...
1550
		if ($globalDebug) echo "Schedules Oneworld : Download...";
1551
		update_db::download('http://data.flightairmap.fr/data/schedules/oneworld.csv.gz',$tmp_dir.'oneworld.csv.gz');
1552
		if (file_exists($tmp_dir.'oneworld.csv.gz')) {
1553
			if ($globalDebug) echo "Gunzip...";
1554
			update_db::gunzip($tmp_dir.'oneworld.csv.gz');
1555
			if ($globalDebug) echo "Add to DB...";
1556
			$error = update_db::retrieve_route_oneworld($tmp_dir.'oneworld.csv');
1557
		} else $error = "File ".$tmp_dir.'oneworld.csv.gz'." doesn't exist. Download failed.";
1558
		if ($error != '') {
1559
			return $error;
1560
		} elseif ($globalDebug) echo "Done\n";
1561
		return '';
1562
	}
1563
	public static function update_skyteam() {
1564
		global $tmp_dir, $globalDebug;
1565
		$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...
1566
		if ($globalDebug) echo "Schedules Skyteam : Download...";
1567
		update_db::download('http://data.flightairmap.fr/data/schedules/skyteam.csv.gz',$tmp_dir.'skyteam.csv.gz');
1568
		if (file_exists($tmp_dir.'skyteam.csv.gz')) {
1569
			if ($globalDebug) echo "Gunzip...";
1570
			update_db::gunzip($tmp_dir.'skyteam.csv.gz');
1571
			if ($globalDebug) echo "Add to DB...";
1572
			$error = update_db::retrieve_route_skyteam($tmp_dir.'skyteam.csv');
1573
		} else $error = "File ".$tmp_dir.'skyteam.csv.gz'." doesn't exist. Download failed.";
1574
		if ($error != '') {
1575
			return $error;
1576
		} elseif ($globalDebug) echo "Done\n";
1577
		return '';
1578
	}
1579
	public static function update_ModeS() {
1580
		global $tmp_dir, $globalDebug;
1581
/*
1582
		if ($globalDebug) echo "Modes : Download...";
1583
		update_db::download('http://pp-sqb.mantma.co.uk/basestation_latest.zip',$tmp_dir.'basestation_latest.zip');
1584
		if ($globalDebug) echo "Unzip...";
1585
		update_db::unzip($tmp_dir.'basestation_latest.zip');
1586
		if ($globalDebug) echo "Add to DB...";
1587
		$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'/basestation_latest/basestation.sqb');
1588
		if ($error != true) {
1589
			echo $error;
1590
			exit;
1591
		} elseif ($globalDebug) echo "Done\n";
1592
*/
1593
		if ($globalDebug) echo "Modes : Download...";
1594
//		update_db::download('http://planebase.biz/sqb.php?f=basestationall.zip',$tmp_dir.'basestation_latest.zip','http://planebase.biz/bstnsqb');
1595
		update_db::download('http://data.flightairmap.fr/data/BaseStation.sqb.gz',$tmp_dir.'BaseStation.sqb.gz');
1596
1597
//		if (file_exists($tmp_dir.'basestation_latest.zip')) {
1598
		if (file_exists($tmp_dir.'BaseStation.sqb.gz')) {
1599
			if ($globalDebug) echo "Unzip...";
1600
//			update_db::unzip($tmp_dir.'basestation_latest.zip');
1601
			update_db::gunzip($tmp_dir.'BaseStation.sqb.gz');
1602
			if ($globalDebug) echo "Add to DB...";
1603
			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'BaseStation.sqb');
1604
//			$error = update_db::retrieve_modes_sqlite_to_dest($tmp_dir.'basestation.sqb');
1605
		} else $error = "File ".$tmp_dir.'basestation_latest.zip'." doesn't exist. Download failed.";
1606
		if ($error != '') {
1607
			return $error;
1608
		} elseif ($globalDebug) echo "Done\n";
1609
		return '';
1610
	}
1611
1612
	public static function update_ModeS_faa() {
1613
		global $tmp_dir, $globalDebug;
1614
		if ($globalDebug) echo "Modes FAA: Download...";
1615
		update_db::download('http://registry.faa.gov/database/ReleasableAircraft.zip',$tmp_dir.'ReleasableAircraft.zip');
1616
		if (file_exists($tmp_dir.'ReleasableAircraft.zip')) {
1617
			if ($globalDebug) echo "Unzip...";
1618
			update_db::unzip($tmp_dir.'ReleasableAircraft.zip');
1619
			if ($globalDebug) echo "Add to DB...";
1620
			$error = update_db::modes_faa();
1621
		} else $error = "File ".$tmp_dir.'ReleasableAircraft.zip'." doesn't exist. Download failed.";
1622
		if ($error != '') {
1623
			return $error;
1624
		} elseif ($globalDebug) echo "Done\n";
1625
		return '';
1626
	}
1627
1628
	public static function update_ModeS_flarm() {
1629
		global $tmp_dir, $globalDebug;
1630
		if ($globalDebug) echo "Modes Flarmnet: Download...";
1631
		update_db::download('http://flarmnet.org/files/data.fln',$tmp_dir.'data.fln');
1632
		if (file_exists($tmp_dir.'data.fln')) {
1633
			if ($globalDebug) echo "Add to DB...";
1634
			$error = update_db::retrieve_modes_flarmnet($tmp_dir.'data.fln');
1635
		} else $error = "File ".$tmp_dir.'data.fln'." doesn't exist. Download failed.";
1636
		if ($error != '') {
1637
			return $error;
1638
		} elseif ($globalDebug) echo "Done\n";
1639
		return '';
1640
	}
1641
1642
	public static function update_ModeS_ogn() {
1643
		global $tmp_dir, $globalDebug;
1644
		if ($globalDebug) echo "Modes OGN: Download...";
1645
		update_db::download('http://ddb.glidernet.org/download/',$tmp_dir.'ogn.csv');
1646
		if (file_exists($tmp_dir.'ogn.csv')) {
1647
			if ($globalDebug) echo "Add to DB...";
1648
			$error = update_db::retrieve_modes_ogn($tmp_dir.'ogn.csv');
1649
		} else $error = "File ".$tmp_dir.'ogn.csv'." doesn't exist. Download failed.";
1650
		if ($error != '') {
1651
			return $error;
1652
		} elseif ($globalDebug) echo "Done\n";
1653
		return '';
1654
	}
1655
1656
	public static function update_owner() {
1657
		global $tmp_dir, $globalDebug;
1658
		
1659
		if ($globalDebug) echo "Owner France: Download...";
1660
		update_db::download('http://antonakis.co.uk/registers/France.txt',$tmp_dir.'owner_f.csv');
1661
		if (file_exists($tmp_dir.'owner_f.csv')) {
1662
			if ($globalDebug) echo "Add to DB...";
1663
			$error = update_db::retrieve_owner($tmp_dir.'owner_f.csv','F');
1664
		} else $error = "File ".$tmp_dir.'owner_f.csv'." doesn't exist. Download failed.";
1665
		if ($error != '') {
1666
			return $error;
1667
		} elseif ($globalDebug) echo "Done\n";
1668
		
1669
		if ($globalDebug) echo "Owner Ireland: Download...";
1670
		update_db::download('http://antonakis.co.uk/registers/Ireland.txt',$tmp_dir.'owner_ei.csv');
1671
		if (file_exists($tmp_dir.'owner_ei.csv')) {
1672
			if ($globalDebug) echo "Add to DB...";
1673
			$error = update_db::retrieve_owner($tmp_dir.'owner_ei.csv','EI');
1674
		} else $error = "File ".$tmp_dir.'owner_ei.csv'." doesn't exist. Download failed.";
1675
		if ($error != '') {
1676
			return $error;
1677
		} elseif ($globalDebug) echo "Done\n";
1678
		if ($globalDebug) echo "Owner Switzerland: Download...";
1679
		update_db::download('http://antonakis.co.uk/registers/Switzerland.txt',$tmp_dir.'owner_hb.csv');
1680
		if (file_exists($tmp_dir.'owner_hb.csv')) {
1681
			if ($globalDebug) echo "Add to DB...";
1682
			$error = update_db::retrieve_owner($tmp_dir.'owner_hb.csv','HB');
1683
		} else $error = "File ".$tmp_dir.'owner_hb.csv'." doesn't exist. Download failed.";
1684
		if ($error != '') {
1685
			return $error;
1686
		} elseif ($globalDebug) echo "Done\n";
1687
		if ($globalDebug) echo "Owner Czech Republic: Download...";
1688
		update_db::download('http://antonakis.co.uk/registers/CzechRepublic.txt',$tmp_dir.'owner_ok.csv');
1689
		if (file_exists($tmp_dir.'owner_ok.csv')) {
1690
			if ($globalDebug) echo "Add to DB...";
1691
			$error = update_db::retrieve_owner($tmp_dir.'owner_ok.csv','OK');
1692
		} else $error = "File ".$tmp_dir.'owner_ok.csv'." doesn't exist. Download failed.";
1693
		if ($error != '') {
1694
			return $error;
1695
		} elseif ($globalDebug) echo "Done\n";
1696
		if ($globalDebug) echo "Owner Australia: Download...";
1697
		update_db::download('http://antonakis.co.uk/registers/Australia.txt',$tmp_dir.'owner_vh.csv');
1698
		if (file_exists($tmp_dir.'owner_vh.csv')) {
1699
			if ($globalDebug) echo "Add to DB...";
1700
			$error = update_db::retrieve_owner($tmp_dir.'owner_vh.csv','VH');
1701
		} else $error = "File ".$tmp_dir.'owner_vh.csv'." doesn't exist. Download failed.";
1702
		if ($error != '') {
1703
			return $error;
1704
		} elseif ($globalDebug) echo "Done\n";
1705
		if ($globalDebug) echo "Owner Austria: Download...";
1706
		update_db::download('http://antonakis.co.uk/registers/Austria.txt',$tmp_dir.'owner_oe.csv');
1707
		if (file_exists($tmp_dir.'owner_oe.csv')) {
1708
			if ($globalDebug) echo "Add to DB...";
1709
			$error = update_db::retrieve_owner($tmp_dir.'owner_oe.csv','OE');
1710
		} else $error = "File ".$tmp_dir.'owner_oe.csv'." doesn't exist. Download failed.";
1711
		if ($error != '') {
1712
			return $error;
1713
		} elseif ($globalDebug) echo "Done\n";
1714
		if ($globalDebug) echo "Owner Chile: Download...";
1715
		update_db::download('http://antonakis.co.uk/registers/Chile.txt',$tmp_dir.'owner_cc.csv');
1716
		if (file_exists($tmp_dir.'owner_cc.csv')) {
1717
			if ($globalDebug) echo "Add to DB...";
1718
			$error = update_db::retrieve_owner($tmp_dir.'owner_cc.csv','CC');
1719
		} else $error = "File ".$tmp_dir.'owner_cc.csv'." doesn't exist. Download failed.";
1720
		if ($error != '') {
1721
			return $error;
1722
		} elseif ($globalDebug) echo "Done\n";
1723
		if ($globalDebug) echo "Owner Colombia: Download...";
1724
		update_db::download('http://antonakis.co.uk/registers/Colombia.txt',$tmp_dir.'owner_hj.csv');
1725
		if (file_exists($tmp_dir.'owner_hj.csv')) {
1726
			if ($globalDebug) echo "Add to DB...";
1727
			$error = update_db::retrieve_owner($tmp_dir.'owner_hj.csv','HJ');
1728
		} else $error = "File ".$tmp_dir.'owner_hj.csv'." doesn't exist. Download failed.";
1729
		if ($error != '') {
1730
			return $error;
1731
		} elseif ($globalDebug) echo "Done\n";
1732
		if ($globalDebug) echo "Owner Bosnia Herzegobina: Download...";
1733
		update_db::download('http://antonakis.co.uk/registers/BosniaHerzegovina.txt',$tmp_dir.'owner_e7.csv');
1734
		if (file_exists($tmp_dir.'owner_e7.csv')) {
1735
			if ($globalDebug) echo "Add to DB...";
1736
			$error = update_db::retrieve_owner($tmp_dir.'owner_e7.csv','E7');
1737
		} else $error = "File ".$tmp_dir.'owner_e7.csv'." doesn't exist. Download failed.";
1738
		if ($error != '') {
1739
			return $error;
1740
		} elseif ($globalDebug) echo "Done\n";
1741
		if ($globalDebug) echo "Owner Brazil: Download...";
1742
		update_db::download('http://antonakis.co.uk/registers/Brazil.txt',$tmp_dir.'owner_pp.csv');
1743
		if (file_exists($tmp_dir.'owner_pp.csv')) {
1744
			if ($globalDebug) echo "Add to DB...";
1745
			$error = update_db::retrieve_owner($tmp_dir.'owner_pp.csv','PP');
1746
		} else $error = "File ".$tmp_dir.'owner_pp.csv'." doesn't exist. Download failed.";
1747
		if ($error != '') {
1748
			return $error;
1749
		} elseif ($globalDebug) echo "Done\n";
1750
		if ($globalDebug) echo "Owner Cayman Islands: Download...";
1751
		update_db::download('http://antonakis.co.uk/registers/CaymanIslands.txt',$tmp_dir.'owner_vp.csv');
1752
		if (file_exists($tmp_dir.'owner_vp.csv')) {
1753
			if ($globalDebug) echo "Add to DB...";
1754
			$error = update_db::retrieve_owner($tmp_dir.'owner_vp.csv','VP');
1755
		} else $error = "File ".$tmp_dir.'owner_vp.csv'." doesn't exist. Download failed.";
1756
		if ($error != '') {
1757
			return $error;
1758
		} elseif ($globalDebug) echo "Done\n";
1759
		if ($globalDebug) echo "Owner Croatia: Download...";
1760
		update_db::download('http://antonakis.co.uk/registers/Croatia.txt',$tmp_dir.'owner_9a.csv');
1761
		if (file_exists($tmp_dir.'owner_9a.csv')) {
1762
			if ($globalDebug) echo "Add to DB...";
1763
			$error = update_db::retrieve_owner($tmp_dir.'owner_9a.csv','9A');
1764
		} else $error = "File ".$tmp_dir.'owner_9a.csv'." doesn't exist. Download failed.";
1765
		if ($error != '') {
1766
			return $error;
1767
		} elseif ($globalDebug) echo "Done\n";
1768
		if ($globalDebug) echo "Owner Luxembourg: Download...";
1769
		update_db::download('http://antonakis.co.uk/registers/Luxembourg.txt',$tmp_dir.'owner_lx.csv');
1770
		if (file_exists($tmp_dir.'owner_lx.csv')) {
1771
			if ($globalDebug) echo "Add to DB...";
1772
			$error = update_db::retrieve_owner($tmp_dir.'owner_lx.csv','LX');
1773
		} else $error = "File ".$tmp_dir.'owner_lx.csv'." doesn't exist. Download failed.";
1774
		if ($error != '') {
1775
			return $error;
1776
		} elseif ($globalDebug) echo "Done\n";
1777
		if ($globalDebug) echo "Owner Maldives: Download...";
1778
		update_db::download('http://antonakis.co.uk/registers/Maldives.txt',$tmp_dir.'owner_8q.csv');
1779
		if (file_exists($tmp_dir.'owner_8q.csv')) {
1780
			if ($globalDebug) echo "Add to DB...";
1781
			$error = update_db::retrieve_owner($tmp_dir.'owner_8q.csv','8Q');
1782
		} else $error = "File ".$tmp_dir.'owner_8q.csv'." doesn't exist. Download failed.";
1783
		if ($error != '') {
1784
			return $error;
1785
		} elseif ($globalDebug) echo "Done\n";
1786
		if ($globalDebug) echo "Owner New Zealand: Download...";
1787
		update_db::download('http://antonakis.co.uk/registers/NewZealand.txt',$tmp_dir.'owner_zk.csv');
1788
		if (file_exists($tmp_dir.'owner_zk.csv')) {
1789
			if ($globalDebug) echo "Add to DB...";
1790
			$error = update_db::retrieve_owner($tmp_dir.'owner_zk.csv','ZK');
1791
		} else $error = "File ".$tmp_dir.'owner_zk.csv'." doesn't exist. Download failed.";
1792
		if ($error != '') {
1793
			return $error;
1794
		} elseif ($globalDebug) echo "Done\n";
1795
		if ($globalDebug) echo "Owner Papua New Guinea: Download...";
1796
		update_db::download('http://antonakis.co.uk/registers/PapuaNewGuinea.txt',$tmp_dir.'owner_p2.csv');
1797
		if (file_exists($tmp_dir.'owner_p2.csv')) {
1798
			if ($globalDebug) echo "Add to DB...";
1799
			$error = update_db::retrieve_owner($tmp_dir.'owner_p2.csv','P2');
1800
		} else $error = "File ".$tmp_dir.'owner_p2.csv'." doesn't exist. Download failed.";
1801
		if ($error != '') {
1802
			return $error;
1803
		} elseif ($globalDebug) echo "Done\n";
1804
		if ($globalDebug) echo "Owner Slovakia: Download...";
1805
		update_db::download('http://antonakis.co.uk/registers/Slovakia.txt',$tmp_dir.'owner_om.csv');
1806
		if (file_exists($tmp_dir.'owner_om.csv')) {
1807
			if ($globalDebug) echo "Add to DB...";
1808
			$error = update_db::retrieve_owner($tmp_dir.'owner_om.csv','OM');
1809
		} else $error = "File ".$tmp_dir.'owner_om.csv'." doesn't exist. Download failed.";
1810
		if ($error != '') {
1811
			return $error;
1812
		} elseif ($globalDebug) echo "Done\n";
1813
		if ($globalDebug) echo "Owner Ecuador: Download...";
1814
		update_db::download('http://antonakis.co.uk/registers/Ecuador.txt',$tmp_dir.'owner_hc.csv');
1815
		if (file_exists($tmp_dir.'owner_hc.csv')) {
1816
			if ($globalDebug) echo "Add to DB...";
1817
			$error = update_db::retrieve_owner($tmp_dir.'owner_hc.csv','HC');
1818
		} else $error = "File ".$tmp_dir.'owner_hc.csv'." doesn't exist. Download failed.";
1819
		if ($error != '') {
1820
			return $error;
1821
		} elseif ($globalDebug) echo "Done\n";
1822
		if ($globalDebug) echo "Owner Iceland: Download...";
1823
		update_db::download('http://antonakis.co.uk/registers/Iceland.txt',$tmp_dir.'owner_tf.csv');
1824
		if (file_exists($tmp_dir.'owner_tf.csv')) {
1825
			if ($globalDebug) echo "Add to DB...";
1826
			$error = update_db::retrieve_owner($tmp_dir.'owner_tf.csv','TF');
1827
		} else $error = "File ".$tmp_dir.'owner_tf.csv'." doesn't exist. Download failed.";
1828
		if ($error != '') {
1829
			return $error;
1830
		} elseif ($globalDebug) echo "Done\n";
1831
		return '';
1832
	}
1833
1834
	public static function update_translation() {
1835
		global $tmp_dir, $globalDebug;
1836
		$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...
1837
		if ($globalDebug) echo "Translation : Download...";
1838
		update_db::download('http://www.acarsd.org/download/translation.php',$tmp_dir.'translation.zip');
1839
		if (file_exists($tmp_dir.'translation.zip')) {
1840
			if ($globalDebug) echo "Unzip...";
1841
			update_db::unzip($tmp_dir.'translation.zip');
1842
			if ($globalDebug) echo "Add to DB...";
1843
			$error = update_db::translation();
1844
		} else $error = "File ".$tmp_dir.'translation.zip'." doesn't exist. Download failed.";
1845
		if ($error != '') {
1846
			return $error;
1847
		} elseif ($globalDebug) echo "Done\n";
1848
		return '';
1849
	}
1850
1851
	public static function update_translation_fam() {
1852
		global $tmp_dir, $globalDebug;
1853
		if ($globalDebug) echo "Translation from FlightAirMap website : Download...";
1854
		update_db::download('http://data.flightairmap.fr/data/translation.tsv.gz',$tmp_dir.'translation.tsv.gz');
1855
		if (file_exists($tmp_dir.'translation.tsv.gz')) {
1856
			if ($globalDebug) echo "Gunzip...";
1857
			update_db::gunzip($tmp_dir.'translation.tsv.gz');
1858
			if ($globalDebug) echo "Add to DB...";
1859
			$error = update_db::translation_fam();
1860
		} else $error = "File ".$tmp_dir.'translation.tsv.gz'." doesn't exist. Download failed.";
1861
		if ($error != '') {
1862
			return $error;
1863
		} elseif ($globalDebug) echo "Done\n";
1864
		return '';
1865
	}
1866
	public static function update_ModeS_fam() {
1867
		global $tmp_dir, $globalDebug;
1868
		if ($globalDebug) echo "ModeS from FlightAirMap website : Download...";
1869
		update_db::download('http://data.flightairmap.fr/data/modes.tsv.gz',$tmp_dir.'modes.tsv.gz');
1870
		if (file_exists($tmp_dir.'modes.tsv.gz')) {
1871
			if ($globalDebug) echo "Gunzip...";
1872
			update_db::gunzip($tmp_dir.'modes.tsv.gz');
1873
			if ($globalDebug) echo "Add to DB...";
1874
			$error = update_db::modes_fam();
1875
		} else $error = "File ".$tmp_dir.'modes.tsv.gz'." doesn't exist. Download failed.";
1876
		if ($error != '') {
1877
			return $error;
1878
		} elseif ($globalDebug) echo "Done\n";
1879
		return '';
1880
	}
1881
	public static function update_owner_fam() {
1882
		global $tmp_dir, $globalDebug, $globalOwner;
1883
		if ($globalDebug) echo "owner from FlightAirMap website : Download...";
1884
		if ($globalOwner === TRUE) {
1885
			update_db::download('http://data.flightairmap.fr/data/owners_all.tsv.gz',$tmp_dir.'owners.tsv.gz');
1886
		} else {
1887
			update_db::download('http://data.flightairmap.fr/data/owners.tsv.gz',$tmp_dir.'owners.tsv.gz');
1888
		}
1889
		if (file_exists($tmp_dir.'owners.tsv.gz')) {
1890
			if ($globalDebug) echo "Gunzip...";
1891
			update_db::gunzip($tmp_dir.'owners.tsv.gz');
1892
			if ($globalDebug) echo "Add to DB...";
1893
			$error = update_db::owner_fam();
1894
		} else $error = "File ".$tmp_dir.'owners.tsv.gz'." doesn't exist. Download failed.";
1895
		if ($error != '') {
1896
			return $error;
1897
		} elseif ($globalDebug) echo "Done\n";
1898
		return '';
1899
	}
1900
	public static function update_routes_fam() {
1901
		global $tmp_dir, $globalDebug;
1902
		if ($globalDebug) echo "Routes from FlightAirMap website : Download...";
1903
		update_db::download('http://data.flightairmap.fr/data/routes.tsv.gz',$tmp_dir.'routes.tsv.gz');
1904
		if (file_exists($tmp_dir.'routes.tsv.gz')) {
1905
			if ($globalDebug) echo "Gunzip...";
1906
			update_db::gunzip($tmp_dir.'routes.tsv.gz');
1907
			if ($globalDebug) echo "Add to DB...";
1908
			$error = update_db::routes_fam();
1909
		} else $error = "File ".$tmp_dir.'routes.tsv.gz'." doesn't exist. Download failed.";
1910
		if ($error != '') {
1911
			return $error;
1912
		} elseif ($globalDebug) echo "Done\n";
1913
		return '';
1914
	}
1915
	public static function update_banned_fam() {
1916
		global $tmp_dir, $globalDebug;
1917
		if ($globalDebug) echo "Banned airlines in Europe from FlightAirMap website : Download...";
1918
		update_db::download('http://data.flightairmap.fr/data/ban_eu.csv',$tmp_dir.'ban_eu.csv');
1919
		if (file_exists($tmp_dir.'ban_eu.csv')) {
1920
			//if ($globalDebug) echo "Gunzip...";
1921
			//update_db::gunzip($tmp_dir.'ban_ue.csv');
1922
			if ($globalDebug) echo "Add to DB...";
1923
			$error = update_db::banned_fam();
1924
		} else $error = "File ".$tmp_dir.'ban_eu.csv'." doesn't exist. Download failed.";
1925
		if ($error != '') {
1926
			return $error;
1927
		} elseif ($globalDebug) echo "Done\n";
1928
		return '';
1929
	}
1930
1931
	public static function update_airspace_fam() {
1932
		global $tmp_dir, $globalDebug, $globalDBdriver;
1933
		include_once('class.create_db.php');
1934
		$error = '';
1935
		if ($globalDebug) echo "Airspace from FlightAirMap website : Download...";
1936
		if ($globalDBdriver == 'mysql') {
1937
			update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1938
		} else {
1939
			update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz.md5',$tmp_dir.'airspace.sql.gz.md5');
1940
		}
1941
		if (file_exists($tmp_dir.'airspace.sql.gz.md5')) {
1942
			$airspace_md5_file = explode(' ',file_get_contents($tmp_dir.'airspace.sql.gz.md5'));
1943
			$airspace_md5 = $airspace_md5_file[0];
1944
			if (!update_db::check_airspace_version($airspace_md5)) {
1945
				if ($globalDBdriver == 'mysql') {
1946
					update_db::download('http://data.flightairmap.fr/data/airspace_mysql.sql.gz',$tmp_dir.'airspace.sql.gz');
1947
				} else {
1948
					update_db::download('http://data.flightairmap.fr/data/airspace_pgsql.sql.gz',$tmp_dir.'airspace.sql.gz');
1949
				}
1950
				if (file_exists($tmp_dir.'airspace.sql.gz')) {
1951
					if ($globalDebug) echo "Gunzip...";
1952
					update_db::gunzip($tmp_dir.'airspace.sql.gz');
1953
					if ($globalDebug) echo "Add to DB...";
1954
					$Connection = new Connection();
1955
					if ($Connection->tableExists('airspace')) {
1956
						$query = 'DROP TABLE airspace';
1957
						try {
1958
							$sth = $Connection->db->prepare($query);
1959
    	    	    					$sth->execute();
1960
			            		} catch(PDOException $e) {
1961
							return "error : ".$e->getMessage();
1962
		            			}
1963
		    			}
1964
					$error = create_db::import_file($tmp_dir.'airspace.sql');
1965
					update_db::insert_airspace_version($airspace_md5);
1966
				} else $error = "File ".$tmp_dir.'airpsace.sql.gz'." doesn't exist. Download failed.";
1967
			}
1968
		} else $error = "File ".$tmp_dir.'airpsace.sql.gz.md5'." doesn't exist. Download failed.";
1969
		if ($error != '') {
1970
			return $error;
1971
		} elseif ($globalDebug) echo "Done\n";
1972
		return '';
1973
	}
1974
1975
	public static function update_tle() {
1976
		global $tmp_dir, $globalDebug;
1977
		if ($globalDebug) echo "Download TLE : Download...";
1978
		$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',
1979
		'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',
1980
		'engineering.txt','education.txt','military.txt','radar.txt','cubesat.txt','other.txt','tle-new.txt');
1981
		foreach ($alltle as $filename) {
1982
			if ($globalDebug) echo "downloading ".$filename.'...';
1983
			update_db::download('http://celestrak.com/NORAD/elements/'.$filename,$tmp_dir.$filename);
1984
			if (file_exists($tmp_dir.$filename)) {
1985
				if ($globalDebug) echo "Add to DB ".$filename."...";
1986
				$error = update_db::tle($tmp_dir.$filename,str_replace('.txt','',$filename));
1987
			} else $error = "File ".$tmp_dir.$filename." doesn't exist. Download failed.";
1988
			if ($error != '') {
1989
				echo $error."\n";
1990
			} elseif ($globalDebug) echo "Done\n";
1991
		}
1992
		return '';
1993
	}
1994
1995
	public static function update_models() {
1996
		global $tmp_dir, $globalDebug;
1997
		$error = '';
1998
		if ($globalDebug) echo "Models from FlightAirMap website : Download...";
1999
		update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',$tmp_dir.'models.md5sum');
2000
		if (file_exists($tmp_dir.'models.md5sum')) {
2001
			if ($globalDebug) echo "Check files...\n";
2002
			$newmodelsdb = array();
2003
			if (($handle = fopen($tmp_dir.'models.md5sum','r')) !== FALSE) {
2004
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2005
					$model = trim($row[2]);
2006
					$newmodelsdb[$model] = trim($row[0]);
2007
				}
2008
			}
2009
			$modelsdb = array();
2010
			if (file_exists(dirname(__FILE__).'/../models/models.md5sum')) {
2011
				if (($handle = fopen(dirname(__FILE__).'/../models/models.md5sum','r')) !== FALSE) {
2012
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2013
						$model = trim($row[2]);
2014
						$modelsdb[$model] = trim($row[0]);
2015
					}
2016
				}
2017
			}
2018
			$diff = array_diff($newmodelsdb,$modelsdb);
2019
			foreach ($diff as $key => $value) {
2020
				if ($globalDebug) echo 'Downloading model '.$key.' ...'."\n";
2021
				update_db::download('http://data.flightairmap.fr/data/models/'.$key,dirname(__FILE__).'/../models/'.$key);
2022
				
2023
			}
2024
			update_db::download('http://data.flightairmap.fr/data/models/models.md5sum',dirname(__FILE__).'/../models/models.md5sum');
2025
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2026
		if ($error != '') {
2027
			return $error;
2028
		} elseif ($globalDebug) echo "Done\n";
2029
		return '';
2030
	}
2031
2032
	public static function update_space_models() {
2033
		global $tmp_dir, $globalDebug;
2034
		$error = '';
2035
		if ($globalDebug) echo "Space models from FlightAirMap website : Download...";
2036
		update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',$tmp_dir.'space_models.md5sum');
2037
		if (file_exists($tmp_dir.'space_models.md5sum')) {
2038
			if ($globalDebug) echo "Check files...\n";
2039
			$newmodelsdb = array();
2040
			if (($handle = fopen($tmp_dir.'space_models.md5sum','r')) !== FALSE) {
2041
				while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2042
					$model = trim($row[2]);
2043
					$newmodelsdb[$model] = trim($row[0]);
2044
				}
2045
			}
2046
			$modelsdb = array();
2047
			if (file_exists(dirname(__FILE__).'/../models/space/space_models.md5sum')) {
2048
				if (($handle = fopen(dirname(__FILE__).'/../models/space/space_models.md5sum','r')) !== FALSE) {
2049
					while (($row = fgetcsv($handle,1000," ")) !== FALSE) {
2050
						$model = trim($row[2]);
2051
						$modelsdb[$model] = trim($row[0]);
2052
					}
2053
				}
2054
			}
2055
			$diff = array_diff($newmodelsdb,$modelsdb);
2056
			foreach ($diff as $key => $value) {
2057
				if ($globalDebug) echo 'Downloading space model '.$key.' ...'."\n";
2058
				update_db::download('http://data.flightairmap.fr/data/models/space/'.$key,dirname(__FILE__).'/../models/space/'.$key);
2059
				
2060
			}
2061
			update_db::download('http://data.flightairmap.fr/data/models/space/space_models.md5sum',dirname(__FILE__).'/../models/space/space_models.md5sum');
2062
		} else $error = "File ".$tmp_dir.'models.md5sum'." doesn't exist. Download failed.";
2063
		if ($error != '') {
2064
			return $error;
2065
		} elseif ($globalDebug) echo "Done\n";
2066
		return '';
2067
	}
2068
2069
	public static function update_aircraft() {
2070
		global $tmp_dir, $globalDebug;
2071
		date_default_timezone_set('UTC');
2072
		//$error = '';
2073
		/*
2074
		if ($globalDebug) echo "Aircrafts : Download...";
2075
		$data_req_array = array('Mnfctrer' => '','Model' => '','Dscrptn'=> '','EngCount' =>'' ,'EngType'=> '','TDesig' => '*','WTC' => '','Button' => 'Search');
2076
		$data_req = 'Mnfctrer=Airbus&Model=&Dscrptn=&EngCount=&EngType=&TDesig=&WTC=&Button=Search';
2077
		//$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);
2078
		$data = Common::getData('http://cfapp.icao.int/Doc8643/8643_List1.cfm','post',$data_req_array,'','','http://cfapp.icao.int/Doc8643/search.cfm',30);
2079
//		echo strlen($data_req);
2080
		echo $data;
2081
		*/
2082
		if (file_exists($tmp_dir.'aircrafts.html')) {
2083
		    //var_dump(file_get_html($tmp_dir.'aircrafts.html'));
2084
		    $fh = fopen($tmp_dir.'aircrafts.html',"r");
2085
		    $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...
2086
		    //echo $result;
2087
		    //var_dump(str_get_html($result));
2088
		    //print_r(self::table2array($result));
2089
		}
2090
2091
	}
2092
	
2093
	public static function update_notam() {
2094
		global $tmp_dir, $globalDebug, $globalNOTAMSource;
2095
		require(dirname(__FILE__).'/../require/class.NOTAM.php');
2096
		$Common = new Common();
2097
		date_default_timezone_set('UTC');
2098
		$query = 'TRUNCATE TABLE notam';
2099
		try {
2100
			$Connection = new Connection();
2101
			$sth = $Connection->db->prepare($query);
2102
                        $sth->execute();
2103
                } catch(PDOException $e) {
2104
                        return "error : ".$e->getMessage();
2105
                }
2106
2107
		$error = '';
2108
		if ($globalDebug) echo "Notam : Download...";
2109
		update_db::download($globalNOTAMSource,$tmp_dir.'notam.rss');
2110
		if (file_exists($tmp_dir.'notam.rss')) {
2111
			$notams = json_decode(json_encode(simplexml_load_file($tmp_dir.'notam.rss')),true);
2112
			foreach ($notams['channel']['item'] as $notam) {
2113
				$title = explode(':',$notam['title']);
2114
				$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...
2115
				unset($title[0]);
2116
				$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...
2117
				$description = strip_tags($notam['description'],'<pre>');
2118
				preg_match(':^(.*?)<pre>:',$description,$match);
2119
				$q = explode('/',$match[1]);
2120
				$data['fir'] = $q[0];
2121
				$data['code'] = $q[1];
2122
				$ifrvfr = $q[2];
2123
				if ($ifrvfr == 'IV') $data['rules'] = 'IFR/VFR';
2124
				if ($ifrvfr == 'I') $data['rules'] = 'IFR';
2125
				if ($ifrvfr == 'V') $data['rules'] = 'VFR';
2126
				if ($q[4] == 'A') $data['scope'] = 'Airport warning';
2127
				if ($q[4] == 'E') $data['scope'] = 'Enroute warning';
2128
				if ($q[4] == 'W') $data['scope'] = 'Navigation warning';
2129
				if ($q[4] == 'AE') $data['scope'] = 'Airport/Enroute warning';
2130
				if ($q[4] == 'AW') $data['scope'] = 'Airport/Navigation warning';
2131
				//$data['scope'] = $q[4];
2132
				$data['lower_limit'] = $q[5];
2133
				$data['upper_limit'] = $q[6];
2134
				$latlonrad = $q[7];
2135
				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...
2136
				$latitude = $Common->convertDec($las,'latitude');
2137
				$longitude = $Common->convertDec($lns,'longitude');
2138
				if ($lac == 'S') $latitude = '-'.$latitude;
2139
				if ($lnc == 'W') $longitude = '-'.$longitude;
2140
				$data['center_latitude'] = $latitude;
2141
				$data['center_longitude'] = $longitude;
2142
				$data['radius'] = intval($radius);
2143
				
2144
				preg_match(':<pre>(.*?)</pre>:',$description,$match);
2145
				$data['text'] = $match[1];
2146
				preg_match(':</pre>(.*?)$:',$description,$match);
2147
				$fromto = $match[1];
2148
				preg_match('#FROM:(.*?)TO:#',$fromto,$match);
2149
				$fromall = trim($match[1]);
2150
				preg_match('#^(.*?) \((.*?)\)$#',$fromall,$match);
2151
				$from = trim($match[1]);
2152
				$data['date_begin'] = date("Y-m-d H:i:s",strtotime($from));
2153
				preg_match('#TO:(.*?)$#',$fromto,$match);
2154
				$toall = trim($match[1]);
2155
				if (!preg_match(':Permanent:',$toall)) {
2156
					preg_match('#^(.*?) \((.*?)\)#',$toall,$match);
2157
					$to = trim($match[1]);
2158
					$data['date_end'] = date("Y-m-d H:i:s",strtotime($to));
2159
					$data['permanent'] = 0;
2160
				} else {
2161
				    $data['date_end'] = NULL;
2162
				    $data['permanent'] = 1;
2163
				}
2164
				$data['full_notam'] = $notam['title'].'<br>'.$notam['description'];
2165
				$NOTAM = new NOTAM();
2166
				$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']);
2167
				unset($data);
2168
			} 
2169
		} else $error = "File ".$tmp_dir.'notam.rss'." doesn't exist. Download failed.";
2170
		if ($error != '') {
2171
			return $error;
2172
		} elseif ($globalDebug) echo "Done\n";
2173
		return '';
2174
	}
2175
	
2176
	public static function create_airspace() {
2177
		global $globalDBdriver, $globalDebug, $tmp_dir, $globalDBhost, $globalDBuser, $globalDBname, $globalDBpass, $globalDBport;
2178
		$Connection = new Connection();
2179
		if ($Connection->tableExists('airspace')) {
2180
			if ($globalDBdriver == 'mysql') {
2181
				$query = 'DROP TABLE geometry_columns; DROP TABLE spatial_ref_sys;DROP TABLE airspace;';
2182
			} else {
2183
				$query = 'DROP TABLE airspace';
2184
			}
2185
			try {
2186
				$Connection = new Connection();
2187
				$sth = $Connection->db->prepare($query);
2188
				$sth->execute();
2189
			} catch(PDOException $e) {
2190
				return "error : ".$e->getMessage();
2191
			}
2192
		}
2193
		$Common = new Common();
2194
		$airspace_lst = $Common->getData('https://raw.githubusercontent.com/XCSoar/xcsoar-data-repository/master/data/airspace.json');
2195
		$airspace_json = json_decode($airspace_lst,true);
2196
		foreach ($airspace_json['records'] as $airspace) {
2197
			if ($globalDebug) echo $airspace['name']."...\n";
2198
			update_db::download($airspace['uri'],$tmp_dir.$airspace['name']);
2199
			if (file_exists($tmp_dir.$airspace['name'])) {
2200
				file_put_contents($tmp_dir.$airspace['name'], utf8_encode(file_get_contents($tmp_dir.$airspace['name'])));
2201
				//system('recode l9..utf8 '.$tmp_dir.$airspace['name']);
2202
				if ($globalDBdriver == 'mysql') {
2203
					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'].'"');
2204
				} else {
2205
					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'].'"');
2206
				}
2207
			}
2208
		}
2209
	}
2210
	
2211
	public static function check_last_update() {
2212
		global $globalDBdriver;
2213
		if ($globalDBdriver == 'mysql') {
2214
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2215
		} else {
2216
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2217
		}
2218
		try {
2219
			$Connection = new Connection();
2220
			$sth = $Connection->db->prepare($query);
2221
                        $sth->execute();
2222
                } catch(PDOException $e) {
2223
                        return "error : ".$e->getMessage();
2224
                }
2225
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2226
                if ($row['nb'] > 0) return false;
2227
                else return true;
2228
	}
2229
2230
	public static function insert_last_update() {
2231
		$query = "DELETE FROM config WHERE name = 'last_update_db';
2232
			INSERT INTO config (name,value) VALUES ('last_update_db',NOW());";
2233
		try {
2234
			$Connection = new Connection();
2235
			$sth = $Connection->db->prepare($query);
2236
                        $sth->execute();
2237
                } catch(PDOException $e) {
2238
                        return "error : ".$e->getMessage();
2239
                }
2240
	}
2241
2242
	public static function check_airspace_version($version) {
2243
		$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'airspace_version' AND value = :version";
2244
		try {
2245
			$Connection = new Connection();
2246
			$sth = $Connection->db->prepare($query);
2247
                        $sth->execute(array(':version' => $version));
2248
                } catch(PDOException $e) {
2249
                        return "error : ".$e->getMessage();
2250
                }
2251
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2252
                if ($row['nb'] > 0) return true;
2253
                else return false;
2254
	}
2255
2256
2257
	public static function insert_airspace_version($version) {
2258
		$query = "DELETE FROM config WHERE name = 'airspace_version';
2259
			INSERT INTO config (name,value) VALUES ('airspace_version',: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
	}
2268
2269
	public static function check_last_notam_update() {
2270
		global $globalDBdriver;
2271
		if ($globalDBdriver == 'mysql') {
2272
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
2273
		} else {
2274
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_notam_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
2275
		}
2276
		try {
2277
			$Connection = new Connection();
2278
			$sth = $Connection->db->prepare($query);
2279
                        $sth->execute();
2280
                } catch(PDOException $e) {
2281
                        return "error : ".$e->getMessage();
2282
                }
2283
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2284
                if ($row['nb'] > 0) return false;
2285
                else return true;
2286
	}
2287
2288
	public static function insert_last_notam_update() {
2289
		$query = "DELETE FROM config WHERE name = 'last_update_notam_db';
2290
			INSERT INTO config (name,value) VALUES ('last_update_notam_db',NOW());";
2291
		try {
2292
			$Connection = new Connection();
2293
			$sth = $Connection->db->prepare($query);
2294
                        $sth->execute();
2295
                } catch(PDOException $e) {
2296
                        return "error : ".$e->getMessage();
2297
                }
2298
	}
2299
	public static function check_last_airspace_update() {
2300
		global $globalDBdriver;
2301
		if ($globalDBdriver == 'mysql') {
2302
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2303
		} else {
2304
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_airspace_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2305
		}
2306
		try {
2307
			$Connection = new Connection();
2308
			$sth = $Connection->db->prepare($query);
2309
                        $sth->execute();
2310
                } catch(PDOException $e) {
2311
                        return "error : ".$e->getMessage();
2312
                }
2313
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2314
                if ($row['nb'] > 0) return false;
2315
                else return true;
2316
	}
2317
2318
	public static function insert_last_airspace_update() {
2319
		$query = "DELETE FROM config WHERE name = 'last_update_airspace_db';
2320
			INSERT INTO config (name,value) VALUES ('last_update_airspace_db',NOW());";
2321
		try {
2322
			$Connection = new Connection();
2323
			$sth = $Connection->db->prepare($query);
2324
                        $sth->execute();
2325
                } catch(PDOException $e) {
2326
                        return "error : ".$e->getMessage();
2327
                }
2328
	}
2329
2330
	public static function check_last_owner_update() {
2331
		global $globalDBdriver;
2332
		if ($globalDBdriver == 'mysql') {
2333
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2334
		} else {
2335
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_owner_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2336
		}
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
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2345
                if ($row['nb'] > 0) return false;
2346
                else return true;
2347
	}
2348
2349
	public static function insert_last_owner_update() {
2350
		$query = "DELETE FROM config WHERE name = 'last_update_owner_db';
2351
			INSERT INTO config (name,value) VALUES ('last_update_owner_db',NOW());";
2352
		try {
2353
			$Connection = new Connection();
2354
			$sth = $Connection->db->prepare($query);
2355
                        $sth->execute();
2356
                } catch(PDOException $e) {
2357
                        return "error : ".$e->getMessage();
2358
                }
2359
	}
2360
	public static function check_last_schedules_update() {
2361
		global $globalDBdriver;
2362
		if ($globalDBdriver == 'mysql') {
2363
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value > DATE_SUB(NOW(), INTERVAL 15 DAY)";
2364
		} else {
2365
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_schedules' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '15 DAYS'";
2366
		}
2367
		try {
2368
			$Connection = new Connection();
2369
			$sth = $Connection->db->prepare($query);
2370
                        $sth->execute();
2371
                } catch(PDOException $e) {
2372
                        return "error : ".$e->getMessage();
2373
                }
2374
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2375
                if ($row['nb'] > 0) return false;
2376
                else return true;
2377
	}
2378
2379
	public static function insert_last_schedules_update() {
2380
		$query = "DELETE FROM config WHERE name = 'last_update_schedules';
2381
			INSERT INTO config (name,value) VALUES ('last_update_schedules',NOW());";
2382
		try {
2383
			$Connection = new Connection();
2384
			$sth = $Connection->db->prepare($query);
2385
                        $sth->execute();
2386
                } catch(PDOException $e) {
2387
                        return "error : ".$e->getMessage();
2388
                }
2389
	}
2390
	public static function check_last_tle_update() {
2391
		global $globalDBdriver;
2392
		if ($globalDBdriver == 'mysql') {
2393
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value > DATE_SUB(NOW(), INTERVAL 7 DAY)";
2394
		} else {
2395
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_tle' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '7 DAYS'";
2396
		}
2397
		try {
2398
			$Connection = new Connection();
2399
			$sth = $Connection->db->prepare($query);
2400
                        $sth->execute();
2401
                } catch(PDOException $e) {
2402
                        return "error : ".$e->getMessage();
2403
                }
2404
                $row = $sth->fetch(PDO::FETCH_ASSOC);
2405
                if ($row['nb'] > 0) return false;
2406
                else return true;
2407
	}
2408
2409
	public static function insert_last_tle_update() {
2410
		$query = "DELETE FROM config WHERE name = 'last_update_tle';
2411
			INSERT INTO config (name,value) VALUES ('last_update_tle',NOW());";
2412
		try {
2413
			$Connection = new Connection();
2414
			$sth = $Connection->db->prepare($query);
2415
                        $sth->execute();
2416
                } catch(PDOException $e) {
2417
                        return "error : ".$e->getMessage();
2418
                }
2419
	}
2420
	public static function delete_duplicatemodes() {
2421
		global $globalDBdriver;
2422
		if ($globalDBdriver == 'mysql') {
2423
			$query = "DELETE a FROM aircraft_modes a, aircraft_modes b WHERE a.ModeS = b.ModeS AND a.FirstCreated < b.FirstCreated AND a.Source != 'ACARS'";
2424
		} else {
2425
			$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'";
2426
		}
2427
		try {
2428
			$Connection = new Connection();
2429
			$sth = $Connection->db->prepare($query);
2430
                        $sth->execute();
2431
                } catch(PDOException $e) {
2432
                        return "error : ".$e->getMessage();
2433
                }
2434
	}
2435
	public static function delete_duplicateowner() {
2436
		global $globalDBdriver;
2437
		if ($globalDBdriver == 'mysql') {
2438
			$query = "DELETE a FROM aircraft_owner a, aircraft_owner b WHERE a.registration = b.registration AND a.owner_id < b.owner_id";
2439
		} else {
2440
			$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)";
2441
		}
2442
		try {
2443
			$Connection = new Connection();
2444
			$sth = $Connection->db->prepare($query);
2445
                        $sth->execute();
2446
                } catch(PDOException $e) {
2447
                        return "error : ".$e->getMessage();
2448
                }
2449
	}
2450
	
2451
	public static function update_all() {
2452
		global $globalMasterServer, $globalMasterSource;
2453
		if (!isset($globalMasterServer) || !$globalMasterServer) {
2454
			if (isset($globalMasterSource) && $globalMasterSource) {
2455
				echo update_db::update_routes();
2456
				echo update_db::update_translation();
2457
				//echo update_db::update_notam_fam();
2458
				echo update_db::update_ModeS();
2459
				echo update_db::update_ModeS_flarm();
2460
				echo update_db::update_ModeS_ogn();
2461
				echo update_db::update_ModeS_faa();
2462
				echo update_db::update_banned_fam();
2463
				//echo update_db::delete_duplicatemodes();
2464
			} else {
2465
				//echo update_db::update_routes();
2466
				echo update_db::update_routes_fam();
2467
				echo update_db::update_translation();
2468
				echo update_db::update_translation_fam();
2469
				//echo update_db::update_notam_fam();
2470
				//echo update_db::update_ModeS();
2471
				echo update_db::update_ModeS_fam();
2472
				echo update_db::update_ModeS_flarm();
2473
				echo update_db::update_ModeS_ogn();
2474
				echo update_db::delete_duplicatemodes();
2475
				echo update_db::update_banned_fam();
2476
			}
2477
		}
2478
	}
2479
}
2480
2481
//echo update_db::update_airports();
2482
//echo update_db::translation();
2483
//echo update_db::update_waypoints();
2484
//echo update_db::update_airspace();
2485
//echo update_db::update_notam();
2486
//echo update_db::update_ivao();
2487
//echo update_db::update_ModeS_flarm();
2488
//echo update_db::update_ModeS_ogn();
2489
//echo update_db::update_aircraft();
2490
//$update_db = new update_db();
2491
//echo $update_db->update_owner();
2492
//update_db::update_translation_fam();
2493
//echo update_db::update_routes();
2494
//update_db::update_models();
2495
//echo $update_db::update_skyteam();
2496
//echo $update_db::update_tle();
2497
//echo update_db::update_notam_fam();
2498
//echo update_db::create_airspace();
2499
//echo update_db::update_ModeS();
2500
//echo update_db::update_ModeS_fam();
2501
//echo update_db::update_routes_fam();
2502
//echo update_db::update_ModeS_faa();
2503
//echo update_db::update_banned_fam();
2504
//echo update_db::modes_faa();
2505
//echo update_db::update_owner_fam();
2506
//echo update_db::delete_duplicateowner();
2507
?>
2508