Completed
Push — master ( d0d974...d44f1f )
by Yannick
16:44
created

update_db::check_last_banned_update()   A

Complexity

Conditions 4
Paths 10

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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